diff --git a/build.gradle.kts b/build.gradle.kts index a02f640b65..320df8f8dd 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -328,8 +328,8 @@ subprojects { spotless { java { - // Upgrade the formatter independently: Spotless 8.11 changes its default to 2.x. - googleJavaFormat(libs.findVersion("google-java-format").get().requiredVersion) + // Keep formatter upgrades limited to layout; do not rewrite Java syntax. + googleJavaFormat(libs.findVersion("google-java-format").get().requiredVersion).cleanup(false) targetExclude("build/generated/**", "build/generated-src/**") } } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index c371a9dd9a..d4ed835b25 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -12,7 +12,7 @@ lombok-mapstruct-binding = "0.2.0" grpc = "1.85.1" protobuf = "4.36.2" spotbugs = "4.10.5" -google-java-format = "1.36.1" +google-java-format = "2.0.0" opentelemetry = "1.68.0" micrometer = "1.17.2" jjwt = "0.13.0" diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthority.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthority.java index 33e5d8f330..00db355801 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthority.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthority.java @@ -173,11 +173,10 @@ public Snapshot captureAccount(UUID authenticatedAccountId) { } List roles = Arrays.asList(roleValues.clone()); if (roles.stream() - .anyMatch( - value -> - value == null - || !java.util.Set.of("platformAdmin", "billingAdmin", "support") - .contains(value)) + .anyMatch(value -> + value == null + || !java.util.Set.of("platformAdmin", "billingAdmin", "support") + .contains(value)) || !roles.equals(roles.stream().distinct().sorted().toList())) { throw unavailable(); } @@ -189,14 +188,13 @@ public Snapshot captureAccount(UUID authenticatedAccountId) { authority.put("privateRealmGrantVersions", List.of()); source .accountSecurityCutoff() - .ifPresent( - cutoff -> - authority.put( - "accountSecurityCutoff", - Map.of( - "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), - "outboxStreamKey", cutoff.outboxStreamKey(), - "outboxSequence", cutoff.outboxSequence()))); + .ifPresent(cutoff -> + authority.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence()))); byte[] issuerBytes = current.canonicalIssuerProjection().toJson().getBytes(StandardCharsets.UTF_8); byte[] accountBytes = @@ -305,14 +303,13 @@ private void requireOwnerTransaction() { || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { throw unavailable(); } - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw unavailable(); - } - }); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw unavailable(); + } + }); } private static IllegalStateException unavailable() { @@ -372,37 +369,34 @@ private Snapshot snapshot( authority.put("privateRealmGrantVersions", List.of()); tuple .accountSecurityCutoff() - .ifPresent( - cutoff -> - authority.put( - "accountSecurityCutoff", - Map.of( - "accountAuthorityGeneration", - cutoff.accountAuthorityGeneration(), - "outboxStreamKey", - cutoff.outboxStreamKey(), - "outboxSequence", - cutoff.outboxSequence()))); + .ifPresent(cutoff -> + authority.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + cutoff.accountAuthorityGeneration(), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + cutoff.outboxSequence()))); tuple .tenantBillingCutoff() - .ifPresent( - cutoffs -> { - Map values = new LinkedHashMap<>(); - cutoffs.forEach( - (id, cutoff) -> - values.put( - id, - Map.of( - "tenantAuthorityGeneration", - Long.parseLong(cutoff.tenantAuthorityGeneration()), - "tenantBillingSequence", - Long.parseLong(cutoff.tenantBillingSequence()), - "outboxStreamKey", - cutoff.outboxStreamKey(), - "outboxSequence", - Long.parseLong(cutoff.outboxSequence())))); - authority.put("tenantBillingCutoff", Map.copyOf(values)); - }); + .ifPresent(cutoffs -> { + Map values = new LinkedHashMap<>(); + cutoffs.forEach((id, cutoff) -> + values.put( + id, + Map.of( + "tenantAuthorityGeneration", + Long.parseLong(cutoff.tenantAuthorityGeneration()), + "tenantBillingSequence", + Long.parseLong(cutoff.tenantBillingSequence()), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + Long.parseLong(cutoff.outboxSequence())))); + authority.put("tenantBillingCutoff", Map.copyOf(values)); + }); var upstream = existing.issuerAccount(); var issuanceFenceSource = requireIssuanceFenceSource(member); byte[] issuer = upstream.canonicalIssuerProjection().toJson().getBytes(StandardCharsets.UTF_8); @@ -489,21 +483,19 @@ private Snapshot snapshot( .toList())); var checkpoints = member.outboxCheckpoints().stream() - .map( - checkpoint -> { - Map value = new LinkedHashMap<>(); - value.put("outboxStreamKey", checkpoint.outboxStreamKey()); - value.put("outboxSequence", checkpoint.outboxSequence()); - member.outboxSourceEvidence().stream() - .filter(event -> event.outboxStreamKey().equals(checkpoint.outboxStreamKey())) - .findFirst() - .ifPresent( - event -> { - value.put("sourceEventId", event.eventId()); - value.put("sourceEventDigest", event.eventDigest()); - }); - return Map.copyOf(value); - }) + .map(checkpoint -> { + Map value = new LinkedHashMap<>(); + value.put("outboxStreamKey", checkpoint.outboxStreamKey()); + value.put("outboxSequence", checkpoint.outboxSequence()); + member.outboxSourceEvidence().stream() + .filter(event -> event.outboxStreamKey().equals(checkpoint.outboxStreamKey())) + .findFirst() + .ifPresent(event -> { + value.put("sourceEventId", event.eventId()); + value.put("sourceEventDigest", event.eventDigest()); + }); + return Map.copyOf(value); + }) .toList(); Map identity = Map.of( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadService.java index ac7e0a64b2..2991a82df5 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadService.java @@ -62,27 +62,26 @@ public void requireHeld(DraftCommitOrderReadEvidence.Request request) { throw invalid("Complete canonical original Account binding is required"); } try { - ownerTransaction.execute( - status -> { - DraftAuthorizationFenceBinding retained = - repository - .readOriginalBinding(requested.operationId()) - .orElseThrow(AccountDraftCommitOrderReadService::unheld); - if (!Arrays.equals(retained.canonicalBytes(), request.originalAccountBinding())) { - throw unheld(); - } + ownerTransaction.execute(status -> { + DraftAuthorizationFenceBinding retained = + repository + .readOriginalBinding(requested.operationId()) + .orElseThrow(AccountDraftCommitOrderReadService::unheld); + if (!Arrays.equals(retained.canonicalBytes(), request.originalAccountBinding())) { + throw unheld(); + } - var fence = repository.read(retained); - if (fence.ordering() != Ordering.COMMIT_ORDER - || fence.reservedAt() == null - || fence.orderedAt() == null - || !Arrays.equals(fence.binding(), request.originalAccountBinding())) { - throw unheld(); - } - Settlement settlement = repository.readSettlement(retained); - if (settlement != Settlement.PENDING) throw unheld(); - return null; - }); + var fence = repository.read(retained); + if (fence.ordering() != Ordering.COMMIT_ORDER + || fence.reservedAt() == null + || fence.orderedAt() == null + || !Arrays.equals(fence.binding(), request.originalAccountBinding())) { + throw unheld(); + } + Settlement settlement = repository.readSettlement(retained); + if (settlement != Settlement.PENDING) throw unheld(); + return null; + }); } catch (StatusRuntimeException failure) { throw failure; } catch (DataAccessException | org.jooq.exception.DataAccessException unavailable) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionService.java index d7a5c33684..92ad255826 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftSourceCompositionService.java @@ -97,18 +97,17 @@ public ExistingSources readExistingSources( CreatorPartyEncoding.creation(creator), bootstrap.creatorEvidencePayload()) || currentTerms.sourceEvidence().stream() .filter(source -> source.kind() == SourceKind.CREATOR_PARTY) - .noneMatch( - source -> - source.scopeId().equals(association.partySource().creatorPartyId().toString()) - && Objects.equals( - source.generation(), - Long.toString(association.partySource().identityVersion())) - && source - .sourceVersion() - .equals(Long.toString(association.partySource().sourceVersion())) - && Arrays.equals( - source.evidence(), - CreatorPartyEncoding.party(association.partySource())))) { + .noneMatch(source -> + source.scopeId().equals(association.partySource().creatorPartyId().toString()) + && Objects.equals( + source.generation(), + Long.toString(association.partySource().identityVersion())) + && source + .sourceVersion() + .equals(Long.toString(association.partySource().sourceVersion())) + && Arrays.equals( + source.evidence(), + CreatorPartyEncoding.party(association.partySource())))) { throw mismatch(); } return new ExistingSources(membership, issuerAccount, association, currentTerms); @@ -172,14 +171,13 @@ private void requireOwnerTransaction() { || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { throw new IllegalStateException("Writable READ_COMMITTED Account transaction required"); } - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new IllegalStateException("Writable READ_COMMITTED Account transaction required"); - } - }); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable READ_COMMITTED Account transaction required"); + } + }); } private static IllegalStateException mismatch() { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationService.java index a2ed5db9ac..ea959d509e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationService.java @@ -86,24 +86,23 @@ public Optional reconcile(UUID operationId) { : Optional.empty(); Settlement settled = - ownerTransaction.execute( - status -> { - DraftAuthorizationFenceBinding current = - repository - .readOriginalBinding(operationId) - .orElseThrow( - () -> new IllegalStateException("Original Draft operation disappeared")); - if (!Arrays.equals(current.canonicalBytes(), before.binding().canonicalBytes())) { - throw new IllegalStateException("Original Draft binding changed during recovery"); - } - Snapshot after = snapshot(current); - if (after.ordering() != before.ordering()) { - throw new IllegalStateException("Original Draft ordering changed during recovery"); - } - retainExactMissing(current, Owner.GAME_DESIGN, gameDesignReadback, after); - retainExactMissing(current, Owner.WORLD, worldReadback, after); - return repository.readSettlement(current); - }); + ownerTransaction.execute(status -> { + DraftAuthorizationFenceBinding current = + repository + .readOriginalBinding(operationId) + .orElseThrow( + () -> new IllegalStateException("Original Draft operation disappeared")); + if (!Arrays.equals(current.canonicalBytes(), before.binding().canonicalBytes())) { + throw new IllegalStateException("Original Draft binding changed during recovery"); + } + Snapshot after = snapshot(current); + if (after.ordering() != before.ordering()) { + throw new IllegalStateException("Original Draft ordering changed during recovery"); + } + retainExactMissing(current, Owner.GAME_DESIGN, gameDesignReadback, after); + retainExactMissing(current, Owner.WORLD, worldReadback, after); + return repository.readSettlement(current); + }); return Optional.of(Objects.requireNonNull(settled)); } @@ -143,14 +142,13 @@ private Optional readStoredOwnerResult( if (!binding.requiredOwners().contains(owner)) return Optional.empty(); return repository .readOwnerResult(binding, owner) - .map( - stored -> { - OwnerReadback readback = OwnerReadback.fromStored(stored.readback()); - if (stored.outcome() != readback.outcome()) { - throw new IllegalStateException("Stored Draft outcome differs from its readback"); - } - return verifyOwnerReadback(binding, owner, readback); - }); + .map(stored -> { + OwnerReadback readback = OwnerReadback.fromStored(stored.readback()); + if (stored.outcome() != readback.outcome()) { + throw new IllegalStateException("Stored Draft outcome differs from its readback"); + } + return verifyOwnerReadback(binding, owner, readback); + }); } private static OwnerReadback verifyOwnerReadback( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index c93e734885..5a36b4fe41 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -718,14 +718,13 @@ public List readUnresolvedOperations(RecoveryCursor after, } sql += " ORDER BY f.reserved_at, f.operation_id LIMIT ?"; return dsl.fetch(sql, parameters).stream() - .map( - row -> - new UnresolvedOperation( - originalBinding(row), - Ordering.valueOf(row.get("ordering", String.class)), - new RecoveryCursor( - row.get("reserved_at", OffsetDateTime.class), - row.get("operation_id", UUID.class)))) + .map(row -> + new UnresolvedOperation( + originalBinding(row), + Ordering.valueOf(row.get("ordering", String.class)), + new RecoveryCursor( + row.get("reserved_at", OffsetDateTime.class), + row.get("operation_id", UUID.class)))) .toList(); } @@ -773,16 +772,15 @@ public List waitingSourceChanges() { return dsl .fetch("SELECT * FROM " + CHANGES + " WHERE status = 'WAITING' ORDER BY change_id") .stream() - .map( - row -> - new SourceChangeSnapshot( - row.get("change_id", UUID.class), - row.get("binding", byte[].class), - row.get("status", String.class), - row.get("requested_at", OffsetDateTime.class), - row.get("committed_at", OffsetDateTime.class), - row.get("aborted_at", OffsetDateTime.class), - abortReason(row.get("abort_reason", String.class)))) + .map(row -> + new SourceChangeSnapshot( + row.get("change_id", UUID.class), + row.get("binding", byte[].class), + row.get("status", String.class), + row.get("requested_at", OffsetDateTime.class), + row.get("committed_at", OffsetDateTime.class), + row.get("aborted_at", OffsetDateTime.class), + abortReason(row.get("abort_reason", String.class)))) .toList(); } @@ -899,14 +897,12 @@ private boolean hasWaitingChange(List sources) { private List affectedOperations(List sources) { return sources.stream() - .flatMap( - source -> - dsl - .fetch( - "SELECT operation_id FROM " + SOURCES + " WHERE source_key = ?", - source.key()) - .getValues("operation_id", UUID.class) - .stream()) + .flatMap(source -> + dsl + .fetch( + "SELECT operation_id FROM " + SOURCES + " WHERE source_key = ?", source.key()) + .getValues("operation_id", UUID.class) + .stream()) .distinct() .sorted(Comparator.comparing(UUID::toString)) .toList(); @@ -1047,14 +1043,13 @@ private void requireTransaction() { || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { throw new IllegalStateException("Writable caller Account transaction required"); } - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new IllegalStateException( - "Transaction-bound writable READ_COMMITTED connection required"); - } - }); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Transaction-bound writable READ_COMMITTED connection required"); + } + }); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountOriginalNewFinalAdmissionReadClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountOriginalNewFinalAdmissionReadClient.java index 2efcab8069..78c7a874a7 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountOriginalNewFinalAdmissionReadClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/AccountOriginalNewFinalAdmissionReadClient.java @@ -64,8 +64,8 @@ public String toString() { } /** - * Typed response only constructible by the protected reader implementation. Account exact- - * compares every anchor and checks the canonical continuity deadline before persisting it. + * Typed response only constructible by the protected reader implementation. Account + * exact-compares every anchor and checks the canonical continuity deadline before persisting it. */ final class AuthenticatedFinalAdmissionReadback { private static final long MAX_CANONICAL_SESSION_DURATION_MILLIS = 300_000L; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiBinding.java index 3f34a89974..d6ab9aa670 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiBinding.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiBinding.java @@ -342,12 +342,11 @@ private ApiResponse send( client.send(request.build(), HttpResponse.BodyHandlers.ofInputStream()); try (java.io.InputStream body = response.body()) { ExecutorService bodyReader = - Executors.newSingleThreadExecutor( - task -> { - Thread thread = new Thread(task, "account-jwks-api-response-reader"); - thread.setDaemon(true); - return thread; - }); + Executors.newSingleThreadExecutor(task -> { + Thread thread = new Thread(task, "account-jwks-api-response-reader"); + thread.setDaemon(true); + return thread; + }); Future bodyFuture = bodyReader.submit(() -> readBounded(body, MAX_RESPONSE_BYTES)); try { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java index dbf1c8270b..06d3aff763 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBinding.java @@ -435,10 +435,9 @@ private static String canonicalRuntimeConfig( try { List> profileValues = profiles.stream() - .map( - profile -> - Map.of( - "tokenProfile", profile.tokenProfile(), "audience", profile.audience())) + .map(profile -> + Map.of( + "tokenProfile", profile.tokenProfile(), "audience", profile.audience())) .toList(); Map runtime = Map.of( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java index de5bde5a35..349ff6b119 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/TestDataSeeder.java @@ -44,13 +44,12 @@ public void run(ApplicationArguments args) { throw new IllegalStateException("Demo account identity does not match configured email"); } Account account = - existingDemoAccount.orElseGet( - () -> { - Account seeded = new Account(); - seeded.setUsername(DEMO_USERNAME); - seeded.setEmail(DEMO_EMAIL); - return seeded; - }); + existingDemoAccount.orElseGet(() -> { + Account seeded = new Account(); + seeded.setUsername(DEMO_USERNAME); + seeded.setEmail(DEMO_EMAIL); + return seeded; + }); account.setUsername(DEMO_USERNAME); account.setEmail(DEMO_EMAIL); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java index 5f9cabaa4a..8a3da01f77 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/AccountHostedTermsService.java @@ -122,17 +122,15 @@ public EnvironmentBindingPublicationResult resumeEnvironmentBinding(UUID request requireEnvironmentBindingRepository(); HostedTermsEncoding.requireUuid(requestId, "environment binding publication request"); return Objects.requireNonNull( - ownerTransaction.execute( - ignored -> { - HostedTermsEnvironmentBindingRepository.PublicationOperation operation = - environmentBindings - .readPublication(requestId, true) - .orElseThrow( - () -> - new IllegalArgumentException( - "Original environment binding publication is absent")); - return advanceEnvironmentBinding(operation); - }), + ownerTransaction.execute(ignored -> { + HostedTermsEnvironmentBindingRepository.PublicationOperation operation = + environmentBindings + .readPublication(requestId, true) + .orElseThrow(() -> + new IllegalArgumentException( + "Original environment binding publication is absent")); + return advanceEnvironmentBinding(operation); + }), "Account environment binding recovery result"); } @@ -204,17 +202,14 @@ private CapturedEnvironmentBoundary( public PublicationResult resumePublication(UUID requestId) { HostedTermsEncoding.requireUuid(requestId, "publication request"); return Objects.requireNonNull( - ownerTransaction.execute( - ignored -> { - HostedTermsRepository.PublicationOperation operation = - repository - .readPublication(requestId, true) - .orElseThrow( - () -> - new IllegalArgumentException( - "Original publication request is absent")); - return advancePublication(operation, null); - }), + ownerTransaction.execute(ignored -> { + HostedTermsRepository.PublicationOperation operation = + repository + .readPublication(requestId, true) + .orElseThrow( + () -> new IllegalArgumentException("Original publication request is absent")); + return advancePublication(operation, null); + }), "Account publication recovery result"); } @@ -802,10 +797,9 @@ private CurrentnessEvidence currentnessInTransaction(UUID scopeId, UUID partyId) IndividualHostedTermsAcceptance acceptance = repository .readCurrentAcceptance(partyId, scopeId, current) - .orElseThrow( - () -> - new IllegalStateException( - "No current affirmative party-wide hosted terms acceptance")); + .orElseThrow(() -> + new IllegalStateException( + "No current affirmative party-wide hosted terms acceptance")); byte[] currentParty = HostedTermsEncoding.individualParty(party); if (!acceptance.accountId().equals(accountId) || !acceptance.creatorPartyId().equals(partyId) @@ -1072,27 +1066,24 @@ public record EnvironmentBoundCurrentness( if (sourceEvidence.size() != 3 || sourceEvidence.stream().map(SourceEvidence::key).distinct().count() != 3 || sourceEvidence.stream() - .noneMatch( - source -> - source.key().equals(binding.sourceEvidence().key()) - && Arrays.equals( - source.canonicalBytes(), binding.sourceEvidence().canonicalBytes())) + .noneMatch(source -> + source.key().equals(binding.sourceEvidence().key()) + && Arrays.equals( + source.canonicalBytes(), binding.sourceEvidence().canonicalBytes())) || sourceEvidence.stream() - .noneMatch( - source -> - source.kind() == SourceKind.HOSTED_TERMS - && source.scopeId().equals(terms.hostedScopeId().toString()) - && Objects.equals( - source.generation(), Long.toString(terms.materialGeneration())) - && source.sourceVersion().equals(Long.toString(terms.sourceVersion())) - && Arrays.equals(source.evidence(), terms.exactCurrentnessSource())) + .noneMatch(source -> + source.kind() == SourceKind.HOSTED_TERMS + && source.scopeId().equals(terms.hostedScopeId().toString()) + && Objects.equals( + source.generation(), Long.toString(terms.materialGeneration())) + && source.sourceVersion().equals(Long.toString(terms.sourceVersion())) + && Arrays.equals(source.evidence(), terms.exactCurrentnessSource())) || sourceEvidence.stream() - .noneMatch( - source -> - source.kind() == SourceKind.CREATOR_PARTY - && source.scopeId().equals(terms.creatorPartyId().toString()) - && source.generation() != null - && source.sourceVersion() != null)) { + .noneMatch(source -> + source.kind() == SourceKind.CREATOR_PARTY + && source.scopeId().equals(terms.creatorPartyId().toString()) + && source.generation() != null + && source.sourceVersion() != null)) { throw new IllegalArgumentException( "Bound currentness must retain exact binding, catalog/acceptance and party sources"); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java index 128615894f..0c731633de 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffRepository.java @@ -410,14 +410,13 @@ private void requireWriteTransaction() { || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { throw new IllegalStateException("Writable caller Account transaction required"); } - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new IllegalStateException( - "Transaction-bound writable READ_COMMITTED connection required"); - } - }); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Transaction-bound writable READ_COMMITTED connection required"); + } + }); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingRepository.java index cec24c3388..cb97d91a2a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingRepository.java @@ -410,13 +410,12 @@ private void requireWriteTransaction() { if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { throw new IllegalStateException("Writable owner transaction required"); } - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new IllegalStateException("Writable READ_COMMITTED Account transaction required"); - } - }); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable READ_COMMITTED Account transaction required"); + } + }); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java index fcbab70124..aa0430b90c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java @@ -87,13 +87,12 @@ public Optional findExactCanonicalTenantEnvelopeForUpdate( } Optional found = findCanonicalTenantEnvelopeForUpdate(expected.auditEventId()); - found.ifPresent( - actual -> { - if (!actual.equals(expected)) { - throw new IllegalStateException( - "Canonical Account audit identity conflicts with its immutable original envelope"); - } - }); + found.ifPresent(actual -> { + if (!actual.equals(expected)) { + throw new IllegalStateException( + "Canonical Account audit identity conflicts with its immutable original envelope"); + } + }); return found; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepository.java index e05fa9e804..805609048c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepository.java @@ -439,12 +439,11 @@ private static Map authorityTuple(IssuerAccountSourceSnapshot so sources .account() .accountSecurityCutoff() - .map( - cutoff -> - new GameSessionAccountDelegationProfile.AccountSecurityCutoff( - cutoff.accountAuthorityGeneration(), - cutoff.outboxStreamKey(), - cutoff.outboxSequence()))); + .map(cutoff -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence()))); } private static Map sourceVersions(IssuerAccountSourceSnapshot sources) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepository.java index 87109ba150..b26ec0df79 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepository.java @@ -274,10 +274,9 @@ public Optional readCheckpoint(String outboxStreamKey) { } Event event = findEvent(outboxStreamKey, sequence) - .orElseThrow( - () -> - new IllegalStateException( - "Account authority outbox checkpoint has no matching event evidence")); + .orElseThrow(() -> + new IllegalStateException( + "Account authority outbox checkpoint has no matching event evidence")); return Optional.of( new Checkpoint( outboxStreamKey, event.outboxSequence(), event.eventId(), event.eventDigest())); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotRepository.java index d7920a6619..e92ef9b78d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotRepository.java @@ -257,12 +257,11 @@ public Snapshot readCurrent(UUID accountUuid, UUID tenantUuid) { currentSources .account() .accountSecurityCutoff() - .map( - cutoff -> - new AccountSecurityCutoff( - cutoff.accountAuthorityGeneration(), - cutoff.outboxStreamKey(), - cutoff.outboxSequence())), + .map(cutoff -> + new AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence())), Optional.of( Map.of( tenantUuid.toString(), diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java index 732f6cbed0..02b676fbdd 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java @@ -209,10 +209,9 @@ public void insertCanonical( CanonicalConnectScopeEvidence committed = readCanonicalEvidenceByTokenHash(tokenHash) - .orElseThrow( - () -> - new IllegalStateException( - "Canonical Account connect scope insert readback is absent")); + .orElseThrow(() -> + new IllegalStateException( + "Canonical Account connect scope insert readback is absent")); if (!committed.equals(expected)) { throw new CanonicalScopeConflictException( "Canonical Account connect scope conflicts with immutable token-hash evidence"); @@ -230,14 +229,13 @@ public Optional findCanonical(String connectScopeId) { } String tokenHash = AccountJoinDigest.tokenHash(connectScopeId); return readCanonicalEvidenceByTokenHash(tokenHash) - .map( - evidence -> { - CanonicalJoinScopeV2 scope = toCanonicalScope(evidence, connectScopeId); - if (!evidence.scopeDigest().equals(AccountJoinDigest.scopeV2(scope))) { - throw new IllegalStateException("Canonical JOIN scope digest mismatch"); - } - return scope; - }); + .map(evidence -> { + CanonicalJoinScopeV2 scope = toCanonicalScope(evidence, connectScopeId); + if (!evidence.scopeDigest().equals(AccountJoinDigest.scopeV2(scope))) { + throw new IllegalStateException("Canonical JOIN scope digest mismatch"); + } + return scope; + }); } /** Hash-only V2 evidence for operation cross-readback; it never reconstructs the bearer. */ @@ -312,10 +310,8 @@ private void verifyTenantIdentity( FreshTenantCreationEvidence association = freshTenantIdentities .read(expectedTenantUuid) - .orElseThrow( - () -> - new IllegalStateException( - "Canonical JOIN scope fresh tenant source is absent")); + .orElseThrow(() -> + new IllegalStateException("Canonical JOIN scope fresh tenant source is absent")); if (!expectedTenantUuid.equals(association.canonicalTenantId()) || expectedProvenance.legacyTenantId() != null || !expectedProvenance.sourceOperationId().equals(association.operationId()) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java index 21958a36e1..7b5345c48a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java @@ -62,11 +62,10 @@ public DemoTenantEntitlementSnapshot provision( FreshTenantCreationEvidence currentSource = tenantIdentityRepository .read(request.canonicalTenantId()) - .orElseThrow( - () -> - new DemoTenantEntitlementException( - Code.SOURCE_EVIDENCE_INVALID, - "Exact fresh Game Design source evidence is absent at Account commit")); + .orElseThrow(() -> + new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "Exact fresh Game Design source evidence is absent at Account commit")); if (!authenticatedSource.equals(currentSource)) { throw new DemoTenantEntitlementException( Code.SOURCE_EVIDENCE_INVALID, @@ -177,11 +176,10 @@ public DemoTenantEntitlementSnapshot readCurrent(UUID canonicalTenantId) { Optional evidence = tenantIdentityRepository.read(canonicalTenantId); FreshTenantCreationEvidence source = - evidence.orElseThrow( - () -> - new DemoTenantEntitlementException( - Code.SOURCE_EVIDENCE_INVALID, - "No exact fresh Game Design source evidence exists for this tenant UUID")); + evidence.orElseThrow(() -> + new DemoTenantEntitlementException( + Code.SOURCE_EVIDENCE_INVALID, + "No exact fresh Game Design source evidence exists for this tenant UUID")); ScopeState authority = authorityGenerationRepository.read(AuthorityScope.tenant(canonicalTenantId)); Record row = readCurrentRow(canonicalTenantId, false); @@ -248,9 +246,8 @@ private DemoTenantEntitlementSnapshot replay( Event event = outboxRepository .readEvent(request.canonicalTenantId(), sequence) - .orElseThrow( - () -> - new IllegalStateException("Committed demo entitlement operation has no event")); + .orElseThrow(() -> + new IllegalStateException("Committed demo entitlement operation has no event")); if (!request.requestId().equals(event.requestId()) || !request.requestDigest().equals(event.requestDigest()) || !event.eventId().equals(get(operation, "event_id", UUID.class)) @@ -308,9 +305,8 @@ private CurrentEvents currentEvents( var checkpoint = outboxRepository .readCheckpoint(source.canonicalTenantId()) - .orElseThrow( - () -> - new IllegalStateException("Current demo entitlement has no outbox checkpoint")); + .orElseThrow(() -> + new IllegalStateException("Current demo entitlement has no outbox checkpoint")); if (checkpoint.sequence() != sequence || !checkpoint.eventId().equals(get(row, "event_id", UUID.class)) || !checkpoint.eventDigest().equals(get(row, "event_digest", String.class))) { 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 06100be2ae..59baf1c0f2 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 @@ -260,13 +260,12 @@ private static Map currentLeaseSourceFields( "membershipAuthorityGeneration", snapshot.membershipAuthorityGeneration()); List> outboxCheckpoints = snapshot.checkpoints().stream() - .map( - checkpoint -> - Map.of( - "outboxStreamKey", - checkpoint.outboxStreamKey(), - "outboxSequence", - checkpoint.outboxSequence())) + .map(checkpoint -> + Map.of( + "outboxStreamKey", + checkpoint.outboxStreamKey(), + "outboxSequence", + checkpoint.outboxSequence())) .toList(); return Map.of( @@ -282,12 +281,11 @@ private static Map currentAuthorityTuple(Snapshot snapshot) { Optional accountCutoff = current .accountSecurityCutoff() - .map( - cutoff -> - new AccountSecurityCutoff( - cutoff.accountAuthorityGeneration(), - cutoff.outboxStreamKey(), - cutoff.outboxSequence())); + .map(cutoff -> + new AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence())); Map authorityTuple = new LinkedHashMap<>( GameSessionAccountDelegationProfile.authorityTuple( @@ -299,24 +297,22 @@ private static Map currentAuthorityTuple(Snapshot snapshot) { authorityTuple.put("privateRealmGrantVersions", current.privateRealmGrantVersions()); current .tenantBillingCutoff() - .ifPresent( - cutoffs -> - authorityTuple.put("tenantBillingCutoff", currentTenantBillingCutoff(cutoffs))); + .ifPresent(cutoffs -> + authorityTuple.put("tenantBillingCutoff", currentTenantBillingCutoff(cutoffs))); return Map.copyOf(authorityTuple); } private static Map currentTenantBillingCutoff( Map currentCutoffs) { Map cutoffs = new LinkedHashMap<>(); - currentCutoffs.forEach( - (tenantId, cutoff) -> - cutoffs.put( - tenantId, - Map.of( - "tenantAuthorityGeneration", cutoff.tenantAuthorityGeneration(), - "tenantBillingSequence", cutoff.tenantBillingSequence(), - "outboxStreamKey", cutoff.outboxStreamKey(), - "outboxSequence", cutoff.outboxSequence()))); + currentCutoffs.forEach((tenantId, cutoff) -> + cutoffs.put( + tenantId, + Map.of( + "tenantAuthorityGeneration", cutoff.tenantAuthorityGeneration(), + "tenantBillingSequence", cutoff.tenantBillingSequence(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence()))); return Map.copyOf(cutoffs); } @@ -362,20 +358,18 @@ private static void requireSupportedPublicTenantTuple( boolean tenantCheckpointPresent = snapshot.checkpoints().stream() - .anyMatch( - checkpoint -> - authorityEvent.outboxStreamKey().equals(checkpoint.outboxStreamKey()) - && Long.toString(authorityEvent.outboxSequence()) - .equals(checkpoint.outboxSequence())); + .anyMatch(checkpoint -> + authorityEvent.outboxStreamKey().equals(checkpoint.outboxStreamKey()) + && Long.toString(authorityEvent.outboxSequence()) + .equals(checkpoint.outboxSequence())); boolean tenantSourceEventPresent = snapshot.sourceEvidence().stream() - .anyMatch( - evidence -> - authorityEvent.outboxStreamKey().equals(evidence.outboxStreamKey()) - && Long.toString(authorityEvent.outboxSequence()) - .equals(evidence.outboxSequence()) - && authorityEvent.eventId().toString().equals(evidence.eventId()) - && authorityEvent.eventDigest().equals(evidence.eventDigest())); + .anyMatch(evidence -> + authorityEvent.outboxStreamKey().equals(evidence.outboxStreamKey()) + && Long.toString(authorityEvent.outboxSequence()) + .equals(evidence.outboxSequence()) + && authorityEvent.eventId().toString().equals(evidence.eventId()) + && authorityEvent.eventDigest().equals(evidence.eventDigest())); if (snapshot.membershipVersion().size() != 1 || !snapshot.membershipVersion().keySet().equals(Set.of(tenantKey)) @@ -432,14 +426,13 @@ private void requireWritableSerializableAccountTransaction() { if (!Integer.valueOf(Connection.TRANSACTION_SERIALIZABLE).equals(declaredIsolation)) { throw unavailable(); } - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_SERIALIZABLE) { - throw unavailable(); - } - }); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_SERIALIZABLE) { + throw unavailable(); + } + }); } private void lockExactAccountFirst(UUID accountId) { 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 d206a05f03..7ee682d41a 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 @@ -410,31 +410,30 @@ public AbortNeverAdmittedGameplayAdmissionLeaseResponse abortNeverAdmitted( final AccountGameplayAdmissionAbortResolution resolution; try { resolution = - inWritableSerializableTransaction( - dsl -> { - AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace) - .requireCurrentAuthenticatedCallerOnly(caller.currentCandidate()); - var repository = new AccountGameplayAdmissionLeaseRepository(dsl); - var original = - repository - .readExact(lease) - .orElseThrow(AccountGameplayAdmissionLeaseOwner::unavailable); - if (original.state() == AccountGameplayAdmissionLeaseOperation.State.COMMITTED - || original.bindingDecisionId() != null) throw unavailable(); - if (original.state() == AccountGameplayAdmissionLeaseOperation.State.PENDING) - original = repository.recordAborted(lease, null, UUID.randomUUID()); - if (original.state() != AccountGameplayAdmissionLeaseOperation.State.ABORTED - || original.bindingDecisionId() != null - || original.orphanCleanupId() == null) throw unavailable(); - return new AccountGameplayAdmissionAbortResolutionRepository(dsl) - .recordOrReplayNeverAdmitted( - lease, - original.orphanCleanupId(), - request.transitionId(), - request.abandonmentId(), - decision.candidateDigest(), - decision.closureDigest()); - }); + inWritableSerializableTransaction(dsl -> { + AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace) + .requireCurrentAuthenticatedCallerOnly(caller.currentCandidate()); + var repository = new AccountGameplayAdmissionLeaseRepository(dsl); + var original = + repository + .readExact(lease) + .orElseThrow(AccountGameplayAdmissionLeaseOwner::unavailable); + if (original.state() == AccountGameplayAdmissionLeaseOperation.State.COMMITTED + || original.bindingDecisionId() != null) throw unavailable(); + if (original.state() == AccountGameplayAdmissionLeaseOperation.State.PENDING) + original = repository.recordAborted(lease, null, UUID.randomUUID()); + if (original.state() != AccountGameplayAdmissionLeaseOperation.State.ABORTED + || original.bindingDecisionId() != null + || original.orphanCleanupId() == null) throw unavailable(); + return new AccountGameplayAdmissionAbortResolutionRepository(dsl) + .recordOrReplayNeverAdmitted( + lease, + original.orphanCleanupId(), + request.transitionId(), + request.abandonmentId(), + decision.candidateDigest(), + decision.closureDigest()); + }); } catch (RuntimeException unknown) { throw unavailable(); } @@ -750,17 +749,16 @@ private T withCurrentSources( Objects.requireNonNull(caller); Objects.requireNonNull(tenantId); try { - return inWritableSerializableTransaction( - dsl -> { - AccountGameplayAdmissionCurrentSources currentSources = - AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace); - var current = - currentSources.readCurrentPublicProductionNew( - tenantId, caller.identity().tokenJti(), caller.currentCandidate()); - return operation.apply( - new CurrentAccountOperation( - dsl, current, new AccountGameplayAdmissionLeaseRepository(dsl))); - }); + return inWritableSerializableTransaction(dsl -> { + AccountGameplayAdmissionCurrentSources currentSources = + AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace); + var current = + currentSources.readCurrentPublicProductionNew( + tenantId, caller.identity().tokenJti(), caller.currentCandidate()); + return operation.apply( + new CurrentAccountOperation( + dsl, current, new AccountGameplayAdmissionLeaseRepository(dsl))); + }); } catch (StatusRuntimeException failure) { throw failure; } catch (RuntimeException unavailable) { @@ -772,15 +770,14 @@ private T withCurrentSources( private AccountGameplayAdmissionLeaseOperation readExactWithCurrentCallerOnly( VerifiedCaller caller, AccountGameplayAdmissionLeaseEvidence lease) { try { - return inWritableSerializableTransaction( - dsl -> { - AccountGameplayAdmissionCurrentSources currentSources = - AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace); - currentSources.requireCurrentAuthenticatedCallerOnly(caller.currentCandidate()); - return new AccountGameplayAdmissionLeaseRepository(dsl) - .readExact(lease) - .orElseThrow(AccountGameplayAdmissionLeaseOwner::unavailable); - }); + return inWritableSerializableTransaction(dsl -> { + AccountGameplayAdmissionCurrentSources currentSources = + AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace); + currentSources.requireCurrentAuthenticatedCallerOnly(caller.currentCandidate()); + return new AccountGameplayAdmissionLeaseRepository(dsl) + .readExact(lease) + .orElseThrow(AccountGameplayAdmissionLeaseOwner::unavailable); + }); } catch (StatusRuntimeException failure) { throw failure; } catch (RuntimeException unavailable) { @@ -795,25 +792,24 @@ private AccountGameplayAdmissionLeaseOperation readExactWithCurrentCallerOnly( 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; - }); + 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) { @@ -827,28 +823,27 @@ private AccountGameplayAdmissionLeaseOperation readExactForFinalization( private AccountGameplayAdmissionLeaseOperation abortExactWithCurrentCallerOnly( VerifiedCaller caller, AccountGameplayAdmissionLeaseEvidence lease, UUID decisionId) { 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) { - // Null decision records an unresolved orphan obligation, not proof of absence. - return repository.recordAborted(lease, decisionId, UUID.randomUUID()); - } - if (operation.state() == AccountGameplayAdmissionLeaseOperation.State.ABORTED) { - requireAbortDecisionMatches(decisionId, operation); - } else if (decisionId != null && !decisionId.equals(operation.bindingDecisionId())) { - throw unavailable(); - } - return operation; - }); + 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) { + // Null decision records an unresolved orphan obligation, not proof of absence. + return repository.recordAborted(lease, decisionId, UUID.randomUUID()); + } + if (operation.state() == AccountGameplayAdmissionLeaseOperation.State.ABORTED) { + requireAbortDecisionMatches(decisionId, operation); + } else if (decisionId != null && !decisionId.equals(operation.bindingDecisionId())) { + throw unavailable(); + } + return operation; + }); } catch (StatusRuntimeException failure) { throw failure; } catch (RuntimeException unavailable) { @@ -864,26 +859,24 @@ private T inWritableSerializableTransaction( transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); transaction.setReadOnly(false); T result = - transaction.execute( - status -> { - if (!status.isNewTransaction()) throw unavailable(); - Object resource = - TransactionSynchronizationManager.getResource( - Objects.requireNonNull(manager.getDataSource())); - if (!(resource instanceof ConnectionHolder holder)) throw unavailable(); - Connection connection = holder.getConnection(); - try { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() - != Connection.TRANSACTION_SERIALIZABLE) { - throw unavailable(); - } - } catch (java.sql.SQLException failure) { - throw unavailable(); - } - return operation.apply(DSL.using(connection, SQLDialect.POSTGRES)); - }); + transaction.execute(status -> { + if (!status.isNewTransaction()) throw unavailable(); + Object resource = + TransactionSynchronizationManager.getResource( + Objects.requireNonNull(manager.getDataSource())); + if (!(resource instanceof ConnectionHolder holder)) throw unavailable(); + Connection connection = holder.getConnection(); + try { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_SERIALIZABLE) { + throw unavailable(); + } + } catch (java.sql.SQLException failure) { + throw unavailable(); + } + return operation.apply(DSL.using(connection, SQLDialect.POSTGRES)); + }); return Objects.requireNonNull(result); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java index 12f1484898..b690f01496 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java @@ -146,16 +146,15 @@ private static T execute( transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); transaction.setReadOnly(false); var result = - transaction.execute( - status -> { - if (!status.isNewTransaction()) throw denied(); - Connection connection = manager.bindConnection(); - var dsl = DSL.using(connection, SQLDialect.POSTGRES); - var repository = - new AccountGameplayAdmissionOriginalAckReceiptRepository( - dsl, new AccountGameplayAdmissionLeaseRepository(dsl)); - return Objects.requireNonNull(operation.apply(repository)); - }); + transaction.execute(status -> { + if (!status.isNewTransaction()) throw denied(); + Connection connection = manager.bindConnection(); + var dsl = DSL.using(connection, SQLDialect.POSTGRES); + var repository = + new AccountGameplayAdmissionOriginalAckReceiptRepository( + dsl, new AccountGameplayAdmissionLeaseRepository(dsl)); + return Objects.requireNonNull(operation.apply(repository)); + }); if (!manager.committed) throw denied(); return Objects.requireNonNull(result); } 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 008e21744d..09c5ecae8b 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 @@ -85,39 +85,38 @@ private OriginalCommitAcknowledgement execute( transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); transaction.setReadOnly(false); - transaction.executeWithoutResult( - ignored -> { - if (!ignored.isNewTransaction()) throw denied(); - Connection connection = manager.enlistedConnection(); - // Every source and lease repository uses this exact enlisted connection. The concrete - // source graph locks Account first, before authority, token and lease-operation rows, and - // retains those locks through the original physical COMMIT below. - var exactDsl = DSL.using(connection, SQLDialect.POSTGRES); - if (currentSources != null) { - var scope = (java.util.Map) evidence.carrier().get("bindingScope"); - var token = (java.util.Map) evidence.carrier().get("tokenIdentityEvidence"); - var current = - AccountGameplayAdmissionCurrentSources.bind( - exactDsl, currentSources.configuredNamespace()) - .readCurrentPublicProductionNew( - UUID.fromString((String) scope.get("tenantId")), - UUID.fromString((String) token.get("tokenJti")), - currentSources.authenticatedCandidate()); - current.requireMatchesOriginalLease(evidence); - } - var repository = new AccountGameplayAdmissionLeaseRepository(exactDsl); - var prior = - repository - .readExact(evidence) - .orElseThrow(AccountGameplayAdmissionOriginalCommitExecutor::denied); - if (prior.state() != State.PENDING) throw denied(); - var committed = repository.recordCommitted(evidence, decisionId); - if (committed.state() != State.COMMITTED - || !decisionId.equals(committed.bindingDecisionId()) - || !evidence.canonicalJson().equals(committed.evidence().canonicalJson()) - || !evidence.sha256().equals(committed.evidence().sha256())) throw denied(); - manager.bindOriginal(connection, evidence, decisionId); - }); + transaction.executeWithoutResult(ignored -> { + if (!ignored.isNewTransaction()) throw denied(); + Connection connection = manager.enlistedConnection(); + // Every source and lease repository uses this exact enlisted connection. The concrete + // source graph locks Account first, before authority, token and lease-operation rows, and + // retains those locks through the original physical COMMIT below. + var exactDsl = DSL.using(connection, SQLDialect.POSTGRES); + if (currentSources != null) { + var scope = (java.util.Map) evidence.carrier().get("bindingScope"); + var token = (java.util.Map) evidence.carrier().get("tokenIdentityEvidence"); + var current = + AccountGameplayAdmissionCurrentSources.bind( + exactDsl, currentSources.configuredNamespace()) + .readCurrentPublicProductionNew( + UUID.fromString((String) scope.get("tenantId")), + UUID.fromString((String) token.get("tokenJti")), + currentSources.authenticatedCandidate()); + current.requireMatchesOriginalLease(evidence); + } + var repository = new AccountGameplayAdmissionLeaseRepository(exactDsl); + var prior = + repository + .readExact(evidence) + .orElseThrow(AccountGameplayAdmissionOriginalCommitExecutor::denied); + if (prior.state() != State.PENDING) throw denied(); + var committed = repository.recordCommitted(evidence, decisionId); + if (committed.state() != State.COMMITTED + || !decisionId.equals(committed.bindingDecisionId()) + || !evidence.canonicalJson().equals(committed.evidence().canonicalJson()) + || !evidence.sha256().equals(committed.evidence().sha256())) throw denied(); + manager.bindOriginal(connection, evidence, decisionId); + }); return Objects.requireNonNull(manager.acknowledgement); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java index b60aabedfd..7ce2183cc4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java @@ -908,17 +908,15 @@ private static AuthenticatedSignerCorrespondence requireCommittedSignerProof( .equals(correspondence.privatePromotionGenerationOperationId()) || correspondence .durableActive() - .filter( - active -> - active.generation().equals(candidate.signerGeneration()) - && active.kid().equals(candidate.kid())) + .filter(active -> + active.generation().equals(candidate.signerGeneration()) + && active.kid().equals(candidate.kid())) .isEmpty() || correspondence .publishedActive() - .filter( - active -> - active.generation().equals(candidate.signerGeneration()) - && active.kid().equals(candidate.kid())) + .filter(active -> + active.generation().equals(candidate.signerGeneration()) + && active.kid().equals(candidate.kid())) .isEmpty() || correspondence .promotionPrivateObservedResourceVersion() @@ -1750,12 +1748,11 @@ private static AccountAuthoritySnapshot authoritySnapshot(IssuerAccountSourceSna snapshot .account() .accountSecurityCutoff() - .map( - value -> - new AccountSecurityCutoff( - value.accountAuthorityGeneration(), - value.outboxStreamKey(), - value.outboxSequence())) + .map(value -> + new AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())) .orElse(null); return new AccountAuthoritySnapshot( snapshot.account().scope().accountId(), diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepository.java index 25e885b407..27c330470f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepository.java @@ -841,12 +841,11 @@ private static void requireCurrentAuthority( account.generation(), account .accountSecurityCutoff() - .map( - cutoff -> - new GameSessionAccountDelegationProfile.AccountSecurityCutoff( - cutoff.accountAuthorityGeneration(), - cutoff.outboxStreamKey(), - cutoff.outboxSequence()))); + .map(cutoff -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence()))); if (!Arrays.equals( bytes(operation, "authority_tuple_canonical_bytes"), canonicalJson(currentTuple)) || !Arrays.equals(bytes(operation, "membership_version_canonical_bytes"), EMPTY_OBJECT)) { @@ -969,12 +968,11 @@ private static AccountAuthoritySnapshot authoritySnapshot(IssuerAccountSourceSna sources .account() .accountSecurityCutoff() - .map( - value -> - new GameSessionAccountDelegationProfile.AccountSecurityCutoff( - value.accountAuthorityGeneration(), - value.outboxStreamKey(), - value.outboxSequence())); + .map(value -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())); return new AccountAuthoritySnapshot( sources.account().scope().accountId(), sources.issuer().generation(), 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 246fc7383b..02d2fb3bcf 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 @@ -130,11 +130,10 @@ public ResolutionPreparation prepareTerminalResolution(Request request) { } new AccountAuditOutboxRepository(dsl) .findCanonicalTenantEnvelopeForUpdate(request.auditEventId()) - .filter( - audit -> - request.digest().equals(audit.payloadDigest()) - && "HOSTING_SUBSCRIPTION_TERMINAL_RESOLVED".equals(audit.eventType()) - && request.tenantId().equals(audit.tenantUuid())) + .filter(audit -> + request.digest().equals(audit.payloadDigest()) + && "HOSTING_SUBSCRIPTION_TERMINAL_RESOLVED".equals(audit.eventType()) + && request.tenantId().equals(audit.tenantUuid())) .orElseThrow( () -> new FenceRejectedException("Terminal resolution audit readback differs")); return new ResolutionPreparation( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountInitialTenantBillingOwnerRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountInitialTenantBillingOwnerRepository.java index ab9743bb3b..66f4eb51a4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountInitialTenantBillingOwnerRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountInitialTenantBillingOwnerRepository.java @@ -99,10 +99,8 @@ public InitialBindingResult establishInitial(InitialRequest request) { insertInitialCurrentOwner(request, ownerGeneration); InitialBindingResult stored = findOperationForUpdate(request.requestId()) - .orElseThrow( - () -> - new IllegalStateException( - "Initial billing-owner result is absent after insert")); + .orElseThrow(() -> + new IllegalStateException("Initial billing-owner result is absent after insert")); requireSameRequest(stored, request, encoded); if (!stored.ownerGeneration().equals(ownerGeneration) || !Arrays.equals(stored.resultPayload(), resultPayload) @@ -112,10 +110,9 @@ public InitialBindingResult establishInitial(InitialRequest request) { } CurrentOwnerBinding current = findCurrentOwnerForUpdate(creation.canonicalTenantId()) - .orElseThrow( - () -> - new IllegalStateException( - "Initial current billing owner is absent after insert")); + .orElseThrow(() -> + new IllegalStateException( + "Initial current billing owner is absent after insert")); requireInitialCurrentOwner(current, request, ownerGeneration); return stored; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java index 60d9ce907c..95ff728bee 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java @@ -257,9 +257,8 @@ public CanonicalJoinOperationEvidence bindCanonicalPolicyEvidence( entitlementVersion); CanonicalJoinOperationEvidence operation = lockCanonicalEvidenceByRequestId(requestId) - .orElseThrow( - () -> - new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); + .orElseThrow(() -> + new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); requireCanonicalIntentMatch(operation, requestId, callerBinding, intentDigest, scopeEvidence); if (operation.requestDigest() != null) { @@ -308,9 +307,8 @@ public CanonicalJoinOperationEvidence bindCanonicalPolicyEvidence( CanonicalJoinOperationEvidence committed = readCanonicalEvidenceByRequestId(requestId, false) - .orElseThrow( - () -> - new IllegalStateException("Canonical JOIN policy binding readback is absent")); + .orElseThrow(() -> + new IllegalStateException("Canonical JOIN policy binding readback is absent")); requireCanonicalIntentMatch(committed, requestId, callerBinding, intentDigest, scopeEvidence); requireCanonicalPolicyMatch(committed, requestDigest, allowPublicJoin, entitlementVersion); return committed; @@ -348,9 +346,8 @@ public CanonicalJoinOperationEvidence recordCanonicalAttemptFailure( String intentDigest = AccountJoinDigest.intentV2(requestId, scope, callerBinding); CanonicalJoinOperationEvidence operation = lockCanonicalEvidenceByRequestId(requestId) - .orElseThrow( - () -> - new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); + .orElseThrow(() -> + new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); requireCanonicalIntentMatch(operation, requestId, callerBinding, intentDigest, scopeEvidence); if (!"PENDING".equals(operation.status())) throw new CanonicalJoinOperationConflictException( @@ -404,9 +401,8 @@ public CanonicalJoinOperationEvidence finishCanonicalFailure( String intentDigest = AccountJoinDigest.intentV2(requestId, scope, callerBinding); CanonicalJoinOperationEvidence operation = lockCanonicalEvidenceByRequestId(requestId) - .orElseThrow( - () -> - new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); + .orElseThrow(() -> + new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); requireCanonicalIntentMatch(operation, requestId, callerBinding, intentDigest, scopeEvidence); if ("FAILED".equals(operation.status()) && outcome.equals(operation.outcome())) return operation; @@ -478,9 +474,8 @@ public CanonicalJoinOperationEvidence commitCanonicalJoin( String intentDigest = AccountJoinDigest.intentV2(requestId, scope, callerBinding); CanonicalJoinOperationEvidence operation = lockCanonicalEvidenceByRequestId(requestId) - .orElseThrow( - () -> - new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); + .orElseThrow(() -> + new CanonicalJoinOperationConflictException("Canonical JOIN intent is absent")); boolean publicJoin = Boolean.TRUE.equals(operation.allowPublicJoin()); if ("JOINED".equals(outcome) && !publicJoin) { throw new CanonicalJoinOperationConflictException( @@ -707,9 +702,8 @@ private Optional readCanonicalEvidenceByRequestI CanonicalConnectScopeEvidence scopeEvidence = connectScopes .findCanonicalEvidenceByTokenHash(scopeTokenHash) - .orElseThrow( - () -> - new IllegalStateException("Canonical JOIN operation scope evidence is absent")); + .orElseThrow(() -> + new IllegalStateException("Canonical JOIN operation scope evidence is absent")); return Optional.of(toCanonicalOperationEvidence(row, scopeEvidence)); } @@ -728,10 +722,9 @@ private CanonicalConnectScopeEvidence requireIncomingScope(CanonicalJoinScopeV2 CanonicalJoinScopeV2 persisted = connectScopes .findCanonical(scope.connectScopeId()) - .orElseThrow( - () -> - new CanonicalJoinOperationConflictException( - "Canonical JOIN scope evidence is absent")); + .orElseThrow(() -> + new CanonicalJoinOperationConflictException( + "Canonical JOIN scope evidence is absent")); if (!persisted.equals(scope)) { throw new CanonicalJoinOperationConflictException( "Canonical JOIN scope differs from immutable token evidence"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java index 515bde1777..ff4b802753 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepository.java @@ -744,11 +744,10 @@ private static long positive(Long value, String field) { private static String activeJson(Optional active) { Map value = new LinkedHashMap<>(); value.put("present", active.isPresent()); - active.ifPresent( - signer -> { - value.put("generation", signer.generation()); - value.put("kid", signer.kid()); - }); + active.ifPresent(signer -> { + value.put("generation", signer.generation()); + value.put("kid", signer.kid()); + }); return new String(canonicalJson(value), StandardCharsets.UTF_8); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java index 05f14f694f..2a4adb2099 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java @@ -303,12 +303,11 @@ public DeliveryClaim claimSingleDelivery( if (currentPlan.entries().isEmpty() || currentPlan.entries().size() > MAX_ENTRIES_PER_OPERATION || currentPlan.entries().stream() - .anyMatch( - entry -> - entry.state() != ProbeState.PLANNED - || entry.signingAttemptedAtEpochSecond().isPresent() - || entry.compactTokenSha256().isPresent() - || entry.verificationReceipt().isPresent())) { + .anyMatch(entry -> + entry.state() != ProbeState.PLANNED + || entry.signingAttemptedAtEpochSecond().isPresent() + || entry.compactTokenSha256().isPresent() + || entry.verificationReceipt().isPresent())) { throw new DeliveryAlreadyClaimedException(); } if (selectDeliveryClaim(currentPlan.operationId(), true) != null) { @@ -607,10 +606,9 @@ public ProbeEntry recordVerified( VerificationReceipt existing = entry .verificationReceipt() - .orElseThrow( - () -> - new QuarantinedStateException( - "Verified readiness entry has no immutable receipt")); + .orElseThrow(() -> + new QuarantinedStateException( + "Verified readiness entry has no immutable receipt")); requireMatchingObservation(existing, observation); return entry; } @@ -2765,61 +2763,54 @@ private static String applicabilityMatrixJson( List> validators = snapshot.validators().stream() .sorted(java.util.Comparator.comparing(ValidatorObservation::validatorId)) - .map( - validator -> { - List> applicable = - validator.profiles().stream() - .map( - profile -> - Map.of( - "audience", profile.audience(), - "tokenProfile", profile.tokenProfile())) - .sorted( - java.util.Comparator.comparing( - (Map value) -> - value.get("tokenProfile").toString()) - .thenComparing(value -> value.get("audience").toString())) - .toList(); - List> inapplicable = - PRODUCTION_PROFILE_CASES.stream() - .filter( - profile -> - validator.profiles().stream() - .noneMatch( - actual -> - actual.tokenProfile().equals(profile.tokenProfile()) - && actual.audience().equals(profile.audience()))) - .map( - profile -> - Map.of( - "audience", profile.audience(), - "tokenProfile", profile.tokenProfile())) - .toList(); - Map value = new LinkedHashMap<>(); - value.put("applicableProfiles", applicable); - value.put("deploymentUid", validator.deploymentUid()); - value.put("image", validator.image()); - value.put("podCount", validator.pods().size()); - value.put( - "pods", - validator.pods().stream() - .sorted(java.util.Comparator.comparing(PodObservation::uid)) - .map( - pod -> - Map.of( - "podUid", pod.uid(), - "podIp", pod.podIp(), - "exactPodEndpoint", pod.endpoint().toString(), - "canonicalServiceUri", pod.receiverServiceUri(), - "leafSpkiSha256", pod.leafSpkiSha256(), - "image", pod.image(), - "verifierConfigSha256", pod.verifierConfigSha256())) - .toList()); - value.put("inapplicableProfiles", inapplicable); - value.put("validatorId", validator.validatorId()); - value.put("verifierConfigSha256", validator.verifierConfigSha256()); - return value; - }) + .map(validator -> { + List> applicable = + validator.profiles().stream() + .map(profile -> + Map.of( + "audience", profile.audience(), + "tokenProfile", profile.tokenProfile())) + .sorted( + java.util.Comparator.comparing((Map value) -> + value.get("tokenProfile").toString()) + .thenComparing(value -> value.get("audience").toString())) + .toList(); + List> inapplicable = + PRODUCTION_PROFILE_CASES.stream() + .filter(profile -> + validator.profiles().stream() + .noneMatch(actual -> + actual.tokenProfile().equals(profile.tokenProfile()) + && actual.audience().equals(profile.audience()))) + .map(profile -> + Map.of( + "audience", profile.audience(), + "tokenProfile", profile.tokenProfile())) + .toList(); + Map value = new LinkedHashMap<>(); + value.put("applicableProfiles", applicable); + value.put("deploymentUid", validator.deploymentUid()); + value.put("image", validator.image()); + value.put("podCount", validator.pods().size()); + value.put( + "pods", + validator.pods().stream() + .sorted(java.util.Comparator.comparing(PodObservation::uid)) + .map(pod -> + Map.of( + "podUid", pod.uid(), + "podIp", pod.podIp(), + "exactPodEndpoint", pod.endpoint().toString(), + "canonicalServiceUri", pod.receiverServiceUri(), + "leafSpkiSha256", pod.leafSpkiSha256(), + "image", pod.image(), + "verifierConfigSha256", pod.verifierConfigSha256())) + .toList()); + value.put("inapplicableProfiles", inapplicable); + value.put("validatorId", validator.validatorId()); + value.put("verifierConfigSha256", validator.verifierConfigSha256()); + return value; + }) .toList(); Map source = new LinkedHashMap<>(); source.put("apiBindingDigest", snapshot.apiBindingDigest()); @@ -2837,11 +2828,10 @@ private static String applicabilityMatrixJson( matrix.put( "productionProfiles", PRODUCTION_PROFILE_CASES.stream() - .map( - profile -> - Map.of( - "audience", profile.audience(), - "tokenProfile", profile.tokenProfile())) + .map(profile -> + Map.of( + "audience", profile.audience(), + "tokenProfile", profile.tokenProfile())) .toList()); matrix.put("schemaVersion", INVENTORY_PLAN_VERSION); matrix.put("source", source); @@ -2899,10 +2889,9 @@ private static List expectedPods( entry.probeKind() == ProbeKind.CANARY ? ProbeExpectation.ACCEPT : validator.profiles().stream() - .anyMatch( - profile -> - profile.tokenProfile().equals(entry.tokenProfile()) - && profile.audience().equals(entry.audience())) + .anyMatch(profile -> + profile.tokenProfile().equals(entry.tokenProfile()) + && profile.audience().equals(entry.audience())) ? ProbeExpectation.ACCEPT : ProbeExpectation.INAPPLICABLE_REJECT; for (PodObservation pod : validator.pods()) { @@ -3522,13 +3511,11 @@ public record ProbeEntry( if (compactTokenSha256.isPresent() != signingAttemptedAtEpochSecond.isPresent()) { throw new QuarantinedStateException("Readiness signing-attempt evidence is partial"); } - signingAttemptedAtEpochSecond.ifPresent( - attemptedAt -> { - if (attemptedAt < plannedIssuedAtEpochSecond || attemptedAt >= expiresAtEpochSecond) { - throw new QuarantinedStateException( - "Readiness signing-attempt time is outside its plan"); - } - }); + signingAttemptedAtEpochSecond.ifPresent(attemptedAt -> { + if (attemptedAt < plannedIssuedAtEpochSecond || attemptedAt >= expiresAtEpochSecond) { + throw new QuarantinedStateException("Readiness signing-attempt time is outside its plan"); + } + }); if ((state == ProbeState.ABORTED || state == ProbeState.EXPIRED || state == ProbeState.CLEANED) @@ -3550,19 +3537,18 @@ public record ProbeEntry( && verificationReceipt.isPresent())) { throw new QuarantinedStateException("Readiness state and verification receipt disagree"); } - verificationReceipt.ifPresent( - receipt -> { - if ((receipt.receiptVersion() == 1 && !receipt.verifiedKid().equals(targetKid)) - || (receipt.receiptVersion() == 2 - && receipt.verifiedKid() != null - && !receipt.verifiedKid().equals(targetKid)) - || receipt.resultEntryVersion() > entryVersion - || receipt.sourceEntryVersion() + 1L != receipt.resultEntryVersion() - || (state == ProbeState.VERIFIED && receipt.resultEntryVersion() != entryVersion)) { - throw new QuarantinedStateException( - "Readiness verification receipt differs from its immutable entry"); - } - }); + verificationReceipt.ifPresent(receipt -> { + if ((receipt.receiptVersion() == 1 && !receipt.verifiedKid().equals(targetKid)) + || (receipt.receiptVersion() == 2 + && receipt.verifiedKid() != null + && !receipt.verifiedKid().equals(targetKid)) + || receipt.resultEntryVersion() > entryVersion + || receipt.sourceEntryVersion() + 1L != receipt.resultEntryVersion() + || (state == ProbeState.VERIFIED && receipt.resultEntryVersion() != entryVersion)) { + throw new QuarantinedStateException( + "Readiness verification receipt differs from its immutable entry"); + } + }); if (verificationReceipt.isPresent() && verificationReceipt.orElseThrow().resultEntryVersion() > entryVersion) { throw new QuarantinedStateException("Terminal readiness receipt version is invalid"); @@ -4064,15 +4050,14 @@ public record DeliveryClaim( requireGeneration(targetGeneration); requireKid(targetKid); expectedActive = Objects.requireNonNull(expectedActive); - expectedActive.ifPresent( - active -> { - requireGeneration(active.generation()); - requireKid(active.kid()); - if (Long.parseLong(targetGeneration) <= Long.parseLong(active.generation()) - || targetKid.equals(active.kid())) { - throw new QuarantinedStateException("Delivery active fence is not older than target"); - } - }); + expectedActive.ifPresent(active -> { + requireGeneration(active.generation()); + requireKid(active.kid()); + if (Long.parseLong(targetGeneration) <= Long.parseLong(active.generation()) + || targetKid.equals(active.kid())) { + throw new QuarantinedStateException("Delivery active fence is not older than target"); + } + }); requireDigest(readinessBindingDigest, "readiness trust digest"); requireRevision(readinessConfigRevision, "readiness trust revision"); if (readinessBindingValidUntilEpochSecond <= claimedAtEpochSecond) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java index f79bc88cde..3826252b21 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java @@ -407,10 +407,9 @@ public GenerationRequest readCurrentGenerationRequest(Binding expectedBinding, T UUID operationId = state .generationOperationId() - .orElseThrow( - () -> - new MissingGenerationOperationException( - "Account has no owner-selected JWT generation operation")); + .orElseThrow(() -> + new MissingGenerationOperationException( + "Account has no owner-selected JWT generation operation")); StoredGenerationOperation operation = selectGenerationOperation(operationId, true); if (operation == null) { throw new QuarantinedStateException("Account JWT signer generation operation is missing"); @@ -441,10 +440,9 @@ public GenerationResult readCurrentGenerationResult(Binding expectedBinding, Tru UUID operationId = state .generationOperationId() - .orElseThrow( - () -> - new MissingGenerationOperationException( - "Account has no owner-selected JWT generation operation")); + .orElseThrow(() -> + new MissingGenerationOperationException( + "Account has no owner-selected JWT generation operation")); StoredGenerationOperation operation = selectGenerationOperation(operationId, true); if (operation == null) { throw new QuarantinedStateException("Account JWT signer generation operation is missing"); @@ -723,10 +721,9 @@ public ActiveJwksPromotionReceipt recordActiveJwksPromotionResult( UUID promotionId = state .preparedOperationId() - .orElseThrow( - () -> - new PromotionPrerequisitesIncompleteException( - "Account has no PREPARED JWT signer promotion")); + .orElseThrow(() -> + new PromotionPrerequisitesIncompleteException( + "Account has no PREPARED JWT signer promotion")); StoredPromotion promotion = selectPromotion(promotionId, true); if (promotion == null || !"PREPARED".equals(promotion.status())) { throw new QuarantinedStateException("Account PREPARED JWT signer operation is missing"); @@ -1321,10 +1318,9 @@ public PreparedPromotion prepareCurrentGeneration( UUID generationOperationId = state .generationOperationId() - .orElseThrow( - () -> - new MissingGenerationOperationException( - "Account has no current generation operation to promote")); + .orElseThrow(() -> + new MissingGenerationOperationException( + "Account has no current generation operation to promote")); StoredGenerationOperation generation = selectGenerationOperation(generationOperationId, true); GenerationResult result = selectGenerationResult(generationOperationId, true); if (generation == null || result == null) { @@ -1605,10 +1601,9 @@ private static void requireEnrollmentTrust(DesiredState state, TrustFence trust) EnrollmentIdentity enrolled = state .enrollmentIdentity() - .orElseThrow( - () -> - new QuarantinedStateException( - "Account JWT signer state has no independently protected enrollment identity")); + .orElseThrow(() -> + new QuarantinedStateException( + "Account JWT signer state has no independently protected enrollment identity")); if (!enrolled.expectedClusterIncarnationUid().equals(trust.expectedClusterIncarnationUid()) || !enrolled.expectedNamespaceUid().equals(trust.expectedNamespaceUid()) || !enrolled.materializerTrustBindingDigest().equals(trust.bindingDigest()) @@ -1932,11 +1927,10 @@ private static String activeMarkerJson(StoredPromotion promotion) { private static Map activeMarker(Optional active) { Map marker = new LinkedHashMap<>(); marker.put("present", active.isPresent()); - active.ifPresent( - signer -> { - marker.put("generation", signer.generation()); - marker.put("kid", signer.kid()); - }); + active.ifPresent(signer -> { + marker.put("generation", signer.generation()); + marker.put("kid", signer.kid()); + }); return marker; } @@ -1997,12 +1991,11 @@ private static void requirePrivatePromotionObservation( Optional expectedPrevious = promotion .expectedPreviousActive() - .map( - active -> - new PublicKeyIdentity( - active.generation(), - active.kid(), - publicFingerprintForKid(promotion.expectedPublicJwksJson(), active.kid()))); + .map(active -> + new PublicKeyIdentity( + active.generation(), + active.kid(), + publicFingerprintForKid(promotion.expectedPublicJwksJson(), active.kid()))); PublicKeyIdentity expectedCurrent = new PublicKeyIdentity( promotion.targetGeneration(), @@ -4473,13 +4466,11 @@ private static PrivatePromotionReceipt fromStored(StoredPromotion promotion) { Optional previous = promotion .expectedPreviousActive() - .map( - active -> - new PublicKeyIdentity( - active.generation(), - active.kid(), - publicFingerprintForKid( - promotion.expectedPublicJwksJson(), active.kid()))); + .map(active -> + new PublicKeyIdentity( + active.generation(), + active.kid(), + publicFingerprintForKid(promotion.expectedPublicJwksJson(), active.kid()))); PrivatePromotionReceipt calculated = from( promotion, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java index 3a5e3016e4..6bdfd21a9c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepository.java @@ -117,10 +117,8 @@ PairAuthority enrollAbsence( PairAuthority readback = readForUpdate(accountUuid, tenantUuid) - .orElseThrow( - () -> - new IllegalStateException( - "Account membership pair baseline readback is absent")); + .orElseThrow(() -> + new IllegalStateException("Account membership pair baseline readback is absent")); if (!baseline.equals(readback)) { throw new IllegalStateException( "Account membership pair baseline readback differs from the exact absence state"); @@ -196,10 +194,8 @@ public PairAuthority commitTransition(PairAuthority expected, PairTransition tra PairAuthority advanced = readForUpdate(expected.accountUuid(), expected.tenantUuid()) - .orElseThrow( - () -> - new IllegalStateException( - "Advanced Account membership pair readback is absent")); + .orElseThrow(() -> + new IllegalStateException("Advanced Account membership pair readback is absent")); PairAuthority required = new PairAuthority( expected.accountUuid(), 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 473bdc3880..41e4522c29 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 @@ -207,17 +207,16 @@ private IssuedOriginalNew issueChecked( } Genesis genesis = - inWritableSerializableTransaction( - dsl -> - new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) - .beginGenesis( - requestedLease, - receipt, - newLineageId, - frozenNewTokenJti, - nowSeconds, - nowSeconds, - expirySeconds)); + inWritableSerializableTransaction(dsl -> + new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) + .beginGenesis( + requestedLease, + receipt, + newLineageId, + frozenNewTokenJti, + nowSeconds, + nowSeconds, + expirySeconds)); if (genesis.tokenHash() == null) { genesis = signAndPersistCandidate(caller, requestedLease, receipt, genesis); @@ -245,30 +244,29 @@ private IssuedOriginalNew issueChecked( } final Genesis exactGenesisForCommit = genesis; Genesis committed = - inWritableSerializableTransaction( - dsl -> { - SourceRead current = readCurrentOriginalSource(dsl, currentCaller, requestedLease); - requireSameOriginalOperation(initial.operation(), current.operation()); - AccountOriginalNewBoundGameplayIssuanceRepository issuance = - new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); - Genesis stored = issuance.readByLease(leaseId(requestedLease)); - requireSameGenesisIdentity(exactGenesisForCommit, stored); - Genesis committedResult = issuance.commit(stored, receiptDigest); - var fenceRepository = new AccountGameplayTokenIdentityFenceRepository(dsl); - var tokenIdentity = - new TokenIdentity( - committedResult.accountId(), - committedResult.lineageId(), - committedResult.requestId(), - committedResult.tokenHash(), - committedResult.tokenJti(), - committedResult.notBeforeEpochSecond(), - committedResult.tokenGeneration(), - committedResult.issuanceFence(), - SourceKind.ORIGINAL_NEW); - fenceRepository.registerCommittedOriginalNewIssuance(tokenIdentity); - return committedResult; - }); + inWritableSerializableTransaction(dsl -> { + SourceRead current = readCurrentOriginalSource(dsl, currentCaller, requestedLease); + requireSameOriginalOperation(initial.operation(), current.operation()); + AccountOriginalNewBoundGameplayIssuanceRepository issuance = + new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); + Genesis stored = issuance.readByLease(leaseId(requestedLease)); + requireSameGenesisIdentity(exactGenesisForCommit, stored); + Genesis committedResult = issuance.commit(stored, receiptDigest); + var fenceRepository = new AccountGameplayTokenIdentityFenceRepository(dsl); + var tokenIdentity = + new TokenIdentity( + committedResult.accountId(), + committedResult.lineageId(), + committedResult.requestId(), + committedResult.tokenHash(), + committedResult.tokenJti(), + committedResult.notBeforeEpochSecond(), + committedResult.tokenGeneration(), + committedResult.issuanceFence(), + SourceKind.ORIGINAL_NEW); + fenceRepository.registerCommittedOriginalNewIssuance(tokenIdentity); + return committedResult; + }); // The caller receives the result only after Account's issuance row and active identity fence // committed together. Opening requires a fresh source and exact active-fence readback. @@ -350,20 +348,19 @@ public OriginalAdmissionConfirmation confirmOriginalFinalAdmission( receiptExecutor.read(requestedLease, beforeRead.operation().bindingDecisionId()); requireExactReceipt(receipt, beforeRead.operation(), requestedLease); Genesis beforeGenesis = - inWritableSerializableTransaction( - dsl -> { - SourceRead current = readCurrentOriginalSource(dsl, caller, requestedLease); - requireSameOriginalOperation(beforeRead.operation(), current.operation()); - Genesis stored = - new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) - .readByLease(leaseId(requestedLease)); - if (stored == null - || stored.status() - != AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED) { - throw unavailable(); - } - return stored; - }); + inWritableSerializableTransaction(dsl -> { + SourceRead current = readCurrentOriginalSource(dsl, caller, requestedLease); + requireSameOriginalOperation(beforeRead.operation(), current.operation()); + Genesis stored = + new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) + .readByLease(leaseId(requestedLease)); + if (stored == null + || stored.status() + != AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED) { + throw unavailable(); + } + return stored; + }); OriginalNewCredential storedCredential = beforeGenesis.confirmedAdmissionAtMillis() == null ? openFrozenCredentialForFinalAdmissionVerification( @@ -398,35 +395,33 @@ public OriginalAdmissionConfirmation confirmOriginalFinalAdmission( throw unavailable(); } Genesis recovered = - inWritableSerializableTransaction( - dsl -> { - SourceRead current = readCurrentOriginalSource(dsl, currentCaller, requestedLease); - requireSameOriginalOperation(beforeRead.operation(), current.operation()); - AccountGameplayAdmissionOriginalAckReceipt durableReceipt = - new AccountGameplayAdmissionOriginalAckReceiptRepository( - dsl, new AccountGameplayAdmissionLeaseRepository(dsl)) - .readExact(requestedLease, current.operation().bindingDecisionId()); - // The receipt owner already proved independent durability outside this - // transaction. Re-read the immutable row here under current source locks. - requireExactReceipt(durableReceipt, current.operation(), requestedLease); - if (!receipt.equals(durableReceipt)) throw unavailable(); - var issuance = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); - Genesis exact = issuance.readByLease(leaseId(requestedLease)); - requireSameGenesisIdentity(beforeGenesis, exact); - if (exact.confirmedAdmissionAtMillis() == null - || !Objects.equals( - exact.confirmedAdmissionAtMillis(), - beforeGenesis.confirmedAdmissionAtMillis()) - || !Objects.equals( - exact.confirmedContinuityExpiresAtMillis(), - beforeGenesis.confirmedContinuityExpiresAtMillis()) - || !exact - .confirmationReadbackSha256() - .equals(beforeGenesis.confirmationReadbackSha256())) throw unavailable(); - new AccountGameplayTokenIdentityFenceRepository(dsl) - .requireActiveReadback(originalNewIdentity(exact)); - return exact; - }); + inWritableSerializableTransaction(dsl -> { + SourceRead current = readCurrentOriginalSource(dsl, currentCaller, requestedLease); + requireSameOriginalOperation(beforeRead.operation(), current.operation()); + AccountGameplayAdmissionOriginalAckReceipt durableReceipt = + new AccountGameplayAdmissionOriginalAckReceiptRepository( + dsl, new AccountGameplayAdmissionLeaseRepository(dsl)) + .readExact(requestedLease, current.operation().bindingDecisionId()); + // The receipt owner already proved independent durability outside this + // transaction. Re-read the immutable row here under current source locks. + requireExactReceipt(durableReceipt, current.operation(), requestedLease); + if (!receipt.equals(durableReceipt)) throw unavailable(); + var issuance = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); + Genesis exact = issuance.readByLease(leaseId(requestedLease)); + requireSameGenesisIdentity(beforeGenesis, exact); + if (exact.confirmedAdmissionAtMillis() == null + || !Objects.equals( + exact.confirmedAdmissionAtMillis(), beforeGenesis.confirmedAdmissionAtMillis()) + || !Objects.equals( + exact.confirmedContinuityExpiresAtMillis(), + beforeGenesis.confirmedContinuityExpiresAtMillis()) + || !exact + .confirmationReadbackSha256() + .equals(beforeGenesis.confirmationReadbackSha256())) throw unavailable(); + new AccountGameplayTokenIdentityFenceRepository(dsl) + .requireActiveReadback(originalNewIdentity(exact)); + return exact; + }); tokenRegistry.requireExactOriginalNewActiveRecord(recovered); if (clock.millis() >= recovered.confirmedContinuityExpiresAtMillis()) throw unavailable(); return new OriginalAdmissionConfirmation( @@ -478,30 +473,28 @@ dsl, new AccountGameplayAdmissionLeaseRepository(dsl)) stringStringMap(beforeGenesis.membershipVersionCanonicalBytes())); String confirmationDigest = confirmationDigest(finalReadback, activation); Genesis confirmed = - inWritableSerializableTransaction( - dsl -> { - SourceRead current = readCurrentOriginalSource(dsl, currentCaller, requestedLease); - requireSameOriginalOperation(beforeRead.operation(), current.operation()); - AccountGameplayAdmissionOriginalAckReceipt durableReceipt = - new AccountGameplayAdmissionOriginalAckReceiptRepository( - dsl, new AccountGameplayAdmissionLeaseRepository(dsl)) - .readExact(requestedLease, current.operation().bindingDecisionId()); - // Keep the independently proved receipt exact; this transaction supplies - // current source exclusion, not another historical durability attempt. - requireExactReceipt(durableReceipt, current.operation(), requestedLease); - if (!receipt.equals(durableReceipt)) throw unavailable(); - var issuance = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); - Genesis exact = issuance.readByLease(leaseId(requestedLease)); - requireSameGenesisIdentity(beforeGenesis, exact); - TokenIdentity tokenIdentity = originalNewIdentity(exact); - new AccountGameplayTokenIdentityFenceRepository(dsl) - .requireActiveReadback(tokenIdentity); - return issuance.confirmFinalAdmission( - exact, - finalReadback.admissionAtMillis(), - finalReadback.continuityExpiresAtMillis(), - confirmationDigest); - }); + inWritableSerializableTransaction(dsl -> { + SourceRead current = readCurrentOriginalSource(dsl, currentCaller, requestedLease); + requireSameOriginalOperation(beforeRead.operation(), current.operation()); + AccountGameplayAdmissionOriginalAckReceipt durableReceipt = + new AccountGameplayAdmissionOriginalAckReceiptRepository( + dsl, new AccountGameplayAdmissionLeaseRepository(dsl)) + .readExact(requestedLease, current.operation().bindingDecisionId()); + // Keep the independently proved receipt exact; this transaction supplies + // current source exclusion, not another historical durability attempt. + requireExactReceipt(durableReceipt, current.operation(), requestedLease); + if (!receipt.equals(durableReceipt)) throw unavailable(); + var issuance = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl); + Genesis exact = issuance.readByLease(leaseId(requestedLease)); + requireSameGenesisIdentity(beforeGenesis, exact); + TokenIdentity tokenIdentity = originalNewIdentity(exact); + new AccountGameplayTokenIdentityFenceRepository(dsl).requireActiveReadback(tokenIdentity); + return issuance.confirmFinalAdmission( + exact, + finalReadback.admissionAtMillis(), + finalReadback.continuityExpiresAtMillis(), + confirmationDigest); + }); tokenRegistry.requireExactOriginalNewActiveRecord(confirmed); if (!confirmationDigest.equals(confirmed.confirmationReadbackSha256())) throw unavailable(); return new OriginalAdmissionConfirmation( @@ -622,31 +615,27 @@ private Genesis signAndPersistCandidate( byte[] exactRecord = recordBytes.clone(); byte[] exactEnvelope = envelopeBytes.clone(); try { - return inWritableSerializableTransaction( - dsl -> { - SourceRead current = readCurrentOriginalSource(dsl, caller, lease); - if (current.operation().state() != State.COMMITTED - || !current - .operation() - .bindingDecisionId() - .equals(receipt.bindingDecisionId())) { - throw unavailable(); - } - requireExactReceipt(receipt, current.operation(), lease); - Genesis currentGenesis = - new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) - .readByLease(leaseId(lease)); - requireSameGenesisIdentity(genesis, currentGenesis); - return new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) - .bindSignedResult( - currentGenesis, - tokenHash, - signerKid, - signerGeneration, - exactRecord, - handleHash, - exactEnvelope); - }); + return inWritableSerializableTransaction(dsl -> { + SourceRead current = readCurrentOriginalSource(dsl, caller, lease); + if (current.operation().state() != State.COMMITTED + || !current.operation().bindingDecisionId().equals(receipt.bindingDecisionId())) { + throw unavailable(); + } + requireExactReceipt(receipt, current.operation(), lease); + Genesis currentGenesis = + new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) + .readByLease(leaseId(lease)); + requireSameGenesisIdentity(genesis, currentGenesis); + return new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) + .bindSignedResult( + currentGenesis, + tokenHash, + signerKid, + signerGeneration, + exactRecord, + handleHash, + exactEnvelope); + }); } finally { wipe(exactRecord); wipe(exactEnvelope); @@ -669,32 +658,30 @@ private OriginalNewCredential openCommittedResult( 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; - }); + 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); @@ -715,21 +702,20 @@ private OriginalNewCredential openFrozenCredentialForFinalAdmissionVerification( 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; - }); + 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; + }); return openFrozenCredentialResult(lease, receipt, source, committed); } @@ -895,13 +881,12 @@ private static Map stringObjectMap(byte[] bytes) { private static Map stringStringMap(byte[] bytes) { Map value = parseJsonMap(bytes); Map copy = new LinkedHashMap<>(); - value.forEach( - (key, item) -> { - if (!(key instanceof String textKey) || !(item instanceof String textValue)) { - throw unavailable(); - } - copy.put(textKey, textValue); - }); + value.forEach((key, item) -> { + if (!(key instanceof String textKey) || !(item instanceof String textValue)) { + throw unavailable(); + } + copy.put(textKey, textValue); + }); return Map.copyOf(copy); } @@ -991,24 +976,23 @@ private T inWritableSerializableTransaction( transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); transaction.setReadOnly(false); T result = - transaction.execute( - status -> { - if (!status.isNewTransaction()) throw unavailable(); - Object resource = - TransactionSynchronizationManager.getResource( - Objects.requireNonNull(manager.getDataSource())); - if (!(resource instanceof ConnectionHolder holder)) throw unavailable(); - var connection = holder.getConnection(); - try { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() - != java.sql.Connection.TRANSACTION_SERIALIZABLE) throw unavailable(); - } catch (java.sql.SQLException failure) { - throw unavailable(); - } - return operation.apply(DSL.using(connection, SQLDialect.POSTGRES)); - }); + transaction.execute(status -> { + if (!status.isNewTransaction()) throw unavailable(); + Object resource = + TransactionSynchronizationManager.getResource( + Objects.requireNonNull(manager.getDataSource())); + if (!(resource instanceof ConnectionHolder holder)) throw unavailable(); + var connection = holder.getConnection(); + try { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() + != java.sql.Connection.TRANSACTION_SERIALIZABLE) throw unavailable(); + } catch (java.sql.SQLException failure) { + throw unavailable(); + } + return operation.apply(DSL.using(connection, SQLDialect.POSTGRES)); + }); return Objects.requireNonNull(result); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java index 4fce1605b2..c9c7d6fcb0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java @@ -696,12 +696,11 @@ public record Operation( throw new IllegalArgumentException( "Positive Account identity and matching predecessor fence are required"); } - receipt.ifPresent( - committed -> { - if (committed.event().outboxSequence() != committed.sourceState().generation() - 1L) { - throw new RestrictionSourceUnavailableException(); - } - }); + receipt.ifPresent(committed -> { + if (committed.event().outboxSequence() != committed.sourceState().generation() - 1L) { + throw new RestrictionSourceUnavailableException(); + } + }); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java index 439fd2c64e..a11c870ba1 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java @@ -523,14 +523,13 @@ private void requireWritableReadCommittedTransaction() { if (isolation != null && isolation != Connection.TRANSACTION_READ_COMMITTED) { throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); } - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); - } - }); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + }); } private static IllegalStateException conflict() { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java index 56d7098520..0b1b06992a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java @@ -513,14 +513,13 @@ private void requireWritableReadCommittedTransaction() { if (isolation != null && isolation != Connection.TRANSACTION_READ_COMMITTED) { throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); } - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); - } - }); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + }); } private static ImmutableBindingConflictException conflict() { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java index 9d04d6e75a..a90b324020 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java @@ -443,14 +443,13 @@ private void requireWritableReadCommittedTransaction() { if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); } - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); - } - }); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + }); } private static void requireColumns(Record row, Set expected, String label) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java index 87beda3478..c7f45e8824 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java @@ -937,14 +937,13 @@ private void requireWritableReadCommittedTransaction() { if (declaredIsolation != null && declaredIsolation != Connection.TRANSACTION_READ_COMMITTED) { throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); } - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); - } - }); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException("Writable Account READ_COMMITTED transaction required"); + } + }); } private static ImmutableBindingConflictException conflict() { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java index ac817af7f1..b1bb8620ed 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java @@ -720,10 +720,9 @@ Event readCurrentDemoByTenant(UUID tenantId) { FreshTenantCreationEvidence source = tenantIdentity .read(tenantId) - .orElseThrow( - () -> - new IllegalStateException( - "Exact fresh Account tenant source evidence is unavailable")); + .orElseThrow(() -> + new IllegalStateException( + "Exact fresh Account tenant source evidence is unavailable")); ScopeState authority = generations.read(AccountAuthorityGenerationRepository.AuthorityScope.tenant(tenantId)); Record current = diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigest.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigest.java index e17c784be8..0c1e2d8c48 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigest.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantCreationBootstrapDigest.java @@ -60,23 +60,21 @@ public static byte[] sourceSnapshotPayload(NeverJoinedMembershipSnapshot snapsho source.put( "outboxCheckpoints", snapshot.outboxCheckpoints().stream() - .map( - checkpoint -> - Map.of( - "outboxStreamKey", checkpoint.outboxStreamKey(), - "outboxSequence", checkpoint.outboxSequence())) + .map(checkpoint -> + Map.of( + "outboxStreamKey", checkpoint.outboxStreamKey(), + "outboxSequence", checkpoint.outboxSequence())) .toList()); source.put( "outboxSourceEvidence", snapshot.outboxSourceEvidence().stream() - .map( - evidence -> - Map.of( - "outboxStreamKey", evidence.outboxStreamKey(), - "outboxSequence", evidence.outboxSequence(), - "eventId", evidence.eventId(), - "eventDigest", evidence.eventDigest(), - "canonicalEventJson", evidence.canonicalEventJson())) + .map(evidence -> + Map.of( + "outboxStreamKey", evidence.outboxStreamKey(), + "outboxSequence", evidence.outboxSequence(), + "eventId", evidence.eventId(), + "eventDigest", evidence.eventDigest(), + "canonicalEventJson", evidence.canonicalEventJson())) .toList()); return canonicalJson(source); } @@ -180,13 +178,11 @@ public static Map authorityTupleMap(AuthorityTuple tuple) { .ifPresent(cutoff -> result.put("accountSecurityCutoff", cutoffMap(cutoff))); tuple .tenantBillingCutoff() - .ifPresent( - cutoffs -> { - Map encodedCutoffs = new LinkedHashMap<>(); - cutoffs.forEach( - (tenantId, cutoff) -> encodedCutoffs.put(tenantId, cutoffMap(cutoff))); - result.put("tenantBillingCutoff", encodedCutoffs); - }); + .ifPresent(cutoffs -> { + Map encodedCutoffs = new LinkedHashMap<>(); + cutoffs.forEach((tenantId, cutoff) -> encodedCutoffs.put(tenantId, cutoffMap(cutoff))); + result.put("tenantBillingCutoff", encodedCutoffs); + }); return result; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepository.java index 0dfc52f2c0..b4c082a68e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepository.java @@ -228,10 +228,9 @@ public RoleSnapshot replaceCanonical( RoleSnapshot readback = findForCanonicalUpdate( accountUuid, tenantUuid, expectedProvenance, membership.getId(), snapshotVersion) - .orElseThrow( - () -> - new IllegalStateException( - "Canonical role snapshot header is absent after its write")); + .orElseThrow(() -> + new IllegalStateException( + "Canonical role snapshot header is absent after its write")); requireSnapshotReadback(expected, Optional.of(readback)); return readback; } @@ -422,10 +421,8 @@ private void requireCanonicalIdentity( private void requireSnapshotReadback(RoleSnapshot expected, Optional readback) { RoleSnapshot actual = - readback.orElseThrow( - () -> - new IllegalStateException( - "Account role snapshot header is absent after its write")); + readback.orElseThrow(() -> + new IllegalStateException("Account role snapshot header is absent after its write")); if (!expected.equals(actual)) { throw new IllegalStateException( "Account role snapshot readback differs from its exact write"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/FreshTenantIdentityAssociationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/FreshTenantIdentityAssociationRepository.java index fb6159eec2..6aae8fc1fe 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/FreshTenantIdentityAssociationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/FreshTenantIdentityAssociationRepository.java @@ -77,10 +77,9 @@ public FreshTenantCreationEvidence importVerified(FreshTenantCreationEvidence ow FreshTenantCreationEvidence readback = read(ownerEvidence.canonicalTenantId()) - .orElseThrow( - () -> - new InvalidTenantIdentityEvidenceException( - "Fresh Account tenant identity import did not read back")); + .orElseThrow(() -> + new InvalidTenantIdentityEvidenceException( + "Fresh Account tenant identity import did not read back")); if (!ownerEvidence.equals(readback)) { throw new InvalidTenantIdentityEvidenceException( "Fresh Account tenant identity import conflicts with immutable stored evidence"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidenceRepository.java index 5aa35ca5b9..7a253b1b27 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/RetainedSubscriptionEvidenceRepository.java @@ -25,17 +25,16 @@ public List findHistoryByAccountId(Long accountId) return dsl.selectFrom(evidence) .where(evidence.ACCOUNT_ID.eq(accountId)) .orderBy(evidence.ID.asc()) - .fetch( - row -> - new RetainedSubscriptionEvidence( - row.get(evidence.ID), - row.get(evidence.ACCOUNT_ID), - row.get(evidence.PLAN_ID), - row.get(evidence.STATUS), - row.get(evidence.STARTED_AT), - row.get(evidence.ENDED_AT), - row.get(evidence.TENANT_ID), - row.get(evidence.ENTITLEMENT_VERSION), - row.get(evidence.TENANT_AUTHORITY_GENERATION))); + .fetch(row -> + new RetainedSubscriptionEvidence( + row.get(evidence.ID), + row.get(evidence.ACCOUNT_ID), + row.get(evidence.PLAN_ID), + row.get(evidence.STATUS), + row.get(evidence.STARTED_AT), + row.get(evidence.ENDED_AT), + row.get(evidence.TENANT_ID), + row.get(evidence.ENTITLEMENT_VERSION), + row.get(evidence.TENANT_AUTHORITY_GENERATION))); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java index adbf21c80f..805f7ff062 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java @@ -138,10 +138,9 @@ public LatestSourceSnapshot requireCurrentLatest(Account account, ScopeState cur PasswordResetReceipt receipt = passwordResetRepository .findByRequestId(verified.requestId()) - .orElseThrow( - () -> - new IllegalStateException( - "Latest Account password-reset event has no immutable operation receipt")); + .orElseThrow(() -> + new IllegalStateException( + "Latest Account password-reset event has no immutable operation receipt")); requirePasswordResetReceipt(account, receipt, latestEvent, verified, current); } else if (verified.securityState().isPresent()) { requireSecurityStateReceipt(account, latestEvent, verified, current, true); @@ -152,10 +151,9 @@ public LatestSourceSnapshot requireCurrentLatest(Account account, ScopeState cur LogoutAllReceipt receipt = logoutAllRepository .findByRequestId(requestId) - .orElseThrow( - () -> - new IllegalStateException( - "Latest Account logout-all event has no immutable operation receipt")); + .orElseThrow(() -> + new IllegalStateException( + "Latest Account logout-all event has no immutable operation receipt")); requireLogoutAllReceipt(account, receipt, latestEvent, verified, current); } return new LatestSourceSnapshot(latestEvent.outboxSequence(), Optional.of(latestEvent)); @@ -202,10 +200,9 @@ public RetainedEventEvidence requireRetainedEvent( PasswordResetReceipt receipt = passwordResetRepository .findByRequestId(verified.requestId()) - .orElseThrow( - () -> - new IllegalStateException( - "Selected Account password-reset event has no immutable operation receipt")); + .orElseThrow(() -> + new IllegalStateException( + "Selected Account password-reset event has no immutable operation receipt")); requirePasswordResetReceiptBinding(account, receipt, event, verified, current); return retainedEvidence( event, verified, receipt.issuanceFence(), receipt.issuanceFenceSourceVersion()); @@ -215,17 +212,15 @@ public RetainedEventEvidence requireRetainedEvent( var operation = securityStateRepository .findCommittedByRequestIdShared(UUID.fromString(verified.requestId())) - .orElseThrow( - () -> - new IllegalStateException( - "Selected Account security-state event has no immutable operation receipt")); + .orElseThrow(() -> + new IllegalStateException( + "Selected Account security-state event has no immutable operation receipt")); var receipt = operation .receipt() - .orElseThrow( - () -> - new IllegalStateException( - "Selected Account security-state operation is not COMMITTED")); + .orElseThrow(() -> + new IllegalStateException( + "Selected Account security-state operation is not COMMITTED")); requireSecurityStateReceipt(account, event, verified, current, false); return retainedEvidence( event, @@ -237,17 +232,15 @@ public RetainedEventEvidence requireRetainedEvent( var operation = securityStateRepository .findRestrictionByRequestIdShared(UUID.fromString(verified.requestId())) - .orElseThrow( - () -> - new IllegalStateException( - "Selected Account restriction event has no immutable operation receipt")); + .orElseThrow(() -> + new IllegalStateException( + "Selected Account restriction event has no immutable operation receipt")); var receipt = operation .receipt() - .orElseThrow( - () -> - new IllegalStateException( - "Selected Account restriction operation is not COMMITTED")); + .orElseThrow(() -> + new IllegalStateException( + "Selected Account restriction operation is not COMMITTED")); requireRestrictionReceipt(account, event, verified, current, false); return retainedEvidence( event, @@ -259,10 +252,9 @@ public RetainedEventEvidence requireRetainedEvent( LogoutAllReceipt receipt = logoutAllRepository .findByRequestId(requestId) - .orElseThrow( - () -> - new IllegalStateException( - "Selected Account logout-all event has no immutable operation receipt")); + .orElseThrow(() -> + new IllegalStateException( + "Selected Account logout-all event has no immutable operation receipt")); requireLogoutAllReceipt(account, receipt, event, verified, current); return retainedEvidence( event, verified, receipt.issuanceFence(), receipt.issuanceFenceSourceVersion()); @@ -296,16 +288,14 @@ private void requireSecurityStateReceipt( var operation = securityStateRepository .findCommittedByRequestIdShared(UUID.fromString(verified.requestId())) - .orElseThrow( - () -> - new IllegalStateException( - "Account security-state event has no immutable operation receipt")); + .orElseThrow(() -> + new IllegalStateException( + "Account security-state event has no immutable operation receipt")); var receipt = operation .receipt() - .orElseThrow( - () -> - new IllegalStateException("Account security-state operation is not COMMITTED")); + .orElseThrow(() -> + new IllegalStateException("Account security-state operation is not COMMITTED")); if (!operation.request().accountUuid().equals(account.getAccountUuid()) || operation.capture().accountId() != account.getId() || operation.capture().provenance() != account.getAccountUuidProvenance() @@ -331,10 +321,9 @@ private void requireRestrictionReceipt( var operation = securityStateRepository .findRestrictionByRequestIdShared(UUID.fromString(verified.requestId())) - .orElseThrow( - () -> - new IllegalStateException( - "Account restriction event has no immutable operation receipt")); + .orElseThrow(() -> + new IllegalStateException( + "Account restriction event has no immutable operation receipt")); var receipt = operation .receipt() diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReader.java index 104217fe25..ad78030f65 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReader.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceReader.java @@ -72,29 +72,26 @@ public AccountSourceEventReadback readCommittedEvent(UUID accountId, long outbox } requireNoAmbientTransaction(); return requireTransactionResult( - ownerTransaction.execute( - status -> { - Account account = loadLockedAccount(accountId); - AccountSourceSnapshot current = readCurrentSnapshot(account, accountId); - if (outboxSequence > current.outboxSequence()) { - throw new IllegalStateException( - "Selected Account source event is ahead of its current checkpoint"); - } - Event requested = - outboxRepository - .findEvent(current.outboxStreamKey(), outboxSequence) - .orElseThrow( - () -> - new IllegalStateException( - "Selected Account source event is missing")); - if (!current.outboxStreamKey().equals(requested.outboxStreamKey()) - || requested.outboxSequence() != outboxSequence) { - throw new IllegalStateException( - "Selected Account source event identity changed during readback"); - } - sourceEventReadback.requireRetainedEvent(account, requested, current.sourceState()); - return new AccountSourceEventReadback(current, requested); - })); + ownerTransaction.execute(status -> { + Account account = loadLockedAccount(accountId); + AccountSourceSnapshot current = readCurrentSnapshot(account, accountId); + if (outboxSequence > current.outboxSequence()) { + throw new IllegalStateException( + "Selected Account source event is ahead of its current checkpoint"); + } + Event requested = + outboxRepository + .findEvent(current.outboxStreamKey(), outboxSequence) + .orElseThrow( + () -> new IllegalStateException("Selected Account source event is missing")); + if (!current.outboxStreamKey().equals(requested.outboxStreamKey()) + || requested.outboxSequence() != outboxSequence) { + throw new IllegalStateException( + "Selected Account source event identity changed during readback"); + } + sourceEventReadback.requireRetainedEvent(account, requested, current.sourceState()); + return new AccountSourceEventReadback(current, requested); + })); } private AccountSourceSnapshot readCurrentSnapshot(Account account, UUID accountId) { @@ -212,10 +209,9 @@ public record AccountSourceSnapshot( || !outboxStreamKey.equals(latestEvent.orElseThrow().outboxStreamKey())))) { throw new IllegalArgumentException("Account source snapshot is inconsistent"); } - latestEvent.ifPresent( - event -> - AccountAuthoritySourceEventReadback.requireEventMatchesSnapshot( - event, accountId, sourceState, true)); + latestEvent.ifPresent(event -> + AccountAuthoritySourceEventReadback.requireEventMatchesSnapshot( + event, accountId, sourceState, true)); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningService.java index e92ba44e1a..58e1e9f88d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningService.java @@ -48,41 +48,37 @@ public Result provision(UUID accountUuid, UUID customerProvisioningRequestId) { } Prepared prepared = Objects.requireNonNull( - transaction.execute( - status -> { - AccountBillingCustomerRecord current = - lock(accountUuid, customerProvisioningRequestId); - if (current.state() == State.CONFIRMED) { - return new Prepared(current, null); - } - return new Prepared( - current, customers.claimFirstProviderDispatch(current, UUID.randomUUID())); - })); + transaction.execute(status -> { + AccountBillingCustomerRecord current = + lock(accountUuid, customerProvisioningRequestId); + if (current.state() == State.CONFIRMED) { + return new Prepared(current, null); + } + return new Prepared( + current, customers.claimFirstProviderDispatch(current, UUID.randomUUID())); + })); if (prepared.dispatch() == null) { return new RetainedCustomer(prepared.intent()); } // Independently verify the committed claim and original durable intent before any provider IO. AccountBillingCustomerRecord dispatchReadback = Objects.requireNonNull( - transaction.execute( - status -> { - AccountBillingCustomerRecord current = - lock(accountUuid, customerProvisioningRequestId); - DispatchClaim retained = - customers - .findDispatchClaim(accountUuid) - .orElseThrow( - () -> - new IllegalStateException( - "Committed dispatch claim disappeared")); - if (!retained.equals(prepared.dispatch().claim()) - || !current - .providerIdempotencyId() - .equals(prepared.intent().providerIdempotencyId())) { - throw new IllegalStateException("Committed customer dispatch binding changed"); - } - return current; - })); + transaction.execute(status -> { + AccountBillingCustomerRecord current = + lock(accountUuid, customerProvisioningRequestId); + DispatchClaim retained = + customers + .findDispatchClaim(accountUuid) + .orElseThrow( + () -> new IllegalStateException("Committed dispatch claim disappeared")); + if (!retained.equals(prepared.dispatch().claim()) + || !current + .providerIdempotencyId() + .equals(prepared.intent().providerIdempotencyId())) { + throw new IllegalStateException("Committed customer dispatch binding changed"); + } + return current; + })); if (dispatchReadback.state() == State.CONFIRMED) { return new RetainedCustomer(dispatchReadback); } @@ -102,80 +98,74 @@ public Result provision(UUID accountUuid, UUID customerProvisioningRequestId) { UUID observationRequestId = UUID.randomUUID(); CommitResult committed = Objects.requireNonNull( - transaction.execute( - status -> { - AccountBillingCustomerRecord current = - lock(accountUuid, customerProvisioningRequestId); - if (!confirmed.accountUuid().equals(current.accountUuid()) - || !confirmed - .customerProvisioningRequestId() - .equals(current.customerProvisioningRequestId()) - || !confirmed - .providerIdempotencyId() - .equals(current.providerIdempotencyId())) { - throw new IllegalStateException( - "Provider evidence changed immutable customer operation"); - } - if (current.state() == State.CONFIRMED) { - if (!confirmed.providerCustomerId().equals(current.providerCustomerId())) { - throw new IllegalStateException( - "Provider customer conflicts with retained confirmation"); - } - return new CommitResult(current, false); - } - if (current.rowVersion() != prepared.intent().rowVersion()) { - throw new AccountBillingCustomerRepository.StaleVersionException(); - } - AccountBillingCustomerRecord receipt = - customers.recordObservation( - accountUuid, - customerProvisioningRequestId, - current.rowVersion(), - observationRequestId, - Observation.CONFIRMED, - confirmed.providerCustomerId(), - confirmed.evidenceDigest()); - if (!receipt.changeRequestId().equals(observationRequestId) - || receipt.rowVersion() != current.rowVersion() + 1 - || !confirmed.evidenceDigest().equals(receipt.evidenceDigest())) { - throw new IllegalStateException( - "Customer confirmation receipt changed observation identity"); - } - return new CommitResult(receipt, true); - })); + transaction.execute(status -> { + AccountBillingCustomerRecord current = + lock(accountUuid, customerProvisioningRequestId); + if (!confirmed.accountUuid().equals(current.accountUuid()) + || !confirmed + .customerProvisioningRequestId() + .equals(current.customerProvisioningRequestId()) + || !confirmed.providerIdempotencyId().equals(current.providerIdempotencyId())) { + throw new IllegalStateException( + "Provider evidence changed immutable customer operation"); + } + if (current.state() == State.CONFIRMED) { + if (!confirmed.providerCustomerId().equals(current.providerCustomerId())) { + throw new IllegalStateException( + "Provider customer conflicts with retained confirmation"); + } + return new CommitResult(current, false); + } + if (current.rowVersion() != prepared.intent().rowVersion()) { + throw new AccountBillingCustomerRepository.StaleVersionException(); + } + AccountBillingCustomerRecord receipt = + customers.recordObservation( + accountUuid, + customerProvisioningRequestId, + current.rowVersion(), + observationRequestId, + Observation.CONFIRMED, + confirmed.providerCustomerId(), + confirmed.evidenceDigest()); + if (!receipt.changeRequestId().equals(observationRequestId) + || receipt.rowVersion() != current.rowVersion() + 1 + || !confirmed.evidenceDigest().equals(receipt.evidenceDigest())) { + throw new IllegalStateException( + "Customer confirmation receipt changed observation identity"); + } + return new CommitResult(receipt, true); + })); // The write transaction has actually committed. Read the exact immutable observation and // current owner afresh; its in-transaction return value alone is not durable readback proof. AccountBillingCustomerRecord retained = Objects.requireNonNull( - transaction.execute( - status -> { - AccountBillingCustomerRecord current = - lock(accountUuid, customerProvisioningRequestId); - AccountBillingCustomerRecord receipt = - customers - .findObservationByRequestId(committed.receipt().changeRequestId()) - .orElseThrow( - () -> - new IllegalStateException( - "Committed customer observation disappeared")); - if (!receipt.equals(committed.receipt()) - || !current.equals(receipt) - || receipt.state() != State.CONFIRMED - || receipt.observation() != Observation.CONFIRMED - || !confirmed.providerCustomerId().equals(receipt.providerCustomerId()) - || !confirmed.accountUuid().equals(receipt.accountUuid()) - || !confirmed - .customerProvisioningRequestId() - .equals(receipt.customerProvisioningRequestId()) - || !confirmed.providerIdempotencyId().equals(receipt.providerIdempotencyId()) - || (committed.newlyRecorded() - && (!observationRequestId.equals(receipt.changeRequestId()) - || !confirmed.evidenceDigest().equals(receipt.evidenceDigest())))) { - throw new IllegalStateException( - "Committed customer confirmation readback mismatch"); - } - return receipt; - })); + transaction.execute(status -> { + AccountBillingCustomerRecord current = + lock(accountUuid, customerProvisioningRequestId); + AccountBillingCustomerRecord receipt = + customers + .findObservationByRequestId(committed.receipt().changeRequestId()) + .orElseThrow(() -> + new IllegalStateException("Committed customer observation disappeared")); + if (!receipt.equals(committed.receipt()) + || !current.equals(receipt) + || receipt.state() != State.CONFIRMED + || receipt.observation() != Observation.CONFIRMED + || !confirmed.providerCustomerId().equals(receipt.providerCustomerId()) + || !confirmed.accountUuid().equals(receipt.accountUuid()) + || !confirmed + .customerProvisioningRequestId() + .equals(receipt.customerProvisioningRequestId()) + || !confirmed.providerIdempotencyId().equals(receipt.providerIdempotencyId()) + || (committed.newlyRecorded() + && (!observationRequestId.equals(receipt.changeRequestId()) + || !confirmed.evidenceDigest().equals(receipt.evidenceDigest())))) { + throw new IllegalStateException( + "Committed customer confirmation readback mismatch"); + } + return receipt; + })); // A simultaneous confirmation keeps its own original observation identity and digest. It is // historical replay, not a new observation under this invocation's unused request identity. if (!committed.newlyRecorded()) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java index 283d449115..e68474e029 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java @@ -360,17 +360,15 @@ private CanonicalJoinTerminalProof commitCanonicalFirstJoin( Account account = accountRepository .findByAccountUuid(scope.accountId()) - .orElseThrow( - () -> - new CanonicalJoinOperationConflictException("Canonical JOIN intent conflicts")); + .orElseThrow(() -> + new CanonicalJoinOperationConflictException("Canonical JOIN intent conflicts")); requireAccountIdentity(account, scope.accountId()); joinOperationRepository.lockAccount(account.getId()); CanonicalJoinOperationEvidence operation = joinOperationRepository .findCanonicalEvidenceForUpdateByRequestId(requestId) - .orElseThrow( - () -> - new CanonicalJoinOperationConflictException("Canonical JOIN intent conflicts")); + .orElseThrow(() -> + new CanonicalJoinOperationConflictException("Canonical JOIN intent conflicts")); requireExactOperation(operation, account.getId(), scope, requestId, verifiedCallerBinding); if (!Boolean.TRUE.equals(operation.allowPublicJoin())) { throw new CanonicalJoinOperationConflictException( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java index 8125edd084..06219ae3f5 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwner.java @@ -185,26 +185,24 @@ private Caller verifyDirectCaller( throw new AuthenticationException( "CONNECT_CONTEXT_INVALID", "Direct caller expired or malformed"); } - return inTransaction( - () -> { - requireDirectPeer(); - Account account = - accounts - .findByAccountUuidForUpdate(context.accountId()) - .orElseThrow( - () -> - new AuthenticationException( - "CONNECT_CONTEXT_INVALID", "Direct caller Account is unknown")); - if (account.getId() == null - || account.getId() <= 0L - || !context.accountId().equals(account.getAccountUuid()) - || !Objects.equals(account.getId(), account.getAccountUuidSourceNumericId()) - || !AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()) - || account.getLifecycleState() != AccountLifecycleState.ACTIVE) { - throw authUnavailable("Direct Account owner is unavailable or ineligible", null); - } - return new Caller(account.getId(), account.getAccountUuid(), issuedAt, deadline); - }); + return inTransaction(() -> { + requireDirectPeer(); + Account account = + accounts + .findByAccountUuidForUpdate(context.accountId()) + .orElseThrow(() -> + new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "Direct caller Account is unknown")); + if (account.getId() == null + || account.getId() <= 0L + || !context.accountId().equals(account.getAccountUuid()) + || !Objects.equals(account.getId(), account.getAccountUuidSourceNumericId()) + || !AccountIdentityProvenance.isAccepted(account.getAccountUuidProvenance()) + || account.getLifecycleState() != AccountLifecycleState.ACTIVE) { + throw authUnavailable("Direct Account owner is unavailable or ineligible", null); + } + return new Caller(account.getId(), account.getAccountUuid(), issuedAt, deadline); + }); } private void requireDirectPeer() { @@ -266,48 +264,45 @@ private List listRealmScopes( requireSameCaller(original, authenticate.get()); requireFresh(entitlement); RealmScope retained = - inTransaction( - () -> { - Prepared current = readSources(original, target, entitlement); - if (!prepared.tenant().equals(current.tenant()) - || !prepared.membership().equals(current.membership())) { - throw authUnavailable("Account discovery sources changed", null); - } - if (prepared.head().kind() != current.head().kind() - || !prepared.head().matches(current.head().checkpoint())) { - throw entitlementUnavailable(null); - } - requireFresh(entitlement); - Instant evaluatedAt = now(); - Instant expiresAt = evaluatedAt.plusMillis(scopeLifetimeMillis); - if (original.expiresAt().isBefore(expiresAt)) expiresAt = original.expiresAt(); - // JWT NumericDate has second precision. The persisted preimage uses that exact - // expiry. - expiresAt = expiresAt.truncatedTo(ChronoUnit.SECONDS); - if (!evaluatedAt.isBefore(expiresAt)) { - throw new AuthenticationException( - "CONNECT_CONTEXT_INVALID", "Bootstrap credential expired"); - } - CanonicalJoinScopeV2 scope = mintScope(original, target, evaluatedAt, expiresAt); - VerifiedTenantProvenance provenance = - new VerifiedTenantProvenance( - null, - TenantProvenanceKind.FRESH_GAME_DESIGN, - current.tenant().operationId(), - current.tenant().evidenceDigest()); - scopes.insertCanonical(original.accountId(), scope, provenance); - if (!scope.equals(scopes.findCanonical(scope.connectScopeId()).orElse(null))) { - throw authUnavailable("Canonical scope readback differs", null); - } - CanonicalConnectScopeEvidence expected = evidence(original, scope, provenance); - if (!expected.equals( - scopes - .findCanonicalEvidenceByTokenHash(expected.scopeTokenHash()) - .orElse(null))) { - throw authUnavailable("Canonical scope evidence readback differs", null); - } - return new RealmScope(target, scope, current.membership(), entitlement); - }); + inTransaction(() -> { + Prepared current = readSources(original, target, entitlement); + if (!prepared.tenant().equals(current.tenant()) + || !prepared.membership().equals(current.membership())) { + throw authUnavailable("Account discovery sources changed", null); + } + if (prepared.head().kind() != current.head().kind() + || !prepared.head().matches(current.head().checkpoint())) { + throw entitlementUnavailable(null); + } + requireFresh(entitlement); + Instant evaluatedAt = now(); + Instant expiresAt = evaluatedAt.plusMillis(scopeLifetimeMillis); + if (original.expiresAt().isBefore(expiresAt)) expiresAt = original.expiresAt(); + // JWT NumericDate has second precision. The persisted preimage uses that exact + // expiry. + expiresAt = expiresAt.truncatedTo(ChronoUnit.SECONDS); + if (!evaluatedAt.isBefore(expiresAt)) { + throw new AuthenticationException( + "CONNECT_CONTEXT_INVALID", "Bootstrap credential expired"); + } + CanonicalJoinScopeV2 scope = mintScope(original, target, evaluatedAt, expiresAt); + VerifiedTenantProvenance provenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + current.tenant().operationId(), + current.tenant().evidenceDigest()); + scopes.insertCanonical(original.accountId(), scope, provenance); + if (!scope.equals(scopes.findCanonical(scope.connectScopeId()).orElse(null))) { + throw authUnavailable("Canonical scope readback differs", null); + } + CanonicalConnectScopeEvidence expected = evidence(original, scope, provenance); + if (!expected.equals( + scopes.findCanonicalEvidenceByTokenHash(expected.scopeTokenHash()).orElse(null))) { + throw authUnavailable("Canonical scope evidence readback differs", null); + } + return new RealmScope(target, scope, current.membership(), entitlement); + }); // No value escapes a failed commit or a caller/source observation that expired during commit. requireSameCaller(original, authenticate.get()); requireFresh(entitlement); @@ -374,10 +369,9 @@ private Optional select( List complete, String tenantSlug, String worldSlug, boolean tenantQualified) { List matches = complete.stream() - .filter( - target -> - worldSlug.equals(target.worldSlug()) - && (!tenantQualified || tenantSlug.equals(target.tenantSlug()))) + .filter(target -> + worldSlug.equals(target.worldSlug()) + && (!tenantQualified || tenantSlug.equals(target.tenantSlug()))) .toList(); if (matches.size() > 1) throw pointerUnavailable(null); for (Target target : matches) { @@ -459,32 +453,31 @@ private Prepared readSources(Caller caller, Target target, Evaluation entitlemen Optional member = memberships.findFreshMembershipForUpdate(caller.accountUuid(), target.canonicalTenantId()); Optional current = - member.map( - value -> { - if (value.getId() == null - || value.getId() <= 0L - || value.getAccount() == null - || !Objects.equals(account.getId(), value.getAccount().getId()) - || !account.getAccountUuid().equals(value.getAccount().getAccountUuid()) - || value.getTenantId() != null - || !target.canonicalTenantId().equals(value.getTenantUuid()) - || !TenantProvenanceKind.FRESH_GAME_DESIGN - .name() - .equals(value.getTenantProvenanceKind()) - || !tenant.operationId().equals(value.getTenantSourceOperationId()) - || !tenant.evidenceDigest().equals(value.getTenantProvenanceDigest()) - || value.getMembershipVersion() <= 0L - || value.getMembershipAuthorityGeneration() <= 0L - || !List.of("ACTIVE", "INACTIVE").contains(value.getLifecycleState())) { - throw authUnavailable("Canonical membership evidence is malformed", null); - } - return new ExistingMembership( - value.getId(), - value.getLifecycleState(), - value.isGameplayAdmissionAllowed(), - value.getMembershipVersion(), - value.getMembershipAuthorityGeneration()); - }); + member.map(value -> { + if (value.getId() == null + || value.getId() <= 0L + || value.getAccount() == null + || !Objects.equals(account.getId(), value.getAccount().getId()) + || !account.getAccountUuid().equals(value.getAccount().getAccountUuid()) + || value.getTenantId() != null + || !target.canonicalTenantId().equals(value.getTenantUuid()) + || !TenantProvenanceKind.FRESH_GAME_DESIGN + .name() + .equals(value.getTenantProvenanceKind()) + || !tenant.operationId().equals(value.getTenantSourceOperationId()) + || !tenant.evidenceDigest().equals(value.getTenantProvenanceDigest()) + || value.getMembershipVersion() <= 0L + || value.getMembershipAuthorityGeneration() <= 0L + || !List.of("ACTIVE", "INACTIVE").contains(value.getLifecycleState())) { + throw authUnavailable("Canonical membership evidence is malformed", null); + } + return new ExistingMembership( + value.getId(), + value.getLifecycleState(), + value.isGameplayAdmissionAllowed(), + value.getMembershipVersion(), + value.getMembershipAuthorityGeneration()); + }); return new Prepared( tenant, new MembershipFacts(account.getAccountUuid(), target.canonicalTenantId(), current), @@ -583,14 +576,13 @@ private T inTransaction(java.util.function.Supplier action) { requireSourceContext(); try { return Objects.requireNonNull( - transaction.execute( - status -> { - if (!TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { - throw authUnavailable("Writable Account source transaction required", null); - } - return action.get(); - })); + transaction.execute(status -> { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw authUnavailable("Writable Account source transaction required", null); + } + return action.get(); + })); } catch (AuthenticationException failure) { throw failure; } catch (RuntimeException failure) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReader.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReader.java index 12f020dfb5..2eb2020bf4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReader.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReader.java @@ -401,10 +401,9 @@ private CurrentSourceEvidence readCurrentUpstreamSourceEvidence( source .account() .accountSecurityCutoff() - .map( - c -> - new MembershipAuthorityEventV1Codec.AccountSecurityCutoff( - c.accountAuthorityGeneration(), c.outboxStreamKey(), c.outboxSequence()))); + .map(c -> + new MembershipAuthorityEventV1Codec.AccountSecurityCutoff( + c.accountAuthorityGeneration(), c.outboxStreamKey(), c.outboxSequence()))); } private CompositeSnapshot readSnapshot(UUID accountUuid, UUID tenantUuid) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java index 37d8f30220..c0105015d6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleService.java @@ -56,14 +56,13 @@ public TransitionResult reconcile( requireNoAmbientTransaction(); var prepared = Objects.requireNonNull( - transaction.execute( - s -> - repository.prepare( - requestId, - creationRequestId, - expectedRowVersion, - providerSubscriptionId, - provisioningAttemptId))); + transaction.execute(s -> + repository.prepare( + requestId, + creationRequestId, + expectedRowVersion, + providerSubscriptionId, + provisioningAttemptId))); if (prepared.outcome() != Outcome.READY) { return prepared.result(); } @@ -96,10 +95,9 @@ public T readCurrentAndCapture( requireNoAmbientTransaction(); var actualSdkResult = observer.observe(fence.binding()); return Objects.requireNonNull( - transaction.execute( - s -> - Objects.requireNonNull( - capture.apply(repository.readCurrent(fence, actualSdkResult))))); + transaction.execute(s -> + Objects.requireNonNull( + capture.apply(repository.readCurrent(fence, actualSdkResult))))); } catch (RuntimeException unavailable) { throw new EntitlementUnavailableException(unavailable); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducer.java index 5cff40cfcb..8f76bae0de 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducer.java @@ -109,26 +109,22 @@ public LogoutAllResult commit( requireNoAmbientTransaction(); CommitAttempt transactionResult = - ownerTransaction.execute( - status -> - commitInOwnerTransaction( - requestId, - requestDigestVersion, - requestDigest, - tokenProfile, - presentedTokenHash, - verifiedAccountAssociation, - expectedAccountState)); + ownerTransaction.execute(status -> + commitInOwnerTransaction( + requestId, + requestDigestVersion, + requestDigest, + tokenProfile, + presentedTokenHash, + verifiedAccountAssociation, + expectedAccountState)); if (transactionResult == null) { throw new IllegalStateException("Logout-all source transaction returned no result"); } if (transactionResult.pendingChange() != null) { - ownerTransaction.executeWithoutResult( - status -> - draftSourceChanges.verifyWaiting( - requestId, - transactionResult.requestPayload(), - transactionResult.pendingChange())); + ownerTransaction.executeWithoutResult(status -> + draftSourceChanges.verifyWaiting( + requestId, transactionResult.requestPayload(), transactionResult.pendingChange())); throw new AccountLogoutAllDraftSourceChangeRepository.PendingSourceChangeException( transactionResult.pendingChange().changeId()); } @@ -373,42 +369,39 @@ private LogoutAllReceipt readCommittedOperation( Account requestedAccount) { requireNoAmbientTransaction(); LogoutAllReceipt receipt = - ownerTransaction.execute( - status -> { - Account account = lockVerifiedAccount(requestedAccount); - LogoutAllReceipt committed = - operationRepository - .findByRequestId(requestId) - .orElseThrow( - () -> - new IllegalStateException( - "Post-commit logout-all request receipt is missing")); - requireExactRetryBinding( - committed, + ownerTransaction.execute(status -> { + Account account = lockVerifiedAccount(requestedAccount); + LogoutAllReceipt committed = + operationRepository + .findByRequestId(requestId) + .orElseThrow(() -> + new IllegalStateException( + "Post-commit logout-all request receipt is missing")); + requireExactRetryBinding( + committed, + requestId, + requestDigestVersion, + requestDigest, + tokenProfile, + presentedTokenHash, + account); + Event event = + outboxRepository + .findEvent(committed.outboxStreamKey(), committed.outboxSequence()) + .orElseThrow( + () -> new IllegalStateException("Logout-all historical event is missing")); + draftSourceChanges.verifyCommittedIfPresent( + requestId, + draftSourceChanges.requestBinding( requestId, requestDigestVersion, requestDigest, tokenProfile, presentedTokenHash, - account); - Event event = - outboxRepository - .findEvent(committed.outboxStreamKey(), committed.outboxSequence()) - .orElseThrow( - () -> - new IllegalStateException("Logout-all historical event is missing")); - draftSourceChanges.verifyCommittedIfPresent( - requestId, - draftSourceChanges.requestBinding( - requestId, - requestDigestVersion, - requestDigest, - tokenProfile, - presentedTokenHash, - account), - event); - return recoverReceipt(account, committed); - }); + account), + event); + return recoverReceipt(account, committed); + }); if (receipt == null) { throw new IllegalStateException("Post-commit logout-all receipt readback returned no result"); } @@ -484,10 +477,9 @@ private Account lockVerifiedAccount(Account requestedAccount) { Account locked = accountRepository .findByIdForUpdate(requestedAccount.getId()) - .orElseThrow( - () -> - new OperationConflictException( - "Logout-all Account identity binding is absent from persisted Account state")); + .orElseThrow(() -> + new OperationConflictException( + "Logout-all Account identity binding is absent from persisted Account state")); if (!Objects.equals(requestedAccount.getId(), locked.getId()) || !Objects.equals(requestedAccount.getAccountUuid(), locked.getAccountUuid()) || !Objects.equals( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllDraftSourceChangeRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllDraftSourceChangeRepository.java index 51dd3d7728..930cd7cdf0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllDraftSourceChangeRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountLogoutAllDraftSourceChangeRepository.java @@ -323,16 +323,15 @@ private static byte[] captureEvidence( return latest .latestEvent() .map(Event::payload) - .orElseGet( - () -> - framed( - List.of( - "account-draft-source-baseline/v1", - account.getAccountUuid().toString(), - Long.toString(current.generation()), - Long.toString(current.sourceVersion()), - stream, - "0"))); + .orElseGet(() -> + framed( + List.of( + "account-draft-source-baseline/v1", + account.getAccountUuid().toString(), + Long.toString(current.generation()), + Long.toString(current.sourceVersion()), + stream, + "0"))); } private static byte[] requestBytes( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java index 0df534e287..89b9041100 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java @@ -395,10 +395,9 @@ private Checkpoint publishCanonicalFirstJoinMembershipChange( PairAuthority pair = pairAuthorityRepository .readForUpdate(accountUuid, tenantUuid) - .orElseThrow( - () -> - new IllegalStateException( - "Canonical first JOIN has no committed never-joined pair baseline")); + .orElseThrow(() -> + new IllegalStateException( + "Canonical first JOIN has no committed never-joined pair baseline")); requireExactPairScope(pair, accountUuid, tenantUuid, provenance); String streamKey = membershipStreamKey(accountUuid, tenantUuid); @@ -518,9 +517,8 @@ private Checkpoint appendFirstJoinEvent( Event bySequence = authorityOutboxRepository .findEvent(streamKey, 1L) - .orElseThrow( - () -> - new IllegalStateException("Canonical first-JOIN sequence-one event is absent")); + .orElseThrow(() -> + new IllegalStateException("Canonical first-JOIN sequence-one event is absent")); if (!appended.equals(byRequest) || !appended.equals(bySequence)) { throw new IllegalStateException("Canonical first-JOIN event readback differs from append"); } @@ -564,9 +562,8 @@ private Checkpoint readExactCommittedFirstJoin( Event bySequence = authorityOutboxRepository .findEvent(streamKey, 1L) - .orElseThrow( - () -> - new IllegalStateException("Committed first-JOIN sequence-one event is absent")); + .orElseThrow(() -> + new IllegalStateException("Committed first-JOIN sequence-one event is absent")); if (!byRequest.equals(bySequence)) { throw new IllegalStateException("Committed first-JOIN event identity is contradictory"); } @@ -616,14 +613,13 @@ private static Map membershipEventPreimage( sourceSnapshot .account() .accountSecurityCutoff() - .ifPresent( - cutoff -> - authorityTuple.put( - "accountSecurityCutoff", - Map.of( - "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), - "outboxStreamKey", cutoff.outboxStreamKey(), - "outboxSequence", cutoff.outboxSequence()))); + .ifPresent(cutoff -> + authorityTuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence()))); authorityTuple.put( "tenantBillingCutoff", Map.of( @@ -1392,20 +1388,18 @@ static Snapshot validatorSnapshot( authorityTuple, issuanceFence, checkpoints.stream() - .map( - checkpoint -> - new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( - checkpoint.outboxStreamKey(), checkpoint.outboxSequence())) + .map(checkpoint -> + new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( + checkpoint.outboxStreamKey(), checkpoint.outboxSequence())) .toList(), sourceEvidence.stream() - .map( - source -> - new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( - source.outboxStreamKey(), - source.outboxSequence(), - source.eventId(), - source.eventDigest(), - source.canonicalEventJson())) + .map(source -> + new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + source.outboxStreamKey(), + source.outboxSequence(), + source.eventId(), + source.eventDigest(), + source.canonicalEventJson())) .toList()); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentService.java index bf73fe09b4..dc5b0555f7 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentService.java @@ -69,22 +69,21 @@ public Result retainSavedMethod(Request request) { } Prepared prepared = Objects.requireNonNull( - transaction.execute( - status -> { - AccountBillingCustomerRecord customer = lockCustomer(request.accountUuid()); - AccountPaymentInstrumentRecord currentInstrument = - instruments - .findByOwnerForUpdate(request.accountUuid(), request.instrumentUuid()) - .orElse(null); - AccountPaymentInstrumentRecord receipt = - instruments.findAttachmentByRequestId(request.requestId()).orElse(null); - if (receipt != null) { - requireReceiptBinding(receipt, request, customer); - } else { - requireInstrumentAvailable(currentInstrument, request); - } - return new Prepared(customer, receipt); - })); + transaction.execute(status -> { + AccountBillingCustomerRecord customer = lockCustomer(request.accountUuid()); + AccountPaymentInstrumentRecord currentInstrument = + instruments + .findByOwnerForUpdate(request.accountUuid(), request.instrumentUuid()) + .orElse(null); + AccountPaymentInstrumentRecord receipt = + instruments.findAttachmentByRequestId(request.requestId()).orElse(null); + if (receipt != null) { + requireReceiptBinding(receipt, request, customer); + } else { + requireInstrumentAvailable(currentInstrument, request); + } + return new Prepared(customer, receipt); + })); if (prepared.receipt() != null) { RetainedBinding retained = readCommitted(request, prepared.customer(), prepared.receipt()); return new HistoricalAttachment(retained.receipt(), retained.current()); @@ -104,57 +103,56 @@ public Result retainSavedMethod(Request request) { } CommitResult committed = Objects.requireNonNull( - transaction.execute( - status -> { - AccountBillingCustomerRecord current = lockCustomer(request.accountUuid()); - if (!current.equals(prepared.customer())) { - throw new IllegalStateException( - "Confirmed customer changed during provider observation"); - } - AccountPaymentInstrumentRecord currentInstrument = - instruments - .findByOwnerForUpdate(request.accountUuid(), request.instrumentUuid()) - .orElse(null); - AccountPaymentInstrumentRecord original = - instruments.findAttachmentByRequestId(request.requestId()).orElse(null); - if (original != null) { - requireReceiptBinding(original, request, current); - return new CommitResult(original, false); - } - requireInstrumentAvailable(currentInstrument, request); - requireFresh(observed); - if (!current.accountUuid().equals(observed.accountUuid()) - || !current - .customerProvisioningRequestId() - .equals(observed.customerProvisioningRequestId()) - || !current.providerCustomerId().equals(observed.providerCustomerId()) - || !request - .providerPaymentMethodId() - .equals(observed.providerPaymentMethodId())) { - throw new IllegalStateException( - "Provider observation changed the selected owner/customer/method"); - } - AccountPaymentInstrumentRecord receipt = - instruments.retainAttachment( - new Attachment( - request.requestId(), - request.instrumentUuid(), - observed.accountUuid(), - observed.customerProvisioningRequestId(), - observed.providerCustomerId(), - observed.providerPaymentMethodId(), - AccountPaymentInstrumentRecord.State.ATTACHABLE, - observed.display(), - observed.evidenceDigest())); - requireReceiptBinding(receipt, request, current); - if (receipt.state() != AccountPaymentInstrumentRecord.State.ATTACHABLE - || !receipt.display().equals(observed.display()) - || !receipt.evidenceDigest().equals(observed.evidenceDigest())) { - throw new IllegalStateException( - "Retained attachment differs from independently observed facts"); - } - return new CommitResult(receipt, true); - })); + transaction.execute(status -> { + AccountBillingCustomerRecord current = lockCustomer(request.accountUuid()); + if (!current.equals(prepared.customer())) { + throw new IllegalStateException( + "Confirmed customer changed during provider observation"); + } + AccountPaymentInstrumentRecord currentInstrument = + instruments + .findByOwnerForUpdate(request.accountUuid(), request.instrumentUuid()) + .orElse(null); + AccountPaymentInstrumentRecord original = + instruments.findAttachmentByRequestId(request.requestId()).orElse(null); + if (original != null) { + requireReceiptBinding(original, request, current); + return new CommitResult(original, false); + } + requireInstrumentAvailable(currentInstrument, request); + requireFresh(observed); + if (!current.accountUuid().equals(observed.accountUuid()) + || !current + .customerProvisioningRequestId() + .equals(observed.customerProvisioningRequestId()) + || !current.providerCustomerId().equals(observed.providerCustomerId()) + || !request + .providerPaymentMethodId() + .equals(observed.providerPaymentMethodId())) { + throw new IllegalStateException( + "Provider observation changed the selected owner/customer/method"); + } + AccountPaymentInstrumentRecord receipt = + instruments.retainAttachment( + new Attachment( + request.requestId(), + request.instrumentUuid(), + observed.accountUuid(), + observed.customerProvisioningRequestId(), + observed.providerCustomerId(), + observed.providerPaymentMethodId(), + AccountPaymentInstrumentRecord.State.ATTACHABLE, + observed.display(), + observed.evidenceDigest())); + requireReceiptBinding(receipt, request, current); + if (receipt.state() != AccountPaymentInstrumentRecord.State.ATTACHABLE + || !receipt.display().equals(observed.display()) + || !receipt.evidenceDigest().equals(observed.evidenceDigest())) { + throw new IllegalStateException( + "Retained attachment differs from independently observed facts"); + } + return new CommitResult(receipt, true); + })); RetainedBinding retained = readCommitted(request, prepared.customer(), committed.receipt()); if (!committed.newlyRecorded()) { return new HistoricalAttachment(retained.receipt(), retained.current()); @@ -167,43 +165,39 @@ private RetainedBinding readCommitted( AccountBillingCustomerRecord expected, AccountPaymentInstrumentRecord committed) { return Objects.requireNonNull( - transaction.execute( - status -> { - AccountBillingCustomerRecord customer = lockCustomer(request.accountUuid()); - if (!customer.equals(expected)) { - throw new IllegalStateException("Committed attachment customer readback changed"); - } - AccountPaymentInstrumentRecord current = - instruments - .findByOwnerForUpdate(request.accountUuid(), request.instrumentUuid()) - .orElseThrow( - () -> new IllegalStateException("Committed instrument disappeared")); - AccountPaymentInstrumentRecord receipt = - instruments - .findAttachmentByRequestId(request.requestId()) - .orElseThrow( - () -> - new IllegalStateException( - "Committed attachment receipt disappeared")); - requireReceiptBinding(receipt, request, customer); - if (!receipt.equals(committed) - || !current.instrumentUuid().equals(receipt.instrumentUuid()) - || !current.accountUuid().equals(receipt.accountUuid()) - || !current - .customerProvisioningRequestId() - .equals(receipt.customerProvisioningRequestId()) - || !current.providerCustomerId().equals(receipt.providerCustomerId()) - || !current.providerPaymentMethodId().equals(receipt.providerPaymentMethodId()) - || !current.attachmentRequestId().equals(receipt.attachmentRequestId()) - || current.rowVersion() < receipt.rowVersion() - || (current.rowVersion() == receipt.rowVersion() && !current.equals(receipt))) { - throw new IllegalStateException( - "Committed historical receipt/current binding readback mismatch"); - } - // Later availability versions are preserved; replay cannot restore the original - // state. - return new RetainedBinding(receipt, current); - })); + transaction.execute(status -> { + AccountBillingCustomerRecord customer = lockCustomer(request.accountUuid()); + if (!customer.equals(expected)) { + throw new IllegalStateException("Committed attachment customer readback changed"); + } + AccountPaymentInstrumentRecord current = + instruments + .findByOwnerForUpdate(request.accountUuid(), request.instrumentUuid()) + .orElseThrow(() -> new IllegalStateException("Committed instrument disappeared")); + AccountPaymentInstrumentRecord receipt = + instruments + .findAttachmentByRequestId(request.requestId()) + .orElseThrow( + () -> new IllegalStateException("Committed attachment receipt disappeared")); + requireReceiptBinding(receipt, request, customer); + if (!receipt.equals(committed) + || !current.instrumentUuid().equals(receipt.instrumentUuid()) + || !current.accountUuid().equals(receipt.accountUuid()) + || !current + .customerProvisioningRequestId() + .equals(receipt.customerProvisioningRequestId()) + || !current.providerCustomerId().equals(receipt.providerCustomerId()) + || !current.providerPaymentMethodId().equals(receipt.providerPaymentMethodId()) + || !current.attachmentRequestId().equals(receipt.attachmentRequestId()) + || current.rowVersion() < receipt.rowVersion() + || (current.rowVersion() == receipt.rowVersion() && !current.equals(receipt))) { + throw new IllegalStateException( + "Committed historical receipt/current binding readback mismatch"); + } + // Later availability versions are preserved; replay cannot restore the original + // state. + return new RetainedBinding(receipt, current); + })); } private AccountBillingCustomerRecord lockCustomer(UUID accountUuid) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java index e918d69b5e..3f8921fc89 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java @@ -128,11 +128,10 @@ public RuntimePlayerAdmissionEntitlementEvidence evaluate( Request request, String presentedInitialLoginJwt) { VerifiedCaller caller = verifyCaller(request, presentedInitialLoginJwt); Prepared prepared = - inSourceTransaction( - () -> { - CurrentPlayer player = readCurrentPlayer(request, caller); - return new Prepared(player, sources.readCurrentSourceSelection(request.tenantId())); - }); + inSourceTransaction(() -> { + CurrentPlayer player = readCurrentPlayer(request, caller); + return new Prepared(player, sources.readCurrentSourceSelection(request.tenantId())); + }); requireCurrentTimes(prepared.player(), now()); RuntimePlayerAdmissionEntitlementEvidence evidence = switch (prepared.selection().kind()) { @@ -151,132 +150,129 @@ public RuntimePlayerAdmissionEntitlementEvidence evaluate( private RuntimePlayerAdmissionEntitlementEvidence capturePaidSources( Request request, VerifiedCaller caller, Prepared prepared) { var fence = - inSourceTransaction( - () -> { - try { - return hosting.prepareCurrentRead(request.tenantId()); - } catch (FenceRejectedException rejected) { - throw unavailable(); - } - }); - requireNoAmbientTransaction(); - var observation = observer.observe(fence.binding()); - PublishedRealmEvidence target = readProtectedTarget(request, prepared.player().scope()); - return inSourceTransaction( - () -> { - CurrentPlayer player = readCurrentPlayer(request, caller); - if (!prepared.player().scope().equals(player.scope())) throw unavailable(); - requireSameHead(request, prepared.selection()); - final AccountHostingSubscriptionCurrentReceipt receipt; + inSourceTransaction(() -> { try { - receipt = hosting.readCurrent(fence, observation); + return hosting.prepareCurrentRead(request.tenantId()); } catch (FenceRejectedException rejected) { throw unavailable(); } - Instant evaluatedAt = now(); - requireFreshReceipt(request, receipt, evaluatedAt); - var event = receipt.tenantAuthorityEvent(); - if (!prepared.selection().matches(event)) throw unavailable(); - requireTenantSource( - player.snapshot(), - event.tenantId(), - event.tenantAuthorityGeneration(), - receipt.tenantBillingSequence(), - event.outboxStreamKey(), - event.outboxSequence(), - event.eventId(), - event.eventDigest()); - if (!receipt.billingEventId().equals(event.tenantBillingEventId()) - || !receipt.billingEventDigest().equals(event.tenantBillingEventDigest()) - || receipt.tenantBillingSequence() != event.tenantBillingSequence()) { - throw unavailable(); - } - requireCurrentTimes(player, evaluatedAt); - var quote = receipt.current().planQuote(); - return capture( - request, - player, - target, - facts( - "PAID_HOSTING", - receipt.subscriptionStatus().storageValue(), - receipt.gameplayAvailable(), - receipt.allowPublicJoin(), - receipt.allowNewGameplayBindings(), - receipt.allowNewInstanceStarts(), - quote.maxActiveSessions(), - quote.maxConcurrentGameInstances(), - quote.maxStorageBytes(), - receipt.entitlementVersion(), - receipt.tenantBillingSequence(), - event.tenantAuthorityGeneration()), - RuntimePlayerAdmissionEntitlementEvidence.digest( - Map.of( - "receiptRequestId", receipt.receiptRequestId().toString(), - "subscriptionId", receipt.current().subscriptionId().toString(), - "subscriptionRowVersion", Long.toString(receipt.current().rowVersion()), - "billingEventId", receipt.billingEventId().toString(), - "billingEventDigest", receipt.billingEventDigest(), - "tenantAuthorityEventDigest", event.eventDigest())), - evaluatedAt, - receipt.validUntil()); }); + requireNoAmbientTransaction(); + var observation = observer.observe(fence.binding()); + PublishedRealmEvidence target = readProtectedTarget(request, prepared.player().scope()); + return inSourceTransaction(() -> { + CurrentPlayer player = readCurrentPlayer(request, caller); + if (!prepared.player().scope().equals(player.scope())) throw unavailable(); + requireSameHead(request, prepared.selection()); + final AccountHostingSubscriptionCurrentReceipt receipt; + try { + receipt = hosting.readCurrent(fence, observation); + } catch (FenceRejectedException rejected) { + throw unavailable(); + } + Instant evaluatedAt = now(); + requireFreshReceipt(request, receipt, evaluatedAt); + var event = receipt.tenantAuthorityEvent(); + if (!prepared.selection().matches(event)) throw unavailable(); + requireTenantSource( + player.snapshot(), + event.tenantId(), + event.tenantAuthorityGeneration(), + receipt.tenantBillingSequence(), + event.outboxStreamKey(), + event.outboxSequence(), + event.eventId(), + event.eventDigest()); + if (!receipt.billingEventId().equals(event.tenantBillingEventId()) + || !receipt.billingEventDigest().equals(event.tenantBillingEventDigest()) + || receipt.tenantBillingSequence() != event.tenantBillingSequence()) { + throw unavailable(); + } + requireCurrentTimes(player, evaluatedAt); + var quote = receipt.current().planQuote(); + return capture( + request, + player, + target, + facts( + "PAID_HOSTING", + receipt.subscriptionStatus().storageValue(), + receipt.gameplayAvailable(), + receipt.allowPublicJoin(), + receipt.allowNewGameplayBindings(), + receipt.allowNewInstanceStarts(), + quote.maxActiveSessions(), + quote.maxConcurrentGameInstances(), + quote.maxStorageBytes(), + receipt.entitlementVersion(), + receipt.tenantBillingSequence(), + event.tenantAuthorityGeneration()), + RuntimePlayerAdmissionEntitlementEvidence.digest( + Map.of( + "receiptRequestId", receipt.receiptRequestId().toString(), + "subscriptionId", receipt.current().subscriptionId().toString(), + "subscriptionRowVersion", Long.toString(receipt.current().rowVersion()), + "billingEventId", receipt.billingEventId().toString(), + "billingEventDigest", receipt.billingEventDigest(), + "tenantAuthorityEventDigest", event.eventDigest())), + evaluatedAt, + receipt.validUntil()); + }); } private RuntimePlayerAdmissionEntitlementEvidence captureDemoSources( Request request, VerifiedCaller caller, Prepared prepared) { PublishedRealmEvidence target = readProtectedTarget(request, prepared.player().scope()); - return inSourceTransaction( - () -> { - CurrentPlayer player = readCurrentPlayer(request, caller); - if (!prepared.player().scope().equals(player.scope())) throw unavailable(); - requireSameHead(request, prepared.selection()); - DemoTenantEntitlementSnapshot demo = demos.readCurrent(request.tenantId()); - var head = prepared.selection().checkpoint(); - if (!demo.tenantAuthorityEventId().equals(head.eventId()) - || !demo.tenantAuthorityEventDigest().equals(head.eventDigest()) - || !demo.canonicalTenantId().equals(head.tenantId()) - || demo.tenantAuthorityGeneration() != head.tenantAuthorityGeneration() - || !demo.tenantAuthorityOutboxStreamKey().equals(head.outboxStreamKey()) - || demo.tenantAuthorityOutboxSequence() != head.outboxSequence() - || demo.tenantBillingSequence() != head.tenantBillingSequence() - || !demo.eventId().equals(head.tenantBillingEventId()) - || !demo.eventDigest().equals(head.tenantBillingEventDigest()) - || demo.tenantAuthoritySourceVersion() != head.tenantAuthoritySourceVersion()) { - throw unavailable(); - } - requireTenantSource( - player.snapshot(), - demo.canonicalTenantId(), - demo.tenantAuthorityGeneration(), + return inSourceTransaction(() -> { + CurrentPlayer player = readCurrentPlayer(request, caller); + if (!prepared.player().scope().equals(player.scope())) throw unavailable(); + requireSameHead(request, prepared.selection()); + DemoTenantEntitlementSnapshot demo = demos.readCurrent(request.tenantId()); + var head = prepared.selection().checkpoint(); + if (!demo.tenantAuthorityEventId().equals(head.eventId()) + || !demo.tenantAuthorityEventDigest().equals(head.eventDigest()) + || !demo.canonicalTenantId().equals(head.tenantId()) + || demo.tenantAuthorityGeneration() != head.tenantAuthorityGeneration() + || !demo.tenantAuthorityOutboxStreamKey().equals(head.outboxStreamKey()) + || demo.tenantAuthorityOutboxSequence() != head.outboxSequence() + || demo.tenantBillingSequence() != head.tenantBillingSequence() + || !demo.eventId().equals(head.tenantBillingEventId()) + || !demo.eventDigest().equals(head.tenantBillingEventDigest()) + || demo.tenantAuthoritySourceVersion() != head.tenantAuthoritySourceVersion()) { + throw unavailable(); + } + requireTenantSource( + player.snapshot(), + demo.canonicalTenantId(), + demo.tenantAuthorityGeneration(), + demo.tenantBillingSequence(), + demo.tenantAuthorityOutboxStreamKey(), + demo.tenantAuthorityOutboxSequence(), + demo.tenantAuthorityEventId(), + demo.tenantAuthorityEventDigest()); + Instant capturedAt = now(); + requireCurrentTimes(player, capturedAt); + return capture( + request, + player, + target, + facts( + "NON_PAID_DEMO", + null, + demo.gameplayAvailable(), + demo.allowPublicJoin(), + demo.allowNewGameplayBindings(), + demo.allowNewInstanceStarts(), + demo.quotas().maxActiveSessions(), + demo.quotas().maxConcurrentGameInstances(), + demo.quotas().maxStorageBytes(), + demo.entitlementVersion(), demo.tenantBillingSequence(), - demo.tenantAuthorityOutboxStreamKey(), - demo.tenantAuthorityOutboxSequence(), - demo.tenantAuthorityEventId(), - demo.tenantAuthorityEventDigest()); - Instant capturedAt = now(); - requireCurrentTimes(player, capturedAt); - return capture( - request, - player, - target, - facts( - "NON_PAID_DEMO", - null, - demo.gameplayAvailable(), - demo.allowPublicJoin(), - demo.allowNewGameplayBindings(), - demo.allowNewInstanceStarts(), - demo.quotas().maxActiveSessions(), - demo.quotas().maxConcurrentGameInstances(), - demo.quotas().maxStorageBytes(), - demo.entitlementVersion(), - demo.tenantBillingSequence(), - demo.tenantAuthorityGeneration()), - demo.snapshotIdentity(), - capturedAt, - null); - }); + demo.tenantAuthorityGeneration()), + demo.snapshotIdentity(), + capturedAt, + null); + }); } private VerifiedCaller verifyCaller(Request request, String token) { @@ -316,27 +312,25 @@ private CurrentPlayer readCurrentPlayer(Request request, VerifiedCaller caller) var expectedCutoff = authority .accountSecurityCutoff() - .map( - cutoff -> - Map.of( - "accountAuthorityGeneration", - cutoff.accountAuthorityGeneration(), - "outboxStreamKey", - cutoff.outboxStreamKey(), - "outboxSequence", - cutoff.outboxSequence())); + .map(cutoff -> + Map.of( + "accountAuthorityGeneration", + cutoff.accountAuthorityGeneration(), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + cutoff.outboxSequence())); var actualCutoff = tuple .accountSecurityCutoff() - .map( - cutoff -> - Map.of( - "accountAuthorityGeneration", - cutoff.accountAuthorityGeneration(), - "outboxStreamKey", - cutoff.outboxStreamKey(), - "outboxSequence", - cutoff.outboxSequence())); + .map(cutoff -> + Map.of( + "accountAuthorityGeneration", + cutoff.accountAuthorityGeneration(), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + cutoff.outboxSequence())); if (!ISSUER.equals(snapshot.issuerId()) || !accountId.toString().equals(snapshot.accountId()) || !request.tenantId().toString().equals(snapshot.tenantId()) @@ -398,12 +392,11 @@ private static void requireTenantSource( .filter(Map.of(tenant, cutoff)::equals) .isPresent() || snapshot.sourceEvidence().stream() - .noneMatch( - source -> - stream.equals(source.outboxStreamKey()) - && Long.toString(sequence).equals(source.outboxSequence()) - && eventId.toString().equals(source.eventId()) - && eventDigest.equals(source.eventDigest()))) { + .noneMatch(source -> + stream.equals(source.outboxStreamKey()) + && Long.toString(sequence).equals(source.outboxSequence()) + && eventId.toString().equals(source.eventId()) + && eventDigest.equals(source.eventDigest()))) { throw unavailable(); } } @@ -433,22 +426,19 @@ private static void requireCurrentTimes(CurrentPlayer player, Instant evaluatedA private T inSourceTransaction(Supplier action) { requireNoAmbientTransaction(); return Objects.requireNonNull( - transaction.execute( - status -> { - if (!TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) - throw unavailable(); - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() - != Connection.TRANSACTION_SERIALIZABLE) { - throw unavailable(); - } - }); - return Objects.requireNonNull(action.get()); - })); + transaction.execute(status -> { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + throw unavailable(); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_SERIALIZABLE) { + throw unavailable(); + } + }); + return Objects.requireNonNull(action.get()); + })); } private Instant now() { @@ -497,10 +487,9 @@ public record Request( if (connectScopeId == null || connectScopeId.isBlank() || connectScopeId.length() > 16384) throw new IllegalArgumentException("Bounded opaque connect scope is required"); GrpcPeerIdentity.parseUri(authenticatedCallerWorkload) - .filter( - peer -> - peer.uri().equals(authenticatedCallerWorkload) - && "game-session-service".equals(peer.service())) + .filter(peer -> + peer.uri().equals(authenticatedCallerWorkload) + && "game-session-service".equals(peer.service())) .orElseThrow( () -> new IllegalArgumentException("Exact Game Session workload is required")); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwner.java index 1f3cb4c545..43563d8427 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwner.java @@ -55,17 +55,16 @@ public Evaluation evaluate(UUID tenantId) { try { Prepared prepared = Objects.requireNonNull( - transaction.execute( - status -> { - requireSourceTransaction(); - SourceSelection selection = sources.readCurrentSourceSelection(tenantId); - Instant observedAt = now(); - DemoTenantEntitlementSnapshot demo = - selection.kind() == SourceKind.NON_PAID_DEMO - ? demos.readCurrent(tenantId) - : null; - return new Prepared(selection, demo, observedAt); - })); + transaction.execute(status -> { + requireSourceTransaction(); + SourceSelection selection = sources.readCurrentSourceSelection(tenantId); + Instant observedAt = now(); + DemoTenantEntitlementSnapshot demo = + selection.kind() == SourceKind.NON_PAID_DEMO + ? demos.readCurrent(tenantId) + : null; + return new Prepared(selection, demo, observedAt); + })); Evaluation evaluation = switch (prepared.selection().kind()) { case PAID_HOSTING -> diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java index ecf214efd4..b6d66e282a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwner.java @@ -129,24 +129,23 @@ private Map evaluateEac .factory())) { List> reads = tenants.stream() - .>map( - tenantId -> - () -> { - requireNoAmbientTransaction(); - requireWorkloadOnlySourceContext(); - if (!ENTITLEMENT_PERMITS.tryAcquire(5, TimeUnit.SECONDS)) - throw new IllegalStateException( - "Discovery entitlement capacity is unavailable"); - try { - var evaluation = Objects.requireNonNull(entitlements.evaluate(tenantId)); - if (!tenantId.equals(evaluation.canonicalTenantId())) - throw new IllegalStateException( - "Entitlement source returned another canonical tenant"); - return evaluation; - } finally { - ENTITLEMENT_PERMITS.release(); - } - }) + .>map(tenantId -> + () -> { + requireNoAmbientTransaction(); + requireWorkloadOnlySourceContext(); + if (!ENTITLEMENT_PERMITS.tryAcquire(5, TimeUnit.SECONDS)) + throw new IllegalStateException( + "Discovery entitlement capacity is unavailable"); + try { + var evaluation = Objects.requireNonNull(entitlements.evaluate(tenantId)); + if (!tenantId.equals(evaluation.canonicalTenantId())) + throw new IllegalStateException( + "Entitlement source returned another canonical tenant"); + return evaluation; + } finally { + ENTITLEMENT_PERMITS.release(); + } + }) .toList(); var completed = workers.invokeAll(reads); Map evaluations = diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java index 2a00b3420c..f03de073f0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwner.java @@ -95,20 +95,19 @@ public Result commit(Request request, String authenticatedCaller) { requireCaller(request, authenticatedCaller); request.requireStructurallyValid(); if (!(request.context() instanceof PlayerContext)) throw unavailable(); - return commitWithFreshSnapshot( - () -> { - // Exact replay/conflict can linearize at the snapshot read without taking a mutation - // lock. - Record existing = capacity.findForReplay(request.identity()); - if (existing != null) return capacity.exact(request, existing); - lockPlayerAccount(request); - if (request.capacityRearmFence() != 1) throw conflict(); - current(request); - requireSupportedShape(request); - if (!request.evidence().permitsCreation()) - throw new CapacityException(Failure.TENANT_BILLING_BLOCKED); - return capacity.create(request, request.evidence().expiresAt(), clock); - }); + return commitWithFreshSnapshot(() -> { + // Exact replay/conflict can linearize at the snapshot read without taking a mutation + // lock. + Record existing = capacity.findForReplay(request.identity()); + if (existing != null) return capacity.exact(request, existing); + lockPlayerAccount(request); + if (request.capacityRearmFence() != 1) throw conflict(); + current(request); + requireSupportedShape(request); + if (!request.evidence().permitsCreation()) + throw new CapacityException(Failure.TENANT_BILLING_BLOCKED); + return capacity.create(request, request.evidence().expiresAt(), clock); + }); } /** Only the Account-owned recovery worker calls this after storing terminal no-commit proof. */ @@ -126,61 +125,59 @@ Result rearm(Request prior, Request next, UUID recoveryOwner, long claimFence) { || !Objects.equals( prior.evidence().fields().get("authorityTuple"), next.evidence().fields().get("authorityTuple"))) throw conflict(); - return inTransaction( - () -> { - lockPlayerAccount(next); - Record row = capacity.find(prior.identity()); - if (row == null) throw conflict(); - if (next.admissionAttemptId().equals(row.get("admission_attempt_id", UUID.class))) { - capacity.requirePriorHistory(prior, next); - return capacity.exact(next, row); - } - capacity.exact(prior, row); - requireClaim(row, recoveryOwner, claimFence, clock.instant()); - if (!"RESERVED".equals(row.get("state", String.class)) - || !"NOT_EXECUTED_AFTER_AUTHORIZATION" - .equals(row.get("execution_status", String.class)) - || row.get("owner_readback", byte[].class) == null) throw conflict(); - current(next); - requireSupportedShape(next); - requireCurrentLifetime(next.evidence(), clock.instant()); - int history = - dsl.execute( - "INSERT INTO account_tenant_capacity_attempt_history " - + "(tenant_uuid, request_id, admission_id, admission_attempt_id, capacity_rearm_fence, mutation_digest, canonical_payload, owner_readback) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", - prior.identity().tenantId(), - prior.identity().requestId(), - prior.identity().admissionId(), - prior.admissionAttemptId(), - prior.capacityRearmFence(), - prior.mutationDigest(), - CapacityAdmissionDigest.preimage(prior), - row.get("owner_readback", byte[].class)); - if (history != 1) throw unavailable(); - int changed = - dsl.execute( - "UPDATE account_tenant_capacity_reservations SET admission_attempt_id = ?, capacity_rearm_fence = ?, reservation_fence = ?, mutation_digest = ?, canonical_payload = ?, evaluation_identity = ?, expires_at = ?::timestamptz, reconcile_deadline = ?::timestamptz, next_reconcile_at = NULL, recovery_attempt_count = 0, execution_status = 'OWNER_EXECUTION_PENDING', owner_readback = NULL, owner_readback_digest = NULL " - + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND admission_attempt_id = ? AND capacity_rearm_fence = ? AND mutation_digest = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION'", - next.admissionAttemptId(), - next.capacityRearmFence(), - Math.incrementExact(number(row, "reservation_fence")), - next.mutationDigest(), - CapacityAdmissionDigest.preimage(next), - next.evidence().evaluationIdentity(), - at(next.evidence().expiresAt()), - at(next.evidence().expiresAt().plusSeconds(60)), - prior.identity().tenantId(), - prior.identity().requestId(), - prior.identity().admissionId(), - prior.admissionAttemptId(), - prior.capacityRearmFence(), - prior.mutationDigest(), - recoveryOwner, - claimFence); - if (changed != 1) throw conflict(); - // Reservation identity and both usage columns are deliberately untouched. - return capacity.exact(next, Objects.requireNonNull(capacity.find(next.identity()))); - }); + return inTransaction(() -> { + lockPlayerAccount(next); + Record row = capacity.find(prior.identity()); + if (row == null) throw conflict(); + if (next.admissionAttemptId().equals(row.get("admission_attempt_id", UUID.class))) { + capacity.requirePriorHistory(prior, next); + return capacity.exact(next, row); + } + capacity.exact(prior, row); + requireClaim(row, recoveryOwner, claimFence, clock.instant()); + if (!"RESERVED".equals(row.get("state", String.class)) + || !"NOT_EXECUTED_AFTER_AUTHORIZATION".equals(row.get("execution_status", String.class)) + || row.get("owner_readback", byte[].class) == null) throw conflict(); + current(next); + requireSupportedShape(next); + requireCurrentLifetime(next.evidence(), clock.instant()); + int history = + dsl.execute( + "INSERT INTO account_tenant_capacity_attempt_history " + + "(tenant_uuid, request_id, admission_id, admission_attempt_id, capacity_rearm_fence, mutation_digest, canonical_payload, owner_readback) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + prior.identity().tenantId(), + prior.identity().requestId(), + prior.identity().admissionId(), + prior.admissionAttemptId(), + prior.capacityRearmFence(), + prior.mutationDigest(), + CapacityAdmissionDigest.preimage(prior), + row.get("owner_readback", byte[].class)); + if (history != 1) throw unavailable(); + int changed = + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET admission_attempt_id = ?, capacity_rearm_fence = ?, reservation_fence = ?, mutation_digest = ?, canonical_payload = ?, evaluation_identity = ?, expires_at = ?::timestamptz, reconcile_deadline = ?::timestamptz, next_reconcile_at = NULL, recovery_attempt_count = 0, execution_status = 'OWNER_EXECUTION_PENDING', owner_readback = NULL, owner_readback_digest = NULL " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND admission_attempt_id = ? AND capacity_rearm_fence = ? AND mutation_digest = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION'", + next.admissionAttemptId(), + next.capacityRearmFence(), + Math.incrementExact(number(row, "reservation_fence")), + next.mutationDigest(), + CapacityAdmissionDigest.preimage(next), + next.evidence().evaluationIdentity(), + at(next.evidence().expiresAt()), + at(next.evidence().expiresAt().plusSeconds(60)), + prior.identity().tenantId(), + prior.identity().requestId(), + prior.identity().admissionId(), + prior.admissionAttemptId(), + prior.capacityRearmFence(), + prior.mutationDigest(), + recoveryOwner, + claimFence); + if (changed != 1) throw conflict(); + // Reservation identity and both usage columns are deliberately untouched. + return capacity.exact(next, Objects.requireNonNull(capacity.find(next.identity()))); + }); } private void current(Request request) { @@ -212,10 +209,9 @@ private void current(Request request) { } if (!(fields.get("sourceReferences") instanceof Map source)) throw unavailable(); var issuance = - qualifiedSource( - () -> - issuances.readCurrentCommittedCandidateByJti( - UUID.fromString((String) source.get("callerTokenJti")))) + qualifiedSource(() -> + issuances.readCurrentCommittedCandidateByJti( + UUID.fromString((String) source.get("callerTokenJti")))) .orElseThrow(AccountTenantCapacityRepository::unavailable); if (!issuance.identity().accountId().equals(player.accountId()) || !issuance.identity().callerWorkload().equals(request.evidence().callerWorkload()) @@ -229,9 +225,8 @@ private void current(Request request) { || now.getEpochSecond() < issuance.identity().notBeforeEpochSecond() || now.getEpochSecond() >= issuance.identity().expiresAtEpochSecond()) throw unavailable(); var scope = - qualifiedSource( - () -> - scopes.findCanonicalEvidenceByTokenHash(parsed.verifiedConnectScopeTokenHash())) + qualifiedSource(() -> + scopes.findCanonicalEvidenceByTokenHash(parsed.verifiedConnectScopeTokenHash())) .orElseThrow(AccountTenantCapacityRepository::unavailable); if (!scope.accountUuid().equals(player.accountId()) || !scope.tenantUuid().equals(player.tenantId()) @@ -291,11 +286,10 @@ private Result commitWithFreshSnapshot(Supplier action) { if (caller.isCancelled() || retryDeadline.isExpired()) throw unavailable(); for (int attempt = 1; ; attempt++) { try { - return inTransaction( - () -> { - if (caller.isCancelled() || retryDeadline.isExpired()) throw unavailable(); - return action.get(); - }); + return inTransaction(() -> { + if (caller.isCancelled() || retryDeadline.isExpired()) throw unavailable(); + return action.get(); + }); } catch (RuntimeException failure) { // A PostgreSQL serialization failure rolls back the whole transaction. Retry outside // that transaction so a concurrent original can become exact replay or conflict. @@ -335,17 +329,15 @@ T inTransaction(Supplier action) { if (TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable(); return Objects.requireNonNull( - transaction.execute( - status -> { - AccountTenantCapacityRepository.transaction(); - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() - != Connection.TRANSACTION_SERIALIZABLE) throw unavailable(); - }); - return action.get(); - })); + transaction.execute(status -> { + AccountTenantCapacityRepository.transaction(); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_SERIALIZABLE) + throw unavailable(); + }); + return action.get(); + })); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java index 11997dbb02..a1bd428056 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCapacityRecoveryWorker.java @@ -130,31 +130,28 @@ private Result reconcileClaim(Request request, NoCommitAction noCommitAction) { if (claim.reservation().state() != State.RESERVED) return claim.reservation(); if (claim.noCommitProof() != null) { if (noCommitAction == NoCommitAction.RETAIN_FOR_REARM) return claim.reservation(); - return owner.inTransaction( - () -> { - Record row = capacity.find(request.identity()); - if (row == null) throw conflict(); - Result current = capacity.exact(request, row); - AccountTenantCapacityOwner.requireClaim(row, workerId, claim.fence(), clock.instant()); - if (!current.equals(claim.reservation()) - || !"NOT_EXECUTED_AFTER_AUTHORIZATION" - .equals(row.get("execution_status", String.class)) - || !Arrays.equals(claim.noCommitProof(), row.get("owner_readback", byte[].class))) - throw conflict(); - moveUsage(request, false); - int changed = - dsl.execute( - "UPDATE account_tenant_capacity_reservations SET state = 'RELEASED', reservation_fence = ?, next_reconcile_at = NULL WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION'", - Math.incrementExact(current.reservationFence()), - request.identity().tenantId(), - request.identity().requestId(), - request.identity().admissionId(), - workerId, - claim.fence()); - if (changed != 1) throw conflict(); - return capacity.exact( - request, Objects.requireNonNull(capacity.find(request.identity()))); - }); + return owner.inTransaction(() -> { + Record row = capacity.find(request.identity()); + if (row == null) throw conflict(); + Result current = capacity.exact(request, row); + AccountTenantCapacityOwner.requireClaim(row, workerId, claim.fence(), clock.instant()); + if (!current.equals(claim.reservation()) + || !"NOT_EXECUTED_AFTER_AUTHORIZATION".equals(row.get("execution_status", String.class)) + || !Arrays.equals(claim.noCommitProof(), row.get("owner_readback", byte[].class))) + throw conflict(); + moveUsage(request, false); + int changed = + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET state = 'RELEASED', reservation_fence = ?, next_reconcile_at = NULL WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'NOT_EXECUTED_AFTER_AUTHORIZATION'", + Math.incrementExact(current.reservationFence()), + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + workerId, + claim.fence()); + if (changed != 1) throw conflict(); + return capacity.exact(request, Objects.requireNonNull(capacity.find(request.identity()))); + }); } Observation candidate = null; byte[] candidateProof = null; @@ -180,93 +177,91 @@ private Result reconcileClaim(Request request, NoCommitAction noCommitAction) { } final Observation observed = candidate; final byte[] exactProof = candidateProof; - return owner.inTransaction( - () -> { - Record row = capacity.find(request.identity()); - if (row == null) throw conflict(); - Result current = capacity.exact(request, row); - AccountTenantCapacityOwner.requireClaim(row, workerId, claim.fence(), clock.instant()); - if (!current.equals(claim.reservation())) throw conflict(); - int attempt = Math.incrementExact(Math.toIntExact(number(row, "recovery_attempt_count"))); - if (attempt > 12) throw unavailable(); - Instant now = clock.instant(); - boolean indeterminate = - observed == null || observed.disposition() == Disposition.INDETERMINATE; - boolean quarantine = - indeterminate && (attempt == 12 || !now.isBefore(claim.reconcileDeadline())); - String outcome = - quarantine - ? State.QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION.name() - : observed == null ? "SOURCE_UNAVAILABLE" : observed.disposition().name(); - int retained = - dsl.execute( - "INSERT INTO account_tenant_capacity_recovery_evidence (tenant_uuid, request_id, admission_id, admission_attempt_id, recovery_claim_fence, recovery_policy_version, recovery_attempt_number, observed_at, outcome, canonical_readback, readback_digest) VALUES (?, ?, ?, ?, ?, 'capacity-recovery/1', ?, ?::timestamptz, ?, ?, ?)", - request.identity().tenantId(), - request.identity().requestId(), - request.identity().admissionId(), - request.admissionAttemptId(), - claim.fence(), - attempt, - at(now), - outcome, - exactProof, - exactProof == null ? null : sha256(exactProof)); - if (retained != 1) throw unavailable(); - if (indeterminate) { - int updated = - dsl.execute( - "UPDATE account_tenant_capacity_reservations SET recovery_attempt_count = ?, state = ?, recovery_escalated_at = ?::timestamptz, next_reconcile_at = ?::timestamptz WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'OWNER_EXECUTION_PENDING'", - attempt, - quarantine - ? State.QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION.name() - : State.RESERVED.name(), - quarantine ? at(now) : null, - quarantine - ? null - : at( - now.plusSeconds(5).isBefore(claim.reconcileDeadline()) - ? now.plusSeconds(5) - : claim.reconcileDeadline()), - request.identity().tenantId(), - request.identity().requestId(), - request.identity().admissionId(), - workerId, - claim.fence()); - if (updated != 1) throw conflict(); - return capacity.exact( - request, Objects.requireNonNull(capacity.find(request.identity()))); - } - boolean committed = observed.disposition() == Disposition.COMMITTED; - State next = - committed - ? State.FINALIZED - : noCommitAction == NoCommitAction.RELEASE ? State.RELEASED : State.RESERVED; - if (committed || next == State.RELEASED) moveUsage(request, committed); - long reservationFence = - next == State.RELEASED - ? Math.incrementExact(current.reservationFence()) - : current.reservationFence(); - int changed = - dsl.execute( - "UPDATE account_tenant_capacity_reservations SET state = ?, execution_status = ?, owner_readback = ?, owner_readback_digest = ?, reservation_fence = ?, recovery_attempt_count = ?, next_reconcile_at = NULL " - + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND admission_attempt_id = ? AND mutation_digest = ? AND reservation_fence = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'OWNER_EXECUTION_PENDING'", - next.name(), - committed ? "COMMITTED" : "NOT_EXECUTED_AFTER_AUTHORIZATION", - exactProof, - sha256(exactProof), - reservationFence, - attempt, - request.identity().tenantId(), - request.identity().requestId(), - request.identity().admissionId(), - request.admissionAttemptId(), - request.mutationDigest(), - current.reservationFence(), - workerId, - claim.fence()); - if (changed != 1) throw conflict(); - return capacity.exact(request, Objects.requireNonNull(capacity.find(request.identity()))); - }); + return owner.inTransaction(() -> { + Record row = capacity.find(request.identity()); + if (row == null) throw conflict(); + Result current = capacity.exact(request, row); + AccountTenantCapacityOwner.requireClaim(row, workerId, claim.fence(), clock.instant()); + if (!current.equals(claim.reservation())) throw conflict(); + int attempt = Math.incrementExact(Math.toIntExact(number(row, "recovery_attempt_count"))); + if (attempt > 12) throw unavailable(); + Instant now = clock.instant(); + boolean indeterminate = + observed == null || observed.disposition() == Disposition.INDETERMINATE; + boolean quarantine = + indeterminate && (attempt == 12 || !now.isBefore(claim.reconcileDeadline())); + String outcome = + quarantine + ? State.QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION.name() + : observed == null ? "SOURCE_UNAVAILABLE" : observed.disposition().name(); + int retained = + dsl.execute( + "INSERT INTO account_tenant_capacity_recovery_evidence (tenant_uuid, request_id, admission_id, admission_attempt_id, recovery_claim_fence, recovery_policy_version, recovery_attempt_number, observed_at, outcome, canonical_readback, readback_digest) VALUES (?, ?, ?, ?, ?, 'capacity-recovery/1', ?, ?::timestamptz, ?, ?, ?)", + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + request.admissionAttemptId(), + claim.fence(), + attempt, + at(now), + outcome, + exactProof, + exactProof == null ? null : sha256(exactProof)); + if (retained != 1) throw unavailable(); + if (indeterminate) { + int updated = + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET recovery_attempt_count = ?, state = ?, recovery_escalated_at = ?::timestamptz, next_reconcile_at = ?::timestamptz WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'OWNER_EXECUTION_PENDING'", + attempt, + quarantine + ? State.QUARANTINED_REQUIRES_AUTHORITY_REMEDIATION.name() + : State.RESERVED.name(), + quarantine ? at(now) : null, + quarantine + ? null + : at( + now.plusSeconds(5).isBefore(claim.reconcileDeadline()) + ? now.plusSeconds(5) + : claim.reconcileDeadline()), + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + workerId, + claim.fence()); + if (updated != 1) throw conflict(); + return capacity.exact(request, Objects.requireNonNull(capacity.find(request.identity()))); + } + boolean committed = observed.disposition() == Disposition.COMMITTED; + State next = + committed + ? State.FINALIZED + : noCommitAction == NoCommitAction.RELEASE ? State.RELEASED : State.RESERVED; + if (committed || next == State.RELEASED) moveUsage(request, committed); + long reservationFence = + next == State.RELEASED + ? Math.incrementExact(current.reservationFence()) + : current.reservationFence(); + int changed = + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET state = ?, execution_status = ?, owner_readback = ?, owner_readback_digest = ?, reservation_fence = ?, recovery_attempt_count = ?, next_reconcile_at = NULL " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND admission_attempt_id = ? AND mutation_digest = ? AND reservation_fence = ? AND recovery_owner = ? AND recovery_claim_fence = ? AND state = 'RESERVED' AND execution_status = 'OWNER_EXECUTION_PENDING'", + next.name(), + committed ? "COMMITTED" : "NOT_EXECUTED_AFTER_AUTHORIZATION", + exactProof, + sha256(exactProof), + reservationFence, + attempt, + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + request.admissionAttemptId(), + request.mutationDigest(), + current.reservationFence(), + workerId, + claim.fence()); + if (changed != 1) throw conflict(); + return capacity.exact(request, Objects.requireNonNull(capacity.find(request.identity()))); + }); } private void moveUsage(Request request, boolean committed) { @@ -289,17 +284,15 @@ public Result rearm(Request prior, Request next) { private Result rearmClaim(Request prior, Request next) { java.util.Optional replay = - owner.inTransaction( - () -> { - Record row = capacity.find(next.identity()); - if (row != null - && next.admissionAttemptId() - .equals(row.get("admission_attempt_id", UUID.class))) { - capacity.requirePriorHistory(prior, next); - return java.util.Optional.of(capacity.exact(next, row)); - } - return java.util.Optional.empty(); - }); + owner.inTransaction(() -> { + Record row = capacity.find(next.identity()); + if (row != null + && next.admissionAttemptId().equals(row.get("admission_attempt_id", UUID.class))) { + capacity.requirePriorHistory(prior, next); + return java.util.Optional.of(capacity.exact(next, row)); + } + return java.util.Optional.empty(); + }); if (replay.isPresent()) return replay.orElseThrow(); Claim claim = claim(prior); return owner.rearm(prior, next, workerId, claim.fence()); @@ -316,45 +309,43 @@ private Result withExclusiveOperation(Identity identity, Supplier operat } private Claim claim(Request request) { - return owner.inTransaction( - () -> { - Record row = capacity.find(request.identity()); - if (row == null) throw conflict(); - Result result = capacity.exact(request, row); - if (result.state() != State.RESERVED) - return new Claim( - result, - number(row, "recovery_claim_fence"), - Math.toIntExact(number(row, "recovery_attempt_count")), - AccountTenantCapacityRepository.time(row, "reconcile_deadline"), - row.get("owner_readback", byte[].class)); - Instant now = clock.instant(); - if (row.get("recovery_owner", UUID.class) != null - && !workerId.equals(row.get("recovery_owner", UUID.class)) - && now.isBefore( - AccountTenantCapacityRepository.time(row, "recovery_claim_expires_at"))) - throw unavailable(); - long fence = Math.incrementExact(number(row, "recovery_claim_fence")); - int changed = - dsl.execute( - "UPDATE account_tenant_capacity_reservations SET recovery_owner = ?, recovery_claim_fence = ?, recovery_claim_expires_at = ?::timestamptz, next_reconcile_at = LEAST(?::timestamptz, reconcile_deadline) " - + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND recovery_claim_fence = ?", - workerId, - fence, - at(now.plusSeconds(15)), - at(now.plusSeconds(5)), - request.identity().tenantId(), - request.identity().requestId(), - request.identity().admissionId(), - number(row, "recovery_claim_fence")); - if (changed != 1) throw conflict(); - return new Claim( - result, + return owner.inTransaction(() -> { + Record row = capacity.find(request.identity()); + if (row == null) throw conflict(); + Result result = capacity.exact(request, row); + if (result.state() != State.RESERVED) + return new Claim( + result, + number(row, "recovery_claim_fence"), + Math.toIntExact(number(row, "recovery_attempt_count")), + AccountTenantCapacityRepository.time(row, "reconcile_deadline"), + row.get("owner_readback", byte[].class)); + Instant now = clock.instant(); + if (row.get("recovery_owner", UUID.class) != null + && !workerId.equals(row.get("recovery_owner", UUID.class)) + && now.isBefore(AccountTenantCapacityRepository.time(row, "recovery_claim_expires_at"))) + throw unavailable(); + long fence = Math.incrementExact(number(row, "recovery_claim_fence")); + int changed = + dsl.execute( + "UPDATE account_tenant_capacity_reservations SET recovery_owner = ?, recovery_claim_fence = ?, recovery_claim_expires_at = ?::timestamptz, next_reconcile_at = LEAST(?::timestamptz, reconcile_deadline) " + + "WHERE tenant_uuid = ? AND request_id = ? AND admission_id = ? AND recovery_claim_fence = ?", + workerId, fence, - Math.toIntExact(number(row, "recovery_attempt_count")), - AccountTenantCapacityRepository.time(row, "reconcile_deadline"), - row.get("owner_readback", byte[].class)); - }); + at(now.plusSeconds(15)), + at(now.plusSeconds(5)), + request.identity().tenantId(), + request.identity().requestId(), + request.identity().admissionId(), + number(row, "recovery_claim_fence")); + if (changed != 1) throw conflict(); + return new Claim( + result, + fence, + Math.toIntExact(number(row, "recovery_attempt_count")), + AccountTenantCapacityRepository.time(row, "reconcile_deadline"), + row.get("owner_readback", byte[].class)); + }); } private static void requireExactSource(Request request, Result expected, Observation observed) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapService.java index 9efe878f3c..f4d2eed6bf 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantCreationBootstrapService.java @@ -191,17 +191,13 @@ private AccountTenantCreationBootstrapResult bootstrapWithSource( UUID requestId = operationRepository .findRequestIdByTenantForUpdate(tenantUuid) - .orElseThrow( - () -> - new IllegalStateException( - "Committed creator-bootstrap operation is absent")); + .orElseThrow(() -> + new IllegalStateException("Committed creator-bootstrap operation is absent")); StoredOperation operation = operationRepository .findForUpdate(requestId) - .orElseThrow( - () -> - new IllegalStateException( - "Committed creator-bootstrap receipt is absent")); + .orElseThrow(() -> + new IllegalStateException("Committed creator-bootstrap receipt is absent")); FreshTenantCreationEvidence creation = tenantAssociationRepository .read(tenantUuid) @@ -251,9 +247,8 @@ private AccountTenantCreationBootstrapResult commitNew( baseline.outboxStreamKey(), "0")) .equals( baseline.outboxCheckpoints().stream() - .filter( - checkpoint -> - checkpoint.outboxStreamKey().equals(baseline.outboxStreamKey())) + .filter(checkpoint -> + checkpoint.outboxStreamKey().equals(baseline.outboxStreamKey())) .toList())) { throw new IllegalStateException( "Creator bootstrap baseline is not exact sequence-zero absence"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java index a576f803db..d9459bf155 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwner.java @@ -75,44 +75,43 @@ public RuntimeTenantOperationEntitlementEvidence evaluateDemo(Request request) { requireRequest(request); requireNoAmbientTransaction(); return Objects.requireNonNull( - transaction.execute( - status -> { - requireSourceTransaction(); - DemoTenantEntitlementSnapshot snapshot = demos.readCurrent(request.tenantId()); - if (!request.tenantId().equals(snapshot.canonicalTenantId())) { - throw unavailable("Demo source targets another tenant"); - } - Map facts = - facts( - request.tenantId(), - "NON_PAID_DEMO", - snapshot.subscriptionStatus(), - snapshot.gameplayAvailable(), - snapshot.allowPublicJoin(), - snapshot.allowNewGameplayBindings(), - snapshot.allowNewInstanceStarts(), - quotas( - snapshot.quotas().maxActiveSessions(), - snapshot.quotas().maxConcurrentGameInstances(), - snapshot.quotas().maxStorageBytes()), - snapshot.entitlementVersion(), - snapshot.tenantBillingSequence(), - snapshot.tenantAuthorityGeneration(), - snapshot.tenantAuthorityOutboxStreamKey(), - snapshot.tenantAuthorityOutboxSequence(), - snapshot.tenantAuthorityEventId(), - snapshot.tenantAuthorityEventDigest()); - Map source = new LinkedHashMap<>(); - source.put("sourceEvidenceDigest", snapshot.sourceEvidence().evidenceDigest()); - source.put( - "tenantAuthoritySourceVersion", - Long.toString(snapshot.tenantAuthoritySourceVersion())); - source.put("billingStream", snapshot.outboxStreamKey()); - source.put("billingSequence", Long.toString(snapshot.tenantBillingSequence())); - source.put("billingEventId", snapshot.eventId().toString()); - source.put("billingEventDigest", snapshot.eventDigest()); - return capture(request, facts, source, now()); - })); + transaction.execute(status -> { + requireSourceTransaction(); + DemoTenantEntitlementSnapshot snapshot = demos.readCurrent(request.tenantId()); + if (!request.tenantId().equals(snapshot.canonicalTenantId())) { + throw unavailable("Demo source targets another tenant"); + } + Map facts = + facts( + request.tenantId(), + "NON_PAID_DEMO", + snapshot.subscriptionStatus(), + snapshot.gameplayAvailable(), + snapshot.allowPublicJoin(), + snapshot.allowNewGameplayBindings(), + snapshot.allowNewInstanceStarts(), + quotas( + snapshot.quotas().maxActiveSessions(), + snapshot.quotas().maxConcurrentGameInstances(), + snapshot.quotas().maxStorageBytes()), + snapshot.entitlementVersion(), + snapshot.tenantBillingSequence(), + snapshot.tenantAuthorityGeneration(), + snapshot.tenantAuthorityOutboxStreamKey(), + snapshot.tenantAuthorityOutboxSequence(), + snapshot.tenantAuthorityEventId(), + snapshot.tenantAuthorityEventDigest()); + Map source = new LinkedHashMap<>(); + source.put("sourceEvidenceDigest", snapshot.sourceEvidence().evidenceDigest()); + source.put( + "tenantAuthoritySourceVersion", + Long.toString(snapshot.tenantAuthoritySourceVersion())); + source.put("billingStream", snapshot.outboxStreamKey()); + source.put("billingSequence", Long.toString(snapshot.tenantBillingSequence())); + source.put("billingEventId", snapshot.eventId().toString()); + source.put("billingEventDigest", snapshot.eventDigest()); + return capture(request, facts, source, now()); + })); } private RuntimeTenantOperationEntitlementEvidence paid( @@ -333,9 +332,8 @@ public record Request(UUID tenantId, UUID requestId, String authenticatedCallerW GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(authenticatedCallerWorkload) .filter(identity -> identity.uri().equals(authenticatedCallerWorkload)) - .orElseThrow( - () -> - new IllegalArgumentException("Canonical authenticated workload is required")); + .orElseThrow(() -> + new IllegalArgumentException("Canonical authenticated workload is required")); if (!"world-management-service".equals(peer.service())) { throw new IllegalArgumentException("Tenant operation requires World Management"); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentService.java index c711ac879a..5c0066114b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentService.java @@ -65,24 +65,22 @@ public FreshTenantCreationEvidence enroll(UUID creationRequestId, String expecte } FreshTenantCreationEvidence committed = - transactionTemplate.execute( - status -> { - FreshTenantCreationEvidence imported = - associationRepository.importVerified(ownerEvidence); - FreshTenantCreationEvidence readback = - associationRepository - .read(ownerEvidence.canonicalTenantId()) - .orElseThrow( - () -> - new IllegalStateException( - "Fresh Account tenant association readback is absent")); - if (!ownerEvidence.equals(imported) || !ownerEvidence.equals(readback)) { - throw new IllegalStateException( - "Fresh Account tenant association readback differs from owner evidence"); - } - generationRepository.initializeTenantIfAbsent(readback.canonicalTenantId()); - return readback; - }); + transactionTemplate.execute(status -> { + FreshTenantCreationEvidence imported = + associationRepository.importVerified(ownerEvidence); + FreshTenantCreationEvidence readback = + associationRepository + .read(ownerEvidence.canonicalTenantId()) + .orElseThrow(() -> + new IllegalStateException( + "Fresh Account tenant association readback is absent")); + if (!ownerEvidence.equals(imported) || !ownerEvidence.equals(readback)) { + throw new IllegalStateException( + "Fresh Account tenant association readback differs from owner evidence"); + } + generationRepository.initializeTenantIfAbsent(readback.canonicalTenantId()); + return readback; + }); return Objects.requireNonNull( committed, "Fresh tenant enrollment transaction returned no result"); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index a0addcc784..d9b2eca643 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -889,13 +889,12 @@ public void listPresenceVisibilityPolicies( } var builder = net.firedevops.firemud.account.v1.ListPresenceVisibilityPoliciesResponse.newBuilder(); - policies.forEach( - (storageId, policy) -> - builder.addPolicies( - net.firedevops.firemud.account.v1.PresenceVisibilityPolicyEntry.newBuilder() - .setAccountId(accountUuidsByStorageId.get(storageId).toString()) - .setPolicy(policy.name()) - .build())); + policies.forEach((storageId, policy) -> + builder.addPolicies( + net.firedevops.firemud.account.v1.PresenceVisibilityPolicyEntry.newBuilder() + .setAccountId(accountUuidsByStorageId.get(storageId).toString()) + .setPolicy(policy.name()) + .build())); responseObserver.onNext(builder.build()); responseObserver.onCompleted(); } catch (AdminAuthorizationException ex) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java index c13cd5aa4c..052f21fa15 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java @@ -133,14 +133,13 @@ public void getCurrentGenerationRequest( validateRequest(request.getSchemaVersion(), request.getUnknownFields().asMap().isEmpty()); Binding binding = requireCurrentAuthenticatedBinding(); GenerationRequest current = - accountTransaction.execute( - status -> { - GenerationRequest requested = - repository.ensureCurrentGenerationRequest( - binding.accountBinding(), trustFence(binding)); - requireUnchangedTrustBinding(binding); - return requested; - }); + accountTransaction.execute(status -> { + GenerationRequest requested = + repository.ensureCurrentGenerationRequest( + binding.accountBinding(), trustFence(binding)); + requireUnchangedTrustBinding(binding); + return requested; + }); if (current == null) { throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( "JWT signer generation request is unavailable"); @@ -175,19 +174,18 @@ public void recordSecretObservation( UUID operationId = parseOperationId(request.getOperationId()); Binding binding = requireCurrentAuthenticatedBinding(); GenerationRequest current = - accountTransaction.execute( - status -> { - GenerationRequest observed = - repository.recordSecretObservation( - binding.accountBinding(), - trustFence(binding), - operationId, - request.getOperationDigest(), - request.getSecretUid(), - request.getObservedResourceVersion()); - requireUnchangedTrustBinding(binding); - return observed; - }); + accountTransaction.execute(status -> { + GenerationRequest observed = + repository.recordSecretObservation( + binding.accountBinding(), + trustFence(binding), + operationId, + request.getOperationDigest(), + request.getSecretUid(), + request.getObservedResourceVersion()); + requireUnchangedTrustBinding(binding); + return observed; + }); if (current == null) { throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( "JWT signer Secret observation is unavailable"); @@ -209,21 +207,20 @@ public void recordGenerationResult( UUID operationId = parseOperationId(request.getOperationId()); Binding binding = requireCurrentAuthenticatedBinding(); GenerationResult result = - accountTransaction.execute( - status -> { - GenerationResult persisted = - repository.recordGenerationResult( - binding.accountBinding(), - trustFence(binding), - operationId, - request.getGenerationRequestDigest(), - request.getSecretUid(), - request.getExpectedPriorResourceVersion(), - request.getObservedResourceVersion(), - request.getPublicJwkJson()); - requireUnchangedTrustBinding(binding); - return persisted; - }); + accountTransaction.execute(status -> { + GenerationResult persisted = + repository.recordGenerationResult( + binding.accountBinding(), + trustFence(binding), + operationId, + request.getGenerationRequestDigest(), + request.getSecretUid(), + request.getExpectedPriorResourceVersion(), + request.getObservedResourceVersion(), + request.getPublicJwkJson()); + requireUnchangedTrustBinding(binding); + return persisted; + }); if (result == null) { throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( "JWT signer generation receipt is unavailable"); @@ -254,10 +251,9 @@ public void getCurrentPromotionRequest( PreparedGenerationEvidence preparedForObservation; try { preparedForObservation = - accountTransaction.execute( - status -> - repository.readPreparedGenerationForRecovery( - binding.accountBinding(), trustFence(binding))); + accountTransaction.execute(status -> + repository.readPreparedGenerationForRecovery( + binding.accountBinding(), trustFence(binding))); } catch (AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException notPrepared) { var preparation = coordinator.prepareCurrentPromotionOnce(); requireUnchangedTrustBinding(binding); @@ -270,10 +266,9 @@ public void getCurrentPromotionRequest( "Account has no complete owner-verified promotion proof"); } preparedForObservation = - accountTransaction.execute( - status -> - repository.readPreparedGenerationForRecovery( - binding.accountBinding(), trustFence(binding))); + accountTransaction.execute(status -> + repository.readPreparedGenerationForRecovery( + binding.accountBinding(), trustFence(binding))); } if (preparedForObservation == null) { throw new AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException( @@ -286,35 +281,34 @@ public void getCurrentPromotionRequest( InventorySnapshot liveInventory = observeCurrentValidatorInventory(observationContext); requireUnchangedTrustBinding(binding); PreparedGenerationEvidence prepared = - accountTransaction.execute( - status -> { - PreparedGenerationEvidence current = - repository.readPreparedGenerationForRecovery( - binding.accountBinding(), trustFence(binding)); - if (!observationContext.equals(observationContext(current))) { - throw new AccountJwtSignerDesiredStateRepository - .PromotionPrerequisitesIncompleteException( - "Prepared signer operation changed during validator inventory proof"); - } - boolean completeProof = - readinessRepository - .readPromotionProof( - binding.accountBinding(), - trustFence(binding), - current.promotion().generationOperationId(), - liveInventory) - .isPresent(); - if (!completeProof) { - throw new AccountJwtSignerDesiredStateRepository - .PromotionPrerequisitesIncompleteException( - "Complete Account readiness proof is unavailable"); - } - PreparedGenerationEvidence evidence = - repository.readAndMarkPreparedPromotionDispatched( - binding.accountBinding(), trustFence(binding)); - requireUnchangedTrustBinding(binding); - return evidence; - }); + accountTransaction.execute(status -> { + PreparedGenerationEvidence current = + repository.readPreparedGenerationForRecovery( + binding.accountBinding(), trustFence(binding)); + if (!observationContext.equals(observationContext(current))) { + throw new AccountJwtSignerDesiredStateRepository + .PromotionPrerequisitesIncompleteException( + "Prepared signer operation changed during validator inventory proof"); + } + boolean completeProof = + readinessRepository + .readPromotionProof( + binding.accountBinding(), + trustFence(binding), + current.promotion().generationOperationId(), + liveInventory) + .isPresent(); + if (!completeProof) { + throw new AccountJwtSignerDesiredStateRepository + .PromotionPrerequisitesIncompleteException( + "Complete Account readiness proof is unavailable"); + } + PreparedGenerationEvidence evidence = + repository.readAndMarkPreparedPromotionDispatched( + binding.accountBinding(), trustFence(binding)); + requireUnchangedTrustBinding(binding); + return evidence; + }); if (prepared == null) { throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( "JWT signer promotion request is unavailable"); @@ -364,14 +358,13 @@ public void recordPrivatePromotionResult( : java.util.Optional.empty(), request.getResultingSlotsList()); PrivatePromotionReceipt receipt = - accountTransaction.execute( - status -> { - PrivatePromotionReceipt persisted = - repository.recordPrivatePromotionResult( - binding.accountBinding(), trustFence(binding), observation); - requireUnchangedTrustBinding(binding); - return persisted; - }); + accountTransaction.execute(status -> { + PrivatePromotionReceipt persisted = + repository.recordPrivatePromotionResult( + binding.accountBinding(), trustFence(binding), observation); + requireUnchangedTrustBinding(binding); + return persisted; + }); if (receipt == null) { throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( "JWT signer private promotion receipt is unavailable"); @@ -489,9 +482,8 @@ private boolean ownerConfirmsNoPromotionReadyYet(Binding binding) { return unselectedInitialEnrollment; } GenerationRequest current = - accountTransaction.execute( - status -> - repository.readCurrentGenerationRequest(binding.accountBinding(), currentTrust)); + accountTransaction.execute(status -> + repository.readCurrentGenerationRequest(binding.accountBinding(), currentTrust)); requireUnchangedTrustBinding(binding); return current != null && (current.phase() == GenerationPhase.OBSERVE_PRIVATE_SECRET @@ -643,13 +635,12 @@ private static GetCurrentPromotionRequestResponse toPromotionRequestResponse( .addAllowedPrivateSlots("previous.key"); promotion .expectedPreviousActive() - .ifPresent( - previous -> { - response.setExpectedPreviousGeneration(previous.generation()); - response.setExpectedPreviousKid(previous.kid()); - response.setExpectedPreviousPublicKeyFingerprint( - promotion.expectedPreviousPublicKeyFingerprint().orElseThrow()); - }); + .ifPresent(previous -> { + response.setExpectedPreviousGeneration(previous.generation()); + response.setExpectedPreviousKid(previous.kid()); + response.setExpectedPreviousPublicKeyFingerprint( + promotion.expectedPreviousPublicKeyFingerprint().orElseThrow()); + }); return response.build(); } 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 5527b0423b..4c4387eebd 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,36 +595,34 @@ 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); - }); + joinTransactionTemplate.executeWithoutResult(status -> { + lockCanonicalScopeAccount(scope); + accountJoinOperationRepository.insertCanonicalIntent(requestId, scope, callerBinding); + }); return Objects.requireNonNull( - joinTransactionTemplate.execute( - status -> { - lockCanonicalScopeAccount(scope); - CanonicalJoinOperationEvidence operation = - accountJoinOperationRepository - .findCanonicalEvidenceForUpdateByRequestId(requestId) - .orElseThrow(); - if ("FAILED".equals(operation.status())) { - return new CanonicalJoinPreparation(operation, null, null, null); - } - SourceSelection source = - consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); - return switch (source.kind()) { - case PAID_HOSTING -> - new CanonicalJoinPreparation( - operation, - source, - null, - consumers.hosting().prepareCurrentRead(scope.tenantId())); - case NON_PAID_DEMO -> - new CanonicalJoinPreparation( - operation, source, consumers.demos().readCurrent(scope.tenantId()), null); - }; - })); + joinTransactionTemplate.execute(status -> { + lockCanonicalScopeAccount(scope); + CanonicalJoinOperationEvidence operation = + accountJoinOperationRepository + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow(); + if ("FAILED".equals(operation.status())) { + return new CanonicalJoinPreparation(operation, null, null, null); + } + SourceSelection source = + consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); + return switch (source.kind()) { + case PAID_HOSTING -> + new CanonicalJoinPreparation( + operation, + source, + null, + consumers.hosting().prepareCurrentRead(scope.tenantId())); + case NON_PAID_DEMO -> + new CanonicalJoinPreparation( + operation, source, consumers.demos().readCurrent(scope.tenantId()), null); + }; + })); } private CanonicalJoinResult commitCanonicalJoin( @@ -635,103 +633,99 @@ private CanonicalJoinResult commitCanonicalJoin( CanonicalJoinPreparation prepared, StripeHostingSubscriptionObserver.Result observation) { return Objects.requireNonNull( - joinTransactionTemplate.execute( - status -> { - lockCanonicalScopeAccount(scope); - requireCanonicalScopeFresh(consumers, scope); - CanonicalJoinOperationEvidence lockedOperation = - accountJoinOperationRepository - .findCanonicalEvidenceForUpdateByRequestId(requestId) - .orElseThrow(); - if ("FAILED".equals(lockedOperation.status())) { - // Preparation precedes provider/target reads. Another exact attempt may have - // finished meanwhile, including before any policy evidence could be bound. - var retained = - accountJoinOperationRepository.finishCanonicalFailure( - requestId, scope, callerBinding, lockedOperation.outcome()); - return new CanonicalJoinResult(retained.outcome(), null, false, true); - } - SourceSelection current = - consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); - if (current.kind() != prepared.source().kind() - || !prepared.source().matches(current.checkpoint())) { - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", "Tenant source changed"); - } - final boolean gameplayAvailable; - final boolean allowPublicJoin; - final long entitlementVersion; - if (prepared.fence() != null) { - AccountHostingSubscriptionCurrentReceipt receipt = - consumers.hosting().readCurrent(prepared.fence(), observation); - gameplayAvailable = receipt.gameplayAvailable(); - allowPublicJoin = receipt.allowPublicJoin(); - entitlementVersion = receipt.entitlementVersion(); - } else { - DemoTenantEntitlementSnapshot demo = consumers.demos().revalidate(prepared.demo()); - gameplayAvailable = demo.gameplayAvailable(); - allowPublicJoin = demo.allowPublicJoin(); - entitlementVersion = demo.entitlementVersion(); - } - CanonicalJoinOperationEvidence policyBoundOperation = - accountJoinOperationRepository.bindCanonicalPolicyEvidence( - requestId, scope, callerBinding, allowPublicJoin, entitlementVersion); - Optional member = - accountTenantMembershipRepository.findFreshMembershipForUpdate( - scope.accountId(), scope.tenantId()); - boolean active = - member.filter(value -> "ACTIVE".equals(value.getLifecycleState())).isPresent(); - if ("PENDING".equals(policyBoundOperation.status()) - && (!gameplayAvailable || (!active && !allowPublicJoin))) { - String outcome = - gameplayAvailable - ? "PUBLIC_PRODUCTION_ADMISSION_DENIED" - : "TENANT_BILLING_BLOCKED"; + joinTransactionTemplate.execute(status -> { + lockCanonicalScopeAccount(scope); + requireCanonicalScopeFresh(consumers, scope); + CanonicalJoinOperationEvidence lockedOperation = + accountJoinOperationRepository + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow(); + if ("FAILED".equals(lockedOperation.status())) { + // Preparation precedes provider/target reads. Another exact attempt may have + // finished meanwhile, including before any policy evidence could be bound. + var retained = accountJoinOperationRepository.finishCanonicalFailure( - requestId, scope, callerBinding, outcome); - return new CanonicalJoinResult(outcome, null, false, false); - } - var committed = - consumers - .firstJoin() - .commitCanonicalJoin( - scope, - requestId, - callerBinding, - prepared.fence() == null ? null : consumers.hosting(), - prepared.fence(), - observation); - requireCanonicalScopeFresh(consumers, scope); - Optional currentMembership = - accountTenantMembershipRepository.findFreshMembershipForUpdate( - scope.accountId(), scope.tenantId()); - if ("COMMITTED".equals(policyBoundOperation.status())) { - // A committed exact retry returns its original operation proof after the current - // policy binding above. Membership may have changed since that proof was retained; - // expose only the current admission flag, never use the old proof as admission. - return new CanonicalJoinResult( - committed.outcome(), - committed.terminalProof(), - gameplayAvailable - && currentMembership - .map(AccountTenantMembership::isGameplayAdmissionAllowed) - .orElse(false), - true); - } - AccountTenantMembership committedMembership = currentMembership.orElseThrow(); - if (committedMembership.getMembershipVersion() - != committed.terminalProof().membershipVersion() - || committedMembership.getMembershipAuthorityGeneration() - != committed.terminalProof().membershipAuthorityGeneration()) { - throw new IllegalStateException( - "Canonical JOIN result differs from current membership"); - } - return new CanonicalJoinResult( - committed.outcome(), - committed.terminalProof(), - committedMembership.isGameplayAdmissionAllowed(), - false); - })); + requestId, scope, callerBinding, lockedOperation.outcome()); + return new CanonicalJoinResult(retained.outcome(), null, false, true); + } + SourceSelection current = + consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); + if (current.kind() != prepared.source().kind() + || !prepared.source().matches(current.checkpoint())) { + throw new AuthenticationException("ENTITLEMENT_UNAVAILABLE", "Tenant source changed"); + } + final boolean gameplayAvailable; + final boolean allowPublicJoin; + final long entitlementVersion; + if (prepared.fence() != null) { + AccountHostingSubscriptionCurrentReceipt receipt = + consumers.hosting().readCurrent(prepared.fence(), observation); + gameplayAvailable = receipt.gameplayAvailable(); + allowPublicJoin = receipt.allowPublicJoin(); + entitlementVersion = receipt.entitlementVersion(); + } else { + DemoTenantEntitlementSnapshot demo = consumers.demos().revalidate(prepared.demo()); + gameplayAvailable = demo.gameplayAvailable(); + allowPublicJoin = demo.allowPublicJoin(); + entitlementVersion = demo.entitlementVersion(); + } + CanonicalJoinOperationEvidence policyBoundOperation = + accountJoinOperationRepository.bindCanonicalPolicyEvidence( + requestId, scope, callerBinding, allowPublicJoin, entitlementVersion); + Optional member = + accountTenantMembershipRepository.findFreshMembershipForUpdate( + scope.accountId(), scope.tenantId()); + boolean active = + member.filter(value -> "ACTIVE".equals(value.getLifecycleState())).isPresent(); + if ("PENDING".equals(policyBoundOperation.status()) + && (!gameplayAvailable || (!active && !allowPublicJoin))) { + String outcome = + gameplayAvailable ? "PUBLIC_PRODUCTION_ADMISSION_DENIED" : "TENANT_BILLING_BLOCKED"; + accountJoinOperationRepository.finishCanonicalFailure( + requestId, scope, callerBinding, outcome); + return new CanonicalJoinResult(outcome, null, false, false); + } + var committed = + consumers + .firstJoin() + .commitCanonicalJoin( + scope, + requestId, + callerBinding, + prepared.fence() == null ? null : consumers.hosting(), + prepared.fence(), + observation); + requireCanonicalScopeFresh(consumers, scope); + Optional currentMembership = + accountTenantMembershipRepository.findFreshMembershipForUpdate( + scope.accountId(), scope.tenantId()); + if ("COMMITTED".equals(policyBoundOperation.status())) { + // A committed exact retry returns its original operation proof after the current + // policy binding above. Membership may have changed since that proof was retained; + // expose only the current admission flag, never use the old proof as admission. + return new CanonicalJoinResult( + committed.outcome(), + committed.terminalProof(), + gameplayAvailable + && currentMembership + .map(AccountTenantMembership::isGameplayAdmissionAllowed) + .orElse(false), + true); + } + AccountTenantMembership committedMembership = currentMembership.orElseThrow(); + if (committedMembership.getMembershipVersion() + != committed.terminalProof().membershipVersion() + || committedMembership.getMembershipAuthorityGeneration() + != committed.terminalProof().membershipAuthorityGeneration()) { + throw new IllegalStateException( + "Canonical JOIN result differs from current membership"); + } + return new CanonicalJoinResult( + committed.outcome(), + committed.terminalProof(), + committedMembership.isGameplayAdmissionAllowed(), + false); + })); } private void requireCanonicalScopeFresh( @@ -774,31 +768,28 @@ public void setAccountBootstrapRosterReadClient(AccountBootstrapRosterReadClient private BootstrapCharacterAuthority prepareBootstrapCharacterAuthority( CanonicalScopeConsumers consumers, CanonicalJoinScopeV2 scope) { return Objects.requireNonNull( - joinTransactionTemplate.execute( - status -> { - lockCanonicalScopeAccount(scope); - requireCanonicalScopeFresh(consumers, scope); - var membership = readBootstrapCharacterMembership(scope); - try { - SourceSelection source = - consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); - return new BootstrapCharacterAuthority( - source, - membership, - source.kind() == AccountTenantAuthorityEventRepository.SourceKind.NON_PAID_DEMO - ? consumers.demos().readCurrent(scope.tenantId()) - : null, - source.kind() == AccountTenantAuthorityEventRepository.SourceKind.PAID_HOSTING - ? consumers.hosting().prepareCurrentRead(scope.tenantId()) - : null, - consumers.clock().instant()); - } catch (RuntimeException failure) { - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", - "Bootstrap entitlement source is unavailable", - failure); - } - })); + joinTransactionTemplate.execute(status -> { + lockCanonicalScopeAccount(scope); + requireCanonicalScopeFresh(consumers, scope); + var membership = readBootstrapCharacterMembership(scope); + try { + SourceSelection source = + consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); + return new BootstrapCharacterAuthority( + source, + membership, + source.kind() == AccountTenantAuthorityEventRepository.SourceKind.NON_PAID_DEMO + ? consumers.demos().readCurrent(scope.tenantId()) + : null, + source.kind() == AccountTenantAuthorityEventRepository.SourceKind.PAID_HOSTING + ? consumers.hosting().prepareCurrentRead(scope.tenantId()) + : null, + consumers.clock().instant()); + } catch (RuntimeException failure) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Bootstrap entitlement source is unavailable", failure); + } + })); } private Optional @@ -806,14 +797,13 @@ private BootstrapCharacterAuthority prepareBootstrapCharacterAuthority( try { return accountTenantMembershipRepository .findFreshMembershipForUpdate(scope.accountId(), scope.tenantId()) - .map( - member -> - new AccountCanonicalPublicRealmScopeOwner.ExistingMembership( - member.getId(), - member.getLifecycleState(), - member.isGameplayAdmissionAllowed(), - member.getMembershipVersion(), - member.getMembershipAuthorityGeneration())); + .map(member -> + new AccountCanonicalPublicRealmScopeOwner.ExistingMembership( + member.getId(), + member.getLifecycleState(), + member.isGameplayAdmissionAllowed(), + member.getMembershipVersion(), + member.getMembershipAuthorityGeneration())); } catch (RuntimeException failure) { throw new AuthenticationException( "AUTH_UNAVAILABLE", "Bootstrap membership source is unavailable", failure); @@ -825,61 +815,58 @@ private void requireBootstrapCharacterAuthority( CanonicalJoinScopeV2 scope, BootstrapCharacterAuthority prepared, StripeHostingSubscriptionObserver.Result observation) { - joinTransactionTemplate.executeWithoutResult( - status -> { - lockCanonicalScopeAccount(scope); - requireCanonicalScopeFresh(consumers, scope); - var membership = readBootstrapCharacterMembership(scope); - if (!prepared.membership().equals(membership)) { - throw new AuthenticationException( - "AUTH_UNAVAILABLE", "Bootstrap membership changed during discovery"); - } - final boolean gameplayAvailable; - final boolean allowPublicJoin; - try { - SourceSelection current = - consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); - if (current.kind() != prepared.source().kind() - || !prepared.source().matches(current.checkpoint())) { - throw new IllegalStateException("Bootstrap entitlement source changed"); - } - if (prepared.fence() != null) { - var receipt = consumers.hosting().readCurrent(prepared.fence(), observation); - gameplayAvailable = receipt.gameplayAvailable(); - allowPublicJoin = receipt.allowPublicJoin(); - } else { - Instant currentTime = consumers.clock().instant(); - if (currentTime.isBefore(prepared.observedAt()) - || !currentTime.isBefore(prepared.observedAt().plusSeconds(15))) { - throw new IllegalStateException( - "Original bootstrap entitlement observation expired"); - } - var demo = consumers.demos().revalidate(prepared.demo()); - gameplayAvailable = demo.gameplayAvailable(); - allowPublicJoin = demo.allowPublicJoin(); - } - } catch (RuntimeException failure) { - throw new AuthenticationException( - "ENTITLEMENT_UNAVAILABLE", - "Bootstrap entitlement source is unavailable or changed", - failure); - } - if (!gameplayAvailable) { - throw new AuthenticationException( - "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); - } - if (membership.isEmpty() - || "INACTIVE".equals(membership.orElseThrow().lifecycleState())) { - throw new AuthenticationException( - allowPublicJoin ? "JOIN_REQUIRED" : "PUBLIC_PRODUCTION_ADMISSION_DENIED", - allowPublicJoin ? JOIN_REQUIRED_CHARACTERS_MESSAGE : "Public enrollment is closed"); - } - if (!"ACTIVE".equals(membership.orElseThrow().lifecycleState()) - || !membership.orElseThrow().gameplayAdmissionAllowed()) { - throw new AuthenticationException( - "PUBLIC_PRODUCTION_ADMISSION_DENIED", "Membership does not allow actor discovery"); + joinTransactionTemplate.executeWithoutResult(status -> { + lockCanonicalScopeAccount(scope); + requireCanonicalScopeFresh(consumers, scope); + var membership = readBootstrapCharacterMembership(scope); + if (!prepared.membership().equals(membership)) { + throw new AuthenticationException( + "AUTH_UNAVAILABLE", "Bootstrap membership changed during discovery"); + } + final boolean gameplayAvailable; + final boolean allowPublicJoin; + try { + SourceSelection current = + consumers.tenantSources().readCurrentSourceSelection(scope.tenantId()); + if (current.kind() != prepared.source().kind() + || !prepared.source().matches(current.checkpoint())) { + throw new IllegalStateException("Bootstrap entitlement source changed"); + } + if (prepared.fence() != null) { + var receipt = consumers.hosting().readCurrent(prepared.fence(), observation); + gameplayAvailable = receipt.gameplayAvailable(); + allowPublicJoin = receipt.allowPublicJoin(); + } else { + Instant currentTime = consumers.clock().instant(); + if (currentTime.isBefore(prepared.observedAt()) + || !currentTime.isBefore(prepared.observedAt().plusSeconds(15))) { + throw new IllegalStateException("Original bootstrap entitlement observation expired"); } - }); + var demo = consumers.demos().revalidate(prepared.demo()); + gameplayAvailable = demo.gameplayAvailable(); + allowPublicJoin = demo.allowPublicJoin(); + } + } catch (RuntimeException failure) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", + "Bootstrap entitlement source is unavailable or changed", + failure); + } + if (!gameplayAvailable) { + throw new AuthenticationException( + "TENANT_BILLING_BLOCKED", "Gameplay is not available for this tenant"); + } + if (membership.isEmpty() || "INACTIVE".equals(membership.orElseThrow().lifecycleState())) { + throw new AuthenticationException( + allowPublicJoin ? "JOIN_REQUIRED" : "PUBLIC_PRODUCTION_ADMISSION_DENIED", + allowPublicJoin ? JOIN_REQUIRED_CHARACTERS_MESSAGE : "Public enrollment is closed"); + } + if (!"ACTIVE".equals(membership.orElseThrow().lifecycleState()) + || !membership.orElseThrow().gameplayAdmissionAllowed()) { + throw new AuthenticationException( + "PUBLIC_PRODUCTION_ADMISSION_DENIED", "Membership does not allow actor discovery"); + } + }); } private record BootstrapCharacterAuthority( @@ -921,28 +908,27 @@ public List listBootstrapRealms( "AUTH_UNAVAILABLE", "Canonical public-realm scope source is unavailable"); } return owner.listRealmScopes(bootstrapToken, tenantSlug, worldSlug).stream() - .map( - retained -> { - var target = retained.target(); - var scope = retained.scope(); - return new BootstrapRealmDto( - scope.worldSlug(), - scope.realmSlug(), - scope.realmId(), - target.realmDisplayName(), - scope.tenantId(), - scope.gameInstanceId(), - scope.pointerVersion(), - scope.catalogRevision(), - scope.playableStateNamespaceId(), - PlayableStateScope.valueOf("PLAYABLE_STATE_SCOPE_" + scope.playableStateScope()) - .name(), - scope.playableStateScope(), - target.characterCreationPolicy(), - scope.evaluatedAt(), - scope.connectScopeExpiresAt(), - scope.connectScopeId()); - }) + .map(retained -> { + var target = retained.target(); + var scope = retained.scope(); + return new BootstrapRealmDto( + scope.worldSlug(), + scope.realmSlug(), + scope.realmId(), + target.realmDisplayName(), + scope.tenantId(), + scope.gameInstanceId(), + scope.pointerVersion(), + scope.catalogRevision(), + scope.playableStateNamespaceId(), + PlayableStateScope.valueOf("PLAYABLE_STATE_SCOPE_" + scope.playableStateScope()) + .name(), + scope.playableStateScope(), + target.characterCreationPolicy(), + scope.evaluatedAt(), + scope.connectScopeExpiresAt(), + scope.connectScopeId()); + }) .toList(); } @@ -1005,14 +991,13 @@ public List listBootstrapCharacters( .sorted( Comparator.comparing(AccountBootstrapRosterReadClient.Actor::displayName) .thenComparing(actor -> actor.characterId().toString())) - .map( - actor -> - new BootstrapCharacterDto( - actor.characterId().toString(), - actor.displayName(), - actor.level(), - scope.playableStateScope(), - published.currentTarget().characterCreationPolicy())) + .map(actor -> + new BootstrapCharacterDto( + actor.characterId().toString(), + actor.displayName(), + actor.level(), + scope.playableStateScope(), + published.currentTarget().characterCreationPolicy())) .toList(); } @@ -1125,30 +1110,26 @@ private void recordCanonicalJoinFailure( // reader rejects the same expired scope without rewriting its retained intent; preserve // that behavior when time crosses the boundary during provider I/O or the commit gate. if ("CONNECT_SCOPE_INVALID".equals(failureCode)) return; - joinTransactionTemplate.executeWithoutResult( - status -> { - lockCanonicalScopeAccount(scope); - Optional found = - accountJoinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId); - if (found.isEmpty() || !"PENDING".equals(found.orElseThrow().status())) return; - if ("CONNECT_SCOPE_MISMATCH".equals(failureCode)) { - accountJoinOperationRepository.finishCanonicalFailure( - requestId, scope, callerBinding, failureCode); - } else { - String retryCode = - List.of( - "ADMISSION_POINTER_UNAVAILABLE", - "ENTITLEMENT_UNAVAILABLE", - "AUTH_UNAVAILABLE") - .contains(failureCode) - ? failureCode - : "AUTH_UNAVAILABLE"; - String authorityAvailability = - "ENTITLEMENT_UNAVAILABLE".equals(retryCode) ? "UNAVAILABLE" : "NOT_EVALUATED"; - accountJoinOperationRepository.recordCanonicalAttemptFailure( - requestId, scope, callerBinding, authorityAvailability, retryCode); - } - }); + joinTransactionTemplate.executeWithoutResult(status -> { + lockCanonicalScopeAccount(scope); + Optional found = + accountJoinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId); + if (found.isEmpty() || !"PENDING".equals(found.orElseThrow().status())) return; + if ("CONNECT_SCOPE_MISMATCH".equals(failureCode)) { + accountJoinOperationRepository.finishCanonicalFailure( + requestId, scope, callerBinding, failureCode); + } else { + String retryCode = + List.of("ADMISSION_POINTER_UNAVAILABLE", "ENTITLEMENT_UNAVAILABLE", "AUTH_UNAVAILABLE") + .contains(failureCode) + ? failureCode + : "AUTH_UNAVAILABLE"; + String authorityAvailability = + "ENTITLEMENT_UNAVAILABLE".equals(retryCode) ? "UNAVAILABLE" : "NOT_EVALUATED"; + accountJoinOperationRepository.recordCanonicalAttemptFailure( + requestId, scope, callerBinding, authorityAvailability, retryCode); + } + }); } @Override @@ -1287,20 +1268,18 @@ public RealmAccessGrantResult getRealmAccessGrantForRuntime( return accountRealmAccessGrantRepository .findByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( accountId, tenantId, worldSlug, realmSlug) - .map( - grant -> - new RealmAccessGrantResult( - accountId, - tenantId, - worldSlug, - realmSlug, - grant.isGranted(), - grant.getGrantVersion(), - evaluatedAt.toString())) - .orElseGet( - () -> - new RealmAccessGrantResult( - accountId, tenantId, worldSlug, realmSlug, false, 0L, evaluatedAt.toString())); + .map(grant -> + new RealmAccessGrantResult( + accountId, + tenantId, + worldSlug, + realmSlug, + grant.isGranted(), + grant.getGrantVersion(), + evaluatedAt.toString())) + .orElseGet(() -> + new RealmAccessGrantResult( + accountId, tenantId, worldSlug, realmSlug, false, 0L, evaluatedAt.toString())); } @Override @@ -1313,18 +1292,17 @@ public RealmAccessGrantResult grantRealmAccess(RealmAccessGrantRequest request) accountRealmAccessGrantRepository .findByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( request.accountId(), request.tenantId(), request.worldSlug(), request.realmSlug()) - .orElseGet( - () -> { - AccountRealmAccessGrant created = new AccountRealmAccessGrant(); - created.setAccount(account); - created.setTenantId(request.tenantId()); - created.setWorldSlug(request.worldSlug()); - created.setRealmSlug(request.realmSlug()); - created.setGrantVersion(0L); - created.setGranted(true); - created.setCreatedAt(now); - return created; - }); + .orElseGet(() -> { + AccountRealmAccessGrant created = new AccountRealmAccessGrant(); + created.setAccount(account); + created.setTenantId(request.tenantId()); + created.setWorldSlug(request.worldSlug()); + created.setRealmSlug(request.realmSlug()); + created.setGrantVersion(0L); + created.setGranted(true); + created.setCreatedAt(now); + return created; + }); grant.setGrantVersion(grant.getGrantVersion() + 1L); grant.setGranted(true); grant.setGrantedBy(request.grantedBy()); @@ -1494,14 +1472,13 @@ public CredentialVerification verifyGameplayPrimaryCredential( } authentication .emailLoginChallenge() - .ifPresent( - challenge -> { - if (challenge.getId() == null - || challenge.getId() <= 0L - || !lockedAccount.getId().equals(challenge.getAccountId())) { - throw new IllegalStateException("Exact login challenge ownership is required"); - } - }); + .ifPresent(challenge -> { + if (challenge.getId() == null + || challenge.getId() <= 0L + || !lockedAccount.getId().equals(challenge.getAccountId())) { + throw new IllegalStateException("Exact login challenge ownership is required"); + } + }); return new CredentialVerification( authentication.account().getAccountUuid(), authentication.emailLoginChallenge().map(AccountEmailLoginChallenge::getId).orElse(null)); @@ -1592,10 +1569,9 @@ private PrimaryAuthentication authenticateAccountIdentity( String username, String password, boolean allowEmailLoginOtp) { Optional accountOpt = findAccountForAuthentication(username); Account account = - accountOpt.orElseThrow( - () -> - new AuthenticationException( - AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials")); + accountOpt.orElseThrow(() -> + new AuthenticationException( + AuthenticationErrorCodes.INVALID_CREDENTIALS, "Invalid credentials")); return authenticateAccountIdentity(account, password, allowEmailLoginOtp); } @@ -1615,11 +1591,10 @@ private PrimaryAuthentication authenticateAccountIdentity( emailLoginChallenge = activeEmailLoginChallenge(account); } if (emailLoginChallenge - .filter( - challenge -> - work == null - ? matchesEmailLoginOtp(challenge, password) - : work.verify(challenge.getCodeHash())) + .filter(challenge -> + work == null + ? matchesEmailLoginOtp(challenge, password) + : work.verify(challenge.getCodeHash())) .isPresent()) { requireAuthenticationEligible(account); return new PrimaryAuthentication(account, emailLoginChallenge); @@ -1837,11 +1812,10 @@ public Map listPresenceVisibilityPolicies return Map.of(); } return profileRepository.findByTenantIdAndAccountIds(tenantId, accountIds).stream() - .filter( - profile -> - profile.getAccount() != null - && profile.getAccount().getId() != null - && profile.getPresenceVisibilityPolicy() != null) + .filter(profile -> + profile.getAccount() != null + && profile.getAccount().getId() != null + && profile.getPresenceVisibilityPolicy() != null) .collect( java.util.stream.Collectors.toUnmodifiableMap( profile -> profile.getAccount().getId(), @@ -1869,9 +1843,8 @@ public ProfileDto updateProfile(UpdateProfileRequest request) { profile.setBio(request.bio()); profile.setPresenceVisibilityPolicy(request.presenceVisibilityPolicy()); profile = profileRepository.save(profile); - runAfterCommit( - () -> - notificationService.sendNotification(request.tenantId(), accountId, "Profile updated")); + runAfterCommit(() -> + notificationService.sendNotification(request.tenantId(), accountId, "Profile updated")); return projectProfile(profile, request.tenantId(), accountId); } @@ -2011,14 +1984,12 @@ public void requestPasswordReset(PasswordResetRequest request) { token.setExpiresAt(java.time.LocalDateTime.now().plusHours(1)); passwordResetTokenRepository.save(token); String url = String.format(mailProperties.getResetUrl(), token.getToken()); - runAfterCommit( - () -> - sendRecoveryEmailSafely( - () -> - emailService.sendEmail( - account.getEmail(), - "Password Reset", - String.format(readTemplate("password-reset.txt"), url)))); + runAfterCommit(() -> + sendRecoveryEmailSafely(() -> + emailService.sendEmail( + account.getEmail(), + "Password Reset", + String.format(readTemplate("password-reset.txt"), url)))); } @Override @@ -2033,10 +2004,8 @@ public void completePasswordReset(CompletePasswordResetRequest request) { String tokenHash = sha256Hex(request.token()); String candidatePasswordVerifier = hashPassword(request.newPassword()); PasswordResetAttempt attempt = - passwordResetOwnerTransaction.execute( - status -> - completePasswordResetInOwnerTransaction( - request, tokenHash, candidatePasswordVerifier)); + passwordResetOwnerTransaction.execute(status -> + completePasswordResetInOwnerTransaction(request, tokenHash, candidatePasswordVerifier)); if (attempt == null) { throw new IllegalStateException("Password-reset owner transaction returned no result"); } @@ -2049,14 +2018,11 @@ public void completePasswordReset(CompletePasswordResetRequest request) { PasswordResetReceipt committed = Objects.requireNonNull(attempt.receipt(), "Committed password-reset receipt is required"); PasswordResetReceipt postCommitReadback = - passwordResetOwnerTransaction.execute( - status -> - passwordResetOperationRepository - .findByTokenHash(tokenHash) - .orElseThrow( - () -> - new IllegalStateException( - "Password-reset receipt disappeared after commit"))); + passwordResetOwnerTransaction.execute(status -> + passwordResetOperationRepository + .findByTokenHash(tokenHash) + .orElseThrow(() -> + new IllegalStateException("Password-reset receipt disappeared after commit"))); if (!committed.equals(postCommitReadback)) { throw new IllegalStateException("Password-reset committed receipt readback differs"); } @@ -2075,17 +2041,12 @@ private PasswordResetAttempt completePasswordResetInOwnerTransaction( Long accountId = resolvedReceipt .map(PasswordResetReceipt::accountId) - .orElseGet( - () -> - resolvedIntentAccountId.orElseGet( - () -> - resolvedToken - .map( - token -> - token.getAccount() == null - ? null - : token.getAccount().getId()) - .orElse(null))); + .orElseGet(() -> + resolvedIntentAccountId.orElseGet(() -> + resolvedToken + .map( + token -> token.getAccount() == null ? null : token.getAccount().getId()) + .orElse(null))); if (accountId == null || accountId <= 0L) { throw new IllegalArgumentException("Invalid token"); } @@ -2782,15 +2743,12 @@ public void sendUsernameReminder(UsernameRecoveryRequest request) { return; } Account account = accountOptional.get(); - runAfterCommit( - () -> - sendRecoveryEmailSafely( - () -> - emailService.sendEmail( - account.getEmail(), - "Username Reminder", - String.format( - readTemplate("username-reminder.txt"), account.getUsername())))); + runAfterCommit(() -> + sendRecoveryEmailSafely(() -> + emailService.sendEmail( + account.getEmail(), + "Username Reminder", + String.format(readTemplate("username-reminder.txt"), account.getUsername())))); } private void sendRecoveryEmailSafely(Runnable delivery) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyServiceImpl.java index ff3672ab63..61d11eabe2 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/VirtualCurrencyServiceImpl.java @@ -39,16 +39,15 @@ public long addCurrency(Long tenantId, Long accountId, String currencyCode, Long CurrencyBalance balance = balanceRepository .findByTenantIdAndAccountIdAndCurrencyCode(tenantId, accountId, currencyCode) - .orElseGet( - () -> { - Account account = requireAccountMembership(tenantId, accountId); - CurrencyBalance cb = new CurrencyBalance(); - cb.setAccount(account); - cb.setCurrencyCode(currencyCode); - cb.setBalance(0L); - cb.setTenantId(tenantId); - return cb; - }); + .orElseGet(() -> { + Account account = requireAccountMembership(tenantId, accountId); + CurrencyBalance cb = new CurrencyBalance(); + cb.setAccount(account); + cb.setCurrencyCode(currencyCode); + cb.setBalance(0L); + cb.setTenantId(tenantId); + return cb; + }); balance.setBalance(balance.getBalance() + amount); balanceRepository.save(balance); return balance.getBalance(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java index 67278ace16..f4ee504d3a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java @@ -139,22 +139,21 @@ T withCurrentAccountSources(String compactJwt, Function action) boolean readHeldOriginalDraft(DraftAuthorizationFenceBinding original) { outsideSql(); return Objects.requireNonNull( - transaction.execute( - ignored -> { - var retained = fences.readOriginalBinding(original.operationId()); - if (retained.isEmpty()) return false; - if (!Arrays.equals(retained.get().canonicalBytes(), original.canonicalBytes())) - throw io.grpc.Status.FAILED_PRECONDITION.asRuntimeException(); - var order = fences.read(original); - if (order.ordering() != DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER - || order.reservedAt() == null - || order.orderedAt() == null - || !Arrays.equals(order.binding(), original.canonicalBytes()) - || fences.readSettlement(original) - != DraftAuthorizationFenceRepository.Settlement.PENDING) - throw io.grpc.Status.FAILED_PRECONDITION.asRuntimeException(); - return true; - })); + transaction.execute(ignored -> { + var retained = fences.readOriginalBinding(original.operationId()); + if (retained.isEmpty()) return false; + if (!Arrays.equals(retained.get().canonicalBytes(), original.canonicalBytes())) + throw io.grpc.Status.FAILED_PRECONDITION.asRuntimeException(); + var order = fences.read(original); + if (order.ordering() != DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER + || order.reservedAt() == null + || order.orderedAt() == null + || !Arrays.equals(order.binding(), original.canonicalBytes()) + || fences.readSettlement(original) + != DraftAuthorizationFenceRepository.Settlement.PENDING) + throw io.grpc.Status.FAILED_PRECONDITION.asRuntimeException(); + return true; + })); } /** No transport or World mutation: original Account reservation/order is the only effect. */ @@ -208,46 +207,45 @@ private T withCurrentScope( String tokenHash = AccountControlUiIssuanceRepository.hash(compactJwt.getBytes(StandardCharsets.US_ASCII)); byte[] exactRegistry = registry.readActive(tokenHash); - return transaction.execute( - ignored -> { - var stored = operations.findToken(tokenHash); - if (stored == null - || stored.scopeKind() != scopeKind - || (scopeKind == AccountControlUiAuthority.ScopeKind.TENANT - && !selectedTenant.equals(stored.tenantId())) - || !"COMMITTED".equals(stored.status) - || !Arrays.equals(stored.activeRegistry, exactRegistry) - || !Arrays.equals( - stored.claims, AccountControlUiAuthority.canonical(signed.claims.claims()))) { - throw denied(); - } - requireSignerIdentity(stored, signed); - requireAcceptedSignerKey(stored, acceptedKey); - signers.requireOriginal(stored.signerReceipt); - var current = - switch (scopeKind) { - case ACCOUNT -> authority.captureAccount(stored.accountId); - case TENANT -> authority.capture(stored.accountId, selectedTenant, environment); - }; - if (current.scopeKind() != scopeKind) throw denied(); - if (scopeKind == AccountControlUiAuthority.ScopeKind.ACCOUNT) { - requireCurrentAccountClaims(current, signed.claims.claims()); - } - if (!Arrays.equals(current.evidence(), stored.sources)) { - throw denied(); - } - var committed = operations.requireCommitted(stored); - if (!committed.tokenHash().equals(tokenHash)) { - throw denied(); - } - if (scopeKind == AccountControlUiAuthority.ScopeKind.ACCOUNT) { - var original = operations.findToken(tokenHash); - if (!sameCommittedOperation(stored, original) - || !Arrays.equals(original.activeRegistry, exactRegistry)) throw denied(); - } - requireCurrentOriginalToken(stored); - return action.apply(new Current(stored, current)); - }); + return transaction.execute(ignored -> { + var stored = operations.findToken(tokenHash); + if (stored == null + || stored.scopeKind() != scopeKind + || (scopeKind == AccountControlUiAuthority.ScopeKind.TENANT + && !selectedTenant.equals(stored.tenantId())) + || !"COMMITTED".equals(stored.status) + || !Arrays.equals(stored.activeRegistry, exactRegistry) + || !Arrays.equals( + stored.claims, AccountControlUiAuthority.canonical(signed.claims.claims()))) { + throw denied(); + } + requireSignerIdentity(stored, signed); + requireAcceptedSignerKey(stored, acceptedKey); + signers.requireOriginal(stored.signerReceipt); + var current = + switch (scopeKind) { + case ACCOUNT -> authority.captureAccount(stored.accountId); + case TENANT -> authority.capture(stored.accountId, selectedTenant, environment); + }; + if (current.scopeKind() != scopeKind) throw denied(); + if (scopeKind == AccountControlUiAuthority.ScopeKind.ACCOUNT) { + requireCurrentAccountClaims(current, signed.claims.claims()); + } + if (!Arrays.equals(current.evidence(), stored.sources)) { + throw denied(); + } + var committed = operations.requireCommitted(stored); + if (!committed.tokenHash().equals(tokenHash)) { + throw denied(); + } + if (scopeKind == AccountControlUiAuthority.ScopeKind.ACCOUNT) { + var original = operations.findToken(tokenHash); + if (!sameCommittedOperation(stored, original) + || !Arrays.equals(original.activeRegistry, exactRegistry)) throw denied(); + } + requireCurrentOriginalToken(stored); + return action.apply(new Current(stored, current)); + }); } /** @@ -289,29 +287,28 @@ T withCurrentCommitted( var acceptedKey = readAcceptedSignerKey(keyId); requireAcceptedSignerKey(original, acceptedKey); byte[] exactRegistry = registry.readActive(original.tokenHash); - return transaction.execute( - ignored -> { - var observed = operations.findTokenJti(tokenJti); - if (!sameCommittedOperation(original, observed) - || !Arrays.equals(observed.activeRegistry, exactRegistry)) { - throw denied(); - } - requireStoredActorIdentity(observed, actorAccountId, selectedTenant, tokenJti); - signers.requireOriginal(observed.signerReceipt); - var current = authority.capture(actorAccountId, selectedTenant, environment); - if (!Arrays.equals(current.evidence(), observed.sources) - || !clock.instant().isBefore(observed.expiresAt)) { - throw denied(); - } - operations.requireCommitted(observed); - var committed = operations.findTokenJti(tokenJti); - if (!sameCommittedOperation(observed, committed) - || !Arrays.equals(committed.activeRegistry, exactRegistry)) { - throw denied(); - } - requireCurrentOriginalToken(committed); - return action.apply(new Current(committed, current)); - }); + return transaction.execute(ignored -> { + var observed = operations.findTokenJti(tokenJti); + if (!sameCommittedOperation(original, observed) + || !Arrays.equals(observed.activeRegistry, exactRegistry)) { + throw denied(); + } + requireStoredActorIdentity(observed, actorAccountId, selectedTenant, tokenJti); + signers.requireOriginal(observed.signerReceipt); + var current = authority.capture(actorAccountId, selectedTenant, environment); + if (!Arrays.equals(current.evidence(), observed.sources) + || !clock.instant().isBefore(observed.expiresAt)) { + throw denied(); + } + operations.requireCommitted(observed); + var committed = operations.findTokenJti(tokenJti); + if (!sameCommittedOperation(observed, committed) + || !Arrays.equals(committed.activeRegistry, exactRegistry)) { + throw denied(); + } + requireCurrentOriginalToken(committed); + return action.apply(new Current(committed, current)); + }); } /** @@ -343,35 +340,34 @@ T withCurrentAccountCommitted( var acceptedKey = readAcceptedSignerKey(keyId); requireAcceptedSignerKey(original, acceptedKey); byte[] exactRegistry = registry.readActive(original.tokenHash); - return transaction.execute( - ignored -> { - var observed = operations.findTokenJti(tokenJti); - if (!sameCommittedOperation(original, observed) - || !Arrays.equals(observed.activeRegistry, exactRegistry)) throw denied(); - Map claims = AccountControlUiIssuanceRepository.object(observed.claims); - ControlUiJwtProfileValidator.validateClaims(claims, 1); - if (!actorAccountId.toString().equals(claims.get("sub")) - || !actorAccountId.toString().equals(claims.get("accountId")) - || !tokenJti.toString().equals(claims.get("jti")) - || !Long.toString(observed.issuedAt.getEpochSecond()) - .equals(String.valueOf(claims.get("iat"))) - || !Long.toString(observed.issuedAt.getEpochSecond()) - .equals(String.valueOf(claims.get("nbf"))) - || !Long.toString(observed.expiresAt.getEpochSecond()) - .equals(String.valueOf(claims.get("exp")))) throw denied(); - signers.requireOriginal(observed.signerReceipt); - var current = authority.captureAccount(actorAccountId); - requireCurrentAccountClaims(current, claims); - if (!Arrays.equals(current.evidence(), observed.sources)) throw denied(); - var result = operations.requireCommitted(observed); - if (!observed.tokenHash.equals(result.tokenHash())) throw denied(); - fences.lockProducerSourcesNowait(current.sources()); - var committed = operations.findTokenJti(tokenJti); - if (!sameCommittedOperation(observed, committed) - || !Arrays.equals(committed.activeRegistry, exactRegistry)) throw denied(); - requireCurrentOriginalToken(committed); - return action.apply(new Current(committed, current)); - }); + return transaction.execute(ignored -> { + var observed = operations.findTokenJti(tokenJti); + if (!sameCommittedOperation(original, observed) + || !Arrays.equals(observed.activeRegistry, exactRegistry)) throw denied(); + Map claims = AccountControlUiIssuanceRepository.object(observed.claims); + ControlUiJwtProfileValidator.validateClaims(claims, 1); + if (!actorAccountId.toString().equals(claims.get("sub")) + || !actorAccountId.toString().equals(claims.get("accountId")) + || !tokenJti.toString().equals(claims.get("jti")) + || !Long.toString(observed.issuedAt.getEpochSecond()) + .equals(String.valueOf(claims.get("iat"))) + || !Long.toString(observed.issuedAt.getEpochSecond()) + .equals(String.valueOf(claims.get("nbf"))) + || !Long.toString(observed.expiresAt.getEpochSecond()) + .equals(String.valueOf(claims.get("exp")))) throw denied(); + signers.requireOriginal(observed.signerReceipt); + var current = authority.captureAccount(actorAccountId); + requireCurrentAccountClaims(current, claims); + if (!Arrays.equals(current.evidence(), observed.sources)) throw denied(); + var result = operations.requireCommitted(observed); + if (!observed.tokenHash.equals(result.tokenHash())) throw denied(); + fences.lockProducerSourcesNowait(current.sources()); + var committed = operations.findTokenJti(tokenJti); + if (!sameCommittedOperation(observed, committed) + || !Arrays.equals(committed.activeRegistry, exactRegistry)) throw denied(); + requireCurrentOriginalToken(committed); + return action.apply(new Current(committed, current)); + }); } private static void requireCurrentAccountClaims( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordination.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordination.java index bb45d3cbe4..3dec8ca30d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordination.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordination.java @@ -43,18 +43,17 @@ public byte[] readActive(String tokenHash) { /** Exact readback for the owner's protected delivery workflow. */ public void requireExactActive(String tokenHash, byte[] exactActive, long expiryMillis) { outsideSql(); - withConnection( - commands -> { - byte[] key = key(tokenHash); - if (!Arrays.equals(exactActive, commands.get(key))) { - throw denied(); - } - Long expiry = commands.pexpiretime(key); - if (expiry == null || expiry != expiryMillis) { - throw denied(); - } - return null; - }); + withConnection(commands -> { + byte[] key = key(tokenHash); + if (!Arrays.equals(exactActive, commands.get(key))) { + throw denied(); + } + Long expiry = commands.pexpiretime(key); + if (expiry == null || expiry != expiryMillis) { + throw denied(); + } + return null; + }); } /** Only package-local owner workflow may register a non-authorizing pending candidate. */ @@ -76,19 +75,18 @@ Receipt revoke(AccountControlUiIssuanceRepository.Stored original) { outsideSql(); byte[] replacement = AccountControlUiIssuanceRepository.revokedRegistry(original); byte[] expected = - withConnection( - commands -> { - byte[] observed = commands.get(key(original.tokenHash)); - Long expiry = commands.pexpiretime(key(original.tokenHash)); - if (expiry == null - || expiry != original.expiryMillis() - || (!Arrays.equals(observed, original.pendingRegistry) - && !Arrays.equals(observed, original.activeRegistry) - && !Arrays.equals(observed, replacement))) { - throw denied(); - } - return observed; - }); + withConnection(commands -> { + byte[] observed = commands.get(key(original.tokenHash)); + Long expiry = commands.pexpiretime(key(original.tokenHash)); + if (expiry == null + || expiry != original.expiryMillis() + || (!Arrays.equals(observed, original.pendingRegistry) + && !Arrays.equals(observed, original.activeRegistry) + && !Arrays.equals(observed, replacement))) { + throw denied(); + } + return observed; + }); return cas(original.tokenHash, expected, replacement, original.expiryMillis()); } @@ -120,53 +118,52 @@ private Receipt cas(String tokenHash, byte[] expected, byte[] replacement, long } catch (java.io.IOException | RuntimeException failure) { throw denied(); } - return withConnection( - commands -> { - byte[] key = key(tokenHash); - String sha = commands.scriptLoad(source); - if (!digest("SHA-1", source).equals(sha)) { - throw denied(); - } - Long outcome = - commands.evalsha( - sha, - ScriptOutputType.INTEGER, - new byte[][] {key}, - expected, - replacement, - Long.toString(expiryMillis).getBytes(StandardCharsets.US_ASCII)); - if (outcome == null || (outcome != 0L && outcome != 1L)) { - throw denied(); - } - List counts = - commands.dispatch( - WaitAof.INSTANCE, - new ArrayOutput<>(ByteArrayCodec.INSTANCE), - new CommandArgs<>(ByteArrayCodec.INSTANCE) - .add(acknowledgements.requiredLocalAofCount()) - .add(acknowledgements.requiredReplicaAofCount()) - .add(acknowledgements.timeoutMillis())); - if (counts == null - || counts.size() != 2 - || !(counts.get(0) instanceof Long local) - || !(counts.get(1) instanceof Long replicas) - || local < acknowledgements.requiredLocalAofCount() - || replicas < acknowledgements.requiredReplicaAofCount()) { - throw denied(); - } - Long expiry = commands.pexpiretime(key); - if (!Arrays.equals(replacement, commands.get(key)) - || expiry == null - || expiry != expiryMillis) { - throw denied(); - } - return new Receipt( - tokenHash, - digest("SHA-256", replacement), - expiryMillis, - acknowledgements.requiredLocalAofCount(), - acknowledgements.requiredReplicaAofCount()); - }); + return withConnection(commands -> { + byte[] key = key(tokenHash); + String sha = commands.scriptLoad(source); + if (!digest("SHA-1", source).equals(sha)) { + throw denied(); + } + Long outcome = + commands.evalsha( + sha, + ScriptOutputType.INTEGER, + new byte[][] {key}, + expected, + replacement, + Long.toString(expiryMillis).getBytes(StandardCharsets.US_ASCII)); + if (outcome == null || (outcome != 0L && outcome != 1L)) { + throw denied(); + } + List counts = + commands.dispatch( + WaitAof.INSTANCE, + new ArrayOutput<>(ByteArrayCodec.INSTANCE), + new CommandArgs<>(ByteArrayCodec.INSTANCE) + .add(acknowledgements.requiredLocalAofCount()) + .add(acknowledgements.requiredReplicaAofCount()) + .add(acknowledgements.timeoutMillis())); + if (counts == null + || counts.size() != 2 + || !(counts.get(0) instanceof Long local) + || !(counts.get(1) instanceof Long replicas) + || local < acknowledgements.requiredLocalAofCount() + || replicas < acknowledgements.requiredReplicaAofCount()) { + throw denied(); + } + Long expiry = commands.pexpiretime(key); + if (!Arrays.equals(replacement, commands.get(key)) + || expiry == null + || expiry != expiryMillis) { + throw denied(); + } + return new Receipt( + tokenHash, + digest("SHA-256", replacement), + expiryMillis, + acknowledgements.requiredLocalAofCount(), + acknowledgements.requiredReplicaAofCount()); + }); } private T withConnection( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java index 704ffcd74b..97054b7639 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifier.java @@ -272,19 +272,18 @@ private T verifyObserved( String tokenHash = sha256(compactBytes); byte[] activeRegistry = registry.readActive(tokenHash); T result = - accountTransaction.execute( - ignored -> { - var issuance = - verifyOwnerState( - tokenHash, - scopeKind, - selectedTenant, - signed, - publicSourcePin, - currentJwks, - activeRegistry); - return action.apply(issuance, signed.claims()); - }); + accountTransaction.execute(ignored -> { + var issuance = + verifyOwnerState( + tokenHash, + scopeKind, + selectedTenant, + signed, + publicSourcePin, + currentJwks, + activeRegistry); + return action.apply(issuance, signed.claims()); + }); if (result == null) throw denied(); return result; } @@ -679,17 +678,16 @@ private void requireClaimsCurrent( source .account() .accountSecurityCutoff() - .ifPresent( - cutoff -> - expectedTuple.put( - "accountSecurityCutoff", - Map.of( - "accountAuthorityGeneration", - cutoff.accountAuthorityGeneration(), - "outboxStreamKey", - cutoff.outboxStreamKey(), - "outboxSequence", - cutoff.outboxSequence()))); + .ifPresent(cutoff -> + expectedTuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + cutoff.accountAuthorityGeneration(), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + cutoff.outboxSequence()))); if (tenantEvent.tenantBillingSequence() > 0L) { expectedTuple.put( "tenantBillingCutoff", @@ -784,13 +782,12 @@ private static Map object(Object value) { throw denied(); } Map result = new LinkedHashMap<>(); - map.forEach( - (key, item) -> { - if (!(key instanceof String text)) { - throw denied(); - } - result.put(text, item); - }); + map.forEach((key, item) -> { + if (!(key instanceof String text)) { + throw denied(); + } + result.put(text, item); + }); return result; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java index c34941c4a0..bd6e00b2d6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepository.java @@ -544,14 +544,13 @@ private void requireTransaction() { || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { throw denied(); } - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw denied(); - } - }); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw denied(); + } + }); } static final class Stored { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java index b97cd3d450..238e1fe369 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java @@ -131,60 +131,57 @@ private IssuedCredential issueInternal(Invocation request) { byte[] exactRequest = AccountControlUiAuthority.canonical(requestFields); try { InitialPreparation initial = - transaction.execute( - ignored -> { - var existing = operations.findRequest(request.requestId); - if (existing != null) { - requireRequest(existing, request, peer.uri(), exactRequest); - return new InitialPreparation(current(existing, environment), null); - } - // Preserve canonical tenant -> Account owner order before OTP/advisory - // authentication. - java.util.Optional tenantSource = - request.scopeKind == AccountControlUiAuthority.ScopeKind.TENANT - ? java.util.Optional.of( - authority.captureInitial( - request.tenantId.orElseThrow(), environment.orElseThrow())) - : java.util.Optional.empty(); - tenantSource.ifPresent(value -> fences.lockProducerSourcesNowait(value.sources())); - AccountServiceImpl.ControlUiPrimaryIdentity authenticated; - try { - authenticated = - primaryAuthentication.authenticateControlUiPrimaryIdentity( - email, request.secret); - } catch (AuthenticationException denial) { - // Only primary denial commits attempt accounting. No signer/issuance work - // follows. - return new InitialPreparation( - null, new PrimaryDenial(denial.getCode(), denial.getMessage())); - } - var source = - tenantSource.orElseGet( - () -> authority.captureAccount(authenticated.accountId())); - if (!source.actor().equals(authenticated.accountId()) - || source.scopeKind() != request.scopeKind) { - throw denied(); - } - if (source.scopeKind() == AccountControlUiAuthority.ScopeKind.ACCOUNT) { - fences.lockProducerSourcesNowait(source.sources()); - } - var signer = signers.captureCurrent(); - String macKey = cryptography.currentKeyId(); - String requestDigest = cryptography.requestDigest(macKey, exactRequest); - var stored = - operations.prepare( - request.requestId, - peer.uri(), - request.callerContextId, - macKey, - requestDigest, - authenticated, - source, - signer, - Instant.ofEpochSecond(clock.instant().getEpochSecond()), - sessionSafetyMarginMillis); - return new InitialPreparation(new Prepared(stored, source, signer), null); - }); + transaction.execute(ignored -> { + var existing = operations.findRequest(request.requestId); + if (existing != null) { + requireRequest(existing, request, peer.uri(), exactRequest); + return new InitialPreparation(current(existing, environment), null); + } + // Preserve canonical tenant -> Account owner order before OTP/advisory + // authentication. + java.util.Optional tenantSource = + request.scopeKind == AccountControlUiAuthority.ScopeKind.TENANT + ? java.util.Optional.of( + authority.captureInitial( + request.tenantId.orElseThrow(), environment.orElseThrow())) + : java.util.Optional.empty(); + tenantSource.ifPresent(value -> fences.lockProducerSourcesNowait(value.sources())); + AccountServiceImpl.ControlUiPrimaryIdentity authenticated; + try { + authenticated = + primaryAuthentication.authenticateControlUiPrimaryIdentity(email, request.secret); + } catch (AuthenticationException denial) { + // Only primary denial commits attempt accounting. No signer/issuance work + // follows. + return new InitialPreparation( + null, new PrimaryDenial(denial.getCode(), denial.getMessage())); + } + var source = + tenantSource.orElseGet(() -> authority.captureAccount(authenticated.accountId())); + if (!source.actor().equals(authenticated.accountId()) + || source.scopeKind() != request.scopeKind) { + throw denied(); + } + if (source.scopeKind() == AccountControlUiAuthority.ScopeKind.ACCOUNT) { + fences.lockProducerSourcesNowait(source.sources()); + } + var signer = signers.captureCurrent(); + String macKey = cryptography.currentKeyId(); + String requestDigest = cryptography.requestDigest(macKey, exactRequest); + var stored = + operations.prepare( + request.requestId, + peer.uri(), + request.callerContextId, + macKey, + requestDigest, + authenticated, + source, + signer, + Instant.ofEpochSecond(clock.instant().getEpochSecond()), + sessionSafetyMarginMillis); + return new InitialPreparation(new Prepared(stored, source, signer), null); + }); if (initial == null) { throw denied(); } @@ -218,13 +215,12 @@ private IssuedCredential issueInternal(Invocation request) { } byte[] binding = envelopeBinding(original, tokenHash); byte[] encrypted = cryptography.seal(credential, binding, original.recoveryExpiry); - transaction.execute( - ignored -> { - var stillCurrent = current(original, environment); - operations.bindCandidate( - stillCurrent.stored, tokenHash, encrypted, binding, stillCurrent.signer); - return null; - }); + transaction.execute(ignored -> { + var stillCurrent = current(original, environment); + operations.bindCandidate( + stillCurrent.stored, tokenHash, encrypted, binding, stillCurrent.signer); + return null; + }); }); } var candidate = transaction.execute(ignored -> current(original, environment).stored); @@ -237,18 +233,16 @@ private IssuedCredential issueInternal(Invocation request) { registry.registerPending( candidate.tokenHash, candidate.pendingRegistry, candidate.expiryMillis()); committed = - transaction.execute( - ignored -> { - var observed = current(candidate, environment); - return operations.commit(observed.stored, pending); - }); + transaction.execute(ignored -> { + var observed = current(candidate, environment); + return operations.commit(observed.stored, pending); + }); } else if ("COMMITTED".equals(candidate.status)) { committed = - transaction.execute( - ignored -> { - current(candidate, environment); - return operations.requireCommitted(candidate); - }); + transaction.execute(ignored -> { + current(candidate, environment); + return operations.requireCommitted(candidate); + }); } else { throw denied(); } @@ -257,11 +251,10 @@ private IssuedCredential issueInternal(Invocation request) { } registry.activate(committed); var envelope = - transaction.execute( - ignored -> { - current(committed.stored, environment); - return operations.envelope(committed.stored); - }); + transaction.execute(ignored -> { + current(committed.stored, environment); + return operations.envelope(committed.stored); + }); if (envelope == null || !Arrays.equals( envelope.binding(), envelopeBinding(committed.stored, committed.tokenHash()))) { @@ -308,11 +301,10 @@ private IssuedCredential issueInternal(Invocation request) { transaction.execute(ignored -> operations.beginRecoveryFailure(permanent.original)); if (failed != null && "REVOKING".equals(failed.status)) { var receipt = registry.revoke(failed); - transaction.execute( - ignored -> { - operations.finishRecoveryFailure(failed, receipt); - return null; - }); + transaction.execute(ignored -> { + operations.finishRecoveryFailure(failed, receipt); + return null; + }); } throw denied(); } finally { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java index e52e3279c9..b4c73b00ba 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationReadService.java @@ -42,11 +42,10 @@ public void requireHeld(GameLogicIntakeAuthorizationReadEvidence.Request request || TransactionSynchronizationManager.isSynchronizationActive()) throw Status.FAILED_PRECONDITION.asRuntimeException(); try { - transaction.execute( - ignored -> { - repository.readHeld(request.binding(), namespace); - return null; - }); + transaction.execute(ignored -> { + repository.readHeld(request.binding(), namespace); + return null; + }); } catch (StatusRuntimeException failure) { throw sanitized(Status.fromCode(failure.getStatus().getCode())); } catch (IllegalArgumentException | IllegalStateException changed) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java index 2557d1aded..9660a3b043 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRepository.java @@ -560,13 +560,12 @@ private void requireTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) throw new IllegalStateException("Writable Account owner transaction required"); - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) - throw new IllegalStateException( - "Writable READ_COMMITTED Account owner transaction required"); - }); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) + throw new IllegalStateException( + "Writable READ_COMMITTED Account owner transaction required"); + }); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadService.java index 5db667b9ee..6b82ab83e8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadService.java @@ -55,11 +55,10 @@ public GameLogicIntakeSourceReadScope readSourceScope( var active = registry.readActive(current.tokenHash()); if (!current.registryDigest().equals(DraftAuthorizationFenceBinding.digest(active))) throw Status.FAILED_PRECONDITION.asRuntimeException(); - return transaction.execute( - ignored -> { - repository.readSourceScope(scope, current, clock.instant()); - return scope; - }); + return transaction.execute(ignored -> { + repository.readSourceScope(scope, current, clock.instant()); + return scope; + }); } public GameLogicIntakeAuthorizationBinding readFinalizedIntake( @@ -68,11 +67,10 @@ public GameLogicIntakeAuthorizationBinding readFinalizedIntake( requireReader(intendedReader, purpose, "game-logic-service"); Objects.requireNonNull(authorization); outsideSql(); - return transaction.execute( - ignored -> { - repository.readFinalizedSourceScope(authorization, namespace); - return authorization; - }); + return transaction.execute(ignored -> { + repository.readFinalizedSourceScope(authorization, namespace); + return authorization; + }); } private void requireReader(String reader, String purpose, String service) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java index db10824751..23a9cb8624 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java @@ -79,10 +79,9 @@ public InitialGameplayLoginResult authenticate( String normalizedEmail = EmailCanonicalization.normalize(request.email()); LoginPreparation preparation = - accountTransaction.execute( - status -> - prepareOrReplay( - request, normalizedEmail, verifiedGameSessionWorkload, credentialVerifier)); + accountTransaction.execute(status -> + prepareOrReplay( + request, normalizedEmail, verifiedGameSessionWorkload, credentialVerifier)); if (preparation == null) throw unavailable(); if (preparation.authenticationFailure() != null) { throw preparation.authenticationFailure(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java index 700723c593..d53328319f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjection.java @@ -163,168 +163,160 @@ private SelectedSnapshot readSelectedSnapshot(UUID accountId, UUID tenantId) { requireAccountId(tenantId); if (selectedOwner == null) throw new ProjectionUnavailableException(); SelectedSnapshot result = - accountTransaction.execute( - status -> { - // The source and composite owners both take Account first; the composite fixes all - // four scopes. - var source = - sourceEvidence.readCurrentIssuerAccountSources( - GameSessionAccountDelegationProfile.ISSUER, accountId); - var composite = - selectedOwner - .generations() - .readCompositeSnapshot( - GameSessionAccountDelegationProfile.ISSUER, - accountId, - List.of(tenantId), - List.of(tenantId)); - var tenant = selectedOwner.tenantSources().readCurrentByTenant(tenantId); - var member = - selectedOwner - .memberships() - .findFreshMembershipForUpdate(accountId, tenantId) - .orElseThrow(ProjectionUnavailableException::new); - var pair = - selectedOwner - .pairs() - .readForUpdate(accountId, tenantId) - .orElseThrow(ProjectionUnavailableException::new); - String memberStream = - "account:auth-authority:v1:membership/" + accountId + "/" + tenantId; - var memberCheckpoint = - selectedOwner - .outbox() - .readCheckpoint(memberStream) - .orElseThrow(ProjectionUnavailableException::new); - String tenantStream = "account:auth-authority:v1:tenant/" + tenantId; - var tenantCheckpoint = - selectedOwner - .outbox() - .readCheckpoint(tenantStream) - .orElseThrow(ProjectionUnavailableException::new); - var memberEvent = - selectedOwner - .outbox() - .findEvent(memberStream, memberCheckpoint.outboxSequence()) - .orElseThrow(ProjectionUnavailableException::new); - var tenantEvent = - selectedOwner - .outbox() - .findEvent(tenantStream, tenantCheckpoint.outboxSequence()) - .orElseThrow(ProjectionUnavailableException::new); - var event = memberEvent; - var verified = - MembershipAuthorityEventV1Codec.verify( - new String(event.payload(), StandardCharsets.UTF_8)); - var tenantState = composite.tenants().getFirst(); - var memberState = composite.memberships().getFirst(); - if (source.issuer().generation() != composite.issuer().generation() - || source.issuer().sourceVersion() != composite.issuer().sourceVersion() - || source.account().generation() != composite.account().generation() - || source.account().sourceVersion() != composite.account().sourceVersion() - || !source.issuanceFence().equals(composite.issuanceFence()) - || tenant.tenantAuthorityGeneration() != tenantState.generation() - || tenant.tenantAuthoritySourceVersion() != tenantState.sourceVersion() - || !tenantId.equals(tenant.tenantId()) - || !pair.provenance() - .sourceOperationId() - .equals(tenant.sourceEvidence().operationId()) - || !pair.provenance().digest().equals(tenant.sourceEvidence().evidenceDigest()) - || !pair.membershipExists() - || pair.lastTransitionInvalidated() - || !"ACTIVE".equals(member.getLifecycleState()) - || !member.isGameplayAdmissionAllowed() - || member.getMembershipVersion() != pair.membershipVersion() - || member.getMembershipAuthorityGeneration() - != pair.membershipAuthorityGeneration() - || memberState.generation() != pair.membershipAuthorityGeneration() - || memberState.sourceVersion() != memberState.generation() - || !Long.toString(memberState.sourceVersion()) - .equals(verified.membershipAuthorityGeneration()) - || memberCheckpoint.outboxSequence() != pair.eventSequence() - || !memberCheckpoint.sourceEventId().equals(pair.eventId()) - || !memberCheckpoint.sourceEventDigest().equals(pair.eventDigest()) - || !event.eventId().equals(pair.eventId()) - || !event.eventDigest().equals(pair.eventDigest()) - || !Long.toString(memberCheckpoint.outboxSequence()) - .equals(verified.outboxSequence()) - || !memberCheckpoint.outboxStreamKey().equals(verified.outboxStreamKey()) - || tenantCheckpoint.outboxSequence() != tenant.outboxSequence() - || !tenantCheckpoint.sourceEventId().equals(tenant.eventId().toString()) - || !tenantCheckpoint.sourceEventDigest().equals(tenant.eventDigest()) - || !tenantEvent.eventId().equals(tenant.eventId().toString()) - || !tenantEvent.eventDigest().equals(tenant.eventDigest()) - || !Arrays.equals(tenantEvent.payload(), tenant.payload()) - || !Arrays.equals(event.payload(), verified.canonicalJsonUtf8()) - || !accountId.toString().equals(verified.accountId()) - || !tenantId.toString().equals(verified.tenantId()) - || !Long.toString(pair.membershipVersion()) - .equals(verified.membershipVersion().get(tenantId.toString())) - || !Long.toString(pair.membershipAuthorityGeneration()) - .equals(verified.membershipAuthorityGeneration()) - || !"ACTIVE".equals(verified.membershipLifecycleState()) - || !verified.gameplayAdmissionAllowed() - || verified.callerBoundAuthorityInvalidated() - || !verified.roles().contains("player")) - throw new ProjectionUnavailableException(); - // The immutable event proves this pair, not today's independent global/tenant - // sources. - // Derive today's tuple from the same locked owner read; never rewrite the historical - // event. - Map tuple = new LinkedHashMap<>(); - tuple.put("issuerAuthGeneration", Long.toString(composite.issuer().generation())); - tuple.put( - "accountAuthorityGeneration", Long.toString(composite.account().generation())); - tuple.put( - "tenantAuthorityGeneration", - Map.of(tenantId.toString(), Long.toString(tenantState.generation()))); - tuple.put( - "membershipAuthorityGeneration", - Map.of(tenantId.toString(), Long.toString(memberState.generation()))); - tuple.put("privateRealmGrantVersions", List.of()); - var accountCutoff = source.account().accountSecurityCutoff(); - if (accountCutoff.isPresent()) { - var cutoff = accountCutoff.orElseThrow(); - tuple.put( - "accountSecurityCutoff", - Map.of( - "accountAuthorityGeneration", - cutoff.accountAuthorityGeneration(), - "outboxStreamKey", - cutoff.outboxStreamKey(), - "outboxSequence", - cutoff.outboxSequence())); - } - // The explicit demo owner has positive linked billing evidence; non-paid does not - // mean absent cutoff. - tuple.put( - "tenantBillingCutoff", + accountTransaction.execute(status -> { + // The source and composite owners both take Account first; the composite fixes all + // four scopes. + var source = + sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, accountId); + var composite = + selectedOwner + .generations() + .readCompositeSnapshot( + GameSessionAccountDelegationProfile.ISSUER, + accountId, + List.of(tenantId), + List.of(tenantId)); + var tenant = selectedOwner.tenantSources().readCurrentByTenant(tenantId); + var member = + selectedOwner + .memberships() + .findFreshMembershipForUpdate(accountId, tenantId) + .orElseThrow(ProjectionUnavailableException::new); + var pair = + selectedOwner + .pairs() + .readForUpdate(accountId, tenantId) + .orElseThrow(ProjectionUnavailableException::new); + String memberStream = + "account:auth-authority:v1:membership/" + accountId + "/" + tenantId; + var memberCheckpoint = + selectedOwner + .outbox() + .readCheckpoint(memberStream) + .orElseThrow(ProjectionUnavailableException::new); + String tenantStream = "account:auth-authority:v1:tenant/" + tenantId; + var tenantCheckpoint = + selectedOwner + .outbox() + .readCheckpoint(tenantStream) + .orElseThrow(ProjectionUnavailableException::new); + var memberEvent = + selectedOwner + .outbox() + .findEvent(memberStream, memberCheckpoint.outboxSequence()) + .orElseThrow(ProjectionUnavailableException::new); + var tenantEvent = + selectedOwner + .outbox() + .findEvent(tenantStream, tenantCheckpoint.outboxSequence()) + .orElseThrow(ProjectionUnavailableException::new); + var event = memberEvent; + var verified = + MembershipAuthorityEventV1Codec.verify( + new String(event.payload(), StandardCharsets.UTF_8)); + var tenantState = composite.tenants().getFirst(); + var memberState = composite.memberships().getFirst(); + if (source.issuer().generation() != composite.issuer().generation() + || source.issuer().sourceVersion() != composite.issuer().sourceVersion() + || source.account().generation() != composite.account().generation() + || source.account().sourceVersion() != composite.account().sourceVersion() + || !source.issuanceFence().equals(composite.issuanceFence()) + || tenant.tenantAuthorityGeneration() != tenantState.generation() + || tenant.tenantAuthoritySourceVersion() != tenantState.sourceVersion() + || !tenantId.equals(tenant.tenantId()) + || !pair.provenance() + .sourceOperationId() + .equals(tenant.sourceEvidence().operationId()) + || !pair.provenance().digest().equals(tenant.sourceEvidence().evidenceDigest()) + || !pair.membershipExists() + || pair.lastTransitionInvalidated() + || !"ACTIVE".equals(member.getLifecycleState()) + || !member.isGameplayAdmissionAllowed() + || member.getMembershipVersion() != pair.membershipVersion() + || member.getMembershipAuthorityGeneration() != pair.membershipAuthorityGeneration() + || memberState.generation() != pair.membershipAuthorityGeneration() + || memberState.sourceVersion() != memberState.generation() + || !Long.toString(memberState.sourceVersion()) + .equals(verified.membershipAuthorityGeneration()) + || memberCheckpoint.outboxSequence() != pair.eventSequence() + || !memberCheckpoint.sourceEventId().equals(pair.eventId()) + || !memberCheckpoint.sourceEventDigest().equals(pair.eventDigest()) + || !event.eventId().equals(pair.eventId()) + || !event.eventDigest().equals(pair.eventDigest()) + || !Long.toString(memberCheckpoint.outboxSequence()).equals(verified.outboxSequence()) + || !memberCheckpoint.outboxStreamKey().equals(verified.outboxStreamKey()) + || tenantCheckpoint.outboxSequence() != tenant.outboxSequence() + || !tenantCheckpoint.sourceEventId().equals(tenant.eventId().toString()) + || !tenantCheckpoint.sourceEventDigest().equals(tenant.eventDigest()) + || !tenantEvent.eventId().equals(tenant.eventId().toString()) + || !tenantEvent.eventDigest().equals(tenant.eventDigest()) + || !Arrays.equals(tenantEvent.payload(), tenant.payload()) + || !Arrays.equals(event.payload(), verified.canonicalJsonUtf8()) + || !accountId.toString().equals(verified.accountId()) + || !tenantId.toString().equals(verified.tenantId()) + || !Long.toString(pair.membershipVersion()) + .equals(verified.membershipVersion().get(tenantId.toString())) + || !Long.toString(pair.membershipAuthorityGeneration()) + .equals(verified.membershipAuthorityGeneration()) + || !"ACTIVE".equals(verified.membershipLifecycleState()) + || !verified.gameplayAdmissionAllowed() + || verified.callerBoundAuthorityInvalidated() + || !verified.roles().contains("player")) throw new ProjectionUnavailableException(); + // The immutable event proves this pair, not today's independent global/tenant + // sources. + // Derive today's tuple from the same locked owner read; never rewrite the historical + // event. + Map tuple = new LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", Long.toString(composite.issuer().generation())); + tuple.put("accountAuthorityGeneration", Long.toString(composite.account().generation())); + tuple.put( + "tenantAuthorityGeneration", + Map.of(tenantId.toString(), Long.toString(tenantState.generation()))); + tuple.put( + "membershipAuthorityGeneration", + Map.of(tenantId.toString(), Long.toString(memberState.generation()))); + tuple.put("privateRealmGrantVersions", List.of()); + var accountCutoff = source.account().accountSecurityCutoff(); + if (accountCutoff.isPresent()) { + var cutoff = accountCutoff.orElseThrow(); + tuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", + cutoff.accountAuthorityGeneration(), + "outboxStreamKey", + cutoff.outboxStreamKey(), + "outboxSequence", + cutoff.outboxSequence())); + } + // The explicit demo owner has positive linked billing evidence; non-paid does not + // mean absent cutoff. + tuple.put( + "tenantBillingCutoff", + Map.of( + tenantId.toString(), Map.of( - tenantId.toString(), - Map.of( - "tenantAuthorityGeneration", - Long.toString(tenant.tenantAuthorityGeneration()), - "tenantBillingSequence", Long.toString(tenant.tenantBillingSequence()), - "outboxStreamKey", tenant.outboxStreamKey(), - "outboxSequence", Long.toString(tenant.outboxSequence())))); - byte[][] initial = canonicalProjectionPair(source); - byte[] tenantProjectionBytes = - tenantProjection(tenantEvent, tenantId).canonicalBytes(); - byte[] membershipProjection = - membershipProjection(memberEvent, accountId, tenantId).canonicalBytes(); - return new SelectedSnapshot( - source, - composite, - pair, - verified.canonicalJson(), - new String(tenant.payload(), StandardCharsets.UTF_8), - canonical(tuple), - new byte[][] { - initial[0], initial[1], tenantProjectionBytes, membershipProjection - }, - tenantCheckpoint, - memberCheckpoint); - }); + "tenantAuthorityGeneration", + Long.toString(tenant.tenantAuthorityGeneration()), + "tenantBillingSequence", Long.toString(tenant.tenantBillingSequence()), + "outboxStreamKey", tenant.outboxStreamKey(), + "outboxSequence", Long.toString(tenant.outboxSequence())))); + byte[][] initial = canonicalProjectionPair(source); + byte[] tenantProjectionBytes = tenantProjection(tenantEvent, tenantId).canonicalBytes(); + byte[] membershipProjection = + membershipProjection(memberEvent, accountId, tenantId).canonicalBytes(); + return new SelectedSnapshot( + source, + composite, + pair, + verified.canonicalJson(), + new String(tenant.payload(), StandardCharsets.UTF_8), + canonical(tuple), + new byte[][] {initial[0], initial[1], tenantProjectionBytes, membershipProjection}, + tenantCheckpoint, + memberCheckpoint); + }); if (result == null) throw new ProjectionUnavailableException(); return result; } @@ -355,12 +347,11 @@ private boolean replayRetainedHistory( } if (redisSequence > checkpoint.outboxSequence()) throw new ProjectionUnavailableException(); AccountAuthorityOutboxRepository.Event retainedHead = - accountTransaction.execute( - status -> - selectedOwner - .outbox() - .findEvent(streamKey, redisSequence) - .orElseThrow(ProjectionUnavailableException::new)); + accountTransaction.execute(status -> + selectedOwner + .outbox() + .findEvent(streamKey, redisSequence) + .orElseThrow(ProjectionUnavailableException::new)); if (!streamKey.equals(retainedHead.outboxStreamKey()) || retainedHead.outboxSequence() != redisSequence) { throw new ProjectionUnavailableException(); @@ -382,11 +373,10 @@ private boolean replayRetainedHistory( while (cursor < checkpoint.outboxSequence()) { long afterSequence = cursor; List page = - accountTransaction.execute( - status -> - selectedOwner - .outbox() - .findEventPage(streamKey, afterSequence, checkpoint.outboxSequence())); + accountTransaction.execute(status -> + selectedOwner + .outbox() + .findEventPage(streamKey, afterSequence, checkpoint.outboxSequence())); if (page == null || page.isEmpty() || page.size() > AccountAuthorityOutboxRepository.MAX_EVENT_HISTORY_PAGE_SIZE) { @@ -661,10 +651,9 @@ public ProjectionObservation observeCurrent(UUID accountId) { private IssuerAccountSourceSnapshot readOwnerSnapshot(UUID accountId) { IssuerAccountSourceSnapshot snapshot = - accountTransaction.execute( - status -> - sourceEvidence.readCurrentIssuerAccountSources( - GameSessionAccountDelegationProfile.ISSUER, accountId)); + accountTransaction.execute(status -> + sourceEvidence.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, accountId)); if (snapshot == null || !GameSessionAccountDelegationProfile.ISSUER.equals(snapshot.issuer().scope().issuerId()) || !accountId.equals(snapshot.account().scope().accountId())) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java index c79bfaee41..d5a4ade016 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwner.java @@ -91,15 +91,14 @@ public CommittedCandidateVerificationData requireCurrentActiveCommittedCandidate if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); try { CommittedCandidateVerificationData evidence = - accountTransaction.execute( - status -> { - CommittedCandidateVerificationData current = - issuanceRepository - .readCurrentCommittedCandidateByJti(tokenJti) - .orElseThrow(AccountGameplayDelegationCommittedIssuanceOwner::unavailable); - signer.requireCurrentCommittedRecoverySigner(current); - return current; - }); + accountTransaction.execute(status -> { + CommittedCandidateVerificationData current = + issuanceRepository + .readCurrentCommittedCandidateByJti(tokenJti) + .orElseThrow(AccountGameplayDelegationCommittedIssuanceOwner::unavailable); + signer.requireCurrentCommittedRecoverySigner(current); + return current; + }); if (evidence == null || !tokenJti.equals(evidence.identity().tokenJti()) || Math.floorDiv(clock.millis(), 1_000L) >= evidence.identity().expiresAtEpochSecond()) { @@ -153,13 +152,12 @@ public ActiveCommittedIssuanceObservation activateCommittedIssuance(UUID request } private CheckedObservation readCurrentOwnerEvidence(UUID requestId) { - return accountTransaction.execute( - status -> { - CommittedCandidateVerificationData evidence = - issuanceRepository.readCurrentCommittedCandidate(requestId); - signer.requireCurrentCommittedSigner(evidence); - return new CheckedObservation(evidence, clock.millis()); - }); + return accountTransaction.execute(status -> { + CommittedCandidateVerificationData evidence = + issuanceRepository.readCurrentCommittedCandidate(requestId); + signer.requireCurrentCommittedSigner(evidence); + return new CheckedObservation(evidence, clock.millis()); + }); } /** @@ -168,13 +166,12 @@ private CheckedObservation readCurrentOwnerEvidence(UUID requestId) { */ private CheckedObservation readCurrentRecoveryOwnerEvidence(UUID requestId) { CheckedObservation checked = - accountTransaction.execute( - status -> { - CommittedCandidateVerificationData evidence = - issuanceRepository.readCurrentCommittedCandidate(requestId); - signer.requireCurrentCommittedRecoverySigner(evidence); - return new CheckedObservation(evidence, clock.millis()); - }); + accountTransaction.execute(status -> { + CommittedCandidateVerificationData evidence = + issuanceRepository.readCurrentCommittedCandidate(requestId); + signer.requireCurrentCommittedRecoverySigner(evidence); + return new CheckedObservation(evidence, clock.millis()); + }); if (checked == null) return null; signer.requireRetainedCommittedPublicKey(checked.evidence()); return checked; diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitService.java index e976050b4a..2da00615be 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitService.java @@ -108,12 +108,11 @@ public CommitResult commitPendingCandidate(UUID requestId) { CommitProof commitProof = CommitProof.create(proof, registration, projection); CommittedIssuanceReadback transactionReadback = - accountTransaction.execute( - status -> { - signer.requireCurrentCommittedSigner(proof); - return issuanceRepository.commitPendingCandidate( - requestId, proof, registration, projection, commitProof); - }); + accountTransaction.execute(status -> { + signer.requireCurrentCommittedSigner(proof); + return issuanceRepository.commitPendingCandidate( + requestId, proof, registration, projection, commitProof); + }); if (transactionReadback == null || !transactionReadback.proofSha256().equals(commitProof.sha256())) { throw unavailable(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwner.java index 5f237f30ff..1c7ffb88b8 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationResponseRecoveryOwner.java @@ -60,10 +60,8 @@ public RecoveredCredential recoverInitialLoginResponse( if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); try { RecoveryPreflight preflight = - accountTransaction.execute( - status -> - responseEnvelopes.preflightCommittedRecovery( - requestId, expectedAccountId, caller)); + accountTransaction.execute(status -> + responseEnvelopes.preflightCommittedRecovery(requestId, expectedAccountId, caller)); if (preflight == null || !requestId.equals(preflight.requestId()) || !expectedAccountId.equals(preflight.accountId()) @@ -79,15 +77,14 @@ public RecoveredCredential recoverInitialLoginResponse( if (active == null) throw unavailable(); RecoveredCredential credential = - accountTransaction.execute( - status -> { - committedIssuanceOwner.requireOriginalRequestNotDisposed(requestId); - RecoveredCredential recovered = - responseEnvelopes.recoverCommittedResponse( - requestId, expectedAccountId, caller, active); - committedIssuanceOwner.requireOriginalRequestNotDisposed(requestId); - return recovered; - }); + accountTransaction.execute(status -> { + committedIssuanceOwner.requireOriginalRequestNotDisposed(requestId); + RecoveredCredential recovered = + responseEnvelopes.recoverCommittedResponse( + requestId, expectedAccountId, caller, active); + committedIssuanceOwner.requireOriginalRequestNotDisposed(requestId); + return recovered; + }); if (credential == null) throw unavailable(); return credential; } catch (IdempotencyConflictException | ResponseRecoveryExpiredException failure) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java index fd57932553..3e1ac9dd11 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSigner.java @@ -180,26 +180,25 @@ CandidateOutcome signPendingCandidate(UUID requestId) { PendingCandidateCredential openedCandidate = null; try { InvocationIdentity acquired = - accountTransaction.execute( - status -> { - CurrentSigner signer = currentCommittedSigner(); - PendingSigningIdentity pending = requireCurrentPendingIdentity(requestId); - requireUnexpired(pending); - PendingCandidateCredential resumed = - pending.persistedCandidate().isPresent() - ? responseEnvelopeService.openPendingCandidate( - requestId, - new CallerIdentity( - pending.identity().callerWorkload(), - pending.identity().callerContextId())) - : null; - if (resumed != null) { - PendingCandidateCredential replaced = acquiredCandidate.getAndSet(resumed); - if (replaced != null) replaced.close(); - requireOpenedCandidate(pending, resumed); - } - return new InvocationIdentity(signer, pending, resumed); - }); + accountTransaction.execute(status -> { + CurrentSigner signer = currentCommittedSigner(); + PendingSigningIdentity pending = requireCurrentPendingIdentity(requestId); + requireUnexpired(pending); + PendingCandidateCredential resumed = + pending.persistedCandidate().isPresent() + ? responseEnvelopeService.openPendingCandidate( + requestId, + new CallerIdentity( + pending.identity().callerWorkload(), + pending.identity().callerContextId())) + : null; + if (resumed != null) { + PendingCandidateCredential replaced = acquiredCandidate.getAndSet(resumed); + if (replaced != null) replaced.close(); + requireOpenedCandidate(pending, resumed); + } + return new InvocationIdentity(signer, pending, resumed); + }); openedCandidate = acquiredCandidate.getAndSet(null); if (acquired == null) { throw unavailable(); @@ -286,18 +285,17 @@ CandidateOutcome signPendingCandidate(UUID requestId) { AccountMountedJwtSignerBundle.SignedDelegationDigest signedDigest = digest; VerifiedCandidateIdentity verifiedCandidateIdentity = candidateIdentity; CandidateOutcome outcome = - accountTransaction.execute( - status -> - initial.resumedCandidate() == null - ? bindAndSealWithinTransaction( - requestId, - compactJwt, - initial, - verifiedCandidateIdentity, - signedDigest, - sourcePin) - : resumeAndReadbackWithinTransaction( - requestId, initial, verifiedCandidateIdentity, sourcePin)); + accountTransaction.execute(status -> + initial.resumedCandidate() == null + ? bindAndSealWithinTransaction( + requestId, + compactJwt, + initial, + verifiedCandidateIdentity, + signedDigest, + sourcePin) + : resumeAndReadbackWithinTransaction( + requestId, initial, verifiedCandidateIdentity, sourcePin)); if (outcome == null) { throw unavailable(); } @@ -680,17 +678,15 @@ private AuthenticatedSignerCorrespondence requireCommittedCandidateIdentity( || !original.targetPublicKeyFingerprint().matches("[0-9a-f]{64}") || original .durableActive() - .filter( - active -> - active.generation().equals(committed.signerGeneration()) - && active.kid().equals(committed.signerKid())) + .filter(active -> + active.generation().equals(committed.signerGeneration()) + && active.kid().equals(committed.signerKid())) .isEmpty() || original .publishedActive() - .filter( - active -> - active.generation().equals(committed.signerGeneration()) - && active.kid().equals(committed.signerKid())) + .filter(active -> + active.generation().equals(committed.signerGeneration()) + && active.kid().equals(committed.signerKid())) .isEmpty()) { throw unavailable(); } @@ -1514,17 +1510,15 @@ private PendingCandidateVerificationProof( .equals(signerCorrespondence.privatePromotionGenerationOperationId()) || signerCorrespondence .durableActive() - .filter( - active -> - active.generation().equals(signerCorrespondence.targetGeneration()) - && active.kid().equals(signerCorrespondence.targetKid())) + .filter(active -> + active.generation().equals(signerCorrespondence.targetGeneration()) + && active.kid().equals(signerCorrespondence.targetKid())) .isEmpty() || signerCorrespondence .publishedActive() - .filter( - active -> - active.generation().equals(signerCorrespondence.targetGeneration()) - && active.kid().equals(signerCorrespondence.targetKid())) + .filter(active -> + active.generation().equals(signerCorrespondence.targetGeneration()) + && active.kid().equals(signerCorrespondence.targetKid())) .isEmpty() || signerCorrespondence .promotionPrivateObservedResourceVersion() diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java index 48de813354..e03dad65df 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClient.java @@ -288,12 +288,11 @@ private static void requirePreservedUnrelatedData( private static Map unrelatedData(Map data) { Map unrelated = new LinkedHashMap<>(); - data.forEach( - (key, value) -> { - if (!ACCOUNT_DATA_KEYS.contains(key)) { - unrelated.put(key, value); - } - }); + data.forEach((key, value) -> { + if (!ACCOUNT_DATA_KEYS.contains(key)) { + unrelated.put(key, value); + } + }); return Map.copyOf(unrelated); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationService.java index 17de38c401..ff59bc8ec9 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationService.java @@ -165,24 +165,23 @@ public PublicationReceipt prepublishCurrentGeneration() { String desiredJwks = appendPendingPublicKey(sourceJwks, current.result()); String marker = generationMarker(current.result(), current.request(), apiIdentity); PrepublicationIntent intent = - accountTransaction.execute( - status -> { - PrepublicationIntent persisted = - publicationRepository.recordPrepublicationIntent( - binding.accountBinding(), - trustFence(binding), - current.result(), - current.request(), - apiIdentity.bindingDigest(), - apiIdentity.configRevision(), - snapshot.uid(), - snapshot.resourceVersion(), - AccountJwtJwksPublicationRepository.snapshotDigest(snapshot.data()), - desiredJwks, - marker); - requireUnchangedBindings(binding, apiIdentity); - return persisted; - }); + accountTransaction.execute(status -> { + PrepublicationIntent persisted = + publicationRepository.recordPrepublicationIntent( + binding.accountBinding(), + trustFence(binding), + current.result(), + current.request(), + apiIdentity.bindingDigest(), + apiIdentity.configRevision(), + snapshot.uid(), + snapshot.resourceVersion(), + AccountJwtJwksPublicationRepository.snapshotDigest(snapshot.data()), + desiredJwks, + marker); + requireUnchangedBindings(binding, apiIdentity); + return persisted; + }); if (intent == null) { throw new PublicationRejectedException("Account JWT JWKS intent was not persisted"); } @@ -202,16 +201,14 @@ public MountObservation observeCurrentMountedCorrespondence() { PublicationEvidence evidence = current .publication() - .orElseThrow( - () -> - new PublicationRejectedException( - "Account JWT JWKS publication evidence is not available")); + .orElseThrow(() -> + new PublicationRejectedException( + "Account JWT JWKS publication evidence is not available")); PrepublicationIntent intent = evidence.intent(); evidence .receipt() - .orElseThrow( - () -> - new PublicationRejectedException("Account JWT JWKS API readback is not available")); + .orElseThrow(() -> + new PublicationRejectedException("Account JWT JWKS API readback is not available")); requireIntentApiIdentity(intent, apiIdentity); byte[] markerBytes = @@ -267,19 +264,18 @@ public MountObservation observeCurrentMountedCorrespondence() { "Mounted Account public JWT projection changed during correspondence observation"); } MountObservation observation = - accountTransaction.execute( - status -> { - MountObservation persisted = - publicationRepository.recordMountedCorrespondence( - binding.accountBinding(), - trustFence(binding), - current.result().operationId(), - sha256(markerBytes), - AccountJwtJwksPublicationRepository.publicDataDigest(mountedJwks, marker), - localObservation.publicKeyFingerprint()); - requireUnchangedBindings(binding, apiIdentity); - return persisted; - }); + accountTransaction.execute(status -> { + MountObservation persisted = + publicationRepository.recordMountedCorrespondence( + binding.accountBinding(), + trustFence(binding), + current.result().operationId(), + sha256(markerBytes), + AccountJwtJwksPublicationRepository.publicDataDigest(mountedJwks, marker), + localObservation.publicKeyFingerprint()); + requireUnchangedBindings(binding, apiIdentity); + return persisted; + }); if (observation == null) { throw new PublicationRejectedException( "Mounted Account JWT correspondence was not persisted"); @@ -316,10 +312,9 @@ public ConfigMapSnapshot observePreparedCurrentKeyCorrespondence( } var publication = - accountTransaction.execute( - status -> - publicationRepository.readPreparedPublicationForRecovery( - binding.accountBinding(), trust)); + accountTransaction.execute(status -> + publicationRepository.readPreparedPublicationForRecovery( + binding.accountBinding(), trust)); if (publication == null || !publication.intent().operationId().equals(promotion.generationOperationId()) || !publication.intent().intentDigest().equals(promotion.prepublicationIntentDigest()) @@ -456,22 +451,21 @@ private PublicationReceipt publishAndRecord( } requireUnchangedBindings(binding, apiIdentity); PublicationReceipt persisted = - accountTransaction.execute( - status -> { - PublicationReceipt receipt = - publicationRepository.recordPublicationReceipt( - binding.accountBinding(), - trustFence(binding), - intent.operationId(), - apiIdentity.bindingDigest(), - apiIdentity.configRevision(), - observation.uid(), - observation.resourceVersion(), - intent.jwksJson(), - intent.generationMarkerJson()); - requireUnchangedBindings(binding, apiIdentity); - return receipt; - }); + accountTransaction.execute(status -> { + PublicationReceipt receipt = + publicationRepository.recordPublicationReceipt( + binding.accountBinding(), + trustFence(binding), + intent.operationId(), + apiIdentity.bindingDigest(), + apiIdentity.configRevision(), + observation.uid(), + observation.resourceVersion(), + intent.jwksJson(), + intent.generationMarkerJson()); + requireUnchangedBindings(binding, apiIdentity); + return receipt; + }); if (persisted == null) { throw new PublicationRejectedException("Account JWT JWKS API receipt was not persisted"); } @@ -480,27 +474,26 @@ private PublicationReceipt publishAndRecord( private CurrentGeneration loadCurrentGeneration(Binding binding, BindingIdentity apiIdentity) { CurrentGeneration current = - accountTransaction.execute( - status -> { - GenerationResult result = - desiredStateRepository.readCurrentGenerationResult( - binding.accountBinding(), trustFence(binding)); - GenerationRequest request = - desiredStateRepository.readCurrentGenerationRequest( - binding.accountBinding(), trustFence(binding)); - Optional publication = - publicationRepository.readCurrentPublication( - binding.accountBinding(), trustFence(binding)); - if (!result.binding().equals(binding.accountBinding()) - || !result.trustFence().equals(trustFence(binding)) - || !request.operationId().equals(result.operationId()) - || !request.generationReceiptDigest().equals(result.receiptDigest())) { - throw new PublicationRejectedException( - "Account JWT generation receipt does not match the current protected binding"); - } - requireUnchangedBindings(binding, apiIdentity); - return new CurrentGeneration(result, request, publication); - }); + accountTransaction.execute(status -> { + GenerationResult result = + desiredStateRepository.readCurrentGenerationResult( + binding.accountBinding(), trustFence(binding)); + GenerationRequest request = + desiredStateRepository.readCurrentGenerationRequest( + binding.accountBinding(), trustFence(binding)); + Optional publication = + publicationRepository.readCurrentPublication( + binding.accountBinding(), trustFence(binding)); + if (!result.binding().equals(binding.accountBinding()) + || !result.trustFence().equals(trustFence(binding)) + || !request.operationId().equals(result.operationId()) + || !request.generationReceiptDigest().equals(result.receiptDigest())) { + throw new PublicationRejectedException( + "Account JWT generation receipt does not match the current protected binding"); + } + requireUnchangedBindings(binding, apiIdentity); + return new CurrentGeneration(result, request, publication); + }); if (current == null) { throw new PublicationRejectedException("Current Account JWT generation is unavailable"); } @@ -740,11 +733,10 @@ private static Map activeMarker( Optional active) { Map marker = new LinkedHashMap<>(); marker.put("present", active.isPresent()); - active.ifPresent( - signer -> { - marker.put("generation", signer.generation()); - marker.put("kid", signer.kid()); - }); + active.ifPresent(signer -> { + marker.put("generation", signer.generation()); + marker.put("kid", signer.kid()); + }); return marker; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java index df2a7f5a17..76da16d59d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSource.java @@ -371,90 +371,86 @@ private OwnerProjection currentOwnerProjection( } try { OwnerProjection result = - accountTransaction.execute( - status -> { - Optional enrollment = - allowPreparedDeny - ? desiredStateRepository.readLockedEnrollmentState(binding.accountBinding()) - : desiredStateRepository.readEnrollmentState(binding.accountBinding()); - DesiredState enrolled = - enrollment.orElseThrow(() -> allowPreparedDeny ? rejected() : unavailable()); - if (allowPreparedDeny && enrolled.preparedOperationId().isPresent()) { - return preparedProjection(enrolled, binding, api); - } - if (enrolled.durableActive().isEmpty() && enrolled.publishedActive().isEmpty()) { - return initialPrepublicationProjection(enrolled, binding, api, allowPreparedDeny); - } - CommittedSignerEvidence committed = - desiredStateRepository - .readCurrentCommittedSigner( - binding.accountBinding(), - trustFence(binding), - api.bindingDigest(), - api.configRevision()) - .orElseThrow(() -> allowPreparedDeny ? rejected() : unavailable()); - ActiveSigner currentActive = - new ActiveSigner( - committed.promotion().targetGeneration(), - committed.promotion().targetKid()); - PublishedProjection projection = committedProjection(committed); - if (committed.desiredState().generationOperationId().isEmpty()) { - return new OwnerProjection(committed, projection); - } + accountTransaction.execute(status -> { + Optional enrollment = + allowPreparedDeny + ? desiredStateRepository.readLockedEnrollmentState(binding.accountBinding()) + : desiredStateRepository.readEnrollmentState(binding.accountBinding()); + DesiredState enrolled = + enrollment.orElseThrow(() -> allowPreparedDeny ? rejected() : unavailable()); + if (allowPreparedDeny && enrolled.preparedOperationId().isPresent()) { + return preparedProjection(enrolled, binding, api); + } + if (enrolled.durableActive().isEmpty() && enrolled.publishedActive().isEmpty()) { + return initialPrepublicationProjection(enrolled, binding, api, allowPreparedDeny); + } + CommittedSignerEvidence committed = + desiredStateRepository + .readCurrentCommittedSigner( + binding.accountBinding(), + trustFence(binding), + api.bindingDigest(), + api.configRevision()) + .orElseThrow(() -> allowPreparedDeny ? rejected() : unavailable()); + ActiveSigner currentActive = + new ActiveSigner( + committed.promotion().targetGeneration(), committed.promotion().targetKid()); + PublishedProjection projection = committedProjection(committed); + if (committed.desiredState().generationOperationId().isEmpty()) { + return new OwnerProjection(committed, projection); + } - var request = - desiredStateRepository.readCurrentGenerationRequest( - binding.accountBinding(), trustFence(binding)); - if (request.phase() - != AccountJwtSignerDesiredStateRepository.GenerationPhase.GENERATION_RECORDED) { - return new OwnerProjection(committed, projection); - } - Optional currentPublication = - publicationRepository.readCurrentPublication( - binding.accountBinding(), trustFence(binding)); - if (currentPublication.isEmpty()) { - return new OwnerProjection(committed, projection); - } - PublicationEvidence evidence = currentPublication.orElseThrow(); - requirePublicationBinding(evidence, binding, api); - PrepublicationIntent intent = evidence.intent(); - PublicationReceipt receipt = evidence.receipt().orElse(null); - if (receipt == null && !allowPreparedDeny) throw unavailable(); - if (!intent.operationId().equals(request.operationId()) - || !intent.operationDigest().equals(request.operationDigest()) - || !intent.generationRequestDigest().equals(request.generationRequestDigest()) - || !intent.generationReceiptDigest().equals(request.generationReceiptDigest()) - || !intent.targetGeneration().equals(request.targetGeneration()) - || !intent.targetKid().equals(request.targetKid()) - || !intent.publicKeyFingerprint().equals(request.publicKeyFingerprint()) - || !intent.expectedDurableActive().equals(Optional.of(currentActive)) - || !intent.expectedPublishedActive().equals(Optional.of(currentActive)) - || !intent.configMapUid().equals(committed.promotion().publicConfigMapUid()) - || (receipt != null - && !receipt - .configMapUid() - .equals(committed.promotion().publicConfigMapUid())) - || !intent.apiBindingDigest().equals(api.bindingDigest()) - || !intent.apiConfigRevision().equals(api.configRevision())) { - throw rejected(); - } - requireRetainedPublicKeySet(committed, intent); - if (receipt == null) { - requirePrepublicationMarker(intent, binding, api); - if (!intent.expectedResourceVersion().equals(projection.resourceVersion())) { - throw rejected(); - } - return new OwnerProjection(committed, projection, null, null, intent); - } - return new OwnerProjection( - committed, - new PublishedProjection( - intent.configMapUid(), - receipt.observedResourceVersion(), - intent.jwksJson(), - intent.generationMarkerJson(), - receipt.publicDataDigest())); - }); + var request = + desiredStateRepository.readCurrentGenerationRequest( + binding.accountBinding(), trustFence(binding)); + if (request.phase() + != AccountJwtSignerDesiredStateRepository.GenerationPhase.GENERATION_RECORDED) { + return new OwnerProjection(committed, projection); + } + Optional currentPublication = + publicationRepository.readCurrentPublication( + binding.accountBinding(), trustFence(binding)); + if (currentPublication.isEmpty()) { + return new OwnerProjection(committed, projection); + } + PublicationEvidence evidence = currentPublication.orElseThrow(); + requirePublicationBinding(evidence, binding, api); + PrepublicationIntent intent = evidence.intent(); + PublicationReceipt receipt = evidence.receipt().orElse(null); + if (receipt == null && !allowPreparedDeny) throw unavailable(); + if (!intent.operationId().equals(request.operationId()) + || !intent.operationDigest().equals(request.operationDigest()) + || !intent.generationRequestDigest().equals(request.generationRequestDigest()) + || !intent.generationReceiptDigest().equals(request.generationReceiptDigest()) + || !intent.targetGeneration().equals(request.targetGeneration()) + || !intent.targetKid().equals(request.targetKid()) + || !intent.publicKeyFingerprint().equals(request.publicKeyFingerprint()) + || !intent.expectedDurableActive().equals(Optional.of(currentActive)) + || !intent.expectedPublishedActive().equals(Optional.of(currentActive)) + || !intent.configMapUid().equals(committed.promotion().publicConfigMapUid()) + || (receipt != null + && !receipt.configMapUid().equals(committed.promotion().publicConfigMapUid())) + || !intent.apiBindingDigest().equals(api.bindingDigest()) + || !intent.apiConfigRevision().equals(api.configRevision())) { + throw rejected(); + } + requireRetainedPublicKeySet(committed, intent); + if (receipt == null) { + requirePrepublicationMarker(intent, binding, api); + if (!intent.expectedResourceVersion().equals(projection.resourceVersion())) { + throw rejected(); + } + return new OwnerProjection(committed, projection, null, null, intent); + } + return new OwnerProjection( + committed, + new PublishedProjection( + intent.configMapUid(), + receipt.observedResourceVersion(), + intent.jwksJson(), + intent.generationMarkerJson(), + receipt.publicDataDigest())); + }); if (result == null) { throw unavailable(); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java index c001802deb..089de6f1a0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeService.java @@ -150,10 +150,8 @@ public ReadinessProbePlan planCurrent(Binding binding, TrustFence trust) { inTransaction(() -> repository.readCurrentInventoryObservationContext(binding, trust)); AccountJwtValidatorInventorySource.InventorySnapshot snapshot = inventorySource.observe(observationContext); - return inTransaction( - () -> - repository.planCurrent( - binding, trust, Instant.ofEpochSecond(nowEpochSecond()), snapshot)); + return inTransaction(() -> + repository.planCurrent(binding, trust, Instant.ofEpochSecond(nowEpochSecond()), snapshot)); } /** Rereads protected live inventory before opening the exact receiver target-read transaction. */ @@ -178,10 +176,9 @@ public OwnerProbeEvidence readCurrentProbeOwner( if (!snapshot.namespace().equals(authenticatedWorkloadNamespace)) { throw new AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException(); } - return inTransaction( - () -> - repository.readCurrentProbeOwner( - binding, trust, selector, snapshot, authenticatedWorkloadNamespace)); + return inTransaction(() -> + repository.readCurrentProbeOwner( + binding, trust, selector, snapshot, authenticatedWorkloadNamespace)); } /** Rereads protected live inventory before committing one immutable per-Pod receipt. */ @@ -193,10 +190,8 @@ public ProbeEntry recordPodAcceptance( AuthenticatedAcceptance acceptance) { AccountJwtValidatorInventorySource.InventorySnapshot snapshot = observeCurrentInventory(binding, trust, entry.rotationOperationId()); - return inTransaction( - () -> - repository.recordPodAcceptance( - binding, trust, entry, expectedPod, acceptance, snapshot)); + return inTransaction(() -> + repository.recordPodAcceptance(binding, trust, entry, expectedPod, acceptance, snapshot)); } /** @@ -259,10 +254,9 @@ List issueCurrentPlan( Objects.requireNonNull(claim, "Persisted one-shot delivery claim is required"); Objects.requireNonNull(delivery, "Per-invocation internal delivery is required"); DeliveryClaim persistedClaim = - inTransaction( - () -> - repository.requireCurrentDeliveryClaim( - binding, trust, plan, claim, Instant.ofEpochSecond(nowEpochSecond()))); + inTransaction(() -> + repository.requireCurrentDeliveryClaim( + binding, trust, plan, claim, Instant.ofEpochSecond(nowEpochSecond()))); if (persistedClaim == null || !persistedClaim.equals(claim)) { throw new AccountJwtReadinessProbeRepository.DeliveryAlreadyClaimedException(); } @@ -326,13 +320,9 @@ List issueCurrentPlan( try { pinBeforeDelivery(binding, trust, digest); ProbeEntry issued = - inTransaction( - () -> - repository.recordIssued( - binding, - trust, - digest, - Instant.ofEpochSecond(nowEpochSecond()))); + inTransaction(() -> + repository.recordIssued( + binding, trust, digest, Instant.ofEpochSecond(nowEpochSecond()))); DeliveryMetadata metadata = DeliveryMetadata.from(plan, issued, digest); delivery.deliver(metadata, exactCompactJwt); if (!sha256(exactCompactJwt).equals(metadata.compactTokenSha256())) { @@ -370,29 +360,26 @@ public List abortCurrentPlan(Binding binding, TrustFence trust, UUID /** Expires due entries and performs bounded cleanup for only the named operation. */ public List expireAndClean(Binding binding, TrustFence trust, UUID operationId) { - return inTransaction( - () -> { - repository.expireCurrent( - binding, trust, operationId, Instant.ofEpochSecond(nowEpochSecond())); - return repository.cleanTerminalEntries( - operationId, AccountJwtReadinessProbeRepository.MAX_ENTRIES_PER_OPERATION); - }); + return inTransaction(() -> { + repository.expireCurrent( + binding, trust, operationId, Instant.ofEpochSecond(nowEpochSecond())); + return repository.cleanTerminalEntries( + operationId, AccountJwtReadinessProbeRepository.MAX_ENTRIES_PER_OPERATION); + }); } /** Bounded terminal cleanup never scans outside this explicit operation ID. */ public List cleanTerminalEntries(UUID operationId) { - return inTransaction( - () -> - repository.cleanTerminalEntries( - operationId, AccountJwtReadinessProbeRepository.MAX_ENTRIES_PER_OPERATION)); + return inTransaction(() -> + repository.cleanTerminalEntries( + operationId, AccountJwtReadinessProbeRepository.MAX_ENTRIES_PER_OPERATION)); } private void pinBeforeDelivery(Binding binding, TrustFence trust, SignedProbeDigest digest) { try { - inTransaction( - () -> - repository.recordSigningAttempt( - binding, trust, digest, Instant.ofEpochSecond(nowEpochSecond()))); + inTransaction(() -> + repository.recordSigningAttempt( + binding, trust, digest, Instant.ofEpochSecond(nowEpochSecond()))); } catch (RuntimeException failure) { throw new SigningAttemptConflict(); } @@ -437,22 +424,19 @@ private static boolean exactSignedReadback( && (readback.state() != ProbeState.VERIFIED || readback .verificationReceipt() - .filter( - receipt -> - receipt.sourceEntryVersion() == issuedEntryVersion - && receipt.resultEntryVersion() == resultEntryVersion) + .filter(receipt -> + receipt.sourceEntryVersion() == issuedEntryVersion + && receipt.resultEntryVersion() == resultEntryVersion) .isPresent()) && readback.compactTokenSha256().equals(java.util.Optional.of(signed.compactTokenSha256())); } private List quarantineCurrent(Binding binding, TrustFence trust, UUID operationId) { - return inTransaction( - () -> { - repository.abortCurrent( - binding, trust, operationId, Instant.ofEpochSecond(nowEpochSecond())); - return repository.cleanTerminalEntries( - operationId, AccountJwtReadinessProbeRepository.MAX_ENTRIES_PER_OPERATION); - }); + return inTransaction(() -> { + repository.abortCurrent(binding, trust, operationId, Instant.ofEpochSecond(nowEpochSecond())); + return repository.cleanTerminalEntries( + operationId, AccountJwtReadinessProbeRepository.MAX_ENTRIES_PER_OPERATION); + }); } private ProbeEntry currentEntry( @@ -462,10 +446,9 @@ private ProbeEntry currentEntry( return plan.entries().stream() .filter(entry -> entry.jti().equals(expected.jti())) .findFirst() - .orElseThrow( - () -> - new AccountJwtReadinessProbeRepository.QuarantinedStateException( - "Readiness probe entry disappeared from its immutable plan")); + .orElseThrow(() -> + new AccountJwtReadinessProbeRepository.QuarantinedStateException( + "Readiness probe entry disappeared from its immutable plan")); } private long nowEpochSecond() { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverInvocationPort.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverInvocationPort.java index 88acaea9a6..8cc1e444ad 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverInvocationPort.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverInvocationPort.java @@ -248,18 +248,16 @@ public static final class Invocation { if (expectedActiveGeneration.isPresent() != expectedActiveKid.isPresent()) { throw new IllegalArgumentException("Expected active signer fence is partial"); } - this.expectedActiveGeneration.ifPresent( - value -> { - if (!value.matches("[1-9][0-9]{0,18}")) { - throw new IllegalArgumentException("Expected active generation is malformed"); - } - }); - this.expectedActiveKid.ifPresent( - value -> { - if (!value.matches("[A-Za-z0-9_-]{1,64}")) { - throw new IllegalArgumentException("Expected active key ID is malformed"); - } - }); + this.expectedActiveGeneration.ifPresent(value -> { + if (!value.matches("[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("Expected active generation is malformed"); + } + }); + this.expectedActiveKid.ifPresent(value -> { + if (!value.matches("[A-Za-z0-9_-]{1,64}")) { + throw new IllegalArgumentException("Expected active key ID is malformed"); + } + }); if (issuedAtEpochSecond <= 0L || expiresAtEpochSecond <= issuedAtEpochSecond || expiresAtEpochSecond > planExpiresAtEpochSecond) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverMetadataService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverMetadataService.java index f7c559a191..a1d2352379 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverMetadataService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverMetadataService.java @@ -321,10 +321,9 @@ private static void requirePodDeploymentJoin( InventorySnapshot inventory, ValidatorObservation validator, PodObservation pod) { List ownedReplicaSets = validator.replicaSets().stream() - .filter( - replicaSet -> - replicaSet.uid().equals(pod.ownerUid()) - && replicaSet.name().equals(pod.ownerName())) + .filter(replicaSet -> + replicaSet.uid().equals(pod.ownerUid()) + && replicaSet.name().equals(pod.ownerName())) .toList(); URI endpoint = pod.endpoint(); String endpointHost = endpoint == null ? null : endpoint.getHost(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java index 4e5ab7a257..dc2f696199 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtSignerBootstrapCoordinator.java @@ -170,63 +170,61 @@ public Optional prepareCurrentPromotionOnce() { InventorySnapshot liveInventory = observeCurrentValidatorInventory(sources, request); requireUnchangedProtectedBindings(sources); PreparedPromotion prepared = - accountTransaction.execute( - status -> { - requireUnchangedProtectedBindings(sources); - var proof = - readinessRepository.readCurrentPromotionPrerequisites( - sources.materializerBinding().accountBinding(), - trustFence(sources.materializerBinding()), - request.operationId(), - liveInventory); - if (proof.isEmpty()) { - return null; - } - ReadinessPromotionProof verifiedProof = proof.orElseThrow(); - DesiredState state = - desiredStateRepository.read(sources.materializerBinding().accountBinding()); - EnrollmentIdentity enrollment = - state - .enrollmentIdentity() - .orElseThrow( - () -> - new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS)); - var publication = verifiedProof.publication(); - PromotionPreparation preparation = - new PromotionPreparation( - verifiedProof.generationResult().operationId(), - verifiedProof.generationResult(), - enrollment, - publication.intent().apiBindingDigest(), - publication.intent().apiConfigRevision(), - publication.intent().configMapUid(), - publication.receipt().observedResourceVersion(), - publication.intent().intentDigest(), - publication.receipt().receiptDigest(), - publication.mountedCorrespondence().observationDigest(), - verifiedProof.plan().planDigest(), - verifiedProof.readinessEvidenceDigest(), - publication.intent().jwksJson()); - PreparedPromotion persisted = - desiredStateRepository.prepareCurrentGeneration( - sources.materializerBinding().accountBinding(), - trustFence(sources.materializerBinding()), - preparation, - verifiedProof); - PreparedGenerationEvidence readback = - desiredStateRepository.readPreparedGenerationForRecovery( - sources.materializerBinding().accountBinding(), - trustFence(sources.materializerBinding())); - if (!readback.promotion().operationId().equals(persisted.operationId()) - || !readback.promotion().requestDigest().equals(persisted.requestDigest()) - || !readback.promotion().generationOperationId().equals(request.operationId()) - || !readback.generationResult().equals(verifiedProof.generationResult()) - || !"PREPARED".equals(persisted.status())) { - throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); - } - requireUnchangedProtectedBindings(sources); - return persisted; - }); + accountTransaction.execute(status -> { + requireUnchangedProtectedBindings(sources); + var proof = + readinessRepository.readCurrentPromotionPrerequisites( + sources.materializerBinding().accountBinding(), + trustFence(sources.materializerBinding()), + request.operationId(), + liveInventory); + if (proof.isEmpty()) { + return null; + } + ReadinessPromotionProof verifiedProof = proof.orElseThrow(); + DesiredState state = + desiredStateRepository.read(sources.materializerBinding().accountBinding()); + EnrollmentIdentity enrollment = + state + .enrollmentIdentity() + .orElseThrow( + () -> new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS)); + var publication = verifiedProof.publication(); + PromotionPreparation preparation = + new PromotionPreparation( + verifiedProof.generationResult().operationId(), + verifiedProof.generationResult(), + enrollment, + publication.intent().apiBindingDigest(), + publication.intent().apiConfigRevision(), + publication.intent().configMapUid(), + publication.receipt().observedResourceVersion(), + publication.intent().intentDigest(), + publication.receipt().receiptDigest(), + publication.mountedCorrespondence().observationDigest(), + verifiedProof.plan().planDigest(), + verifiedProof.readinessEvidenceDigest(), + publication.intent().jwksJson()); + PreparedPromotion persisted = + desiredStateRepository.prepareCurrentGeneration( + sources.materializerBinding().accountBinding(), + trustFence(sources.materializerBinding()), + preparation, + verifiedProof); + PreparedGenerationEvidence readback = + desiredStateRepository.readPreparedGenerationForRecovery( + sources.materializerBinding().accountBinding(), + trustFence(sources.materializerBinding())); + if (!readback.promotion().operationId().equals(persisted.operationId()) + || !readback.promotion().requestDigest().equals(persisted.requestDigest()) + || !readback.promotion().generationOperationId().equals(request.operationId()) + || !readback.generationResult().equals(verifiedProof.generationResult()) + || !"PREPARED".equals(persisted.status())) { + throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); + } + requireUnchangedProtectedBindings(sources); + return persisted; + }); if (prepared == null) { return Optional.empty(); } @@ -298,18 +296,17 @@ public void reconcilePreparedPromotionOnce( promotion.expectedPublicJwksJson(), promotion.expectedActiveMarkerJson()); ActiveJwksPromotionReceipt activeReceipt = - accountTransaction.execute( - status -> { - PrivatePromotionReceipt currentPrivateReceipt = - desiredStateRepository.recordPrivatePromotionResult( - binding.accountBinding(), trustFence(binding), observation); - if (!expectedReceipt.equals(currentPrivateReceipt)) { - throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( - "Original private promotion receipt changed before ACTIVE readback recording"); - } - return desiredStateRepository.recordActiveJwksPromotionResult( - binding.accountBinding(), trustFence(binding), activeObservation); - }); + accountTransaction.execute(status -> { + PrivatePromotionReceipt currentPrivateReceipt = + desiredStateRepository.recordPrivatePromotionResult( + binding.accountBinding(), trustFence(binding), observation); + if (!expectedReceipt.equals(currentPrivateReceipt)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Original private promotion receipt changed before ACTIVE readback recording"); + } + return desiredStateRepository.recordActiveJwksPromotionResult( + binding.accountBinding(), trustFence(binding), activeObservation); + }); if (activeReceipt == null) { throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( "Account ACTIVE JWKS receipt is unavailable"); @@ -329,10 +326,9 @@ public void reconcilePreparedPromotionOnce( } PreparedGenerationEvidence afterActiveReceipt = - accountTransaction.execute( - status -> - desiredStateRepository.readPreparedGenerationForRecovery( - binding.accountBinding(), trustFence(binding))); + accountTransaction.execute(status -> + desiredStateRepository.readPreparedGenerationForRecovery( + binding.accountBinding(), trustFence(binding))); if (afterActiveReceipt == null) { throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( "Prepared Account promotion evidence is unavailable after ACTIVE readback"); @@ -383,45 +379,43 @@ private PromotionOwnerSnapshot readPromotionOwnerSnapshot( PrivatePromotionReceipt expectedReceipt) { TrustFence trust = trustFence(binding); PromotionOwnerSnapshot snapshot = - accountTransaction.execute( - status -> { - PrivatePromotionReceipt receipt = - desiredStateRepository.recordPrivatePromotionResult( - binding.accountBinding(), trust, observation); - if (!expectedReceipt.equals(receipt)) { - throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( - "Private promotion receipt changed before Account reconciliation"); - } - try { - PreparedGenerationEvidence prepared = - desiredStateRepository.readPreparedGenerationForRecovery( - binding.accountBinding(), trust); - requirePreparedReceipt(prepared, observation, receipt); - return new PromotionOwnerSnapshot(prepared, null, receipt); - } catch (AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException done) { - CommittedSignerEvidence committed = - desiredStateRepository - .readCurrentCommittedSigner( - binding.accountBinding(), - trust, - apiIdentity.bindingDigest(), - apiIdentity.configRevision()) - .orElseThrow( - () -> - new AccountJwtSignerDesiredStateRepository - .PromotionPrerequisitesIncompleteException( - "Private promotion is neither PREPARED nor currently committed")); - if (!committed.privateReceipt().equals(receipt) - || !committed - .promotion() - .operationId() - .equals(observation.promotionOperationId())) { - throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( - "Committed private promotion retry differs from Account evidence"); - } - return new PromotionOwnerSnapshot(null, committed, receipt); - } - }); + accountTransaction.execute(status -> { + PrivatePromotionReceipt receipt = + desiredStateRepository.recordPrivatePromotionResult( + binding.accountBinding(), trust, observation); + if (!expectedReceipt.equals(receipt)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Private promotion receipt changed before Account reconciliation"); + } + try { + PreparedGenerationEvidence prepared = + desiredStateRepository.readPreparedGenerationForRecovery( + binding.accountBinding(), trust); + requirePreparedReceipt(prepared, observation, receipt); + return new PromotionOwnerSnapshot(prepared, null, receipt); + } catch (AccountJwtSignerDesiredStateRepository.NoPreparedPromotionException done) { + CommittedSignerEvidence committed = + desiredStateRepository + .readCurrentCommittedSigner( + binding.accountBinding(), + trust, + apiIdentity.bindingDigest(), + apiIdentity.configRevision()) + .orElseThrow(() -> + new AccountJwtSignerDesiredStateRepository + .PromotionPrerequisitesIncompleteException( + "Private promotion is neither PREPARED nor currently committed")); + if (!committed.privateReceipt().equals(receipt) + || !committed + .promotion() + .operationId() + .equals(observation.promotionOperationId())) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Committed private promotion retry differs from Account evidence"); + } + return new PromotionOwnerSnapshot(null, committed, receipt); + } + }); if (snapshot == null) { throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( "Account signer promotion evidence is unavailable"); @@ -438,31 +432,29 @@ private ReadinessPromotionProof readPreparedPromotionProof( InventorySnapshot liveInventory) { TrustFence trust = trustFence(binding); ReadinessPromotionProof proof = - accountTransaction.execute( - status -> { - PrivatePromotionReceipt receipt = - desiredStateRepository.recordPrivatePromotionResult( - binding.accountBinding(), trust, observation); - if (!expectedReceipt.equals(receipt)) { - throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( - "Private promotion receipt changed before ACTIVE publication"); - } - PreparedGenerationEvidence current = - desiredStateRepository.readPreparedGenerationForRecovery( - binding.accountBinding(), trust); - requireSamePreparedPromotion(current, expectedPromotion, observation, receipt); - return readinessRepository - .readPromotionProof( - binding.accountBinding(), - trust, - expectedPromotion.generationOperationId(), - liveInventory) - .orElseThrow( - () -> - new AccountJwtSignerDesiredStateRepository - .PromotionPrerequisitesIncompleteException( - "Fresh complete Account readiness proof is unavailable")); - }); + accountTransaction.execute(status -> { + PrivatePromotionReceipt receipt = + desiredStateRepository.recordPrivatePromotionResult( + binding.accountBinding(), trust, observation); + if (!expectedReceipt.equals(receipt)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Private promotion receipt changed before ACTIVE publication"); + } + PreparedGenerationEvidence current = + desiredStateRepository.readPreparedGenerationForRecovery( + binding.accountBinding(), trust); + requireSamePreparedPromotion(current, expectedPromotion, observation, receipt); + return readinessRepository + .readPromotionProof( + binding.accountBinding(), + trust, + expectedPromotion.generationOperationId(), + liveInventory) + .orElseThrow(() -> + new AccountJwtSignerDesiredStateRepository + .PromotionPrerequisitesIncompleteException( + "Fresh complete Account readiness proof is unavailable")); + }); if (proof == null) { throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( "Account readiness proof is unavailable"); @@ -480,34 +472,32 @@ private CommittedSignerEvidence commitPreparedPromotion( InventorySnapshot liveInventory) { TrustFence trust = trustFence(binding); CommittedSignerEvidence committed = - accountTransaction.execute( - status -> { - PrivatePromotionReceipt receipt = - desiredStateRepository.recordPrivatePromotionResult( - binding.accountBinding(), trust, observation); - if (!expectedReceipt.equals(receipt)) { - throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( - "Original private promotion observation no longer matches Account evidence"); - } - PreparedGenerationEvidence current = - desiredStateRepository.readPreparedGenerationForRecovery( - binding.accountBinding(), trust); - requireSamePreparedPromotion(current, expectedPromotion, observation, receipt); - ReadinessPromotionProof proof = - readinessRepository - .readPromotionProof( - binding.accountBinding(), - trust, - expectedPromotion.generationOperationId(), - liveInventory) - .orElseThrow( - () -> - new AccountJwtSignerDesiredStateRepository - .PromotionPrerequisitesIncompleteException( - "Post-CAS complete Account readiness proof is unavailable")); - return desiredStateRepository.commitPreparedPromotion( - binding.accountBinding(), trust, expectedPromotion.operationId(), proof); - }); + accountTransaction.execute(status -> { + PrivatePromotionReceipt receipt = + desiredStateRepository.recordPrivatePromotionResult( + binding.accountBinding(), trust, observation); + if (!expectedReceipt.equals(receipt)) { + throw new AccountJwtSignerDesiredStateRepository.IdempotencyConflictException( + "Original private promotion observation no longer matches Account evidence"); + } + PreparedGenerationEvidence current = + desiredStateRepository.readPreparedGenerationForRecovery( + binding.accountBinding(), trust); + requireSamePreparedPromotion(current, expectedPromotion, observation, receipt); + ReadinessPromotionProof proof = + readinessRepository + .readPromotionProof( + binding.accountBinding(), + trust, + expectedPromotion.generationOperationId(), + liveInventory) + .orElseThrow(() -> + new AccountJwtSignerDesiredStateRepository + .PromotionPrerequisitesIncompleteException( + "Post-CAS complete Account readiness proof is unavailable")); + return desiredStateRepository.commitPreparedPromotion( + binding.accountBinding(), trust, expectedPromotion.operationId(), proof); + }); if (committed == null) { throw new AccountJwtSignerDesiredStateRepository.StorageUnavailableException( "Account signer promotion commit is unavailable"); @@ -676,17 +666,16 @@ private InventorySnapshot observeCurrentValidatorInventory( throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); } ObservationContext context = - accountTransaction.execute( - status -> { - requireUnchangedProtectedBindings(sources); - ObservationContext selected = - readinessRepository.readCurrentInventoryObservationContext( - sources.materializerBinding().accountBinding(), - trustFence(sources.materializerBinding()), - request.operationId()); - requireUnchangedProtectedBindings(sources); - return selected; - }); + accountTransaction.execute(status -> { + requireUnchangedProtectedBindings(sources); + ObservationContext selected = + readinessRepository.readCurrentInventoryObservationContext( + sources.materializerBinding().accountBinding(), + trustFence(sources.materializerBinding()), + request.operationId()); + requireUnchangedProtectedBindings(sources); + return selected; + }); if (context == null) { throw new BootstrapOperationException(FailureCode.VALIDATOR_INVENTORY_UNAVAILABLE); } @@ -759,14 +748,13 @@ private DesiredState initializeEnrollment(EnrollmentSources sources) { sources.materializerBinding().accountBinding(); try { DesiredState initialized = - accountTransaction.execute( - status -> { - requireUnchangedProtectedBindings(sources); - DesiredState persisted = - desiredStateRepository.initialize(accountBinding, sources.enrollmentIdentity()); - requireUnchangedProtectedBindings(sources); - return persisted; - }); + accountTransaction.execute(status -> { + requireUnchangedProtectedBindings(sources); + DesiredState persisted = + desiredStateRepository.initialize(accountBinding, sources.enrollmentIdentity()); + requireUnchangedProtectedBindings(sources); + return persisted; + }); if (initialized == null) { throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); } @@ -784,14 +772,13 @@ private DesiredState readEnrollmentState(EnrollmentSources sources) { sources.materializerBinding().accountBinding(); try { Optional state = - accountTransaction.execute( - status -> { - requireUnchangedProtectedBindings(sources); - Optional current = - desiredStateRepository.readEnrollmentState(accountBinding); - requireUnchangedProtectedBindings(sources); - return current; - }); + accountTransaction.execute(status -> { + requireUnchangedProtectedBindings(sources); + Optional current = + desiredStateRepository.readEnrollmentState(accountBinding); + requireUnchangedProtectedBindings(sources); + return current; + }); if (state == null || state.isEmpty()) { throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); } @@ -832,14 +819,13 @@ private GenerationRequest readCurrentGenerationRequest(EnrollmentSources sources TrustFence trustFence = trustFence(sources.materializerBinding()); try { GenerationRequest request = - accountTransaction.execute( - status -> { - requireUnchangedProtectedBindings(sources); - GenerationRequest current = - desiredStateRepository.readCurrentGenerationRequest(accountBinding, trustFence); - requireUnchangedProtectedBindings(sources); - return current; - }); + accountTransaction.execute(status -> { + requireUnchangedProtectedBindings(sources); + GenerationRequest current = + desiredStateRepository.readCurrentGenerationRequest(accountBinding, trustFence); + requireUnchangedProtectedBindings(sources); + return current; + }); if (request == null) { throw new BootstrapOperationException(FailureCode.ACCOUNT_STATE_AMBIGUOUS); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java index 5b779ced63..7e2a7d3feb 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountJwtValidatorInventorySource.java @@ -920,9 +920,8 @@ private static Map validatorMap(ValidatorObservation validator) result.put( "profiles", validator.profiles().stream() - .map( - profile -> - Map.of("tokenProfile", profile.tokenProfile(), "audience", profile.audience())) + .map(profile -> + Map.of("tokenProfile", profile.tokenProfile(), "audience", profile.audience())) .toList()); result.put( "pods", validator.pods().stream().map(AccountJwtValidatorInventorySource::podMap).toList()); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java index df26c62b31..dfebf340c6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java @@ -50,11 +50,10 @@ public void requireHeld(AccountPublicationAuthorizationReadEvidence.Request requ .asRuntimeException(); } try { - ownerTransaction.execute( - status -> { - repository.readHeld(request.binding()); - return null; - }); + ownerTransaction.execute(status -> { + repository.readHeld(request.binding()); + return null; + }); } catch (StatusRuntimeException failure) { throw failure; } catch (IllegalArgumentException inconsistent) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java index 729a47bd3c..038424413b 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationService.java @@ -99,92 +99,89 @@ public AccountRecentReauthenticationEvidence reauthenticate(Request request) { Attempt attempt; try { attempt = - transaction.execute( - ignored -> { - evidenceRepository.lockRequest(request.requestId); - Optional existingRequest = - evidenceRepository.findByRequest(request.requestId); - if (existingRequest.isPresent()) { - AccountRecentReauthenticationEvidence existing = existingRequest.orElseThrow(); - requireExactRequest(existing, request); - return replayAttempt(existing, credentialRequest); - } - if (!PURPOSE.equals(request.purpose)) { - throw conflict(); - } - - evidenceRepository.lockCreationOperation(request.creationOperationId); - if (evidenceRepository - .findByCreationOperation(request.creationOperationId) - .isPresent()) { - throw conflict(); - } - - // Resolve and lock the current policy before primary authentication. Missing policy - // therefore cannot consume an OTP or commit a new authentication grant. - AccountRecentReauthenticationPolicy.Effective policy = - policyRepository.resolveCurrentForGameCreation(); - Account account = requireCurrentAccount(request.accountId); - String email = EmailCanonicalization.normalize(request.email); - if (!email.equals(EmailCanonicalization.normalize(account.getEmail()))) { - throw conflict(); - } - - ControlUiPrimaryIdentity authenticated; - try { - authenticated = - primaryAuthentication.authenticateControlUiPrimaryIdentity( - email, request.secret); - } catch (AuthenticationException denied) { - // Return the denial from the transaction callback so normal failed-attempt - // accounting commits. A successful OTP remains rollback-capable with retention. - return Attempt.denied(denied.getCode(), denied.getMessage()); - } - if (!request.accountId.equals(authenticated.accountId()) - || !request.accountId.equals(account.getAccountUuid())) { - throw conflict(); - } - - ScopeState authority = generations.read(AuthorityScope.account(request.accountId)); - requireAccountAuthority(request.accountId, authority); - IssuanceFence fence = Objects.requireNonNull(authority.issuanceFence()); - var issuedAt = clock.instant().truncatedTo(ChronoUnit.MICROS); - byte[] requestPayload = - AccountRecentReauthenticationRepository.requestPayload( - request.requestId, - request.accountId, - request.purpose, - request.creationOperationId); - var evidence = - new AccountRecentReauthenticationEvidence( - UUID.randomUUID(), - request.requestId, - request.accountId, - request.purpose, - request.creationOperationId, - AccountRecentReauthenticationRepository.digest(requestPayload), - account.getAccountUuidProvenance(), - account.getAccountUuidSourceNumericId(), - account.getLifecycleState(), - authority.generation(), - authority.sourceVersion(), - fence.value(), - fence.sourceVersion(), - policy.platformVersion(), - policy.deploymentVersion(), - policy.effectivePolicyVersion(), - policy.recentAgeSeconds(), - policy.maxClockSkewSeconds(), - issuedAt); - String keyId = cryptography.currentKeyId(); - var replayProof = - new AccountRecentReauthenticationRepository.ReplayProof( - keyId, - cryptography.recentReauthenticationRequestMac(keyId, credentialRequest)); - evidenceRepository.insert(evidence, requestPayload, replayProof); - return Attempt.success( - evidenceRepository.findByRequest(request.requestId).orElseThrow()); - }); + transaction.execute(ignored -> { + evidenceRepository.lockRequest(request.requestId); + Optional existingRequest = + evidenceRepository.findByRequest(request.requestId); + if (existingRequest.isPresent()) { + AccountRecentReauthenticationEvidence existing = existingRequest.orElseThrow(); + requireExactRequest(existing, request); + return replayAttempt(existing, credentialRequest); + } + if (!PURPOSE.equals(request.purpose)) { + throw conflict(); + } + + evidenceRepository.lockCreationOperation(request.creationOperationId); + if (evidenceRepository + .findByCreationOperation(request.creationOperationId) + .isPresent()) { + throw conflict(); + } + + // Resolve and lock the current policy before primary authentication. Missing policy + // therefore cannot consume an OTP or commit a new authentication grant. + AccountRecentReauthenticationPolicy.Effective policy = + policyRepository.resolveCurrentForGameCreation(); + Account account = requireCurrentAccount(request.accountId); + String email = EmailCanonicalization.normalize(request.email); + if (!email.equals(EmailCanonicalization.normalize(account.getEmail()))) { + throw conflict(); + } + + ControlUiPrimaryIdentity authenticated; + try { + authenticated = + primaryAuthentication.authenticateControlUiPrimaryIdentity(email, request.secret); + } catch (AuthenticationException denied) { + // Return the denial from the transaction callback so normal failed-attempt + // accounting commits. A successful OTP remains rollback-capable with retention. + return Attempt.denied(denied.getCode(), denied.getMessage()); + } + if (!request.accountId.equals(authenticated.accountId()) + || !request.accountId.equals(account.getAccountUuid())) { + throw conflict(); + } + + ScopeState authority = generations.read(AuthorityScope.account(request.accountId)); + requireAccountAuthority(request.accountId, authority); + IssuanceFence fence = Objects.requireNonNull(authority.issuanceFence()); + var issuedAt = clock.instant().truncatedTo(ChronoUnit.MICROS); + byte[] requestPayload = + AccountRecentReauthenticationRepository.requestPayload( + request.requestId, + request.accountId, + request.purpose, + request.creationOperationId); + var evidence = + new AccountRecentReauthenticationEvidence( + UUID.randomUUID(), + request.requestId, + request.accountId, + request.purpose, + request.creationOperationId, + AccountRecentReauthenticationRepository.digest(requestPayload), + account.getAccountUuidProvenance(), + account.getAccountUuidSourceNumericId(), + account.getLifecycleState(), + authority.generation(), + authority.sourceVersion(), + fence.value(), + fence.sourceVersion(), + policy.platformVersion(), + policy.deploymentVersion(), + policy.effectivePolicyVersion(), + policy.recentAgeSeconds(), + policy.maxClockSkewSeconds(), + issuedAt); + String keyId = cryptography.currentKeyId(); + var replayProof = + new AccountRecentReauthenticationRepository.ReplayProof( + keyId, cryptography.recentReauthenticationRequestMac(keyId, credentialRequest)); + evidenceRepository.insert(evidence, requestPayload, replayProof); + return Attempt.success( + evidenceRepository.findByRequest(request.requestId).orElseThrow()); + }); if (attempt == null) { throw unavailable(); } @@ -193,12 +190,11 @@ public AccountRecentReauthenticationEvidence reauthenticate(Request request) { } var expected = Objects.requireNonNull(attempt.evidence); Attempt readback = - transaction.execute( - ignored -> { - evidenceRepository.lockRequest(expected.requestId()); - var retained = evidenceRepository.readExactOriginal(expected); - return replayAttempt(retained, credentialRequest); - }); + transaction.execute(ignored -> { + evidenceRepository.lockRequest(expected.requestId()); + var retained = evidenceRepository.readExactOriginal(expected); + return replayAttempt(retained, credentialRequest); + }); if (readback == null) throw unavailable(); if (readback.denial != null) { throw new AuthenticationException(readback.denial.code, readback.denial.message); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java index 14ebe403b7..325cb68045 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java @@ -89,24 +89,19 @@ public byte[] settle(byte[] originalOperation) { requireNoAmbientTransaction(); byte[] receipt = Objects.requireNonNull( - ownerTransaction.execute( - ignored -> - repository.settle( - operation, - terminal, - world.worldOutcome().name(), - world.worldTerminalEvidence()))); - // A second transaction establishes post-commit historical readback; no new issuer or - // credential capture is involved. Neither SQL phase can contain an owner RPC. - requireNoAmbientTransaction(); - byte[] committed = - ownerTransaction.execute( - ignored -> + ownerTransaction.execute(ignored -> repository.settle( operation, terminal, world.worldOutcome().name(), - world.worldTerminalEvidence())); + world.worldTerminalEvidence()))); + // A second transaction establishes post-commit historical readback; no new issuer or + // credential capture is involved. Neither SQL phase can contain an owner RPC. + requireNoAmbientTransaction(); + byte[] committed = + ownerTransaction.execute(ignored -> + repository.settle( + operation, terminal, world.worldOutcome().name(), world.worldTerminalEvidence())); if (!Arrays.equals(receipt, committed)) { throw new IllegalStateException("Committed Account settlement readback differs from receipt"); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadService.java index 1895937609..7410540c07 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadService.java @@ -45,11 +45,10 @@ public void requireHeld(SelectedOwnerIntakeAuthorizationReadEvidence.Request req throw Status.FAILED_PRECONDITION.asRuntimeException(); } try { - ownerTransaction.execute( - ignored -> { - repository.readHeldFinalAuthorization(request.binding()); - return null; - }); + ownerTransaction.execute(ignored -> { + repository.readHeldFinalAuthorization(request.binding()); + return null; + }); } catch (StatusRuntimeException failure) { throw failure; } catch (IllegalArgumentException changedOrAbsent) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java index 238be12848..2824751e46 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java @@ -75,14 +75,13 @@ public SelectedOwnerIntakeAuthorizationBinding authorizeWithEnvironmentCapture( SelectedOwnerIntakeSourceReadScope scope = findScope(originalCreatorCredential, intakeRequestId, owner, selected) - .orElseGet( - () -> - reserveSourceRead( - originalCreatorCredential, - intakeRequestId, - owner, - selected, - requireEnvironment(environmentCapture.get()))); + .orElseGet(() -> + reserveSourceRead( + originalCreatorCredential, + intakeRequestId, + owner, + selected, + requireEnvironment(environmentCapture.get()))); var recovery = recover(scope); if (recovery.state() == AccountSelectedOwnerIntakeSourceReservationRepository.State.ABORTED) throw denied("Original selected-owner intake reservation was aborted"); @@ -188,10 +187,9 @@ private Optional findScope( AccountControlUiIssuanceRepository.hash( originalCreatorCredential.getBytes(StandardCharsets.US_ASCII)); return Objects.requireNonNull( - ownerTransaction.execute( - ignored -> - repository.findSourceReadScope( - intakeRequestId, owner, selected, namespace, tokenHash))); + ownerTransaction.execute(ignored -> + repository.findSourceReadScope( + intakeRequestId, owner, selected, namespace, tokenHash))); } private AccountSelectedOwnerIntakeSourceReservationRepository.Recovery recover( @@ -215,11 +213,10 @@ private SelectedOwnerIntakeAuthorizationBinding readFinalAuthorization( Objects.requireNonNull(requested, "finalized selected-owner authorization is required"); requireScope(requested.content().scope()); outsideSql(); - ownerTransaction.execute( - ignored -> { - repository.readFinalAuthorization(requested); - return null; - }); + ownerTransaction.execute(ignored -> { + repository.readFinalAuthorization(requested); + return null; + }); return requested; } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java index ffc0dacc05..f6013c346e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java @@ -84,22 +84,21 @@ public AccountSelectedOwnerIntakeSettlementReceipt settle( requireOriginalBinding(original); Lookup lookup = - ownerTransaction.execute( - ignored -> { - try { - repository.readFinalAuthorization(original); - Optional prior = - Objects.requireNonNull( - repository.findSettlement(original), - "Account settlement lookup returned no result"); - return new Lookup(prior.orElse(null)); - } catch (IllegalArgumentException absentOrChanged) { - throw Status.FAILED_PRECONDITION - .withDescription("Exact finalized selected-owner authorization is unavailable") - .withCause(absentOrChanged) - .asRuntimeException(); - } - }); + ownerTransaction.execute(ignored -> { + try { + repository.readFinalAuthorization(original); + Optional prior = + Objects.requireNonNull( + repository.findSettlement(original), + "Account settlement lookup returned no result"); + return new Lookup(prior.orElse(null)); + } catch (IllegalArgumentException absentOrChanged) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact finalized selected-owner authorization is unavailable") + .withCause(absentOrChanged) + .asRuntimeException(); + } + }); if (lookup == null) { throw Status.FAILED_PRECONDITION .withDescription("Account authorization transaction returned no result") @@ -211,21 +210,19 @@ private AccountSelectedOwnerIntakeSettlementReceipt commitAndReadBack( requireNoAmbientTransaction(); boolean entityOwner = original.owner() == Owner.ENTITY_MANAGEMENT; AccountSelectedOwnerIntakeSettlementReceipt readback = - ownerTransaction.execute( - ignored -> - Objects.requireNonNull( - repository.findSettlement(original), - entityOwner - ? "Account lookup returned no result" - : "Account settlement readback returned no result") - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription( - entityOwner - ? "Committed Account Entity settlement is not readable" - : "Committed Account settlement is not readable") - .asRuntimeException())); + ownerTransaction.execute(ignored -> + Objects.requireNonNull( + repository.findSettlement(original), + entityOwner + ? "Account lookup returned no result" + : "Account settlement readback returned no result") + .orElseThrow(() -> + Status.FAILED_PRECONDITION + .withDescription( + entityOwner + ? "Committed Account Entity settlement is not readable" + : "Committed Account settlement is not readable") + .asRuntimeException())); requireSettlement(readback, original, exactOwnerTerminal); if (!sameSettlement(committed, readback)) { throw Status.FAILED_PRECONDITION diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java index 59f97e0136..1546c5c240 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadService.java @@ -67,11 +67,10 @@ public SelectedOwnerIntakeSourceReadScope readSourceScope( .asRuntimeException(); } return Objects.requireNonNull( - transaction.execute( - ignored -> { - repository.readSourceScope(scope, current); - return scope; - })); + transaction.execute(ignored -> { + repository.readSourceScope(scope, current); + return scope; + })); } private String intendedReader(Owner owner) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java index 822596e9c6..0a55d185a6 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationRepository.java @@ -948,14 +948,13 @@ private void requireTransaction() { || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { throw new IllegalStateException("Writable Account owner transaction required"); } - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new IllegalStateException( - "Writable READ_COMMITTED Account owner transaction required"); - } - }); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Writable READ_COMMITTED Account owner transaction required"); + } + }); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java index 9af79b25db..284537133d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java @@ -119,11 +119,10 @@ public AccountSelectedOwnerIntakeSourceReservationRepository.Recovery recover( Objects.requireNonNull(selected, "selected"); var scope = findScope(originalCompactJwt, intakeRequestId, owner, selected) - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription("Original source-read reservation is unavailable") - .asRuntimeException()); + .orElseThrow(() -> + Status.FAILED_PRECONDITION + .withDescription("Original source-read reservation is unavailable") + .asRuntimeException()); return recover(scope); } @@ -146,11 +145,10 @@ public AccountSelectedOwnerIntakeSourceReservationRepository.Recovery abortSourc Objects.requireNonNull(selected, "selected"); var scope = findScope(originalCompactJwt, intakeRequestId, owner, selected) - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription("Original source-read reservation is unavailable") - .asRuntimeException()); + .orElseThrow(() -> + Status.FAILED_PRECONDITION + .withDescription("Original source-read reservation is unavailable") + .asRuntimeException()); return abortSourceRead(scope); } @@ -177,10 +175,9 @@ public RecoveryPage recoverExpiredPreliminarySourceReads( var page = Objects.requireNonNull( - ownerTransaction.execute( - ignored -> - repository.findExpiredPreliminarySourceReadScopes( - boundedCandidates, namespace, after)), + ownerTransaction.execute(ignored -> + repository.findExpiredPreliminarySourceReadScopes( + boundedCandidates, namespace, after)), "Expired source-read candidate lookup returned no result"); int aborted = 0; int candidateNumber = 0; @@ -221,10 +218,9 @@ private Optional findScope( AccountControlUiIssuanceRepository.hash( originalCompactJwt.getBytes(StandardCharsets.US_ASCII)); return Objects.requireNonNull( - ownerTransaction.execute( - ignored -> - repository.findSourceReadScope( - intakeRequestId, owner, selected, namespace, tokenHash))); + ownerTransaction.execute(ignored -> + repository.findSourceReadScope( + intakeRequestId, owner, selected, namespace, tokenHash))); } private void requireScope(SelectedOwnerIntakeSourceReadScope scope) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java index 190a47e7b6..af92dd2c73 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java @@ -44,11 +44,10 @@ public void requireHeld( throw Status.FAILED_PRECONDITION.asRuntimeException(); } try { - ownerTransaction.execute( - ignored -> { - repository.readHeldFinalAuthorization(request.binding()); - return null; - }); + ownerTransaction.execute(ignored -> { + repository.readHeldFinalAuthorization(request.binding()); + return null; + }); } catch (StatusRuntimeException failure) { throw failure; } catch (IllegalArgumentException changedOrAbsent) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionService.java index dd56d3addc..44f9bd6b9d 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionService.java @@ -137,10 +137,9 @@ public AccountStartSessionActivationProtectionEvidence acquire( StoredParticipation exactParticipation = participationRepository .findHistoricalForOriginalTuple(tupleBytes) - .orElseThrow( - () -> - failedPrecondition( - "Exact committed original World participation is unavailable")); + .orElseThrow(() -> + failedPrecondition( + "Exact committed original World participation is unavailable")); requireSameParticipation(initiallyRetained, exactParticipation); requireCommittedParticipation(exactParticipation); requireExactRetainedAttempt(exactParticipation, attemptRequest, currentAttempt); @@ -150,16 +149,14 @@ public AccountStartSessionActivationProtectionEvidence acquire( requireNoAmbientTransaction(); StoredProtection readback = Objects.requireNonNull( - readbackTransaction.execute( - ignored -> - protectionRepository - .findHistoricalExact( - committed.evidence().accountProtectionId(), - committed.evidence().accountProtectionFence()) - .orElseThrow( - () -> - failedPrecondition( - "Committed original activation protection is not readable"))), + readbackTransaction.execute(ignored -> + protectionRepository + .findHistoricalExact( + committed.evidence().accountProtectionId(), + committed.evidence().accountProtectionFence()) + .orElseThrow(() -> + failedPrecondition( + "Committed original activation protection is not readable"))), "Account activation protection readback transaction returned no value"); if (!Arrays.equals( committed.evidence().canonicalBytes(), readback.evidence().canonicalBytes())) { @@ -171,19 +168,16 @@ public AccountStartSessionActivationProtectionEvidence acquire( private StoredParticipation readCommittedParticipation( byte[] tupleBytes, AccountStartSessionActivationProtectionAcquisitionInput input) { return Objects.requireNonNull( - ownerTransaction.execute( - ignored -> { - StoredParticipation participation = - participationRepository - .findHistoricalForOriginalTuple(tupleBytes) - .orElseThrow( - () -> - failedPrecondition( - "Exact original World participation is unavailable")); - requireTupleAndWorldBinding(participation, tupleBytes, input); - requireCommittedParticipation(participation); - return participation; - }), + ownerTransaction.execute(ignored -> { + StoredParticipation participation = + participationRepository + .findHistoricalForOriginalTuple(tupleBytes) + .orElseThrow(() -> + failedPrecondition("Exact original World participation is unavailable")); + requireTupleAndWorldBinding(participation, tupleBytes, input); + requireCommittedParticipation(participation); + return participation; + }), "Account World participation transaction returned no value"); } @@ -208,10 +202,8 @@ private void requireExactRetainedAttempt( // Read the immutable first witness without reopening that participation. Currentness // comes from the separate authenticated fresh read and Account's admission callback. .findHistoricalExact(participation, expectedRequest) - .orElseThrow( - () -> - failedPrecondition( - "Exact retained original Game Session attempt is unavailable")); + .orElseThrow(() -> + failedPrecondition("Exact retained original Game Session attempt is unavailable")); var stored = retained.result(); if (!OriginalStartSessionCurrentAttemptEvidence.PENDING_PHASE.equals(stored.phaseState()) || !stored.originalLeaseExpiresAt().equals(observed.originalLeaseExpiresAt()) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementService.java index f1621b65f7..b7eae040a0 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementService.java @@ -61,24 +61,22 @@ public AccountStartSessionActivationProtectionSettlementEvidence settle( Lookup lookup = Objects.requireNonNull( - ownerTransaction.execute( - ignored -> { - StoredProtection protection = - repository - .findHistoricalExact( - input.accountProtectionId(), input.accountProtectionFence()) - .orElseThrow( - () -> - failedPrecondition( - "Exact historical Account activation protection is unavailable")); - requireTargetBinding(protection, input.targetNamespace()); - StoredSettlement settled = - repository - .findSettlementExact( - input.accountProtectionId(), input.accountProtectionFence()) - .orElse(null); - return new Lookup(protection, settled); - }), + ownerTransaction.execute(ignored -> { + StoredProtection protection = + repository + .findHistoricalExact( + input.accountProtectionId(), input.accountProtectionFence()) + .orElseThrow(() -> + failedPrecondition( + "Exact historical Account activation protection is unavailable")); + requireTargetBinding(protection, input.targetNamespace()); + StoredSettlement settled = + repository + .findSettlementExact( + input.accountProtectionId(), input.accountProtectionFence()) + .orElse(null); + return new Lookup(protection, settled); + }), "Account activation-protection lookup transaction returned no result"); if (lookup.settlement() != null) { @@ -124,15 +122,13 @@ public AccountStartSessionActivationProtectionSettlementEvidence settle( requireNoAmbientTransaction(); StoredSettlement readback = Objects.requireNonNull( - readbackTransaction.execute( - ignored -> - repository - .findSettlementExact( - input.accountProtectionId(), input.accountProtectionFence()) - .orElseThrow( - () -> - failedPrecondition( - "Committed World activation settlement is not readable"))), + readbackTransaction.execute(ignored -> + repository + .findSettlementExact( + input.accountProtectionId(), input.accountProtectionFence()) + .orElseThrow(() -> + failedPrecondition( + "Committed World activation settlement is not readable"))), "Account activation settlement readback transaction returned no value"); if (!sameSettlement(committed, readback)) { throw failedPrecondition("Committed World activation settlement readback differs"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java index 883cc3358f..dea14fb0cd 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java @@ -98,18 +98,16 @@ public AccountStartSessionAdmissionProtectionEvidence acquire( StoredParticipation exactParticipation = participationRepository .findHistoricalForOriginalTuple(tupleBytes) - .orElseThrow( - () -> - failedPrecondition( - "Exact original Account participation is unavailable")); + .orElseThrow(() -> + failedPrecondition( + "Exact original Account participation is unavailable")); requireSameParticipation(initial.participation(), exactParticipation); StoredEvidence retainedAttempt = attemptRepository .findHistoricalExact(exactParticipation, currentAttemptRequest) - .orElseThrow( - () -> - failedPrecondition( - "Exact original Account attempt evidence is unavailable")); + .orElseThrow(() -> + failedPrecondition( + "Exact original Account attempt evidence is unavailable")); requireSameAttempt(retainedAttempt.result(), observed); return protectionRepository.acquireOrReadExact(request, capture, exactParticipation); }); @@ -117,17 +115,15 @@ public AccountStartSessionAdmissionProtectionEvidence acquire( requireNoAmbientTransaction(); StoredProtection readback = Objects.requireNonNull( - readbackTransaction.execute( - ignored -> - protectionRepository - .findCurrentExact( - committed.evidence().accountProtectionId(), - committed.evidence().accountProtectionFence(), - request.canonicalBytes()) - .orElseThrow( - () -> - failedPrecondition( - "Committed current admission protection is not readable"))), + readbackTransaction.execute(ignored -> + protectionRepository + .findCurrentExact( + committed.evidence().accountProtectionId(), + committed.evidence().accountProtectionFence(), + request.canonicalBytes()) + .orElseThrow(() -> + failedPrecondition( + "Committed current admission protection is not readable"))), "Account admission protection readback transaction returned no value"); if (!Arrays.equals( committed.evidence().canonicalBytes(), readback.evidence().canonicalBytes())) { @@ -142,29 +138,24 @@ private InitialOwnerState readInitialOwnerState( AccountStartSessionAdmissionProtectionRequest request) { requireNoAmbientTransaction(); return Objects.requireNonNull( - lookupTransaction.execute( - ignored -> { - StoredParticipation participation = - participationRepository - .findHistoricalForOriginalTuple(tupleBytes) - .orElseThrow( - () -> - failedPrecondition( - "Exact original Account participation is unavailable")); - requireParticipationBinding(request, participation); - // World preparation is already COMMITTED, so its Account participation is settled. - // Read the immutable original witness here; currentness comes from the fresh - // authenticated Game Session observation and the Account callback below. - StoredEvidence attempt = - attemptRepository - .findHistoricalExact(participation, currentAttemptRequest) - .orElseThrow( - () -> - failedPrecondition( - "Exact original Account attempt evidence is unavailable")); - requireStoredAttemptBinding(request, currentAttemptRequest, attempt.result()); - return new InitialOwnerState(participation, attempt); - }), + lookupTransaction.execute(ignored -> { + StoredParticipation participation = + participationRepository + .findHistoricalForOriginalTuple(tupleBytes) + .orElseThrow(() -> + failedPrecondition("Exact original Account participation is unavailable")); + requireParticipationBinding(request, participation); + // World preparation is already COMMITTED, so its Account participation is settled. + // Read the immutable original witness here; currentness comes from the fresh + // authenticated Game Session observation and the Account callback below. + StoredEvidence attempt = + attemptRepository + .findHistoricalExact(participation, currentAttemptRequest) + .orElseThrow(() -> + failedPrecondition("Exact original Account attempt evidence is unavailable")); + requireStoredAttemptBinding(request, currentAttemptRequest, attempt.result()); + return new InitialOwnerState(participation, attempt); + }), "Account initial owner-state transaction returned no value"); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java index 532b086185..a3bb48ea39 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java @@ -62,21 +62,19 @@ public AccountStartSessionAdmissionProtectionSettlementEvidence settle( Lookup lookup = Objects.requireNonNull( - lookupTransaction.execute( - ignored -> { - StoredProtection protection = - repository - .findHistoricalExact(protectionId, protectionFence) - .orElseThrow( - () -> - failedPrecondition( - "Exact historical Account admission protection is unavailable")); - requireExactProtection(protection, protectionId, protectionFence); - requireTargetBinding(protection); - StoredSettlement settled = - repository.findSettlementExact(protectionId, protectionFence).orElse(null); - return new Lookup(protection, settled); - }), + lookupTransaction.execute(ignored -> { + StoredProtection protection = + repository + .findHistoricalExact(protectionId, protectionFence) + .orElseThrow(() -> + failedPrecondition( + "Exact historical Account admission protection is unavailable")); + requireExactProtection(protection, protectionId, protectionFence); + requireTargetBinding(protection); + StoredSettlement settled = + repository.findSettlementExact(protectionId, protectionFence).orElse(null); + return new Lookup(protection, settled); + }), "Account admission protection lookup transaction returned no value"); if (lookup.settlement() != null) { @@ -129,14 +127,12 @@ public AccountStartSessionAdmissionProtectionSettlementEvidence settle( requireNoAmbientTransaction(); StoredSettlement readback = Objects.requireNonNull( - readbackTransaction.execute( - ignored -> - repository - .findSettlementExact(protectionId, protectionFence) - .orElseThrow( - () -> - failedPrecondition( - "Committed Game Session terminal settlement is not readable"))), + readbackTransaction.execute(ignored -> + repository + .findSettlementExact(protectionId, protectionFence) + .orElseThrow(() -> + failedPrecondition( + "Committed Game Session terminal settlement is not readable"))), "Account admission settlement readback transaction returned no value"); if (!Arrays.equals(committed.canonicalBytes(), readback.canonicalBytes())) { throw failedPrecondition("Committed admission settlement readback differs"); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java index 3b6ae7a0ff..8859a16516 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java @@ -157,25 +157,23 @@ public AcquiredParticipation acquire(AcquisitionRequest request) { requireNoAmbientTransaction(); Readback readback = Objects.requireNonNull( - readbackTransaction.execute( - ignored -> { - Optional participation = - Objects.requireNonNull( - participationRepository.findCurrentExact(commit.candidate()), - "Current participation lookup returned no optional"); - if (participation.isEmpty()) { - throw denied("Committed exact World participation is not readable as current"); - } - StoredParticipation actualParticipation = participation.orElseThrow(); - StoredEvidence actualEvidence = - attemptEvidenceRepository - .findCurrentExact(actualParticipation, commit.request()) - .orElseThrow( - () -> - denied( - "Committed original Game Session attempt evidence is not readable")); - return new Readback(actualParticipation, actualEvidence); - }), + readbackTransaction.execute(ignored -> { + Optional participation = + Objects.requireNonNull( + participationRepository.findCurrentExact(commit.candidate()), + "Current participation lookup returned no optional"); + if (participation.isEmpty()) { + throw denied("Committed exact World participation is not readable as current"); + } + StoredParticipation actualParticipation = participation.orElseThrow(); + StoredEvidence actualEvidence = + attemptEvidenceRepository + .findCurrentExact(actualParticipation, commit.request()) + .orElseThrow(() -> + denied( + "Committed original Game Session attempt evidence is not readable")); + return new Readback(actualParticipation, actualEvidence); + }), "Account World participation readback transaction returned no result"); if (!sameParticipation(commit.participation(), readback.participation()) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java index 231b98da08..06b12fe8c3 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java @@ -57,16 +57,13 @@ public AccountStartSessionWorldParticipationHistoricalReadEvidence read( StoredParticipation participation = Objects.requireNonNull( - ownerTransaction.execute( - ignored -> - repository - .findHistoricalForOriginalTuple(request.originalPostAuthorizationTuple()) - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription( - "Exact historical World participation is unavailable") - .asRuntimeException())), + ownerTransaction.execute(ignored -> + repository + .findHistoricalForOriginalTuple(request.originalPostAuthorizationTuple()) + .orElseThrow(() -> + Status.FAILED_PRECONDITION + .withDescription("Exact historical World participation is unavailable") + .asRuntimeException())), "Account historical participation transaction returned no result"); if (!java.security.MessageDigest.isEqual( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java index 5b3e786ca4..04ee021547 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java @@ -63,27 +63,25 @@ public StoredSettlement settle(UUID participationId, long participationFence) { Lookup lookup = Objects.requireNonNull( - ownerTransaction.execute( - ignored -> { - StoredParticipation participation = - repository - .findHistoricalExact(participationId, participationFence) - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription( - "Exact historical World participation is unavailable") - .asRuntimeException()); - if (!workloadNamespace.equals(participation.targetNamespace())) { - throw Status.PERMISSION_DENIED - .withDescription( - "World participation target namespace differs from authenticated peer") - .asRuntimeException(); - } - Optional settled = - repository.findSettlementExact(participationId, participationFence); - return new Lookup(participation, settled.orElse(null)); - }), + ownerTransaction.execute(ignored -> { + StoredParticipation participation = + repository + .findHistoricalExact(participationId, participationFence) + .orElseThrow(() -> + Status.FAILED_PRECONDITION + .withDescription( + "Exact historical World participation is unavailable") + .asRuntimeException()); + if (!workloadNamespace.equals(participation.targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription( + "World participation target namespace differs from authenticated peer") + .asRuntimeException(); + } + Optional settled = + repository.findSettlementExact(participationId, participationFence); + return new Lookup(participation, settled.orElse(null)); + }), "Account participation lookup transaction returned no result"); if (lookup.settlement() != null) return lookup.settlement(); @@ -113,16 +111,13 @@ public StoredSettlement settle(UUID participationId, long participationFence) { requireNoAmbientTransaction(); StoredSettlement readback = Objects.requireNonNull( - ownerTransaction.execute( - ignored -> - repository - .findSettlementExact(participationId, participationFence) - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription( - "Committed World terminal settlement is not readable") - .asRuntimeException())), + ownerTransaction.execute(ignored -> + repository + .findSettlementExact(participationId, participationFence) + .orElseThrow(() -> + Status.FAILED_PRECONDITION + .withDescription("Committed World terminal settlement is not readable") + .asRuntimeException())), "Account terminal settlement readback transaction returned no receipt"); if (!sameSettlement(committed, readback)) { throw Status.FAILED_PRECONDITION diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionOwner.java index 37df7bb4ba..8515c4fc17 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionOwner.java @@ -115,16 +115,15 @@ public PreparedResult start( // rows, the original issuance bytes, and their binding have survived the first transaction. Frozen frozen = Objects.requireNonNull( - readTransaction.execute( - ignored -> { - Persisted persisted = readPersisted(initial.binding, false); - requireSameFrozen(initial, persisted, true); - if (initial.admitted != null && persisted.admitted == null) throw denied(); - if (persisted.admitted != null && initial.admitted != null) { - requireSameAdmitted(initial.admitted, persisted.admitted); - } - return initial.withPersisted(persisted); - })); + readTransaction.execute(ignored -> { + Persisted persisted = readPersisted(initial.binding, false); + requireSameFrozen(initial, persisted, true); + if (initial.admitted != null && persisted.admitted == null) throw denied(); + if (persisted.admitted != null && initial.admitted != null) { + requireSameAdmitted(initial.admitted, persisted.admitted); + } + return initial.withPersisted(persisted); + })); String originalKid = AccountTenantCreationOwnerChecks.originalKid( @@ -178,12 +177,11 @@ public PreparedResult recover( Persisted original = Objects.requireNonNull( - readTransaction.execute( - ignored -> { - Persisted stored = readPersisted(null, true, creationOperationId); - requireRecoveryEvidenceIdentity(stored.intent, recentReauthentication); - return stored; - })); + readTransaction.execute(ignored -> { + Persisted stored = readPersisted(null, true, creationOperationId); + requireRecoveryEvidenceIdentity(stored.intent, recentReauthentication); + return stored; + })); if (original.admitted == null) throw denied(); if (!configuredNamespace.equals(original.intent.targetNamespace())) throw denied(); @@ -587,9 +585,8 @@ private static void requireExactSourceVector(List sources) { if (!sources.equals(sorted) || sources.stream().map(SourceEvidence::key).distinct().count() != sources.size() || sources.stream() - .anyMatch( - source -> - source.kind() == SourceKind.TENANT || source.kind() == SourceKind.MEMBERSHIP)) { + .anyMatch(source -> + source.kind() == SourceKind.TENANT || source.kind() == SourceKind.MEMBERSHIP)) { throw denied(); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAuthorizationPreparation.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAuthorizationPreparation.java index 0317c3543c..abcfa04dbc 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAuthorizationPreparation.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAuthorizationPreparation.java @@ -68,49 +68,45 @@ Prepared prepare( AccountTenantCreationSourceOrderBinding stored = Objects.requireNonNull( - transactions.execute( - status -> { - Original current = read(creationOperationId); - same(first, current); - AccountControlUiActorService.requireAcceptedSignerKey(current.issuance, accepted); - var sources = - capture.captureLocked( - current.intent, current.admitted, environment, reauthentication); - if (!Arrays.equals(sources.originalClaims(), current.issuance.claims) - || !Arrays.equals( - sources.originalSignerReceipt(), current.issuance.signerReceipt) - || !current.issuance.operationId.equals(sources.issuanceOperationId()) - || !current.issuance.jti.equals(sources.tokenJti()) - || !current.issuance.tokenHash.equals(sources.tokenHash())) { - throw denied(); - } - var result = - orders.acquireLocked(current.intent, current.admitted, sources.sources()); - requirePending(creationOperationId); - return result; - })); - - return Objects.requireNonNull( - transactions.execute( - status -> { - Original committed = read(creationOperationId); - same(first, committed); - var readback = - orders - .readOriginal(creationOperationId) - .orElseThrow(AccountTenantCreationAuthorizationPreparation::denied); - if (!Arrays.equals(stored.canonicalBytes(), readback.canonicalBytes()) - || !stored.authorizationDigest().equals(readback.authorizationDigest()) - || !Arrays.equals(committed.intent.requestPayload(), readback.intentPayload()) - || !committed.intent.requestDigest().equals(readback.intentDigest()) - || !Arrays.equals( - committed.admitted.receiptPayload(), readback.admissionPayload()) - || !committed.admitted.receiptDigest().equals(readback.admissionDigest())) { + transactions.execute(status -> { + Original current = read(creationOperationId); + same(first, current); + AccountControlUiActorService.requireAcceptedSignerKey(current.issuance, accepted); + var sources = + capture.captureLocked( + current.intent, current.admitted, environment, reauthentication); + if (!Arrays.equals(sources.originalClaims(), current.issuance.claims) + || !Arrays.equals(sources.originalSignerReceipt(), current.issuance.signerReceipt) + || !current.issuance.operationId.equals(sources.issuanceOperationId()) + || !current.issuance.jti.equals(sources.tokenJti()) + || !current.issuance.tokenHash.equals(sources.tokenHash())) { throw denied(); } + var result = + orders.acquireLocked(current.intent, current.admitted, sources.sources()); requirePending(creationOperationId); - return new Prepared(readback); + return result; })); + + return Objects.requireNonNull( + transactions.execute(status -> { + Original committed = read(creationOperationId); + same(first, committed); + var readback = + orders + .readOriginal(creationOperationId) + .orElseThrow(AccountTenantCreationAuthorizationPreparation::denied); + if (!Arrays.equals(stored.canonicalBytes(), readback.canonicalBytes()) + || !stored.authorizationDigest().equals(readback.authorizationDigest()) + || !Arrays.equals(committed.intent.requestPayload(), readback.intentPayload()) + || !committed.intent.requestDigest().equals(readback.intentDigest()) + || !Arrays.equals(committed.admitted.receiptPayload(), readback.admissionPayload()) + || !committed.admitted.receiptDigest().equals(readback.admissionDigest())) { + throw denied(); + } + requirePending(creationOperationId); + return new Prepared(readback); + })); } private Original read(UUID operationId) { @@ -156,14 +152,13 @@ private void requirePending(UUID operationId) { private void requireOwnerTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) throw denied(); - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw denied(); - } - }); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw denied(); + } + }); } private static void same(Original expected, Original actual) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionOwner.java index ba521eab3b..2221d61218 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionOwner.java @@ -103,26 +103,24 @@ Result complete( Objects.requireNonNull(recent); Initial first = Objects.requireNonNull( - transactions.execute( - status -> { - Original original = readOriginal(operationId, terminal); - Result result = readRetainedOrExpiredResult(original, terminal); - return new Initial(original, result); - })); + transactions.execute(status -> { + Original original = readOriginal(operationId, terminal); + Result result = readRetainedOrExpiredResult(original, terminal); + return new Initial(original, result); + })); if (first.result != null) { if (first.result.state == State.COMPLETED) return first.result; // Expose terminal-only recovery only after independent committed original/settlement reads. return Objects.requireNonNull( - transactions.execute( - status -> { - Original original = readOriginal(operationId, terminal); - requireSame(first.original, original); - Result success = readResult(original, terminal); - if (success != null) return success; - Result historical = readHistoricalResult(original, terminal); - if (historical == null) throw denied(); - return historical; - })); + transactions.execute(status -> { + Original original = readOriginal(operationId, terminal); + requireSame(first.original, original); + Result success = readResult(original, terminal); + if (success != null) return success; + Result historical = readHistoricalResult(original, terminal); + if (historical == null) throw denied(); + return historical; + })); } String kid = @@ -132,144 +130,140 @@ Result complete( AccountControlUiActorService.requireAcceptedSignerKey(first.original.issuance, accepted); Result committed = Objects.requireNonNull( - transactions.execute( - status -> { - Original original = readOriginal(operationId, terminal); - requireSame(first.original, original); - Result replay = readRetainedOrExpiredResult(original, terminal); - if (replay != null) return replay; - // Account-first capture serializes concurrent completion before any Account - // creator writes. - current(original, environment, recent, accepted); - if (dsl.fetchOne( - "SELECT request_id FROM account_tenant_creation_bootstrap_operations WHERE request_id = ? OR tenant_uuid = ? FOR UPDATE", - operationId, - terminal.evidence().receipt().orElseThrow().canonicalTenantId()) - != null) { - throw denied(); - } - var receipt = - terminal - .evidence() - .receipt() - .orElseThrow(AccountTenantCreationCompletionOwner::denied); - var creator = creator(original, receipt); - if (!identities.importVerified(receipt).equals(receipt) - || !identities - .read(receipt.canonicalTenantId()) - .filter(receipt::equals) - .isPresent()) throw denied(); - var tenant = generations.initializeTenantIfAbsent(receipt.canonicalTenantId()); - if (tenant.generation() != 1L || tenant.sourceVersion() != 1L) throw denied(); - var source = - new CurrentSource( - this, original, environment, recent, accepted, creator, transactionId()); - var bootstrap = bootstraps.bootstrapForCompletion(creator, source); - var party = - parties.readIndividualSource( - original.intent.creatorPartyId(), original.intent.initiatingAccountId()); - var associated = parties.associateFresh(operationId, creator, party); - if (!associated.equals( - parties.readInitialAssociation(operationId, creator, party))) throw denied(); - var owner = - owners.establishInitial( - new AccountInitialTenantBillingOwnerRepository.InitialRequest( - original.intent.requestId(), - creator, - original.intent.consentOperationId(), - original.intent.consentStatementVersion(), - original.intent.affirmativeConsent())); - // Fresh capture immediately before consumption; all captured source locks remain - // held to commit. - Current current = current(original, environment, recent, accepted); - var consumed = - reauthentication.validateAndConsumeLocked( - recent, - original.intent.initiatingAccountId(), - AccountRecentReauthenticationPolicy.PURPOSE, - operationId); - if (consumed.disposition() - != AccountRecentReauthenticationService.Disposition.CONSUMED) throw denied(); - UUID auditId = - UUID.nameUUIDFromBytes( - ("account-tenant-creation-completion/v1:" + operationId) - .getBytes(StandardCharsets.UTF_8)); - byte[] payload = - net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority - .canonical( - Map.ofEntries( - Map.entry("schema", "account-tenant-creation-completion/v1"), - Map.entry("operationId", operationId.toString()), - Map.entry("intentDigest", original.intent.requestDigest()), - Map.entry( - "authorizationDigest", original.holder.authorizationDigest()), - Map.entry("terminalDigest", terminal.evidence().evidenceDigest()), - Map.entry("tenantId", receipt.canonicalTenantId().toString()), - Map.entry( - "accountId", - original.intent.initiatingAccountId().toString()), - Map.entry( - "creatorPartyId", - original.intent.creatorPartyId().toString()), - Map.entry("creatorEvidenceDigest", creator.evidenceDigest()), - Map.entry("bootstrapResultDigest", bootstrap.resultDigest()), - Map.entry("initialOwnerResultDigest", owner.resultDigest()), - Map.entry("ownerGeneration", owner.ownerGeneration().toString()), - Map.entry("ownerVersion", owner.ownerVersion()), - Map.entry( - "consentOperationId", - original.intent.consentOperationId().toString()), - Map.entry( - "consentStatementVersion", - original.intent.consentStatementVersion()), - Map.entry( - "reauthenticationEvidenceId", recent.evidenceId().toString()), - Map.entry("auditEventId", auditId.toString()))); - String digest = digest(payload); - var audit = - audits.appendCanonicalTenant( - auditId, - receipt.canonicalTenantId().toString(), - EVENT, - new String(payload, StandardCharsets.UTF_8)); - if (!digest.equals(audit.payloadDigest())) throw denied(); - orders.settleLocked(original.holder, terminal); - Instant validBefore = - AccountTenantCreationOwnerChecks.currentValidBefore( - original.admitted.binding(), current.capture); - dsl.execute( - "INSERT INTO " - + TABLE - + " (creation_operation_id, intent_request_id, tenant_uuid, terminal_payload, terminal_digest," - + " result_payload, result_digest, audit_event_id, valid_before) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz)", - operationId, - original.intent.requestId(), - receipt.canonicalTenantId(), - terminal.evidence().canonicalBytes(), - terminal.evidence().evidenceDigest(), - payload, - digest, - auditId, - OffsetDateTime.ofInstant(validBefore, ZoneOffset.UTC)); - return Objects.requireNonNull(readResult(original, terminal)); - })); - return Objects.requireNonNull( - transactions.execute( - status -> { + transactions.execute(status -> { Original original = readOriginal(operationId, terminal); requireSame(first.original, original); - Result readback = readResult(original, terminal); - if (committed.state == State.CREATED_WITHOUT_ACCOUNT_COMPLETION) { - // A completed original keeps precedence even if it became visible after settling. - if (readback != null) return readback; - readback = readHistoricalResult(original, terminal); + Result replay = readRetainedOrExpiredResult(original, terminal); + if (replay != null) return replay; + // Account-first capture serializes concurrent completion before any Account + // creator writes. + current(original, environment, recent, accepted); + if (dsl.fetchOne( + "SELECT request_id FROM account_tenant_creation_bootstrap_operations WHERE request_id = ? OR tenant_uuid = ? FOR UPDATE", + operationId, + terminal.evidence().receipt().orElseThrow().canonicalTenantId()) + != null) { + throw denied(); } - if (readback == null - || committed.state != readback.state - || !Arrays.equals(committed.payload, readback.payload) - || !committed.digest.equals(readback.digest)) throw denied(); - return readback; + var receipt = + terminal + .evidence() + .receipt() + .orElseThrow(AccountTenantCreationCompletionOwner::denied); + var creator = creator(original, receipt); + if (!identities.importVerified(receipt).equals(receipt) + || !identities + .read(receipt.canonicalTenantId()) + .filter(receipt::equals) + .isPresent()) throw denied(); + var tenant = generations.initializeTenantIfAbsent(receipt.canonicalTenantId()); + if (tenant.generation() != 1L || tenant.sourceVersion() != 1L) throw denied(); + var source = + new CurrentSource( + this, original, environment, recent, accepted, creator, transactionId()); + var bootstrap = bootstraps.bootstrapForCompletion(creator, source); + var party = + parties.readIndividualSource( + original.intent.creatorPartyId(), original.intent.initiatingAccountId()); + var associated = parties.associateFresh(operationId, creator, party); + if (!associated.equals(parties.readInitialAssociation(operationId, creator, party))) + throw denied(); + var owner = + owners.establishInitial( + new AccountInitialTenantBillingOwnerRepository.InitialRequest( + original.intent.requestId(), + creator, + original.intent.consentOperationId(), + original.intent.consentStatementVersion(), + original.intent.affirmativeConsent())); + // Fresh capture immediately before consumption; all captured source locks remain + // held to commit. + Current current = current(original, environment, recent, accepted); + var consumed = + reauthentication.validateAndConsumeLocked( + recent, + original.intent.initiatingAccountId(), + AccountRecentReauthenticationPolicy.PURPOSE, + operationId); + if (consumed.disposition() + != AccountRecentReauthenticationService.Disposition.CONSUMED) throw denied(); + UUID auditId = + UUID.nameUUIDFromBytes( + ("account-tenant-creation-completion/v1:" + operationId) + .getBytes(StandardCharsets.UTF_8)); + byte[] payload = + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority + .canonical( + Map.ofEntries( + Map.entry("schema", "account-tenant-creation-completion/v1"), + Map.entry("operationId", operationId.toString()), + Map.entry("intentDigest", original.intent.requestDigest()), + Map.entry( + "authorizationDigest", original.holder.authorizationDigest()), + Map.entry("terminalDigest", terminal.evidence().evidenceDigest()), + Map.entry("tenantId", receipt.canonicalTenantId().toString()), + Map.entry( + "accountId", original.intent.initiatingAccountId().toString()), + Map.entry( + "creatorPartyId", original.intent.creatorPartyId().toString()), + Map.entry("creatorEvidenceDigest", creator.evidenceDigest()), + Map.entry("bootstrapResultDigest", bootstrap.resultDigest()), + Map.entry("initialOwnerResultDigest", owner.resultDigest()), + Map.entry("ownerGeneration", owner.ownerGeneration().toString()), + Map.entry("ownerVersion", owner.ownerVersion()), + Map.entry( + "consentOperationId", + original.intent.consentOperationId().toString()), + Map.entry( + "consentStatementVersion", + original.intent.consentStatementVersion()), + Map.entry( + "reauthenticationEvidenceId", recent.evidenceId().toString()), + Map.entry("auditEventId", auditId.toString()))); + String digest = digest(payload); + var audit = + audits.appendCanonicalTenant( + auditId, + receipt.canonicalTenantId().toString(), + EVENT, + new String(payload, StandardCharsets.UTF_8)); + if (!digest.equals(audit.payloadDigest())) throw denied(); + orders.settleLocked(original.holder, terminal); + Instant validBefore = + AccountTenantCreationOwnerChecks.currentValidBefore( + original.admitted.binding(), current.capture); + dsl.execute( + "INSERT INTO " + + TABLE + + " (creation_operation_id, intent_request_id, tenant_uuid, terminal_payload, terminal_digest," + + " result_payload, result_digest, audit_event_id, valid_before) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz)", + operationId, + original.intent.requestId(), + receipt.canonicalTenantId(), + terminal.evidence().canonicalBytes(), + terminal.evidence().evidenceDigest(), + payload, + digest, + auditId, + OffsetDateTime.ofInstant(validBefore, ZoneOffset.UTC)); + return Objects.requireNonNull(readResult(original, terminal)); })); + return Objects.requireNonNull( + transactions.execute(status -> { + Original original = readOriginal(operationId, terminal); + requireSame(first.original, original); + Result readback = readResult(original, terminal); + if (committed.state == State.CREATED_WITHOUT_ACCOUNT_COMPLETION) { + // A completed original keeps precedence even if it became visible after settling. + if (readback != null) return readback; + readback = readHistoricalResult(original, terminal); + } + if (readback == null + || committed.state != readback.state + || !Arrays.equals(committed.payload, readback.payload) + || !committed.digest.equals(readback.digest)) throw denied(); + return readback; + })); } private Result readRetainedOrExpiredResult(Original original, VerifiedTerminal terminal) { @@ -438,13 +432,12 @@ private String transactionId() { private void requireOwnerTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) throw denied(); - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) - throw denied(); - }); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) + throw denied(); + }); } private static void requireSame(Original expected, Original actual) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCoordinator.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCoordinator.java index 1b2819a2dd..bb3a32849f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCoordinator.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCoordinator.java @@ -157,25 +157,23 @@ private VerifiedTerminal readOrCloseOriginal(Original original) { } private void settleNegative(Original original, VerifiedTerminal terminal) { - transactions.executeWithoutResult( - status -> { - var actual = - orders - .readOriginal(original.intent().creationOperationId()) - .orElseThrow(AccountTenantCreationCoordinator::inconsistent); - if (!Arrays.equals(actual.canonicalBytes(), original.holder().canonicalBytes()) - || !actual.outcomeBinding().equals(terminal.binding())) throw inconsistent(); - orders.settleLocked(actual, terminal); - }); - transactions.executeWithoutResult( - status -> { - var actual = - orders - .readSettlement(original.intent().creationOperationId()) - .orElseThrow(AccountTenantCreationCoordinator::inconsistent); - if (!Arrays.equals(actual.canonicalBytes(), terminal.evidence().canonicalBytes())) - throw inconsistent(); - }); + transactions.executeWithoutResult(status -> { + var actual = + orders + .readOriginal(original.intent().creationOperationId()) + .orElseThrow(AccountTenantCreationCoordinator::inconsistent); + if (!Arrays.equals(actual.canonicalBytes(), original.holder().canonicalBytes()) + || !actual.outcomeBinding().equals(terminal.binding())) throw inconsistent(); + orders.settleLocked(actual, terminal); + }); + transactions.executeWithoutResult(status -> { + var actual = + orders + .readSettlement(original.intent().creationOperationId()) + .orElseThrow(AccountTenantCreationCoordinator::inconsistent); + if (!Arrays.equals(actual.canonicalBytes(), terminal.evidence().canonicalBytes())) + throw inconsistent(); + }); } private static void requireExactRequest(OriginalIntent original, Request request) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCurrentAuthorizationOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCurrentAuthorizationOwner.java index 15334a47a7..4e80204d32 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCurrentAuthorizationOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCurrentAuthorizationOwner.java @@ -72,42 +72,40 @@ public Authorization resolve(Binding binding) { var environment = terms.captureCurrentEnvironmentBoundary(); Authorization observed = Objects.requireNonNull( - transactions.execute( - status -> { - Original original = read(binding); - same(first, original); - // Actual Account-first capture precedes issuer/issuance/source locking. No - // network in SQL. - var checked = - AccountTenantCreationOwnerChecks.captureCurrent( - capture, - orders, - original.intent, - original.admitted, - original.issuance, - original.holder, - environment, - original.recent, - accepted, - AccountTenantCreationCurrentAuthorizationOwner::denied); - Instant deadline = - AccountTenantCreationOwnerChecks.currentValidBefore( - original.admitted.binding(), checked.captured()); - Instant dispatchDeadline = Instant.ofEpochMilli(original.dispatchDeadline); - if (dispatchDeadline.isBefore(deadline)) deadline = dispatchDeadline; - long validBefore = deadline.toEpochMilli(); - requireTime(original, validBefore); - return new Authorization(binding, validBefore); - })); + transactions.execute(status -> { + Original original = read(binding); + same(first, original); + // Actual Account-first capture precedes issuer/issuance/source locking. No + // network in SQL. + var checked = + AccountTenantCreationOwnerChecks.captureCurrent( + capture, + orders, + original.intent, + original.admitted, + original.issuance, + original.holder, + environment, + original.recent, + accepted, + AccountTenantCreationCurrentAuthorizationOwner::denied); + Instant deadline = + AccountTenantCreationOwnerChecks.currentValidBefore( + original.admitted.binding(), checked.captured()); + Instant dispatchDeadline = Instant.ofEpochMilli(original.dispatchDeadline); + if (dispatchDeadline.isBefore(deadline)) deadline = dispatchDeadline; + long validBefore = deadline.toEpochMilli(); + requireTime(original, validBefore); + return new Authorization(binding, validBefore); + })); // Independently read the committed original and still-pending holder before transport reply. return Objects.requireNonNull( - transactions.execute( - status -> { - Original committed = read(binding); - same(first, committed); - requireTime(committed, observed.validBeforeEpochMillis()); - return observed; - })); + transactions.execute(status -> { + Original committed = read(binding); + same(first, committed); + requireTime(committed, observed.validBeforeEpochMillis()); + return observed; + })); } private Original read(Binding binding) { @@ -196,13 +194,12 @@ private static void same(Original first, Original second) { private void requireOwnerTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) throw denied(); - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) - throw denied(); - }); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) + throw denied(); + }); } private static IllegalStateException denied() { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationDispatchRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationDispatchRepository.java index cd313e5faa..7b81651c2a 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationDispatchRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationDispatchRepository.java @@ -65,34 +65,32 @@ boolean isDispatchWindowClosed(Original original) { outsideSql(); Objects.requireNonNull(original); return Boolean.TRUE.equals( - transactions.execute( - status -> { - Original retained = read(original.intent.creationOperationId()).original; - if (!Arrays.equals(original.intent.requestPayload(), retained.intent.requestPayload()) - || !original.intent.requestDigest().equals(retained.intent.requestDigest()) - || !Arrays.equals( - original.admitted.receiptPayload(), retained.admitted.receiptPayload()) - || !original.admitted.receiptDigest().equals(retained.admitted.receiptDigest()) - || !Arrays.equals( - original.holder.canonicalBytes(), retained.holder.canonicalBytes())) - throw denied(); - // Without a claim, a concurrent first claimant may still use the original's whole - // immutable operation window. Absence must never become an immediate close permit. - long validBefore = retained.admitted.binding().operationDeadlineEpochMillis(); - Record claim = row(retained.intent.creationOperationId()); - if (claim != null) { - requireRow(retained, claim); - validBefore = claim.get("valid_before_epoch_millis", Long.class); - } - if (validBefore <= 0 - || validBefore > AccountTenantCreationAdmissionBinding.MAX_REDIS_SAFE_INTEGER) - throw denied(); - Record clock = dsl.fetchOne("SELECT clock_timestamp() AS observed_at"); - OffsetDateTime observed = - clock == null ? null : clock.get("observed_at", OffsetDateTime.class); - if (observed == null) throw denied(); - return !observed.toInstant().isBefore(Instant.ofEpochMilli(validBefore)); - })); + transactions.execute(status -> { + Original retained = read(original.intent.creationOperationId()).original; + if (!Arrays.equals(original.intent.requestPayload(), retained.intent.requestPayload()) + || !original.intent.requestDigest().equals(retained.intent.requestDigest()) + || !Arrays.equals( + original.admitted.receiptPayload(), retained.admitted.receiptPayload()) + || !original.admitted.receiptDigest().equals(retained.admitted.receiptDigest()) + || !Arrays.equals(original.holder.canonicalBytes(), retained.holder.canonicalBytes())) + throw denied(); + // Without a claim, a concurrent first claimant may still use the original's whole + // immutable operation window. Absence must never become an immediate close permit. + long validBefore = retained.admitted.binding().operationDeadlineEpochMillis(); + Record claim = row(retained.intent.creationOperationId()); + if (claim != null) { + requireRow(retained, claim); + validBefore = claim.get("valid_before_epoch_millis", Long.class); + } + if (validBefore <= 0 + || validBefore > AccountTenantCreationAdmissionBinding.MAX_REDIS_SAFE_INTEGER) + throw denied(); + Record clock = dsl.fetchOne("SELECT clock_timestamp() AS observed_at"); + OffsetDateTime observed = + clock == null ? null : clock.get("observed_at", OffsetDateTime.class); + if (observed == null) throw denied(); + return !observed.toInstant().isBefore(Instant.ofEpochMilli(validBefore)); + })); } Optional claim( @@ -114,65 +112,63 @@ Optional claim( AccountControlUiActorService.requireAcceptedSignerKey(first.issuance, accepted); UUID callId = UUID.randomUUID(); Long deadline = - transactions.execute( - status -> { - Stored current = read(operation); - same(first, current); - var checked = - AccountTenantCreationOwnerChecks.captureCurrent( - capture, - orders, - current.original.intent, - current.original.admitted, - current.issuance, - current.original.holder, - environment, - recent, - accepted, - AccountTenantCreationDispatchRepository::denied); - if (existing(current.original)) return null; - long validBefore = - AccountTenantCreationOwnerChecks.currentValidBefore( - current.original.admitted.binding(), checked.captured()) - .toEpochMilli(); - int inserted = - dsl.execute( - "INSERT INTO " - + TABLE - + " (creation_operation_id, dispatch_call_id, authorization_binding_payload, authorization_digest, valid_before_epoch_millis)" - + " VALUES (?, ?, ?, ?, ?) ON CONFLICT DO NOTHING", - operation, - callId, - checked.lockedHolder().canonicalBytes(), - checked.lockedHolder().authorizationDigest(), - validBefore); - if (inserted == 0) { - if (!existing(current.original)) throw denied(); - return null; - } - if (inserted != 1) throw denied(); - return validBefore; - }); + transactions.execute(status -> { + Stored current = read(operation); + same(first, current); + var checked = + AccountTenantCreationOwnerChecks.captureCurrent( + capture, + orders, + current.original.intent, + current.original.admitted, + current.issuance, + current.original.holder, + environment, + recent, + accepted, + AccountTenantCreationDispatchRepository::denied); + if (existing(current.original)) return null; + long validBefore = + AccountTenantCreationOwnerChecks.currentValidBefore( + current.original.admitted.binding(), checked.captured()) + .toEpochMilli(); + int inserted = + dsl.execute( + "INSERT INTO " + + TABLE + + " (creation_operation_id, dispatch_call_id, authorization_binding_payload, authorization_digest, valid_before_epoch_millis)" + + " VALUES (?, ?, ?, ?, ?) ON CONFLICT DO NOTHING", + operation, + callId, + checked.lockedHolder().canonicalBytes(), + checked.lockedHolder().authorizationDigest(), + validBefore); + if (inserted == 0) { + if (!existing(current.original)) throw denied(); + return null; + } + if (inserted != 1) throw denied(); + return validBefore; + }); if (deadline == null) return Optional.empty(); // The committed claim is independently read before returning the sole initial-send value. return Optional.of( Objects.requireNonNull( - transactions.execute( - status -> { - Stored committed = read(operation); - same(first, committed); - Record row = row(operation); - requireRow(committed.original, row); - if (!callId.equals(row.get("dispatch_call_id", UUID.class)) - || !deadline.equals(row.get("valid_before_epoch_millis", Long.class)) - || orders.readSettlement(operation).isPresent()) throw denied(); - Record clock = dsl.fetchOne("SELECT clock_timestamp() AS observed_at"); - if (clock == null - || !Objects.requireNonNull(clock.get("observed_at", OffsetDateTime.class)) - .toInstant() - .isBefore(Instant.ofEpochMilli(deadline))) throw denied(); - return new InitialDispatch(committed.original, callId, deadline); - }))); + transactions.execute(status -> { + Stored committed = read(operation); + same(first, committed); + Record row = row(operation); + requireRow(committed.original, row); + if (!callId.equals(row.get("dispatch_call_id", UUID.class)) + || !deadline.equals(row.get("valid_before_epoch_millis", Long.class)) + || orders.readSettlement(operation).isPresent()) throw denied(); + Record clock = dsl.fetchOne("SELECT clock_timestamp() AS observed_at"); + if (clock == null + || !Objects.requireNonNull(clock.get("observed_at", OffsetDateTime.class)) + .toInstant() + .isBefore(Instant.ofEpochMilli(deadline))) throw denied(); + return new InitialDispatch(committed.original, callId, deadline); + }))); } private Stored read(UUID operation) { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderRepository.java index 074a80bdfb..a9b97a1a48 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderRepository.java @@ -322,13 +322,12 @@ List readPending(PendingCursor after, int limit) { } sql += " ORDER BY order_row.created_at, order_row.creation_operation_id LIMIT ?"; return dsl.fetch(sql, parameters).stream() - .map( - row -> { - AccountTenantCreationSourceOrderBinding binding = mapOriginal(row); - OffsetDateTime createdAt = required(row, "created_at", OffsetDateTime.class); - return new PendingSourceOrder( - binding, createdAt, new PendingCursor(createdAt, binding.creationOperationId())); - }) + .map(row -> { + AccountTenantCreationSourceOrderBinding binding = mapOriginal(row); + OffsetDateTime createdAt = required(row, "created_at", OffsetDateTime.class); + return new PendingSourceOrder( + binding, createdAt, new PendingCursor(createdAt, binding.creationOperationId())); + }) .toList(); } @@ -410,15 +409,14 @@ private void requireExactSourceRows(AccountTenantCreationSourceOrderBinding bind } List stored = rows.stream() - .map( - row -> { - byte[] evidence = required(row, "source_evidence", byte[].class); - SourceEvidence source = SourceEvidence.fromStored(evidence); - if (!source.key().equals(row.get("source_key", String.class))) { - throw conflict("Stored source key differs from canonical owner evidence"); - } - return source; - }) + .map(row -> { + byte[] evidence = required(row, "source_evidence", byte[].class); + SourceEvidence source = SourceEvidence.fromStored(evidence); + if (!source.key().equals(row.get("source_key", String.class))) { + throw conflict("Stored source key differs from canonical owner evidence"); + } + return source; + }) .toList(); List expected = binding.sources().stream().sorted(Comparator.comparing(SourceEvidence::key)).toList(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java index ed7fc5ed23..89d0004ea5 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java @@ -240,16 +240,15 @@ void expiredAndExactlyExpiringEmailVerificationTokensCannotMutateAccount() { var before = emailVerificationState(fixture); if (equality) { new TransactionTemplate(transactionManager) - .executeWithoutResult( - status -> { - accountRepository.findByIdForUpdate(fixture.accountId()).orElseThrow(); - var token = - emailVerificationTokenRepository.findByToken(fixture.token()).orElseThrow(); - assertThat( - emailVerificationTokenRepository.consumeIfUnexpired( - token, token.getExpiresAt())) - .isFalse(); - }); + .executeWithoutResult(status -> { + accountRepository.findByIdForUpdate(fixture.accountId()).orElseThrow(); + var token = + emailVerificationTokenRepository.findByToken(fixture.token()).orElseThrow(); + assertThat( + emailVerificationTokenRepository.consumeIfUnexpired( + token, token.getExpiresAt())) + .isFalse(); + }); } else { assertThatThrownBy(() -> verifyEmail(fixture.token())) .isInstanceOf(IllegalArgumentException.class) @@ -310,13 +309,11 @@ void emailVerificationRollbackRestoresTokenAccountAndSourceEvidence() { var fixture = emailVerificationFixture(); var before = emailVerificationState(fixture); var transaction = new TransactionTemplate(transactionManager); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - status -> { - verifyEmail(fixture.token()); - throw new IllegalStateException("failure after verification source update"); - })) + assertThatThrownBy(() -> + transaction.executeWithoutResult(status -> { + verifyEmail(fixture.token()); + throw new IllegalStateException("failure after verification source update"); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("failure after verification source update"); assertThat(emailVerificationState(fixture)).isEqualTo(before); @@ -356,23 +353,20 @@ void emailVerificationUsesFreshOwnerAfterConcurrentAccountUpdate() throws Except var original = invocation.callRealMethod(); if (changed.compareAndSet(false, true)) { executor - .submit( - () -> - new TransactionTemplate(transactionManager) - .executeWithoutResult( - status -> { - var current = - accountRepository - .findByIdForUpdate(fixture.accountId()) - .orElseThrow(); - current.setUsername("current-" + fixture.accountId()); - current.setEmail( - "current-" + fixture.accountId() + "@example.com"); - current.setPasswordHash("current-password-hash"); - current.setRole("player"); - current.setLoginAuthModes("EMAIL_OTP"); - accountRepository.save(current); - })) + .submit(() -> + new TransactionTemplate(transactionManager) + .executeWithoutResult(status -> { + var current = + accountRepository + .findByIdForUpdate(fixture.accountId()) + .orElseThrow(); + current.setUsername("current-" + fixture.accountId()); + current.setEmail("current-" + fixture.accountId() + "@example.com"); + current.setPasswordHash("current-password-hash"); + current.setRole("player"); + current.setLoginAuthModes("EMAIL_OTP"); + accountRepository.save(current); + })) .get(30, TimeUnit.SECONDS); } return original; @@ -469,23 +463,21 @@ void publicJoinBrowserAndDirectScopesUseActualUuidIntentMembershipEventAndAuditO assertThat(claims.get("gameInstanceId")) .isEqualTo(f.target.canonicalGameInstanceId().toString()); var retained = - f.in( - () -> - f.scopes - .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(token)) - .orElseThrow()); + f.in(() -> + f.scopes + .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(token)) + .orElseThrow()); assertThat(retained.privateAccountId()).isEqualTo(f.account.getId()); assertThat(retained.scopeDigestVersion()).isEqualTo(2); assertThat(retained.tenantUuid()).isEqualTo(f.tenantId); assertThat(f.in(() -> f.scopes.find(token))).isEmpty(); } for (String token : List.of(browser, direct)) { - assertThatThrownBy( - () -> - f.service.issueConnectToken( - f.bootstrap, - new net.firedevops.firemud.accountservice.dto.ConnectTokenRequest( - token, "held-issuer"))) + assertThatThrownBy(() -> + f.service.issueConnectToken( + f.bootstrap, + new net.firedevops.firemud.accountservice.dto.ConnectTokenRequest( + token, "held-issuer"))) .isInstanceOf(AuthenticationException.class) .extracting(value -> ((AuthenticationException) value).getCode()) .isEqualTo("AUTH_UNAVAILABLE"); @@ -747,11 +739,10 @@ void publicJoinExpiryDuringProcessingPreservesPendingIntentAndRollsBack(boolean if (duringProvider) { f.paid .transport() - .duringRead( - () -> { - intent.set(f.operation(request).intentDigest()); - f.clock.offset = Duration.ofMinutes(3); - }); + .duringRead(() -> { + intent.set(f.operation(request).intentDigest()); + f.clock.offset = Duration.ofMinutes(3); + }); } else { org.mockito.Mockito.doAnswer( invocation -> { @@ -975,10 +966,9 @@ void publicJoinAnotherAuthenticatedAccountCannotConsumeTheOriginalScopeOrCreateI org.mockito.Mockito.when(f.sessions.isAccountSessionActive(owner.getId(), bootstrap)) .thenReturn(true); String request = UUID.randomUUID().toString(); - assertThatThrownBy( - () -> - f.service.joinPublicProduction( - bootstrap, new JoinPublicProductionRequest(token, request))) + assertThatThrownBy(() -> + f.service.joinPublicProduction( + bootstrap, new JoinPublicProductionRequest(token, request))) .isInstanceOf(AuthenticationException.class) .extracting(value -> ((AuthenticationException) value).getCode()) .isEqualTo("CONNECT_SCOPE_INVALID"); @@ -1001,22 +991,21 @@ void bootstrapCharactersUsesActualAccountAuthorityAndPreservesControlledEntityNa org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.eq(f.account.getAccountUuid()), org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isSynchronizationActive()) - .isFalse(); - return List.of( - new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient - .Actor(zed, "Zed", 37), - new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient - .Actor(ada, "Ada", 12)); - }); + .thenAnswer(invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + .isFalse(); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(zed, "Zed", 37), + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(ada, "Ada", 12)); + }); var before = f.state(join); int providerReads = paid ? f.paid.transport().reads() : 0; var actors = f.characters(token); @@ -1026,11 +1015,10 @@ void bootstrapCharactersUsesActualAccountAuthorityAndPreservesControlledEntityNa .containsExactly(ada.toString(), zed.toString()); assertThat(actors).extracting(value -> value.level()).containsExactly(12, 37); assertThat(actors) - .allSatisfy( - actor -> { - assertThat(actor.stateScope()).isEqualTo("SHARED"); - assertThat(actor.characterCreationPolicy()).isEqualTo("PRESEEDED_ONLY"); - }); + .allSatisfy(actor -> { + assertThat(actor.stateScope()).isEqualTo("SHARED"); + assertThat(actor.characterCreationPolicy()).isEqualTo("PRESEEDED_ONLY"); + }); var selected = org.mockito.ArgumentCaptor.forClass( CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); @@ -1157,10 +1145,9 @@ void bootstrapCharactersAnotherAuthenticatedAccountCannotConsumeTheSelectedScope UUID.randomUUID().toString())); org.mockito.Mockito.when(f.sessions.isAccountSessionActive(owner.getId(), bootstrap)) .thenReturn(true); - assertThatThrownBy( - () -> - f.service.listBootstrapCharacters( - bootstrap, f.target.worldSlug(), f.target.realmSlug(), token)) + assertThatThrownBy(() -> + f.service.listBootstrapCharacters( + bootstrap, f.target.worldSlug(), f.target.realmSlug(), token)) .isInstanceOf(AuthenticationException.class) .extracting(value -> ((AuthenticationException) value).getCode()) .isEqualTo("CONNECT_SCOPE_INVALID"); @@ -1218,17 +1205,16 @@ void bootstrapCharactersRechecksActualMembershipSnapshotAfterEntityDiscovery() { org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.eq(f.account.getAccountUuid()), org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - f.seedControlledInactiveSnapshot(); - return List.of( - new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient - .Actor(UUID.randomUUID(), "Withheld", 19)); - }); + .thenAnswer(invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + f.seedControlledInactiveSnapshot(); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Withheld", 19)); + }); assertThatThrownBy(() -> f.characters(token)) .isInstanceOf(AuthenticationException.class) .extracting(value -> ((AuthenticationException) value).getCode()) @@ -1271,21 +1257,20 @@ void bootstrapCharactersFinalEntitlementOutageDiscardsEntityResultAndPreservesAc org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.eq(f.account.getAccountUuid()), org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - org.mockito.Mockito.doThrow( - new org.springframework.dao.DataAccessResourceFailureException( - "controlled late demo currentness outage")) - .when(f.demos) - .revalidate(org.mockito.ArgumentMatchers.any()); - return List.of( - new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient - .Actor(UUID.randomUUID(), "Withheld", 31)); - }); + .thenAnswer(invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + org.mockito.Mockito.doThrow( + new org.springframework.dao.DataAccessResourceFailureException( + "controlled late demo currentness outage")) + .when(f.demos) + .revalidate(org.mockito.ArgumentMatchers.any()); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Withheld", 31)); + }); assertThatThrownBy(() -> f.characters(token)) .isInstanceOf(AuthenticationException.class) .extracting(value -> ((AuthenticationException) value).getCode()) @@ -1480,12 +1465,11 @@ private CanonicalPublicJoinFixture(boolean usePaid, Account existingAccount) { key, "NEW_GAME_ROW")); clock = new FixtureClock(Clock.systemUTC()); - in( - () -> { - tenants.importVerified(source); - generations.initializeTenantIfAbsent(tenantId); - return null; - }); + in(() -> { + tenants.importVerified(source); + generations.initializeTenantIfAbsent(tenantId); + return null; + }); policy(true, true); } String suffix = UUID.randomUUID().toString(); @@ -1498,14 +1482,13 @@ private CanonicalPublicJoinFixture(boolean usePaid, Account existingAccount) { } else { account = accounts.findByAccountUuid(existingAccount.getAccountUuid()).orElseThrow(); } - in( - () -> { - evidence.initializeIssuerIfAbsent("firemud-account-service"); - generations.initialize( - AccountAuthorityGenerationRepository.AuthorityScope.membership( - account.getAccountUuid(), tenantId)); - return null; - }); + in(() -> { + evidence.initializeIssuerIfAbsent("firemud-account-service"); + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.getAccountUuid(), tenantId)); + return null; + }); if (paid != null) { // The SQL lifecycle owner evaluates at microsecond precision; its SDK input must use the // same controlled instant rather than appear nanoseconds later than the evaluation. @@ -1519,89 +1502,82 @@ private CanonicalPublicJoinFixture(boolean usePaid, Account existingAccount) { org.mockito.Mockito.when( targets.listVisiblePublicProductionAdmissionTargets( org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - var request = - new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( - invocation.getArgument(0, UUID.class), namespace); - return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( - request, - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( - request, List.of(target))); - }); + .thenAnswer(invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var request = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( + invocation.getArgument(0, UUID.class), namespace); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, List.of(target))); + }); org.mockito.Mockito.when( targets.resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - var selector = - invocation.getArgument( - 0, - CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector - .class); - return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( - selector, - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( - selector, target)); - }); + .thenAnswer(invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var selector = + invocation.getArgument( + 0, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( + selector, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( + selector, target)); + }); // The transport boundary is controlled. Actual Account owners must still request this strict // published-source/World ACTIVE result; the resolver response alone cannot authorize JOIN. org.mockito.Mockito.when( targets.readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - var strict = - invocation.getArgument( - 0, - net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence - .Request.class); - var published = - org.mockito.Mockito.mock( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence - .class); - org.mockito.Mockito.when(published.selector()).thenReturn(strict); - org.mockito.Mockito.when(published.currentTarget()).thenReturn(target); - var sourceEvidence = - org.mockito.Mockito.mock( - net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence - .class); - org.mockito.Mockito.when(sourceEvidence.request()).thenReturn(strict); - org.mockito.Mockito.when(sourceEvidence.admissionPointerSnapshotDigest()) - .thenReturn(target.admissionPointerSnapshotDigest()); - // Controlled remote policy capture; the Account integration test does not qualify - // its decoder. - var policies = - org.mockito.Mockito.mock( - net.firedevops.firemud.common.publication - .PublishedRealmEntryPolicySetEvidence.class); - org.mockito.Mockito.when(policies.canonicalBytes()) - .thenReturn( - ("controlled-policy-set-" + tenantId).getBytes(StandardCharsets.UTF_8)); - org.mockito.Mockito.when(sourceEvidence.publishedPolicySetEvidence()) - .thenReturn(policies); - var world = - org.mockito.Mockito.mock( - net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence - .class); - org.mockito.Mockito.when(world.lifecycleStatus()).thenReturn("ACTIVE"); - org.mockito.Mockito.when(world.lifecycleEpoch()) - .thenReturn(target.activeWorldEpoch()); - org.mockito.Mockito.when(world.rowVersion()).thenReturn(1L); - org.mockito.Mockito.when(published.sourceEvidence()).thenReturn(sourceEvidence); - org.mockito.Mockito.when(published.worldLifecycleEvidence()).thenReturn(world); - return published; - }); + .thenAnswer(invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var strict = + invocation.getArgument( + 0, + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence + .Request.class); + var published = + org.mockito.Mockito.mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + org.mockito.Mockito.when(published.selector()).thenReturn(strict); + org.mockito.Mockito.when(published.currentTarget()).thenReturn(target); + var sourceEvidence = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence + .class); + org.mockito.Mockito.when(sourceEvidence.request()).thenReturn(strict); + org.mockito.Mockito.when(sourceEvidence.admissionPointerSnapshotDigest()) + .thenReturn(target.admissionPointerSnapshotDigest()); + // Controlled remote policy capture; the Account integration test does not qualify + // its decoder. + var policies = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence + .class); + org.mockito.Mockito.when(policies.canonicalBytes()) + .thenReturn(("controlled-policy-set-" + tenantId).getBytes(StandardCharsets.UTF_8)); + org.mockito.Mockito.when(sourceEvidence.publishedPolicySetEvidence()) + .thenReturn(policies); + var world = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence + .class); + org.mockito.Mockito.when(world.lifecycleStatus()).thenReturn("ACTIVE"); + org.mockito.Mockito.when(world.lifecycleEpoch()).thenReturn(target.activeWorldEpoch()); + org.mockito.Mockito.when(world.rowVersion()).thenReturn(1L); + org.mockito.Mockito.when(published.sourceEvidence()).thenReturn(sourceEvidence); + org.mockito.Mockito.when(published.worldLifecycleEvidence()).thenReturn(world); + return published; + }); var properties = new AccountTokenProperties(); properties.setConnectScopeExpirationMs(120000L); bootstrap = @@ -1690,18 +1666,17 @@ private CanonicalPublicJoinFixture(boolean usePaid, Account existingAccount) { org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.eq(account.getAccountUuid()), org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isSynchronizationActive()) - .isFalse(); - return List.of(); - }); + .thenAnswer(invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + .isFalse(); + return List.of(); + }); service.setCanonicalScopeConsumers( new AccountCanonicalConnectScopeReader(jwt, scopes, transactionManager, clock), targets, @@ -1715,35 +1690,33 @@ private CanonicalPublicJoinFixture(boolean usePaid, Account existingAccount) { } private void policy(boolean join, boolean gameplay) { - in( - () -> { - DemoTenantEntitlementSnapshot previous; - try { - previous = demos.readCurrent(tenantId); - } catch ( - net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException - missing) { - if (missing.code() - != net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException - .Code.ENTITLEMENT_UNAVAILABLE) throw missing; - previous = null; - } - return demos.provision( - new DemoTenantEntitlementRequest( - UUID.randomUUID(), - tenantId, - source.creationRequestId(), - source.requestDigest(), - previous == null ? null : previous.entitlementVersion(), - previous == null ? null : previous.tenantAuthorityGeneration(), - previous == null ? null : previous.tenantAuthoritySourceVersion(), - gameplay, - join, - gameplay, - gameplay, - new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)), - source); - }); + in(() -> { + DemoTenantEntitlementSnapshot previous; + try { + previous = demos.readCurrent(tenantId); + } catch ( + net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException missing) { + if (missing.code() + != net.firedevops.firemud.accountservice.service.DemoTenantEntitlementException.Code + .ENTITLEMENT_UNAVAILABLE) throw missing; + previous = null; + } + return demos.provision( + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + tenantId, + source.creationRequestId(), + source.requestDigest(), + previous == null ? null : previous.entitlementVersion(), + previous == null ? null : previous.tenantAuthorityGeneration(), + previous == null ? null : previous.tenantAuthoritySourceVersion(), + gameplay, + join, + gameplay, + gameplay, + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L)), + source); + }); } private Target target() { @@ -1835,30 +1808,28 @@ private DirectTextCallerContext directCaller(String request) { private String directScope() throws Exception { String request = UUID.randomUUID().toString(); return peer() - .call( - () -> - service - .issueDirectTextConnectScope( - directCaller(request), - new DirectTextJoinTarget( - tenantId, - target.realmId(), - target.worldSlug(), - target.realmSlug(), - target.playableStateNamespaceId(), - target.playableStateScope(), - target.canonicalGameInstanceId(), - target.catalogRevision(), - target.pointerVersion())) - .connectScopeId()); + .call(() -> + service + .issueDirectTextConnectScope( + directCaller(request), + new DirectTextJoinTarget( + tenantId, + target.realmId(), + target.worldSlug(), + target.realmSlug(), + target.playableStateNamespaceId(), + target.playableStateScope(), + target.canonicalGameInstanceId(), + target.catalogRevision(), + target.pointerVersion())) + .connectScopeId()); } private JoinPublicProductionResult directJoin(String token, String request) throws Exception { return peer() - .call( - () -> - service.joinPublicProductionFromGameSession( - directCaller(request), new JoinPublicProductionRequest(token, request))); + .call(() -> + service.joinPublicProductionFromGameSession( + directCaller(request), new JoinPublicProductionRequest(token, request))); } private io.grpc.Context peer() { @@ -1894,155 +1865,147 @@ private void seedControlledSnapshot(String lifecycle, boolean gameplay, List { - operations.lockAccount(account.getId()); - var member = - members - .findFreshMembershipForUpdate(account.getAccountUuid(), tenantId) - .orElseThrow(); - var generation = - generations.read( - AccountAuthorityGenerationRepository.AuthorityScope.membership( - account.getAccountUuid(), tenantId)); - var beforeSource = - evidence.readCurrentIssuerAccountSources( - "firemud-account-service", account.getAccountUuid()); - - // Closed receipt/source-change mechanics supply the one shared Account fence advance. - // This remains controlled historical input, not a registered security or leave - // producer. - var currentSource = advanceControlledClosedAccountSource(beforeSource); - if (currentSource.account().generation() != beforeSource.account().generation() + 1L - || currentSource.account().sourceVersion() - != beforeSource.account().sourceVersion() + 1L - || currentSource.account().checkpoint().sequence() - != beforeSource.account().checkpoint().sequence() + 1L - || currentSource.issuanceFence().value() != generation.issuanceFence().value() + 1L - || currentSource.issuanceFence().sourceVersion() - != generation.issuanceFence().sourceVersion() + 1L) { - throw new IllegalStateException( - "Controlled Account source/fence did not advance once"); - } - int advanced = - dsl.execute( - "UPDATE account_authority_generations SET generation = generation + 1, " - + "source_version = source_version + 1, updated_at = CURRENT_TIMESTAMP " - + "WHERE scope_kind = 'MEMBERSHIP' AND issuer_id IS NULL " - + "AND account_uuid = ? AND tenant_uuid = ? AND generation = ? AND source_version = ?", - account.getAccountUuid(), - tenantId, - generation.generation(), - generation.sourceVersion()); - if (advanced != 1) { - throw new IllegalStateException( - "Controlled membership authority CAS did not advance once"); - } - var authority = - generations.readCompositeSnapshot( - "firemud-account-service", - account.getAccountUuid(), - List.of(tenantId), - List.of(tenantId)); - var next = authority.memberships().getFirst(); - if (next.generation() != generation.generation() + 1L - || next.sourceVersion() != generation.sourceVersion() + 1L - || !next.issuanceFence().equals(currentSource.issuanceFence()) - || !authority.issuanceFence().equals(currentSource.issuanceFence())) { - throw new IllegalStateException( - "Controlled membership differs from the actual Account fence"); - } - var tenantSource = sources.readCurrentSourceSelection(tenantId).checkpoint(); - var prior = pairs.readForUpdate(account.getAccountUuid(), tenantId).orElseThrow(); - var previous = outbox.findEvent(stream(), prior.eventSequence()).orElseThrow(); - Map event = - JsonMapper.builder() - .build() - .readValue(new String(previous.payload(), StandardCharsets.UTF_8), Map.class); - event.remove("eventDigest"); - String leave = "controlled-inactive-" + UUID.randomUUID(); - event.put("eventId", UUID.randomUUID().toString()); - event.put("requestId", leave); - event.put("outboxSequence", "2"); - event.put("membershipLifecycleState", lifecycle); - event.put("roles", roleSet); - event.put("membershipVersion", Map.of(tenantId.toString(), "3")); - event.put("membershipAuthorityGeneration", Long.toString(next.generation())); - Map tuple = new java.util.LinkedHashMap<>(); - tuple.put("issuerAuthGeneration", Long.toString(authority.issuer().generation())); - tuple.put( - "accountAuthorityGeneration", Long.toString(authority.account().generation())); - tuple.put( - "tenantAuthorityGeneration", - Map.of( - tenantId.toString(), - Long.toString(authority.tenants().getFirst().generation()))); - tuple.put( - "membershipAuthorityGeneration", - Map.of(tenantId.toString(), Long.toString(next.generation()))); - tuple.put("privateRealmGrantVersions", List.of()); - currentSource - .account() - .accountSecurityCutoff() - .ifPresent( - cutoff -> - tuple.put( - "accountSecurityCutoff", - Map.of( - "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), - "outboxStreamKey", cutoff.outboxStreamKey(), - "outboxSequence", cutoff.outboxSequence()))); - tuple.put( - "tenantBillingCutoff", - Map.of( - tenantId.toString(), - Map.of( - "tenantAuthorityGeneration", - Long.toString(tenantSource.tenantAuthorityGeneration()), - "tenantBillingSequence", - Long.toString(tenantSource.tenantBillingSequence()), - "outboxStreamKey", tenantSource.outboxStreamKey(), - "outboxSequence", Long.toString(tenantSource.outboxSequence())))); - event.put("authorityTuple", tuple); - event.put("issuanceFence", Long.toString(authority.issuanceFence().value())); - event.put("gameplayAdmissionAllowed", gameplay); - event.put("callerBoundAuthorityInvalidated", true); - var sealed = MembershipAuthorityEventV1Codec.seal(event); - var appended = - outbox.append( - stream(), - leave, - sequence -> { - if (sequence != 2L) - throw new IllegalStateException("Controlled prior event sequence changed"); - return new AccountAuthorityOutboxRepository.EventEvidence( - sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); - }); - dsl.execute( - "UPDATE account_tenant_membership SET lifecycle_state = ?, gameplay_admission_allowed = ?, membership_version = 3, membership_authority_generation = 2 WHERE id = ?", - lifecycle, - gameplay, - member.getId()); - var inactive = - members - .findCanonicalMembershipForUpdate(account.getAccountUuid(), tenantId) - .orElseThrow(); - var provenance = - new AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance( - null, - AccountMembershipPairAuthorityRepository.TenantProvenanceKind.FRESH_GAME_DESIGN, - source.operationId(), - source.evidenceDigest()); - roles.replaceCanonical( - inactive, account.getAccountUuid(), tenantId, provenance, 3L, roleSet); + history.execute(status -> { + operations.lockAccount(account.getId()); + var member = + members.findFreshMembershipForUpdate(account.getAccountUuid(), tenantId).orElseThrow(); + var generation = + generations.read( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.getAccountUuid(), tenantId)); + var beforeSource = + evidence.readCurrentIssuerAccountSources( + "firemud-account-service", account.getAccountUuid()); + + // Closed receipt/source-change mechanics supply the one shared Account fence advance. + // This remains controlled historical input, not a registered security or leave + // producer. + var currentSource = advanceControlledClosedAccountSource(beforeSource); + if (currentSource.account().generation() != beforeSource.account().generation() + 1L + || currentSource.account().sourceVersion() + != beforeSource.account().sourceVersion() + 1L + || currentSource.account().checkpoint().sequence() + != beforeSource.account().checkpoint().sequence() + 1L + || currentSource.issuanceFence().value() != generation.issuanceFence().value() + 1L + || currentSource.issuanceFence().sourceVersion() + != generation.issuanceFence().sourceVersion() + 1L) { + throw new IllegalStateException("Controlled Account source/fence did not advance once"); + } + int advanced = dsl.execute( - "UPDATE account_membership_pair_authority SET membership_version = 3, membership_authority_generation = 2, last_event_sequence = 2, last_event_id = ?, last_event_digest = ?, last_transition_invalidated = TRUE WHERE account_uuid = ? AND tenant_uuid = ?", - appended.eventId(), - appended.eventDigest(), + "UPDATE account_authority_generations SET generation = generation + 1, " + + "source_version = source_version + 1, updated_at = CURRENT_TIMESTAMP " + + "WHERE scope_kind = 'MEMBERSHIP' AND issuer_id IS NULL " + + "AND account_uuid = ? AND tenant_uuid = ? AND generation = ? AND source_version = ?", account.getAccountUuid(), - tenantId); - return null; - }); + tenantId, + generation.generation(), + generation.sourceVersion()); + if (advanced != 1) { + throw new IllegalStateException( + "Controlled membership authority CAS did not advance once"); + } + var authority = + generations.readCompositeSnapshot( + "firemud-account-service", + account.getAccountUuid(), + List.of(tenantId), + List.of(tenantId)); + var next = authority.memberships().getFirst(); + if (next.generation() != generation.generation() + 1L + || next.sourceVersion() != generation.sourceVersion() + 1L + || !next.issuanceFence().equals(currentSource.issuanceFence()) + || !authority.issuanceFence().equals(currentSource.issuanceFence())) { + throw new IllegalStateException( + "Controlled membership differs from the actual Account fence"); + } + var tenantSource = sources.readCurrentSourceSelection(tenantId).checkpoint(); + var prior = pairs.readForUpdate(account.getAccountUuid(), tenantId).orElseThrow(); + var previous = outbox.findEvent(stream(), prior.eventSequence()).orElseThrow(); + Map event = + JsonMapper.builder() + .build() + .readValue(new String(previous.payload(), StandardCharsets.UTF_8), Map.class); + event.remove("eventDigest"); + String leave = "controlled-inactive-" + UUID.randomUUID(); + event.put("eventId", UUID.randomUUID().toString()); + event.put("requestId", leave); + event.put("outboxSequence", "2"); + event.put("membershipLifecycleState", lifecycle); + event.put("roles", roleSet); + event.put("membershipVersion", Map.of(tenantId.toString(), "3")); + event.put("membershipAuthorityGeneration", Long.toString(next.generation())); + Map tuple = new java.util.LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", Long.toString(authority.issuer().generation())); + tuple.put("accountAuthorityGeneration", Long.toString(authority.account().generation())); + tuple.put( + "tenantAuthorityGeneration", + Map.of( + tenantId.toString(), Long.toString(authority.tenants().getFirst().generation()))); + tuple.put( + "membershipAuthorityGeneration", + Map.of(tenantId.toString(), Long.toString(next.generation()))); + tuple.put("privateRealmGrantVersions", List.of()); + currentSource + .account() + .accountSecurityCutoff() + .ifPresent(cutoff -> + tuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence()))); + tuple.put( + "tenantBillingCutoff", + Map.of( + tenantId.toString(), + Map.of( + "tenantAuthorityGeneration", + Long.toString(tenantSource.tenantAuthorityGeneration()), + "tenantBillingSequence", Long.toString(tenantSource.tenantBillingSequence()), + "outboxStreamKey", tenantSource.outboxStreamKey(), + "outboxSequence", Long.toString(tenantSource.outboxSequence())))); + event.put("authorityTuple", tuple); + event.put("issuanceFence", Long.toString(authority.issuanceFence().value())); + event.put("gameplayAdmissionAllowed", gameplay); + event.put("callerBoundAuthorityInvalidated", true); + var sealed = MembershipAuthorityEventV1Codec.seal(event); + var appended = + outbox.append( + stream(), + leave, + sequence -> { + if (sequence != 2L) + throw new IllegalStateException("Controlled prior event sequence changed"); + return new AccountAuthorityOutboxRepository.EventEvidence( + sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); + }); + dsl.execute( + "UPDATE account_tenant_membership SET lifecycle_state = ?, gameplay_admission_allowed = ?, membership_version = 3, membership_authority_generation = 2 WHERE id = ?", + lifecycle, + gameplay, + member.getId()); + var inactive = + members + .findCanonicalMembershipForUpdate(account.getAccountUuid(), tenantId) + .orElseThrow(); + var provenance = + new AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance( + null, + AccountMembershipPairAuthorityRepository.TenantProvenanceKind.FRESH_GAME_DESIGN, + source.operationId(), + source.evidenceDigest()); + roles.replaceCanonical( + inactive, account.getAccountUuid(), tenantId, provenance, 3L, roleSet); + dsl.execute( + "UPDATE account_membership_pair_authority SET membership_version = 3, membership_authority_generation = 2, last_event_sequence = 2, last_event_id = ?, last_event_digest = ?, last_transition_invalidated = TRUE WHERE account_uuid = ? AND tenant_uuid = ?", + appended.eventId(), + appended.eventDigest(), + account.getAccountUuid(), + tenantId); + return null; + }); } /** @@ -2188,29 +2151,26 @@ private void seedControlledSnapshot(String lifecycle, boolean gameplay, List currentRoles() { - return in( - () -> { - operations.lockAccount(account.getId()); - var member = - members - .findFreshMembershipForUpdate(account.getAccountUuid(), tenantId) - .orElseThrow(); - var provenance = - new AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance( - null, - AccountMembershipPairAuthorityRepository.TenantProvenanceKind.FRESH_GAME_DESIGN, - source.operationId(), - source.evidenceDigest()); - return roles - .findForCanonicalUpdate( - account.getAccountUuid(), - tenantId, - provenance, - member.getId(), - member.getMembershipVersion()) - .orElseThrow() - .roles(); - }); + return in(() -> { + operations.lockAccount(account.getId()); + var member = + members.findFreshMembershipForUpdate(account.getAccountUuid(), tenantId).orElseThrow(); + var provenance = + new AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance( + null, + AccountMembershipPairAuthorityRepository.TenantProvenanceKind.FRESH_GAME_DESIGN, + source.operationId(), + source.evidenceDigest()); + return roles + .findForCanonicalUpdate( + account.getAccountUuid(), + tenantId, + provenance, + member.getId(), + member.getMembershipVersion()) + .orElseThrow() + .roles(); + }); } private long membershipCount() { @@ -2476,16 +2436,15 @@ void ordinaryUuidPasswordOtpBootstrapAndScopeJourneysPreservePersistedIdentity() org.mockito.Mockito.when( emptyTargets.listVisiblePublicProductionAdmissionTargets( org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - var request = - new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( - invocation.getArgument(0, UUID.class), "test"); - return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( - request, - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( - request, List.of())); - }); + .thenAnswer(invocation -> { + var request = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( + invocation.getArgument(0, UUID.class), "test"); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, List.of())); + }); var unusedEntitlements = org.mockito.Mockito.mock(AccountPublicBootstrapEntitlementOwner.class); canonicalFacade.setPublicBootstrapWorldsOwner( new AccountPublicBootstrapWorldsOwner( @@ -2519,14 +2478,12 @@ void ordinaryUuidPasswordOtpBootstrapAndScopeJourneysPreservePersistedIdentity() String otpBody = messages.getAllValues().stream() .filter(message -> "Your FireMUD login code".equals(message.getSubject())) - .filter( - message -> { - String[] recipients = message.getTo(); - return recipients != null && java.util.Arrays.asList(recipients).contains(email); - }) - .map( - message -> - java.util.Objects.requireNonNull(message.getText(), "Expected OTP email body")) + .filter(message -> { + String[] recipients = message.getTo(); + return recipients != null && java.util.Arrays.asList(recipients).contains(email); + }) + .map(message -> + java.util.Objects.requireNonNull(message.getText(), "Expected OTP email body")) .findFirst() .orElseThrow(); var matcher = java.util.regex.Pattern.compile("\\b(\\d{6})\\b").matcher(otpBody); @@ -2570,14 +2527,12 @@ void ordinaryUuidPasswordOtpBootstrapAndScopeJourneysPreservePersistedIdentity() String loginOtpBody = loginMessages.getAllValues().stream() .filter(message -> "Your FireMUD login code".equals(message.getSubject())) - .filter( - message -> { - String[] recipients = message.getTo(); - return recipients != null && java.util.Arrays.asList(recipients).contains(email); - }) - .map( - message -> - java.util.Objects.requireNonNull(message.getText(), "Expected login OTP body")) + .filter(message -> { + String[] recipients = message.getTo(); + return recipients != null && java.util.Arrays.asList(recipients).contains(email); + }) + .map(message -> + java.util.Objects.requireNonNull(message.getText(), "Expected login OTP body")) .reduce((earlier, latest) -> latest) .orElseThrow(); var loginMatcher = java.util.regex.Pattern.compile("\\b(\\d{6})\\b").matcher(loginOtpBody); @@ -2628,13 +2583,12 @@ void ordinaryUuidPasswordOtpBootstrapAndScopeJourneysPreservePersistedIdentity() .isEqualTo(provenance); // Controlled persisted role assignment, not a synthetic privileged JWT or scoped-role issuer. new org.springframework.transaction.support.TransactionTemplate(transactionManager) - .execute( - status -> { - var owner = accountRepository.findByIdForUpdate(numericAccountId).orElseThrow(); - owner.setRole("moderator"); - accountRepository.save(owner); - return null; - }); + .execute(status -> { + var owner = accountRepository.findByIdForUpdate(numericAccountId).orElseThrow(); + owner.setRole("moderator"); + accountRepository.save(owner); + return null; + }); HttpResponse moderatorResponse = HTTP_CLIENT.send(authenticationRequest, HttpResponse.BodyHandlers.ofString()); assertThat(moderatorResponse.statusCode()).isEqualTo(200); @@ -2935,17 +2889,16 @@ private void assertOrdinaryCredentialPreservesSocialGuildSelf( var guild = org.mockito.Mockito.mock(net.firedevops.firemud.socialgroups.service.GuildService.class); org.mockito.Mockito.when(guild.createGuild(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - net.firedevops.firemud.socialgroups.dto.CreateGuildRequest request = - invocation.getArgument(0); - return new net.firedevops.firemud.socialgroups.dto.GuildDto( - 91L, - request.tenantId(), - request.name(), - request.ownerAccountId(), - java.time.Instant.now()); - }); + .thenAnswer(invocation -> { + net.firedevops.firemud.socialgroups.dto.CreateGuildRequest request = + invocation.getArgument(0); + return new net.firedevops.firemud.socialgroups.dto.GuildDto( + 91L, + request.tenantId(), + request.name(), + request.ownerAccountId(), + java.time.Instant.now()); + }); assertThat(jwtUtil.parseToken(token).getPayload().get("globalRoles")) .isEqualTo(java.util.List.of()); var same = invokeSocialCreateGuild(token, accountUuid, guild); @@ -2972,17 +2925,16 @@ private void assertOrdinaryModeratorPreservesGuildTenantAccess( var guild = org.mockito.Mockito.mock(net.firedevops.firemud.socialgroups.service.GuildService.class); org.mockito.Mockito.when(guild.createGuild(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - net.firedevops.firemud.socialgroups.dto.CreateGuildRequest request = - invocation.getArgument(0); - return new net.firedevops.firemud.socialgroups.dto.GuildDto( - 92L, - request.tenantId(), - request.name(), - request.ownerAccountId(), - java.time.Instant.now()); - }); + .thenAnswer(invocation -> { + net.firedevops.firemud.socialgroups.dto.CreateGuildRequest request = + invocation.getArgument(0); + return new net.firedevops.firemud.socialgroups.dto.GuildDto( + 92L, + request.tenantId(), + request.name(), + request.ownerAccountId(), + java.time.Instant.now()); + }); assertThat(jwtUtil.parseToken(token).getPayload().get("globalRoles")) .isEqualTo(java.util.List.of("moderator")); assertThat(invokeSocialCreateGuild(token, other, guild).hasError()).isFalse(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java index 2e71e3b8ac..f6fdd0e040 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountRuntimeEntitlementNoWriteIntegrationTest.java @@ -227,12 +227,11 @@ void missingClientCertificateIsRefusedByTlsWithoutCapacityCreation() throws Exce Map before = emptyCapacityImages(); ManagedChannel channel = channel(null); try { - assertThatThrownBy( - () -> - AccountServiceGrpc.newBlockingStub(channel) - .withInterceptors(MetadataUtils.newAttachHeadersInterceptor(fakePeer())) - .withDeadlineAfter(5, TimeUnit.SECONDS) - .getTenantEntitlementsForRuntime(REQUEST)) + assertThatThrownBy(() -> + AccountServiceGrpc.newBlockingStub(channel) + .withInterceptors(MetadataUtils.newAttachHeadersInterceptor(fakePeer())) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .getTenantEntitlementsForRuntime(REQUEST)) .isInstanceOf(StatusRuntimeException.class) .satisfies( failure -> assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue()); @@ -275,11 +274,10 @@ private static void close(ManagedChannel channel) throws InterruptedException { private Map emptyCapacityImages() throws Exception { Map images = capacityImages(); assertThat(images).hasSize(5); - images.forEach( - (table, image) -> { - assertThat(image.count()).as(table).isZero(); - assertThat(image.rows()).as(table).isEmpty(); - }); + images.forEach((table, image) -> { + assertThat(image.count()).as(table).isZero(); + assertThat(image.rows()).as(table).isEmpty(); + }); return images; } 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 15b72d484c..547f5b69bd 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 @@ -232,16 +232,14 @@ void failedEntityStartupClosesEveryRegisteredResourceDespiteCleanupFailures() { var closed = new ArrayList(); Deque resources = new ArrayDeque<>(); resources.push(() -> closed.add("postgres")); - resources.push( - () -> { - closed.add("source server"); - throw sourceFailure; - }); - resources.push( - () -> { - closed.add("owner client"); - throw clientFailure; - }); + resources.push(() -> { + closed.add("source server"); + throw sourceFailure; + }); + resources.push(() -> { + closed.add("owner client"); + throw clientFailure; + }); resources.push(() -> closed.add("meters")); resources.push(() -> closed.add("entity server")); @@ -417,27 +415,26 @@ private void configureCanonicalAccountOwners() { rowId, key, "NEW_GAME_ROW")); - transaction.executeWithoutResult( - status -> { - tenants.importVerified(source); - generations.initializeTenantIfAbsent(target.canonicalTenantId()); - accountSources.initializeIssuerIfAbsent("firemud-account-service"); - demos.provision( - new DemoTenantEntitlementRequest( - UUID.randomUUID(), - target.canonicalTenantId(), - source.creationRequestId(), - source.requestDigest(), - null, - null, - null, - true, - true, - true, - true, - new DemoTenantEntitlementRequest.Quotas(10L, 3L, 4096L)), - source); - }); + transaction.executeWithoutResult(status -> { + tenants.importVerified(source); + generations.initializeTenantIfAbsent(target.canonicalTenantId()); + accountSources.initializeIssuerIfAbsent("firemud-account-service"); + demos.provision( + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + target.canonicalTenantId(), + source.creationRequestId(), + source.requestDigest(), + null, + null, + null, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(10L, 3L, 4096L)), + source); + }); var targets = controlledAccountTargets(target); var hosting = Mockito.mock(AccountHostingSubscriptionLifecycleRepository.class); var observer = Mockito.mock(StripeHostingSubscriptionObserver.class); @@ -479,55 +476,50 @@ private void configureCanonicalAccountOwners() { private CanonicalGameplayAdmissionDecisionReadClient controlledAccountTargets(Target target) { var client = Mockito.mock(CanonicalGameplayAdmissionDecisionReadClient.class); Mockito.when(client.listVisiblePublicProductionAdmissionTargets(Mockito.any())) - .thenAnswer( - invocation -> { - var request = - new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( - invocation.getArgument(0, UUID.class), TEST_NAMESPACE); - return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( - request, - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( - request, List.of(target))); - }); + .thenAnswer(invocation -> { + var request = + new CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( + invocation.getArgument(0, UUID.class), TEST_NAMESPACE); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, List.of(target))); + }); Mockito.when(client.resolvePublishedRealmAdmissionTarget(Mockito.any())) - .thenAnswer( - invocation -> { - var request = - invocation.getArgument( - 0, - CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); - return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( - request, - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( - request, target)); - }); + .thenAnswer(invocation -> { + var request = + invocation.getArgument( + 0, CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( + request, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( + request, target)); + }); Mockito.when(client.readPublishedRealmAdmissionOwner(Mockito.any())) - .thenAnswer( - invocation -> { - var request = - invocation.getArgument(0, CanonicalGameplayRosterOwnerReadEvidence.Request.class); - var published = - Mockito.mock( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); - Mockito.when(published.selector()).thenReturn(request); - Mockito.when(published.currentTarget()).thenReturn(target); - Mockito.when(published.sourceEvidence()).thenReturn(ownerEvidence(request)); - var world = Mockito.mock(WorldCanonicalInstanceLifecycleEvidence.class); - Mockito.when(world.lifecycleStatus()).thenReturn("ACTIVE"); - Mockito.when(world.lifecycleEpoch()).thenReturn(target.activeWorldEpoch()); - Mockito.when(published.worldLifecycleEvidence()).thenReturn(world); - return published; - }); + .thenAnswer(invocation -> { + var request = + invocation.getArgument(0, CanonicalGameplayRosterOwnerReadEvidence.Request.class); + var published = + Mockito.mock( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + Mockito.when(published.selector()).thenReturn(request); + Mockito.when(published.currentTarget()).thenReturn(target); + Mockito.when(published.sourceEvidence()).thenReturn(ownerEvidence(request)); + var world = Mockito.mock(WorldCanonicalInstanceLifecycleEvidence.class); + Mockito.when(world.lifecycleStatus()).thenReturn("ACTIVE"); + Mockito.when(world.lifecycleEpoch()).thenReturn(target.activeWorldEpoch()); + Mockito.when(published.worldLifecycleEvidence()).thenReturn(world); + return published; + }); return client; } private void initializeMemberAuthority(TestAccount account) { new TransactionTemplate(transactionManager) - .executeWithoutResult( - status -> - generations.initialize( - AccountAuthorityGenerationRepository.AuthorityScope.membership( - account.accountUuid(), SOURCE.target().tenantUuid()))); + .executeWithoutResult(status -> + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.accountUuid(), SOURCE.target().tenantUuid()))); } private static Target accountTarget() { @@ -653,10 +645,9 @@ 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, accountTarget().tenantSlug(), SOURCE.target().worldSlug())) .as("REALMS owner composition after HTTP response: %s", response.body()) .doesNotThrowAnyException(); } @@ -747,21 +738,20 @@ private static UUID assign( target.playableStateScope())); var result = new TransactionTemplate(runtime.transactionManager()) - .execute( - status -> - runtime - .characterRepository() - .assignPreseededActor( - request, - evidence, - new RuntimeAccountIdentityEvidence( - 1, - TEST_NAMESPACE, - operation, - account.accountUuid(), - account.storageId(), - "ACCOUNT_REPOSITORY_INSERT"), - request.mutationIntentDigest())); + .execute(status -> + runtime + .characterRepository() + .assignPreseededActor( + request, + evidence, + new RuntimeAccountIdentityEvidence( + 1, + TEST_NAMESPACE, + operation, + account.accountUuid(), + account.storageId(), + "ACCOUNT_REPOSITORY_INSERT"), + request.mutationIntentDigest())); assertThat(result.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); assertThat( runtime @@ -850,10 +840,9 @@ private static AccountBootstrapRosterReadClient newRosterClient() { private static synchronized EntityRuntime requireEntityRuntime() { if (entityRuntime != null) return entityRuntime; Deque startedResources = new ArrayDeque<>(); - startedResources.push( - () -> { - if (entityPostgres.isRunning()) entityPostgres.stop(); - }); + startedResources.push(() -> { + if (entityPostgres.isRunning()) entityPostgres.stop(); + }); try { if (!entityPostgres.isRunning()) entityPostgres.start(); var ds = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java index f5952eeb40..f2fbabbfe2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java @@ -164,22 +164,20 @@ void commitsPasswordTokenAuthorityFenceClosedEventAndImmutableReceiptTogether() assertThat(countReceipts(fixture, seed.accountId())).isEqualTo(1L); assertThat(countEvents(fixture, streamKey)).isEqualTo(1L); byte[] tokenHashBytes = HexFormat.of().parseHex(tokenHash(seed.rawToken())); - assertThatThrownBy( - () -> - fixture - .setupDsl() - .execute( - "UPDATE account_password_reset_operation_receipts " - + "SET request_digest = request_digest WHERE token_hash = ?", - tokenHashBytes)) + assertThatThrownBy(() -> + fixture + .setupDsl() + .execute( + "UPDATE account_password_reset_operation_receipts " + + "SET request_digest = request_digest WHERE token_hash = ?", + tokenHashBytes)) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - fixture - .setupDsl() - .execute( - "DELETE FROM account_password_reset_operation_receipts WHERE token_hash = ?", - tokenHashBytes)) + assertThatThrownBy(() -> + fixture + .setupDsl() + .execute( + "DELETE FROM account_password_reset_operation_receipts WHERE token_hash = ?", + tokenHashBytes)) .isInstanceOf(DataAccessException.class); assertThat(countReceipts(fixture, seed.accountId())).isEqualTo(1L); } @@ -293,14 +291,13 @@ void waitingResetRetainsExactIntentAndSettlesOnlyAfterOriginalOwnersDeny() { assertThat(waitingVerifier).isNotBlank(); assertThat(verifierDigest).hasSize(32); assertThat(sha256Hex(waitingVerifier)).isEqualTo(HexFormat.of().formatHex(verifierDigest)); - assertThatThrownBy( - () -> - fixture - .setupDsl() - .execute( - "UPDATE account_password_reset_draft_source_changes " - + "SET password_verifier = NULL WHERE token_hash = ?", - HexFormat.of().parseHex(tokenHash(seed.rawToken())))) + assertThatThrownBy(() -> + fixture + .setupDsl() + .execute( + "UPDATE account_password_reset_draft_source_changes " + + "SET password_verifier = NULL WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash(seed.rawToken())))) .isInstanceOf(DataAccessException.class); var persistedTokenBinding = Objects.requireNonNull( @@ -360,15 +357,14 @@ void waitingResetRetainsExactIntentAndSettlesOnlyAfterOriginalOwnersDeny() { assertThat(committedResetIntent.get("request_payload", byte[].class)).isEqualTo(requestBytes); assertThat(committedResetIntent.get("source_change_binding", byte[].class)) .isEqualTo(changeBinding); - assertThatThrownBy( - () -> - fixture - .setupDsl() - .execute( - "UPDATE account_password_reset_draft_source_changes " - + "SET password_verifier_digest = password_verifier_digest " - + "WHERE token_hash = ?", - HexFormat.of().parseHex(tokenHash(seed.rawToken())))) + assertThatThrownBy(() -> + fixture + .setupDsl() + .execute( + "UPDATE account_password_reset_draft_source_changes " + + "SET password_verifier_digest = password_verifier_digest " + + "WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash(seed.rawToken())))) .isInstanceOf(DataAccessException.class); var committedV76Change = Objects.requireNonNull( @@ -560,23 +556,21 @@ void expiredWaitingResetAbortsAndDeletesOnlyItsExactOriginalToken() { .isEqualTo(waitingIntent.get("request_payload", byte[].class)); assertThat(abortedIntent.get("source_change_binding", byte[].class)) .isEqualTo(waitingIntent.get("source_change_binding", byte[].class)); - assertThatThrownBy( - () -> - fixture - .setupDsl() - .execute( - "UPDATE account_password_reset_draft_source_changes " - + "SET status = 'WAITING' WHERE token_hash = ?", - HexFormat.of().parseHex(tokenHash))) + assertThatThrownBy(() -> + fixture + .setupDsl() + .execute( + "UPDATE account_password_reset_draft_source_changes " + + "SET status = 'WAITING' WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - fixture - .setupDsl() - .execute( - "DELETE FROM account_password_reset_draft_source_changes " - + "WHERE token_hash = ?", - HexFormat.of().parseHex(tokenHash))) + assertThatThrownBy(() -> + fixture + .setupDsl() + .execute( + "DELETE FROM account_password_reset_draft_source_changes " + + "WHERE token_hash = ?", + HexFormat.of().parseHex(tokenHash))) .isInstanceOf(DataAccessException.class); assertThatThrownBy(() -> reset(fixture, seed.rawToken(), "expired-password")) @@ -654,16 +648,15 @@ public Optional findByTokenHash(String tokenHash) { }; AccountServiceImpl service = newService(readbackFailure, hideInsertedReceipt); - assertThatThrownBy( - () -> - transaction( - readbackFailure.transaction(), - () -> { - service.completePasswordReset( - new CompletePasswordResetRequest( - readbackSeed.rawToken(), "readback-failure-password")); - return null; - })) + assertThatThrownBy(() -> + transaction( + readbackFailure.transaction(), + () -> { + service.completePasswordReset( + new CompletePasswordResetRequest( + readbackSeed.rawToken(), "readback-failure-password")); + return null; + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("receipt readback is missing"); assertUnchangedAfterRollback(readbackFailure, readbackSeed, 1L, 1L); @@ -673,16 +666,15 @@ public Optional findByTokenHash(String tokenHash) { void issuanceFenceRejectsAnUnbackedOverflowAdvance() { Fixture fixture = newFixture(); Seed seed = seedAccountAndToken(fixture, "initial-password"); - assertThatThrownBy( - () -> - fixture - .setupDsl() - .execute( - "UPDATE account_authority_issuance_fences " - + "SET issuance_fence = ?, source_version = ? WHERE account_uuid = ?", - Long.MAX_VALUE, - 11L, - seed.accountUuid())) + assertThatThrownBy(() -> + fixture + .setupDsl() + .execute( + "UPDATE account_authority_issuance_fences " + + "SET issuance_fence = ?, source_version = ? WHERE account_uuid = ?", + Long.MAX_VALUE, + 11L, + seed.accountUuid())) .isInstanceOf(DataAccessException.class) .hasMessageContaining( "Account authority issuance fence and source version must advance by one"); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java index 885f7fc151..b6dd12f9c8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountControlUiSourceGuardPostgresIntegrationTest.java @@ -96,34 +96,29 @@ void ownerSourceGuardPrerequisiteSchemaIsInstalledBeforeGuardBackfill() { void rawProtectedMutationCannotBypassOriginalFenceButNoOpAndUnrelatedAccountRemainWritable() { Context c = context(); var binding = binding(c); - c.tx( - () -> { - c.fences.reserve(binding); - c.fences.claimCommitOrder(binding); - return null; - }); - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - "UPDATE accounts SET password_hash = ? WHERE account_uuid = ?", - "test-only-bypass", - binding.actorAccountId()))) + c.tx(() -> { + c.fences.reserve(binding); + c.fences.claimCommitOrder(binding); + return null; + }); + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + "UPDATE accounts SET password_hash = ? WHERE account_uuid = ?", + "test-only-bypass", + binding.actorAccountId()))) .isInstanceOf(DataAccessException.class) .hasMessageContaining("every original owner settles"); - c.tx( - () -> - c.dsl.execute( - "UPDATE accounts SET id = id WHERE account_uuid = ?", binding.actorAccountId())); + c.tx(() -> + c.dsl.execute( + "UPDATE accounts SET id = id WHERE account_uuid = ?", binding.actorAccountId())); // Username/email are not captured Account security/role fields. Existing protections still // apply. - c.tx( - () -> - c.dsl.execute( - "UPDATE accounts SET username = ? WHERE account_uuid = ?", - "test-noop-metadata", - binding.actorAccountId())); + c.tx(() -> + c.dsl.execute( + "UPDATE accounts SET username = ? WHERE account_uuid = ?", + "test-noop-metadata", + binding.actorAccountId())); UUID unrelated = account(c); changePassword(c, unrelated, "test-only-unrelated-account-change"); var ordering = @@ -140,12 +135,11 @@ void exactAllOwnerSettlementUnblocksButOneOrMixedReadbackDoesNot() { for (Outcome outcome : Outcome.values()) { Context c = context(); var binding = binding(c); - c.tx( - () -> { - c.fences.reserve(binding); - c.fences.claimCommitOrder(binding); - return null; - }); + c.tx(() -> { + c.fences.reserve(binding); + c.fences.claimCommitOrder(binding); + return null; + }); terminal(c, binding, Owner.WORLD, outcome); assertThatThrownBy(() -> changePassword(c, binding.actorAccountId(), "test-only-blocked")) .isInstanceOf(DataAccessException.class); @@ -161,12 +155,11 @@ void exactAllOwnerSettlementUnblocksButOneOrMixedReadbackDoesNot() { } Context c = context(); var binding = binding(c); - c.tx( - () -> { - c.fences.reserve(binding); - c.fences.claimCommitOrder(binding); - return null; - }); + c.tx(() -> { + c.fences.reserve(binding); + c.fences.claimCommitOrder(binding); + return null; + }); terminal(c, binding, Owner.WORLD, Outcome.COMMITTED); terminal(c, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); assertThatThrownBy(() -> changePassword(c, binding.actorAccountId(), "test-only-mixed-denied")) @@ -187,17 +180,15 @@ void sourceFirstContentionRollsBackRowsFirstProducerWithoutWaitingOrTerminalRece statement.executeQuery().close(); } Instant started = Instant.now(); - assertThatThrownBy( - () -> - c.tx( - () -> { - c.dsl.fetchOne( - "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", - binding.actorAccountId()); - c.fences.lockProducerSourcesNowait(binding.sources()); - c.fences.reserve(binding); - return c.fences.claimCommitOrder(binding); - })) + assertThatThrownBy(() -> + c.tx(() -> { + c.dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", + binding.actorAccountId()); + c.fences.lockProducerSourcesNowait(binding.sources()); + c.fences.reserve(binding); + return c.fences.claimCommitOrder(binding); + })) .isInstanceOf(DataAccessException.class); assertThat(Duration.between(started, Instant.now())).isLessThan(Duration.ofSeconds(2)); assertThat(c.dsl.fetchCount(DSL.table("account_draft_authorization_fences"))).isZero(); @@ -205,12 +196,11 @@ void sourceFirstContentionRollsBackRowsFirstProducerWithoutWaitingOrTerminalRece .isZero(); writer.rollback(); } - c.tx( - () -> { - c.fences.lockProducerSourcesNowait(binding.sources()); - c.fences.reserve(binding); - return c.fences.claimCommitOrder(binding); - }); + c.tx(() -> { + c.fences.lockProducerSourcesNowait(binding.sources()); + c.fences.reserve(binding); + return c.fences.claimCommitOrder(binding); + }); assertThatThrownBy( () -> changePassword(c, binding.actorAccountId(), "test-only-producer-first")) .isInstanceOf(DataAccessException.class); @@ -249,16 +239,15 @@ void everyMixedOwnerOutcomePairingRemainsFencedUnderBothOrderings() { Context c = context(); var binding = binding(c); var change = sourceChange(binding); - c.tx( - () -> { - c.fences.reserve(binding); - if (ordering == DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER) { - c.fences.claimCommitOrder(binding); - } else { - assertThat(c.fences.requestSourceChange(change)).isFalse(); - } - return null; - }); + c.tx(() -> { + c.fences.reserve(binding); + if (ordering == DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER) { + c.fences.claimCommitOrder(binding); + } else { + assertThat(c.fences.requestSourceChange(change)).isFalse(); + } + return null; + }); terminal(c, binding, Owner.WORLD, worldOutcome); terminal(c, binding, Owner.GAME_DESIGN, gameDesignOutcome); @@ -294,16 +283,15 @@ void overlappingSourceChangeClaimsObserveBackendWaitWhileDisjointSourcesProceed( new Thread( () -> { try { - c.tx( - () -> { - firstPid.set( - Objects.requireNonNull(c.dsl.fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class)); - assertThat(c.fences.requestSourceChange(firstChange)).isFalse(); - firstIntentRecorded.countDown(); - await(releaseFirstIntent); - return null; - }); + c.tx(() -> { + firstPid.set( + Objects.requireNonNull(c.dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + assertThat(c.fences.requestSourceChange(firstChange)).isFalse(); + firstIntentRecorded.countDown(); + await(releaseFirstIntent); + return null; + }); } catch (Throwable failure) { firstFailure.set(failure); firstIntentRecorded.countDown(); @@ -366,14 +354,12 @@ void reservationAndSourceChangeIntentRollbackLeavesRowsUnchangedAndAllowsDisjoin Map before = authorizationRowCounts(c); String passwordBefore = accountPassword(c, binding.actorAccountId()); - assertThatThrownBy( - () -> - c.tx( - () -> { - c.fences.reserve(binding); - assertThat(c.fences.requestSourceChange(change)).isFalse(); - throw new IllegalStateException("test-only transaction rollback"); - })) + assertThatThrownBy(() -> + c.tx(() -> { + c.fences.reserve(binding); + assertThat(c.fences.requestSourceChange(change)).isFalse(); + throw new IllegalStateException("test-only transaction rollback"); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("test-only transaction rollback"); @@ -400,21 +386,19 @@ void exactSourceAbortRetryPreservesTerminalReadbackAndCannotReopen() { Context c = context(); var binding = binding(c); var change = sourceChange(binding); - c.tx( - () -> { - c.fences.reserve(binding); - assertThat(c.fences.requestSourceChange(change)).isFalse(); - return null; - }); + c.tx(() -> { + c.fences.reserve(binding); + assertThat(c.fences.requestSourceChange(change)).isFalse(); + return null; + }); terminal(c, binding, Owner.WORLD, Outcome.DEFINITIVELY_ABORTED); terminal(c, binding, Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED); assertThat(c.tx(() -> c.fences.sourceAbortPermitted(change))).isTrue(); - c.tx( - () -> { - c.fences.markSourceAborted(change, SourceChangeAbortReason.EXPIRED); - return null; - }); + c.tx(() -> { + c.fences.markSourceAborted(change, SourceChangeAbortReason.EXPIRED); + return null; + }); var aborted = c.tx(() -> c.fences.readSourceChange(change)); String abortedRowVersion = sourceChangeRowVersion(c, change.changeId()); assertThat(aborted.status()).isEqualTo("SOURCE_ABORTED"); @@ -423,21 +407,18 @@ void exactSourceAbortRetryPreservesTerminalReadbackAndCannotReopen() { assertThat(aborted.abortedAt()).isNotNull(); assertThat(aborted.abortReason()).isEqualTo(SourceChangeAbortReason.EXPIRED); - c.tx( - () -> { - c.fences.markSourceAborted(change, SourceChangeAbortReason.EXPIRED); - return null; - }); + c.tx(() -> { + c.fences.markSourceAborted(change, SourceChangeAbortReason.EXPIRED); + return null; + }); assertSourceChangeUnchanged(c.tx(() -> c.fences.readSourceChange(change)), aborted); assertThat(sourceChangeRowVersion(c, change.changeId())).isEqualTo(abortedRowVersion); - assertThatThrownBy( - () -> - c.tx( - () -> { - c.fences.markSourceAborted(change, SourceChangeAbortReason.DEFINITIVE_ABORT); - return null; - })) + assertThatThrownBy(() -> + c.tx(() -> { + c.fences.markSourceAborted(change, SourceChangeAbortReason.DEFINITIVE_ABORT); + return null; + })) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Source change abort reason differs from readback"); assertSourceChangeUnchanged(c.tx(() -> c.fences.readSourceChange(change)), aborted); @@ -445,13 +426,11 @@ void exactSourceAbortRetryPreservesTerminalReadbackAndCannotReopen() { assertThatThrownBy(() -> c.tx(() -> c.fences.requestSourceChange(change))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Aborted source change cannot be requested again"); - assertThatThrownBy( - () -> - c.tx( - () -> { - c.fences.markSourceCommitted(change); - return null; - })) + assertThatThrownBy(() -> + c.tx(() -> { + c.fences.markSourceCommitted(change); + return null; + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Aborted source change cannot be committed"); assertSourceChangeUnchanged(c.tx(() -> c.fences.readSourceChange(change)), aborted); @@ -559,15 +538,14 @@ private static Thread startContender( new Thread( () -> { try { - c.tx( - () -> { - backendPid.set( - Objects.requireNonNull(c.dsl.fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class)); - started.countDown(); - action.run(); - return null; - }); + c.tx(() -> { + backendPid.set( + Objects.requireNonNull(c.dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + started.countDown(); + action.run(); + return null; + }); } catch (Throwable thrown) { failure.set(thrown); started.countDown(); @@ -659,42 +637,39 @@ private static String sourceChangeRowVersion(Context c, UUID changeId) { private static void terminal( Context c, DraftAuthorizationFenceBinding binding, Owner owner, Outcome outcome) { - c.tx( - () -> { - c.fences.recordOwnerReadback( - binding, - new OwnerReadback( - owner, - outcome, - binding.operationId(), - binding.commitId(), - binding.fenceId(), - binding.inputDigest(), - binding.canonicalBytes(), - new byte[] {7})); - return null; - }); + c.tx(() -> { + c.fences.recordOwnerReadback( + binding, + new OwnerReadback( + owner, + outcome, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + new byte[] {7})); + return null; + }); } private static void changePassword(Context c, UUID id, String hash) { - c.tx( - () -> { - Account account = new AccountRepository(c.dsl).findByAccountUuid(id).orElseThrow(); - account.setPasswordHash(hash); - return new AccountRepository(c.dsl).save(account); - }); + c.tx(() -> { + Account account = new AccountRepository(c.dsl).findByAccountUuid(id).orElseThrow(); + account.setPasswordHash(hash); + return new AccountRepository(c.dsl).save(account); + }); } private static UUID account(Context c) { - return c.tx( - () -> { - Account row = new Account(); - String suffix = UUID.randomUUID().toString(); - row.setUsername("test-" + suffix); - row.setEmail(suffix + "@example.test"); - row.setPasswordHash("test-only-hash"); - return new AccountRepository(c.dsl).save(row).getAccountUuid(); - }); + return c.tx(() -> { + Account row = new Account(); + String suffix = UUID.randomUUID().toString(); + row.setUsername("test-" + suffix); + row.setEmail(suffix + "@example.test"); + row.setPasswordHash("test-only-hash"); + return new AccountRepository(c.dsl).save(row).getAccountUuid(); + }); } private static DraftAuthorizationFenceBinding binding(Context c) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadPostgresIntegrationTest.java index 527d9fffe9..a1d1b8f335 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftCommitOrderReadPostgresIntegrationTest.java @@ -67,12 +67,11 @@ void acceptsOnlyExactCommittedHeldOrderInSeparateWritableReadCommittedTransactio throws Exception { Fixture fixture = fixture(); DraftAuthorizationFenceBinding binding = binding(fixture); - fixture.tx( - () -> { - fixture.repository.reserve(binding); - fixture.repository.claimCommitOrder(binding); - return null; - }); + fixture.tx(() -> { + fixture.repository.reserve(binding); + fixture.repository.claimCommitOrder(binding); + return null; + }); var before = snapshot(fixture); assertThat(ordering(fixture, binding)).isEqualTo("COMMIT_ORDER"); Record order = @@ -99,16 +98,14 @@ void acceptsOnlyExactCommittedHeldOrderInSeparateWritableReadCommittedTransactio // V87's real source guard remains effective while this original owner result is unresolved. String passwordBefore = accountPassword(fixture, binding.actorAccountId()); - assertThatThrownBy( - () -> - fixture.tx( - () -> { - fixture.dsl.execute( - "UPDATE accounts SET password_hash = ? WHERE account_uuid = ?", - "test-only-blocked-change", - binding.actorAccountId()); - return null; - })) + assertThatThrownBy(() -> + fixture.tx(() -> { + fixture.dsl.execute( + "UPDATE accounts SET password_hash = ? WHERE account_uuid = ?", + "test-only-blocked-change", + binding.actorAccountId()); + return null; + })) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("Required creator source is held"); assertThat(accountPassword(fixture, binding.actorAccountId())).isEqualTo(passwordBefore); @@ -213,15 +210,14 @@ private static Fixture fixture() { private static DraftAuthorizationFenceBinding binding(Fixture fixture) { UUID account = - fixture.tx( - () -> { - Account row = new Account(); - String suffix = UUID.randomUUID().toString(); - row.setUsername("held-order-" + suffix); - row.setEmail(suffix + "@example.test"); - row.setPasswordHash("test-only-original-hash"); - return new AccountRepository(fixture.dsl).save(row).getAccountUuid(); - }); + fixture.tx(() -> { + Account row = new Account(); + String suffix = UUID.randomUUID().toString(); + row.setUsername("held-order-" + suffix); + row.setEmail(suffix + "@example.test"); + row.setPasswordHash("test-only-original-hash"); + return new AccountRepository(fixture.dsl).save(row).getAccountUuid(); + }); UUID tenant = UUID.randomUUID(); UUID version = UUID.randomUUID(); UUID request = UUID.randomUUID(); @@ -303,12 +299,11 @@ private static DraftAuthorizationFenceBinding changedBinding( private static void reserveAndCommitOrder( Fixture fixture, DraftAuthorizationFenceBinding binding) { - fixture.tx( - () -> { - fixture.repository.reserve(binding); - fixture.repository.claimCommitOrder(binding); - return null; - }); + fixture.tx(() -> { + fixture.repository.reserve(binding); + fixture.repository.claimCommitOrder(binding); + return null; + }); } private static void recordReadback( @@ -327,11 +322,10 @@ private static void recordReadback( binding.inputDigest(), binding.canonicalBytes(), result); - fixture.tx( - () -> { - fixture.repository.recordOwnerReadback(binding, readback); - return null; - }); + fixture.tx(() -> { + fixture.repository.recordOwnerReadback(binding, readback); + return null; + }); } private static DraftCommitOrderReadEvidence.Request request( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java index 5984a479e7..eb36525f00 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java @@ -112,42 +112,38 @@ void retainedV1OrderReadbackAndPendingChangeSurviveRequiredOwnerAndCurrentMigrat assertThat(historyRank(dsl)).isGreaterThan(rank76); assertThat(history(dsl, rank76)).isEqualTo(history76); Map> currentRows = rows(dsl, queries); - rows.forEach( - (table, originalRows) -> { - if (table.equals("account_draft_authorization_source_locks")) { - // V87 adds a serialization lock from the real Account scope, never authority evidence. - assertThat(currentRows.get(table)) - .containsAll(originalRows) - .hasSize(originalRows.size() + 1); - } else { - assertThat(currentRows.get(table)).isEqualTo(originalRows); - } - }); + rows.forEach((table, originalRows) -> { + if (table.equals("account_draft_authorization_source_locks")) { + // V87 adds a serialization lock from the real Account scope, never authority evidence. + assertThat(currentRows.get(table)) + .containsAll(originalRows) + .hasSize(originalRows.size() + 1); + } else { + assertThat(currentRows.get(table)).isEqualTo(originalRows); + } + }); assertThat( dsl.fetch("SELECT source_key FROM account_draft_authorization_source_locks") .getValues(0, String.class)) .containsExactlyInAnyOrder( binding.sources().get(0).key(), legacyKey.key(), "GLOBAL_ROLES:" + account); assertRetained(dsl, transaction, binding, world, change, legacyKey); - transaction.executeWithoutResult( - ignored -> - assertThat(new DraftAuthorizationFenceRepository(dsl).sourceMutationPermitted(change)) - .isFalse()); + transaction.executeWithoutResult(ignored -> + assertThat(new DraftAuthorizationFenceRepository(dsl).sourceMutationPermitted(change)) + .isFalse()); assertThat(rows(dsl, queries)).isEqualTo(currentRows); assertHistoricalProvenance(dsl, account); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE account_draft_authorization_fences SET binding = ? WHERE operation_id = ?", - new byte[] {99}, - binding.operationId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE account_draft_authorization_fences SET binding = ? WHERE operation_id = ?", + new byte[] {99}, + binding.operationId())) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM account_draft_authorization_owner_readbacks WHERE operation_id = ?", - binding.operationId())) + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM account_draft_authorization_owner_readbacks WHERE operation_id = ?", + binding.operationId())) .isInstanceOf(DataAccessException.class); assertThat(rows(dsl, queries)).isEqualTo(currentRows); } @@ -160,23 +156,18 @@ private static void assertRetained( SourceChange change, SourceEvidence legacyKey) { var repository = new DraftAuthorizationFenceRepository(dsl); - transaction.executeWithoutResult( - ignored -> { - assertThat( - repository - .readOriginalBinding(binding.operationId()) - .orElseThrow() - .canonicalBytes()) - .containsExactly(binding.canonicalBytes()); - assertThat(repository.reserve(binding).binding()) - .containsExactly(binding.canonicalBytes()); - assertThat(repository.read(binding).ordering()).isEqualTo(Ordering.COMMIT_ORDER); - assertThat(repository.readOwnerResult(binding, Owner.WORLD).orElseThrow().readback()) - .containsExactly(world.canonicalBytes()); - assertThat(repository.readOwnerResult(binding, Owner.GAME_DESIGN)).isEmpty(); - assertThat(repository.readSettlement(binding)).isEqualTo(Settlement.PENDING); - assertThat(repository.readSourceChange(change).status()).isEqualTo("WAITING"); - }); + transaction.executeWithoutResult(ignored -> { + assertThat( + repository.readOriginalBinding(binding.operationId()).orElseThrow().canonicalBytes()) + .containsExactly(binding.canonicalBytes()); + assertThat(repository.reserve(binding).binding()).containsExactly(binding.canonicalBytes()); + assertThat(repository.read(binding).ordering()).isEqualTo(Ordering.COMMIT_ORDER); + assertThat(repository.readOwnerResult(binding, Owner.WORLD).orElseThrow().readback()) + .containsExactly(world.canonicalBytes()); + assertThat(repository.readOwnerResult(binding, Owner.GAME_DESIGN)).isEmpty(); + assertThat(repository.readSettlement(binding)).isEqualTo(Settlement.PENDING); + assertThat(repository.readSourceChange(change).status()).isEqualTo("WAITING"); + }); assertThat( Objects.requireNonNull( dsl.fetchOne( @@ -194,45 +185,44 @@ private static void seedHistoricalState( SourceChange change) { // Preserve V75's actual guarded insert/order lifecycle. Current source-change APIs also // inspect later publication owners, which do not exist in this predecessor schema. - transaction.executeWithoutResult( - ignored -> { - for (SourceEvidence evidence : binding.sources()) { - dsl.execute( - "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?) ON CONFLICT DO NOTHING", - evidence.key()); - } - dsl.execute( - "INSERT INTO account_draft_authorization_fences (operation_id, request_id, commit_id, fence_id, binding, ordering) VALUES (?, ?, ?, ?, ?, 'RESERVED')", - binding.operationId(), - binding.requestId(), - binding.commitId(), - binding.fenceId(), - binding.canonicalBytes()); - for (SourceEvidence evidence : binding.sources()) { - dsl.execute( - "INSERT INTO account_draft_authorization_sources (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", - binding.operationId(), - evidence.key(), - evidence.canonicalBytes()); - } - dsl.execute( - "UPDATE account_draft_authorization_fences SET ordering = 'COMMIT_ORDER', ordered_at = CURRENT_TIMESTAMP WHERE operation_id = ?", - binding.operationId()); - dsl.execute( - "INSERT INTO account_draft_authorization_owner_readbacks (operation_id, owner, outcome, readback) VALUES (?, 'WORLD', 'COMMITTED', ?)", - binding.operationId(), - world.canonicalBytes()); - dsl.execute( - "INSERT INTO account_draft_authorization_source_changes (change_id, binding, status) VALUES (?, ?, 'WAITING')", - change.changeId(), - change.canonicalBytes()); - for (SourceEvidence evidence : change.sources()) { - dsl.execute( - "INSERT INTO account_draft_authorization_changed_scopes (change_id, source_key) VALUES (?, ?)", - change.changeId(), - evidence.key()); - } - }); + transaction.executeWithoutResult(ignored -> { + for (SourceEvidence evidence : binding.sources()) { + dsl.execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?) ON CONFLICT DO NOTHING", + evidence.key()); + } + dsl.execute( + "INSERT INTO account_draft_authorization_fences (operation_id, request_id, commit_id, fence_id, binding, ordering) VALUES (?, ?, ?, ?, ?, 'RESERVED')", + binding.operationId(), + binding.requestId(), + binding.commitId(), + binding.fenceId(), + binding.canonicalBytes()); + for (SourceEvidence evidence : binding.sources()) { + dsl.execute( + "INSERT INTO account_draft_authorization_sources (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + binding.operationId(), + evidence.key(), + evidence.canonicalBytes()); + } + dsl.execute( + "UPDATE account_draft_authorization_fences SET ordering = 'COMMIT_ORDER', ordered_at = CURRENT_TIMESTAMP WHERE operation_id = ?", + binding.operationId()); + dsl.execute( + "INSERT INTO account_draft_authorization_owner_readbacks (operation_id, owner, outcome, readback) VALUES (?, 'WORLD', 'COMMITTED', ?)", + binding.operationId(), + world.canonicalBytes()); + dsl.execute( + "INSERT INTO account_draft_authorization_source_changes (change_id, binding, status) VALUES (?, ?, 'WAITING')", + change.changeId(), + change.canonicalBytes()); + for (SourceEvidence evidence : change.sources()) { + dsl.execute( + "INSERT INTO account_draft_authorization_changed_scopes (change_id, source_key) VALUES (?, ?)", + change.changeId(), + evidence.key()); + } + }); } private static UUID insertHistoricalAccount(DSLContext dsl) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java index ad3851a609..7c408561c3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java @@ -221,37 +221,35 @@ void exactRetryAmbiguityAndTerminalEvidenceAreDurableAndImmutable() throws Excep assertThatThrownBy(() -> tx(database, () -> journal.recordResult(handoff, changedResult))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Changed terminal"); - assertThatThrownBy( - () -> - tx( - database, - () -> { - database - .dsl() - .execute( - "UPDATE account_hosted_terms_disclosure_handoffs " - + "SET result_payload = ? WHERE handoff_id = ?", - "test-only-overwrite".getBytes(StandardCharsets.UTF_8), - handoff.handoffId()); - return null; - })) + assertThatThrownBy(() -> + tx( + database, + () -> { + database + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs " + + "SET result_payload = ? WHERE handoff_id = ?", + "test-only-overwrite".getBytes(StandardCharsets.UTF_8), + handoff.handoffId()); + return null; + })) .isInstanceOf(DataAccessException.class); HostedTermsDisclosureHandoff noDisclosure = handoff(source("definitive-no-disclosure")); tx(database, () -> journal.prepare(noDisclosure)); - assertThatThrownBy( - () -> - tx( - database, - () -> - journal.recordResult( - noDisclosure, - new DisclosureResult( - noDisclosure.handoffId(), - noDisclosure.requestId(), - HostedTermsEncoding.digest(noDisclosure.canonicalBytes()), - Outcome.DEFINITIVELY_NOT_DISCLOSED, - "test-only-premature-negative".getBytes(StandardCharsets.UTF_8))))) + assertThatThrownBy(() -> + tx( + database, + () -> + journal.recordResult( + noDisclosure, + new DisclosureResult( + noDisclosure.handoffId(), + noDisclosure.requestId(), + HostedTermsEncoding.digest(noDisclosure.canonicalBytes()), + Outcome.DEFINITIVELY_NOT_DISCLOSED, + "test-only-premature-negative".getBytes(StandardCharsets.UTF_8))))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("dispatch authorization"); tx(database, () -> journal.authorizeDispatch(noDisclosure)); @@ -338,9 +336,8 @@ public void attachAccountRedemptionProjection( SourceEvidence source = ((List) captureSnapshot.get("sourceVector")) .stream() - .map( - value -> - SourceEvidence.fromStored(Base64.getDecoder().decode((String) value))) + .map(value -> + SourceEvidence.fromStored(Base64.getDecoder().decode((String) value))) .filter(value -> value.kind() != SourceKind.HOSTED_TERMS) .findFirst() .orElseThrow(() -> new IllegalStateException("Expected a non-terms source")); @@ -356,14 +353,12 @@ public void attachAccountRedemptionProjection( String preparationInput = preparationInput(NAMESPACE, controlUi.tenantId(), requestId, gameInstance, 42L); AccountStartSessionWorldParticipationAcquisitionService acquisition = - proof.worldParticipationAcquisitionService( - request -> - new Result( - request, - Instant.ofEpochMilli( - Instant.now().plus(Duration.ofMinutes(1)).toEpochMilli()), - StartSessionAccountRedemptionProjection.fromOriginalTuple( - request.originalTuple()))); + proof.worldParticipationAcquisitionService(request -> + new Result( + request, + Instant.ofEpochMilli(Instant.now().plus(Duration.ofMinutes(1)).toEpochMilli()), + StartSessionAccountRedemptionProjection.fromOriginalTuple( + request.originalTuple()))); var acquisitionRequest = new AcquisitionRequest( original.originalTuple().canonicalBytes(), @@ -612,46 +607,44 @@ private static void concurrentAcquisitionAndDispatch(boolean dispatchFirst) thro var executor = Executors.newFixedThreadPool(2); try { var first = - executor.submit( - () -> - tx( - database, - () -> { - firstPid.set( - Objects.requireNonNull( - database.dsl().fetchOne("SELECT pg_backend_pid()"), - "Expected first transaction PostgreSQL backend PID row") - .get(0, Integer.class)); - if (dispatchFirst) { - journal.authorizeDispatch(handoff); - } else { - fences.reserve(original); - fences.claimCommitOrder(original); - } - firstLocked.countDown(); - await(releaseFirst); - return null; - })); + executor.submit(() -> + tx( + database, + () -> { + firstPid.set( + Objects.requireNonNull( + database.dsl().fetchOne("SELECT pg_backend_pid()"), + "Expected first transaction PostgreSQL backend PID row") + .get(0, Integer.class)); + if (dispatchFirst) { + journal.authorizeDispatch(handoff); + } else { + fences.reserve(original); + fences.claimCommitOrder(original); + } + firstLocked.countDown(); + await(releaseFirst); + return null; + })); assertThat(firstLocked.await(10, TimeUnit.SECONDS)).isTrue(); var second = - executor.submit( - () -> - tx( - database, - () -> { - secondPid.set( - Objects.requireNonNull( - database.dsl().fetchOne("SELECT pg_backend_pid()"), - "Expected second transaction PostgreSQL backend PID row") - .get(0, Integer.class)); - secondStarted.countDown(); - if (dispatchFirst) { - fences.reserve(original); - } else { - journal.authorizeDispatch(handoff); - } - return null; - })); + executor.submit(() -> + tx( + database, + () -> { + secondPid.set( + Objects.requireNonNull( + database.dsl().fetchOne("SELECT pg_backend_pid()"), + "Expected second transaction PostgreSQL backend PID row") + .get(0, Integer.class)); + secondStarted.countDown(); + if (dispatchFirst) { + fences.reserve(original); + } else { + journal.authorizeDispatch(handoff); + } + return null; + })); assertThat(secondStarted.await(10, TimeUnit.SECONDS)).isTrue(); awaitBlocked(database, secondPid.get(), firstPid.get()); assertThatThrownBy(() -> second.get(200, TimeUnit.MILLISECONDS)) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingFencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingFencePostgresIntegrationTest.java index af0206dee2..4ac7a32725 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingFencePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsEnvironmentBindingFencePostgresIntegrationTest.java @@ -170,16 +170,15 @@ private CatalogVersion insertInitialCatalog( context .transaction() - .executeWithoutResult( - status -> { - repository.ensureScope(scopeId); - repository.claimPublication(requestId, scopeId, request); - repository.lockScope(scopeId); - repository.insertCandidate(candidate); - repository.markScheduled(requestId, candidate); - repository.completePublication( - requestId, candidate, HostedTermsEncoding.catalog(candidate), null); - }); + .executeWithoutResult(status -> { + repository.ensureScope(scopeId); + repository.claimPublication(requestId, scopeId, request); + repository.lockScope(scopeId); + repository.insertCandidate(candidate); + repository.markScheduled(requestId, candidate); + repository.completePublication( + requestId, candidate, HostedTermsEncoding.catalog(candidate), null); + }); return new CatalogVersion(candidate); } @@ -193,15 +192,13 @@ private HostedTermsEnvironmentBinding publishInitialBinding( HostedTermsEnvironmentBinding[] candidate = new HostedTermsEnvironmentBinding[1]; context .transaction() - .executeWithoutResult( - status -> { - repository.ensureHead(boundary); - repository.claimPublication(requestId, boundary, request); - repository.lockHead(boundary); - candidate[0] = - repository.insertCandidate(UUID.randomUUID(), requestId, evidence, null); - repository.completePublication(requestId, candidate[0], null, null); - }); + .executeWithoutResult(status -> { + repository.ensureHead(boundary); + repository.claimPublication(requestId, boundary, request); + repository.lockHead(boundary); + candidate[0] = repository.insertCandidate(UUID.randomUUID(), requestId, evidence, null); + repository.completePublication(requestId, candidate[0], null, null); + }); return candidate[0]; } @@ -222,39 +219,36 @@ private HostedTermsEnvironmentBinding publishSuccessor( context .transaction() - .executeWithoutResult( - status -> { - bindings.claimPublication(requestId, boundary, request); - HostedTermsEnvironmentBindingRepository.HeadSnapshot head = - bindings.lockHead(boundary); - if (!predecessor.equals(head.current())) { - throw new IllegalStateException("Test predecessor differs from exact binding head"); - } - HostedTermsEnvironmentBinding candidate = - bindings.insertCandidate(UUID.randomUUID(), requestId, evidence, head.current()); - SourceEvidence predecessorSource = predecessor.sourceEvidence(); - SourceEvidence priorCatalogSource = catalogSource(catalogs.first()); - SourceEvidence targetCatalogSource = catalogSource(catalogs.second()); - List expectedSources = - List.of(predecessorSource, priorCatalogSource, targetCatalogSource); - List changedSources = - changedSources(shape, expectedSources, predecessor); - DraftAuthorizationFenceRepository.SourceChange change = - new DraftAuthorizationFenceRepository.SourceChange( - changeId, - changedSources, - HostedTermsEnvironmentBindingEncoding.receipt(candidate)); - if (!fences.requestSourceChange(change) || !fences.sourceMutationPermitted(change)) { - throw new IllegalStateException("Run-owned Draft source fixture did not settle"); - } - bindings.markOwnerSettlementPending(requestId, candidate, change.canonicalBytes()); - bindings.completePublication( - requestId, candidate, change.canonicalBytes(), head.current()); - if (shape != ChangeShape.WAITING) { - fences.markSourceCommitted(change); - } - committed[0] = candidate; - }); + .executeWithoutResult(status -> { + bindings.claimPublication(requestId, boundary, request); + HostedTermsEnvironmentBindingRepository.HeadSnapshot head = bindings.lockHead(boundary); + if (!predecessor.equals(head.current())) { + throw new IllegalStateException("Test predecessor differs from exact binding head"); + } + HostedTermsEnvironmentBinding candidate = + bindings.insertCandidate(UUID.randomUUID(), requestId, evidence, head.current()); + SourceEvidence predecessorSource = predecessor.sourceEvidence(); + SourceEvidence priorCatalogSource = catalogSource(catalogs.first()); + SourceEvidence targetCatalogSource = catalogSource(catalogs.second()); + List expectedSources = + List.of(predecessorSource, priorCatalogSource, targetCatalogSource); + List changedSources = changedSources(shape, expectedSources, predecessor); + DraftAuthorizationFenceRepository.SourceChange change = + new DraftAuthorizationFenceRepository.SourceChange( + changeId, + changedSources, + HostedTermsEnvironmentBindingEncoding.receipt(candidate)); + if (!fences.requestSourceChange(change) || !fences.sourceMutationPermitted(change)) { + throw new IllegalStateException("Run-owned Draft source fixture did not settle"); + } + bindings.markOwnerSettlementPending(requestId, candidate, change.canonicalBytes()); + bindings.completePublication( + requestId, candidate, change.canonicalBytes(), head.current()); + if (shape != ChangeShape.WAITING) { + fences.markSourceCommitted(change); + } + committed[0] = candidate; + }); return committed[0]; } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java index 5edc57d71a..4a584fc5cf 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundlePersistenceIntegrationTest.java @@ -109,12 +109,11 @@ void forwardCheckpointRepairRetainsV84OwnersAndCapturesZeroAndPositiveEvidence() inTransaction(context, () -> bundles.captureAndPersist(zero.requestId())); assertThat(zeroBundle.fields().get("outboxCheckpoints")) .asList() - .allSatisfy( - checkpoint -> - assertThat(checkpoint) - .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.MAP) - .containsEntry("outboxSequence", "0") - .hasSize(2)); + .allSatisfy(checkpoint -> + assertThat(checkpoint) + .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.MAP) + .containsEntry("outboxSequence", "0") + .hasSize(2)); AccountGameplayDelegationIssuancePersistenceIntegrationTest.advanceEmailVerifiedThroughOwner( dsl, context.transaction(), sources, account.getAccountUuid()); @@ -123,13 +122,12 @@ void forwardCheckpointRepairRetainsV84OwnersAndCapturesZeroAndPositiveEvidence() inTransaction(context, () -> bundles.captureAndPersist(positive.requestId())); assertThat(positiveBundle.fields().get("outboxCheckpoints")) .asList() - .anySatisfy( - checkpoint -> - assertThat(checkpoint) - .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.MAP) - .containsEntry("outboxSequence", "1") - .containsKeys("sourceEventId", "sourceEventDigest") - .hasSize(4)); + .anySatisfy(checkpoint -> + assertThat(checkpoint) + .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.MAP) + .containsEntry("outboxSequence", "1") + .containsKeys("sourceEventId", "sourceEventDigest") + .hasSize(4)); var retainedBundles = dsl.fetch( "SELECT * FROM account_gameplay_delegation_auth_evidence_bundles ORDER BY operation_id") @@ -417,17 +415,15 @@ void freshOwnerBaselinesProduceExactZeroCheckpointBundlesAndConcurrentRetryReadb CountDownLatch captureStart = new CountDownLatch(1); ExecutorService concurrentCaptures = Executors.newFixedThreadPool(2); var firstCapture = - concurrentCaptures.submit( - () -> { - captureStart.await(); - return inTransaction(context, () -> bundles.captureAndPersist(pending.requestId())); - }); + concurrentCaptures.submit(() -> { + captureStart.await(); + return inTransaction(context, () -> bundles.captureAndPersist(pending.requestId())); + }); var secondCapture = - concurrentCaptures.submit( - () -> { - captureStart.await(); - return inTransaction(context, () -> bundles.captureAndPersist(pending.requestId())); - }); + concurrentCaptures.submit(() -> { + captureStart.await(); + return inTransaction(context, () -> bundles.captureAndPersist(pending.requestId())); + }); AccountAuthEvidenceBundle first; AccountAuthEvidenceBundle concurrentRetry; try { @@ -480,24 +476,22 @@ void freshOwnerBaselinesProduceExactZeroCheckpointBundlesAndConcurrentRetryReadb assertThat(nextReference.get("sourceFence")).isEqualTo("2"); assertThat(new java.math.BigInteger((String) nextReference.get("sourceFence"))) .isGreaterThan(new java.math.BigInteger((String) firstReference.get("sourceFence"))); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - dsl.execute( - "UPDATE account_gameplay_delegation_auth_evidence_bundles " - + "SET source_fence = '99' WHERE operation_id = ?", - pending.operationId()))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + dsl.execute( + "UPDATE account_gameplay_delegation_auth_evidence_bundles " + + "SET source_fence = '99' WHERE operation_id = ?", + pending.operationId()))) .isInstanceOf(RuntimeException.class); assertThat(first.fields().get("outboxCheckpoints")) .asList() - .allSatisfy( - checkpoint -> - assertThat(checkpoint) - .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.MAP) - .containsEntry("outboxSequence", "0") - .doesNotContainKeys("sourceEventId", "sourceEventDigest")); + .allSatisfy(checkpoint -> + assertThat(checkpoint) + .asInstanceOf(org.assertj.core.api.InstanceOfAssertFactories.MAP) + .containsEntry("outboxSequence", "0") + .doesNotContainKeys("sourceEventId", "sourceEventDigest")); Long bundleCount = Objects.requireNonNull( dsl.fetchOne( @@ -569,12 +563,11 @@ private static AccountAuthoritySnapshot authoritySnapshot(IssuerAccountSourceSna snapshot .account() .accountSecurityCutoff() - .map( - value -> - new GameSessionAccountDelegationProfile.AccountSecurityCutoff( - value.accountAuthorityGeneration(), - value.outboxStreamKey(), - value.outboxSequence())); + .map(value -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())); return new AccountAuthoritySnapshot( snapshot.account().scope().accountId(), snapshot.issuer().generation(), diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java index c6b3054318..beacf29af4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthorityCurrentnessIntegrationTest.java @@ -126,11 +126,10 @@ void subscriptionAndRealmGrantMutationsAdvanceCurrentnessAndKeepRevocationTombst .isNotEqualTo(initial.tenantAuthorityEvent().eventId()); assertCanonicalCheckpoint(fixture, changed); - assertThatThrownBy( - () -> - jdbc.update( - "UPDATE subscription SET status = 'active', row_version = row_version + 1 WHERE subscription_id = ?", - fixture.creation().subscriptionId())) + assertThatThrownBy(() -> + jdbc.update( + "UPDATE subscription SET status = 'active', row_version = row_version + 1 WHERE subscription_id = ?", + fixture.creation().subscriptionId())) .isInstanceOf(org.springframework.dao.DataIntegrityViolationException.class); int changedReads = fixture.transport().reads(); assertThat( @@ -197,10 +196,9 @@ void subscriptionAndRealmGrantMutationsAdvanceCurrentnessAndKeepRevocationTombst TransactionTemplate transaction = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); - transaction.executeWithoutResult( - status -> - grants.revokeByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( - accountId, tenantId, "world", "private")); + transaction.executeWithoutResult(status -> + grants.revokeByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( + accountId, tenantId, "world", "private")); AccountRealmAccessGrant revoked = grants .findByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( @@ -232,45 +230,43 @@ private static void assertCanonicalCheckpoint( assertThat(event.tenantBillingEventDigest()).isEqualTo(receipt.billingEventDigest()); fixture .transaction() - .executeWithoutResult( - status -> { - var currentGeneration = - new AccountAuthorityGenerationRepository(fixture.dsl()) - .read(AuthorityScope.tenant(fixture.tenantId())); - assertThat(currentGeneration.generation()) - .isEqualTo(event.tenantAuthorityGeneration()); - assertThat(currentGeneration.sourceVersion()) - .isEqualTo(event.tenantAuthoritySourceVersion()); - var checkpoint = - new AccountAuthorityOutboxRepository(fixture.dsl()) - .readCheckpoint(event.outboxStreamKey()) - .orElseThrow(); - assertThat(checkpoint.outboxSequence()).isEqualTo(event.outboxSequence()); - assertThat(checkpoint.sourceEventId()).isEqualTo(event.eventId().toString()); - assertThat(checkpoint.sourceEventDigest()).isEqualTo(event.eventDigest()); - assertThat( - fixture - .jdbc() - .queryForObject( - "SELECT event_digest FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ? AND tenant_billing_sequence = ? AND event_id = ?", - String.class, - fixture.tenantId(), - receipt.tenantBillingSequence(), - receipt.billingEventId())) - .isEqualTo(receipt.billingEventDigest()); - assertThat( - fixture - .jdbc() - .queryForMap( - "SELECT current_generation, tenant_billing_sequence, last_outbox_sequence, " - + "last_event_id, last_event_digest FROM account_tenant_authority_source_records WHERE tenant_uuid = ?", - fixture.tenantId())) - .containsEntry("current_generation", event.tenantAuthorityGeneration()) - .containsEntry("tenant_billing_sequence", receipt.tenantBillingSequence()) - .containsEntry("last_outbox_sequence", checkpoint.outboxSequence()) - .containsEntry("last_event_id", event.eventId().toString()) - .containsEntry("last_event_digest", event.eventDigest()); - }); + .executeWithoutResult(status -> { + var currentGeneration = + new AccountAuthorityGenerationRepository(fixture.dsl()) + .read(AuthorityScope.tenant(fixture.tenantId())); + assertThat(currentGeneration.generation()).isEqualTo(event.tenantAuthorityGeneration()); + assertThat(currentGeneration.sourceVersion()) + .isEqualTo(event.tenantAuthoritySourceVersion()); + var checkpoint = + new AccountAuthorityOutboxRepository(fixture.dsl()) + .readCheckpoint(event.outboxStreamKey()) + .orElseThrow(); + assertThat(checkpoint.outboxSequence()).isEqualTo(event.outboxSequence()); + assertThat(checkpoint.sourceEventId()).isEqualTo(event.eventId().toString()); + assertThat(checkpoint.sourceEventDigest()).isEqualTo(event.eventDigest()); + assertThat( + fixture + .jdbc() + .queryForObject( + "SELECT event_digest FROM account_tenant_entitlement_outbox_events WHERE tenant_uuid = ? AND tenant_billing_sequence = ? AND event_id = ?", + String.class, + fixture.tenantId(), + receipt.tenantBillingSequence(), + receipt.billingEventId())) + .isEqualTo(receipt.billingEventDigest()); + assertThat( + fixture + .jdbc() + .queryForMap( + "SELECT current_generation, tenant_billing_sequence, last_outbox_sequence, " + + "last_event_id, last_event_digest FROM account_tenant_authority_source_records WHERE tenant_uuid = ?", + fixture.tenantId())) + .containsEntry("current_generation", event.tenantAuthorityGeneration()) + .containsEntry("tenant_billing_sequence", receipt.tenantBillingSequence()) + .containsEntry("last_outbox_sequence", checkpoint.outboxSequence()) + .containsEntry("last_event_id", event.eventId().toString()) + .containsEntry("last_event_digest", event.eventDigest()); + }); } @Test diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java index a052837a81..4f10afc4c2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java @@ -151,13 +151,11 @@ void preV40RetainedPasswordResetFailsTypedAndRollsBackWithoutInventingSource() { "expected retained reset token") .intoMap(); var beforeEvents = dsl.fetch("SELECT * FROM account_authority_outbox_events").intoMaps(); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - status -> - service.completePasswordReset( - new net.firedevops.firemud.accountservice.dto - .CompletePasswordResetRequest(tokenValue, "replacement-password")))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(status -> + service.completePasswordReset( + new net.firedevops.firemud.accountservice.dto.CompletePasswordResetRequest( + tokenValue, "replacement-password")))) .isInstanceOf( AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class); assertThat(accounts.findById(accountId).orElseThrow().getPasswordHash()) @@ -223,15 +221,13 @@ void freshAccountGenericSecurityEventsRemainNonCurrentWithExactSourceEvidence() .isEqualTo(baseline.account().accountRepositoryInsertTransactionId()); assertThat(baseline.account().accountSecurityCutoff()).isEmpty(); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - status -> - dsl.execute( - "UPDATE account_authority_generations " - + "SET generation = 2, source_version = 2 " - + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", - account.getAccountUuid()))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(status -> + dsl.execute( + "UPDATE account_authority_generations " + + "SET generation = 2, source_version = 2 " + + "WHERE scope_kind = 'ACCOUNT' AND account_uuid = ?", + account.getAccountUuid()))) .isInstanceOf(RuntimeException.class); assertThat( Objects.requireNonNull( @@ -247,11 +243,9 @@ void freshAccountGenericSecurityEventsRemainNonCurrentWithExactSourceEvidence() account.setEmailVerified(true); transaction.executeWithoutResult(status -> accounts.save(account)); - assertThatThrownBy( - () -> - transaction.execute( - status -> - sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid()))) + assertThatThrownBy(() -> + transaction.execute(status -> + sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid()))) .isInstanceOf( AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class) .hasMessage("Account authority source evidence is unavailable or inconsistent"); @@ -309,20 +303,16 @@ void freshAccountGenericSecurityEventsRemainNonCurrentWithExactSourceEvidence() Account rollbackAttempt = accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow(); rollbackAttempt.setPasswordHash("rollback-only-password-hash"); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - status -> { - accounts.save(rollbackAttempt); - throw new IllegalStateException("force Account source event rollback"); - })) + assertThatThrownBy(() -> + transaction.executeWithoutResult(status -> { + accounts.save(rollbackAttempt); + throw new IllegalStateException("force Account source event rollback"); + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("force Account source event rollback"); - assertThatThrownBy( - () -> - transaction.execute( - status -> - sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid()))) + assertThatThrownBy(() -> + transaction.execute(status -> + sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid()))) .isInstanceOf( AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class) .hasMessage("Account authority source evidence is unavailable or inconsistent"); @@ -441,13 +431,10 @@ void freshAccountGenericSecurityEventsRemainNonCurrentWithExactSourceEvidence() assertThatThrownBy(() -> accounts.delete(account)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("pending-deletion retention workflow"); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - status -> - dsl.execute( - "DELETE FROM accounts WHERE account_uuid = ?", - account.getAccountUuid()))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(status -> + dsl.execute( + "DELETE FROM accounts WHERE account_uuid = ?", account.getAccountUuid()))) .isInstanceOf(DataAccessException.class); assertThat(accounts.findByAccountUuid(account.getAccountUuid())).isPresent(); } @@ -474,11 +461,9 @@ void freshAccountWithNullGlobalRoleKeepsGenericEventOutOfCurrentness() { account.setPasswordHash("changed-null-role-account-password-hash"); transaction.executeWithoutResult(status -> accounts.save(account)); - assertThatThrownBy( - () -> - transaction.execute( - status -> - sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid()))) + assertThatThrownBy(() -> + transaction.execute(status -> + sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid()))) .isInstanceOf( AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class) .hasMessage("Account authority source evidence is unavailable or inconsistent"); @@ -527,10 +512,9 @@ void existingIssuerInitializationReadsExactSourceWithoutWritingThroughPendingOri transaction.executeWithoutResult(status -> sources.initializeIssuerIfAbsent(ISSUER)); var original = Objects.requireNonNull( - transaction.execute( - status -> - sources.appendIssuerAuthorityChange( - ISSUER, "SIGNER_COMPROMISE", "held-issuer-" + UUID.randomUUID()))); + transaction.execute(status -> + sources.appendIssuerAuthorityChange( + ISSUER, "SIGNER_COMPROMISE", "held-issuer-" + UUID.randomUUID()))); var originalEvent = transaction.execute( status -> outbox.findEvent(original.checkpoint().outboxStreamKey(), 1L).orElseThrow()); @@ -586,11 +570,10 @@ void existingIssuerInitializationReadsExactSourceWithoutWritingThroughPendingOri Long.toString(original.checkpoint().sequence()), Objects.requireNonNull(originalEvent).payload()))); var fences = new DraftAuthorizationFenceRepository(dsl); - transaction.executeWithoutResult( - status -> { - fences.reserve(holder); - fences.claimCommitOrder(holder); - }); + transaction.executeWithoutResult(status -> { + fences.reserve(holder); + fences.claimCommitOrder(holder); + }); Map>> retained = new java.util.LinkedHashMap<>(); for (String table : List.of( @@ -612,21 +595,16 @@ void existingIssuerInitializationReadsExactSourceWithoutWritingThroughPendingOri } var observed = transaction.execute(status -> sources.initializeIssuerIfAbsent(ISSUER)); assertThat(observed).isEqualTo(original); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - status -> - sources.appendIssuerAuthorityChange( - ISSUER, - "SIGNER_COMPROMISE", - "blocked-held-issuer-" + UUID.randomUUID()))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(status -> + sources.appendIssuerAuthorityChange( + ISSUER, "SIGNER_COMPROMISE", "blocked-held-issuer-" + UUID.randomUUID()))) .rootCause() .isInstanceOf(org.postgresql.util.PSQLException.class) .hasMessageContaining("Required creator source is held until every original owner settles") - .satisfies( - failure -> - assertThat(((org.postgresql.util.PSQLException) failure).getSQLState()) - .isEqualTo("55P03")); + .satisfies(failure -> + assertThat(((org.postgresql.util.PSQLException) failure).getSQLState()) + .isEqualTo("55P03")); assertThat( Objects.requireNonNull( dsl.fetchOne( @@ -662,30 +640,26 @@ void concurrentFirstIssuerEnrollmentRetainsOneExactSourceBaseline() throws Excep CompletableFuture secondPid = new CompletableFuture<>(); ExecutorService executor = Executors.newFixedThreadPool(2); var first = - executor.submit( - () -> - transaction.execute( - status -> { - firstPid.complete( - Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class)); - var baseline = sources.initializeIssuerIfAbsent(ISSUER); - firstInitialized.countDown(); - await(releaseFirst, "First issuer enrollment was not released"); - return baseline; - })); + executor.submit(() -> + transaction.execute(status -> { + firstPid.complete( + Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + var baseline = sources.initializeIssuerIfAbsent(ISSUER); + firstInitialized.countDown(); + await(releaseFirst, "First issuer enrollment was not released"); + return baseline; + })); var second = - executor.submit( - () -> { - await(firstInitialized, "First issuer enrollment did not initialize"); - return transaction.execute( - status -> { - secondPid.complete( - Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class)); - return sources.initializeIssuerIfAbsent(ISSUER); - }); - }); + executor.submit(() -> { + await(firstInitialized, "First issuer enrollment did not initialize"); + return transaction.execute(status -> { + secondPid.complete( + Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + return sources.initializeIssuerIfAbsent(ISSUER); + }); + }); try { assertThat(firstInitialized.await(30, TimeUnit.SECONDS)).isTrue(); awaitLockWait(dsl, secondPid.get(30, TimeUnit.SECONDS), firstPid.get(30, TimeUnit.SECONDS)); @@ -737,17 +711,15 @@ void retainedOrForgedEmptyStreamsDoNotBecomeFreshSourceBaselines() { "SELECT account_uuid FROM accounts WHERE username = ?", retained.getUsername())) .get("account_uuid", UUID.class); String retainedIssuer = "retained-issuer-" + UUID.randomUUID(); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - status -> { - dsl.execute( - "INSERT INTO account_authority_generations " - + "(scope_kind, issuer_id, generation, source_version) " - + "VALUES ('ISSUER', ?, 1, 1)", - retainedIssuer); - sources.initializeIssuerIfAbsent(retainedIssuer); - })) + assertThatThrownBy(() -> + transaction.executeWithoutResult(status -> { + dsl.execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, issuer_id, generation, source_version) " + + "VALUES ('ISSUER', ?, 1, 1)", + retainedIssuer); + sources.initializeIssuerIfAbsent(retainedIssuer); + })) .isInstanceOf( AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException.class); assertThat( @@ -761,21 +733,19 @@ void retainedOrForgedEmptyStreamsDoNotBecomeFreshSourceBaselines() { transaction.executeWithoutResult(status -> sources.initializeIssuerIfAbsent(ISSUER)); - assertThatThrownBy( - () -> - transaction.execute( - status -> { - dsl.execute( - "INSERT INTO account_authority_generations " - + "(scope_kind, account_uuid, generation, source_version) " - + "VALUES ('ACCOUNT', ?, 1, 1)", - retainedUuid); - dsl.execute( - "INSERT INTO account_authority_issuance_fences " - + "(account_uuid, issuance_fence, source_version) VALUES (?, 1, 1)", - retainedUuid); - return sources.readCurrentIssuerAccountSources(ISSUER, retainedUuid); - })) + assertThatThrownBy(() -> + transaction.execute(status -> { + dsl.execute( + "INSERT INTO account_authority_generations " + + "(scope_kind, account_uuid, generation, source_version) " + + "VALUES ('ACCOUNT', ?, 1, 1)", + retainedUuid); + dsl.execute( + "INSERT INTO account_authority_issuance_fences " + + "(account_uuid, issuance_fence, source_version) VALUES (?, 1, 1)", + retainedUuid); + return sources.readCurrentIssuerAccountSources(ISSUER, retainedUuid); + })) .isInstanceOf(IllegalStateException.class); assertThat( Objects.requireNonNull( @@ -787,21 +757,18 @@ void retainedOrForgedEmptyStreamsDoNotBecomeFreshSourceBaselines() { .isZero(); String forgedKey = "account:auth-authority:v1:issuer/forged-empty-" + UUID.randomUUID(); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - status -> - dsl.execute( - "INSERT INTO account_authority_outbox_streams " - + "(outbox_stream_key, last_sequence) VALUES (?, 0)", - forgedKey))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(status -> + dsl.execute( + "INSERT INTO account_authority_outbox_streams " + + "(outbox_stream_key, last_sequence) VALUES (?, 0)", + forgedKey))) .isInstanceOf(RuntimeException.class) - .satisfies( - failure -> { - Throwable rootCause = failure; - while (rootCause.getCause() != null) rootCause = rootCause.getCause(); - assertThat(rootCause.getMessage()).contains("fresh source-baseline provenance"); - }); + .satisfies(failure -> { + Throwable rootCause = failure; + while (rootCause.getCause() != null) rootCause = rootCause.getCause(); + assertThat(rootCause.getMessage()).contains("fresh source-baseline provenance"); + }); } @Test @@ -827,39 +794,33 @@ void concurrentAccountMutationAndAuthorityReadUseAccountRowBeforeGenerationLocks CompletableFuture snapshotBackendPid = new CompletableFuture<>(); ExecutorService executor = Executors.newFixedThreadPool(2); Future writer = - executor.submit( - () -> - transaction.executeWithoutResult( - status -> { - writerBackendPid.complete( - Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class)); - participantsReady.countDown(); - await(startLockPhase, "Account lock-order phase was not started"); - dsl.fetchOne( - "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", - account.getAccountUuid()); - accountRowLocked.countDown(); - await(releaseWriter, "Account writer was not released"); - Account updated = - accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow(); - updated.setPasswordHash("lock-order-updated-hash"); - accounts.save(updated); - })); + executor.submit(() -> + transaction.executeWithoutResult(status -> { + writerBackendPid.complete( + Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + participantsReady.countDown(); + await(startLockPhase, "Account lock-order phase was not started"); + dsl.fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", + account.getAccountUuid()); + accountRowLocked.countDown(); + await(releaseWriter, "Account writer was not released"); + Account updated = accounts.findByAccountUuid(account.getAccountUuid()).orElseThrow(); + updated.setPasswordHash("lock-order-updated-hash"); + accounts.save(updated); + })); Future snapshot = - executor.submit( - () -> - transaction.execute( - status -> { - snapshotBackendPid.complete( - Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class)); - participantsReady.countDown(); - await(startLockPhase, "Account lock-order phase was not started"); - await(accountRowLocked, "Account writer did not acquire its row lock"); - return sources.readCurrentIssuerAccountSources( - ISSUER, account.getAccountUuid()); - })); + executor.submit(() -> + transaction.execute(status -> { + snapshotBackendPid.complete( + Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + participantsReady.countDown(); + await(startLockPhase, "Account lock-order phase was not started"); + await(accountRowLocked, "Account writer did not acquire its row lock"); + return sources.readCurrentIssuerAccountSources(ISSUER, account.getAccountUuid()); + })); try { assertThat(participantsReady.await(30, TimeUnit.SECONDS)).isTrue(); @@ -872,15 +833,14 @@ void concurrentAccountMutationAndAuthorityReadUseAccountRowBeforeGenerationLocks writer.get(45, TimeUnit.SECONDS); assertThatThrownBy(() -> snapshot.get(45, TimeUnit.SECONDS)) .isInstanceOf(java.util.concurrent.ExecutionException.class) - .satisfies( - failure -> { - assertThat(failure.getCause()) - .isInstanceOf( - AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException - .class); - assertThat(failure.getCause()) - .hasMessage("Account authority source evidence is unavailable or inconsistent"); - }); + .satisfies(failure -> { + assertThat(failure.getCause()) + .isInstanceOf( + AccountAuthoritySourceEvidenceRepository.SourceEvidenceUnavailableException + .class); + assertThat(failure.getCause()) + .hasMessage("Account authority source evidence is unavailable or inconsistent"); + }); var committedState = transaction.execute( status -> generations.read(AuthorityScope.account(account.getAccountUuid()))); @@ -945,55 +905,43 @@ void concurrentCompositeReadersShareIssuerRowWhileIssuerAdvanceWaitsForTheirSnap CompletableFuture writerPid = new CompletableFuture<>(); ExecutorService executor = Executors.newFixedThreadPool(3); Future firstReader = - executor.submit( - () -> - transaction.execute( - status -> { - firstReaderPid.complete( - Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class)); - var snapshot = - generations.readCompositeSnapshot( - ISSUER, - first.getAccountUuid(), - java.util.List.of(), - java.util.List.of()); - readersReady.countDown(); - await(releaseReaders, "Shared issuer readers were not released"); - return snapshot; - })); + executor.submit(() -> + transaction.execute(status -> { + firstReaderPid.complete( + Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + var snapshot = + generations.readCompositeSnapshot( + ISSUER, first.getAccountUuid(), java.util.List.of(), java.util.List.of()); + readersReady.countDown(); + await(releaseReaders, "Shared issuer readers were not released"); + return snapshot; + })); Future secondReader = - executor.submit( - () -> - transaction.execute( - status -> { - secondReaderPid.complete( - Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class)); - var snapshot = - generations.readCompositeSnapshot( - ISSUER, - second.getAccountUuid(), - java.util.List.of(), - java.util.List.of()); - readersReady.countDown(); - await(releaseReaders, "Shared issuer readers were not released"); - return snapshot; - })); + executor.submit(() -> + transaction.execute(status -> { + secondReaderPid.complete( + Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + var snapshot = + generations.readCompositeSnapshot( + ISSUER, second.getAccountUuid(), java.util.List.of(), java.util.List.of()); + readersReady.countDown(); + await(releaseReaders, "Shared issuer readers were not released"); + return snapshot; + })); Future issuerWriter = - executor.submit( - () -> { - await(readersReady, "Both shared issuer readers did not acquire their snapshot"); - transaction.executeWithoutResult( - status -> { - writerPid.complete( - Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class)); - writerStarted.countDown(); - sources.appendIssuerAuthorityChange( - ISSUER, "SIGNER_COMPROMISE", "shared-reader-" + UUID.randomUUID()); - }); - }); + executor.submit(() -> { + await(readersReady, "Both shared issuer readers did not acquire their snapshot"); + transaction.executeWithoutResult(status -> { + writerPid.complete( + Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + writerStarted.countDown(); + sources.appendIssuerAuthorityChange( + ISSUER, "SIGNER_COMPROMISE", "shared-reader-" + UUID.randomUUID()); + }); + }); try { assertThat(readersReady.await(30, TimeUnit.SECONDS)).isTrue(); @@ -1047,40 +995,34 @@ void concurrentIssuerWritersSerializeBeforeReadingAndAppendingSourceState() thro String secondRequestId = "issuer-writer-two-" + UUID.randomUUID(); ExecutorService executor = Executors.newFixedThreadPool(2); Future firstWriter = - executor.submit( - () -> - transaction.executeWithoutResult( - status -> { - firstWriterPid.complete( - Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class)); - var issuerRow = - dsl.fetchOne( - "SELECT generation FROM account_authority_generations " - + "WHERE scope_kind = 'ISSUER' AND issuer_id = ? FOR UPDATE", - ISSUER); - assertThat(issuerRow).isNotNull(); - firstWriterLocked.countDown(); - await(secondWriterStarted, "Second issuer writer did not start"); - sources.appendIssuerAuthorityChange( - ISSUER, "SIGNER_COMPROMISE", firstRequestId); - firstWriterAppended.countDown(); - await(allowFirstWriterCommit, "First issuer writer was not released"); - })); + executor.submit(() -> + transaction.executeWithoutResult(status -> { + firstWriterPid.complete( + Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + var issuerRow = + dsl.fetchOne( + "SELECT generation FROM account_authority_generations " + + "WHERE scope_kind = 'ISSUER' AND issuer_id = ? FOR UPDATE", + ISSUER); + assertThat(issuerRow).isNotNull(); + firstWriterLocked.countDown(); + await(secondWriterStarted, "Second issuer writer did not start"); + sources.appendIssuerAuthorityChange(ISSUER, "SIGNER_COMPROMISE", firstRequestId); + firstWriterAppended.countDown(); + await(allowFirstWriterCommit, "First issuer writer was not released"); + })); Future secondWriter = - executor.submit( - () -> { - await(firstWriterLocked, "First issuer writer did not acquire issuer row"); - transaction.executeWithoutResult( - status -> { - secondWriterPid.complete( - Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class)); - secondWriterStarted.countDown(); - sources.appendIssuerAuthorityChange( - ISSUER, "SIGNER_COMPROMISE", secondRequestId); - }); - }); + executor.submit(() -> { + await(firstWriterLocked, "First issuer writer did not acquire issuer row"); + transaction.executeWithoutResult(status -> { + secondWriterPid.complete( + Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + secondWriterStarted.countDown(); + sources.appendIssuerAuthorityChange(ISSUER, "SIGNER_COMPROMISE", secondRequestId); + }); + }); try { assertThat(firstWriterLocked.await(30, TimeUnit.SECONDS)).isTrue(); @@ -1104,23 +1046,21 @@ void concurrentIssuerWritersSerializeBeforeReadingAndAppendingSourceState() thro (IssuerEvent) AccountAuthoritySourceEventV1Codec.verify( new String( - transaction.execute( - status -> - outbox - .findEvent(readback.issuer().checkpoint().outboxStreamKey(), 1L) - .orElseThrow() - .payload()), + transaction.execute(status -> + outbox + .findEvent(readback.issuer().checkpoint().outboxStreamKey(), 1L) + .orElseThrow() + .payload()), StandardCharsets.UTF_8)); var secondEvent = (IssuerEvent) AccountAuthoritySourceEventV1Codec.verify( new String( - transaction.execute( - status -> - outbox - .findEvent(readback.issuer().checkpoint().outboxStreamKey(), 2L) - .orElseThrow() - .payload()), + transaction.execute(status -> + outbox + .findEvent(readback.issuer().checkpoint().outboxStreamKey(), 2L) + .orElseThrow() + .payload()), StandardCharsets.UTF_8)); assertThat(firstEvent.requestId()).isEqualTo(firstRequestId); assertThat(firstEvent.issuerAuthGeneration()).isEqualTo("2"); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerDispatchPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerDispatchPostgresIntegrationTest.java index f0784a878d..2d5e52d44d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerDispatchPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerDispatchPostgresIntegrationTest.java @@ -81,17 +81,15 @@ void competingClaimsHaveOneInitialCallerAndExactReplayNeverReissuesPermission() var start = new CountDownLatch(1); try (var executor = Executors.newFixedThreadPool(2)) { var first = - executor.submit( - () -> { - start.await(); - return claim(c, UUID.randomUUID()); - }); + executor.submit(() -> { + start.await(); + return claim(c, UUID.randomUUID()); + }); var second = - executor.submit( - () -> { - start.await(); - return claim(c, UUID.randomUUID()); - }); + executor.submit(() -> { + start.await(); + return claim(c, UUID.randomUUID()); + }); start.countDown(); List results = List.of(first.get(20, TimeUnit.SECONDS), second.get(20, TimeUnit.SECONDS)); @@ -140,29 +138,27 @@ void claimIdentityBindingTimeAndRetentionCannotBeRewrittenOrErased() { @Test void mismatchedDirectInsertAndConfirmedOwnerCannotAcquireFirstDispatch() { Context c = context(true); - assertThatThrownBy( - () -> - c.sql() - .execute( - "INSERT INTO account_billing_customer_dispatch_claim " - + "(account_uuid, customer_provisioning_request_id, provider_idempotency_id, claim_id) VALUES (?, ?, ?, ?)", - c.intent().accountUuid(), - c.intent().customerProvisioningRequestId(), - UUID.randomUUID(), - UUID.randomUUID())) + assertThatThrownBy(() -> + c.sql() + .execute( + "INSERT INTO account_billing_customer_dispatch_claim " + + "(account_uuid, customer_provisioning_request_id, provider_idempotency_id, claim_id) VALUES (?, ?, ?, ?)", + c.intent().accountUuid(), + c.intent().customerProvisioningRequestId(), + UUID.randomUUID(), + UUID.randomUUID())) .isInstanceOf(org.jooq.exception.DataAccessException.class); c.tx() - .executeWithoutResult( - s -> - c.repository() - .recordObservation( - c.intent().accountUuid(), - c.intent().customerProvisioningRequestId(), - 1, - UUID.randomUUID(), - AccountBillingCustomerRecord.Observation.CONFIRMED, - "cus_preexisting", - "sha256:" + "a".repeat(64))); + .executeWithoutResult(s -> + c.repository() + .recordObservation( + c.intent().accountUuid(), + c.intent().customerProvisioningRequestId(), + 1, + UUID.randomUUID(), + AccountBillingCustomerRecord.Observation.CONFIRMED, + "cus_preexisting", + "sha256:" + "a".repeat(64))); assertThatThrownBy(() -> claim(c, UUID.randomUUID())) .isInstanceOf(AccountBillingCustomerRepository.ConflictException.class); assertThat(c.sql().fetchCount(DSL.table("account_billing_customer_dispatch_claim"))).isZero(); @@ -172,15 +168,14 @@ void mismatchedDirectInsertAndConfirmedOwnerCannotAcquireFirstDispatch() { void rolledBackClaimDoesNotSurviveAndOnlyFreshCommittedInsertGetsPermission() { Context c = context(true); c.tx() - .executeWithoutResult( - s -> { - assertThat( - c.repository() - .claimFirstProviderDispatch(c.intent(), UUID.randomUUID()) - .inserted()) - .isTrue(); - s.setRollbackOnly(); - }); + .executeWithoutResult(s -> { + assertThat( + c.repository() + .claimFirstProviderDispatch(c.intent(), UUID.randomUUID()) + .inserted()) + .isTrue(); + s.setRollbackOnly(); + }); assertThat(c.sql().fetchCount(DSL.table("account_billing_customer_dispatch_claim"))).isZero(); assertThat(claim(c, UUID.randomUUID()).inserted()).isTrue(); assertThat(claim(c, UUID.randomUUID()).inserted()).isFalse(); @@ -283,16 +278,14 @@ void concurrentMatchingSdkResultsKeepOneConfirmationAndExactHistoricalRetry() th var service = customerService(c, transactions, transport); try (var executor = Executors.newFixedThreadPool(2)) { var first = - executor.submit( - () -> - service.provision( - c.intent().accountUuid(), c.intent().customerProvisioningRequestId())); + executor.submit(() -> + service.provision( + c.intent().accountUuid(), c.intent().customerProvisioningRequestId())); assertThat(transport.firstRetrieve.await(10, TimeUnit.SECONDS)).isTrue(); var second = - executor.submit( - () -> - service.provision( - c.intent().accountUuid(), c.intent().customerProvisioningRequestId())); + executor.submit(() -> + service.provision( + c.intent().accountUuid(), c.intent().customerProvisioningRequestId())); var results = List.of(first.get(20, TimeUnit.SECONDS), second.get(20, TimeUnit.SECONDS)); assertThat( results.stream() @@ -350,13 +343,12 @@ private static AccountBillingCustomerProvisioningService customerService( private static void assertCommittedReceipt(Context c, AccountBillingCustomerRecord expected) { c.tx() - .executeWithoutResult( - status -> { - assertThat(c.repository().findByAccountForUpdate(expected.accountUuid())) - .contains(expected); - assertThat(c.repository().findObservationByRequestId(expected.changeRequestId())) - .contains(expected); - }); + .executeWithoutResult(status -> { + assertThat(c.repository().findByAccountForUpdate(expected.accountUuid())) + .contains(expected); + assertThat(c.repository().findObservationByRequestId(expected.changeRequestId())) + .contains(expected); + }); var currentRow = Objects.requireNonNull( c.sql() @@ -547,11 +539,8 @@ private static Context context(boolean forward) { .get(0, UUID.class); var intent = Objects.requireNonNull( - tx.execute( - s -> - repository - .retainIntent(account, UUID.randomUUID(), UUID.randomUUID()) - .customer())); + tx.execute(s -> + repository.retainIntent(account, UUID.randomUUID(), UUID.randomUUID()).customer())); Context result = new Context(source, schema, sql, repository, tx, intent); if (forward) { migrate(result, "1027.1"); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingPrerequisitesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingPrerequisitesPostgresIntegrationTest.java index d4e9ca124a..c2c1187860 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingPrerequisitesPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountBillingPrerequisitesPostgresIntegrationTest.java @@ -86,16 +86,14 @@ void concurrentCandidatesShareOneDurableCustomerIntentAndExactRetryUsesItsRetain race( () -> c.tx() - .execute( - s -> - c.customers() - .retainIntent(c.account(), UUID.randomUUID(), UUID.randomUUID())), + .execute(s -> + c.customers() + .retainIntent(c.account(), UUID.randomUUID(), UUID.randomUUID())), () -> c.tx() - .execute( - s -> - c.customers() - .retainIntent(c.account(), UUID.randomUUID(), UUID.randomUUID()))); + .execute(s -> + c.customers() + .retainIntent(c.account(), UUID.randomUUID(), UUID.randomUUID()))); assertThat(results) .extracting(AccountBillingCustomerRepository.IntentResult::disposition) .containsExactlyInAnyOrder(IntentDisposition.CREATED, IntentDisposition.REUSED); @@ -107,39 +105,34 @@ void concurrentCandidatesShareOneDurableCustomerIntentAndExactRetryUsesItsRetain .isNotEqualTo(retained.providerIdempotencyId()); var retry = c.tx() - .execute( - s -> - c.customers() - .retainIntent( - c.account(), - retained.customerProvisioningRequestId(), - retained.providerIdempotencyId())); + .execute(s -> + c.customers() + .retainIntent( + c.account(), + retained.customerProvisioningRequestId(), + retained.providerIdempotencyId())); assertThat(Objects.requireNonNull(retry).disposition()).isEqualTo(IntentDisposition.REPLAYED); assertThat(retry.customer()).isEqualTo(retained); assertThat(count(c, "billing_customer")).isOne(); assertThat(c.customers().readHistory(c.account())).containsExactly(retained); - assertThatThrownBy( - () -> - c.tx() - .execute( - s -> - c.customers() - .retainIntent( - c.otherAccount(), - retained.customerProvisioningRequestId(), - retained.providerIdempotencyId()))) + assertThatThrownBy(() -> + c.tx() + .execute(s -> + c.customers() + .retainIntent( + c.otherAccount(), + retained.customerProvisioningRequestId(), + retained.providerIdempotencyId()))) .isInstanceOf(AccountBillingCustomerRepository.ConflictException.class); - assertThatThrownBy( - () -> - c.tx() - .execute( - s -> - c.customers() - .retainIntent( - c.account(), - retained.customerProvisioningRequestId(), - UUID.randomUUID()))) + assertThatThrownBy(() -> + c.tx() + .execute(s -> + c.customers() + .retainIntent( + c.account(), + retained.customerProvisioningRequestId(), + UUID.randomUUID()))) .isInstanceOf(AccountBillingCustomerRepository.ConflictException.class); } @@ -170,23 +163,18 @@ void ambiguousAndAbsentEvidenceStayNonterminalAndExactObservationRetriesNeverReb assertThat(c.customers().findByAccount(c.account())).contains(confirmed); assertThat(c.customers().readHistory(c.account())) .containsExactly(intent, ambiguous, absent, confirmed); - assertThatThrownBy( - () -> - observe(c, intent, 1, ambiguousRequest, Observation.PROVIDER_ABSENT, null, DIGEST)) + assertThatThrownBy(() -> + observe(c, intent, 1, ambiguousRequest, Observation.PROVIDER_ABSENT, null, DIGEST)) .isInstanceOf(AccountBillingCustomerRepository.ConflictException.class); assertThatThrownBy( () -> observe(c, intent, 2, UUID.randomUUID(), Observation.AMBIGUOUS, null, DIGEST)) .isInstanceOf(AccountBillingCustomerRepository.StaleVersionException.class); - assertThatThrownBy( - () -> - observe( - c, intent, 4, UUID.randomUUID(), Observation.CONFIRMED, "cus_changed", DIGEST)) + assertThatThrownBy(() -> + observe(c, intent, 4, UUID.randomUUID(), Observation.CONFIRMED, "cus_changed", DIGEST)) .isInstanceOf(AccountBillingCustomerRepository.ConflictException.class); var other = intent(c, c.otherAccount()); - assertThatThrownBy( - () -> - observe( - c, other, 1, UUID.randomUUID(), Observation.CONFIRMED, "cus_primary", DIGEST)) + assertThatThrownBy(() -> + observe(c, other, 1, UUID.randomUUID(), Observation.CONFIRMED, "cus_primary", DIGEST)) .isInstanceOf(AccountBillingCustomerRepository.ConflictException.class); assertThat(c.customers().findByAccount(c.otherAccount())).contains(other); assertThat(c.customers().readHistory(c.otherAccount())).containsExactly(other); @@ -202,14 +190,11 @@ void attachmentRequiresExactConfirmedAccountCustomerAndImmutableProviderBinding( var confirmed = observe(c, pending, 1, UUID.randomUUID(), Observation.CONFIRMED, "cus_primary", DIGEST); var other = confirm(c, c.otherAccount(), "cus_other"); - assertThatThrownBy( - () -> - c.tx() - .execute( - s -> - c.instruments() - .retainAttachment( - attachment(confirmed, "cus_other", "pm_wrongCustomer")))) + assertThatThrownBy(() -> + c.tx() + .execute(s -> + c.instruments() + .retainAttachment(attachment(confirmed, "cus_other", "pm_wrongCustomer")))) .isInstanceOf(AccountPaymentInstrumentRepository.ConflictException.class); Attachment wrongOperation = new Attachment( @@ -236,13 +221,10 @@ void attachmentRequiresExactConfirmedAccountCustomerAndImmutableProviderBinding( .isEqualTo(instrument); assertThat(c.instruments().findByOwner(c.otherAccount(), instrument.instrumentUuid())) .isEmpty(); - assertThatThrownBy( - () -> - c.tx() - .execute( - s -> - c.instruments() - .retainAttachment(attachment(other, "cus_other", "pm_primary")))) + assertThatThrownBy(() -> + c.tx() + .execute(s -> + c.instruments().retainAttachment(attachment(other, "cus_other", "pm_primary")))) .isInstanceOf(AccountPaymentInstrumentRepository.ConflictException.class); Attachment changedInput = new Attachment( @@ -311,50 +293,46 @@ void concurrentInstrumentCasHasOneWinnerAndRetainsReplayReceiptAfterLaterObserva void rollbackRemovesOwnerChangesAndTheirAutomaticAuditRows() { Context c = context(); c.tx() - .executeWithoutResult( - s -> { - c.customers().retainIntent(c.account(), UUID.randomUUID(), UUID.randomUUID()); - s.setRollbackOnly(); - }); + .executeWithoutResult(s -> { + c.customers().retainIntent(c.account(), UUID.randomUUID(), UUID.randomUUID()); + s.setRollbackOnly(); + }); assertThat(c.customers().findByAccount(c.account())).isEmpty(); assertThat(c.customers().readHistory(c.account())).isEmpty(); var intent = intent(c, c.account()); c.tx() - .executeWithoutResult( - s -> { - c.customers() - .recordObservation( - c.account(), - intent.customerProvisioningRequestId(), - 1, - UUID.randomUUID(), - Observation.CONFIRMED, - "cus_rolledBack", - DIGEST); - s.setRollbackOnly(); - }); + .executeWithoutResult(s -> { + c.customers() + .recordObservation( + c.account(), + intent.customerProvisioningRequestId(), + 1, + UUID.randomUUID(), + Observation.CONFIRMED, + "cus_rolledBack", + DIGEST); + s.setRollbackOnly(); + }); assertThat(c.customers().findByAccount(c.account())).contains(intent); assertThat(c.customers().readHistory(c.account())).containsExactly(intent); var confirmed = observe(c, intent, 1, UUID.randomUUID(), Observation.CONFIRMED, "cus_primary", DIGEST); var request = attachment(confirmed, "cus_primary", "pm_primary"); c.tx() - .executeWithoutResult( - s -> { - c.instruments().retainAttachment(request); - s.setRollbackOnly(); - }); + .executeWithoutResult(s -> { + c.instruments().retainAttachment(request); + s.setRollbackOnly(); + }); assertThat(count(c, "payment_instrument")).isZero(); assertThat(count(c, "account_payment_instrument_observations")).isZero(); var instrument = Objects.requireNonNull(c.tx().execute(s -> c.instruments().retainAttachment(request))); c.tx() - .executeWithoutResult( - s -> { - c.instruments() - .recordAvailability(availability(instrument, 1, State.UNAVAILABLE, OTHER_DIGEST)); - s.setRollbackOnly(); - }); + .executeWithoutResult(s -> { + c.instruments() + .recordAvailability(availability(instrument, 1, State.UNAVAILABLE, OTHER_DIGEST)); + s.setRollbackOnly(); + }); assertThat(c.instruments().findByOwner(c.account(), instrument.instrumentUuid())) .contains(instrument); assertThat(c.instruments().readHistory(c.account(), instrument.instrumentUuid())) @@ -541,17 +519,16 @@ private static AccountBillingCustomerRecord observe( String digest) { return Objects.requireNonNull( c.tx() - .execute( - s -> - c.customers() - .recordObservation( - intent.accountUuid(), - intent.customerProvisioningRequestId(), - version, - request, - observation, - customer, - digest))); + .execute(s -> + c.customers() + .recordObservation( + intent.accountUuid(), + intent.customerProvisioningRequestId(), + version, + request, + observation, + customer, + digest))); } private static List race(Supplier left, Supplier right) throws Exception { @@ -581,16 +558,15 @@ private static T afterBarrier(Supplier action, CountDownLatch ready, Coun private static void rejectSql(String sqlState, ThrowingCallable action) { assertThatThrownBy(action) - .satisfies( - failure -> { - for (Throwable cause = failure; cause != null; cause = cause.getCause()) { - if (cause instanceof SQLException sql) { - assertThat(sql.getSQLState()).isEqualTo(sqlState); - return; - } - } - throw new AssertionError("Expected PostgreSQL storage refusal", failure); - }); + .satisfies(failure -> { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sql) { + assertThat(sql.getSQLState()).isEqualTo(sqlState); + return; + } + } + throw new AssertionError("Expected PostgreSQL storage refusal", failure); + }); } private static long count(Context c, String table) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java index 9ca9d6efb5..7ec610ae97 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalJoinScopePersistenceIntegrationTest.java @@ -113,18 +113,17 @@ void migrationRetainsV1AndStoresExactV2ScopeAndPendingIntentWithoutMembershipOrE new AccountJoinOperationRepository(transactionDsl, scopes); VerifiedJoinScope v1Scope = retainedV1Scope(privateAccountId); - transaction.executeWithoutResult( - status -> { - scopes.insert(v1Scope); - assertThat( - operations.insertIntent( - "retained-v1-request", - v1Scope, - "legacy-caller-binding", - AccountJoinDigest.intent( - "retained-v1-request", v1Scope, "legacy-caller-binding"))) - .isTrue(); - }); + transaction.executeWithoutResult(status -> { + scopes.insert(v1Scope); + assertThat( + operations.insertIntent( + "retained-v1-request", + v1Scope, + "legacy-caller-binding", + AccountJoinDigest.intent( + "retained-v1-request", v1Scope, "legacy-caller-binding"))) + .isTrue(); + }); Optional retainedV1Operation = transaction.execute(status -> operations.find("retained-v1-request")); assertThat(retainedV1Operation).isPresent(); @@ -140,11 +139,10 @@ void migrationRetainsV1AndStoresExactV2ScopeAndPendingIntentWithoutMembershipOrE status -> scopes.insertCanonical(privateAccountId, scope, tenantProvenance)); CanonicalConnectScopeEvidence scopeEvidence = - transaction.execute( - status -> - scopes - .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(CONNECT_SCOPE_ID)) - .orElseThrow()); + transaction.execute(status -> + scopes + .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(CONNECT_SCOPE_ID)) + .orElseThrow()); Optional scopeReadback = transaction.execute(status -> scopes.findCanonical(CONNECT_SCOPE_ID)); assertThat(scopeReadback).contains(scope); @@ -160,14 +158,11 @@ void migrationRetainsV1AndStoresExactV2ScopeAndPendingIntentWithoutMembershipOrE String requestId = "canonical-join-request-1"; String callerBinding = "authenticated-bootstrap-jti"; CanonicalJoinOperationEvidence pending = - transaction.execute( - status -> { - assertThat(operations.insertCanonicalIntent(requestId, scope, callerBinding)) - .isTrue(); - assertThat(operations.insertCanonicalIntent(requestId, scope, callerBinding)) - .isFalse(); - return operations.findCanonicalEvidenceByRequestId(requestId).orElseThrow(); - }); + transaction.execute(status -> { + assertThat(operations.insertCanonicalIntent(requestId, scope, callerBinding)).isTrue(); + assertThat(operations.insertCanonicalIntent(requestId, scope, callerBinding)).isFalse(); + return operations.findCanonicalEvidenceByRequestId(requestId).orElseThrow(); + }); assertThat(pending.status()).isEqualTo("PENDING"); assertThat(pending.entitlementAuthorityAvailability()).isEqualTo("NOT_EVALUATED"); assertThat(pending.requestDigest()).isNull(); @@ -178,9 +173,8 @@ void migrationRetainsV1AndStoresExactV2ScopeAndPendingIntentWithoutMembershipOrE assertThat(numericOperationReadback).isEmpty(); CanonicalJoinOperationEvidence policyBound = - transaction.execute( - status -> - operations.bindCanonicalPolicyEvidence(requestId, scope, callerBinding, true, 23L)); + transaction.execute(status -> + operations.bindCanonicalPolicyEvidence(requestId, scope, callerBinding, true, 23L)); assertThat(policyBound.entitlementAuthorityAvailability()).isEqualTo("AVAILABLE"); assertThat(policyBound.requestDigestVersion()).isEqualTo(2); assertThat(policyBound.requestDigest()) @@ -192,14 +186,12 @@ void migrationRetainsV1AndStoresExactV2ScopeAndPendingIntentWithoutMembershipOrE true, 23L)); CanonicalJoinOperationEvidence policyReplay = - transaction.execute( - status -> - operations.bindCanonicalPolicyEvidence(requestId, scope, callerBinding, true, 23L)); + transaction.execute(status -> + operations.bindCanonicalPolicyEvidence(requestId, scope, callerBinding, true, 23L)); assertThat(policyReplay).isEqualTo(policyBound); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - status -> operations.insertCanonicalIntent(requestId, scope, "changed-caller"))) + assertThatThrownBy(() -> + transaction.executeWithoutResult( + status -> operations.insertCanonicalIntent(requestId, scope, "changed-caller"))) .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); Record otherAccount = @@ -213,33 +205,25 @@ void migrationRetainsV1AndStoresExactV2ScopeAndPendingIntentWithoutMembershipOrE UUID otherAccountUuid = Objects.requireNonNull(otherAccount).get("account_uuid", UUID.class); CanonicalJoinScopeV2 otherAccountScope = canonicalScope(OTHER_ACCOUNT_SCOPE_ID, otherAccountUuid, tenantSource.canonicalTenantId()); - transaction.executeWithoutResult( - status -> - scopes.insertCanonical(otherPrivateAccountId, otherAccountScope, tenantProvenance)); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - status -> - operations.insertCanonicalIntent( - requestId, otherAccountScope, callerBinding))) + transaction.executeWithoutResult(status -> + scopes.insertCanonical(otherPrivateAccountId, otherAccountScope, tenantProvenance)); + assertThatThrownBy(() -> + transaction.executeWithoutResult(status -> + operations.insertCanonicalIntent(requestId, otherAccountScope, callerBinding))) .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class) .hasMessage("JOIN request ID conflicts with canonical caller or scope intent"); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - status -> - operations.insertCanonicalIntent( - "retained-v1-request", scope, callerBinding))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(status -> + operations.insertCanonicalIntent("retained-v1-request", scope, callerBinding))) .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); CanonicalJoinOperationEvidence unavailable = - transaction.execute( - status -> { - operations.insertCanonicalIntent("canonical-join-unavailable", scope, callerBinding); - return operations.recordCanonicalPolicyUnavailable( - "canonical-join-unavailable", scope, callerBinding, "ENTITLEMENT_UNAVAILABLE"); - }); + transaction.execute(status -> { + operations.insertCanonicalIntent("canonical-join-unavailable", scope, callerBinding); + return operations.recordCanonicalPolicyUnavailable( + "canonical-join-unavailable", scope, callerBinding, "ENTITLEMENT_UNAVAILABLE"); + }); assertThat(unavailable.status()).isEqualTo("PENDING"); assertThat(unavailable.entitlementAuthorityAvailability()).isEqualTo("UNAVAILABLE"); assertThat(unavailable.entitlementVersion()).isNull(); @@ -326,11 +310,10 @@ void capacityUpgradeFromParent1036Through1040PreservesCanonicalRowsAndHistory() tenantSource.evidenceDigest()); String requestId = "canonical-migration-upgrade-pending"; String callerBinding = "canonical-migration-upgrade-caller"; - transaction.executeWithoutResult( - status -> { - scopes.insertCanonical(privateAccountId, scope, tenantProvenance); - assertThat(operations.insertCanonicalIntent(requestId, scope, callerBinding)).isTrue(); - }); + transaction.executeWithoutResult(status -> { + scopes.insertCanonical(privateAccountId, scope, tenantProvenance); + assertThat(operations.insertCanonicalIntent(requestId, scope, callerBinding)).isTrue(); + }); CanonicalJoinOperationEvidence pending = transaction.execute( status -> operations.findCanonicalEvidenceByRequestId(requestId).orElseThrow()); @@ -380,11 +363,10 @@ void capacityUpgradeFromParent1036Through1040PreservesCanonicalRowsAndHistory() "V1039__hosting_unclaimed_wallet_settlement.sql", "V1040__account_tenant_capacity_owner.sql"); assertThat(addedHistory) - .allSatisfy( - row -> { - assertThat(row.get("checksum")).isNotNull(); - assertThat(row.get("success")).isEqualTo(true); - }); + .allSatisfy(row -> { + assertThat(row.get("checksum")).isNotNull(); + assertThat(row.get("success")).isEqualTo(true); + }); assertThat( retainedPhysicalRow( setupDsl, @@ -438,10 +420,9 @@ void capacityUpgradeFromParent1036Through1040PreservesCanonicalRowsAndHistory() .contains("ALREADY_ACTIVE", "account_tenant_membership", "last_attempt_failure_code"); CanonicalJoinOperationEvidence diagnosed = - transaction.execute( - status -> - operations.recordCanonicalAttemptFailure( - requestId, scope, callerBinding, "NOT_EVALUATED", "AUTH_UNAVAILABLE")); + transaction.execute(status -> + operations.recordCanonicalAttemptFailure( + requestId, scope, callerBinding, "NOT_EVALUATED", "AUTH_UNAVAILABLE")); assertThat(diagnosed.status()).isEqualTo("PENDING"); assertThat(diagnosed.lastAttemptAuthorityAvailability()).isEqualTo("NOT_EVALUATED"); assertThat(diagnosed.lastAttemptFailureCode()).isEqualTo("AUTH_UNAVAILABLE"); @@ -451,12 +432,11 @@ void capacityUpgradeFromParent1036Through1040PreservesCanonicalRowsAndHistory() "SELECT to_jsonb(operation_row)::text, operation_row.xmin::text " + "FROM account_join_operations operation_row WHERE request_id = ?", requestId); - assertThatThrownBy( - () -> - setupDsl.execute( - "UPDATE account_join_operations SET verified_caller_binding = ? WHERE request_id = ?", - "changed-migration-caller", - requestId)) + assertThatThrownBy(() -> + setupDsl.execute( + "UPDATE account_join_operations SET verified_caller_binding = ? WHERE request_id = ?", + "changed-migration-caller", + requestId)) .isInstanceOfSatisfying( org.jooq.exception.DataAccessException.class, failure -> assertThat(failure.sqlState()).isEqualTo("23514")); @@ -558,25 +538,22 @@ void definitiveFailureRetainsOriginalIntentAndOptionalPolicyAndExactlyReplaysWit JournalFixture f = journalFixture(); if (bound) f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); + .execute(status -> + f.operations() + .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); else f.transaction() - .execute( - status -> - f.operations() - .recordCanonicalPolicyUnavailable( - f.requestId(), f.scope(), f.caller(), "ENTITLEMENT_UNAVAILABLE")); + .execute(status -> + f.operations() + .recordCanonicalPolicyUnavailable( + f.requestId(), f.scope(), f.caller(), "ENTITLEMENT_UNAVAILABLE")); var original = f.read(); String outcome = bound ? "IDEMPOTENCY_CONFLICT" : "CONNECT_SCOPE_INVALID"; var failed = f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure(f.requestId(), f.scope(), f.caller(), outcome)); + .execute(status -> + f.operations() + .finishCanonicalFailure(f.requestId(), f.scope(), f.caller(), outcome)); assertThat(failed.status()).isEqualTo("FAILED"); assertThat(failed.outcome()).isEqualTo(outcome); assertThat(failed.intentDigest()).isEqualTo(original.intentDigest()); @@ -593,69 +570,51 @@ void definitiveFailureRetainsOriginalIntentAndOptionalPolicyAndExactlyReplaysWit String retained = f.bytes(); var replay = f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure(f.requestId(), f.scope(), f.caller(), outcome)); + .execute(status -> + f.operations() + .finishCanonicalFailure(f.requestId(), f.scope(), f.caller(), outcome)); assertThat(replay).isEqualTo(failed); assertThat(f.bytes()).isEqualTo(retained); f.transaction() - .executeWithoutResult( - status -> - assertThat( - f.operations().insertCanonicalIntent(f.requestId(), f.scope(), f.caller())) - .isFalse()); + .executeWithoutResult(status -> + assertThat(f.operations().insertCanonicalIntent(f.requestId(), f.scope(), f.caller())) + .isFalse()); if (bound) { var policyReplay = f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence( - f.requestId(), f.scope(), f.caller(), true, 23)); + .execute(status -> + f.operations() + .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); assertThat(policyReplay).isEqualTo(failed); } else { - assertThatThrownBy( - () -> - f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence( - f.requestId(), f.scope(), f.caller(), true, 23))) + assertThatThrownBy(() -> + f.transaction() + .execute(status -> + f.operations() + .bindCanonicalPolicyEvidence( + f.requestId(), f.scope(), f.caller(), true, 23))) .isInstanceOf( AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); } - assertThatThrownBy( - () -> - f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure( - f.requestId(), - f.scope(), - f.caller(), - "TENANT_BILLING_BLOCKED"))) + assertThatThrownBy(() -> + f.transaction() + .execute(status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), f.scope(), f.caller(), "TENANT_BILLING_BLOCKED"))) .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); - assertThatThrownBy( - () -> - f.transaction() - .execute( - status -> - f.operations() - .recordCanonicalPolicyUnavailable( - f.requestId(), - f.scope(), - f.caller(), - "ENTITLEMENT_UNAVAILABLE"))) + assertThatThrownBy(() -> + f.transaction() + .execute(status -> + f.operations() + .recordCanonicalPolicyUnavailable( + f.requestId(), f.scope(), f.caller(), "ENTITLEMENT_UNAVAILABLE"))) .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); - assertThatThrownBy( - () -> - f.dsl() - .execute( - "UPDATE account_join_operations SET updated_at = CURRENT_TIMESTAMP WHERE request_id = ?", - f.requestId())) + assertThatThrownBy(() -> + f.dsl() + .execute( + "UPDATE account_join_operations SET updated_at = CURRENT_TIMESTAMP WHERE request_id = ?", + f.requestId())) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(f.bytes()).isEqualTo(retained); f.assertNoSuccessEffects(); @@ -667,18 +626,15 @@ void definitiveFailureRetainsOriginalIntentAndOptionalPolicyAndExactlyReplaysWit JournalFixture f = journalFixture(); var bound = f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence( - f.requestId(), f.scope(), f.caller(), true, 23)); + .execute(status -> + f.operations() + .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); var unavailable = f.transaction() - .execute( - status -> - f.operations() - .recordCanonicalPolicyUnavailable( - f.requestId(), f.scope(), f.caller(), "ENTITLEMENT_UNAVAILABLE")); + .execute(status -> + f.operations() + .recordCanonicalPolicyUnavailable( + f.requestId(), f.scope(), f.caller(), "ENTITLEMENT_UNAVAILABLE")); assertThat(unavailable.entitlementAuthorityAvailability()).isEqualTo("AVAILABLE"); assertThat(unavailable.requestDigest()).isEqualTo(bound.requestDigest()); assertThat(unavailable.entitlementVersion()).isEqualTo(23); @@ -687,35 +643,26 @@ void definitiveFailureRetainsOriginalIntentAndOptionalPolicyAndExactlyReplaysWit assertThat(unavailable.lastAttemptFailureCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); var targetUnavailable = f.transaction() - .execute( - status -> - f.operations() - .recordCanonicalAttemptFailure( - f.requestId(), - f.scope(), - f.caller(), - "NOT_EVALUATED", - "AUTH_UNAVAILABLE")); + .execute(status -> + f.operations() + .recordCanonicalAttemptFailure( + f.requestId(), f.scope(), f.caller(), "NOT_EVALUATED", "AUTH_UNAVAILABLE")); assertThat(targetUnavailable.requestDigest()).isEqualTo(bound.requestDigest()); assertThat(targetUnavailable.lastAttemptFailureCode()).isEqualTo("AUTH_UNAVAILABLE"); String beforeConflict = f.bytes(); - assertThatThrownBy( - () -> - f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence( - f.requestId(), f.scope(), f.caller(), true, 24))) + assertThatThrownBy(() -> + f.transaction() + .execute(status -> + f.operations() + .bindCanonicalPolicyEvidence( + f.requestId(), f.scope(), f.caller(), true, 24))) .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); assertThat(f.bytes()).isEqualTo(beforeConflict); var recovered = f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence( - f.requestId(), f.scope(), f.caller(), true, 23)); + .execute(status -> + f.operations() + .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); assertThat(recovered.requestDigest()).isEqualTo(bound.requestDigest()); assertThat(recovered.entitlementVersion()).isEqualTo(bound.entitlementVersion()); assertThat(recovered.allowPublicJoin()).isEqualTo(bound.allowPublicJoin()); @@ -723,10 +670,9 @@ void definitiveFailureRetainsOriginalIntentAndOptionalPolicyAndExactlyReplaysWit assertThat(recovered.lastAttemptFailureCode()).isNull(); String recoveredBytes = f.bytes(); f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); + .execute(status -> + f.operations() + .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); assertThat(f.bytes()).isEqualTo(recoveredBytes); f.assertNoSuccessEffects(); } @@ -736,21 +682,18 @@ void definitivePublicJoinDenialRetainsItsAlreadyBoundNegativePolicy() { JournalFixture f = journalFixture(); var deniedPolicy = f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence( - f.requestId(), f.scope(), f.caller(), false, 23)); + .execute(status -> + f.operations() + .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), false, 23)); var failed = f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure( - f.requestId(), - f.scope(), - f.caller(), - "PUBLIC_PRODUCTION_ADMISSION_DENIED")); + .execute(status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), + f.scope(), + f.caller(), + "PUBLIC_PRODUCTION_ADMISSION_DENIED")); assertThat(failed.status()).isEqualTo("FAILED"); assertThat(failed.allowPublicJoin()).isFalse(); assertThat(failed.entitlementAuthorityAvailability()).isEqualTo("AVAILABLE"); @@ -763,52 +706,41 @@ void definitivePublicJoinDenialRetainsItsAlreadyBoundNegativePolicy() { void failedJournalRejectsConflictingCallerRequestAndRetainedScopeWithoutRewritingReceipt() { JournalFixture f = journalFixture(); f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure( - f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID")); + .execute(status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID")); String retained = f.bytes(); var alternate = canonicalScope("different-canonical-bearer", f.scope().accountId(), f.scope().tenantId()); f.transaction() - .executeWithoutResult( - status -> - f.scopes() - .insertCanonical( - f.accountId(), alternate, f.read().scopeEvidence().tenantProvenance())); - assertThatThrownBy( - () -> - f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure( - f.requestId(), - f.scope(), - "different-caller", - "CONNECT_SCOPE_INVALID"))) + .executeWithoutResult(status -> + f.scopes() + .insertCanonical( + f.accountId(), alternate, f.read().scopeEvidence().tenantProvenance())); + assertThatThrownBy(() -> + f.transaction() + .execute(status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), f.scope(), "different-caller", "CONNECT_SCOPE_INVALID"))) .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); - assertThatThrownBy( - () -> - f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure( - "different-global-request", - f.scope(), - f.caller(), - "CONNECT_SCOPE_INVALID"))) + assertThatThrownBy(() -> + f.transaction() + .execute(status -> + f.operations() + .finishCanonicalFailure( + "different-global-request", + f.scope(), + f.caller(), + "CONNECT_SCOPE_INVALID"))) .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); - assertThatThrownBy( - () -> - f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure( - f.requestId(), alternate, f.caller(), "CONNECT_SCOPE_INVALID"))) + assertThatThrownBy(() -> + f.transaction() + .execute(status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), alternate, f.caller(), "CONNECT_SCOPE_INVALID"))) .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class); assertThat(f.bytes()).isEqualTo(retained); } @@ -823,20 +755,18 @@ void sqlGuardsRefuseRetryableTerminalOutcomesPolicyDowngradeInventedProofAndTerm "status = 'FAILED', outcome = 'CONNECT_SCOPE_INVALID', membership_id = 1", "status = 'COMMITTED', outcome = 'JOINED'", "intent_digest = 'sha256:" + "b".repeat(64) + "'")) { - assertThatThrownBy( - () -> - f.dsl() - .execute( - "UPDATE account_join_operations SET " + change + " WHERE request_id = ?", - f.requestId())) + assertThatThrownBy(() -> + f.dsl() + .execute( + "UPDATE account_join_operations SET " + change + " WHERE request_id = ?", + f.requestId())) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(f.bytes()).isEqualTo(original); } f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); + .execute(status -> + f.operations() + .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); String bound = f.bytes(); for (String change : java.util.List.of( @@ -844,27 +774,23 @@ void sqlGuardsRefuseRetryableTerminalOutcomesPolicyDowngradeInventedProofAndTerm "entitlement_version = 24", "request_digest = NULL", "last_attempt_authority_availability = 'UNAVAILABLE', last_attempt_failure_code = NULL")) { - assertThatThrownBy( - () -> - f.dsl() - .execute( - "UPDATE account_join_operations SET " + change + " WHERE request_id = ?", - f.requestId())) + assertThatThrownBy(() -> + f.dsl() + .execute( + "UPDATE account_join_operations SET " + change + " WHERE request_id = ?", + f.requestId())) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(f.bytes()).isEqualTo(bound); } f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure( - f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID")); + .execute(status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID")); String terminal = f.bytes(); - assertThatThrownBy( - () -> - f.dsl() - .execute( - "DELETE FROM account_join_operations WHERE request_id = ?", f.requestId())) + assertThatThrownBy(() -> + f.dsl() + .execute("DELETE FROM account_join_operations WHERE request_id = ?", f.requestId())) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThatThrownBy(() -> f.dsl().execute("TRUNCATE account_join_operations")) .isInstanceOf(org.jooq.exception.DataAccessException.class); @@ -878,33 +804,29 @@ void journalDiagnosticsAndDefinitiveFailureRollBackAsOneTransaction(boolean boun JournalFixture f = journalFixture(); if (bound) f.transaction() - .execute( - status -> - f.operations() - .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); + .execute(status -> + f.operations() + .bindCanonicalPolicyEvidence(f.requestId(), f.scope(), f.caller(), true, 23)); String original = f.bytes(); - assertThatThrownBy( - () -> - f.transaction() - .execute( - status -> { - f.operations() - .recordCanonicalPolicyUnavailable( - f.requestId(), f.scope(), f.caller(), "ENTITLEMENT_UNAVAILABLE"); - f.operations() - .finishCanonicalFailure( - f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID"); - throw new IllegalStateException("controlled canonical journal rollback"); - })) + assertThatThrownBy(() -> + f.transaction() + .execute(status -> { + f.operations() + .recordCanonicalPolicyUnavailable( + f.requestId(), f.scope(), f.caller(), "ENTITLEMENT_UNAVAILABLE"); + f.operations() + .finishCanonicalFailure( + f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID"); + throw new IllegalStateException("controlled canonical journal rollback"); + })) .hasMessageContaining("controlled canonical journal rollback"); assertThat(f.bytes()).isEqualTo(original); var failed = f.transaction() - .execute( - status -> - f.operations() - .finishCanonicalFailure( - f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID")); + .execute(status -> + f.operations() + .finishCanonicalFailure( + f.requestId(), f.scope(), f.caller(), "CONNECT_SCOPE_INVALID")); assertThat(failed.status()).isEqualTo("FAILED"); f.assertNoSuccessEffects(); } @@ -938,18 +860,17 @@ private JournalFixture journalFixture() { var scope = canonicalScope(accountId, tenant.canonicalTenantId()); String requestId = "journal-" + UUID.randomUUID(); String caller = "controlled-journal-caller"; - transaction.executeWithoutResult( - status -> { - scopes.insertCanonical( - privateAccountId, - scope, - new VerifiedTenantProvenance( - null, - TenantProvenanceKind.FRESH_GAME_DESIGN, - tenant.operationId(), - tenant.evidenceDigest())); - operations.insertCanonicalIntent(requestId, scope, caller); - }); + transaction.executeWithoutResult(status -> { + scopes.insertCanonical( + privateAccountId, + scope, + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + tenant.operationId(), + tenant.evidenceDigest())); + operations.insertCanonicalIntent(requestId, scope, caller); + }); return new JournalFixture( setup, transaction, operations, scopes, scope, privateAccountId, requestId, caller); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotPostgresIntegrationTest.java index 9d0cb16e1e..f645ba862b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotPostgresIntegrationTest.java @@ -92,11 +92,10 @@ void readsCommittedFirstJoinFromActualOwnersWithoutChangingRowsOrXmins() { assertThat(snapshot.checkpoints()).hasSize(4); assertThat(snapshot.sourceEvidence()).hasSize(2); assertThat(snapshot.checkpoints()) - .anySatisfy( - checkpoint -> { - assertThat(checkpoint.outboxStreamKey()).isEqualTo(fixture.membershipStream()); - assertThat(checkpoint.outboxSequence()).isEqualTo("1"); - }); + .anySatisfy(checkpoint -> { + assertThat(checkpoint.outboxStreamKey()).isEqualTo(fixture.membershipStream()); + assertThat(checkpoint.outboxSequence()).isEqualTo("1"); + }); assertThat(snapshot.authorityTuple().tenantBillingCutoff()) .hasValueSatisfying( cutoffs -> assertThat(cutoffs).containsKey(fixture.tenantUuid.toString())); @@ -120,11 +119,10 @@ void emitsOnlyTheProvenNonadmittingMissingBaselineForAnEnrolledFreshPair() { assertThat(snapshot.membershipVersion()).containsEntry(fixture.tenantUuid.toString(), "1"); assertThat(snapshot.membershipAuthorityGeneration()).isEqualTo("1"); assertThat(snapshot.checkpoints()) - .anySatisfy( - checkpoint -> { - assertThat(checkpoint.outboxStreamKey()).isEqualTo(fixture.membershipStream()); - assertThat(checkpoint.outboxSequence()).isEqualTo("0"); - }); + .anySatisfy(checkpoint -> { + assertThat(checkpoint.outboxStreamKey()).isEqualTo(fixture.membershipStream()); + assertThat(checkpoint.outboxSequence()).isEqualTo("0"); + }); assertThat(snapshot.sourceEvidence()) .noneMatch(source -> source.outboxStreamKey().equals(fixture.membershipStream())); assertThat(fixture.schemaImage()).isEqualTo(before); @@ -148,20 +146,18 @@ void missingCommittedRoleSnapshotFailsClosed() { Fixture fixture = newFixture(); fixture.commitFirstJoin(); long membershipId = fixture.membershipId(); - fixture.inTransaction( - () -> { - fixture.dsl.execute( - "DELETE FROM account_tenant_membership_role_snapshot_roles WHERE membership_id = ?", - membershipId); - fixture.dsl.execute( - "DELETE FROM account_tenant_membership_role_snapshots WHERE membership_id = ?", - membershipId); - return null; - }); - - assertThatThrownBy( - () -> - fixture.snapshots.readCurrent(fixture.account.getAccountUuid(), fixture.tenantUuid)) + fixture.inTransaction(() -> { + fixture.dsl.execute( + "DELETE FROM account_tenant_membership_role_snapshot_roles WHERE membership_id = ?", + membershipId); + fixture.dsl.execute( + "DELETE FROM account_tenant_membership_role_snapshots WHERE membership_id = ?", + membershipId); + return null; + }); + + assertThatThrownBy(() -> + fixture.snapshots.readCurrent(fixture.account.getAccountUuid(), fixture.tenantUuid)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Committed current membership role snapshot is absent"); } @@ -298,50 +294,43 @@ private Account createAccount() { } private void seedOwnerRowsAndOperation(AccountConnectScopeRepository connectScopes) { - inTransaction( - () -> { - freshTenants.importVerified(tenantEvidence); - sourceEvidence.initializeIssuerIfAbsent(ACCOUNT_ISSUER); - generations.initializeTenantIfAbsent(tenantUuid); - generations.initialize( - AccountAuthorityGenerationRepository.AuthorityScope.membership( - account.getAccountUuid(), tenantUuid)); - connectScopes.insertCanonical(account.getId(), scope, provenance); - operations.insertCanonicalIntent(requestId, scope, callerBinding); - return null; - }); + inTransaction(() -> { + freshTenants.importVerified(tenantEvidence); + sourceEvidence.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + generations.initializeTenantIfAbsent(tenantUuid); + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.getAccountUuid(), tenantUuid)); + connectScopes.insertCanonical(account.getId(), scope, provenance); + operations.insertCanonicalIntent(requestId, scope, callerBinding); + return null; + }); DemoTenantEntitlementSnapshot entitlement = - inTransaction( - () -> - demoEntitlements.provision( - entitlementRequest(UUID.randomUUID()), tenantEvidence)); - inTransaction( - () -> { - operations.bindCanonicalPolicyEvidence( - requestId, - scope, - callerBinding, - entitlement.allowPublicJoin(), - entitlement.entitlementVersion()); - return null; - }); + inTransaction(() -> + demoEntitlements.provision(entitlementRequest(UUID.randomUUID()), tenantEvidence)); + inTransaction(() -> { + operations.bindCanonicalPolicyEvidence( + requestId, + scope, + callerBinding, + entitlement.allowPublicJoin(), + entitlement.entitlementVersion()); + return null; + }); } private void enrollAbsenceBaseline() { - inTransaction( - () -> { - accounts - .findByAccountUuidForUpdate(account.getAccountUuid()) - .orElseThrow(() -> new IllegalStateException("Account owner row is absent")); - if (!tenantEvidence.equals(freshTenants.read(tenantUuid).orElseThrow()) - || memberships - .findFreshMembership(account.getAccountUuid(), tenantUuid) - .isPresent()) { - throw new IllegalStateException("Absence fixture is not the exact fresh empty pair"); - } - pairs.enrollAbsence(account.getAccountUuid(), tenantUuid, provenance); - return null; - }); + inTransaction(() -> { + accounts + .findByAccountUuidForUpdate(account.getAccountUuid()) + .orElseThrow(() -> new IllegalStateException("Account owner row is absent")); + if (!tenantEvidence.equals(freshTenants.read(tenantUuid).orElseThrow()) + || memberships.findFreshMembership(account.getAccountUuid(), tenantUuid).isPresent()) { + throw new IllegalStateException("Absence fixture is not the exact fresh empty pair"); + } + pairs.enrollAbsence(account.getAccountUuid(), tenantUuid, provenance); + return null; + }); } private AccountJoinOperationRepository.CanonicalJoinTerminalProof commitFirstJoin() { @@ -350,12 +339,11 @@ private AccountJoinOperationRepository.CanonicalJoinTerminalProof commitFirstJoi } private long membershipId() { - return inTransaction( - () -> - memberships - .findFreshMembership(account.getAccountUuid(), tenantUuid) - .orElseThrow() - .getId()); + return inTransaction(() -> + memberships + .findFreshMembership(account.getAccountUuid(), tenantUuid) + .orElseThrow() + .getId()); } private DemoTenantEntitlementRequest entitlementRequest(UUID entitlementRequestId) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java index 2df2df1f65..e1d949fa48 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountControlUiCommittedIssuanceRepositoryIntegrationTest.java @@ -119,28 +119,26 @@ void readsOnlyExactCommittedEvidenceInsideTheOwnerTransaction() { assertThat(evidence.committedAt()).isNotNull(); assertThat(evidence.recoveryFailedAt()).isNull(); assertThat( - context.inTransaction( - () -> - Objects.requireNonNull( - context.transactionDsl.fetchOne( - "SELECT encrypted_response FROM account_control_ui_response_envelopes " - + "WHERE operation_id = ?", - seed.operationId()), - "Missing committed control-ui response envelope row for operation " - + seed.operationId()) - .get(0, byte[].class))) + context.inTransaction(() -> + Objects.requireNonNull( + context.transactionDsl.fetchOne( + "SELECT encrypted_response FROM account_control_ui_response_envelopes " + + "WHERE operation_id = ?", + seed.operationId()), + "Missing committed control-ui response envelope row for operation " + + seed.operationId()) + .get(0, byte[].class))) .containsExactly(seed.encryptedResponse()); assertThat( - context.inTransaction( - () -> - Objects.requireNonNull( - context.transactionDsl.fetchOne( - "SELECT owner_binding FROM account_control_ui_response_envelopes " - + "WHERE operation_id = ?", - seed.operationId()), - "Missing committed control-ui owner-binding row for operation " - + seed.operationId()) - .get(0, byte[].class))) + context.inTransaction(() -> + Objects.requireNonNull( + context.transactionDsl.fetchOne( + "SELECT owner_binding FROM account_control_ui_response_envelopes " + + "WHERE operation_id = ?", + seed.operationId()), + "Missing committed control-ui owner-binding row for operation " + + seed.operationId()) + .get(0, byte[].class))) .containsExactly(seed.ownerBinding()); byte[] exposedClaims = evidence.claims(); @@ -160,17 +158,14 @@ void missingCandidateAndRevokedIssuancesDoNotReadAsCommitted() { assertThat(context.inTransaction(() -> context.repository.readCommitted("f".repeat(64)))) .isEmpty(); - assertThatThrownBy( - () -> - context.inTransaction( - () -> context.repository.readCommitted(candidate.tokenHash()))) + assertThatThrownBy(() -> + context.inTransaction(() -> context.repository.readCommitted(candidate.tokenHash()))) .isInstanceOf(IllegalStateException.class) .hasMessage("Exact committed Account control-ui issuance evidence unavailable"); assertThat(context.status(candidate.requestId())).isEqualTo("CANDIDATE"); assertThat(context.status(revoked.requestId())).isEqualTo("REVOKED"); - assertThatThrownBy( - () -> - context.inTransaction(() -> context.repository.readCommitted(revoked.tokenHash()))) + assertThatThrownBy(() -> + context.inTransaction(() -> context.repository.readCommitted(revoked.tokenHash()))) .isInstanceOf(IllegalStateException.class) .hasMessage("Exact committed Account control-ui issuance evidence unavailable"); } @@ -180,41 +175,33 @@ void importedPostgresGuardsRejectRewritingOrDeletingCommittedEvidence() { Context context = context(); IssuanceSeed seed = context.insertCommitted(); - assertThatThrownBy( - () -> - context.inTransaction( - () -> - context.transactionDsl.execute( - "UPDATE account_control_ui_issuance_operations " - + "SET source_payload = ? WHERE request_id = ?", - bytes("test-only-rewritten-source"), - seed.requestId()))) + assertThatThrownBy(() -> + context.inTransaction(() -> + context.transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET source_payload = ? WHERE request_id = ?", + bytes("test-only-rewritten-source"), + seed.requestId()))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - context.inTransaction( - () -> - context.transactionDsl.execute( - "DELETE FROM account_control_ui_issuance_operations WHERE request_id = ?", - seed.requestId()))) + assertThatThrownBy(() -> + context.inTransaction(() -> + context.transactionDsl.execute( + "DELETE FROM account_control_ui_issuance_operations WHERE request_id = ?", + seed.requestId()))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - context.inTransaction( - () -> - context.transactionDsl.execute( - "UPDATE account_control_ui_response_envelopes " - + "SET encrypted_response = ? WHERE operation_id = ?", - bytes("test-only-rewritten-envelope"), - seed.operationId()))) + assertThatThrownBy(() -> + context.inTransaction(() -> + context.transactionDsl.execute( + "UPDATE account_control_ui_response_envelopes " + + "SET encrypted_response = ? WHERE operation_id = ?", + bytes("test-only-rewritten-envelope"), + seed.operationId()))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - context.inTransaction( - () -> - context.transactionDsl.execute( - "DELETE FROM account_control_ui_response_envelopes WHERE operation_id = ?", - seed.operationId()))) + assertThatThrownBy(() -> + context.inTransaction(() -> + context.transactionDsl.execute( + "DELETE FROM account_control_ui_response_envelopes WHERE operation_id = ?", + seed.operationId()))) .isInstanceOf(DataAccessException.class); var retained = @@ -222,16 +209,15 @@ void importedPostgresGuardsRejectRewritingOrDeletingCommittedEvidence() { () -> context.repository.readCommitted(seed.tokenHash()).orElseThrow()); assertThat(retained.source()).containsExactly(seed.source()); assertThat( - context.inTransaction( - () -> - Objects.requireNonNull( - context.transactionDsl.fetchOne( - "SELECT encrypted_response FROM account_control_ui_response_envelopes " - + "WHERE operation_id = ?", - seed.operationId()), - "Missing retained control-ui response envelope row for operation " - + seed.operationId()) - .get(0, byte[].class))) + context.inTransaction(() -> + Objects.requireNonNull( + context.transactionDsl.fetchOne( + "SELECT encrypted_response FROM account_control_ui_response_envelopes " + + "WHERE operation_id = ?", + seed.operationId()), + "Missing retained control-ui response envelope row for operation " + + seed.operationId()) + .get(0, byte[].class))) .containsExactly(seed.encryptedResponse()); } @@ -247,42 +233,37 @@ void committedReadShareLockLinearizesBeforeConcurrentRevocation() throws Excepti ExecutorService executor = Executors.newFixedThreadPool(2); Future reader = - executor.submit( - () -> - context.inTransaction( - () -> { - var evidence = - context.repository.readCommitted(seed.tokenHash()).orElseThrow(); - readerPid.set( - Objects.requireNonNull( - context.transactionDsl.fetchOne("SELECT pg_backend_pid()"), - "Missing PostgreSQL backend pid row for committed-read reader") - .get(0, Integer.class)); - readerHasLoadedEvidence.countDown(); - await(releaseReaderTransaction, "reader transaction release"); - return evidence; - })); + executor.submit(() -> + context.inTransaction(() -> { + var evidence = context.repository.readCommitted(seed.tokenHash()).orElseThrow(); + readerPid.set( + Objects.requireNonNull( + context.transactionDsl.fetchOne("SELECT pg_backend_pid()"), + "Missing PostgreSQL backend pid row for committed-read reader") + .get(0, Integer.class)); + readerHasLoadedEvidence.countDown(); + await(releaseReaderTransaction, "reader transaction release"); + return evidence; + })); Future revocation; try { assertThat(readerHasLoadedEvidence.await(5, TimeUnit.SECONDS)).isTrue(); revocation = - executor.submit( - () -> - context.inTransaction( - () -> { - revokerPid.set( - Objects.requireNonNull( - context.transactionDsl.fetchOne("SELECT pg_backend_pid()"), - "Missing PostgreSQL backend pid row for concurrent revoker") - .get(0, Integer.class)); - revocationIsAboutToUpdate.countDown(); - context.transactionDsl.execute( - "UPDATE account_control_ui_issuance_operations " - + "SET status = 'REVOKING', recovery_failed_at = clock_timestamp() " - + "WHERE request_id = ? AND status = 'COMMITTED'", - seed.requestId()); - return null; - })); + executor.submit(() -> + context.inTransaction(() -> { + revokerPid.set( + Objects.requireNonNull( + context.transactionDsl.fetchOne("SELECT pg_backend_pid()"), + "Missing PostgreSQL backend pid row for concurrent revoker") + .get(0, Integer.class)); + revocationIsAboutToUpdate.countDown(); + context.transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'REVOKING', recovery_failed_at = clock_timestamp() " + + "WHERE request_id = ? AND status = 'COMMITTED'", + seed.requestId()); + return null; + })); assertThat(revocationIsAboutToUpdate.await(5, TimeUnit.SECONDS)).isTrue(); assertThat( waitUntilBlockedBy( @@ -440,19 +421,18 @@ private static final class Context { transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); repository = new AccountControlUiCommittedIssuanceRepository(transactionDsl); owner = - inTransaction( - () -> { - String suffix = UUID.randomUUID().toString(); - Account account = new Account(); - account.setUsername("cui-" + suffix.replace("-", "")); - account.setEmail("control-ui-committed-" + suffix + "@example.test"); - account.setPasswordHash("test-only-account-password-hash"); - Account saved = new AccountRepository(transactionDsl).save(account); - UUID tenantId = UUID.randomUUID(); - new FreshTenantIdentityAssociationRepository(transactionDsl, "prod") - .importVerified(tenantEvidence(tenantId)); - return new OwnerIdentity(saved.getAccountUuid(), tenantId); - }); + inTransaction(() -> { + String suffix = UUID.randomUUID().toString(); + Account account = new Account(); + account.setUsername("cui-" + suffix.replace("-", "")); + account.setEmail("control-ui-committed-" + suffix + "@example.test"); + account.setPasswordHash("test-only-account-password-hash"); + Account saved = new AccountRepository(transactionDsl).save(account); + UUID tenantId = UUID.randomUUID(); + new FreshTenantIdentityAssociationRepository(transactionDsl, "prod") + .importVerified(tenantEvidence(tenantId)); + return new OwnerIdentity(saved.getAccountUuid(), tenantId); + }); } OwnerIdentity owner() { @@ -482,57 +462,52 @@ IssuanceSeed insertCommitted() { } void insertProtectedResponse(IssuanceSeed seed) { - inTransactionWithoutResult( - () -> - transactionDsl.execute( - "INSERT INTO account_control_ui_response_envelopes " - + "(operation_id, encrypted_response, owner_binding, recovery_expires_at) " - + "VALUES (?, ?, ?, CAST(? AS timestamptz))", - seed.operationId(), - seed.encryptedResponse(), - seed.ownerBinding(), - seed.recoveryExpiresAt())); + inTransactionWithoutResult(() -> + transactionDsl.execute( + "INSERT INTO account_control_ui_response_envelopes " + + "(operation_id, encrypted_response, owner_binding, recovery_expires_at) " + + "VALUES (?, ?, ?, CAST(? AS timestamptz))", + seed.operationId(), + seed.encryptedResponse(), + seed.ownerBinding(), + seed.recoveryExpiresAt())); } void commitCandidate(IssuanceSeed seed) { - inTransactionWithoutResult( - () -> - transactionDsl.execute( - "UPDATE account_control_ui_issuance_operations " - + "SET status = 'COMMITTED', pending_receipt = ?, " - + "committed_at = clock_timestamp() " - + "WHERE request_id = ? AND status = 'CANDIDATE'", - seed.pendingReceipt(), - seed.requestId())); + inTransactionWithoutResult(() -> + transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'COMMITTED', pending_receipt = ?, " + + "committed_at = clock_timestamp() " + + "WHERE request_id = ? AND status = 'CANDIDATE'", + seed.pendingReceipt(), + seed.requestId())); } void revokeCommitted(IssuanceSeed seed) { - inTransactionWithoutResult( - () -> - transactionDsl.execute( - "UPDATE account_control_ui_issuance_operations " - + "SET status = 'REVOKING', recovery_failed_at = clock_timestamp() " - + "WHERE request_id = ? AND status = 'COMMITTED'", - seed.requestId())); - inTransactionWithoutResult( - () -> - transactionDsl.execute( - "UPDATE account_control_ui_issuance_operations " - + "SET status = 'REVOKED', revocation_receipt = ? " - + "WHERE request_id = ? AND status = 'REVOKING'", - bytes("test-only-revocation-receipt"), - seed.requestId())); + inTransactionWithoutResult(() -> + transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'REVOKING', recovery_failed_at = clock_timestamp() " + + "WHERE request_id = ? AND status = 'COMMITTED'", + seed.requestId())); + inTransactionWithoutResult(() -> + transactionDsl.execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'REVOKED', revocation_receipt = ? " + + "WHERE request_id = ? AND status = 'REVOKING'", + bytes("test-only-revocation-receipt"), + seed.requestId())); } String status(UUID requestId) { - return inTransaction( - () -> - Objects.requireNonNull( - transactionDsl.fetchOne( - "SELECT status FROM account_control_ui_issuance_operations WHERE request_id = ?", - requestId), - "Missing Account control-ui issuance status row for request " + requestId) - .get(0, String.class)); + return inTransaction(() -> + Objects.requireNonNull( + transactionDsl.fetchOne( + "SELECT status FROM account_control_ui_issuance_operations WHERE request_id = ?", + requestId), + "Missing Account control-ui issuance status row for request " + requestId) + .get(0, String.class)); } private void insertPrepared(IssuanceSeed seed) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCurrentLifecycleRealmGrantReadPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCurrentLifecycleRealmGrantReadPostgresIntegrationTest.java index b37c3a8adb..fa551aaccb 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCurrentLifecycleRealmGrantReadPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCurrentLifecycleRealmGrantReadPostgresIntegrationTest.java @@ -163,12 +163,11 @@ void absentGrantAbsentSourceWrongLifecycleAndTransportFailureNeverInferAuthority .isEqualTo(AccountCurrentLifecycleRealmGrantReadOwner.Status.CURRENT_LIFECYCLE_MISMATCH); assertThat(wrongLifecycle.grant()).isEmpty(); assertThat(wrongLifecycle.admissionAllowed()).isFalse(); - transport.respond( - request -> { - throw Status.UNAVAILABLE - .withDescription("Controlled GS source outage") - .asRuntimeException(); - }); + transport.respond(request -> { + throw Status.UNAVAILABLE + .withDescription("Controlled GS source outage") + .asRuntimeException(); + }); assertThatThrownBy(() -> owner.read(context.scope())).isInstanceOf(RuntimeException.class); assertThat(context.history()).usingRecursiveComparison().isEqualTo(before); } @@ -187,14 +186,12 @@ void sourceReplacementAfterReadDoesNotTurnAsOfObservationIntoAContinuingHold() t var replacement = CurrentPrivatePlaytestReadTransportFixture.snapshot( original.scope(), UUID.randomUUID(), fork, context.now(), 2L); - transport.respond( - request -> { - var response = - CurrentPrivatePlaytestLifecycleReadGrpcCodec.toResponse( - request, Optional.of(original)); - transport.current(Optional.of(replacement)); - return response; - }); + transport.respond(request -> { + var response = + CurrentPrivatePlaytestLifecycleReadGrpcCodec.toResponse(request, Optional.of(original)); + transport.current(Optional.of(replacement)); + return response; + }); var owner = context.owner(transport); var asOf = owner.read(context.scope()); assertThat(asOf.status()) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java index 712e84247c..18ca273963 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java @@ -93,24 +93,22 @@ void sequenceZeroTenantAuthorityHeadCannotCommit() { return null; }); - assertThatThrownBy( - () -> - inTransaction( - context.transaction(), - () -> { - tenantAuthorityEvents.establishFirstEventSource( - tenantId, - requestId, - source, - generationRepository.read( - AccountAuthorityGenerationRepository.AuthorityScope.tenant( - tenantId))); - context - .dsl() - .execute( - "SET CONSTRAINTS account_tenant_authority_stream_consistency IMMEDIATE"); - return null; - })) + assertThatThrownBy(() -> + inTransaction( + context.transaction(), + () -> { + tenantAuthorityEvents.establishFirstEventSource( + tenantId, + requestId, + source, + generationRepository.read( + AccountAuthorityGenerationRepository.AuthorityScope.tenant(tenantId))); + context + .dsl() + .execute( + "SET CONSTRAINTS account_tenant_authority_stream_consistency IMMEDIATE"); + return null; + })) .rootCause() .hasMessageContaining( "Tenant authority outbox head lacks an Account-owned source checkpoint"); @@ -244,18 +242,16 @@ void exactFreshUuidReplayConflictQuotasAndGenerationChangeAreTransactionallyFenc DemoTenantEntitlementRequest conflictingReplay = request(create.requestId(), tenantId, source, null, null, null, false); - assertThatThrownBy( - () -> - inTransaction( - context.transaction(), () -> entitlements.provision(conflictingReplay, source))) + assertThatThrownBy(() -> + inTransaction( + context.transaction(), () -> entitlements.provision(conflictingReplay, source))) .isInstanceOf(DemoTenantEntitlementException.class) .hasMessageContaining("reused for a different tenant or payload"); FreshTenantCreationEvidence alteredProvenance = alteredProvenance(source); - assertThatThrownBy( - () -> - inTransaction( - context.transaction(), () -> entitlements.provision(create, alteredProvenance))) + assertThatThrownBy(() -> + inTransaction( + context.transaction(), () -> entitlements.provision(create, alteredProvenance))) .isInstanceOf(DemoTenantEntitlementException.class) .hasMessageContaining("differs from exact Account UUID readback"); @@ -270,11 +266,10 @@ void exactFreshUuidReplayConflictQuotasAndGenerationChangeAreTransactionallyFenc }); DemoTenantEntitlementRequest crossTenantReplay = request(create.requestId(), otherTenantId, otherSource, null, null, null, true); - assertThatThrownBy( - () -> - inTransaction( - context.transaction(), - () -> entitlements.provision(crossTenantReplay, otherSource))) + assertThatThrownBy(() -> + inTransaction( + context.transaction(), + () -> entitlements.provision(crossTenantReplay, otherSource))) .isInstanceOf(DemoTenantEntitlementException.class) .hasMessageContaining("reused for a different tenant or payload"); @@ -287,10 +282,9 @@ void exactFreshUuidReplayConflictQuotasAndGenerationChangeAreTransactionallyFenc null, null, true); - assertThatThrownBy( - () -> - inTransaction( - context.transaction(), () -> entitlements.provision(wrongSourceTenant, source))) + assertThatThrownBy(() -> + inTransaction( + context.transaction(), () -> entitlements.provision(wrongSourceTenant, source))) .isInstanceOf(DemoTenantEntitlementException.class) .hasMessageContaining( "Only exact authenticated fresh Game Design tenant creation evidence"); @@ -362,20 +356,19 @@ void exactFreshUuidReplayConflictQuotasAndGenerationChangeAreTransactionallyFenc .get(0, Long.class); assertThat(operationCount).isEqualTo(2L); - assertThatThrownBy( - () -> - inTransaction( - context.transaction(), - () -> { - context - .dsl() - .execute( - "UPDATE account_authority_generations SET generation = generation + 1, " - + "source_version = source_version + 1 WHERE scope_kind = 'TENANT' " - + "AND tenant_uuid = ?", - tenantId); - return null; - })) + assertThatThrownBy(() -> + inTransaction( + context.transaction(), + () -> { + context + .dsl() + .execute( + "UPDATE account_authority_generations SET generation = generation + 1, " + + "source_version = source_version + 1 WHERE scope_kind = 'TENANT' " + + "AND tenant_uuid = ?", + tenantId); + return null; + })) .isInstanceOf(TransactionSystemException.class) .hasMessageContaining("JDBC commit failed") .rootCause() @@ -384,19 +377,18 @@ void exactFreshUuidReplayConflictQuotasAndGenerationChangeAreTransactionallyFenc "Tenant authority generation advance lacks its canonical source event"); assertThat(inTransaction(context.transaction(), () -> entitlements.readCurrent(tenantId))) .isEqualTo(updated); - assertThatThrownBy( - () -> - inTransaction( - context.transaction(), - () -> { - context - .dsl() - .execute( - "UPDATE account_demo_tenant_entitlements SET gameplay_available = NOT gameplay_available " - + "WHERE tenant_uuid = ?", - tenantId); - return null; - })) + assertThatThrownBy(() -> + inTransaction( + context.transaction(), + () -> { + context + .dsl() + .execute( + "UPDATE account_demo_tenant_entitlements SET gameplay_available = NOT gameplay_available " + + "WHERE tenant_uuid = ?", + tenantId); + return null; + })) .isInstanceOf(DataAccessException.class) .hasMessageContaining("Demo entitlement identity is immutable and version advances by one"); assertThat(inTransaction(context.transaction(), () -> entitlements.readCurrent(tenantId))) @@ -463,14 +455,13 @@ void failedOwnerTransactionAndUnmappedGenerationCannotCreateSyntheticAuthorityHi null, null, true); - assertThatThrownBy( - () -> - inTransaction( - context.transaction(), - () -> { - entitlements.provision(rollbackRequest, rollbackSource); - throw new IllegalStateException("force owner transaction rollback"); - })) + assertThatThrownBy(() -> + inTransaction( + context.transaction(), + () -> { + entitlements.provision(rollbackRequest, rollbackSource); + throw new IllegalStateException("force owner transaction rollback"); + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("force owner transaction rollback"); assertTenantHasOnlyGenerationOne(context, rollbackTenant); @@ -525,11 +516,10 @@ void failedOwnerTransactionAndUnmappedGenerationCannotCreateSyntheticAuthorityHi null, null, true); - assertThatThrownBy( - () -> - inTransaction( - context.transaction(), - () -> entitlements.provision(retainedRequest, retainedSource))) + assertThatThrownBy(() -> + inTransaction( + context.transaction(), + () -> entitlements.provision(retainedRequest, retainedSource))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("advanced without canonical source-event evidence"); assertThat( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java index f81e90f9e7..f9c8c1a6c1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFirstJoinAuthorityStorageIntegrationTest.java @@ -98,26 +98,20 @@ void appendsContiguousPerStreamAndReplaysOnlyExactRequestEvidence() { stream, "request-1", "event-1", "canonical-digest-1", new byte[] {1, 2})); assertThat(exactReplay).isEqualTo(first); - assertThatThrownBy( - () -> - inTransaction( - transaction, - () -> - repository.append( - stream, "request-1", "event-1", "different-digest", new byte[] {1, 2}))) + assertThatThrownBy(() -> + inTransaction( + transaction, + () -> + repository.append( + stream, "request-1", "event-1", "different-digest", new byte[] {1, 2}))) .isInstanceOf(IdempotencyConflictException.class); - assertThatThrownBy( - () -> - inTransaction( - transaction, - () -> - repository.append( - stream, - "request-1", - "event-1", - "canonical-digest-1", - new byte[] {1, 9}))) + assertThatThrownBy(() -> + inTransaction( + transaction, + () -> + repository.append( + stream, "request-1", "event-1", "canonical-digest-1", new byte[] {1, 9}))) .isInstanceOf(IdempotencyConflictException.class); Event second = @@ -236,76 +230,73 @@ void v38DoesNotBackfillRetainedMembershipAndCanonicalRoleSnapshotRequiresExactSo tenantSource.evidenceDigest()); Long canonicalMembershipId = - transaction.execute( - status -> { - AccountTenantMembership pendingMembership = - memberships.createFreshMembershipForJoin(account.getAccountUuid(), tenantUuid); - long membershipId = Objects.requireNonNull(pendingMembership.getId()); - assertThat( - roleSnapshots.findForCanonicalUpdate( - account.getAccountUuid(), - tenantUuid, - provenance, - membershipId, - pendingMembership.getMembershipVersion())) - .isEmpty(); - - AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot written = - roleSnapshots.replaceCanonical( - pendingMembership, + transaction.execute(status -> { + AccountTenantMembership pendingMembership = + memberships.createFreshMembershipForJoin(account.getAccountUuid(), tenantUuid); + long membershipId = Objects.requireNonNull(pendingMembership.getId()); + assertThat( + roleSnapshots.findForCanonicalUpdate( + account.getAccountUuid(), + tenantUuid, + provenance, + membershipId, + pendingMembership.getMembershipVersion())) + .isEmpty(); + + AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot written = + roleSnapshots.replaceCanonical( + pendingMembership, + account.getAccountUuid(), + tenantUuid, + provenance, + pendingMembership.getMembershipVersion(), + List.of()); + assertThat(written.roles()).isEmpty(); + assertThat(written.accountUuid()).isEqualTo(account.getAccountUuid()); + assertThat(written.tenantUuid()).isEqualTo(tenantUuid); + assertThat(written.tenantId()).isNull(); + assertThat(written.tenantProvenance()).isEqualTo(provenance); + + VerifiedTenantProvenance changedProvenance = + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + UUID.randomUUID(), + tenantSource.evidenceDigest()); + assertThatThrownBy(() -> + roleSnapshots.findForCanonicalUpdate( + account.getAccountUuid(), + tenantUuid, + changedProvenance, + membershipId, + pendingMembership.getMembershipVersion())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs from exact UUID identity or stored provenance"); + assertThatThrownBy(() -> + roleSnapshots.findForCanonicalUpdate( account.getAccountUuid(), tenantUuid, provenance, - pendingMembership.getMembershipVersion(), - List.of()); - assertThat(written.roles()).isEmpty(); - assertThat(written.accountUuid()).isEqualTo(account.getAccountUuid()); - assertThat(written.tenantUuid()).isEqualTo(tenantUuid); - assertThat(written.tenantId()).isNull(); - assertThat(written.tenantProvenance()).isEqualTo(provenance); - - VerifiedTenantProvenance changedProvenance = - new VerifiedTenantProvenance( - null, - TenantProvenanceKind.FRESH_GAME_DESIGN, - UUID.randomUUID(), - tenantSource.evidenceDigest()); - assertThatThrownBy( - () -> - roleSnapshots.findForCanonicalUpdate( - account.getAccountUuid(), - tenantUuid, - changedProvenance, - membershipId, - pendingMembership.getMembershipVersion())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("differs from exact UUID identity or stored provenance"); - assertThatThrownBy( - () -> - roleSnapshots.findForCanonicalUpdate( - account.getAccountUuid(), - tenantUuid, - provenance, - membershipId, - pendingMembership.getMembershipVersion() + 1L)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("membership version is missing or mismatched"); - assertThat( - roleSnapshots.findForCanonicalUpdate( - account.getAccountUuid(), - tenantUuid, - provenance, - membershipId, - pendingMembership.getMembershipVersion())) - .contains(written); - - assertThatThrownBy( - () -> memberships.findFreshMembership(account.getAccountUuid(), tenantUuid)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("no positive authority event"); - status.setRollbackOnly(); - return membershipId; - }); + membershipId, + pendingMembership.getMembershipVersion() + 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("membership version is missing or mismatched"); + assertThat( + roleSnapshots.findForCanonicalUpdate( + account.getAccountUuid(), + tenantUuid, + provenance, + membershipId, + pendingMembership.getMembershipVersion())) + .contains(written); + + assertThatThrownBy( + () -> memberships.findFreshMembership(account.getAccountUuid(), tenantUuid)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no positive authority event"); + status.setRollbackOnly(); + return membershipId; + }); assertThat( dsl.resultQuery( @@ -405,17 +396,16 @@ void databaseRejectsDeletingAHeadWithRetainedHistoryWithoutChangingEvidence() { "retained-digest", retainedPayload)); - assertThatThrownBy( - () -> - inTransaction( - transaction, - () -> { - dsl.execute( - "DELETE FROM account_authority_outbox_streams " - + "WHERE outbox_stream_key = ?", - stream); - return null; - })) + assertThatThrownBy(() -> + inTransaction( + transaction, + () -> { + dsl.execute( + "DELETE FROM account_authority_outbox_streams " + + "WHERE outbox_stream_key = ?", + stream); + return null; + })) .isInstanceOf(DataAccessException.class) .hasMessageContaining("Account authority outbox stream history cannot be deleted"); @@ -480,25 +470,23 @@ void databaseRejectsTruncatingOutboxHistoryAndPreservesEventsAndCheckpoint() { assertThat(inTransaction(transaction, () -> repository.findEvent(stream, 1L))).contains(first); assertThat(inTransaction(transaction, () -> repository.findEvent(stream, 2L))).contains(second); - assertThatThrownBy( - () -> - inTransaction( - transaction, - () -> { - dsl.execute("TRUNCATE TABLE account_authority_outbox_events CASCADE"); - return null; - })) + assertThatThrownBy(() -> + inTransaction( + transaction, + () -> { + dsl.execute("TRUNCATE TABLE account_authority_outbox_events CASCADE"); + return null; + })) .isInstanceOf(DataAccessException.class) .hasMessageContaining("Account authority outbox history cannot be truncated"); - assertThatThrownBy( - () -> - inTransaction( - transaction, - () -> { - dsl.execute("TRUNCATE TABLE account_authority_outbox_streams CASCADE"); - return null; - })) + assertThatThrownBy(() -> + inTransaction( + transaction, + () -> { + dsl.execute("TRUNCATE TABLE account_authority_outbox_streams CASCADE"); + return null; + })) .isInstanceOf(DataAccessException.class) .hasMessageContaining("Account authority outbox history cannot be truncated"); @@ -536,13 +524,12 @@ void callerRollbackRemovesAppendAndConcurrentExactRetriesShareOneSequence() thro TransactionTemplate transaction = context.transaction(); String rollbackStream = "account:auth-authority:v1:account/" + UUID.randomUUID(); - transaction.execute( - status -> { - repository.append( - rollbackStream, "rollback-request", "rollback-event", "digest", new byte[] {9}); - status.setRollbackOnly(); - return null; - }); + transaction.execute(status -> { + repository.append( + rollbackStream, "rollback-request", "rollback-event", "digest", new byte[] {9}); + status.setRollbackOnly(); + return null; + }); assertThat(inTransaction(transaction, () -> repository.readCheckpoint(rollbackStream))) .isEmpty(); @@ -583,18 +570,17 @@ void evidenceFactoryFailureRollsBackStreamCreationAndDoesNotAdvanceHead() { TransactionTemplate transaction = context.transaction(); String stream = membershipStream(UUID.randomUUID(), UUID.randomUUID()); - assertThatThrownBy( - () -> - inTransaction( - transaction, - () -> - repository.append( - stream, - "factory-failure-request", - sequence -> { - assertThat(sequence).isEqualTo(1L); - throw new IllegalStateException("producer failed"); - }))) + assertThatThrownBy(() -> + inTransaction( + transaction, + () -> + repository.append( + stream, + "factory-failure-request", + sequence -> { + assertThat(sequence).isEqualTo(1L); + throw new IllegalStateException("producer failed"); + }))) .isInstanceOf(IllegalStateException.class) .hasMessage("producer failed"); @@ -661,21 +647,20 @@ void exhaustedSequenceRejectsAppendWithoutChangingEventCheckpointOrCallerSentine assertThat(inTransaction(transaction, () -> repository.findEvent(stream, Long.MAX_VALUE))) .contains(originalEvent); - assertThatThrownBy( - () -> - inTransaction( - transaction, - () -> { - dsl.execute( - "UPDATE authority_overflow_sentinel SET value = value + 1 " - + "WHERE sentinel_id = 1"); - return repository.append( - stream, - "exhaustion-attempt-request", - "exhaustion-attempt-event", - "exhaustion-attempt-digest", - new byte[] {1, 2, 3}); - })) + assertThatThrownBy(() -> + inTransaction( + transaction, + () -> { + dsl.execute( + "UPDATE authority_overflow_sentinel SET value = value + 1 " + + "WHERE sentinel_id = 1"); + return repository.append( + stream, + "exhaustion-attempt-request", + "exhaustion-attempt-event", + "exhaustion-attempt-digest", + new byte[] {1, 2, 3}); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("Account authority outbox sequence is exhausted"); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java index 8743b5b649..26bcba5aed 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountFreshEnrollmentPostgresIntegrationTest.java @@ -70,61 +70,60 @@ void actualNewInsertCommitsBothExplicitOwnerDecisionsCurrentHeadsAndOriginalEven context.dsl.fetchCount(DSL.table("account_platform_restriction_current_projections"))) .isEqualTo(2); assertThat(context.dsl.fetchCount(DSL.table("account_authority_outbox_events"))).isEqualTo(2); - context.transaction.executeWithoutResult( - status -> { - var roleSource = - context.dsl.fetchSingle( - "SELECT a.id AS account_id, a.role, a.xmin::text AS account_xmin, " - + "a.account_uuid_source_numeric_id AS account_source_numeric_id, " - + "a.account_uuid_provenance AS account_provenance, s.account_uuid, " - + "s.account_uuid_source_numeric_id, s.account_uuid_provenance, " - + "s.global_roles, s.global_role_source_version, s.xmin::text AS source_xmin " - + "FROM accounts a JOIN account_global_role_sources s " - + "ON s.account_uuid = a.account_uuid WHERE a.account_uuid = ?", - result.accountUuid()); - assertThat(roleSource.get("role", String.class)).isNull(); - assertThat(roleSource.get("account_id", Long.class)).isEqualTo(result.accountId()); - assertThat(roleSource.get("account_uuid", UUID.class)).isEqualTo(result.accountUuid()); - assertThat(roleSource.get("account_uuid_source_numeric_id", Long.class)) - .isEqualTo(roleSource.get("account_source_numeric_id", Long.class)) - .isEqualTo(result.accountId()); - assertThat(roleSource.get("account_uuid_provenance", String.class)) - .isEqualTo(roleSource.get("account_provenance", String.class)) - .isEqualTo("ACCOUNT_REPOSITORY_INSERT"); - assertThat(roleSource.get("global_roles", String[].class)).isEmpty(); - assertThat(roleSource.get("global_role_source_version", Long.class)).isEqualTo(1L); - assertThat(roleSource.get("source_xmin", String.class)) - .isEqualTo(roleSource.get("account_xmin", String.class)); - var outbox = new AccountAuthorityOutboxRepository(context.dsl); - for (var operation : - java.util.List.of(result.accountSecurityLock(), result.platformAccessBan())) { - var receipt = operation.receipt().orElseThrow(); - var event = receipt.event(); - assertThat(outbox.findEvent(event.outboxStreamKey(), event.outboxSequence())) - .contains(event); - assertThat(event.outboxSequence()).isEqualTo(receipt.sourceState().generation() - 1); - assertThat( - context - .dsl - .fetchSingle( - "SELECT expected_generation FROM account_fresh_enrollment_decisions WHERE request_id = ?", - operation.request().requestId()) - .get("expected_generation", Long.class)) - .isEqualTo(receipt.sourceState().generation() - 1); - } - var generations = new AccountAuthorityGenerationRepository(context.dsl); - var state = generations.read(AuthorityScope.account(result.accountUuid())); - assertThat(state.generation()).isEqualTo(3); - assertThat(state.sourceVersion()).isEqualTo(3); - assertThat(state.issuanceFence().value()).isEqualTo(3); - assertThat(state.issuanceFence().sourceVersion()).isEqualTo(3); - var source = source(context.dsl).readCurrentSource(state.scope(), state); - assertThat(source.checkpoint().sequence()).isEqualTo(2); - assertThat(source.checkpoint().sourceEventId().orElseThrow()) - .isEqualTo(result.platformAccessBan().receipt().orElseThrow().event().eventId()); - assertThat(source.checkpoint().sourceEventDigest().orElseThrow()) - .isEqualTo(result.platformAccessBan().receipt().orElseThrow().event().eventDigest()); - }); + context.transaction.executeWithoutResult(status -> { + var roleSource = + context.dsl.fetchSingle( + "SELECT a.id AS account_id, a.role, a.xmin::text AS account_xmin, " + + "a.account_uuid_source_numeric_id AS account_source_numeric_id, " + + "a.account_uuid_provenance AS account_provenance, s.account_uuid, " + + "s.account_uuid_source_numeric_id, s.account_uuid_provenance, " + + "s.global_roles, s.global_role_source_version, s.xmin::text AS source_xmin " + + "FROM accounts a JOIN account_global_role_sources s " + + "ON s.account_uuid = a.account_uuid WHERE a.account_uuid = ?", + result.accountUuid()); + assertThat(roleSource.get("role", String.class)).isNull(); + assertThat(roleSource.get("account_id", Long.class)).isEqualTo(result.accountId()); + assertThat(roleSource.get("account_uuid", UUID.class)).isEqualTo(result.accountUuid()); + assertThat(roleSource.get("account_uuid_source_numeric_id", Long.class)) + .isEqualTo(roleSource.get("account_source_numeric_id", Long.class)) + .isEqualTo(result.accountId()); + assertThat(roleSource.get("account_uuid_provenance", String.class)) + .isEqualTo(roleSource.get("account_provenance", String.class)) + .isEqualTo("ACCOUNT_REPOSITORY_INSERT"); + assertThat(roleSource.get("global_roles", String[].class)).isEmpty(); + assertThat(roleSource.get("global_role_source_version", Long.class)).isEqualTo(1L); + assertThat(roleSource.get("source_xmin", String.class)) + .isEqualTo(roleSource.get("account_xmin", String.class)); + var outbox = new AccountAuthorityOutboxRepository(context.dsl); + for (var operation : + java.util.List.of(result.accountSecurityLock(), result.platformAccessBan())) { + var receipt = operation.receipt().orElseThrow(); + var event = receipt.event(); + assertThat(outbox.findEvent(event.outboxStreamKey(), event.outboxSequence())) + .contains(event); + assertThat(event.outboxSequence()).isEqualTo(receipt.sourceState().generation() - 1); + assertThat( + context + .dsl + .fetchSingle( + "SELECT expected_generation FROM account_fresh_enrollment_decisions WHERE request_id = ?", + operation.request().requestId()) + .get("expected_generation", Long.class)) + .isEqualTo(receipt.sourceState().generation() - 1); + } + var generations = new AccountAuthorityGenerationRepository(context.dsl); + var state = generations.read(AuthorityScope.account(result.accountUuid())); + assertThat(state.generation()).isEqualTo(3); + assertThat(state.sourceVersion()).isEqualTo(3); + assertThat(state.issuanceFence().value()).isEqualTo(3); + assertThat(state.issuanceFence().sourceVersion()).isEqualTo(3); + var source = source(context.dsl).readCurrentSource(state.scope(), state); + assertThat(source.checkpoint().sequence()).isEqualTo(2); + assertThat(source.checkpoint().sourceEventId().orElseThrow()) + .isEqualTo(result.platformAccessBan().receipt().orElseThrow().event().eventId()); + assertThat(source.checkpoint().sourceEventDigest().orElseThrow()) + .isEqualTo(result.platformAccessBan().receipt().orElseThrow().event().eventDigest()); + }); assertThat( context .dsl @@ -154,25 +153,21 @@ void sourceGuardsStillRefuseGenerationOrFenceAdvanceWithoutExactSourceEvidenceAt "UPDATE account_authority_issuance_fences SET issuance_fence = issuance_fence + 1, source_version = source_version + 1 WHERE account_uuid = ?", "account_authority_source_fence_required") .entrySet()) { - assertThatThrownBy( - () -> - context.transaction.executeWithoutResult( - status -> context.dsl.execute(mutation.getKey(), result.accountUuid()))) + assertThatThrownBy(() -> + context.transaction.executeWithoutResult( + status -> context.dsl.execute(mutation.getKey(), result.accountUuid()))) .rootCause() .isInstanceOf(org.postgresql.util.PSQLException.class) - .satisfies( - cause -> { - var failure = (org.postgresql.util.PSQLException) cause; - assertThat(failure.getSQLState()).isEqualTo("23514"); - assertThat(Objects.requireNonNull(failure.getServerErrorMessage()).getConstraint()) - .isEqualTo(mutation.getValue()); - }); - context.transaction.executeWithoutResult( - status -> { - assertThat(generations.read(scope)).isEqualTo(before); - assertThat(source(context.dsl).readCurrentSource(scope, before)) - .isEqualTo(originalSource); + .satisfies(cause -> { + var failure = (org.postgresql.util.PSQLException) cause; + assertThat(failure.getSQLState()).isEqualTo("23514"); + assertThat(Objects.requireNonNull(failure.getServerErrorMessage()).getConstraint()) + .isEqualTo(mutation.getValue()); }); + context.transaction.executeWithoutResult(status -> { + assertThat(generations.read(scope)).isEqualTo(before); + assertThat(source(context.dsl).readCurrentSource(scope, before)).isEqualTo(originalSource); + }); } } @@ -200,10 +195,9 @@ void lostResponseRetryReturnsExactOriginalAccountAndResultsWithoutRevisionDuplic () -> context.transaction.execute(status -> producer(context).enroll(changed))) .isInstanceOf(AccountAuthorityOutboxRepository.IdempotencyConflictException.class); // New policy publications do not rewrite or re-certify original retained success receipts. - context.transaction.executeWithoutResult( - status -> - controlledPublication( - context, Category.ACCOUNT_SECURITY_LOCK, 2, "DENY_NEW_ACCOUNT", "CLOSED")); + context.transaction.executeWithoutResult(status -> + controlledPublication( + context, Category.ACCOUNT_SECURITY_LOCK, 2, "DENY_NEW_ACCOUNT", "CLOSED")); var replayAfterPolicyAdvance = context.transaction.execute(status -> producer(context).enroll(request)); assertThat(replayAfterPolicyAdvance).isEqualTo(first); @@ -222,16 +216,15 @@ void missingPolicyUnsafePolicyAndSecondCategoryClosedPolicyNeverLeaveAnAccountOr {"DENY_NEW_ACCOUNT", "EXACT_FRESH_INSERT_ONLY"}, {"CERTIFY_NEW_ACTIVE_ACCOUNT", "CLOSED"} }) { Context context = context(null); - context.transaction.executeWithoutResult( - status -> { - controlledPublication( - context, - Category.ACCOUNT_SECURITY_LOCK, - 1, - "CERTIFY_NEW_ACTIVE_ACCOUNT", - "EXACT_FRESH_INSERT_ONLY"); - controlledPublication(context, Category.PLATFORM_ACCESS_BAN, 1, rules[0], rules[1]); - }); + context.transaction.executeWithoutResult(status -> { + controlledPublication( + context, + Category.ACCOUNT_SECURITY_LOCK, + 1, + "CERTIFY_NEW_ACTIVE_ACCOUNT", + "EXACT_FRESH_INSERT_ONLY"); + controlledPublication(context, Category.PLATFORM_ACCESS_BAN, 1, rules[0], rules[1]); + }); assertThatThrownBy( () -> context.transaction.execute(status -> producer(context).enroll(request()))) .isInstanceOf(IllegalStateException.class); @@ -250,23 +243,18 @@ void ordinarySaveRemainsBirthOnlyAndRetainedAccountCannotAcquireInsertionOrEnrol assertThat( context.dsl.fetchCount(DSL.table("account_platform_restriction_current_projections"))) .isZero(); - assertThatThrownBy( - () -> - context.transaction.execute( - status -> - new AccountRepository(context.dsl) - .insertFreshAndApply(retained, proof -> proof))) + assertThatThrownBy(() -> + context.transaction.execute(status -> + new AccountRepository(context.dsl).insertFreshAndApply(retained, proof -> proof))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - context.transaction.executeWithoutResult( - status -> - context.dsl.execute( - "INSERT INTO account_fresh_enrollments (enrollment_id, request_digest, account_uuid, account_id, insertion_xid) " - + "SELECT ?, ?, account_uuid, id, txid_current() FROM accounts WHERE account_uuid = ?", - UUID.randomUUID(), - "sha256:" + "0".repeat(64), - retained.getAccountUuid()))) + assertThatThrownBy(() -> + context.transaction.executeWithoutResult(status -> + context.dsl.execute( + "INSERT INTO account_fresh_enrollments (enrollment_id, request_digest, account_uuid, account_id, insertion_xid) " + + "SELECT ?, ?, account_uuid, id, txid_current() FROM accounts WHERE account_uuid = ?", + UUID.randomUUID(), + "sha256:" + "0".repeat(64), + retained.getAccountUuid()))) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(context.dsl.fetchCount(DSL.table("account_fresh_enrollments"))).isZero(); } @@ -276,37 +264,28 @@ void escapedCapabilityAndDifferentTransactionCannotCertifyAnInsert() throws Exce Context context = context(null); controlledPolicies(context); AtomicReference escaped = new AtomicReference<>(); - context.transaction.executeWithoutResult( - status -> - new AccountRepository(context.dsl) - .insertFreshAndApply( - request().newAccount(), - proof -> { - escaped.set(proof); - var independent = - new TransactionTemplate( - new DataSourceTransactionManager(context.dataSource)); - independent.setPropagationBehavior( - TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertThatThrownBy( - () -> - independent.execute( - inner -> - new AccountFreshEnrollmentPolicyRepository(context.dsl) - .evaluate( - proof, - UUID.randomUUID(), - Category.ACCOUNT_SECURITY_LOCK))) - .isInstanceOf(IllegalStateException.class); - return proof.accountUuid(); - })); - assertThatThrownBy( - () -> - context.transaction.execute( - status -> - new AccountFreshEnrollmentPolicyRepository(context.dsl) - .evaluate( - escaped.get(), UUID.randomUUID(), Category.ACCOUNT_SECURITY_LOCK))) + context.transaction.executeWithoutResult(status -> + new AccountRepository(context.dsl) + .insertFreshAndApply( + request().newAccount(), + proof -> { + escaped.set(proof); + var independent = + new TransactionTemplate(new DataSourceTransactionManager(context.dataSource)); + independent.setPropagationBehavior( + TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThatThrownBy(() -> + independent.execute(inner -> + new AccountFreshEnrollmentPolicyRepository(context.dsl) + .evaluate( + proof, UUID.randomUUID(), Category.ACCOUNT_SECURITY_LOCK))) + .isInstanceOf(IllegalStateException.class); + return proof.accountUuid(); + })); + assertThatThrownBy(() -> + context.transaction.execute(status -> + new AccountFreshEnrollmentPolicyRepository(context.dsl) + .evaluate(escaped.get(), UUID.randomUUID(), Category.ACCOUNT_SECURITY_LOCK))) .isInstanceOf(IllegalStateException.class); assertThat(context.dsl.fetchCount(DSL.table("account_fresh_enrollment_decisions"))).isZero(); } @@ -316,28 +295,25 @@ void missingSecondCertificationFailsAtPhysicalCommitAndRollsBackTheCompleteFirst throws Exception { Context context = context(null); controlledPolicies(context); - assertThatThrownBy( - () -> - context.transaction.executeWithoutResult( - status -> { - var policies = new AccountFreshEnrollmentPolicyRepository(context.dsl); - policies.lockCurrentPolicies(); - new AccountRepository(context.dsl) - .insertFreshAndApply( - request().newAccount(), - proof -> { - checkCompletedSourceBoundary(context); - UUID id = UUID.randomUUID(); - insertEnrollment(context, proof, id); - restrictions(context.dsl) - .certifyFreshEnrollment( - proof, - policies.evaluate( - proof, id, Category.ACCOUNT_SECURITY_LOCK)); - checkCompletedSourceBoundary(context); - return proof.accountUuid(); - }); - })) + assertThatThrownBy(() -> + context.transaction.executeWithoutResult(status -> { + var policies = new AccountFreshEnrollmentPolicyRepository(context.dsl); + policies.lockCurrentPolicies(); + new AccountRepository(context.dsl) + .insertFreshAndApply( + request().newAccount(), + proof -> { + checkCompletedSourceBoundary(context); + UUID id = UUID.randomUUID(); + insertEnrollment(context, proof, id); + restrictions(context.dsl) + .certifyFreshEnrollment( + proof, + policies.evaluate(proof, id, Category.ACCOUNT_SECURITY_LOCK)); + checkCompletedSourceBoundary(context); + return proof.accountUuid(); + }); + })) .rootCause() .isInstanceOf(org.postgresql.util.PSQLException.class) .hasMessageContaining( @@ -357,40 +333,29 @@ void currentOwnerPolicyWriterWaitsThroughBothCertificationsAndResultCompletion() AtomicReference writerPid = new AtomicReference<>(); try (var executor = Executors.newFixedThreadPool(2)) { var reader = - executor.submit( - () -> - context.transaction.execute( - status -> { - int backendPid = - Objects.requireNonNull( - context.dsl.fetchOne("SELECT pg_backend_pid() AS pid")) - .get("pid", Integer.class); - readerPid.set(backendPid); - new AccountFreshEnrollmentPolicyRepository(context.dsl) - .lockCurrentPolicies(); - shared.countDown(); - await(release); - return producer(context).enroll(request()); - })); + executor.submit(() -> + context.transaction.execute(status -> { + int backendPid = + Objects.requireNonNull(context.dsl.fetchOne("SELECT pg_backend_pid() AS pid")) + .get("pid", Integer.class); + readerPid.set(backendPid); + new AccountFreshEnrollmentPolicyRepository(context.dsl).lockCurrentPolicies(); + shared.countDown(); + await(release); + return producer(context).enroll(request()); + })); assertThat(shared.await(10, TimeUnit.SECONDS)).isTrue(); var writer = - executor.submit( - () -> - context.transaction.executeWithoutResult( - status -> { - int backendPid = - Objects.requireNonNull( - context.dsl.fetchOne("SELECT pg_backend_pid() AS pid")) - .get("pid", Integer.class); - writerPid.set(backendPid); - writerStarted.countDown(); - controlledPublication( - context, - Category.ACCOUNT_SECURITY_LOCK, - 2, - "DENY_NEW_ACCOUNT", - "CLOSED"); - })); + executor.submit(() -> + context.transaction.executeWithoutResult(status -> { + int backendPid = + Objects.requireNonNull(context.dsl.fetchOne("SELECT pg_backend_pid() AS pid")) + .get("pid", Integer.class); + writerPid.set(backendPid); + writerStarted.countDown(); + controlledPublication( + context, Category.ACCOUNT_SECURITY_LOCK, 2, "DENY_NEW_ACCOUNT", "CLOSED"); + })); assertThat(writerStarted.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(readerPid.get()).isNotNull(); assertThat(writerPid.get()).isNotNull(); @@ -431,10 +396,9 @@ void directSqlCannotOmitClosureForgeDecisionMutateReceiptsRegressPolicyOrBreakRe () -> context.transaction.executeWithoutResult(status -> context.dsl.execute(sql))) .isInstanceOf(RuntimeException.class); } - context.transaction.executeWithoutResult( - status -> - context.dsl.fetch( - "SELECT account_fresh_enrollment_require_complete(?)", result.enrollmentId())); + context.transaction.executeWithoutResult(status -> + context.dsl.fetch( + "SELECT account_fresh_enrollment_require_complete(?)", result.enrollmentId())); assertThat(context.dsl.fetchCount(DSL.table("account_fresh_enrollment_results"))).isEqualTo(1); } @@ -443,46 +407,42 @@ void swappedReciprocalCategoryResultsAreRefusedEvenWithTwoGenuineFreshDecisions( throws Exception { Context context = context(null); controlledPolicies(context); - assertThatThrownBy( - () -> - context.transaction.executeWithoutResult( - status -> { - var policies = new AccountFreshEnrollmentPolicyRepository(context.dsl); - policies.lockCurrentPolicies(); - new AccountRepository(context.dsl) - .insertFreshAndApply( - request().newAccount(), - proof -> { - checkCompletedSourceBoundary(context); - UUID id = UUID.randomUUID(); - insertEnrollment(context, proof, id); - var lockDecision = - policies.evaluate(proof, id, Category.ACCOUNT_SECURITY_LOCK); - // Even genuine fresh-owner correlation cannot authorize the - // ordinary request command. - var request = lockDecision.requireCurrent(context.dsl, proof); - assertThatThrownBy(() -> restrictions(context.dsl).commit(request)) - .isInstanceOf( - AccountPlatformRestrictionOperationRepository - .OwnerAuthorizationUnresolvedException.class); - var lock = - restrictions(context.dsl) - .certifyFreshEnrollment(proof, lockDecision); - checkCompletedSourceBoundary(context); - var ban = - restrictions(context.dsl) - .certifyFreshEnrollment( - proof, - policies.evaluate( - proof, id, Category.PLATFORM_ACCESS_BAN)); - context.dsl.execute( - "INSERT INTO account_fresh_enrollment_results (enrollment_id, security_request_id, ban_request_id) VALUES (?, ?, ?)", - id, - ban.request().requestId(), - lock.request().requestId()); - return id; - }); - })) + assertThatThrownBy(() -> + context.transaction.executeWithoutResult(status -> { + var policies = new AccountFreshEnrollmentPolicyRepository(context.dsl); + policies.lockCurrentPolicies(); + new AccountRepository(context.dsl) + .insertFreshAndApply( + request().newAccount(), + proof -> { + checkCompletedSourceBoundary(context); + UUID id = UUID.randomUUID(); + insertEnrollment(context, proof, id); + var lockDecision = + policies.evaluate(proof, id, Category.ACCOUNT_SECURITY_LOCK); + // Even genuine fresh-owner correlation cannot authorize the + // ordinary request command. + var request = lockDecision.requireCurrent(context.dsl, proof); + assertThatThrownBy(() -> restrictions(context.dsl).commit(request)) + .isInstanceOf( + AccountPlatformRestrictionOperationRepository + .OwnerAuthorizationUnresolvedException.class); + var lock = + restrictions(context.dsl).certifyFreshEnrollment(proof, lockDecision); + checkCompletedSourceBoundary(context); + var ban = + restrictions(context.dsl) + .certifyFreshEnrollment( + proof, + policies.evaluate(proof, id, Category.PLATFORM_ACCESS_BAN)); + context.dsl.execute( + "INSERT INTO account_fresh_enrollment_results (enrollment_id, security_request_id, ban_request_id) VALUES (?, ?, ?)", + id, + ban.request().requestId(), + lock.request().requestId()); + return id; + }); + })) .rootCause() .isInstanceOf(org.postgresql.util.PSQLException.class) .hasMessageContaining( @@ -496,25 +456,21 @@ void malformedPublicationWithoutClosureAndForgedDecisionForRetainedAccountFailCl Context context = context(null); controlledPolicies(context); var result = context.transaction.execute(status -> producer(context).enroll(request())); - assertThatThrownBy( - () -> - context.transaction.executeWithoutResult( - status -> - context.dsl.execute( - "INSERT INTO account_fresh_enrollment_policy_publications SELECT gen_random_uuid(), category, 2, policy_id, closure_id, " - + "policy_rule, closure_rule, source_identity, source_root, 'sha256:' || encode(sha256(convert_to('{}','UTF8')),'hex'), " - + "convert_to('{}','UTF8') FROM account_fresh_enrollment_policy_publications LIMIT 1"))) + assertThatThrownBy(() -> + context.transaction.executeWithoutResult(status -> + context.dsl.execute( + "INSERT INTO account_fresh_enrollment_policy_publications SELECT gen_random_uuid(), category, 2, policy_id, closure_id, " + + "policy_rule, closure_rule, source_identity, source_root, 'sha256:' || encode(sha256(convert_to('{}','UTF8')),'hex'), " + + "convert_to('{}','UTF8') FROM account_fresh_enrollment_policy_publications LIMIT 1"))) .isInstanceOf(org.jooq.exception.DataAccessException.class); - assertThatThrownBy( - () -> - context.transaction.executeWithoutResult( - status -> - context.dsl.execute( - "INSERT INTO account_fresh_enrollment_decisions SELECT gen_random_uuid(), enrollment_id, account_uuid, account_id, txid_current(), " - + "category, publication_id, publication_digest, policy_id, closure_id, gen_random_uuid(), expected_generation, expected_source_version, " - + "expected_fence, expected_fence_source_version, expected_revision, expected_epoch, expected_result_id, decision_digest " - + "FROM account_fresh_enrollment_decisions WHERE enrollment_id = ? LIMIT 1", - result.enrollmentId()))) + assertThatThrownBy(() -> + context.transaction.executeWithoutResult(status -> + context.dsl.execute( + "INSERT INTO account_fresh_enrollment_decisions SELECT gen_random_uuid(), enrollment_id, account_uuid, account_id, txid_current(), " + + "category, publication_id, publication_digest, policy_id, closure_id, gen_random_uuid(), expected_generation, expected_source_version, " + + "expected_fence, expected_fence_source_version, expected_revision, expected_epoch, expected_result_id, decision_digest " + + "FROM account_fresh_enrollment_decisions WHERE enrollment_id = ? LIMIT 1", + result.enrollmentId()))) .isInstanceOf(org.jooq.exception.DataAccessException.class); } @@ -563,16 +519,14 @@ void upgradePreservesRetainedAccountBirthAndSourceRowsWithoutCertifyingThem() th context.dsl.fetchCount(DSL.table("account_platform_restriction_current_projections"))) .isZero(); controlledPolicies(context); - assertThatThrownBy( - () -> - context.transaction.executeWithoutResult( - status -> - context.dsl.execute( - "INSERT INTO account_fresh_enrollments (enrollment_id, request_digest, account_uuid, account_id, insertion_xid) " - + "SELECT ?, ?, account_uuid, id, txid_current() FROM accounts WHERE account_uuid = ?", - UUID.randomUUID(), - "sha256:" + "0".repeat(64), - retained.getAccountUuid()))) + assertThatThrownBy(() -> + context.transaction.executeWithoutResult(status -> + context.dsl.execute( + "INSERT INTO account_fresh_enrollments (enrollment_id, request_digest, account_uuid, account_id, insertion_xid) " + + "SELECT ?, ?, account_uuid, id, txid_current() FROM accounts WHERE account_uuid = ?", + UUID.randomUUID(), + "sha256:" + "0".repeat(64), + retained.getAccountUuid()))) .isInstanceOf(org.jooq.exception.DataAccessException.class); } @@ -614,12 +568,11 @@ private static void checkCompletedSourceBoundary(Context context) { } private static void controlledPolicies(Context context) { - context.transaction.executeWithoutResult( - status -> { - for (Category category : Category.values()) - controlledPublication( - context, category, 1, "CERTIFY_NEW_ACTIVE_ACCOUNT", "EXACT_FRESH_INSERT_ONLY"); - }); + context.transaction.executeWithoutResult(status -> { + for (Category category : Category.values()) + controlledPublication( + context, category, 1, "CERTIFY_NEW_ACTIVE_ACCOUNT", "EXACT_FRESH_INSERT_ONLY"); + }); } /** diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionAbortCompositionFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionAbortCompositionFixture.java index be95424631..3d863f5835 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionAbortCompositionFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionAbortCompositionFixture.java @@ -294,12 +294,11 @@ String image() { "game_session_canonical_issuer_binding_local_operation", "game_session_canonical_issuer_binding_local_release_operation") .stream() - .map( - table -> - gs.dsl() - .fetch("SELECT to_jsonb(t)::text AS image FROM " + table + " t ORDER BY 1") - .getValues("image") - .toString()) + .map(table -> + gs.dsl() + .fetch("SELECT to_jsonb(t)::text AS image FROM " + table + " t ORDER BY 1") + .getValues("image") + .toString()) .collect(java.util.stream.Collectors.joining("\n")); } @@ -322,15 +321,14 @@ String issuerCleanupHistoryImage() { "game_session_canonical_issuer_binding_local_retirement", "game_session_canonical_issuer_partition_mutation") .stream() - .map( - table -> - gs.dsl() - .fetch( - "SELECT jsonb_build_array(to_jsonb(t), t.xmin::text)::text AS image FROM " - + table - + " t ORDER BY 1") - .getValues("image") - .toString()) + .map(table -> + gs.dsl() + .fetch( + "SELECT jsonb_build_array(to_jsonb(t), t.xmin::text)::text AS image FROM " + + table + + " t ORDER BY 1") + .getValues("image") + .toString()) .collect(java.util.stream.Collectors.joining("\n")); } @@ -366,15 +364,14 @@ String completedNegativeCleanupCurrentImage() { "game_session_canonical_issuer_partition_mutation_head", "game_session_canonical_binding_inventory_clock") .stream() - .map( - table -> - gs.dsl() - .fetch( - "SELECT jsonb_build_array(to_jsonb(t), t.xmin::text)::text AS image FROM " - + table - + " t ORDER BY 1") - .getValues("image") - .toString()) + .map(table -> + gs.dsl() + .fetch( + "SELECT jsonb_build_array(to_jsonb(t), t.xmin::text)::text AS image FROM " + + table + + " t ORDER BY 1") + .getValues("image") + .toString()) .collect(java.util.stream.Collectors.joining("\n")); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java index 34d8d81029..89feed0cbf 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionDefinitiveAbortCompositionIntegrationTest.java @@ -203,27 +203,25 @@ void actualAbortExactRetryAndRestartRetainOriginalLeaseAndRejectTerminalRewrites "admission_lease_evidence = '{}'", "inventory_revision = inventory_revision - 1" }) { - assertThatThrownBy( - () -> - session - .gs - .dsl() - .execute( - "UPDATE game_session_canonical_binding_transition SET " - + assignment - + " WHERE transition_id = ?", - session.gs.transitionId())) + assertThatThrownBy(() -> + session + .gs + .dsl() + .execute( + "UPDATE game_session_canonical_binding_transition SET " + + assignment + + " WHERE transition_id = ?", + session.gs.transitionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(session.image()).isEqualTo(retainedImage); } - assertThatThrownBy( - () -> - session - .gs - .dsl() - .execute( - "UPDATE game_session_canonical_issuer_partition_reservation SET lifecycle = 'RELEASED' WHERE transition_id = ?", - session.gs.transitionId())) + assertThatThrownBy(() -> + session + .gs + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_partition_reservation SET lifecycle = 'RELEASED' WHERE transition_id = ?", + session.gs.transitionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(session.image()).isEqualTo(retainedImage); for (String statement : @@ -306,26 +304,24 @@ void actualConcurrentFinalizeAndAbortHaveOneAccountWinnerWithoutGsCommittedRelab var executor = Executors.newFixedThreadPool(2)) { var start = new CountDownLatch(1); var finalize = - executor.submit( - () -> { - start.await(); - try { - return session.client.finalizeLease( - session.jwt, session.leaseBytes(), session.gs.transitionId()); - } catch (RuntimeException ambiguous) { - return null; - } - }); + executor.submit(() -> { + start.await(); + try { + return session.client.finalizeLease( + session.jwt, session.leaseBytes(), session.gs.transitionId()); + } catch (RuntimeException ambiguous) { + return null; + } + }); var abort = - executor.submit( - () -> { - start.await(); - try { - return session.abort(); - } catch (RuntimeException ambiguous) { - return null; - } - }); + executor.submit(() -> { + start.await(); + try { + return session.abort(); + } catch (RuntimeException ambiguous) { + return null; + } + }); start.countDown(); var finalized = finalize.get(20, TimeUnit.SECONDS); var aborted = abort.get(20, TimeUnit.SECONDS); @@ -402,51 +398,47 @@ void actualAccountAbortedOrdinaryIssuerMemberReleaseHasExactReadbackRetryAndFree .isEqualTo(pending.sourceInventoryRevision()); String preparedImage = session.image(); - assertThatThrownBy( - () -> - session - .gs - .dsl() - .execute( - "UPDATE game_session_canonical_issuer_binding_local_release_operation" - + " SET original_member_value_bytes = ? WHERE operation_id = ?", - new byte[] {1}, - pending.operationId())) + assertThatThrownBy(() -> + session + .gs + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_binding_local_release_operation" + + " SET original_member_value_bytes = ? WHERE operation_id = ?", + new byte[] {1}, + pending.operationId())) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(session.image()).isEqualTo(preparedImage); - assertThatThrownBy( - () -> - session - .gs - .dsl() - .execute( - "UPDATE game_session_canonical_issuer_binding_local_release_operation" - + " SET original_reservation_fence = ? WHERE operation_id = ?", - UUID.randomUUID(), - pending.operationId())) + assertThatThrownBy(() -> + session + .gs + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_binding_local_release_operation" + + " SET original_reservation_fence = ? WHERE operation_id = ?", + UUID.randomUUID(), + pending.operationId())) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(session.image()).isEqualTo(preparedImage); - assertThatThrownBy( - () -> - session - .gs - .dsl() - .execute( - "UPDATE game_session_canonical_issuer_binding_local_release_operation" - + " SET anchor_operation_fence = anchor_operation_fence + 1 WHERE operation_id = ?", - pending.operationId())) + assertThatThrownBy(() -> + session + .gs + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_binding_local_release_operation" + + " SET anchor_operation_fence = anchor_operation_fence + 1 WHERE operation_id = ?", + pending.operationId())) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(session.image()).isEqualTo(preparedImage); - assertThatThrownBy( - () -> - session - .gs - .dsl() - .execute( - "UPDATE game_session_canonical_issuer_partition_reservation" - + " SET lifecycle = 'RELEASED', inventory_revision = inventory_revision + 1" - + " WHERE reservation_id = ?", - pending.abortSource().reservation().reservationId())) + assertThatThrownBy(() -> + session + .gs + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_partition_reservation" + + " SET lifecycle = 'RELEASED', inventory_revision = inventory_revision + 1" + + " WHERE reservation_id = ?", + pending.abortSource().reservation().reservationId())) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(session.image()).isEqualTo(preparedImage); @@ -599,12 +591,11 @@ void actualReverseReadRefusesWrongPeerDecisionAndChangedOriginalTupleWithoutAcco var changedLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(changedCarrier); assertThatThrownBy(() -> session.reverse.read(session.gs.transitionId(), changedLease)) .isInstanceOf(RuntimeException.class); - assertThatThrownBy( - () -> - session.client.abort( - session.jwt, - changedLease.canonicalJson().getBytes(StandardCharsets.UTF_8), - session.gs.transitionId())) + assertThatThrownBy(() -> + session.client.abort( + session.jwt, + changedLease.canonicalJson().getBytes(StandardCharsets.UTF_8), + session.gs.transitionId())) .isInstanceOf(RuntimeException.class); var endpoints = new ServiceEndpointsProperties(); endpoints.setGameSessionService("127.0.0.1:" + session.gsServer.getPort()); @@ -1018,205 +1009,203 @@ void verify(DriverManagerDataSource source) { } private static void seedControlledAcknowledgedAbort(DSLContext dsl) { - dsl.transaction( - configuration -> { - DSLContext tx = DSL.using(configuration); - tx.execute("UPDATE " + PREFIX + "binding_inventory_clock SET inventory_revision = 5"); - insert( - tx, - "account_coverage_control", - Map.of( - "account_id", - ACCOUNT, - "state", - "NO_ACTIVE_ACCOUNT_WIDE_FLOW", - "last_operation_fence", - 0)); - insert( - tx, - "account_member_repair_control", - Map.of( - "account_id", ACCOUNT, - "last_operation_fence", 1, - "last_coverage_generation", 3)); - Map candidate = new LinkedHashMap<>(); - candidate.put("binding_ref", BINDING_REF); - candidate.put("account_id", ACCOUNT); - candidate.put("tenant_id", TENANT); - candidate.put("playable_state_namespace_id", NAMESPACE); - candidate.put("character_id", CHARACTER); - candidate.put("playable_state_scope", "SHARED"); - candidate.put("game_instance_id", INSTANCE); - candidate.put("runtime_game_instance_id", 1L); - candidate.put("session_id", UUID.randomUUID().toString()); - candidate.put("binding_generation", 1); - candidate.put("region_id", REGION); - candidate.put("region_epoch", 1); - candidate.put("issuer_id", "firemud-account-service"); - candidate.put("issuer_auth_generation", 1); - candidate.put("issuer_index_layout_version", 1); - candidate.put("issuer_index_partition_count", 1); - candidate.put("issuer_index_partition_capacity", 3); - candidate.put("issuer_partition_id", 0); - candidate.put("account_index_fence", ACCOUNT_FENCE); - candidate.put("issuer_reservation_id", RESERVATION); - candidate.put("transition_id", TRANSITION); - candidate.put("lifecycle", "TERMINAL_UNRESOLVED"); - candidate.put("account_index_state", "ACKNOWLEDGED"); - candidate.put("issuer_index_state", "REPAIR_REQUIRED"); - candidate.put("inventory_revision", 5); - insert(tx, "gameplay_binding_inventory", candidate); + dsl.transaction(configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("UPDATE " + PREFIX + "binding_inventory_clock SET inventory_revision = 5"); + insert( + tx, + "account_coverage_control", + Map.of( + "account_id", + ACCOUNT, + "state", + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + "last_operation_fence", + 0)); + insert( + tx, + "account_member_repair_control", + Map.of( + "account_id", ACCOUNT, + "last_operation_fence", 1, + "last_coverage_generation", 3)); + Map candidate = new LinkedHashMap<>(); + candidate.put("binding_ref", BINDING_REF); + candidate.put("account_id", ACCOUNT); + candidate.put("tenant_id", TENANT); + candidate.put("playable_state_namespace_id", NAMESPACE); + candidate.put("character_id", CHARACTER); + candidate.put("playable_state_scope", "SHARED"); + candidate.put("game_instance_id", INSTANCE); + candidate.put("runtime_game_instance_id", 1L); + candidate.put("session_id", UUID.randomUUID().toString()); + candidate.put("binding_generation", 1); + candidate.put("region_id", REGION); + candidate.put("region_epoch", 1); + candidate.put("issuer_id", "firemud-account-service"); + candidate.put("issuer_auth_generation", 1); + candidate.put("issuer_index_layout_version", 1); + candidate.put("issuer_index_partition_count", 1); + candidate.put("issuer_index_partition_capacity", 3); + candidate.put("issuer_partition_id", 0); + candidate.put("account_index_fence", ACCOUNT_FENCE); + candidate.put("issuer_reservation_id", RESERVATION); + candidate.put("transition_id", TRANSITION); + candidate.put("lifecycle", "TERMINAL_UNRESOLVED"); + candidate.put("account_index_state", "ACKNOWLEDGED"); + candidate.put("issuer_index_state", "REPAIR_REQUIRED"); + candidate.put("inventory_revision", 5); + insert(tx, "gameplay_binding_inventory", candidate); - Map transition = new LinkedHashMap<>(); - transition.put("transition_id", TRANSITION); - transition.put("tenant_id", TENANT); - transition.put("playable_state_namespace_id", NAMESPACE); - transition.put("character_id", CHARACTER); - transition.put("candidate_binding_ref", BINDING_REF); - transition.put("candidate_binding_generation", 1); - transition.put("candidate_account_index_fence", ACCOUNT_FENCE); - transition.put("issuer_reservation_id", RESERVATION); - transition.put("status", "ABORTED"); - transition.put("inventory_revision", 5); - transition.put("admission_request_id", UUID.randomUUID()); - transition.put("admission_lease_id", UUID.randomUUID()); - transition.put("admission_lease_fence", 1); - transition.put("admission_lease_kind", "NEW_BINDING"); - transition.put("admission_lease_digest", RAW_DIGEST); - transition.put( - "admission_lease_evidence", "{\"controlledHistoricalAccountAbort\":true}"); - transition.put("admission_lease_expires_at", 1); - transition.put("admission_orphan_cleanup_id", UUID.randomUUID()); - transition.put("admission_target_namespace", "test"); - transition.put("admission_target_tenant_slug", "historical-tenant"); - transition.put("admission_target_tenant_id", TENANT); - transition.put("admission_target_world_slug", "historical-world"); - transition.put("admission_target_world_display_name", "Historical world"); - transition.put("admission_target_realm_id", UUID.randomUUID()); - transition.put("admission_target_realm_slug", "historical-realm"); - transition.put("admission_target_realm_display_name", "Historical realm"); - transition.put("admission_target_game_session_tenant_id", 1L); - transition.put("admission_target_game_instance_id", 1L); - transition.put("admission_target_playable_state_namespace_id", NAMESPACE); - transition.put("admission_target_playable_state_scope", "SHARED"); - transition.put("admission_target_canonical_game_instance_id", INSTANCE); - transition.put("admission_target_canonical_version_id", UUID.randomUUID()); - transition.put("admission_target_runtime_version_id", 1L); - transition.put("admission_target_catalog_revision", 1L); - transition.put("admission_target_pointer_version", 1L); - transition.put("admission_target_pointer_snapshot_digest", RAW_DIGEST); - transition.put("admission_target_active_world_epoch", 1L); - transition.put( - "admission_target_initial_admission_request_id", "controlled-historical-request"); - transition.put("admission_target_initial_admission_request_digest", RAW_DIGEST); - transition.put("admission_target_origin_kind", "NO_PRIOR_POINTER"); - transition.put("admission_target_hold_id", UUID.randomUUID()); - transition.put("admission_target_hold_fence", UUID.randomUUID()); - transition.put("admission_target_hold_binding_digest", DIGEST); - transition.put("admission_target_audit_event_id", 1L); - transition.put("admission_target_owner_proof_digest", DIGEST); - transition.put("admission_target_owner_proof_outcome", "COMMITTED"); - transition.put("admission_target_positive_durable_abort", false); - transition.put( - "admission_target_terminal_at", OffsetDateTime.parse("2026-10-26T00:00:00Z")); - transition.put("admission_target_character_creation_policy", "{}"); - insert(tx, "binding_transition", transition); + Map transition = new LinkedHashMap<>(); + transition.put("transition_id", TRANSITION); + transition.put("tenant_id", TENANT); + transition.put("playable_state_namespace_id", NAMESPACE); + transition.put("character_id", CHARACTER); + transition.put("candidate_binding_ref", BINDING_REF); + transition.put("candidate_binding_generation", 1); + transition.put("candidate_account_index_fence", ACCOUNT_FENCE); + transition.put("issuer_reservation_id", RESERVATION); + transition.put("status", "ABORTED"); + transition.put("inventory_revision", 5); + transition.put("admission_request_id", UUID.randomUUID()); + transition.put("admission_lease_id", UUID.randomUUID()); + transition.put("admission_lease_fence", 1); + transition.put("admission_lease_kind", "NEW_BINDING"); + transition.put("admission_lease_digest", RAW_DIGEST); + transition.put("admission_lease_evidence", "{\"controlledHistoricalAccountAbort\":true}"); + transition.put("admission_lease_expires_at", 1); + transition.put("admission_orphan_cleanup_id", UUID.randomUUID()); + transition.put("admission_target_namespace", "test"); + transition.put("admission_target_tenant_slug", "historical-tenant"); + transition.put("admission_target_tenant_id", TENANT); + transition.put("admission_target_world_slug", "historical-world"); + transition.put("admission_target_world_display_name", "Historical world"); + transition.put("admission_target_realm_id", UUID.randomUUID()); + transition.put("admission_target_realm_slug", "historical-realm"); + transition.put("admission_target_realm_display_name", "Historical realm"); + transition.put("admission_target_game_session_tenant_id", 1L); + transition.put("admission_target_game_instance_id", 1L); + transition.put("admission_target_playable_state_namespace_id", NAMESPACE); + transition.put("admission_target_playable_state_scope", "SHARED"); + transition.put("admission_target_canonical_game_instance_id", INSTANCE); + transition.put("admission_target_canonical_version_id", UUID.randomUUID()); + transition.put("admission_target_runtime_version_id", 1L); + transition.put("admission_target_catalog_revision", 1L); + transition.put("admission_target_pointer_version", 1L); + transition.put("admission_target_pointer_snapshot_digest", RAW_DIGEST); + transition.put("admission_target_active_world_epoch", 1L); + transition.put( + "admission_target_initial_admission_request_id", "controlled-historical-request"); + transition.put("admission_target_initial_admission_request_digest", RAW_DIGEST); + transition.put("admission_target_origin_kind", "NO_PRIOR_POINTER"); + transition.put("admission_target_hold_id", UUID.randomUUID()); + transition.put("admission_target_hold_fence", UUID.randomUUID()); + transition.put("admission_target_hold_binding_digest", DIGEST); + transition.put("admission_target_audit_event_id", 1L); + transition.put("admission_target_owner_proof_digest", DIGEST); + transition.put("admission_target_owner_proof_outcome", "COMMITTED"); + transition.put("admission_target_positive_durable_abort", false); + transition.put( + "admission_target_terminal_at", OffsetDateTime.parse("2026-10-26T00:00:00Z")); + transition.put("admission_target_character_creation_policy", "{}"); + insert(tx, "binding_transition", transition); - Map reservation = new LinkedHashMap<>(candidate); - reservation.remove("issuer_partition_id"); - reservation.remove("account_index_fence"); - reservation.remove("issuer_reservation_id"); - reservation.remove("account_index_state"); - reservation.remove("issuer_index_state"); - reservation.put("reservation_id", RESERVATION); - reservation.put("partition_id", 0); - reservation.put("lifecycle", "RELEASE_PENDING"); - reservation.put("reservation_fence", UUID.randomUUID()); - reservation.put("issuer_coverage_operation_id", UUID.randomUUID()); - reservation.put("issuer_coverage_operation_fence", 1); - reservation.put("coverage_fence", 1); - reservation.put("inventory_snapshot_revision", 1); - insert(tx, "issuer_partition_reservation", reservation); + Map reservation = new LinkedHashMap<>(candidate); + reservation.remove("issuer_partition_id"); + reservation.remove("account_index_fence"); + reservation.remove("issuer_reservation_id"); + reservation.remove("account_index_state"); + reservation.remove("issuer_index_state"); + reservation.put("reservation_id", RESERVATION); + reservation.put("partition_id", 0); + reservation.put("lifecycle", "RELEASE_PENDING"); + reservation.put("reservation_fence", UUID.randomUUID()); + reservation.put("issuer_coverage_operation_id", UUID.randomUUID()); + reservation.put("issuer_coverage_operation_fence", 1); + reservation.put("coverage_fence", 1); + reservation.put("inventory_snapshot_revision", 1); + insert(tx, "issuer_partition_reservation", reservation); - Map accountObligation = new LinkedHashMap<>(); - accountObligation.put("transition_id", TRANSITION); - accountObligation.put("obligation_ordinal", 0); - accountObligation.put("binding_ref", BINDING_REF); - accountObligation.put("account_id", ACCOUNT); - accountObligation.put("tenant_id", TENANT); - accountObligation.put("action", "ADD_OR_RETAIN"); - accountObligation.put("binding_generation", 1); - accountObligation.put("account_index_fence", ACCOUNT_FENCE); - accountObligation.put("execution_phase", "BEFORE_FINAL_CAS"); - accountObligation.put("status", "ACKNOWLEDGED"); - accountObligation.put("inventory_revision", 5); - accountObligation.put("projection_state", "PRESENT_AWAITING_COVERAGE"); - accountObligation.put("projection_member", MEMBER); - accountObligation.put("projection_inventory_revision", 4); - insert(tx, "binding_account_index_obligation", accountObligation); - insert( - tx, - "binding_issuer_index_obligation", - Map.of( - "transition_id", - TRANSITION, - "binding_ref", - BINDING_REF, - "binding_generation", - 1, - "reservation_id", - RESERVATION, - "status", - "REQUIRED", - "inventory_revision", - 5)); - Map region = new LinkedHashMap<>(); - for (String key : - List.of( - "transition_id", - "binding_ref", - "binding_generation", - "account_id", - "tenant_id", - "game_instance_id", - "runtime_game_instance_id", - "session_id", - "region_id", - "region_epoch", - "inventory_revision")) { - region.put(key, candidate.get(key)); - } - region.put("status", "REQUIRED"); - insert(tx, "binding_region_bridge_obligation", region); + Map accountObligation = new LinkedHashMap<>(); + accountObligation.put("transition_id", TRANSITION); + accountObligation.put("obligation_ordinal", 0); + accountObligation.put("binding_ref", BINDING_REF); + accountObligation.put("account_id", ACCOUNT); + accountObligation.put("tenant_id", TENANT); + accountObligation.put("action", "ADD_OR_RETAIN"); + accountObligation.put("binding_generation", 1); + accountObligation.put("account_index_fence", ACCOUNT_FENCE); + accountObligation.put("execution_phase", "BEFORE_FINAL_CAS"); + accountObligation.put("status", "ACKNOWLEDGED"); + accountObligation.put("inventory_revision", 5); + accountObligation.put("projection_state", "PRESENT_AWAITING_COVERAGE"); + accountObligation.put("projection_member", MEMBER); + accountObligation.put("projection_inventory_revision", 4); + insert(tx, "binding_account_index_obligation", accountObligation); + insert( + tx, + "binding_issuer_index_obligation", + Map.of( + "transition_id", + TRANSITION, + "binding_ref", + BINDING_REF, + "binding_generation", + 1, + "reservation_id", + RESERVATION, + "status", + "REQUIRED", + "inventory_revision", + 5)); + Map region = new LinkedHashMap<>(); + for (String key : + List.of( + "transition_id", + "binding_ref", + "binding_generation", + "account_id", + "tenant_id", + "game_instance_id", + "runtime_game_instance_id", + "session_id", + "region_id", + "region_epoch", + "inventory_revision")) { + region.put(key, candidate.get(key)); + } + region.put("status", "REQUIRED"); + insert(tx, "binding_region_bridge_obligation", region); - Map repair = new LinkedHashMap<>(); - repair.put("operation_id", UUID.randomUUID()); - repair.put("transition_id", TRANSITION); - repair.put("obligation_ordinal", 0); - repair.put("operation_fence", 1); - repair.put("coverage_fence", UUID.randomUUID()); - repair.put("inventory_snapshot_revision", 2); - repair.put("binding_ref", BINDING_REF); - repair.put("account_id", ACCOUNT); - repair.put("tenant_id", TENANT); - repair.put("binding_generation", 1); - repair.put("account_index_fence", ACCOUNT_FENCE); - repair.put("original_action", "ADD_OR_RETAIN"); - repair.put("original_execution_phase", "BEFORE_FINAL_CAS"); - repair.put("original_status", "REQUIRED"); - repair.put("original_inventory_revision", 1); - repair.put("original_projection_state", "REQUIRED"); - repair.put("desired_action", "ADD_OR_RETAIN"); - repair.put("member", MEMBER); - repair.put("account_control_state", "NO_ACTIVE_ACCOUNT_WIDE_FLOW"); - repair.put("account_control_epoch", 0); - repair.put("status", "ACKNOWLEDGED"); - repair.put("coverage_generation", 3); - repair.put("readback_state", "PRESENT"); - repair.put("readback_member", MEMBER); - repair.put("completed_inventory_revision", 4); - insert(tx, "account_member_repair_operation", repair); - }); + Map repair = new LinkedHashMap<>(); + repair.put("operation_id", UUID.randomUUID()); + repair.put("transition_id", TRANSITION); + repair.put("obligation_ordinal", 0); + repair.put("operation_fence", 1); + repair.put("coverage_fence", UUID.randomUUID()); + repair.put("inventory_snapshot_revision", 2); + repair.put("binding_ref", BINDING_REF); + repair.put("account_id", ACCOUNT); + repair.put("tenant_id", TENANT); + repair.put("binding_generation", 1); + repair.put("account_index_fence", ACCOUNT_FENCE); + repair.put("original_action", "ADD_OR_RETAIN"); + repair.put("original_execution_phase", "BEFORE_FINAL_CAS"); + repair.put("original_status", "REQUIRED"); + repair.put("original_inventory_revision", 1); + repair.put("original_projection_state", "REQUIRED"); + repair.put("desired_action", "ADD_OR_RETAIN"); + repair.put("member", MEMBER); + repair.put("account_control_state", "NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + repair.put("account_control_epoch", 0); + repair.put("status", "ACKNOWLEDGED"); + repair.put("coverage_generation", 3); + repair.put("readback_state", "PRESENT"); + repair.put("readback_member", MEMBER); + repair.put("completed_inventory_revision", 4); + insert(tx, "account_member_repair_operation", repair); + }); } private static void seedLaterControlledAcquisitionIntent(DSLContext dsl) { @@ -1255,14 +1244,13 @@ private static void seedLaterControlledAcquisitionIntent(DSLContext dsl) { } private static void advanceRetainedRevision(DSLContext dsl) { - dsl.transaction( - configuration -> { - DSLContext tx = DSL.using(configuration); - tx.execute("UPDATE " + PREFIX + "binding_inventory_clock SET inventory_revision = 6"); - for (String table : RETAINED_TABLES.subList(0, 6)) { - tx.execute("UPDATE " + PREFIX + table + " SET inventory_revision = 6"); - } - }); + dsl.transaction(configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("UPDATE " + PREFIX + "binding_inventory_clock SET inventory_revision = 6"); + for (String table : RETAINED_TABLES.subList(0, 6)) { + tx.execute("UPDATE " + PREFIX + table + " SET inventory_revision = 6"); + } + }); } private static Map> rows(DSLContext dsl, boolean immutableOnly) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionNeverAdmittedAbortCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionNeverAdmittedAbortCompositionIntegrationTest.java index 82301c4283..411fd2f0f9 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionNeverAdmittedAbortCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionNeverAdmittedAbortCompositionIntegrationTest.java @@ -203,10 +203,8 @@ void installedBootstrapNegativeCleanupResumesOriginalReleaseAndRetirementAfterLo session.gs.prepareIssuerRetirement(session.gs.transitionId()); assertThatThrownBy(() -> session.gs.projectOtherControllerNew("pending-bootstrap-cleanup")) .isInstanceOf(RuntimeException.class); - assertThatThrownBy( - () -> - session.gs.retireIssuerCapacityAndLoseReplyForTransition( - session.gs.transitionId())) + assertThatThrownBy(() -> + session.gs.retireIssuerCapacityAndLoseReplyForTransition(session.gs.transitionId())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("controlled lost retirement reply"); assertThat( @@ -279,10 +277,8 @@ void negativeCleanupOwnerResumesAfterCommittedRetirementReplyLoss(boolean instal session.gs.restoreIssuerState(); var release = session.gs.prepareIssuerRelease(); session.gs.completeIssuerRelease(release, session.gs.projectIssuerRelease(release)); - assertThatThrownBy( - () -> - session.gs.retireIssuerCapacityAndLoseReplyForTransition( - session.gs.transitionId())) + assertThatThrownBy(() -> + session.gs.retireIssuerCapacityAndLoseReplyForTransition(session.gs.transitionId())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("controlled lost retirement reply"); String history = session.issuerCleanupHistoryImage(); @@ -308,18 +304,16 @@ void neverAdmittedMissingQualificationChangedCredentialAndMismatchedAbandonmentR throws Exception { try (var session = openNeverAdmitted()) { String accountPending = session.accountOperationImage(); - assertThatThrownBy( - () -> - session.client.abortNeverAdmitted( - session.jwt, session.lease, session.gs.transitionId(), UUID.randomUUID())) + assertThatThrownBy(() -> + session.client.abortNeverAdmitted( + session.jwt, session.lease, session.gs.transitionId(), UUID.randomUUID())) .isInstanceOf(RuntimeException.class); assertThat(session.accountOperationImage()).isEqualTo(accountPending); - assertThatThrownBy( - () -> - session - .gs - .neverAdmittedOwner(session.client) - .abort(session.gs.transitionId(), "invalid-current-caller-token")) + assertThatThrownBy(() -> + session + .gs + .neverAdmittedOwner(session.client) + .abort(session.gs.transitionId(), "invalid-current-caller-token")) .isInstanceOf(RuntimeException.class); assertThat(session.accountOperationImage()).isEqualTo(accountPending); assertThat(session.gs.abandonmentSource().cleanupComplete()).isFalse(); @@ -352,13 +346,9 @@ void retainedNegativeSettlementResumesIssuerCleanupAfterPresentedCallerExpires( session.restartAccountAfterPresentedCallerExpiry(); // The actual receiving verifier now rejects the unchanged original signed JWT. - assertThatThrownBy( - () -> - session.client.abortNeverAdmitted( - session.jwt, - session.lease, - session.gs.transitionId(), - retained.abandonmentId())) + assertThatThrownBy(() -> + session.client.abortNeverAdmitted( + session.jwt, session.lease, session.gs.transitionId(), retained.abandonmentId())) .isInstanceOf(IllegalStateException.class); var expiredAccount = spy(session.client); var recreatedOwner = session.gs.neverAdmittedOwner(expiredAccount); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java index 66ed319edd..028f871aca 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameSessionOriginalNewFinalAdmissionCompositionIntegrationTest.java @@ -403,10 +403,9 @@ private CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.Receipt com } private Genesis genesis() { - return serializable.execute( - status -> - new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) - .readByLease(UUID.fromString((String) lease.carrier().get("leaseId")))); + return serializable.execute(status -> + new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) + .readByLease(UUID.fromString((String) lease.carrier().get("leaseId")))); } private String durableImage() { 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 a36e2e21ba..427c0b614c 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 @@ -367,10 +367,9 @@ void authenticatedAccountOwnerAcquiresAndRetriesTheExactRecoveredAccountToken() requestId, originalJwt, mismatchedCaller, target, BigInteger.ONE); assertThatThrownBy(() -> withPeer(peer, () -> owner.acquire(mismatchedRequest))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); + .satisfies(failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); assertThat(fixture.leaseAllocationState(originalRequestId, accountId)) .isEqualTo(allocationAfterFirst); assertThat(fixture.sourceAndIssuanceImageForAuthenticatedAcquire()) @@ -400,10 +399,9 @@ void authenticatedAccountOwnerAcquiresAndRetriesTheExactRecoveredAccountToken() originalJwt, originalBytes, UUID.randomUUID()); assertThatThrownBy(() -> withPeer(peer, () -> owner.finalizeLease(finalizeWire))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); + .satisfies(failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); assertThat(fixture.readLeaseOperation(originalLease).state()) .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.PENDING); @@ -529,29 +527,25 @@ void authenticatedMtlsOwnerComposesAllFourRpcMethodsWithOriginalCommitAndAck() t var sourceImageBeforeAnyRpc = fixture.sourceAndIssuanceImageForAuthenticatedAcquire(); var allocatorBeforeAnyRpc = fixture.leaseAllocationState(accountRequestId, accountId); assertThat(allocatorBeforeAnyRpc).isEqualTo(new LeaseAllocationState(0L, 0L, null, null)); - assertThatThrownBy( - () -> - wrongRoleStub - .withDeadlineAfter(5, TimeUnit.SECONDS) - .acquireGameplayAdmissionLease( - AcquireGameplayAdmissionLeaseRequest.getDefaultInstance())) + assertThatThrownBy(() -> + wrongRoleStub + .withDeadlineAfter(5, TimeUnit.SECONDS) + .acquireGameplayAdmissionLease( + AcquireGameplayAdmissionLeaseRequest.getDefaultInstance())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); - assertThatThrownBy( - () -> - ClientCalls.blockingUnaryCall( - wrongRoleStub.getChannel(), - malformedAcquireMethod(), - wrongRoleStub.getCallOptions().withDeadlineAfter(5, TimeUnit.SECONDS), - new byte[] {0x0f})) + .satisfies(failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + assertThatThrownBy(() -> + ClientCalls.blockingUnaryCall( + wrongRoleStub.getChannel(), + malformedAcquireMethod(), + wrongRoleStub.getCallOptions().withDeadlineAfter(5, TimeUnit.SECONDS), + new byte[] {0x0f})) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); assertThat(fixture.leaseOperationCount()).isZero(); assertThat(fixture.leaseAllocationState(accountRequestId, accountId)) .isEqualTo(allocatorBeforeAnyRpc); @@ -823,22 +817,19 @@ void authenticatedMtlsOwnerComposesAllFourRpcMethodsWithOriginalCommitAndAck() t TokenIdentity tokenIdentity = fixture.tokenIdentity(fixture.committedCandidate); UUID revocationRequestId = UUID.randomUUID(); - fixture.inSerializableTransaction( - () -> - fixture.tokenFences.beginRevocationIntent( - tokenIdentity, - revocationRequestId, - AccountGameplayTokenIdentityFenceRepository.revocationDigest( - tokenIdentity, revocationRequestId))); - assertThatThrownBy( - () -> - stub.withDeadlineAfter(5, TimeUnit.SECONDS) - .finalizeGameplayAdmissionLease(abortFinalizeWire)) + fixture.inSerializableTransaction(() -> + fixture.tokenFences.beginRevocationIntent( + tokenIdentity, + revocationRequestId, + AccountGameplayTokenIdentityFenceRepository.revocationDigest( + tokenIdentity, revocationRequestId))); + assertThatThrownBy(() -> + stub.withDeadlineAfter(5, TimeUnit.SECONDS) + .finalizeGameplayAdmissionLease(abortFinalizeWire)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); + .satisfies(failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); assertThat(abortDecisionReads.get()).isZero(); assertThat(fixture.readLeaseOperation(abortedLease)).isEqualTo(retainedAbortBeforeFinalize); assertThat(fixture.leaseOperationCount()).isEqualTo(operationCountBeforeAbortFinalize); @@ -882,25 +873,23 @@ void tenantEntitlementWriterWaitsForCurrentSourceLocksUntilOriginalPhysicalCommi try { Future originalCommit = - executor.submit( - () -> - new AccountGameplayAdmissionOriginalCommitExecutor(commitBarrierDataSource) - .executeWithCurrentSources( - prepared.lease(), decisionId, TEST_NAMESPACE, prepared.candidate())); + executor.submit(() -> + new AccountGameplayAdmissionOriginalCommitExecutor(commitBarrierDataSource) + .executeWithCurrentSources( + prepared.lease(), decisionId, TEST_NAMESPACE, prepared.candidate())); assertThat(originalCommitReached.await(5, TimeUnit.SECONDS)).isTrue(); assertThat(originalBackendPid.get()).isPositive(); Future tenantWriter = - executor.submit( - () -> { - writerStarted.countDown(); - try { - fixture.disableTenantGameplay(currentEntitlement); - return null; - } finally { - writerCompleted.countDown(); - } - }); + executor.submit(() -> { + writerStarted.countDown(); + try { + fixture.disableTenantGameplay(currentEntitlement); + return null; + } finally { + writerCompleted.countDown(); + } + }); assertThat(writerStarted.await(5, TimeUnit.SECONDS)).isTrue(); int blockedWriterPid = @@ -956,32 +945,28 @@ void accountAuthorityWriterWaitsForOriginalPhysicalCommitAndInvalidatesOldLease( try { Future originalCommit = - executor.submit( - () -> - new AccountGameplayAdmissionOriginalCommitExecutor(commitBarrierDataSource) - .executeWithCurrentSources( - prepared.lease(), decisionId, TEST_NAMESPACE, prepared.candidate())); + executor.submit(() -> + new AccountGameplayAdmissionOriginalCommitExecutor(commitBarrierDataSource) + .executeWithCurrentSources( + prepared.lease(), decisionId, TEST_NAMESPACE, prepared.candidate())); assertThat(originalCommitReached.await(5, TimeUnit.SECONDS)).isTrue(); assertThat(originalBackendPid.get()).isPositive(); Future accountWriter = - executor.submit( - () -> { - writerStarted.countDown(); - try { - fixture.inSerializableTransaction( - () -> { - Account updated = - fixture.accounts.findById(fixture.account.getId()).orElseThrow(); - updated.setPasswordHash("authority-writer-updated-password-hash"); - fixture.accounts.save(updated); - return null; - }); - return null; - } finally { - writerCompleted.countDown(); - } + executor.submit(() -> { + writerStarted.countDown(); + try { + fixture.inSerializableTransaction(() -> { + Account updated = fixture.accounts.findById(fixture.account.getId()).orElseThrow(); + updated.setPasswordHash("authority-writer-updated-password-hash"); + fixture.accounts.save(updated); + return null; }); + return null; + } finally { + writerCompleted.countDown(); + } + }); assertThat(writerStarted.await(5, TimeUnit.SECONDS)).isTrue(); int blockedWriterPid = @@ -1042,32 +1027,29 @@ void tokenRevocationWriterWaitsForOriginalPhysicalCommitAndInvalidatesOldLease() try { Future originalCommit = - executor.submit( - () -> - new AccountGameplayAdmissionOriginalCommitExecutor(commitBarrierDataSource) - .executeWithCurrentSources( - prepared.lease(), decisionId, TEST_NAMESPACE, prepared.candidate())); + executor.submit(() -> + new AccountGameplayAdmissionOriginalCommitExecutor(commitBarrierDataSource) + .executeWithCurrentSources( + prepared.lease(), decisionId, TEST_NAMESPACE, prepared.candidate())); assertThat(originalCommitReached.await(5, TimeUnit.SECONDS)).isTrue(); assertThat(originalBackendPid.get()).isPositive(); Future tokenWriter = - executor.submit( - () -> { - writerStarted.countDown(); - try { - revocation.set( - fixture.inSerializableTransaction( - () -> - fixture.tokenFences.beginRevocationIntent( - identity, - revocationRequestId, - AccountGameplayTokenIdentityFenceRepository.revocationDigest( - identity, revocationRequestId)))); - return null; - } finally { - writerCompleted.countDown(); - } - }); + executor.submit(() -> { + writerStarted.countDown(); + try { + revocation.set( + fixture.inSerializableTransaction(() -> + fixture.tokenFences.beginRevocationIntent( + identity, + revocationRequestId, + AccountGameplayTokenIdentityFenceRepository.revocationDigest( + identity, revocationRequestId)))); + return null; + } finally { + writerCompleted.countDown(); + } + }); assertThat(writerStarted.await(5, TimeUnit.SECONDS)).isTrue(); int blockedWriterPid = @@ -1120,11 +1102,10 @@ void tenantEntitlementOwnerUpdateRefusesRetainedOriginalLeaseWithoutChangingIssu assertThat(disabled.gameplayAvailable()).isFalse(); assertThat(disabled.allowNewGameplayBindings()).isFalse(); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalCommitExecutor(fixture.dataSource) - .executeWithCurrentSources( - prepared.lease(), UUID.randomUUID(), TEST_NAMESPACE, prepared.candidate())) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalCommitExecutor(fixture.dataSource) + .executeWithCurrentSources( + prepared.lease(), UUID.randomUUID(), TEST_NAMESPACE, prepared.candidate())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("membership source tenantAuthorityGeneration current equality"); @@ -1144,22 +1125,20 @@ void changedSqlTokenIdentityFenceRefusesRetainedOriginalLeaseAndCommittedCandida TokenIdentity identity = fixture.tokenIdentity(prepared.candidate()); UUID revocationRequestId = UUID.randomUUID(); var pendingRevocation = - fixture.inSerializableTransaction( - () -> - fixture.tokenFences.beginRevocationIntent( - identity, - revocationRequestId, - AccountGameplayTokenIdentityFenceRepository.revocationDigest( - identity, revocationRequestId))); + fixture.inSerializableTransaction(() -> + fixture.tokenFences.beginRevocationIntent( + identity, + revocationRequestId, + AccountGameplayTokenIdentityFenceRepository.revocationDigest( + identity, revocationRequestId))); assertThat(pendingRevocation.state()) .isEqualTo(AccountGameplayTokenIdentityFence.State.PENDING); assertThat(pendingRevocation.tokenIdentityFence()).isEqualTo(2L); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalCommitExecutor(fixture.dataSource) - .executeWithCurrentSources( - prepared.lease(), UUID.randomUUID(), TEST_NAMESPACE, prepared.candidate())) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalCommitExecutor(fixture.dataSource) + .executeWithCurrentSources( + prepared.lease(), UUID.randomUUID(), TEST_NAMESPACE, prepared.candidate())) .isInstanceOf(IllegalStateException.class); assertThat(fixture.readCandidateRow(prepared.candidate())) @@ -1219,19 +1198,17 @@ void unknownAbortResolutionPreservesPopulatedTerminalAndReplaysWithoutReverseRea new Object[] {leaseId, fence + 1, digest, cleanupId}, new Object[] {leaseId, fence, "0".repeat(64), cleanupId}, new Object[] {leaseId, fence, digest, UUID.randomUUID()})) { - assertThatThrownBy( - () -> - fixture.inSerializableTransaction( - () -> - fixture.dsl.execute( - insertion, - requestId, - UUID.randomUUID(), - changed[0], - changed[1], - changed[2], - changed[3], - decisionId))) + assertThatThrownBy(() -> + fixture.inSerializableTransaction(() -> + fixture.dsl.execute( + insertion, + requestId, + UUID.randomUUID(), + changed[0], + changed[1], + changed[2], + changed[3], + decisionId))) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("Exact original unknown-decision abort linkage required"); } @@ -1248,11 +1225,10 @@ void unknownAbortResolutionPreservesPopulatedTerminalAndReplaysWithoutReverseRea assertThat(first.get().getBindingDecisionUuidCount()).isZero(); assertThat(first.get().getOrphanCleanupUuidList()).containsExactly(cleanupId.toString()); var retained = - fixture.inSerializableTransaction( - () -> - new AccountGameplayAdmissionAbortResolutionRepository(fixture.dsl) - .readExact(prepared.lease(), cleanupId, decisionId) - .orElseThrow()); + fixture.inSerializableTransaction(() -> + new AccountGameplayAdmissionAbortResolutionRepository(fixture.dsl) + .readExact(prepared.lease(), cleanupId, decisionId) + .orElseThrow()); assertThat(retained) .isEqualTo( new AccountGameplayAdmissionAbortResolution( @@ -1346,13 +1322,12 @@ void unknownAbortResolutionRefusesUnknownReverseReadAndCallerMovementWithoutWrit assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); TokenIdentity token = fixture.tokenIdentity(fixture.committedCandidate); UUID revocation = UUID.randomUUID(); - fixture.inSerializableTransaction( - () -> - fixture.tokenFences.beginRevocationIntent( - token, - revocation, - AccountGameplayTokenIdentityFenceRepository.revocationDigest( - token, revocation))); + fixture.inSerializableTransaction(() -> + fixture.tokenFences.beginRevocationIntent( + token, + revocation, + AccountGameplayTokenIdentityFenceRepository.revocationDigest( + token, revocation))); callerMovementReached.set(true); return decision; }) @@ -1865,28 +1840,25 @@ private static void controlProvisionalDecisionRead( Candidate candidate, Target target) { when(decisionClient.read(any(), any())) - .thenAnswer( - invocation -> { - UUID decisionId = invocation.getArgument(0); - AccountGameplayAdmissionLeaseEvidence expectedLease = invocation.getArgument(1); - var wireRead = - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toRequest( - decisionId, expectedLease); - var parsedRead = - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(wireRead); - var controlledWireEvidence = - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toResponse( - parsedRead, - decisionId, - expectedLease, - BigInteger.ONE, - null, - null, - candidate, - target); - return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromResponse( - parsedRead, controlledWireEvidence); - }); + .thenAnswer(invocation -> { + UUID decisionId = invocation.getArgument(0); + AccountGameplayAdmissionLeaseEvidence expectedLease = invocation.getArgument(1); + var wireRead = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toRequest(decisionId, expectedLease); + var parsedRead = CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(wireRead); + var controlledWireEvidence = + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toResponse( + parsedRead, + decisionId, + expectedLease, + BigInteger.ONE, + null, + null, + candidate, + target); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromResponse( + parsedRead, controlledWireEvidence); + }); } private static MethodDescriptor @@ -1926,12 +1898,11 @@ private static Map expectedLeaseSourceFields( Optional accountCutoff = tuple .accountSecurityCutoff() - .map( - cutoff -> - new AccountSecurityCutoff( - cutoff.accountAuthorityGeneration(), - cutoff.outboxStreamKey(), - cutoff.outboxSequence())); + .map(cutoff -> + new AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence())); Map authorityTuple = new LinkedHashMap<>( GameSessionAccountDelegationProfile.authorityTuple( @@ -1943,20 +1914,18 @@ private static Map expectedLeaseSourceFields( authorityTuple.put("privateRealmGrantVersions", tuple.privateRealmGrantVersions()); tuple .tenantBillingCutoff() - .ifPresent( - cutoffs -> { - Map mapped = new LinkedHashMap<>(); - cutoffs.forEach( - (tenantId, cutoff) -> - mapped.put( - tenantId, - Map.of( - "tenantAuthorityGeneration", cutoff.tenantAuthorityGeneration(), - "tenantBillingSequence", cutoff.tenantBillingSequence(), - "outboxStreamKey", cutoff.outboxStreamKey(), - "outboxSequence", cutoff.outboxSequence()))); - authorityTuple.put("tenantBillingCutoff", Map.copyOf(mapped)); - }); + .ifPresent(cutoffs -> { + Map mapped = new LinkedHashMap<>(); + cutoffs.forEach((tenantId, cutoff) -> + mapped.put( + tenantId, + Map.of( + "tenantAuthorityGeneration", cutoff.tenantAuthorityGeneration(), + "tenantBillingSequence", cutoff.tenantBillingSequence(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence()))); + authorityTuple.put("tenantBillingCutoff", Map.copyOf(mapped)); + }); Map membershipBaseline = Map.of( @@ -1965,11 +1934,10 @@ private static Map expectedLeaseSourceFields( "membershipAuthorityGeneration", snapshot.membershipAuthorityGeneration()); List> outboxCheckpoints = snapshot.checkpoints().stream() - .map( - checkpoint -> - Map.of( - "outboxStreamKey", checkpoint.outboxStreamKey(), - "outboxSequence", checkpoint.outboxSequence())) + .map(checkpoint -> + Map.of( + "outboxStreamKey", checkpoint.outboxStreamKey(), + "outboxSequence", checkpoint.outboxSequence())) .toList(); TokenIdentity tokenIdentity = fixture.tokenIdentity(candidate); var activeFence = fixture.tokenFences.requireActiveReadback(tokenIdentity); @@ -2157,10 +2125,9 @@ private Fixture( new AccountAuthEvidenceBundleRepository(dsl, generations, authorityOutbox); this.issuance = new AccountGameplayDelegationIssuanceRepository(dsl, sourceEvidence, bundles); this.issuanceSource = - transaction.execute( - status -> - sourceEvidence.readCurrentIssuerAccountSources( - ACCOUNT_ISSUER, account.getAccountUuid())); + transaction.execute(status -> + sourceEvidence.readCurrentIssuerAccountSources( + ACCOUNT_ISSUER, account.getAccountUuid())); this.committedCandidate = createCommittedIssuanceCandidate(bundles, redisClient); } @@ -2171,13 +2138,11 @@ CanonicalJoinScopeV2 playerEntitlementScope() { void beginPlayerEntitlementLoginRevocation() { var identity = tokenIdentity(committedCandidate); UUID requestId = UUID.randomUUID(); - transaction.execute( - status -> - tokenFences.beginRevocationIntent( - identity, - requestId, - AccountGameplayTokenIdentityFenceRepository.revocationDigest( - identity, requestId))); + transaction.execute(status -> + tokenFences.beginRevocationIntent( + identity, + requestId, + AccountGameplayTokenIdentityFenceRepository.revocationDigest(identity, requestId))); } net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner @@ -2221,36 +2186,31 @@ void beginPlayerEntitlementLoginRevocation() { private void establishTenantEntitlementAndMembership( AccountConnectScopeRepository connectScopes) { - transaction.execute( - status -> { - freshTenants.importVerified(tenantEvidence); - sourceEvidence.initializeIssuerIfAbsent(ACCOUNT_ISSUER); - generations.initializeTenantIfAbsent(tenantUuid); - generations.initialize(AuthorityScope.membership(account.getAccountUuid(), tenantUuid)); - connectScopes.insertCanonical(account.getId(), joinScope, tenantProvenance); - joinOperations.insertCanonicalIntent( - joinRequestId.toString(), joinScope, callerBinding); - return null; - }); + transaction.execute(status -> { + freshTenants.importVerified(tenantEvidence); + sourceEvidence.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + generations.initializeTenantIfAbsent(tenantUuid); + generations.initialize(AuthorityScope.membership(account.getAccountUuid(), tenantUuid)); + connectScopes.insertCanonical(account.getId(), joinScope, tenantProvenance); + joinOperations.insertCanonicalIntent(joinRequestId.toString(), joinScope, callerBinding); + return null; + }); DemoTenantEntitlementSnapshot entitlement = - transaction.execute( - status -> - demoEntitlements.provision( - AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest - .entitlementRequest(tenantUuid, tenantEvidence), - tenantEvidence)); - transaction.execute( - status -> { - joinOperations.bindCanonicalPolicyEvidence( - joinRequestId.toString(), - joinScope, - callerBinding, - entitlement.allowPublicJoin(), - entitlement.entitlementVersion()); - joinTerminal.commitCanonicalFirstJoin( - joinScope, joinRequestId.toString(), callerBinding); - return null; - }); + transaction.execute(status -> + demoEntitlements.provision( + AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.entitlementRequest( + tenantUuid, tenantEvidence), + tenantEvidence)); + transaction.execute(status -> { + joinOperations.bindCanonicalPolicyEvidence( + joinRequestId.toString(), + joinScope, + callerBinding, + entitlement.allowPublicJoin(), + entitlement.entitlementVersion()); + joinTerminal.commitCanonicalFirstJoin(joinScope, joinRequestId.toString(), callerBinding); + return null; + }); } private CommittedCandidateVerificationData createCommittedIssuanceCandidate( @@ -2262,12 +2222,11 @@ private CommittedCandidateVerificationData createCommittedIssuanceCandidate( issuanceSource .account() .accountSecurityCutoff() - .map( - value -> - new AccountSecurityCutoff( - value.accountAuthorityGeneration(), - value.outboxStreamKey(), - value.outboxSequence())); + .map(value -> + new AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())); UUID operationId = UUID.randomUUID(); UUID requestId = UUID.randomUUID(); UUID callerContextId = UUID.randomUUID(); @@ -2358,41 +2317,39 @@ private CommittedCandidateVerificationData createCommittedIssuanceCandidate( private AccountGameplayAdmissionCurrentSources.Current readCurrent( CommittedCandidateVerificationData expectedCandidate) { - return serializable.execute( - status -> { - if (!TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isCurrentTransactionReadOnly() - || !Integer.valueOf(Connection.TRANSACTION_SERIALIZABLE) - .equals( - TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { - throw new IllegalStateException("Expected writable SERIALIZABLE Account transaction"); - } - Object resource = TransactionSynchronizationManager.getResource(dataSource); - if (!(resource instanceof ConnectionHolder holder)) { - throw new IllegalStateException("Expected the manager-enlisted Account connection"); - } - Connection connection = holder.getConnection(); - DSLContext exactDsl = DSL.using(connection, SQLDialect.POSTGRES); - 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); - Integer backendAfter = - exactDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class); - assertThat(backendAfter).isEqualTo(backendBefore); - assertThat(connection.getAutoCommit()).isFalse(); - assertThat(connection.isReadOnly()).isFalse(); - assertThat(connection.getTransactionIsolation()) - .isEqualTo(Connection.TRANSACTION_SERIALIZABLE); - return current; - } catch (SQLException failure) { - throw new IllegalStateException( - "Could not verify the enlisted Account connection", failure); - } - }); + return serializable.execute(status -> { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Integer.valueOf(Connection.TRANSACTION_SERIALIZABLE) + .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { + throw new IllegalStateException("Expected writable SERIALIZABLE Account transaction"); + } + Object resource = TransactionSynchronizationManager.getResource(dataSource); + if (!(resource instanceof ConnectionHolder holder)) { + throw new IllegalStateException("Expected the manager-enlisted Account connection"); + } + Connection connection = holder.getConnection(); + DSLContext exactDsl = DSL.using(connection, SQLDialect.POSTGRES); + 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); + Integer backendAfter = + exactDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class); + assertThat(backendAfter).isEqualTo(backendBefore); + assertThat(connection.getAutoCommit()).isFalse(); + assertThat(connection.isReadOnly()).isFalse(); + assertThat(connection.getTransactionIsolation()) + .isEqualTo(Connection.TRANSACTION_SERIALIZABLE); + return current; + } catch (SQLException failure) { + throw new IllegalStateException( + "Could not verify the enlisted Account connection", failure); + } + }); } private PreparedAdmission prepareAdmission() { @@ -2403,30 +2360,29 @@ private PreparedAdmission prepareAdmission() { private AccountGameplayAdmissionLeaseEvidence beginPendingAdmissionLease( AccountGameplayAdmissionCurrentSources.Current current) { - return inSerializableTransaction( - () -> { - UUID requestId = UUID.randomUUID(); - UUID leaseId = UUID.randomUUID(); - var allocation = leases.allocate(account.getAccountUuid(), requestId, leaseId); - long evaluatedAt = currentDatabaseMillisOnEnlistedConnection(); - Map carrier = new LinkedHashMap<>(); - carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); - carrier.put("schemaVersion", "1"); - carrier.put("mode", "PUBLIC_PRODUCTION"); - carrier.put("targetNamespace", TEST_NAMESPACE); - carrier.put("callerWorkload", CALLER_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", bindingScope()); - carrier.putAll(current.leaseSourceFields()); - carrier.put("evaluatedAt", Long.toString(evaluatedAt)); - carrier.put("expiresAt", Long.toString(evaluatedAt + 14_000L)); - var evidence = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); - leases.beginPending(evidence); - return evidence; - }); + return inSerializableTransaction(() -> { + UUID requestId = UUID.randomUUID(); + UUID leaseId = UUID.randomUUID(); + var allocation = leases.allocate(account.getAccountUuid(), requestId, leaseId); + long evaluatedAt = currentDatabaseMillisOnEnlistedConnection(); + Map carrier = new LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("targetNamespace", TEST_NAMESPACE); + carrier.put("callerWorkload", CALLER_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", bindingScope()); + carrier.putAll(current.leaseSourceFields()); + carrier.put("evaluatedAt", Long.toString(evaluatedAt)); + carrier.put("expiresAt", Long.toString(evaluatedAt + 14_000L)); + var evidence = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + leases.beginPending(evidence); + return evidence; + }); } private Map bindingScope() { @@ -2449,11 +2405,10 @@ private Map bindingScope() { } private CommittedCandidateVerificationData readCommittedCandidate() { - return transaction.execute( - status -> - issuance - .readCurrentCommittedCandidateByJti(committedCandidate.identity().tokenJti()) - .orElseThrow()); + return transaction.execute(status -> + issuance + .readCurrentCommittedCandidateByJti(committedCandidate.identity().tokenJti()) + .orElseThrow()); } private TokenIdentity tokenIdentity(CommittedCandidateVerificationData candidate) { @@ -2493,14 +2448,13 @@ private void disableTenantGameplay(DemoTenantEntitlementSnapshot current) { private AccountGameplayAdmissionLeaseOperation readLeaseOperation( AccountGameplayAdmissionLeaseEvidence evidence) { - return inSerializableTransaction( - () -> - leases - .findByRequest( - account.getAccountUuid(), - UUID.fromString((String) evidence.carrier().get("requestId")), - CALLER_WORKLOAD) - .orElseThrow()); + return inSerializableTransaction(() -> + leases + .findByRequest( + account.getAccountUuid(), + UUID.fromString((String) evidence.carrier().get("requestId")), + CALLER_WORKLOAD) + .orElseThrow()); } private CandidateRow readCandidateRow(CommittedCandidateVerificationData candidate) { @@ -2617,22 +2571,20 @@ private List sourceAndIssuanceImage() { /** Adds only the two legitimate allocator-table exclusions to the original strict image. */ private List sourceAndIssuanceImageForAuthenticatedAcquire() { return sourceAndIssuanceImage().stream() - .filter( - tableImage -> - !tableImage.startsWith("account_gameplay_admission_lease_allocations:") - && !tableImage.startsWith("account_gameplay_admission_lease_fences:")) + .filter(tableImage -> + !tableImage.startsWith("account_gameplay_admission_lease_allocations:") + && !tableImage.startsWith("account_gameplay_admission_lease_fences:")) .toList(); } /** Also excludes only the durable ACK table legitimately written by fresh finalization. */ private List sourceAndIssuanceImageForAuthenticatedCommit() { return sourceAndIssuanceImage().stream() - .filter( - tableImage -> - !tableImage.startsWith("account_gameplay_admission_lease_allocations:") - && !tableImage.startsWith("account_gameplay_admission_lease_fences:") - && !tableImage.startsWith( - "account_gameplay_admission_original_commit_ack_receipts:")) + .filter(tableImage -> + !tableImage.startsWith("account_gameplay_admission_lease_allocations:") + && !tableImage.startsWith("account_gameplay_admission_lease_fences:") + && !tableImage.startsWith( + "account_gameplay_admission_original_commit_ack_receipts:")) .toList(); } @@ -3014,45 +2966,43 @@ private RedisHarness( .thenAnswer(invocation -> sha1(invocation.getArgument(0))); when(commands.evalsha( anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) - .thenAnswer( - invocation -> { - byte[][] keys = (byte[][]) invocation.getRawArguments()[2]; - byte[][] arguments = (byte[][]) invocation.getRawArguments()[3]; - String key = new String(keys[0], StandardCharsets.US_ASCII); - if (key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { - if (arguments.length == 2) pendingRecord.set(arguments[0].clone()); - else if (arguments.length == 3) pendingRecord.set(arguments[1].clone()); - else throw new AssertionError("Unexpected token registry script arguments"); - absoluteExpiryMillis.set( - Long.parseLong( - new String(arguments[arguments.length - 1], StandardCharsets.US_ASCII))); - } else if (key.equals( - AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX - + GameSessionAccountDelegationProfile.ISSUER)) { - authorityProjectionBytes[0] = arguments[0].clone(); - } else if (key.equals( - AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId)) { - if (arguments.length == 3 && arguments[2].length > 0) { - authorityProjectionBytes[1] = arguments[2].clone(); - } - } - return 1L; - }); + .thenAnswer(invocation -> { + byte[][] keys = (byte[][]) invocation.getRawArguments()[2]; + byte[][] arguments = (byte[][]) invocation.getRawArguments()[3]; + String key = new String(keys[0], StandardCharsets.US_ASCII); + if (key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { + if (arguments.length == 2) pendingRecord.set(arguments[0].clone()); + else if (arguments.length == 3) pendingRecord.set(arguments[1].clone()); + else throw new AssertionError("Unexpected token registry script arguments"); + absoluteExpiryMillis.set( + Long.parseLong( + new String(arguments[arguments.length - 1], StandardCharsets.US_ASCII))); + } else if (key.equals( + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER)) { + authorityProjectionBytes[0] = arguments[0].clone(); + } else if (key.equals( + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId)) { + if (arguments.length == 3 && arguments[2].length > 0) { + authorityProjectionBytes[1] = arguments[2].clone(); + } + } + return 1L; + }); when(commands.get(any(byte[].class))) - .thenAnswer( - invocation -> { - String key = new String(invocation.getArgument(0), StandardCharsets.US_ASCII); - if (key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { - byte[] value = pendingRecord.get(); - return value == null ? null : value.clone(); - } - if ((AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX - + GameSessionAccountDelegationProfile.ISSUER) - .equals(key)) return authorityProjectionBytes[0].clone(); - if ((AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId) - .equals(key)) return authorityProjectionBytes[1].clone(); - return null; - }); + .thenAnswer(invocation -> { + String key = new String(invocation.getArgument(0), StandardCharsets.US_ASCII); + if (key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { + byte[] value = pendingRecord.get(); + return value == null ? null : value.clone(); + } + if ((AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER) + .equals(key)) return authorityProjectionBytes[0].clone(); + if ((AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId) + .equals(key)) return authorityProjectionBytes[1].clone(); + return null; + }); when(commands.pexpiretime(any(byte[].class))) .thenAnswer(invocation -> absoluteExpiryMillis.get()); when(commands.pttl(any(byte[].class))).thenReturn(-1L); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java index 546b3af7e3..c4e95feb09 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java @@ -74,62 +74,54 @@ void neverAdmittedResolutionPreservesOriginalTerminalAndRejectsPositivePurposeRe UUID abandonment = UUID.randomUUID(); context .transaction() - .executeWithoutResult( - status -> - new AccountGameplayAdmissionLeaseRepository(context.dsl()) - .recordAborted(lease, null, cleanup)); + .executeWithoutResult(status -> + new AccountGameplayAdmissionLeaseRepository(context.dsl()) + .recordAborted(lease, null, cleanup)); var terminal = operation(context, lease); var repository = new AccountGameplayAdmissionAbortResolutionRepository(context.dsl()); var resolution = context .transaction() - .execute( - status -> - repository.recordOrReplayNeverAdmitted( - lease, cleanup, transition, abandonment, "a".repeat(64), "b".repeat(64))); + .execute(status -> + repository.recordOrReplayNeverAdmitted( + lease, cleanup, transition, abandonment, "a".repeat(64), "b".repeat(64))); var retry = context .transaction() - .execute( - status -> - repository.recordOrReplayNeverAdmitted( - lease, cleanup, transition, abandonment, "a".repeat(64), "b".repeat(64))); + .execute(status -> + repository.recordOrReplayNeverAdmitted( + lease, cleanup, transition, abandonment, "a".repeat(64), "b".repeat(64))); assertThat(retry).isEqualTo(resolution); assertThat(operation(context, lease)).isEqualTo(terminal); assertThat(resolution.bindingDecisionId()).isNull(); assertThat(resolution.orphanCleanupId()).isEqualTo(cleanup); - assertThatThrownBy( - () -> - context - .transaction() - .execute(status -> repository.readExact(lease, cleanup, transition))) + assertThatThrownBy(() -> + context + .transaction() + .execute(status -> repository.readExact(lease, cleanup, transition))) .hasMessageContaining("Abort resolution changed"); - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> - repository.recordOrReplayNeverAdmitted( - lease, - cleanup, - transition, - UUID.randomUUID(), - "a".repeat(64), - "b".repeat(64)))) + assertThatThrownBy(() -> + context + .transaction() + .execute(status -> + repository.recordOrReplayNeverAdmitted( + lease, + cleanup, + transition, + UUID.randomUUID(), + "a".repeat(64), + "b".repeat(64)))) .hasMessageContaining("Negative abort resolution changed"); - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult( - status -> - context - .dsl() - .execute( - "UPDATE account_gameplay_admission_abort_resolutions SET closure_readback_sha256 = ? WHERE request_id = ?", - "c".repeat(64), - request(lease)))) + assertThatThrownBy(() -> + context + .transaction() + .executeWithoutResult(status -> + context + .dsl() + .execute( + "UPDATE account_gameplay_admission_abort_resolutions SET closure_readback_sha256 = ? WHERE request_id = ?", + "c".repeat(64), + request(lease)))) .hasMessageContaining("Account abort resolution is immutable"); assertThat(operation(context, lease)).isEqualTo(terminal); } @@ -139,37 +131,32 @@ void neverAdmittedResolutionRejectsPendingAndCommittedOriginalOperations() { var context = context(); var lease = pending(context, 15000); var repository = new AccountGameplayAdmissionAbortResolutionRepository(context.dsl()); - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> - repository.recordOrReplayNeverAdmitted( - lease, - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - "a".repeat(64), - "b".repeat(64)))) + assertThatThrownBy(() -> + context + .transaction() + .execute(status -> + repository.recordOrReplayNeverAdmitted( + lease, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "a".repeat(64), + "b".repeat(64)))) .hasMessageContaining("Exact retained unknown-decision Account abort required"); var committedContext = context(); var committed = finalized(committedContext, 15000); - assertThatThrownBy( - () -> - committedContext - .transaction() - .execute( - status -> - new AccountGameplayAdmissionAbortResolutionRepository( - committedContext.dsl()) - .recordOrReplayNeverAdmitted( - committed.evidence(), - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - "a".repeat(64), - "b".repeat(64)))) + assertThatThrownBy(() -> + committedContext + .transaction() + .execute(status -> + new AccountGameplayAdmissionAbortResolutionRepository(committedContext.dsl()) + .recordOrReplayNeverAdmitted( + committed.evidence(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "a".repeat(64), + "b".repeat(64)))) .hasMessageContaining("Exact retained unknown-decision Account abort required"); } @@ -223,11 +210,9 @@ void currentSourceCommitEntryRefusesStorageOnlyLeaseWithoutCurrentPlayerAuthorit // This controlled candidate is correlation only. The real in-transaction source readers // must refuse this storage fixture, which has no current player membership/tenant authority. - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) - .executeWithCurrentSources( - evidence, UUID.randomUUID(), "test", expectedCandidate)) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) + .executeWithCurrentSources(evidence, UUID.randomUUID(), "test", expectedCandidate)) .isInstanceOf(IllegalStateException.class); assertThat(operation(context, evidence)).isEqualTo(originalOperation); @@ -257,15 +242,14 @@ void coldGenuineAcknowledgedFinalizationPersistsExactProofWithoutAuxiliaryWrites assertThat(receipt.receiptXid()).isNotEqualTo(ack.finalizationXid()); assertThat(receipt.operation().evidence()).isEqualTo(ack.evidence()); assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isOne(); - assertThatThrownBy( - () -> - context - .dsl() - .fetch( - "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)", - request(ack.evidence()), - ack.evidence().sha256(), - ack.decisionId())) + assertThatThrownBy(() -> + context + .dsl() + .fetch( + "SELECT * FROM account_gameplay_admission_confirm_committed(?, ?, ?)", + request(ack.evidence()), + ack.evidence().sha256(), + ack.decisionId())) .hasMessageContaining("Experimental Account admission confirmation writes are retired"); assertThat( context.dsl().fetchCount(DSL.table("account_gameplay_admission_commit_confirmations"))) @@ -297,11 +281,8 @@ void concurrentGenuineAckCreatorsRetainOneExactWinnerWithoutRestamping() throws java.util.concurrent.Callable duplicate = () -> { if (!start.await(10, TimeUnit.SECONDS)) throw new IllegalStateException("start timeout"); - return retrySerialization( - () -> - context - .transaction() - .execute(status -> repository(context).create(ack).receipt())); + return retrySerialization(() -> + context.transaction().execute(status -> repository(context).create(ack).receipt())); }; try (var executor = Executors.newFixedThreadPool(2)) { var left = executor.submit(duplicate); @@ -400,29 +381,26 @@ void ownFinalizationAndReleasedSubtransactionCannotSupplyIndependentOriginal() { var context = context(); var evidence = pending(context, 15000); UUID decision = UUID.randomUUID(); - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult( - status -> { - if (subtransaction) - context.dsl().execute("SAVEPOINT original_finalization"); - new AccountGameplayAdmissionLeaseRepository(context.dsl()) - .recordCommitted(evidence, decision); - if (subtransaction) - context.dsl().execute("RELEASE SAVEPOINT original_finalization"); - context - .dsl() - .execute( - "INSERT INTO " - + RECEIPTS - + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms) VALUES (?, ?, ?, pg_current_xact_id()::text, ?)", - request(evidence), - evidence.sha256(), - decision, - Long.parseLong((String) evidence.carrier().get("evaluatedAt"))); - })) + assertThatThrownBy(() -> + context + .transaction() + .executeWithoutResult(status -> { + if (subtransaction) context.dsl().execute("SAVEPOINT original_finalization"); + new AccountGameplayAdmissionLeaseRepository(context.dsl()) + .recordCommitted(evidence, decision); + if (subtransaction) + context.dsl().execute("RELEASE SAVEPOINT original_finalization"); + context + .dsl() + .execute( + "INSERT INTO " + + RECEIPTS + + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms) VALUES (?, ?, ?, pg_current_xact_id()::text, ?)", + request(evidence), + evidence.sha256(), + decision, + Long.parseLong((String) evidence.carrier().get("evaluatedAt"))); + })) .hasMessageContaining("requires independent transaction"); assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); } @@ -433,18 +411,15 @@ void ownReceiptAndReleasedSubtransactionCannotSupplyHistoricalDurability() { for (boolean subtransaction : List.of(false, true)) { var context = context(); var ack = finalized(context, 15000); - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult( - status -> { - if (subtransaction) context.dsl().execute("SAVEPOINT receipt_creation"); - repository(context).create(ack); - if (subtransaction) - context.dsl().execute("RELEASE SAVEPOINT receipt_creation"); - repository(context).readDurably(ack.evidence(), ack.decisionId()); - })) + assertThatThrownBy(() -> + context + .transaction() + .executeWithoutResult(status -> { + if (subtransaction) context.dsl().execute("SAVEPOINT receipt_creation"); + repository(context).create(ack); + if (subtransaction) context.dsl().execute("RELEASE SAVEPOINT receipt_creation"); + repository(context).readDurably(ack.evidence(), ack.decisionId()); + })) .hasMessageContaining("requires independent commit"); assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); } @@ -462,23 +437,22 @@ void historicalCaptureFreezesItsFenceBeforeLocksAndObservesCoverageAfterCompleti java.util.Objects.requireNonNull( context .transaction() - .execute( - status -> { - var captured = - repository(context).captureHistorical(ack.evidence(), ack.decisionId()); - assertThat(captured.receipt()).isEqualTo(expected); - // Actual capture locks append WAL after the original frozen upper fence. - // That later insert position must never replace the SQL-issued proof fence. - assertThat( - context - .dsl() - .fetchSingle( - "SELECT pg_current_wal_insert_lsn() > ?::pg_lsn", - captured.walUpperFence()) - .get(0, Boolean.class)) - .isTrue(); - return captured; - })); + .execute(status -> { + var captured = + repository(context).captureHistorical(ack.evidence(), ack.decisionId()); + assertThat(captured.receipt()).isEqualTo(expected); + // Actual capture locks append WAL after the original frozen upper fence. + // That later insert position must never replace the SQL-issued proof fence. + assertThat( + context + .dsl() + .fetchSingle( + "SELECT pg_current_wal_insert_lsn() > ?::pg_lsn", + captured.walUpperFence()) + .get(0, Boolean.class)) + .isTrue(); + return captured; + })); String exactFrozenFence = pending.walUpperFence(); // No SQL transaction/row lock remains open. Completion itself is not accepted as proof; // positively observe durable WAL coverage of precisely the captured fence. @@ -511,34 +485,30 @@ void historicalRecoveryRefusesChangedDigestDecisionAndMissingOperationWithoutCha var storageBefore = ackStorageSnapshot(context); var sourcesBefore = sourceSnapshot(context); for (boolean changedDigest : List.of(false, true)) { - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult( - status -> - context - .dsl() - .fetch( - "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", - request(ack.evidence()), - changedDigest ? "0".repeat(64) : ack.evidence().sha256(), - changedDigest ? ack.decisionId() : UUID.randomUUID()))) + assertThatThrownBy(() -> + context + .transaction() + .executeWithoutResult(status -> + context + .dsl() + .fetch( + "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", + request(ack.evidence()), + changedDigest ? "0".repeat(64) : ack.evidence().sha256(), + changedDigest ? ack.decisionId() : UUID.randomUUID()))) .hasMessageContaining("Exact durable original Account acknowledgement receipt required"); } - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult( - status -> - context - .dsl() - .fetch( - "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", - UUID.randomUUID(), - ack.evidence().sha256(), - ack.decisionId()))) + assertThatThrownBy(() -> + context + .transaction() + .executeWithoutResult(status -> + context + .dsl() + .fetch( + "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", + UUID.randomUUID(), + ack.evidence().sha256(), + ack.decisionId()))) .hasMessageContaining("Original Account acknowledgement operation missing"); assertThat( new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()) @@ -560,14 +530,13 @@ void historicalRecoveryCannotSeeReceiptCommittedAfterItsFixedSnapshot() throws E new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()) .confirm(ack); var storageBefore = ackStorageSnapshot(context); - assertThatThrownBy( - () -> - DSL.using(stale) - .fetch( - "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", - request(ack.evidence()), - ack.evidence().sha256(), - ack.decisionId())) + assertThatThrownBy(() -> + DSL.using(stale) + .fetch( + "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", + request(ack.evidence()), + ack.evidence().sha256(), + ack.decisionId())) .hasMessageContaining("Exact durable original Account acknowledgement receipt required"); stale.rollback(); assertThat( @@ -586,13 +555,11 @@ void v1013QualifiesRetainedPg18ReceiptWithoutChangingHistoricalStorage() { new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(context.admin()).confirm(ack); var storageBefore = ackStorageSnapshot(context); var sourcesBefore = sourceSnapshot(context); - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> - repository(context).readDurably(ack.evidence(), ack.decisionId()))) + assertThatThrownBy(() -> + context + .transaction() + .execute( + status -> repository(context).readDurably(ack.evidence(), ack.decisionId()))) .hasMessageContaining("Supported durable PostgreSQL 16 primary required"); Flyway.configure() .dataSource(context.admin()) @@ -641,53 +608,43 @@ void changedCallerProofAndBindingsDenyAndRetainedReceiptRemainsImmutable() { case "receipt_xid" -> "'1'"; default -> "1"; }; - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult( - status -> - context - .dsl() - .execute( - "INSERT INTO " - + RECEIPTS - + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms, " - + field - + ") VALUES (?, ?, ?, ?, ?, " - + value - + ")", - request(ack.evidence()), - ack.evidence().sha256(), - ack.decisionId(), - ack.finalizationXid(), - ack.committedBeforeMs()))) + assertThatThrownBy(() -> + context + .transaction() + .executeWithoutResult(status -> + context + .dsl() + .execute( + "INSERT INTO " + + RECEIPTS + + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms, " + + field + + ") VALUES (?, ?, ?, ?, ?, " + + value + + ")", + request(ack.evidence()), + ack.evidence().sha256(), + ack.decisionId(), + ack.finalizationXid(), + ack.committedBeforeMs()))) .hasMessageContaining("binding is database derived"); } for (String changed : List.of("digest", "decision", "xid", "bound")) { - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult( - status -> - context - .dsl() - .execute( - "INSERT INTO " - + RECEIPTS - + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms) VALUES (?, ?, ?, ?, ?)", - request(ack.evidence()), - changed.equals("digest") - ? "b".repeat(64) - : ack.evidence().sha256(), - changed.equals("decision") - ? UUID.randomUUID() - : ack.decisionId(), - changed.equals("xid") ? "1" : ack.finalizationXid(), - changed.equals("bound") - ? expiry(ack) - : ack.committedBeforeMs()))) + assertThatThrownBy(() -> + context + .transaction() + .executeWithoutResult(status -> + context + .dsl() + .execute( + "INSERT INTO " + + RECEIPTS + + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms) VALUES (?, ?, ?, ?, ?)", + request(ack.evidence()), + changed.equals("digest") ? "b".repeat(64) : ack.evidence().sha256(), + changed.equals("decision") ? UUID.randomUUID() : ack.decisionId(), + changed.equals("xid") ? "1" : ack.finalizationXid(), + changed.equals("bound") ? expiry(ack) : ack.committedBeforeMs()))) .hasMessageContaining("Exact original Account COMMIT acknowledgement required"); } var receipt = @@ -700,11 +657,8 @@ void changedCallerProofAndBindingsDenyAndRetainedReceiptRemainsImmutable() { "UPDATE " + RECEIPTS + " SET evidence_sha256 = '" + "b".repeat(64) + "'", "DELETE FROM " + RECEIPTS, "TRUNCATE " + RECEIPTS)) { - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult(status -> context.dsl().execute(mutation))) + assertThatThrownBy(() -> + context.transaction().executeWithoutResult(status -> context.dsl().execute(mutation))) .hasMessageContaining("receipt is immutable"); } assertThat(receipt(context)).isEqualTo(before); @@ -752,10 +706,9 @@ public Connection getConnection() throws SQLException { } }; var attempt = - executor.submit( - () -> - new AccountGameplayAdmissionOriginalCommitExecutor(waitingSource) - .execute(evidence, UUID.randomUUID())); + executor.submit(() -> + new AccountGameplayAdmissionOriginalCommitExecutor(waitingSource) + .execute(evidence, UUID.randomUUID())); assertThat(started.await(5, TimeUnit.SECONDS)).isTrue(); // Verify an actual independent lock wait before the original expiry is allowed to pass. boolean waiting = false; @@ -829,17 +782,14 @@ private Connection delayedCommitConnection(Connection physical) { } } }; - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalCommitExecutor(delayed) - .execute(evidence, decision)) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalCommitExecutor(delayed).execute(evidence, decision)) .hasMessageContaining("post-COMMIT clock bound unavailable"); assertThat(physicalCommits.get()).isOne(); assertThat(operation(context, evidence).get("status")).isEqualTo("COMMITTED"); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) - .execute(evidence, decision)) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) + .execute(evidence, decision)) .hasMessageContaining("Fresh owned Account original COMMIT required"); assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); } @@ -854,10 +804,8 @@ void lostOriginalCommitAcknowledgementCannotReconstructCapabilityOrRetryFinaliza var physicalCommits = new java.util.concurrent.atomic.AtomicInteger(); var source = loseCommitAcknowledgementAfter(context.admin(), physicalCommits, 1); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalCommitExecutor(source) - .execute(evidence, decision)) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalCommitExecutor(source).execute(evidence, decision)) .hasMessageContaining("physical COMMIT unavailable"); assertThat(physicalCommits.get()).isOne(); @@ -881,10 +829,9 @@ void lostOriginalCommitAcknowledgementCannotReconstructCapabilityOrRetryFinaliza // The physical COMMIT succeeded, but its missing JDBC acknowledgement never yielded the // opaque capability. A retained retry cannot stamp or reconstruct one. - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) - .execute(evidence, decision)) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) + .execute(evidence, decision)) .hasMessageContaining("Fresh owned Account original COMMIT required"); assertThat(operation(context, evidence)).isEqualTo(committed); assertThat(sourceSnapshot(context)).isEqualTo(sourcesBefore); @@ -898,10 +845,9 @@ void acknowledgementFromAnotherPostgresDataSourceCannotCreateReceipt() { var ack = finalized(original, 15000); var operationBefore = operation(original, ack.evidence()); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(other.admin()) - .confirm(ack)) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(other.admin()) + .confirm(ack)) .hasMessageContaining("Fresh owned Account receipt COMMIT required"); assertThat(operation(original, ack.evidence())).isEqualTo(operationBefore); @@ -1009,10 +955,9 @@ void retainedCommittedRetryCannotMintFreshAckAndHistoricalReceiptRecoveryPreserv assertThat(receipt.finalizationXid()).isEqualTo(ack.finalizationXid()); assertThat(receipt.receiptXid()).isNotEqualTo(ack.finalizationXid()); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) - .execute(ack.evidence(), ack.decisionId())) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalCommitExecutor(context.admin()) + .execute(ack.evidence(), ack.decisionId())) .hasMessageContaining("Fresh owned Account original COMMIT required"); assertThat(receiptExecutor.read(ack.evidence(), ack.decisionId())).isEqualTo(receipt); assertThat(receiptExecutor.confirm(ack)).isEqualTo(receipt); @@ -1040,42 +985,36 @@ void rolledBackAndAbortedOriginalTransitionsCannotInsertFreshAckReceipt() { if (abort) { context .transaction() - .executeWithoutResult( - status -> - new AccountGameplayAdmissionLeaseRepository(context.dsl()) - .recordAborted(evidence, null, decision)); + .executeWithoutResult(status -> + new AccountGameplayAdmissionLeaseRepository(context.dsl()) + .recordAborted(evidence, null, decision)); assertThat(operation(context, evidence).get("status")).isEqualTo("ABORTED"); } else { - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult( - status -> { - new AccountGameplayAdmissionLeaseRepository(context.dsl()) - .recordCommitted(evidence, decision); - throw new IllegalStateException("rollback original finalization"); - })) + assertThatThrownBy(() -> + context + .transaction() + .executeWithoutResult(status -> { + new AccountGameplayAdmissionLeaseRepository(context.dsl()) + .recordCommitted(evidence, decision); + throw new IllegalStateException("rollback original finalization"); + })) .hasMessageContaining("rollback original finalization"); assertThat(operation(context, evidence)).isEqualTo(original); } - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult( - status -> - context - .dsl() - .execute( - "INSERT INTO " - + RECEIPTS - + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms) VALUES (?, ?, ?, '1', ?)", - request(evidence), - evidence.sha256(), - decision, - Long.parseLong( - (String) evidence.carrier().get("evaluatedAt"))))) + assertThatThrownBy(() -> + context + .transaction() + .executeWithoutResult(status -> + context + .dsl() + .execute( + "INSERT INTO " + + RECEIPTS + + "(request_id, evidence_sha256, binding_decision_id, finalization_xid, committed_before_ms) VALUES (?, ?, ?, '1', ?)", + request(evidence), + evidence.sha256(), + decision, + Long.parseLong((String) evidence.carrier().get("evaluatedAt"))))) .hasMessageContaining("Exact original Account COMMIT acknowledgement required"); assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); } @@ -1094,45 +1033,39 @@ void genuineAckSqlEntryRequiresWritableSerializableTransactionAndKeepsFinalizerS assertThatThrownBy( () -> unsupported.executeWithoutResult(status -> insertAck(context.dsl(), ack))) .hasMessageContaining("Writable SERIALIZABLE"); - assertThatThrownBy( - () -> - unsupported.executeWithoutResult( - status -> - context - .dsl() - .fetch( - "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", - request(ack.evidence()), - ack.evidence().sha256(), - ack.decisionId()))) + assertThatThrownBy(() -> + unsupported.executeWithoutResult(status -> + context + .dsl() + .fetch( + "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", + request(ack.evidence()), + ack.evidence().sha256(), + ack.decisionId()))) .hasMessageContaining("Writable SERIALIZABLE"); } var readOnly = new TransactionTemplate(new DataSourceTransactionManager(context.admin())); readOnly.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); readOnly.setReadOnly(true); - assertThatThrownBy( - () -> - readOnly.executeWithoutResult( - status -> - context - .dsl() - .fetch( - "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", - request(ack.evidence()), - ack.evidence().sha256(), - ack.decisionId()))) - .hasMessageContaining("Writable SERIALIZABLE"); - assertThatThrownBy( - () -> + assertThatThrownBy(() -> + readOnly.executeWithoutResult(status -> context - .transaction() - .executeWithoutResult( - status -> - context - .dsl() - .execute( - "UPDATE account_gameplay_admission_lease_operations SET finalization_xid = '1' WHERE request_id = ?", - request(ack.evidence())))) + .dsl() + .fetch( + "SELECT * FROM account_gameplay_admission_read_original_ack_receipt_durably(?, ?, ?)", + request(ack.evidence()), + ack.evidence().sha256(), + ack.decisionId()))) + .hasMessageContaining("Writable SERIALIZABLE"); + assertThatThrownBy(() -> + context + .transaction() + .executeWithoutResult(status -> + context + .dsl() + .execute( + "UPDATE account_gameplay_admission_lease_operations SET finalization_xid = '1' WHERE request_id = ?", + request(ack.evidence())))) .hasMessageContaining("finalization transaction is database stamped"); assertThat(context.dsl().fetchCount(DSL.table(RECEIPTS))).isZero(); } @@ -1151,16 +1084,15 @@ void originalNewLineageFreezesGenerationAndHandleUntilAuthenticatedAdmissionConf var created = context .transaction() - .execute( - status -> - repository.beginGenesis( - ack.evidence(), - receipt, - lineageId, - tokenJti, - nowSeconds, - nowSeconds, - nowSeconds + 300L)); + .execute(status -> + repository.beginGenesis( + ack.evidence(), + receipt, + lineageId, + tokenJti, + nowSeconds, + nowSeconds, + nowSeconds + 300L)); assertThat(created.tokenGeneration()).isEqualTo(1L); assertThat(created.status()) .isEqualTo(AccountOriginalNewBoundGameplayIssuanceRepository.Status.PENDING); @@ -1179,16 +1111,15 @@ void originalNewLineageFreezesGenerationAndHandleUntilAuthenticatedAdmissionConf var retry = context .transaction() - .execute( - status -> - repository.beginGenesis( - ack.evidence(), - receipt, - UUID.randomUUID(), - UUID.randomUUID(), - nowSeconds + 1L, - nowSeconds + 1L, - nowSeconds + 301L)); + .execute(status -> + repository.beginGenesis( + ack.evidence(), + receipt, + UUID.randomUUID(), + UUID.randomUUID(), + nowSeconds + 1L, + nowSeconds + 1L, + nowSeconds + 301L)); assertThat(retry.lineageId()).isEqualTo(created.lineageId()); assertThat(retry.tokenJti()).isEqualTo(created.tokenJti()); assertThat(retry.issuedAtEpochSecond()).isEqualTo(created.issuedAtEpochSecond()); @@ -1212,35 +1143,32 @@ void originalNewLineageFreezesGenerationAndHandleUntilAuthenticatedAdmissionConf var bound = context .transaction() - .execute( - status -> - repository.bindSignedResult( - retry, - tokenHash, - "controlled-test-kid", - "1", - registryRecord, - handleHash, - protectedEnvelope)); + .execute(status -> + repository.bindSignedResult( + retry, + tokenHash, + "controlled-test-kid", + "1", + registryRecord, + handleHash, + protectedEnvelope)); assertThat(bound.status()) .isEqualTo(AccountOriginalNewBoundGameplayIssuanceRepository.Status.PENDING); assertThat(bound.rebindHandleSha256()).isEqualTo(handleHash); assertThat(bound.confirmedAdmissionAtMillis()).isNull(); assertThat(bound.handleConsumedAtMillis()).isNull(); - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> - repository.bindSignedResult( - bound, - "c".repeat(64), - "controlled-test-kid", - "1", - registryRecord, - handleHash, - protectedEnvelope))) + assertThatThrownBy(() -> + context + .transaction() + .execute(status -> + repository.bindSignedResult( + bound, + "c".repeat(64), + "controlled-test-kid", + "1", + registryRecord, + handleHash, + protectedEnvelope))) .hasMessageContaining("Original-new bound gameplay issuance is unavailable"); assertThat(repositoryRead(context, repository, ack.evidence()).tokenHash()) .isEqualTo(tokenHash); @@ -1265,29 +1193,24 @@ void originalNewLineageFreezesGenerationAndHandleUntilAuthenticatedAdmissionConf var activeTokenFence = context .transaction() - .execute( - status -> - new AccountGameplayTokenIdentityFenceRepository(context.dsl()) - .registerCommittedOriginalNewIssuance(tokenIdentity)); + .execute(status -> + new AccountGameplayTokenIdentityFenceRepository(context.dsl()) + .registerCommittedOriginalNewIssuance(tokenIdentity)); assertThat(activeTokenFence.identity().sourceKind()).isEqualTo(SourceKind.ORIGINAL_NEW); assertThat(activeTokenFence.tokenIdentityFence()).isEqualTo(1L); var recoveredActiveTokenFence = context .transaction() - .execute( - status -> - new AccountGameplayTokenIdentityFenceRepository(context.dsl()) - .requireActiveForUpdate(tokenIdentity)); + .execute(status -> + new AccountGameplayTokenIdentityFenceRepository(context.dsl()) + .requireActiveForUpdate(tokenIdentity)); assertThat(recoveredActiveTokenFence).isEqualTo(activeTokenFence); UUID consumeRequest = UUID.randomUUID(); - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> - repository.consumeOneUseHandle( - committed, handleHash, consumeRequest, 1L))) + assertThatThrownBy(() -> + context + .transaction() + .execute(status -> + repository.consumeOneUseHandle(committed, handleHash, consumeRequest, 1L))) .hasMessageContaining("Original-new bound gameplay issuance is unavailable"); long databaseNow = @@ -1302,64 +1225,53 @@ void originalNewLineageFreezesGenerationAndHandleUntilAuthenticatedAdmissionConf var confirmed = context .transaction() - .execute( - status -> - repository.confirmFinalAdmission( - committed, actualAdmissionAt, continuityExpiresAt, authenticatedReadback)); + .execute(status -> + repository.confirmFinalAdmission( + committed, actualAdmissionAt, continuityExpiresAt, authenticatedReadback)); assertThat(confirmed.confirmedAdmissionAtMillis()).isEqualTo(actualAdmissionAt); assertThat(confirmed.confirmedContinuityExpiresAtMillis()).isEqualTo(continuityExpiresAt); assertThat(confirmed.confirmationReadbackSha256()).isEqualTo(authenticatedReadback); var sameConfirmationRetry = context .transaction() - .execute( - status -> - repository.confirmFinalAdmission( - confirmed, actualAdmissionAt, continuityExpiresAt, authenticatedReadback)); + .execute(status -> + repository.confirmFinalAdmission( + confirmed, actualAdmissionAt, continuityExpiresAt, authenticatedReadback)); assertThat(sameConfirmationRetry.confirmedAdmissionAtMillis()).isEqualTo(actualAdmissionAt); assertThat(sameConfirmationRetry.confirmationReadbackSha256()).isEqualTo(authenticatedReadback); - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> - repository.confirmFinalAdmission( - confirmed, - actualAdmissionAt + 1L, - continuityExpiresAt + 1L, - authenticatedReadback))) + assertThatThrownBy(() -> + context + .transaction() + .execute(status -> + repository.confirmFinalAdmission( + confirmed, + actualAdmissionAt + 1L, + continuityExpiresAt + 1L, + authenticatedReadback))) .hasMessageContaining("Original-new bound gameplay issuance is unavailable"); var consumed = context .transaction() - .execute( - status -> - repository.consumeOneUseHandle( - confirmed, handleHash, consumeRequest, actualAdmissionAt)); + .execute(status -> + repository.consumeOneUseHandle( + confirmed, handleHash, consumeRequest, actualAdmissionAt)); assertThat(consumed.handleConsumptionRequestId()).isEqualTo(consumeRequest); assertThat(consumed.handleConsumedAtMillis()).isBetween(actualAdmissionAt, continuityExpiresAt); var sameConsumeRetry = context .transaction() - .execute( - status -> - repository.consumeOneUseHandle( - consumed, handleHash, consumeRequest, actualAdmissionAt)); + .execute(status -> + repository.consumeOneUseHandle( + consumed, handleHash, consumeRequest, actualAdmissionAt)); assertThat(sameConsumeRetry.handleConsumedAtMillis()) .isEqualTo(consumed.handleConsumedAtMillis()); - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> - repository.consumeOneUseHandle( - sameConsumeRetry, - handleHash, - UUID.randomUUID(), - actualAdmissionAt))) + assertThatThrownBy(() -> + context + .transaction() + .execute(status -> + repository.consumeOneUseHandle( + sameConsumeRetry, handleHash, UUID.randomUUID(), actualAdmissionAt))) .hasMessageContaining("Original-new bound gameplay issuance is unavailable"); java.util.Arrays.fill(registryRecord, (byte) 0); @@ -1398,10 +1310,8 @@ private static AccountOriginalNewBoundGameplayIssuanceRepository.Genesis reposit AccountGameplayAdmissionLeaseEvidence evidence) { return context .transaction() - .execute( - status -> - repository.readByLease( - UUID.fromString((String) evidence.carrier().get("leaseId")))); + .execute(status -> + repository.readByLease(UUID.fromString((String) evidence.carrier().get("leaseId")))); } private static String sha256(byte[] value) { @@ -1520,34 +1430,30 @@ private static AccountGameplayAdmissionLeaseEvidence pending( Context context, long lifetime, long issuanceFence) { return context .transaction() - .execute( - status -> { - var authorities = new AccountAuthorityGenerationRepository(context.dsl()); - var sources = - new AccountAuthoritySourceEvidenceRepository( - context.dsl(), - authorities, - new AccountAuthorityOutboxRepository(context.dsl())); - sources.initializeIssuerIfAbsent("firemud-account-service"); - var account = new Account(); - account.setUsername("protected-" + UUID.randomUUID()); - account.setEmail(UUID.randomUUID() + "@example.test"); - account.setPasswordHash("shape-fixture-only"); - account.setLoginAuthModes("PASSWORD"); - UUID accountId = - new AccountRepository(context.dsl(), sources).save(account).getAccountUuid(); - var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); - var allocation = repository.allocate(accountId, UUID.randomUUID(), UUID.randomUUID()); - long databaseNow = - context - .dsl() - .fetchSingle( - "SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint") - .get(0, Long.class); - var evidence = evidence(allocation, lifetime, databaseNow, issuanceFence); - repository.beginPending(evidence); - return evidence; - }); + .execute(status -> { + var authorities = new AccountAuthorityGenerationRepository(context.dsl()); + var sources = + new AccountAuthoritySourceEvidenceRepository( + context.dsl(), authorities, new AccountAuthorityOutboxRepository(context.dsl())); + sources.initializeIssuerIfAbsent("firemud-account-service"); + var account = new Account(); + account.setUsername("protected-" + UUID.randomUUID()); + account.setEmail(UUID.randomUUID() + "@example.test"); + account.setPasswordHash("shape-fixture-only"); + account.setLoginAuthModes("PASSWORD"); + UUID accountId = + new AccountRepository(context.dsl(), sources).save(account).getAccountUuid(); + var repository = new AccountGameplayAdmissionLeaseRepository(context.dsl()); + var allocation = repository.allocate(accountId, UUID.randomUUID(), UUID.randomUUID()); + long databaseNow = + context + .dsl() + .fetchSingle("SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint") + .get(0, Long.class); + var evidence = evidence(allocation, lifetime, databaseNow, issuanceFence); + repository.beginPending(evidence); + return evidence; + }); } private static AccountGameplayAdmissionLeaseEvidence evidence( @@ -1615,13 +1521,12 @@ private static AccountGameplayAdmissionLeaseEvidence evidence( "membership/" + account + "/" + TENANT, "tenant/" + TENANT) .stream() - .map( - suffix -> - Map.of( - "outboxStreamKey", - "account:auth-authority:v1:" + suffix, - "outboxSequence", - "1")) + .map(suffix -> + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:" + suffix, + "outboxSequence", + "1")) .toList()); Map token = new LinkedHashMap<>(); token.put("accountId", account); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java index dfd312e520..fbf03aeba3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java @@ -290,44 +290,41 @@ void createsRequestIdentityFromCurrentAccountAuthorityAndReplaysItExactly() { assertThat(replay.identity()).isEqualTo(created.identity()); assertThat(replay.operation()).isEqualTo(created.operation()); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - repository.beginPendingForAccount( - requestId, - accountId, - "spiffe://firemud/ns/other/sa/game-session-service", - callerContextId, - AccountGameplayCredentialRequestBindingFixture.binding()))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + repository.beginPendingForAccount( + requestId, + accountId, + "spiffe://firemud/ns/other/sa/game-session-service", + callerContextId, + AccountGameplayCredentialRequestBindingFixture.binding()))) .isInstanceOf( AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - repository.beginPendingForAccount( - requestId, - accountId, - CALLER_WORKLOAD, - UUID.randomUUID(), - AccountGameplayCredentialRequestBindingFixture.binding()))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + repository.beginPendingForAccount( + requestId, + accountId, + CALLER_WORKLOAD, + UUID.randomUUID(), + AccountGameplayCredentialRequestBindingFixture.binding()))) .isInstanceOf( AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); UUID otherAccountId = createAccount(context).getAccountUuid(); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - repository.beginPendingForAccount( - requestId, - otherAccountId, - CALLER_WORKLOAD, - callerContextId, - AccountGameplayCredentialRequestBindingFixture.binding()))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + repository.beginPendingForAccount( + requestId, + otherAccountId, + CALLER_WORKLOAD, + callerContextId, + AccountGameplayCredentialRequestBindingFixture.binding()))) .isInstanceOf( AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); @@ -390,41 +387,38 @@ void credentialBindingMigrationRetainsLegacyEvidenceAndRequiresImmutableBoundRow AccountGameplayDelegationIssuanceRepository repository = new AccountGameplayDelegationIssuanceRepository(context.dsl(), sources); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> repository.readCurrentGameplayLoginReplay(retainedIntent.requestId()))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> repository.readCurrentGameplayLoginReplay(retainedIntent.requestId()))) .isInstanceOf( AccountGameplayDelegationIssuanceRepository.StorageUnavailableException.class); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - context - .dsl() - .execute( - "UPDATE account_gameplay_delegation_issuance_operations " - + "SET token_hash = ?, signer_kid = ?, signer_generation = ?, " - + "pending_registry_candidate_bytes = ? WHERE request_id = ?", - "cd".repeat(32), - "integration-key", - "1", - new byte[] {1, 2, 3}, - retainedIntent.requestId()))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET token_hash = ?, signer_kid = ?, signer_generation = ?, " + + "pending_registry_candidate_bytes = ? WHERE request_id = ?", + "cd".repeat(32), + "integration-key", + "1", + new byte[] {1, 2, 3}, + retainedIntent.requestId()))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - context - .dsl() - .execute( - "UPDATE account_gameplay_delegation_issuance_operations " - + "SET status = 'COMMITTED' WHERE request_id = ?", - retainedIntent.requestId()))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET status = 'COMMITTED' WHERE request_id = ?", + retainedIntent.requestId()))) .isInstanceOf(DataAccessException.class); Record retainedAfterDeniedAdvances = context @@ -470,18 +464,17 @@ void credentialBindingMigrationRetainsLegacyEvidenceAndRequiresImmutableBoundRow .isEqualTo(binding.digestKeyId()); assertThat(bound.get("credential_request_digest", String.class)) .isEqualTo(binding.credentialRequestDigest()); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - context - .dsl() - .execute( - "UPDATE account_gameplay_delegation_issuance_operations " - + "SET credential_request_digest = ? WHERE request_id = ?", - "cd".repeat(32), - newRequestId))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET credential_request_digest = ? WHERE request_id = ?", + "cd".repeat(32), + newRequestId))) .isInstanceOf(DataAccessException.class); Record boundAfterDeniedMutation = context @@ -524,14 +517,13 @@ void deterministicOtpFixtureAndCanonicalLoginCommitBeforeReturningCredential() t canonicalLoginRequest(account.getEmail(), "123456", requestId, callerContextId); var result = - withAuthenticatedGameSession( - () -> - harness - .loginOwner() - .authenticate( - request, - CALLER_WORKLOAD, - deterministicOtpCredentialVerifier(challenges, "123456"))); + withAuthenticatedGameSession(() -> + harness + .loginOwner() + .authenticate( + request, + CALLER_WORKLOAD, + deterministicOtpCredentialVerifier(challenges, "123456"))); assertThat(result.accountId()).isEqualTo(account.getAccountUuid()); assertThat(result.tokenJti()).isNotNull(); @@ -587,16 +579,14 @@ void failureAfterOtpDeleteRollsBackCanonicalLoginAndOtpConsumption() throws Exce CanonicalGameplayLoginRequest request = canonicalLoginRequest(account.getEmail(), "654321", requestId, callerContextId); - assertThatThrownBy( - () -> - withAuthenticatedGameSession( - () -> - harness - .loginOwner() - .authenticate( - request, - CALLER_WORKLOAD, - deterministicOtpCredentialVerifier(challenges, "654321")))) + assertThatThrownBy(() -> + withAuthenticatedGameSession(() -> + harness + .loginOwner() + .authenticate( + request, + CALLER_WORKLOAD, + deterministicOtpCredentialVerifier(challenges, "654321")))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("simulated failure"); @@ -658,13 +648,12 @@ void keepsExactPendingIntentAndCandidateImmutableAndRejectsAdvancedAuthority() t String mismatchedTimeCandidate = compactCandidate(firstIntent, firstIntent.expiresAtEpochSecond() + 1L); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - repository.bindSignedCandidate( - firstIntent.requestId(), mismatchedTimeCandidate, "1"))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + repository.bindSignedCandidate( + firstIntent.requestId(), mismatchedTimeCandidate, "1"))) .isInstanceOf( AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); assertThat(readCandidate(dsl, firstIntent.requestId()).tokenHash()).isNull(); @@ -713,24 +702,22 @@ void keepsExactPendingIntentAndCandidateImmutableAndRejectsAdvancedAuthority() t assertThat(persisted.tokenHash()).isEqualTo(bound.tokenHash()); assertThat(persisted.authorityTupleBytes()) .isEqualTo(canonicalBytes(GameSessionAccountDelegationProfile.authorityTuple(1L, 1L))); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE account_gameplay_delegation_issuance_operations " - + "SET token_hash = ? WHERE request_id = ?", - "f".repeat(64), - firstIntent.requestId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET token_hash = ? WHERE request_id = ?", + "f".repeat(64), + firstIntent.requestId())) .isInstanceOf(DataAccessException.class) .hasMessageContaining("token identity may be bound exactly once"); advanceEmailVerifiedThroughOwner(dsl, context.transaction(), sources, accountId); assertThatThrownBy(() -> inTransaction(context, () -> repository.beginPending(firstIntent))) .isInstanceOf(StaleAuthorityException.class); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> repository.bindSignedCandidate(firstIntent.requestId(), compactJwt, "1"))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> repository.bindSignedCandidate(firstIntent.requestId(), compactJwt, "1"))) .isInstanceOf(StaleAuthorityException.class); RecordData accountAdvancePersisted = readCandidate(dsl, firstIntent.requestId()); assertThat(accountAdvancePersisted.status()).isEqualTo(persisted.status()); @@ -750,33 +737,30 @@ void keepsExactPendingIntentAndCandidateImmutableAndRejectsAdvancedAuthority() t secondIntent.authoritySnapshot().issuerGeneration(), secondIntent.authoritySnapshot().accountGeneration(), secondIntent.authoritySnapshot().accountSecurityCutoff())); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE account_gameplay_delegation_issuance_operations " - + "SET authority_tuple_canonical_bytes = ? WHERE request_id = ?", - canonicalBytes( - authorityTupleWithoutCutoff( - secondIntent.authoritySnapshot().issuerGeneration(), - secondIntent.authoritySnapshot().accountGeneration())), - secondIntent.requestId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET authority_tuple_canonical_bytes = ? WHERE request_id = ?", + canonicalBytes( + authorityTupleWithoutCutoff( + secondIntent.authoritySnapshot().issuerGeneration(), + secondIntent.authoritySnapshot().accountGeneration())), + secondIntent.requestId())) .isInstanceOf(DataAccessException.class) .hasMessageContaining("authority snapshot is stale or missing"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE account_gameplay_delegation_issuance_operations " - + "SET issuance_fence = issuance_fence + 1 WHERE request_id = ?", - secondIntent.requestId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET issuance_fence = issuance_fence + 1 WHERE request_id = ?", + secondIntent.requestId())) .isInstanceOf(DataAccessException.class) .hasMessageContaining("authority snapshot is stale or missing"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE account_gameplay_delegation_issuance_operations " - + "SET issuance_fence_source_version = issuance_fence_source_version + 1 " - + "WHERE request_id = ?", - secondIntent.requestId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET issuance_fence_source_version = issuance_fence_source_version + 1 " + + "WHERE request_id = ?", + secondIntent.requestId())) .isInstanceOf(DataAccessException.class) .hasMessageContaining("authority snapshot is stale or missing"); assertThat(readCandidate(dsl, secondIntent.requestId()).authorityTupleBytes()) @@ -806,35 +790,34 @@ void keepsExactPendingIntentAndCandidateImmutableAndRejectsAdvancedAuthority() t Map.entry("signer", Map.of()), Map.entry("envelope", Map.of()))); String otherwiseShapedProofSha256 = sha256Hex(otherwiseShapedCommitProof); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO account_gameplay_delegation_issuance_operations (" - + "operation_id, request_id, account_uuid, caller_workload, caller_context_id, " - + "credential_request_digest_version, credential_digest_key_id, credential_request_digest, " - + "request_digest_version, request_digest, token_jti, token_generation, " - + "issued_at_epoch_second, not_before_epoch_second, expires_at_epoch_second, " - + "authority_issuer_generation, authority_issuer_source_version, " - + "authority_account_generation, authority_account_source_version, issuance_fence, " - + "issuance_fence_source_version, authority_tuple_canonical_bytes, " - + "membership_version_canonical_bytes, authority_source_versions_canonical_bytes, " - + "status, token_hash, signer_kid, signer_generation, " - + "pending_registry_candidate_bytes, commit_proof_version, commit_proof_sha256, " - + "commit_proof_canonical_bytes, committed_at) " - + "SELECT operation_id, request_id, account_uuid, caller_workload, caller_context_id, " - + "credential_request_digest_version, credential_digest_key_id, credential_request_digest, " - + "request_digest_version, request_digest, token_jti, token_generation, " - + "issued_at_epoch_second, not_before_epoch_second, expires_at_epoch_second, " - + "authority_issuer_generation, authority_issuer_source_version, " - + "authority_account_generation, authority_account_source_version, issuance_fence, " - + "issuance_fence_source_version, authority_tuple_canonical_bytes, " - + "membership_version_canonical_bytes, authority_source_versions_canonical_bytes, " - + "'COMMITTED', token_hash, signer_kid, signer_generation, " - + "pending_registry_candidate_bytes, 1, ?, ?, CURRENT_TIMESTAMP " - + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", - otherwiseShapedProofSha256, - otherwiseShapedCommitProof, - secondIntent.requestId())) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO account_gameplay_delegation_issuance_operations (" + + "operation_id, request_id, account_uuid, caller_workload, caller_context_id, " + + "credential_request_digest_version, credential_digest_key_id, credential_request_digest, " + + "request_digest_version, request_digest, token_jti, token_generation, " + + "issued_at_epoch_second, not_before_epoch_second, expires_at_epoch_second, " + + "authority_issuer_generation, authority_issuer_source_version, " + + "authority_account_generation, authority_account_source_version, issuance_fence, " + + "issuance_fence_source_version, authority_tuple_canonical_bytes, " + + "membership_version_canonical_bytes, authority_source_versions_canonical_bytes, " + + "status, token_hash, signer_kid, signer_generation, " + + "pending_registry_candidate_bytes, commit_proof_version, commit_proof_sha256, " + + "commit_proof_canonical_bytes, committed_at) " + + "SELECT operation_id, request_id, account_uuid, caller_workload, caller_context_id, " + + "credential_request_digest_version, credential_digest_key_id, credential_request_digest, " + + "request_digest_version, request_digest, token_jti, token_generation, " + + "issued_at_epoch_second, not_before_epoch_second, expires_at_epoch_second, " + + "authority_issuer_generation, authority_issuer_source_version, " + + "authority_account_generation, authority_account_source_version, issuance_fence, " + + "issuance_fence_source_version, authority_tuple_canonical_bytes, " + + "membership_version_canonical_bytes, authority_source_versions_canonical_bytes, " + + "'COMMITTED', token_hash, signer_kid, signer_generation, " + + "pending_registry_candidate_bytes, 1, ?, ?, CURRENT_TIMESTAMP " + + "FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", + otherwiseShapedProofSha256, + otherwiseShapedCommitProof, + secondIntent.requestId())) .isInstanceOf(DataAccessException.class) .hasMessageContaining("must begin as unbound PENDING intent"); RecordData afterCommittedInsert = readCandidate(dsl, secondIntent.requestId()); @@ -844,16 +827,15 @@ void keepsExactPendingIntentAndCandidateImmutableAndRejectsAdvancedAuthority() t .containsExactly(advancedPersisted.candidateBytes()); byte[] forgedCommitProof = "{}".getBytes(StandardCharsets.US_ASCII); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE account_gameplay_delegation_issuance_operations " - + "SET status = 'COMMITTED', commit_proof_version = 1, " - + "commit_proof_sha256 = ?, commit_proof_canonical_bytes = ?, " - + "committed_at = CURRENT_TIMESTAMP WHERE request_id = ?", - "a".repeat(64), - forgedCommitProof, - secondIntent.requestId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET status = 'COMMITTED', commit_proof_version = 1, " + + "commit_proof_sha256 = ?, commit_proof_canonical_bytes = ?, " + + "committed_at = CURRENT_TIMESTAMP WHERE request_id = ?", + "a".repeat(64), + forgedCommitProof, + secondIntent.requestId())) .isInstanceOf(DataAccessException.class) .hasMessageContaining("unknown or missing fields"); RecordData afterForgedCommit = readCandidate(dsl, secondIntent.requestId()); @@ -889,18 +871,14 @@ void keepsExactPendingIntentAndCandidateImmutableAndRejectsAdvancedAuthority() t ACCOUNT_ISSUER, "SIGNER_COMPROMISE", UUID.randomUUID().toString())); assertThatThrownBy(() -> inTransaction(context, () -> repository.beginPending(secondIntent))) .isInstanceOf(StaleAuthorityException.class); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> repository.readPendingRegistryCandidate(secondIntent.requestId()))) + assertThatThrownBy(() -> + inTransaction( + context, () -> repository.readPendingRegistryCandidate(secondIntent.requestId()))) .isInstanceOf(StaleAuthorityException.class); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - repository.bindSignedCandidate(secondIntent.requestId(), advancedJwt, "1"))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> repository.bindSignedCandidate(secondIntent.requestId(), advancedJwt, "1"))) .isInstanceOf(StaleAuthorityException.class); RecordData afterIssuerAdvance = readCandidate(dsl, secondIntent.requestId()); assertThat(afterIssuerAdvance.status()).isEqualTo(advancedPersisted.status()); @@ -930,11 +908,10 @@ void realCommittedIssuanceEstablishesExactSqlFenceAndIndependentRetryReadback() assertThat(active.state()).isEqualTo(State.ACTIVE); assertThat(active.tokenIdentityFence()).isEqualTo(1L); assertThat(active.identity()).isEqualTo(identity); - assertThatThrownBy( - () -> - inTransaction( - harness.context(), - () -> harness.dsl().execute("TRUNCATE account_gameplay_token_identity_fences"))) + assertThatThrownBy(() -> + inTransaction( + harness.context(), + () -> harness.dsl().execute("TRUNCATE account_gameplay_token_identity_fences"))) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("Account token fence retention cannot be bypassed by truncation"); assertThat(inTransaction(harness.context(), () -> fences.requireActiveForUpdate(identity))) @@ -995,42 +972,39 @@ void durableExactRevocationIntentDeniesAdmissionAndCommitRecoveryWithoutRecreati .hasNoCause(); UUID conflictingRequest = UUID.randomUUID(); - assertThatThrownBy( - () -> - inTransaction( - harness.context(), - () -> - fences.beginRevocationIntent( - identity, - conflictingRequest, - AccountGameplayTokenIdentityFenceRepository.revocationDigest( - identity, conflictingRequest)))) + assertThatThrownBy(() -> + inTransaction( + harness.context(), + () -> + fences.beginRevocationIntent( + identity, + conflictingRequest, + AccountGameplayTokenIdentityFenceRepository.revocationDigest( + identity, conflictingRequest)))) .isInstanceOf( AccountGameplayTokenIdentityFenceRepository.RevocationConflictException.class); - assertThatThrownBy( - () -> - inTransaction( - harness.context(), - () -> - harness - .dsl() - .execute( - "UPDATE account_gameplay_token_identity_fences SET state = 'ACTIVE', " - + "token_identity_fence = 1, revocation_request_id = NULL, " - + "revocation_digest = NULL WHERE operation_id = ?", - identity.operationId()))) + assertThatThrownBy(() -> + inTransaction( + harness.context(), + () -> + harness + .dsl() + .execute( + "UPDATE account_gameplay_token_identity_fences SET state = 'ACTIVE', " + + "token_identity_fence = 1, revocation_request_id = NULL, " + + "revocation_digest = NULL WHERE operation_id = ?", + identity.operationId()))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - inTransaction( - harness.context(), - () -> - harness - .dsl() - .execute( - "DELETE FROM account_gameplay_token_identity_fences " - + "WHERE operation_id = ?", - identity.operationId()))) + assertThatThrownBy(() -> + inTransaction( + harness.context(), + () -> + harness + .dsl() + .execute( + "DELETE FROM account_gameplay_token_identity_fences " + + "WHERE operation_id = ?", + identity.operationId()))) .isInstanceOf(DataAccessException.class); assertThat( @@ -1066,53 +1040,51 @@ void racingAdmissionWaitsForAccountRevocationTransactionThenObservesPendingFence var executor = Executors.newFixedThreadPool(2); try { var revocation = - executor.submit( - () -> - inTransaction( - harness.context(), - () -> { - revocationPid.set( - Objects.requireNonNull( - harness.dsl().fetchOne("SELECT pg_backend_pid()"), - "revocation transaction must have a PostgreSQL backend") - .get(0, Integer.class)); - UUID requestId = UUID.randomUUID(); - var pending = - fences.beginRevocationIntent( - identity, - requestId, - AccountGameplayTokenIdentityFenceRepository.revocationDigest( - identity, requestId)); - pendingWritten.countDown(); - try { - if (!releaseRevocation.await(30, TimeUnit.SECONDS)) { - throw new IllegalStateException( - "Timed out waiting to release Account revocation transaction"); - } - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException( - "Interrupted waiting to release Account revocation transaction", - interrupted); - } - return pending; - })); + executor.submit(() -> + inTransaction( + harness.context(), + () -> { + revocationPid.set( + Objects.requireNonNull( + harness.dsl().fetchOne("SELECT pg_backend_pid()"), + "revocation transaction must have a PostgreSQL backend") + .get(0, Integer.class)); + UUID requestId = UUID.randomUUID(); + var pending = + fences.beginRevocationIntent( + identity, + requestId, + AccountGameplayTokenIdentityFenceRepository.revocationDigest( + identity, requestId)); + pendingWritten.countDown(); + try { + if (!releaseRevocation.await(30, TimeUnit.SECONDS)) { + throw new IllegalStateException( + "Timed out waiting to release Account revocation transaction"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted waiting to release Account revocation transaction", + interrupted); + } + return pending; + })); assertThat(pendingWritten.await(10, TimeUnit.SECONDS)).isTrue(); var admission = - executor.submit( - () -> - inTransaction( - harness.context(), - () -> { - readerPid.set( - Objects.requireNonNull( - harness.dsl().fetchOne("SELECT pg_backend_pid()"), - "admission transaction must have a PostgreSQL backend") - .get(0, Integer.class)); - readerPidCaptured.countDown(); - return fences.requireActiveForUpdate(identity); - })); + executor.submit(() -> + inTransaction( + harness.context(), + () -> { + readerPid.set( + Objects.requireNonNull( + harness.dsl().fetchOne("SELECT pg_backend_pid()"), + "admission transaction must have a PostgreSQL backend") + .get(0, Integer.class)); + readerPidCaptured.countDown(); + return fences.requireActiveForUpdate(identity); + })); assertThat(readerPidCaptured.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(revocationPid.get()).isPositive(); assertThat(readerPid.get()).isPositive().isNotEqualTo(revocationPid.get()); @@ -1170,29 +1142,27 @@ void concurrentDifferentAccountIssuerSnapshotsAndPendingIssuanceShareGlobalRows( var executor = Executors.newFixedThreadPool(2); try { var first = - executor.submit( - () -> - inTransaction( - context, - () -> { - sources.readCurrentIssuerAccountSources( - ACCOUNT_ISSUER, firstAccount.getAccountUuid()); - sharedIssuerSnapshotsHeld.countDown(); - awaitLatch(releaseIssuance, "release concurrent first Account issuance"); - return issuance.beginPending(firstIntent); - })); + executor.submit(() -> + inTransaction( + context, + () -> { + sources.readCurrentIssuerAccountSources( + ACCOUNT_ISSUER, firstAccount.getAccountUuid()); + sharedIssuerSnapshotsHeld.countDown(); + awaitLatch(releaseIssuance, "release concurrent first Account issuance"); + return issuance.beginPending(firstIntent); + })); var second = - executor.submit( - () -> - inTransaction( - context, - () -> { - sources.readCurrentIssuerAccountSources( - ACCOUNT_ISSUER, secondAccount.getAccountUuid()); - sharedIssuerSnapshotsHeld.countDown(); - awaitLatch(releaseIssuance, "release concurrent second Account issuance"); - return issuance.beginPending(secondIntent); - })); + executor.submit(() -> + inTransaction( + context, + () -> { + sources.readCurrentIssuerAccountSources( + ACCOUNT_ISSUER, secondAccount.getAccountUuid()); + sharedIssuerSnapshotsHeld.countDown(); + awaitLatch(releaseIssuance, "release concurrent second Account issuance"); + return issuance.beginPending(secondIntent); + })); assertThat(sharedIssuerSnapshotsHeld.await(10, TimeUnit.SECONDS)).isTrue(); releaseIssuance.countDown(); @@ -1277,23 +1247,17 @@ void signerProducedRsaProofCommitsWithExactOwnerEvidenceAndExactRetryDoesNotRepe CanonicalGameplayLoginRequest exactLoginRetry = harness.loginRequest(); AtomicInteger credentialVerifierCalls = new AtomicInteger(); var firstLoginReplay = - withAuthenticatedGameSession( - () -> - harness - .loginOwner() - .authenticate( - exactLoginRetry, - CALLER_WORKLOAD, - verifierMustNotRun(credentialVerifierCalls))); + withAuthenticatedGameSession(() -> + harness + .loginOwner() + .authenticate( + exactLoginRetry, CALLER_WORKLOAD, verifierMustNotRun(credentialVerifierCalls))); var exactLoginRetryResult = - withAuthenticatedGameSession( - () -> - harness - .loginOwner() - .authenticate( - exactLoginRetry, - CALLER_WORKLOAD, - verifierMustNotRun(credentialVerifierCalls))); + withAuthenticatedGameSession(() -> + harness + .loginOwner() + .authenticate( + exactLoginRetry, CALLER_WORKLOAD, verifierMustNotRun(credentialVerifierCalls))); assertThat(firstLoginReplay.accountId()).isEqualTo(harness.accountId()); assertThat(firstLoginReplay.tokenJti()).isEqualTo(harness.pending().tokenJti()); assertThat(firstLoginReplay.tokenSha256()).isEqualTo(row.get("token_hash", String.class)); @@ -1324,16 +1288,14 @@ void signerProducedRsaProofCommitsWithExactOwnerEvidenceAndExactRetryDoesNotRepe UUID.randomUUID(), sourceContext.canonicalClientAddress(), sourceContext.transportClass())); - assertThatThrownBy( - () -> - withAuthenticatedGameSession( - () -> - harness - .loginOwner() - .authenticate( - changedCallerContext, - CALLER_WORKLOAD, - verifierMustNotRun(credentialVerifierCalls)))) + assertThatThrownBy(() -> + withAuthenticatedGameSession(() -> + harness + .loginOwner() + .authenticate( + changedCallerContext, + CALLER_WORKLOAD, + verifierMustNotRun(credentialVerifierCalls)))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class); assertThat(credentialVerifierCalls).hasValue(0); @@ -1344,13 +1306,10 @@ void signerProducedRsaProofCommitsWithExactOwnerEvidenceAndExactRetryDoesNotRepe harness.sources(), Clock.fixed( Instant.ofEpochSecond(harness.pending().expiresAtEpochSecond()), ZoneOffset.UTC)); - assertThatThrownBy( - () -> - inTransaction( - harness.context(), - () -> - expiredReader.readCurrentGameplayLoginReplay( - harness.pending().requestId()))) + assertThatThrownBy(() -> + inTransaction( + harness.context(), + () -> expiredReader.readCurrentGameplayLoginReplay(harness.pending().requestId()))) .isInstanceOf( AccountGameplayDelegationIssuanceRepository.PendingCandidateUnavailableException.class); @@ -1415,16 +1374,14 @@ void signerProducedRsaProofCommitsWithExactOwnerEvidenceAndExactRetryDoesNotRepe assertThat(unchangedAfterAuthorityChange.get("commit_proof_canonical_bytes", byte[].class)) .containsExactly(originalProof); - assertThatThrownBy( - () -> - withAuthenticatedGameSession( - () -> - harness - .loginOwner() - .authenticate( - exactLoginRetry, - CALLER_WORKLOAD, - verifierMustNotRun(credentialVerifierCalls)))) + assertThatThrownBy(() -> + withAuthenticatedGameSession(() -> + harness + .loginOwner() + .authenticate( + exactLoginRetry, + CALLER_WORKLOAD, + verifierMustNotRun(credentialVerifierCalls)))) // This generic Account mutation has no closed source-event receipt. Reject its unsupported // authority before comparing a current snapshot with the retained issuance snapshot. .isInstanceOf(IllegalStateException.class) @@ -1507,35 +1464,33 @@ void realIssuerWriterInvalidatesAlreadySignedPendingCommit() throws Exception { var executor = Executors.newFixedThreadPool(2); try { var ownerRead = - executor.submit( - () -> - inTransaction( - harness.context(), - () -> { - harness - .sources() - .readCurrentIssuerAccountSources(ACCOUNT_ISSUER, harness.accountId()); - issuerSnapshotHeld.countDown(); - awaitLatch(releaseIssuerSnapshot, "release held issuer snapshot"); - return null; - })); + executor.submit(() -> + inTransaction( + harness.context(), + () -> { + harness + .sources() + .readCurrentIssuerAccountSources(ACCOUNT_ISSUER, harness.accountId()); + issuerSnapshotHeld.countDown(); + awaitLatch(releaseIssuerSnapshot, "release held issuer snapshot"); + return null; + })); assertThat(issuerSnapshotHeld.await(10, TimeUnit.SECONDS)).isTrue(); var issuerWriter = - executor.submit( - () -> { - inTransaction( - harness.context(), - () -> { - issuerWriterEntered.countDown(); - harness - .sources() - .appendIssuerAuthorityChange( - ACCOUNT_ISSUER, "SIGNER_COMPROMISE", UUID.randomUUID().toString()); - return null; - }); - issuerWriterCompleted.countDown(); - }); + executor.submit(() -> { + inTransaction( + harness.context(), + () -> { + issuerWriterEntered.countDown(); + harness + .sources() + .appendIssuerAuthorityChange( + ACCOUNT_ISSUER, "SIGNER_COMPROMISE", UUID.randomUUID().toString()); + return null; + }); + issuerWriterCompleted.countDown(); + }); assertThat(issuerWriterEntered.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(issuerWriterCompleted.await(250, TimeUnit.MILLISECONDS)).isFalse(); @@ -1676,11 +1631,10 @@ private CommitHarness newCommitHarness( issuance = spy(storedIssuance); AtomicInteger committedReads = new AtomicInteger(); AccountGameplayDelegationIssuanceRepository readbackSpy = issuance; - doAnswer( - invocation -> - committedReads.incrementAndGet() == 1 - ? invocation.callRealMethod() - : Optional.empty()) + doAnswer(invocation -> + committedReads.incrementAndGet() == 1 + ? invocation.callRealMethod() + : Optional.empty()) .when(readbackSpy) .readCommittedProof(pending.requestId()); } else if (hook == CommitHook.TRANSIENT_REDIS_READBACK) { @@ -1910,24 +1864,21 @@ private static void assertCommitBundleEvidenceUnchanged(CommitHarness harness, R private static void assertCommitProofRejected( CommitHarness harness, byte[] proofBytes, String safeConstraint) throws Exception { - assertThatThrownBy( - () -> - harness - .dsl() - .execute( - "UPDATE account_gameplay_delegation_issuance_operations " - + "SET status = 'COMMITTED', commit_proof_version = 1, " - + "commit_proof_sha256 = ?, commit_proof_canonical_bytes = ?, " - + "committed_at = CURRENT_TIMESTAMP WHERE request_id = ?", - sha256Hex(proofBytes), - proofBytes, - harness.pending().requestId())) + assertThatThrownBy(() -> + harness + .dsl() + .execute( + "UPDATE account_gameplay_delegation_issuance_operations " + + "SET status = 'COMMITTED', commit_proof_version = 1, " + + "commit_proof_sha256 = ?, commit_proof_canonical_bytes = ?, " + + "committed_at = CURRENT_TIMESTAMP WHERE request_id = ?", + sha256Hex(proofBytes), + proofBytes, + harness.pending().requestId())) .isInstanceOf(DataAccessException.class) - .satisfies( - failure -> - assertThat( - AccountGameplayDelegationCommitSignerFixture.safeFailureDiagnostic(failure)) - .isEqualTo("sqlstate=23514;constraint=" + safeConstraint)); + .satisfies(failure -> + assertThat(AccountGameplayDelegationCommitSignerFixture.safeFailureDiagnostic(failure)) + .isEqualTo("sqlstate=23514;constraint=" + safeConstraint)); assertPendingWithoutCommitProof(harness); assertThat(tokenFenceCount(harness)).isZero(); } @@ -1996,119 +1947,115 @@ static void advanceEmailVerifiedThroughOwner( AccountSecurityStateOperationRepository operations = new AccountSecurityStateOperationRepository(dsl); DraftAuthorizationFenceRepository fences = new DraftAuthorizationFenceRepository(dsl); - transaction.execute( - status -> { - Account account = - new AccountRepository(dsl, sources).findByAccountUuid(accountUuid).orElseThrow(); - var source = - sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountUuid).account(); - var roleRow = - Objects.requireNonNull( - dsl.fetchOne( - "SELECT global_roles, global_role_source_version " - + "FROM account_global_role_sources WHERE account_uuid = ? FOR SHARE", - accountUuid)); - long roleVersion = roleRow.get("global_role_source_version", Long.class); - AccountState before = - new AccountState( - account.isEmailVerified(), - AccountLoginAuthModes.read(account.getLoginAuthModes()).stream() - .map(Enum::name) - .sorted() - .toList(), - java.util.Arrays.stream(roleRow.get("global_roles", String[].class)) - .sorted() - .toList(), - account.getLifecycleState().name()); - AccountState after = - new AccountState( - true, before.loginAuthModes(), before.globalRoles(), before.lifecycleState()); - if (before.emailVerified()) - throw new IllegalStateException("Fixture expected unverified Account"); - UUID requestId = UUID.randomUUID(); - AccountSecurityStateMutationRequest request = - new AccountSecurityStateMutationRequest( - requestId, - accountUuid, - securityStateCorrelation(accountUuid, requestId), + transaction.execute(status -> { + Account account = + new AccountRepository(dsl, sources).findByAccountUuid(accountUuid).orElseThrow(); + var source = sources.readCurrentIssuerAccountSources(ACCOUNT_ISSUER, accountUuid).account(); + var roleRow = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT global_roles, global_role_source_version " + + "FROM account_global_role_sources WHERE account_uuid = ? FOR SHARE", + accountUuid)); + long roleVersion = roleRow.get("global_role_source_version", Long.class); + AccountState before = + new AccountState( + account.isEmailVerified(), + AccountLoginAuthModes.read(account.getLoginAuthModes()).stream() + .map(Enum::name) + .sorted() + .toList(), + java.util.Arrays.stream(roleRow.get("global_roles", String[].class)) + .sorted() + .toList(), + account.getLifecycleState().name()); + AccountState after = + new AccountState( + true, before.loginAuthModes(), before.globalRoles(), before.lifecycleState()); + if (before.emailVerified()) + throw new IllegalStateException("Fixture expected unverified Account"); + UUID requestId = UUID.randomUUID(); + AccountSecurityStateMutationRequest request = + new AccountSecurityStateMutationRequest( + requestId, + accountUuid, + securityStateCorrelation(accountUuid, requestId), + source.generation(), + source.sourceVersion(), + AccountSecurityStateOperationRepository.detectedKinds(before, after), + after); + long checkpointSequence = source.checkpoint().sequence(); + byte[] checkpointPayload = + checkpointSequence == 0L + ? new byte[0] + : outbox + .findEvent(accountStream(accountUuid), checkpointSequence) + .orElseThrow() + .payload(); + Capture draft = + new Capture( + account.getId(), + account.getAccountUuidProvenance(), + before, + new AccountAuthorityGenerationRepository.ScopeState( + source.scope(), source.generation(), source.sourceVersion(), - AccountSecurityStateOperationRepository.detectedKinds(before, after), - after); - long checkpointSequence = source.checkpoint().sequence(); - byte[] checkpointPayload = - checkpointSequence == 0L - ? new byte[0] - : outbox - .findEvent(accountStream(accountUuid), checkpointSequence) - .orElseThrow() - .payload(); - Capture draft = - new Capture( - account.getId(), - account.getAccountUuidProvenance(), - before, - new AccountAuthorityGenerationRepository.ScopeState( - source.scope(), - source.generation(), - source.sourceVersion(), - source.issuanceFence()), - checkpointSequence, - checkpointPayload, - roleVersion, - null); - byte[] captureBytes = - AccountSecurityStateOperationRepository.captureBytes(request, draft); - SourceEvidence sourceEvidence = - new SourceEvidence( - SourceKind.ACCOUNT, - accountUuid.toString(), - Long.toString(source.generation()), - Long.toString(source.sourceVersion()), - accountStream(accountUuid), - Long.toString(checkpointSequence), - captureBytes); - SourceChange change = - new SourceChange(UUID.randomUUID(), List.of(sourceEvidence), captureBytes); - Capture capture = - new Capture( - draft.accountId(), - draft.provenance(), - before, - draft.sourceState(), - checkpointSequence, - checkpointPayload, - roleVersion, - change); - fences.requestSourceChange(change); - if (!fences.sourceMutationPermitted(change)) - throw new IllegalStateException("Fixture owner source is not settled"); - operations.claim(request, capture); - var advanced = sources.prepareClosedAccountAdvance(accountUuid, source); - dsl.execute( - "UPDATE accounts SET email_verified = TRUE WHERE account_uuid = ?", accountUuid); - Event event = - outbox.append( - accountStream(accountUuid), - requestId.toString(), - sequence -> { - var sealed = - AccountSecurityStateAuthorityEventV1Codec.seal( - AccountSecurityStateMutationRequest.eventPreimage( - requestId, - accountUuid, - Long.toString(advanced.generation()), - Long.toString(advanced.sourceVersion()), - Long.toString(sequence), - request.mutationKinds(), - after)); - return new EventEvidence( - sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); - }); - fences.markSourceCommitted(change); - operations.complete(request, event, advanced, roleVersion); - return null; - }); + source.issuanceFence()), + checkpointSequence, + checkpointPayload, + roleVersion, + null); + byte[] captureBytes = AccountSecurityStateOperationRepository.captureBytes(request, draft); + SourceEvidence sourceEvidence = + new SourceEvidence( + SourceKind.ACCOUNT, + accountUuid.toString(), + Long.toString(source.generation()), + Long.toString(source.sourceVersion()), + accountStream(accountUuid), + Long.toString(checkpointSequence), + captureBytes); + SourceChange change = + new SourceChange(UUID.randomUUID(), List.of(sourceEvidence), captureBytes); + Capture capture = + new Capture( + draft.accountId(), + draft.provenance(), + before, + draft.sourceState(), + checkpointSequence, + checkpointPayload, + roleVersion, + change); + fences.requestSourceChange(change); + if (!fences.sourceMutationPermitted(change)) + throw new IllegalStateException("Fixture owner source is not settled"); + operations.claim(request, capture); + var advanced = sources.prepareClosedAccountAdvance(accountUuid, source); + dsl.execute("UPDATE accounts SET email_verified = TRUE WHERE account_uuid = ?", accountUuid); + Event event = + outbox.append( + accountStream(accountUuid), + requestId.toString(), + sequence -> { + var sealed = + AccountSecurityStateAuthorityEventV1Codec.seal( + AccountSecurityStateMutationRequest.eventPreimage( + requestId, + accountUuid, + Long.toString(advanced.generation()), + Long.toString(advanced.sourceVersion()), + Long.toString(sequence), + request.mutationKinds(), + after)); + return new EventEvidence( + sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); + }); + fences.markSourceCommitted(change); + operations.complete(request, event, advanced, roleVersion); + return null; + }); } private static byte[] securityStateCorrelation(UUID accountUuid, UUID operationId) { @@ -2287,12 +2234,11 @@ private static PendingIntent intent( snapshot .account() .accountSecurityCutoff() - .map( - value -> - new AccountSecurityCutoff( - value.accountAuthorityGeneration(), - value.outboxStreamKey(), - value.outboxSequence())) + .map(value -> + new AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())) .orElse(null); return new PendingIntent( UUID.randomUUID(), @@ -2635,65 +2581,62 @@ private RedisHarness( when(commands.aclWhoami()) .thenReturn(AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY); when(commands.scriptLoad(any(byte[].class))) - .thenAnswer( - invocation -> { - scriptLoadCount.incrementAndGet(); - return sha1Hex(invocation.getArgument(0)); - }); + .thenAnswer(invocation -> { + scriptLoadCount.incrementAndGet(); + return sha1Hex(invocation.getArgument(0)); + }); when(commands.evalsha( anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) - .thenAnswer( - invocation -> { - byte[][] keys = (byte[][]) invocation.getRawArguments()[2]; - byte[][] arguments = (byte[][]) invocation.getRawArguments()[3]; - String key = new String(keys[0], StandardCharsets.US_ASCII); - if (key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { - if (arguments.length == 2) { - pendingRecord.set(arguments[0].clone()); - } else if (arguments.length == 3) { - // The activation CAS ARGV order is exact PENDING bytes, exact ACTIVE bytes, - // and the original absolute deadline. Readback must see the ACTIVE record. - pendingRecord.set(arguments[1].clone()); - } else { - throw new AssertionError("Unexpected token-registry script arguments"); - } - absoluteExpiryMillis.set( - Long.parseLong( - new String(arguments[arguments.length - 1], StandardCharsets.US_ASCII))); - } else if (key.equals( - AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX - + GameSessionAccountDelegationProfile.ISSUER)) { - authorityProjectionBytes[0] = arguments[0].clone(); - } else if (key.equals( - AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId)) { - if (arguments.length == 3 && arguments[2].length > 0) { - authorityProjectionBytes[1] = arguments[2].clone(); - } - } - return 1L; - }); + .thenAnswer(invocation -> { + byte[][] keys = (byte[][]) invocation.getRawArguments()[2]; + byte[][] arguments = (byte[][]) invocation.getRawArguments()[3]; + String key = new String(keys[0], StandardCharsets.US_ASCII); + if (key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { + if (arguments.length == 2) { + pendingRecord.set(arguments[0].clone()); + } else if (arguments.length == 3) { + // The activation CAS ARGV order is exact PENDING bytes, exact ACTIVE bytes, + // and the original absolute deadline. Readback must see the ACTIVE record. + pendingRecord.set(arguments[1].clone()); + } else { + throw new AssertionError("Unexpected token-registry script arguments"); + } + absoluteExpiryMillis.set( + Long.parseLong( + new String(arguments[arguments.length - 1], StandardCharsets.US_ASCII))); + } else if (key.equals( + AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER)) { + authorityProjectionBytes[0] = arguments[0].clone(); + } else if (key.equals( + AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId)) { + if (arguments.length == 3 && arguments[2].length > 0) { + authorityProjectionBytes[1] = arguments[2].clone(); + } + } + return 1L; + }); when(commands.get(any(byte[].class))) - .thenAnswer( - invocation -> { - String key = new String(invocation.getArgument(0), StandardCharsets.US_ASCII); - if (key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { - byte[] value = pendingRecord.get(); - if (value == null) return null; - return this.mismatchPendingReadback - ? ascii("different-pending-record") - : value.clone(); - } - if ((AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX - + GameSessionAccountDelegationProfile.ISSUER) - .equals(key)) { - return authorityProjectionBytes[0].clone(); - } - if ((AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId) - .equals(key)) { - return authorityProjectionBytes[1].clone(); - } - return null; - }); + .thenAnswer(invocation -> { + String key = new String(invocation.getArgument(0), StandardCharsets.US_ASCII); + if (key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { + byte[] value = pendingRecord.get(); + if (value == null) return null; + return this.mismatchPendingReadback + ? ascii("different-pending-record") + : value.clone(); + } + if ((AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER) + .equals(key)) { + return authorityProjectionBytes[0].clone(); + } + if ((AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX + accountId) + .equals(key)) { + return authorityProjectionBytes[1].clone(); + } + return null; + }); when(commands.pexpiretime(any(byte[].class))) .thenAnswer(invocation -> absoluteExpiryMillis.get()); when(commands.pttl( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopePersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopePersistenceIntegrationTest.java index ee72ecd6a2..4a332b09aa 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopePersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopePersistenceIntegrationTest.java @@ -123,21 +123,17 @@ void storesExactEncryptedCandidateAndRejectsMismatchRollbackAndExpiredHorizon() AccountGameplayDelegationResponseEnvelopeRepository.SealedCandidateObservation first; try { Future directCapture = - concurrentCaptureAndSeal.submit( - () -> { - captureAndSealStart.await(); - return inTransaction(context, () -> bundles.captureAndPersist(pending.requestId())); - }); + concurrentCaptureAndSeal.submit(() -> { + captureAndSealStart.await(); + return inTransaction(context, () -> bundles.captureAndPersist(pending.requestId())); + }); Future seal = - concurrentCaptureAndSeal.submit( - () -> { - captureAndSealStart.await(); - return inTransaction( - context, - () -> - realResponses.sealPendingCandidate( - pending.requestId(), caller, compactJwt)); - }); + concurrentCaptureAndSeal.submit(() -> { + captureAndSealStart.await(); + return inTransaction( + context, + () -> realResponses.sealPendingCandidate(pending.requestId(), caller, compactJwt)); + }); captureAndSealStart.countDown(); concurrentBundle = awaitConcurrentProof(directCapture); first = awaitConcurrentProof(seal); @@ -199,23 +195,21 @@ void storesExactEncryptedCandidateAndRejectsMismatchRollbackAndExpiredHorizon() .get("pending_registry_candidate_bytes", byte[].class); assertThat(new String(boundMetadata, StandardCharsets.ISO_8859_1)).doesNotContain(compactJwt); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - realResponses.sealPendingCandidate( - pending.requestId(), caller, compactJwt + "A"))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + realResponses.sealPendingCandidate( + pending.requestId(), caller, compactJwt + "A"))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE account_gameplay_delegation_response_envelopes " - + "SET envelope_bytes = ? WHERE operation_id = ?", - new byte[] {1, 2, 3}, - pending.operationId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE account_gameplay_delegation_response_envelopes " + + "SET envelope_bytes = ? WHERE operation_id = ?", + new byte[] {1, 2, 3}, + pending.operationId())) .isInstanceOf(DataAccessException.class); assertThat( Objects.requireNonNull( @@ -249,24 +243,23 @@ void storesExactEncryptedCandidateAndRejectsMismatchRollbackAndExpiredHorizon() .get("bundle_count", Long.class)) .isEqualTo(2L); byte[] fakeCiphertext = new byte[] {1, 2, 3}; - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO account_gameplay_delegation_response_envelopes " - + "(operation_id, request_id, token_hash, signer_kid, " - + "signer_generation, authority_evidence_bundle_sha256, " - + "issuance_fence, response_recovery_expiry_epoch_ms, " - + "envelope_sha256, envelope_bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - secondPending.operationId(), - secondPending.requestId(), - secondCandidate.tokenHash(), - secondCandidate.kid(), - secondCandidate.signerGeneration(), - "a".repeat(64), - authority.issuanceFence().value(), - Math.multiplyExact(secondPending.expiresAtEpochSecond(), 1_000L), - sha256(fakeCiphertext), - fakeCiphertext)) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO account_gameplay_delegation_response_envelopes " + + "(operation_id, request_id, token_hash, signer_kid, " + + "signer_generation, authority_evidence_bundle_sha256, " + + "issuance_fence, response_recovery_expiry_epoch_ms, " + + "envelope_sha256, envelope_bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + secondPending.operationId(), + secondPending.requestId(), + secondCandidate.tokenHash(), + secondCandidate.kid(), + secondCandidate.signerGeneration(), + "a".repeat(64), + authority.issuanceFence().value(), + Math.multiplyExact(secondPending.expiresAtEpochSecond(), 1_000L), + sha256(fakeCiphertext), + fakeCiphertext)) .isInstanceOf(DataAccessException.class); var unavailableCrypto = @@ -276,13 +269,12 @@ void storesExactEncryptedCandidateAndRejectsMismatchRollbackAndExpiredHorizon() dsl, sourceEvidence, bundles, unavailableCrypto); CallerIdentity secondCaller = new CallerIdentity(secondPending.callerWorkload(), secondPending.callerContextId()); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - unavailableResponses.sealPendingCandidate( - secondPending.requestId(), secondCaller, secondJwt))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + unavailableResponses.sealPendingCandidate( + secondPending.requestId(), secondCaller, secondJwt))) .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); assertThat( Objects.requireNonNull( @@ -325,25 +317,23 @@ void storesExactEncryptedCandidateAndRejectsMismatchRollbackAndExpiredHorizon() ExecutorService concurrentRetries = Executors.newFixedThreadPool(2); try { Future firstRetry = - concurrentRetries.submit( - () -> { - concurrentStart.await(); - return inTransaction( - context, - () -> - realResponses.sealPendingCandidate( - secondPending.requestId(), secondCaller, secondJwt)); - }); + concurrentRetries.submit(() -> { + concurrentStart.await(); + return inTransaction( + context, + () -> + realResponses.sealPendingCandidate( + secondPending.requestId(), secondCaller, secondJwt)); + }); Future secondRetry = - concurrentRetries.submit( - () -> { - concurrentStart.await(); - return inTransaction( - context, - () -> - realResponses.sealPendingCandidate( - secondPending.requestId(), secondCaller, secondJwt)); - }); + concurrentRetries.submit(() -> { + concurrentStart.await(); + return inTransaction( + context, + () -> + realResponses.sealPendingCandidate( + secondPending.requestId(), secondCaller, secondJwt)); + }); concurrentStart.countDown(); var firstConcurrentObservation = awaitConcurrentProof(firstRetry); var secondConcurrentObservation = awaitConcurrentProof(secondRetry); @@ -376,16 +366,15 @@ void storesExactEncryptedCandidateAndRejectsMismatchRollbackAndExpiredHorizon() AccountGameplayDelegationResponseEnvelopeRepository expiredResponses = new AccountGameplayDelegationResponseEnvelopeRepository( dsl, sourceEvidence, bundles, realCrypto); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - expiredResponses.sealPendingCandidate( - expiredPending.requestId(), - new CallerIdentity( - expiredPending.callerWorkload(), expiredPending.callerContextId()), - expiredJwt))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + expiredResponses.sealPendingCandidate( + expiredPending.requestId(), + new CallerIdentity( + expiredPending.callerWorkload(), expiredPending.callerContextId()), + expiredJwt))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.ResponseRecoveryExpiredException .class); @@ -446,12 +435,11 @@ private static AccountAuthoritySnapshot authoritySnapshot(IssuerAccountSourceSna snapshot .account() .accountSecurityCutoff() - .map( - value -> - new GameSessionAccountDelegationProfile.AccountSecurityCutoff( - value.accountAuthorityGeneration(), - value.outboxStreamKey(), - value.outboxSequence())); + .map(value -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())); return new AccountAuthoritySnapshot( snapshot.account().scope().accountId(), snapshot.issuer().generation(), diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseRecoveryPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseRecoveryPersistenceIntegrationTest.java index 7a5afcc1f3..30bdbda2e5 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseRecoveryPersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseRecoveryPersistenceIntegrationTest.java @@ -281,12 +281,11 @@ private static AccountAuthoritySnapshot authoritySnapshot(IssuerAccountSourceSna source .account() .accountSecurityCutoff() - .map( - value -> - new AccountSecurityCutoff( - value.accountAuthorityGeneration(), - value.outboxStreamKey(), - value.outboxSequence())); + .map(value -> + new AccountSecurityCutoff( + value.accountAuthorityGeneration(), + value.outboxStreamKey(), + value.outboxSequence())); return new AccountAuthoritySnapshot( source.account().scope().accountId(), source.issuer().generation(), @@ -378,69 +377,62 @@ private RedisHarness(IssuerAccountSourceSnapshot snapshot, ClassLoader classLoad .thenAnswer(invocation -> sha1(invocation.getArgument(0))); when(commands.evalsha( anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) - .thenAnswer( - invocation -> { - byte[][] keys = invocation.getArgument(2); - byte[][] arguments = (byte[][]) invocation.getRawArguments()[3]; - String key = new String(keys[0], StandardCharsets.US_ASCII); - if (!key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { - return 0L; - } - if (arguments.length == 2) { - byte[] existing = tokenRecord.get(); - long expiry = Long.parseLong(new String(arguments[1], StandardCharsets.US_ASCII)); - if (existing == null) { - tokenRecord.set(arguments[0].clone()); - absoluteExpiryMillis.set(expiry); - return 1L; - } - return Arrays.equals(existing, arguments[0]) - && absoluteExpiryMillis.get() == expiry - ? 0L - : -1L; - } - if (arguments.length == 3) { - byte[] observed = tokenRecord.get(); - long expiry = Long.parseLong(new String(arguments[2], StandardCharsets.US_ASCII)); - if (Arrays.equals(observed, arguments[0]) - && absoluteExpiryMillis.get() == expiry) { - tokenRecord.set(arguments[1].clone()); - return 1L; - } - return Arrays.equals(observed, arguments[1]) - && absoluteExpiryMillis.get() == expiry - ? 0L - : -1L; - } - return -1L; - }); + .thenAnswer(invocation -> { + byte[][] keys = invocation.getArgument(2); + byte[][] arguments = (byte[][]) invocation.getRawArguments()[3]; + String key = new String(keys[0], StandardCharsets.US_ASCII); + if (!key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { + return 0L; + } + if (arguments.length == 2) { + byte[] existing = tokenRecord.get(); + long expiry = Long.parseLong(new String(arguments[1], StandardCharsets.US_ASCII)); + if (existing == null) { + tokenRecord.set(arguments[0].clone()); + absoluteExpiryMillis.set(expiry); + return 1L; + } + return Arrays.equals(existing, arguments[0]) && absoluteExpiryMillis.get() == expiry + ? 0L + : -1L; + } + if (arguments.length == 3) { + byte[] observed = tokenRecord.get(); + long expiry = Long.parseLong(new String(arguments[2], StandardCharsets.US_ASCII)); + if (Arrays.equals(observed, arguments[0]) && absoluteExpiryMillis.get() == expiry) { + tokenRecord.set(arguments[1].clone()); + return 1L; + } + return Arrays.equals(observed, arguments[1]) && absoluteExpiryMillis.get() == expiry + ? 0L + : -1L; + } + return -1L; + }); when(commands.get(any(byte[].class))) - .thenAnswer( - invocation -> { - String key = new String(invocation.getArgument(0), StandardCharsets.US_ASCII); - if (key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { - byte[] value = tokenRecord.get(); - return value == null ? null : value.clone(); - } - if ((AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX - + GameSessionAccountDelegationProfile.ISSUER) - .equals(key)) { - return projections[0].clone(); - } - if (key.startsWith( - AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX)) { - return projections[1].clone(); - } - return null; - }); + .thenAnswer(invocation -> { + String key = new String(invocation.getArgument(0), StandardCharsets.US_ASCII); + if (key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX)) { + byte[] value = tokenRecord.get(); + return value == null ? null : value.clone(); + } + if ((AccountGameplayDelegationAuthorityProjection.ISSUER_KEY_PREFIX + + GameSessionAccountDelegationProfile.ISSUER) + .equals(key)) { + return projections[0].clone(); + } + if (key.startsWith(AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX)) { + return projections[1].clone(); + } + return null; + }); when(commands.pexpiretime(any(byte[].class))) - .thenAnswer( - invocation -> { - String key = new String(invocation.getArgument(0), StandardCharsets.US_ASCII); - return key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX) - ? absoluteExpiryMillis.get() - : null; - }); + .thenAnswer(invocation -> { + String key = new String(invocation.getArgument(0), StandardCharsets.US_ASCII); + return key.startsWith(AccountGameplayDelegationRedisClient.TOKEN_KEY_PREFIX) + ? absoluteExpiryMillis.get() + : null; + }); when(commands.pttl( eq( (AccountGameplayDelegationAuthorityProjection.ACCOUNT_KEY_PREFIX diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchClockPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchClockPostgresIntegrationTest.java index 5c7a518e5c..6a9c143ddc 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchClockPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchClockPostgresIntegrationTest.java @@ -88,31 +88,29 @@ void backdatedDispatchCannotConsumeFirstPermissionAfterActualDatabaseExpiry( // nor the caller's earlier recorded_at is a valid substitute for the trigger's late clock read. Instant sampled = databaseNow(f); assertThat(sampled).isBefore(claim.expiresAt()); - assertThatThrownBy( - () -> - f.transaction() - .executeWithoutResult( - s -> { - assertThat(databaseNow(f)).isBefore(claim.expiresAt()); - f.dsl() - .execute( - "SELECT pg_sleep_until(?::timestamptz)", - claim.expiresAt().plusMillis(5).atOffset(ZoneOffset.UTC)); - assertThat(databaseNow(f)).isAfterOrEqualTo(claim.expiresAt()); - f.dsl() - .execute( - "INSERT INTO subscription_provider_dispatch_claim " - + "(creation_request_id, subscription_id, provider_operation_id, dispatch_id, " - + "classification, first_attempt_id, first_claimed_row_version, recorded_at) " - + "VALUES (?, ?, ?, ?, 'FIRST_DISPATCH', ?, ?, ?::timestamptz)", - f.creation().requestId(), - f.creation().subscriptionId(), - f.creation().subscriptionProvisioningRequestId(), - UUID.randomUUID(), - claim.attemptId(), - claim.subscriptionRowVersion(), - sampled.atOffset(ZoneOffset.UTC)); - })) + assertThatThrownBy(() -> + f.transaction() + .executeWithoutResult(s -> { + assertThat(databaseNow(f)).isBefore(claim.expiresAt()); + f.dsl() + .execute( + "SELECT pg_sleep_until(?::timestamptz)", + claim.expiresAt().plusMillis(5).atOffset(ZoneOffset.UTC)); + assertThat(databaseNow(f)).isAfterOrEqualTo(claim.expiresAt()); + f.dsl() + .execute( + "INSERT INTO subscription_provider_dispatch_claim " + + "(creation_request_id, subscription_id, provider_operation_id, dispatch_id, " + + "classification, first_attempt_id, first_claimed_row_version, recorded_at) " + + "VALUES (?, ?, ?, ?, 'FIRST_DISPATCH', ?, ?, ?::timestamptz)", + f.creation().requestId(), + f.creation().subscriptionId(), + f.creation().subscriptionProvisioningRequestId(), + UUID.randomUUID(), + claim.attemptId(), + claim.subscriptionRowVersion(), + sampled.atOffset(ZoneOffset.UTC)); + })) .isInstanceOf(DataAccessException.class) .hasMessageContaining("Provider dispatch lacks exact live original provisioning fence") .satisfies( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java index 2de7e05f08..fcb539a456 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionDispatchPostgresIntegrationTest.java @@ -119,15 +119,14 @@ void upgradeRetainsControlledUnclaimedWorkWithoutInventingDispatchHistory() { // Controlled retained state is inserted directly with the normal SQL guards enabled. The // existing production claim owner does not commit nonterminal work without its first attempt. f.tx() - .executeWithoutResult( - s -> - f.dsl() - .execute( - "INSERT INTO subscription_provisioning_work (request_id, subscription_id, phase, row_version, " - + "attempt_count, max_attempts, max_stalled_attempts, lease_millis, backoff_millis, deadline_at, retry_at) " - + "SELECT request_id, subscription_id, 'RECONCILING', 1, 0, 4, 3, 10000, 1000, " - + "created_at + interval '1 hour', created_at FROM subscription_create_operations WHERE request_id = ?", - f.creation().requestId())); + .executeWithoutResult(s -> + f.dsl() + .execute( + "INSERT INTO subscription_provisioning_work (request_id, subscription_id, phase, row_version, " + + "attempt_count, max_attempts, max_stalled_attempts, lease_millis, backoff_millis, deadline_at, retry_at) " + + "SELECT request_id, subscription_id, 'RECONCILING', 1, 0, 4, 3, 10000, 1000, " + + "created_at + interval '1 hour', created_at FROM subscription_create_operations WHERE request_id = ?", + f.creation().requestId())); var retained = f.dsl() .fetch( @@ -223,17 +222,15 @@ void onlyOneFreshInsertionCarriesInitialPermissionAndIndependentReadbackIsMandat var start = new CountDownLatch(1); try (var executor = Executors.newFixedThreadPool(2)) { var first = - executor.submit( - () -> { - start.await(); - return prepareAndRead(f, claim); - }); + executor.submit(() -> { + start.await(); + return prepareAndRead(f, claim); + }); var second = - executor.submit( - () -> { - start.await(); - return prepareAndRead(f, claim); - }); + executor.submit(() -> { + start.await(); + return prepareAndRead(f, claim); + }); start.countDown(); var results = List.of(first.get(20, TimeUnit.SECONDS), second.get(20, TimeUnit.SECONDS)); assertThat(results) @@ -248,15 +245,12 @@ void onlyOneFreshInsertionCarriesInitialPermissionAndIndependentReadbackIsMandat void uncommittedSameTransactionReadbackCannotProduceProviderPermission() { Fixture f = fixture("1032"); var claim = claim(f, 1); - assertThatThrownBy( - () -> - f.tx() - .execute( - s -> { - var uncommitted = - f.owner().prepareProviderDispatch(claim, UUID.randomUUID()); - return f.owner().readProviderDispatch(uncommitted); - })) + assertThatThrownBy(() -> + f.tx() + .execute(s -> { + var uncommitted = f.owner().prepareProviderDispatch(claim, UUID.randomUUID()); + return f.owner().readProviderDispatch(uncommitted); + })) .hasMessageContaining("new transaction"); assertThat(f.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))).isZero(); } @@ -295,12 +289,10 @@ void expiredExactAttemptReturnsTypedPendingAndReplacedStaleWorkerHitsBindingFenc } var replacement = claim(f, original.subscriptionRowVersion()); assertThat(replacement.attemptId()).isNotEqualTo(original.attemptId()); - before.replaceAll( - (table, rows) -> - f.dsl() - .fetch( - "SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM " + table + " t") - .intoMaps()); + before.replaceAll((table, rows) -> + f.dsl() + .fetch("SELECT row_to_json(t)::text AS row, xmin::text AS xmin FROM " + table + " t") + .intoMaps()); // Replacement advanced the subscription version, so the original binding rejects this stale // worker before the later attempt-identity check can run. assertThatThrownBy(() -> f.tx().execute(status -> f.owner().deferUnresolved(original))) @@ -465,13 +457,12 @@ void liveFinalBudgetDispatchSurvivesDisplayRefreshAndCompetingClaim() { refreshDisplay(f); var competing = f.tx() - .execute( - s -> - f.owner() - .claim( - f.creation().requestId(), - finalClaim.subscriptionRowVersion(), - UUID.randomUUID())); + .execute(s -> + f.owner() + .claim( + f.creation().requestId(), + finalClaim.subscriptionRowVersion(), + UUID.randomUUID())); assertThat(competing.disposition()).isEqualTo(Disposition.WAITING); assertThat(competing.claim()).isNull(); assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_operator_outbox"))) @@ -548,10 +539,8 @@ void prolongedEmptySearchAfterLostCreateStopsWithOneOperatorItemAndHeldReservati var retry = Objects.requireNonNull( f.tx() - .execute( - s -> - f.owner() - .claim(f.creation().requestId(), finalVersion, UUID.randomUUID()))); + .execute(s -> + f.owner().claim(f.creation().requestId(), finalVersion, UUID.randomUUID()))); assertThat(retry.disposition()).isEqualTo(Disposition.TERMINAL_FAILURE); assertThat(retry.claim()).isNull(); assertThat(f.transport().searches).isEqualTo(3); @@ -598,9 +587,8 @@ void displayRefreshAfterClaimRefusesDispatchButRetainedWorkReachesOperatorDeadli f.dsl().fetch("SELECT * FROM subscription_instrument_reservations").intoMaps(); refreshDisplay(f); - assertThatThrownBy( - () -> - f.tx().execute(s -> f.owner().prepareProviderDispatch(original, UUID.randomUUID()))) + assertThatThrownBy(() -> + f.tx().execute(s -> f.owner().prepareProviderDispatch(original, UUID.randomUUID()))) .isInstanceOf(FenceRejectedException.class); var refused = (AccountHostingSubscriptionProvisioningService.Pending) @@ -611,13 +599,12 @@ void displayRefreshAfterClaimRefusesDispatchButRetainedWorkReachesOperatorDeadli new StripeHostingSubscriptionProvisioner.Pending("DISPATCH_FENCE_REJECTED", null)); var waiting = f.tx() - .execute( - s -> - f.owner() - .claim( - f.creation().requestId(), - original.subscriptionRowVersion(), - UUID.randomUUID())); + .execute(s -> + f.owner() + .claim( + f.creation().requestId(), + original.subscriptionRowVersion(), + UUID.randomUUID())); assertThat(waiting.disposition()).isEqualTo(Disposition.WAITING); assertThat(waiting.claim()).isNull(); assertThat(f.dsl().fetchCount(DSL.table("subscription_provisioning_attempts"))).isOne(); @@ -627,13 +614,12 @@ void displayRefreshAfterClaimRefusesDispatchButRetainedWorkReachesOperatorDeadli var terminal = f.tx() - .execute( - s -> - f.owner() - .claim( - f.creation().requestId(), - original.subscriptionRowVersion(), - UUID.randomUUID())); + .execute(s -> + f.owner() + .claim( + f.creation().requestId(), + original.subscriptionRowVersion(), + UUID.randomUUID())); assertThat(terminal.disposition()).isEqualTo(Disposition.TERMINAL_FAILURE); assertThat(terminal.claim()).isNull(); assertThat(f.tx().execute(s -> f.owner().deferUnresolved(original))) @@ -690,11 +676,8 @@ void displayRefreshBeforeInitialClaimRetainsTerminalFailureWithoutDispatch() { var refused = unclaimed .tx() - .execute( - s -> - unclaimed - .owner() - .claim(unclaimed.creation().requestId(), 1, UUID.randomUUID())); + .execute(s -> + unclaimed.owner().claim(unclaimed.creation().requestId(), 1, UUID.randomUUID())); assertThat(Objects.requireNonNull(refused).disposition()) .isEqualTo(Disposition.TERMINAL_FAILURE); assertThat(refused.claim()).isNull(); @@ -721,26 +704,24 @@ void displayRefreshDoesNotAuthorizeDirectDispatchInsert() { var original = claim(retained, 1); refreshDisplay(retained); // Exercise the unchanged V1032 insertion guard independently of the Java eligibility fence. - assertThatThrownBy( - () -> - retained - .tx() - .execute( - s -> - retained - .dsl() - .execute( - "INSERT INTO subscription_provider_dispatch_claim " - + "(creation_request_id, subscription_id, provider_operation_id, dispatch_id, " - + "classification, first_attempt_id, first_claimed_row_version, recorded_at) " - + "VALUES (?, ?, ?, ?, 'FIRST_DISPATCH', ?, ?, ?::timestamptz)", - retained.creation().requestId(), - retained.creation().subscriptionId(), - retained.creation().subscriptionProvisioningRequestId(), - UUID.randomUUID(), - original.attemptId(), - original.subscriptionRowVersion(), - retained.clock().instant().atOffset(ZoneOffset.UTC)))) + assertThatThrownBy(() -> + retained + .tx() + .execute(s -> + retained + .dsl() + .execute( + "INSERT INTO subscription_provider_dispatch_claim " + + "(creation_request_id, subscription_id, provider_operation_id, dispatch_id, " + + "classification, first_attempt_id, first_claimed_row_version, recorded_at) " + + "VALUES (?, ?, ?, ?, 'FIRST_DISPATCH', ?, ?, ?::timestamptz)", + retained.creation().requestId(), + retained.creation().subscriptionId(), + retained.creation().subscriptionProvisioningRequestId(), + UUID.randomUUID(), + original.attemptId(), + original.subscriptionRowVersion(), + retained.clock().instant().atOffset(ZoneOffset.UTC)))) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("Provider dispatch lacks exact live original provisioning fence"); assertThat(retained.dsl().fetchCount(DSL.table("subscription_provider_dispatch_claim"))) @@ -758,10 +739,8 @@ void displayRefreshDoesNotLetStaleWorkerSettleReplacementOrRewriteOriginalBindin var before = f.dsl().fetch("SELECT * FROM subscription_provisioning_work").intoMaps(); assertThatThrownBy(() -> f.tx().execute(s -> f.owner().deferUnresolved(first))) .isInstanceOf(FenceRejectedException.class); - assertThatThrownBy( - () -> - f.tx() - .execute(s -> f.owner().claim(f.creation().requestId(), 1, first.attemptId()))) + assertThatThrownBy(() -> + f.tx().execute(s -> f.owner().claim(f.creation().requestId(), 1, first.attemptId()))) .isInstanceOf(FenceRejectedException.class); assertThat(f.dsl().fetch("SELECT * FROM subscription_provisioning_work").intoMaps()) .isEqualTo(before); @@ -778,17 +757,15 @@ void displayRefreshDoesNotLetStaleWorkerSettleReplacementOrRewriteOriginalBindin .hasMessage("Exact retained provisioning settlement claim rejected"); // The database also retains its existing owner-change guard; this component cannot invent an // unaudited transfer merely to manufacture a changed-current-owner state. - assertThatThrownBy( - () -> - f.tx() - .execute( - s -> - f.dsl() - .execute( - "UPDATE account_tenant_billing_owners SET owner_version = owner_version + 1, " - + "owner_generation = ? WHERE tenant_uuid = ?", - UUID.randomUUID(), - f.creation().tenantId()))) + assertThatThrownBy(() -> + f.tx() + .execute(s -> + f.dsl() + .execute( + "UPDATE account_tenant_billing_owners SET owner_version = owner_version + 1, " + + "owner_generation = ? WHERE tenant_uuid = ?", + UUID.randomUUID(), + f.creation().tenantId()))) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(f.dsl().fetch("SELECT * FROM subscription_provisioning_work").intoMaps()) .isEqualTo(before); @@ -828,11 +805,8 @@ private static ProvisioningClaim claim(Fixture f, long version) { ProvisioningClaim claim = Objects.requireNonNull( f.tx() - .execute( - s -> - f.owner() - .claim(f.creation().requestId(), version, UUID.randomUUID()) - .claim())); + .execute(s -> + f.owner().claim(f.creation().requestId(), version, UUID.randomUUID()).claim())); // The controlled provider observation clock follows the real, newly issued DB lease. f.clock().now = claim.claimedAt(); return claim; diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java index da0f3691b3..f41d1ae7cb 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecyclePostgresIntegrationTest.java @@ -137,11 +137,9 @@ void actualSdkReadCommitsExactMappingReceiptCanonicalStreamsAndConsistentReaderT assertThat(count(c, "subscription_lifecycle_receipts")).isOne(); assertThat(count(c, "account_tenant_entitlement_outbox_events")).isOne(); assertThat(count(c, "account_authority_outbox_events")).isOne(); - assertThatThrownBy( - () -> - f.service() - .reconcile( - request, f.creation().requestId(), 2, "sub_other", claim.attemptId())) + assertThatThrownBy(() -> + f.service() + .reconcile(request, f.creation().requestId(), 2, "sub_other", claim.attemptId())) .hasMessageContaining("IDEMPOTENCY_CONFLICT"); assertThat(f.transport().reads).isEqualTo(reads); } @@ -202,33 +200,30 @@ void rawSqlActiveMappingWithoutGenuineClaimAndReceiptCannotBecomeAReadOrLifecycl Context c = context("1030"); Fixture f = fixture(c); c.tx() - .executeWithoutResult( - s -> { - c.dsl() - .execute( - "INSERT INTO subscription_provider_history (provider_subscription_id, subscription_id, operation_kind, request_id, " - + "provider_operation_id, role, effective_at, evidence_digest) VALUES (?, ?, 'SUBSCRIPTION_PROVISIONING', ?, ?, 'canonical', ?::timestamptz, ?)", - f.providerId(), - f.creation().subscriptionId(), - f.creation().requestId(), - f.creation().subscriptionProvisioningRequestId(), - f.clock().instant().atOffset(ZoneOffset.UTC), - DIGEST); - c.dsl() - .execute( - "UPDATE subscription SET status = 'active', provider_subscription_id = ?, row_version = row_version + 1 WHERE subscription_id = ?", - f.providerId(), - f.creation().subscriptionId()); - }); + .executeWithoutResult(s -> { + c.dsl() + .execute( + "INSERT INTO subscription_provider_history (provider_subscription_id, subscription_id, operation_kind, request_id, " + + "provider_operation_id, role, effective_at, evidence_digest) VALUES (?, ?, 'SUBSCRIPTION_PROVISIONING', ?, ?, 'canonical', ?::timestamptz, ?)", + f.providerId(), + f.creation().subscriptionId(), + f.creation().requestId(), + f.creation().subscriptionProvisioningRequestId(), + f.clock().instant().atOffset(ZoneOffset.UTC), + DIGEST); + c.dsl() + .execute( + "UPDATE subscription SET status = 'active', provider_subscription_id = ?, row_version = row_version + 1 WHERE subscription_id = ?", + f.providerId(), + f.creation().subscriptionId()); + }); assertThat(c.intents().findCurrentByTenant(f.creation().tenantId()).orElseThrow().status()) .isEqualTo("active"); assertThatThrownBy(() -> f.service().readCurrent(f.creation().tenantId())) .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); - assertThatThrownBy( - () -> - f.service() - .reconcile( - UUID.randomUUID(), f.creation().requestId(), 2, f.providerId(), null)) + assertThatThrownBy(() -> + f.service() + .reconcile(UUID.randomUUID(), f.creation().requestId(), 2, f.providerId(), null)) .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); assertThat(f.transport().reads).isZero(); assertThat(count(c, "subscription_lifecycle_receipts")).isZero(); @@ -315,11 +310,10 @@ void concurrentSameRequestObservesOneInflightOwnerAndReplaysOneCommittedTransiti var executor = Executors.newSingleThreadExecutor(); try { var winner = - executor.submit( - () -> - f.service() - .reconcile( - request, f.creation().requestId(), 2, f.providerId(), claim.attemptId())); + executor.submit(() -> + f.service() + .reconcile( + request, f.creation().requestId(), 2, f.providerId(), claim.attemptId())); assertThat(reading.await(5, TimeUnit.SECONDS)).isTrue(); assertThat( f.service() @@ -433,15 +427,14 @@ void walletDisplayAdvanceDuringSdkReadPreservesBindingAndStaleRowOwnerInputsReje Context c = context("1030"); Fixture f = fixture(c); var claim = claim(f); - assertThatThrownBy( - () -> - f.service() - .reconcile( - UUID.randomUUID(), - f.creation().requestId(), - 1, - f.providerId(), - claim.attemptId())) + assertThatThrownBy(() -> + f.service() + .reconcile( + UUID.randomUUID(), + f.creation().requestId(), + 1, + f.providerId(), + claim.attemptId())) .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); assertThat(f.transport().reads).isZero(); var wrongOwner = @@ -523,27 +516,23 @@ void walletDisplayAdvanceDuringSdkReadPreservesBindingAndStaleRowOwnerInputsReje "23514", () -> c.tx() - .executeWithoutResult( - s -> { - assertThat(f.owner().apply(prepared, actualSdk).outcome()) - .isEqualTo(Outcome.COMMITTED); - var sameTransactionFence = - f.owner().prepareCurrentRead(f.creation().tenantId()); - assertThat( - f.owner() - .readCurrent(sameTransactionFence, actualSdk) - .allowPublicJoin()) - .isTrue(); - // A real monotonic generation advance without its source event must fail at - // transaction - // completion, after the lifecycle owner's ordinary writes and exact readback - // have executed. - c.dsl() - .execute( - "UPDATE account_authority_generations SET generation = generation + 1, source_version = source_version + 1 " - + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", - f.creation().tenantId()); - })); + .executeWithoutResult(s -> { + assertThat(f.owner().apply(prepared, actualSdk).outcome()) + .isEqualTo(Outcome.COMMITTED); + var sameTransactionFence = f.owner().prepareCurrentRead(f.creation().tenantId()); + assertThat( + f.owner().readCurrent(sameTransactionFence, actualSdk).allowPublicJoin()) + .isTrue(); + // A real monotonic generation advance without its source event must fail at + // transaction + // completion, after the lifecycle owner's ordinary writes and exact readback + // have executed. + c.dsl() + .execute( + "UPDATE account_authority_generations SET generation = generation + 1, source_version = source_version + 1 " + + "WHERE scope_kind = 'TENANT' AND tenant_uuid = ?", + f.creation().tenantId()); + })); for (String table : List.of( "subscription_provider_history", @@ -587,13 +576,12 @@ void databaseGuardRejectsUnauditedOwnerUpdateDuringSdkTransport() { f.transport().duringRead = () -> c.tx() - .executeWithoutResult( - s -> - c.dsl() - .execute( - "UPDATE account_tenant_billing_owners SET owner_version = owner_version + 1, owner_generation = ? WHERE tenant_uuid = ?", - UUID.randomUUID(), - f.creation().tenantId())); + .executeWithoutResult(s -> + c.dsl() + .execute( + "UPDATE account_tenant_billing_owners SET owner_version = owner_version + 1, owner_generation = ? WHERE tenant_uuid = ?", + UUID.randomUUID(), + f.creation().tenantId())); UUID reconciliationRequest = UUID.randomUUID(); assertSqlState( "23514", @@ -998,27 +986,24 @@ void effectiveCancellationAdvancesMonotonicCutoffWithoutPrematureReservationRele .isNull(); // Effective hosting cutoff is not proof that the provider can no longer charge. Neither the // typed replacement owner nor structural SQL may strand that still-held original operation. - assertThatThrownBy( - () -> - in( - c, - () -> - c.intents() - .retainPending( - new AccountSubscriptionCreateRequest( - UUID.randomUUID(), - f.creation().tenantId(), - f.creation().owner(), - f.creation().planCode(), - f.instrument().instrumentUuid(), - 1, - new ProducerEvidence( - f.creation().owner().accountUuid(), - UUID.randomUUID(), - DIGEST), - new AccountSubscriptionCreateRequest.ReplacementFence( - f.creation().subscriptionId(), - canceled.current().rowVersion()))))) + assertThatThrownBy(() -> + in( + c, + () -> + c.intents() + .retainPending( + new AccountSubscriptionCreateRequest( + UUID.randomUUID(), + f.creation().tenantId(), + f.creation().owner(), + f.creation().planCode(), + f.instrument().instrumentUuid(), + 1, + new ProducerEvidence( + f.creation().owner().accountUuid(), UUID.randomUUID(), DIGEST), + new AccountSubscriptionCreateRequest.ReplacementFence( + f.creation().subscriptionId(), + canceled.current().rowVersion()))))) .isInstanceOf(AccountSubscriptionIntentRepository.ConflictException.class); assertSqlState( "23514", @@ -1175,11 +1160,8 @@ void committedTerminalCancellationReplaysAfterCanceledSubscriptionIsReplaced() { assertThat(resolutionImage(c)).isEqualTo(retained); assertThat(c.intents().findCurrentByTenant(f.request.tenantId()).orElseThrow().subscriptionId()) .isEqualTo(successor.subscriptionId()); - assertThatThrownBy( - () -> - in( - c, - () -> owner.prepareTerminalResolution(withReason(f.request, "changed reason")))) + assertThatThrownBy(() -> + in(c, () -> owner.prepareTerminalResolution(withReason(f.request, "changed reason")))) .hasMessageContaining("IDEMPOTENCY_CONFLICT"); assertThat(failedImage(c, f.request.failedRequestId())).isEqualTo(f.failureImage); } @@ -1244,11 +1226,8 @@ void committedTerminalCancellationReplaysAfterCanceledSubscriptionIsReplaced() { .isEqualTo(result); assertThat(callbacks).hasValue(2); assertThat(resolutionImage(c)).isEqualTo(committed); - assertThatThrownBy( - () -> - in( - c, - () -> owner.prepareTerminalResolution(withReason(f.request, "changed reason")))) + assertThatThrownBy(() -> + in(c, () -> owner.prepareTerminalResolution(withReason(f.request, "changed reason")))) .hasMessageContaining("IDEMPOTENCY_CONFLICT"); assertSqlState( "23514", @@ -1290,20 +1269,19 @@ void activeUnresolvedStaleAndWrongBindingResolutionEvidenceNeverInvokesAuthoriza var sdk = f.fixture.observer().observe(prepared.binding()); if (failure.equals("stale")) f.fixture.clock().advance(Duration.ofSeconds(11)); AtomicInteger callbacks = new AtomicInteger(); - assertThatThrownBy( - () -> - in( - c, - () -> - f.fixture - .owner() - .applyTerminalResolution( - prepared, - sdk, - target -> { - callbacks.incrementAndGet(); - return authorized(f); - }))) + assertThatThrownBy(() -> + in( + c, + () -> + f.fixture + .owner() + .applyTerminalResolution( + prepared, + sdk, + target -> { + callbacks.incrementAndGet(); + return authorized(f); + }))) .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); assertThat(callbacks).hasValue(0); assertThat(resolutionImage(c)).isEqualTo(before); @@ -1318,23 +1296,21 @@ void deniedAuthorizationAndActualDownstreamSqlFailureRetainFailedFenceAndAllOwne f.fixture.transport().json = response(f.fixture, "canceled"); var sdk = f.fixture.observer().observe(prepared.binding()); List before = resolutionImage(c); - assertThatThrownBy( - () -> - in( - c, - () -> - f.fixture - .owner() - .applyTerminalResolution( - prepared, - sdk, - target -> { - assertThat( - count(c, "subscription_lifecycle_terminal_resolutions")) - .isZero(); - throw new IllegalStateException( - "controlled primary authentication denial"); - }))) + assertThatThrownBy(() -> + in( + c, + () -> + f.fixture + .owner() + .applyTerminalResolution( + prepared, + sdk, + target -> { + assertThat(count(c, "subscription_lifecycle_terminal_resolutions")) + .isZero(); + throw new IllegalStateException( + "controlled primary authentication denial"); + }))) .hasMessage("controlled primary authentication denial"); assertThat(resolutionImage(c)).isEqualTo(before); c.setup() @@ -1404,30 +1380,29 @@ void resolutionRequiresExactCapturedVersionsSameOwnerAndMatchingFreshAuthorizati () -> in(c, () -> f.fixture.owner().applyTerminalResolution(prepared, sdk, null))) .isInstanceOf(NullPointerException.class); for (String changed : List.of("actor", "issuance", "hash", "stale-auth")) { - assertThatThrownBy( - () -> - in( - c, - () -> - f.fixture - .owner() - .applyTerminalResolution( - prepared, - sdk, - target -> - new AuthorizedActor( - changed.equals("actor") - ? UUID.randomUUID() - : f.request.actorAccountId(), - changed.equals("issuance") - ? UUID.randomUUID() - : f.request.controlUiIssuanceOperationId(), - changed.equals("hash") - ? "b".repeat(64) - : f.request.controlUiTokenHash(), - changed.equals("stale-auth") - ? f.fixture.clock().instant().minusSeconds(1) - : f.fixture.clock().instant())))) + assertThatThrownBy(() -> + in( + c, + () -> + f.fixture + .owner() + .applyTerminalResolution( + prepared, + sdk, + target -> + new AuthorizedActor( + changed.equals("actor") + ? UUID.randomUUID() + : f.request.actorAccountId(), + changed.equals("issuance") + ? UUID.randomUUID() + : f.request.controlUiIssuanceOperationId(), + changed.equals("hash") + ? "b".repeat(64) + : f.request.controlUiTokenHash(), + changed.equals("stale-auth") + ? f.fixture.clock().instant().minusSeconds(1) + : f.fixture.clock().instant())))) .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class); } assertThat(resolutionImage(c)).isEqualTo(before); @@ -1461,19 +1436,17 @@ void competingResolutionRequestsCommitExactlyOneAndRejectStaleCapturedTarget() t var executor = Executors.newFixedThreadPool(2); try { var a = - executor.submit( - () -> { - ready.countDown(); - await(go); - return attemptResolution(f, first, firstSdk); - }); + executor.submit(() -> { + ready.countDown(); + await(go); + return attemptResolution(f, first, firstSdk); + }); var b = - executor.submit( - () -> { - ready.countDown(); - await(go); - return attemptResolution(f, second, secondSdk); - }); + executor.submit(() -> { + ready.countDown(); + await(go); + return attemptResolution(f, second, secondSdk); + }); assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); go.countDown(); assertThat(List.of(a.get(20, TimeUnit.SECONDS), b.get(20, TimeUnit.SECONDS))) @@ -1809,13 +1782,13 @@ private static AccountHostingSubscriptionLifecycleService service( "This is a JSON test fixture whose text block intentionally retains LF characters independent of the host console line separator.") private static String response(Fixture f, String status) { return """ - {"id":"%s","object":"subscription","customer":"%s","default_payment_method":"%s", - "livemode":false,"status":"%s","cancel_at_period_end":false,"cancel_at":null,"canceled_at":null,"ended_at":null, - "metadata":{"firemud_metadata_schema_version":"1","firemud_operation_type":"subscription_provisioning", - "firemud_operation_id":"%s","firemud_subscription_id":"%s"}, - "items":{"object":"list","data":[{"id":"si_controlled","object":"subscription_item","subscription":"%s", - "quantity":1,"current_period_start":%d,"current_period_end":%d,"price":{"id":"%s","object":"price"}}],"has_more":false}} - """ + {"id":"%s","object":"subscription","customer":"%s","default_payment_method":"%s", + "livemode":false,"status":"%s","cancel_at_period_end":false,"cancel_at":null,"canceled_at":null,"ended_at":null, + "metadata":{"firemud_metadata_schema_version":"1","firemud_operation_type":"subscription_provisioning", + "firemud_operation_id":"%s","firemud_subscription_id":"%s"}, + "items":{"object":"list","data":[{"id":"si_controlled","object":"subscription_item","subscription":"%s", + "quantity":1,"current_period_start":%d,"current_period_end":%d,"price":{"id":"%s","object":"price"}}],"has_more":false}} + """ .formatted( f.providerId(), f.creation().providerCustomerId(), @@ -1884,16 +1857,15 @@ private static void await(CountDownLatch latch) { private static void assertSqlState(String state, Runnable body) { assertThatThrownBy(body::run) - .satisfies( - failure -> { - for (Throwable cause = failure; cause != null; cause = cause.getCause()) { - if (cause instanceof SQLException sql) { - assertThat(sql.getSQLState()).isEqualTo(state); - return; - } - } - throw new AssertionError("Expected actual PostgreSQL constraint refusal", failure); - }); + .satisfies(failure -> { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sql) { + assertThat(sql.getSQLState()).isEqualTo(state); + return; + } + } + throw new AssertionError("Expected actual PostgreSQL constraint refusal", failure); + }); } private record Context( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountInitialTenantBillingOwnerRepositoryPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountInitialTenantBillingOwnerRepositoryPostgresIntegrationTest.java index 66b7915226..0ecfbca9cb 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountInitialTenantBillingOwnerRepositoryPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountInitialTenantBillingOwnerRepositoryPostgresIntegrationTest.java @@ -99,12 +99,8 @@ void exactRetryReturnsOriginalConsentAndBindingAndRejectsEveryChangedBinding() { CurrentOwnerBinding current = context .transaction() - .execute( - status -> - context - .repository() - .findCurrentOwnerForUpdate(seed.tenantUuid()) - .orElseThrow()); + .execute(status -> + context.repository().findCurrentOwnerForUpdate(seed.tenantUuid()).orElseThrow()); assertThat(current.ownerAccountUuid()).isEqualTo(first.ownerAccountUuid()); assertThat(current.ownerVersion()).isEqualTo(first.ownerVersion()); assertThat(current.ownerGeneration()).isEqualTo(first.ownerGeneration()); @@ -148,18 +144,16 @@ void exactRetryReturnsOriginalConsentAndBindingAndRejectsEveryChangedBinding() { UUID.randomUUID(), UUID.randomUUID(), 3); - assertThatThrownBy( - () -> - context - .transaction() - .execute(status -> context.repository().establishInitial(sourceMismatch))) - .satisfies( - failure -> { - SQLException sqlFailure = findSqlException(failure); - assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); - assertThat(sqlFailure.getMessage()) - .contains("Initial billing-owner operation differs from its fresh tenant source"); - }); + assertThatThrownBy(() -> + context + .transaction() + .execute(status -> context.repository().establishInitial(sourceMismatch))) + .satisfies(failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); + assertThat(sqlFailure.getMessage()) + .contains("Initial billing-owner operation differs from its fresh tenant source"); + }); assertThat( count( context.dsl(), @@ -206,11 +200,10 @@ void rollbackRemovesBothInitialOperationAndCurrentOwnerAndAllowsTheSameOriginalR context .transaction() - .executeWithoutResult( - status -> { - context.repository().establishInitial(request); - status.setRollbackOnly(); - }); + .executeWithoutResult(status -> { + context.repository().establishInitial(request); + status.setRollbackOnly(); + }); assertThat( count( context.dsl(), @@ -251,38 +244,33 @@ void deferredOwnerPairConstraintRejectsCaughtOwnerInsertFailureWithoutPartialCom + "EXECUTE FUNCTION account_test_skip_initial_billing_owner_insert()"); boolean[] repositoryFailureCaught = {false}; - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> { - try { - context.repository().establishInitial(request); - } catch (OperationConflictException expected) { - repositoryFailureCaught[0] = true; - assertThat( - count( - context.dsl(), - "account_initial_tenant_billing_owner_operations", - seed.tenantUuid())) - .isEqualTo(1L); - assertThat( - count( - context.dsl(), - "account_tenant_billing_owners", - seed.tenantUuid())) - .isZero(); - } - return null; - })) - .satisfies( - failure -> { - SQLException sqlFailure = findSqlException(failure); - assertThat(sqlFailure.getSQLState()).isEqualTo("23503"); - assertThat(sqlFailure.getMessage()) - .contains("account_initial_billing_owner_current_owner_fk"); - }); + assertThatThrownBy(() -> + context + .transaction() + .execute(status -> { + try { + context.repository().establishInitial(request); + } catch (OperationConflictException expected) { + repositoryFailureCaught[0] = true; + assertThat( + count( + context.dsl(), + "account_initial_tenant_billing_owner_operations", + seed.tenantUuid())) + .isEqualTo(1L); + assertThat( + count( + context.dsl(), "account_tenant_billing_owners", seed.tenantUuid())) + .isZero(); + } + return null; + })) + .satisfies(failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("23503"); + assertThat(sqlFailure.getMessage()) + .contains("account_initial_billing_owner_current_owner_fk"); + }); assertThat(repositoryFailureCaught[0]).isTrue(); assertThat( count( @@ -320,31 +308,28 @@ void unreviewedCurrentOwnerUpdateIsRejectedAndExactInitialReplayIsUnchanged() { .intoMaps(); UUID candidateOwner = UUID.randomUUID(); UUID candidateGeneration = UUID.randomUUID(); - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> - context - .dsl() - .execute( - "UPDATE account_tenant_billing_owners " - + "SET owner_account_uuid = ?, owner_version = 2, " - + "owner_generation = ?, updated_at = clock_timestamp() " - + "WHERE tenant_uuid = ? AND initial_request_id = ?", - candidateOwner, - candidateGeneration, - seed.tenantUuid(), - original.requestId()))) - .satisfies( - failure -> { - SQLException sqlFailure = findSqlException(failure); - assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); - assertThat(sqlFailure.getMessage()) - .contains( - "Current tenant billing-owner tuple cannot be updated without an audited transfer owner"); - }); + assertThatThrownBy(() -> + context + .transaction() + .execute(status -> + context + .dsl() + .execute( + "UPDATE account_tenant_billing_owners " + + "SET owner_account_uuid = ?, owner_version = 2, " + + "owner_generation = ?, updated_at = clock_timestamp() " + + "WHERE tenant_uuid = ? AND initial_request_id = ?", + candidateOwner, + candidateGeneration, + seed.tenantUuid(), + original.requestId()))) + .satisfies(failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); + assertThat(sqlFailure.getMessage()) + .contains( + "Current tenant billing-owner tuple cannot be updated without an audited transfer owner"); + }); assertThat( context .setupDsl() @@ -371,12 +356,8 @@ void unreviewedCurrentOwnerUpdateIsRejectedAndExactInitialReplayIsUnchanged() { CurrentOwnerBinding current = context .transaction() - .execute( - status -> - context - .repository() - .findCurrentOwnerForUpdate(seed.tenantUuid()) - .orElseThrow()); + .execute(status -> + context.repository().findCurrentOwnerForUpdate(seed.tenantUuid()).orElseThrow()); assertThat(current.ownerAccountUuid()).isEqualTo(original.ownerAccountUuid()); assertThat(current.ownerVersion()).isEqualTo(original.ownerVersion()); assertThat(current.ownerGeneration()).isEqualTo(original.ownerGeneration()); @@ -475,26 +456,23 @@ void immutableOperationSqlRejectsUpdateDeleteAndTruncate() { InitialBindingResult committed = context.transaction().execute(status -> context.repository().establishInitial(request)); - assertAppendOnlyRejected( - () -> - context - .setupDsl() - .execute( - "UPDATE account_initial_tenant_billing_owner_operations " - + "SET result_digest = result_digest WHERE request_id = ?", - committed.requestId())); - assertAppendOnlyRejected( - () -> - context - .setupDsl() - .execute( - "DELETE FROM account_initial_tenant_billing_owner_operations WHERE request_id = ?", - committed.requestId())); - assertAppendOnlyRejected( - () -> - context - .setupDsl() - .execute("TRUNCATE account_initial_tenant_billing_owner_operations CASCADE")); + assertAppendOnlyRejected(() -> + context + .setupDsl() + .execute( + "UPDATE account_initial_tenant_billing_owner_operations " + + "SET result_digest = result_digest WHERE request_id = ?", + committed.requestId())); + assertAppendOnlyRejected(() -> + context + .setupDsl() + .execute( + "DELETE FROM account_initial_tenant_billing_owner_operations WHERE request_id = ?", + committed.requestId())); + assertAppendOnlyRejected(() -> + context + .setupDsl() + .execute("TRUNCATE account_initial_tenant_billing_owner_operations CASCADE")); InitialBindingResult retry = context.transaction().execute(status -> context.repository().establishInitial(request)); @@ -605,11 +583,8 @@ private static InitialRequest request( private static void assertConflictWithoutMutation( Context context, InitialRequest request, UUID originalTenantUuid) { - assertThatThrownBy( - () -> - context - .transaction() - .execute(status -> context.repository().establishInitial(request))) + assertThatThrownBy(() -> + context.transaction().execute(status -> context.repository().establishInitial(request))) .isInstanceOf(OperationConflictException.class); assertThat( count( @@ -700,13 +675,12 @@ private static void assertSameResult(InitialBindingResult expected, InitialBindi private static void assertAppendOnlyRejected( org.assertj.core.api.ThrowableAssert.ThrowingCallable action) { assertThatThrownBy(action) - .satisfies( - failure -> { - SQLException sqlFailure = findSqlException(failure); - assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); - assertThat(sqlFailure.getMessage()) - .contains("Initial billing-owner operation evidence is append-only"); - }); + .satisfies(failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); + assertThat(sqlFailure.getMessage()) + .contains("Initial billing-owner operation evidence is append-only"); + }); } private static SQLException findSqlException(Throwable failure) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationPersistenceIntegrationTest.java index fbff0cf2be..7ec58aed0b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationPersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationPersistenceIntegrationTest.java @@ -145,81 +145,75 @@ void exactIntentReadbackAndMountedObservationPersistAndRejectEveryMutationPath() inTransaction( context, () -> desiredRepository.readCurrentGenerationRequest(PROD_BINDING, trust())); String invalidMarker = marker.replace("\"pending\":{", "\"pending\":{\"unexpected\":true,"); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - publicationRepository.recordPrepublicationIntent( - PROD_BINDING, - trust(), - result, - currentRequest, - API_DIGEST, - API_REVISION, - CONFIG_MAP_UID, - "41", - expectedSnapshotDigest, - desiredJwks, - invalidMarker))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + publicationRepository.recordPrepublicationIntent( + PROD_BINDING, + trust(), + result, + currentRequest, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "41", + expectedSnapshotDigest, + desiredJwks, + invalidMarker))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - publicationRepository.recordPrepublicationIntent( - PROD_BINDING, - trust(), - result, - currentRequest, - API_DIGEST, - API_REVISION, - CONFIG_MAP_UID, - "41", - expectedSnapshotDigest, - desiredJwks, - invalidBindingMarker))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + publicationRepository.recordPrepublicationIntent( + PROD_BINDING, + trust(), + result, + currentRequest, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "41", + expectedSnapshotDigest, + desiredJwks, + invalidBindingMarker))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - publicationRepository.recordPrepublicationIntent( - PROD_BINDING, - trust(), - result, - currentRequest, - API_DIGEST, - API_REVISION, - CONFIG_MAP_UID, - "41", - expectedSnapshotDigest, - jwks( - mutateJwk(retainedJwk, "key_ops", List.of("sign")), - result.publicJwkJson()), - marker))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + publicationRepository.recordPrepublicationIntent( + PROD_BINDING, + trust(), + result, + currentRequest, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "41", + expectedSnapshotDigest, + jwks( + mutateJwk(retainedJwk, "key_ops", List.of("sign")), + result.publicJwkJson()), + marker))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - publicationRepository.recordPrepublicationIntent( - PROD_BINDING, - trust(), - result, - currentRequest, - API_DIGEST, - API_REVISION, - CONFIG_MAP_UID, - "41", - expectedSnapshotDigest, - jwks( - mutateJwk(retainedJwk, "unexpected", "field"), - result.publicJwkJson()), - marker))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + publicationRepository.recordPrepublicationIntent( + PROD_BINDING, + trust(), + result, + currentRequest, + API_DIGEST, + API_REVISION, + CONFIG_MAP_UID, + "41", + expectedSnapshotDigest, + jwks(mutateJwk(retainedJwk, "unexpected", "field"), result.publicJwkJson()), + marker))) .isInstanceOf(DataAccessException.class); var intent = inTransaction( @@ -278,36 +272,33 @@ void exactIntentReadbackAndMountedObservationPersistAndRejectEveryMutationPath() assertThat(count(context, "account_jwt_jwks_publication_receipts")).isEqualTo(1L); assertThat(count(context, "account_jwt_jwks_mount_observations")).isEqualTo(1L); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - context - .dsl() - .execute( - "UPDATE account_jwt_jwks_prepublication_intents " - + "SET public_data_digest = ? WHERE operation_id = ?", - "f".repeat(64), - result.operationId()))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_jwt_jwks_prepublication_intents " + + "SET public_data_digest = ? WHERE operation_id = ?", + "f".repeat(64), + result.operationId()))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - context - .dsl() - .execute( - "DELETE FROM account_jwt_jwks_publication_receipts " - + "WHERE operation_id = ?", - result.operationId()))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "DELETE FROM account_jwt_jwks_publication_receipts " + + "WHERE operation_id = ?", + result.operationId()))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> context.dsl().execute("TRUNCATE account_jwt_jwks_mount_observations"))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> context.dsl().execute("TRUNCATE account_jwt_jwks_mount_observations"))) .isInstanceOf(DataAccessException.class); assertThat(count(context, "account_jwt_jwks_prepublication_intents")).isEqualTo(1L); @@ -318,12 +309,11 @@ void exactIntentReadbackAndMountedObservationPersistAndRejectEveryMutationPath() context, () -> publicationRepository.readCurrentPublication(PROD_BINDING, trust()))) .isPresent() .get() - .satisfies( - evidence -> { - assertThat(evidence.intent()).isEqualTo(intent); - assertThat(evidence.receipt()).contains(receipt); - assertThat(evidence.mountedCorrespondence()).contains(mountObservation); - }); + .satisfies(evidence -> { + assertThat(evidence.intent()).isEqualTo(intent); + assertThat(evidence.receipt()).contains(receipt); + assertThat(evidence.mountedCorrespondence()).contains(mountObservation); + }); } private TestContext newTestContext() { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java index 8badd2eaf2..989833f185 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java @@ -159,18 +159,17 @@ void materializationReadbackIsDurableAndExactReplaysRejectChangedOrStaleEvidence assertThat(observation.expectedSecretResourceVersion()).isEqualTo(observedResourceVersion); assertThat(observation.secretUid()).isEqualTo(SECRET_UID); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - desired.recordSecretObservation( - BINDING, - trust, - request.operationId(), - request.operationDigest(), - SECRET_UID, - "13"))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + desired.recordSecretObservation( + BINDING, + trust, + request.operationId(), + request.operationDigest(), + SECRET_UID, + "13"))) .isInstanceOf(AccountJwtSignerDesiredStateRepository.IdempotencyConflictException.class); PublicJwk key = publicJwk(request.targetKid()); @@ -204,38 +203,36 @@ void materializationReadbackIsDurableAndExactReplaysRejectChangedOrStaleEvidence assertThat(result.publicKeyFingerprint()).isEqualTo(key.fingerprint()); assertThat(result.publicJwkJson()).doesNotContain("\"d\""); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - desired.recordGenerationResult( - BINDING, - trust, - request.operationId(), - observation.generationRequestDigest(), - SECRET_UID, - observedResourceVersion, - "14", - key.json()))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + desired.recordGenerationResult( + BINDING, + trust, + request.operationId(), + observation.generationRequestDigest(), + SECRET_UID, + observedResourceVersion, + "14", + key.json()))) .isInstanceOf(AccountJwtSignerDesiredStateRepository.IdempotencyConflictException.class); TrustFence staleTrust = new TrustFence(CLUSTER_UID, NAMESPACE_UID, "a".repeat(64), TRUST_REVISION); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - desired.recordGenerationResult( - BINDING, - staleTrust, - request.operationId(), - observation.generationRequestDigest(), - SECRET_UID, - observedResourceVersion, - "13", - key.json()))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + desired.recordGenerationResult( + BINDING, + staleTrust, + request.operationId(), + observation.generationRequestDigest(), + SECRET_UID, + observedResourceVersion, + "13", + key.json()))) .isInstanceOf(AccountJwtSignerDesiredStateRepository.BindingMismatchException.class); AccountJwtSignerDesiredStateRepository restartedRepository = @@ -319,26 +316,23 @@ void unpreparedGenerationAbortIsAnImmutableOwnerCasAndExactReplayAcrossRepositor result.publicKeyFingerprint(), result.publicJwkJson(), "f".repeat(64)); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> desired.abortUnpreparedGeneration(BINDING, trust, changedResult))) + assertThatThrownBy(() -> + inTransaction( + context, () -> desired.abortUnpreparedGeneration(BINDING, trust, changedResult))) .isInstanceOf(AccountJwtSignerDesiredStateRepository.IdempotencyConflictException.class); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - context - .dsl() - .execute( - "UPDATE account_jwt_signer_desired_states " - + "SET record_version = record_version + 1, " - + "generation_operation_id = NULL " - + "WHERE environment_id = ?", - BINDING.environmentId()))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_jwt_signer_desired_states " + + "SET record_version = record_version + 1, " + + "generation_operation_id = NULL " + + "WHERE environment_id = ?", + BINDING.environmentId()))) .isInstanceOf(DataAccessException.class); var receipt = @@ -417,13 +411,12 @@ void independentSqlEnrollmentInsertsRejectPartialAndMalformedProtectedIdentity() String validRow = context .transaction() - .execute( - status -> { - desired.initialize(BINDING, enrollmentIdentity()); - String row = signerRow(context, "account_jwt_signer_desired_states"); - status.setRollbackOnly(); - return row; - }); + .execute(status -> { + desired.initialize(BINDING, enrollmentIdentity()); + String row = signerRow(context, "account_jwt_signer_desired_states"); + status.setRollbackOnly(); + return row; + }); assertThat(validRow).isNotNull(); for (String field : List.of( @@ -436,17 +429,16 @@ void independentSqlEnrollmentInsertsRejectPartialAndMalformedProtectedIdentity() "enrollment_public_config_map_uid", "enrollment_public_config_map_resource_version", "enrollment_public_config_map_snapshot_digest")) { - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - insertSignerRow( - context, - "account_jwt_signer_desired_states", - validRow, - "jsonb_build_object(?, NULL)", - field))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + insertSignerRow( + context, + "account_jwt_signer_desired_states", + validRow, + "jsonb_build_object(?, NULL)", + field))) .as("independent partial enrollment INSERT: %s", field) .isInstanceOf(DataAccessException.class) .satisfies(failure -> assertThat(signerSqlState(failure)).isEqualTo("23514")); @@ -457,18 +449,17 @@ void independentSqlEnrollmentInsertsRejectPartialAndMalformedProtectedIdentity() "enrollment_materializer_binding_digest", "enrollment_api_binding_digest", "enrollment_public_config_map_snapshot_digest")) { - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - insertSignerRow( - context, - "account_jwt_signer_desired_states", - validRow, - "jsonb_build_object(?, ?)", - field, - "not-a-sha256"))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + insertSignerRow( + context, + "account_jwt_signer_desired_states", + validRow, + "jsonb_build_object(?, ?)", + field, + "not-a-sha256"))) .as("independent malformed enrollment INSERT: %s", field) .isInstanceOf(DataAccessException.class) .satisfies(failure -> assertThat(signerSqlState(failure)).isEqualTo("23514")); @@ -490,37 +481,34 @@ void rawResourceVersionWritesAndImmutableGenerationEvidenceMutationsAreRefused() String observationRow = context .transaction() - .execute( - status -> { - desired.recordSecretObservation( - BINDING, - trust(), - request.operationId(), - request.operationDigest(), - SECRET_UID, - "12"); - String row = signerRow(context, "account_jwt_signer_secret_observations"); - status.setRollbackOnly(); - return row; - }); + .execute(status -> { + desired.recordSecretObservation( + BINDING, + trust(), + request.operationId(), + request.operationDigest(), + SECRET_UID, + "12"); + String row = signerRow(context, "account_jwt_signer_secret_observations"); + status.setRollbackOnly(); + return row; + }); assertThat(observationRow).isNotNull(); for (String invalid : List.of("", "r\n", "r\u0001", "r".repeat(257))) { - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - insertSignerRow( - context, - "account_jwt_signer_secret_observations", - observationRow, - "jsonb_build_object('observed_resource_version', ?)", - invalid))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + insertSignerRow( + context, + "account_jwt_signer_secret_observations", + observationRow, + "jsonb_build_object('observed_resource_version', ?)", + invalid))) .isInstanceOf(DataAccessException.class) - .satisfies( - failure -> - assertThat(signerSqlState(failure)) - .isEqualTo(invalid.length() > 256 ? "22001" : "23514")); + .satisfies(failure -> + assertThat(signerSqlState(failure)) + .isEqualTo(invalid.length() > 256 ? "22001" : "23514")); assertThat(count(context, "account_jwt_signer_secret_observations")).isZero(); } GenerationRequest observed = @@ -538,42 +526,39 @@ void rawResourceVersionWritesAndImmutableGenerationEvidenceMutationsAreRefused() String resultRow = context .transaction() - .execute( - status -> { - desired.recordGenerationResult( - BINDING, - trust(), - request.operationId(), - observed.generationRequestDigest(), - SECRET_UID, - "12", - "13", - key.json()); - String row = signerRow(context, "account_jwt_signer_generation_results"); - status.setRollbackOnly(); - return row; - }); + .execute(status -> { + desired.recordGenerationResult( + BINDING, + trust(), + request.operationId(), + observed.generationRequestDigest(), + SECRET_UID, + "12", + "13", + key.json()); + String row = signerRow(context, "account_jwt_signer_generation_results"); + status.setRollbackOnly(); + return row; + }); assertThat(resultRow).isNotNull(); for (String field : List.of("expected_prior_resource_version", "observed_resource_version")) { for (String invalid : List.of("", "r\n", "r\u0001", "r".repeat(257))) { - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - insertSignerRow( - context, - "account_jwt_signer_generation_results", - resultRow, - "jsonb_build_object(?, ?)", - field, - invalid))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + insertSignerRow( + context, + "account_jwt_signer_generation_results", + resultRow, + "jsonb_build_object(?, ?)", + field, + invalid))) .as("raw result resource version: %s", field) .isInstanceOf(DataAccessException.class) - .satisfies( - failure -> - assertThat(signerSqlState(failure)) - .isEqualTo(invalid.length() > 256 ? "22001" : "23514")); + .satisfies(failure -> + assertThat(signerSqlState(failure)) + .isEqualTo(invalid.length() > 256 ? "22001" : "23514")); assertThat(count(context, "account_jwt_signer_generation_results")).isZero(); } } @@ -636,21 +621,20 @@ void rawGenerationResultTriggerRetainsOwnerLocksUntilTransactionCompletion() thr String resultRow = context .transaction() - .execute( - status -> { - desired.recordGenerationResult( - BINDING, - trust(), - request.operationId(), - observed.generationRequestDigest(), - SECRET_UID, - "12", - "13", - key.json()); - String row = signerRow(context, "account_jwt_signer_generation_results"); - status.setRollbackOnly(); - return row; - }); + .execute(status -> { + desired.recordGenerationResult( + BINDING, + trust(), + request.operationId(), + observed.generationRequestDigest(), + SECRET_UID, + "12", + "13", + key.json()); + String row = signerRow(context, "account_jwt_signer_generation_results"); + status.setRollbackOnly(); + return row; + }); assertThat(resultRow).isNotNull(); // Raw INSERT takes no repository locks: these locks must come from the result trigger. inTransaction( @@ -766,13 +750,12 @@ void protectedTrustMovementBeforeCommitRollsBackActualGenerationResult() throws var provider = mock(AccountJwtSignerMaterializerTrustBinding.class); when(provider.current()) .thenReturn(Optional.of(initial), Optional.of(initial)) - .thenAnswer( - invocation -> { - assertThat(count(context, "account_jwt_signer_generation_results")) - .as("the real INSERT is visible inside the transaction before trust moves") - .isEqualTo(1L); - return Optional.of(changed); - }); + .thenAnswer(invocation -> { + assertThat(count(context, "account_jwt_signer_generation_results")) + .as("the real INSERT is visible inside the transaction before trust moves") + .isEqualTo(1L); + return Optional.of(changed); + }); var service = new AccountJwtSignerMaterializationService( desired, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryPersistenceIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryPersistenceIntegrationTest.java index 274fdc243c..dd2899888f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryPersistenceIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryPersistenceIntegrationTest.java @@ -91,23 +91,21 @@ void exactDigestRetryReadsBackImmutableCanonicalBytesAndRejectsMutation() throws assertThat(retry.canonicalBytes()).isEqualTo(candidate.canonicalBytes()); assertThat(new String(retry.canonicalBytes(), StandardCharsets.UTF_8)) .doesNotContain("privateKey"); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "UPDATE account_jwt_validator_inventory_snapshots " - + "SET canonical_snapshot = ? WHERE snapshot_digest = ?", - "{}".getBytes(StandardCharsets.UTF_8), - retry.digest())) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "UPDATE account_jwt_validator_inventory_snapshots " + + "SET canonical_snapshot = ? WHERE snapshot_digest = ?", + "{}".getBytes(StandardCharsets.UTF_8), + retry.digest())) .isInstanceOf(DataAccessException.class); long plansBeforeTruncate = count(context, "account_jwt_readiness_probe_plans"); - assertThatThrownBy( - () -> - context - .dsl() - .execute("TRUNCATE TABLE account_jwt_validator_inventory_snapshots CASCADE")) + assertThatThrownBy(() -> + context + .dsl() + .execute("TRUNCATE TABLE account_jwt_validator_inventory_snapshots CASCADE")) .isInstanceOf(DataAccessException.class); assertThat(count(context, "account_jwt_validator_inventory_snapshots")).isEqualTo(1L); assertThat(count(context, "account_jwt_readiness_probe_plans")).isEqualTo(plansBeforeTruncate); @@ -144,10 +142,9 @@ void differentBytesCannotReuseAStoredDigestAndWrongOwnerIdentityIsDenied() throw when(wrongIdentity.digest()).thenReturn(digest); when(wrongIdentity.canonicalBytes()).thenReturn(canonicalBytes); - assertThatThrownBy( - () -> - inTransaction( - context, () -> repository.persistOrReadback(wrongIdentity, BINDING, trust()))) + assertThatThrownBy(() -> + inTransaction( + context, () -> repository.persistOrReadback(wrongIdentity, BINDING, trust()))) .isInstanceOf( AccountJwtValidatorInventoryRepository.InventorySnapshotUnavailableException.class) .hasNoCause(); @@ -167,13 +164,11 @@ void differentBytesCannotReuseAStoredDigestAndWrongOwnerIdentityIsDenied() throw when(conflictingApiBindingRevision.digest()).thenReturn(digest); when(conflictingApiBindingRevision.canonicalBytes()).thenReturn(canonicalBytes); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - repository.persistOrReadback( - conflictingApiBindingRevision, BINDING, trust()))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + repository.persistOrReadback(conflictingApiBindingRevision, BINDING, trust()))) .isInstanceOf( AccountJwtValidatorInventoryRepository.InventorySnapshotUnavailableException.class) .hasNoCause(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountLifecycleBoundRealmGrantPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountLifecycleBoundRealmGrantPostgresIntegrationTest.java index 085b4ab18a..9db562c2f7 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountLifecycleBoundRealmGrantPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountLifecycleBoundRealmGrantPostgresIntegrationTest.java @@ -66,18 +66,17 @@ void rejectsNulBeforeWritesAndRetainsRepresentableReasonAtFullByteLimit() { Context context = context(); Instant fork = context.now().plusSeconds(3600); Instant expiry = context.now().plusSeconds(300); - assertThatThrownBy( - () -> - context.apply( - UUID.randomUUID(), - new RealmGrantMutation( - "local", - context.scope(), - Operation.CREATE, - null, - expiry, - "before" + (char) 0 + "after"), - fork)) + assertThatThrownBy(() -> + context.apply( + UUID.randomUUID(), + new RealmGrantMutation( + "local", + context.scope(), + Operation.CREATE, + null, + expiry, + "before" + (char) 0 + "after"), + fork)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("NUL"); context.assertEmpty(); @@ -230,15 +229,11 @@ void changedRequestIntentAndActorConflictWithoutAnyStateResultOrEventChange() { expiry); assertThatThrownBy(() -> context.apply(request, changedAccount, fork)) .isInstanceOf(IdempotencyConflictException.class); - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> - context - .repository() - .apply(request, otherControlledActor, original, fork))) + assertThatThrownBy(() -> + context + .transaction() + .execute(status -> + context.repository().apply(request, otherControlledActor, original, fork))) .isInstanceOf(IdempotencyConflictException.class); context.assertRowsUnchanged(before); assertThat(context.count("account_authority_outbox_events")).isEqualTo(1); @@ -282,23 +277,21 @@ void twoWritersWithOneExpectedRevisionHaveOneWinnerAndOneNoMutationConflict() th var executor = Executors.newFixedThreadPool(2); try { var first = - executor.submit( - () -> - concurrentWrite( - context, - command(context.scope(), Operation.EXTEND, 1L, expiry.plusSeconds(10)), - fork, - bothReady, - begin)); + executor.submit(() -> + concurrentWrite( + context, + command(context.scope(), Operation.EXTEND, 1L, expiry.plusSeconds(10)), + fork, + bothReady, + begin)); var second = - executor.submit( - () -> - concurrentWrite( - context, - command(context.scope(), Operation.REVOKE, 1L, null), - fork, - bothReady, - begin)); + executor.submit(() -> + concurrentWrite( + context, + command(context.scope(), Operation.REVOKE, 1L, null), + fork, + bothReady, + begin)); assertThat(bothReady.await(30, TimeUnit.SECONDS)).isTrue(); begin.countDown(); assertThat(List.of(first.get(60, TimeUnit.SECONDS), second.get(60, TimeUnit.SECONDS))) @@ -337,19 +330,17 @@ void expiryForkShorteningAndForkExtensionUseRealDatabaseClockWithoutRewritingGra assertThat(context.read(expiredFork).effectiveExpiresAt()).isEqualTo(expiredFork); assertThat(context.read(fork).receipt().grantExpiresAt()).isEqualTo(expiry); List> before = context.rows(); - assertThatThrownBy( - () -> - context.apply( - UUID.randomUUID(), - command(context.scope(), Operation.EXTEND, 1L, expiry.plusSeconds(1)), - expiredFork)) + assertThatThrownBy(() -> + context.apply( + UUID.randomUUID(), + command(context.scope(), Operation.EXTEND, 1L, expiry.plusSeconds(1)), + expiredFork)) .isInstanceOf(GrantRevisionConflictException.class); - assertThatThrownBy( - () -> - context.apply( - UUID.randomUUID(), - command(context.scope(), Operation.EXTEND, 1L, fork.plusNanos(1)), - fork)) + assertThatThrownBy(() -> + context.apply( + UUID.randomUUID(), + command(context.scope(), Operation.EXTEND, 1L, fork.plusNanos(1)), + fork)) .isInstanceOf(IllegalArgumentException.class); context.assertRowsUnchanged(before); } @@ -378,42 +369,38 @@ void rollbackAndFinalCommitExpiryRefusalLeaveNoPartialStateReceiptAuditOrEvent() Context context = context(); Instant fork = context.now().plusSeconds(3600); Instant expiry = context.now().plusSeconds(300); - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult( - status -> { - context - .repository() - .apply( - UUID.randomUUID(), - context.controlledActor(), - command(context.scope(), Operation.CREATE, null, expiry), - fork); - throw new IllegalStateException("Controlled downstream owner refusal"); - })) + assertThatThrownBy(() -> + context + .transaction() + .executeWithoutResult(status -> { + context + .repository() + .apply( + UUID.randomUUID(), + context.controlledActor(), + command(context.scope(), Operation.CREATE, null, expiry), + fork); + throw new IllegalStateException("Controlled downstream owner refusal"); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("Controlled downstream owner refusal"); context.assertEmpty(); UUID request = UUID.randomUUID(); // The policy is genuinely short; no clock, timestamp, source or trigger is rewritten. - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult( - status -> { - Instant shortExpiry = context.now().plusSeconds(5); - context - .repository() - .apply( - request, - context.controlledActor(), - command(context.scope(), Operation.CREATE, null, shortExpiry), - fork); - awaitDatabaseBoundary(context.dsl(), shortExpiry); - })) + assertThatThrownBy(() -> + context + .transaction() + .executeWithoutResult(status -> { + Instant shortExpiry = context.now().plusSeconds(5); + context + .repository() + .apply( + request, + context.controlledActor(), + command(context.scope(), Operation.CREATE, null, shortExpiry), + fork); + awaitDatabaseBoundary(context.dsl(), shortExpiry); + })) .isInstanceOf(RuntimeException.class) .hasStackTraceContaining("expired before final commit"); context.assertEmpty(); @@ -450,9 +437,8 @@ void directHistoryTombstoneHeadAndAuditIdentityViolationsAreRejectedByProduction "UPDATE " + CURRENT + " SET grant_revision = 3", "UPDATE account_authority_outbox_events SET payload = payload", "UPDATE account_audit_outbox SET event_type = 'WRONG'")) { - assertThatThrownBy( - () -> - context.transaction().executeWithoutResult(status -> context.dsl().execute(sql))) + assertThatThrownBy(() -> + context.transaction().executeWithoutResult(status -> context.dsl().execute(sql))) .as(sql) .isInstanceOf(RuntimeException.class); } @@ -465,23 +451,21 @@ void directHistoryTombstoneHeadAndAuditIdentityViolationsAreRejectedByProduction @Test void detachedGenericOutboxEventCannotCommitWithoutItsExactGrantOwnerReceipt() { Context context = context(); - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult( - status -> { - String stream = - GrantAuthorityScopeCodec.outboxStreamKey( - context.scope(), GrantAuthorityScopeCodec.V1_BOUNDS); - new AccountAuthorityOutboxRepository(context.dsl()) - .append( - stream, - UUID.randomUUID().toString(), - "unqualified-event", - "unqualified-digest", - new byte[] {1}); - })) + assertThatThrownBy(() -> + context + .transaction() + .executeWithoutResult(status -> { + String stream = + GrantAuthorityScopeCodec.outboxStreamKey( + context.scope(), GrantAuthorityScopeCodec.V1_BOUNDS); + new AccountAuthorityOutboxRepository(context.dsl()) + .append( + stream, + UUID.randomUUID().toString(), + "unqualified-event", + "unqualified-digest", + new byte[] {1}); + })) .isInstanceOf(RuntimeException.class) .hasStackTraceContaining("exact atomic owner receipt"); context.assertEmpty(); @@ -491,19 +475,15 @@ void detachedGenericOutboxEventCannotCommitWithoutItsExactGrantOwnerReceipt() { void primitiveRequiresOwnerTransactionAndDoesNotReadLegacyGrantsOrInferMembership() { Context context = context(); Instant fork = context.now().plusSeconds(3600); - assertThatThrownBy( - () -> - context - .repository() - .apply( - UUID.randomUUID(), - context.controlledActor(), - command( - context.scope(), - Operation.CREATE, - null, - context.now().plusSeconds(300)), - fork)) + assertThatThrownBy(() -> + context + .repository() + .apply( + UUID.randomUUID(), + context.controlledActor(), + command( + context.scope(), Operation.CREATE, null, context.now().plusSeconds(300)), + fork)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("owner transaction"); assertThatThrownBy(() -> context.repository().readCurrent(context.scope(), fork)) 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 f3d6cba812..8887995142 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 @@ -205,14 +205,13 @@ private void exerciseFinalConfirmation(boolean revokeCallerDuringFinalRead) thro sourceFixture.committedCandidate.authoritySnapshot().issuanceFence()); UUID revocationRequestId = UUID.randomUUID(); var revocation = - serializable.execute( - status -> - new AccountGameplayTokenIdentityFenceRepository(dsl) - .beginRevocationIntent( - loginIdentity, - revocationRequestId, - AccountGameplayTokenIdentityFenceRepository.revocationDigest( - loginIdentity, revocationRequestId))); + serializable.execute(status -> + new AccountGameplayTokenIdentityFenceRepository(dsl) + .beginRevocationIntent( + loginIdentity, + revocationRequestId, + AccountGameplayTokenIdentityFenceRepository.revocationDigest( + loginIdentity, revocationRequestId))); assertThat(revocation).isNotNull(); assertThat(revocation.tokenIdentityFence()).isEqualTo(2L); callerRevocations.incrementAndGet(); @@ -364,11 +363,10 @@ private void exerciseFinalConfirmation(boolean revokeCallerDuringFinalRead) thro } installOwnedConfirmationUpdateFailure(dsl); try { - assertThatThrownBy( - () -> - Context.current() - .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .call(() -> owner.confirmOriginalFinalAdmission(loginJwt, originalLease))) + assertThatThrownBy(() -> + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) + .call(() -> owner.confirmOriginalFinalAdmission(loginJwt, originalLease))) .isInstanceOf(RuntimeException.class) .hasMessageContaining("controlled owned original-new confirmation SQL fault"); } finally { @@ -543,63 +541,60 @@ private AccountGameplayAdmissionLeaseEvidence commitActualOriginalNewLease( 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; - }); + 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; + }); UUID decisionId = UUID.randomUUID(); var acknowledgement = @@ -618,10 +613,9 @@ private static Genesis readGenesis( DSLContext dsl, TransactionTemplate transaction, AccountGameplayAdmissionLeaseEvidence originalLease) { - return transaction.execute( - status -> - new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) - .readByLease(UUID.fromString((String) originalLease.carrier().get("leaseId")))); + return transaction.execute(status -> + new AccountOriginalNewBoundGameplayIssuanceRepository(dsl) + .readByLease(UUID.fromString((String) originalLease.carrier().get("leaseId")))); } private static AccountOriginalNewBoundGameplayCredentialOwner.OriginalAdmissionConfirmation diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java index c12c56a5aa..93bb8a1cfa 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java @@ -68,15 +68,12 @@ void freshBirthDoesNotPopulateTheCurrentRestrictionProjection() { assertThat( context.dsl().fetchCount(DSL.table("account_platform_restriction_current_projections"))) .isZero(); - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> - restrictionRepository(context.dsl()) - .readCurrent( - account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK))) + assertThatThrownBy(() -> + context + .transaction() + .execute(status -> + restrictionRepository(context.dsl()) + .readCurrent(account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK))) .isInstanceOf( AccountPlatformRestrictionOperationRepository.RestrictionProjectionUnavailableException .class); @@ -93,32 +90,30 @@ void fabricatedOwnerCorrelationCannotPromoteBirthToCurrentState() { AccountPlatformRestrictionMutationRequest fabricated = context .transaction() - .execute( - status -> { - var birth = - new AccountPlatformRestrictionBirthRepository(context.dsl()) - .readCurrentBirthSource(account.getAccountUuid()); - var category = birth.accountSecurityLock(); - return new AccountPlatformRestrictionMutationRequest( - UUID.randomUUID(), - account.getAccountUuid(), - Category.ACCOUNT_SECURITY_LOCK, - birth.currentAuthority().generation(), - birth.currentAuthority().sourceVersion(), - category.revision(), - category.enforcementEpoch(), - category.resultId(), - RestrictionState.RESTRICTED, - SourceKind.ACCOUNT_SECURITY_POLICY, - UUID.randomUUID(), - "sha256:" + "0".repeat(64)); - }); - - assertThatThrownBy( - () -> - context - .transaction() - .execute(status -> restrictionRepository(context.dsl()).commit(fabricated))) + .execute(status -> { + var birth = + new AccountPlatformRestrictionBirthRepository(context.dsl()) + .readCurrentBirthSource(account.getAccountUuid()); + var category = birth.accountSecurityLock(); + return new AccountPlatformRestrictionMutationRequest( + UUID.randomUUID(), + account.getAccountUuid(), + Category.ACCOUNT_SECURITY_LOCK, + birth.currentAuthority().generation(), + birth.currentAuthority().sourceVersion(), + category.revision(), + category.enforcementEpoch(), + category.resultId(), + RestrictionState.RESTRICTED, + SourceKind.ACCOUNT_SECURITY_POLICY, + UUID.randomUUID(), + "sha256:" + "0".repeat(64)); + }); + + assertThatThrownBy(() -> + context + .transaction() + .execute(status -> restrictionRepository(context.dsl()).commit(fabricated))) .isInstanceOf( AccountPlatformRestrictionOperationRepository.OwnerAuthorizationUnresolvedException .class); @@ -127,15 +122,12 @@ void fabricatedOwnerCorrelationCannotPromoteBirthToCurrentState() { assertThat( context.dsl().fetchCount(DSL.table("account_platform_restriction_current_projections"))) .isZero(); - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> - restrictionRepository(context.dsl()) - .readCurrent( - account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK))) + assertThatThrownBy(() -> + context + .transaction() + .execute(status -> + restrictionRepository(context.dsl()) + .readCurrent(account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK))) .isInstanceOf( AccountPlatformRestrictionOperationRepository.RestrictionProjectionUnavailableException .class); @@ -175,15 +167,12 @@ void retainedPreV137BirthDoesNotBecomeCurrentRestrictionAbsenceAfterMigration() assertThat( context.dsl().fetchCount(DSL.table("account_platform_restriction_current_projections"))) .isZero(); - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> - restrictionRepository(context.dsl()) - .readCurrent( - account.getAccountUuid(), Category.PLATFORM_ACCESS_BAN))) + assertThatThrownBy(() -> + context + .transaction() + .execute(status -> + restrictionRepository(context.dsl()) + .readCurrent(account.getAccountUuid(), Category.PLATFORM_ACCESS_BAN))) .isInstanceOf( AccountPlatformRestrictionOperationRepository.RestrictionProjectionUnavailableException .class); @@ -255,10 +244,9 @@ void nonrestrictedSecurityLockResultPreservesActiveLifecycleAndPunitiveBanIsInde assertThat( context .transaction() - .execute( - status -> - restrictionRepository(context.dsl()) - .readCurrent(account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK)) + .execute(status -> + restrictionRepository(context.dsl()) + .readCurrent(account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK)) .state()) .isEqualTo(RestrictionState.NONRESTRICTED); @@ -267,10 +255,9 @@ void nonrestrictedSecurityLockResultPreservesActiveLifecycleAndPunitiveBanIsInde assertThat( context .transaction() - .execute( - status -> - restrictionRepository(context.dsl()) - .readCurrent(account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK)) + .execute(status -> + restrictionRepository(context.dsl()) + .readCurrent(account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK)) .revision()) .isEqualTo(3L); @@ -280,10 +267,9 @@ void nonrestrictedSecurityLockResultPreservesActiveLifecycleAndPunitiveBanIsInde assertThat( context .transaction() - .execute( - status -> - restrictionRepository(context.dsl()) - .readCurrent(account.getAccountUuid(), Category.PLATFORM_ACCESS_BAN)) + .execute(status -> + restrictionRepository(context.dsl()) + .readCurrent(account.getAccountUuid(), Category.PLATFORM_ACCESS_BAN)) .state()) .isEqualTo(RestrictionState.RESTRICTED); } @@ -302,10 +288,9 @@ void restrictedSecurityLockOnActiveAccountProjectsLockedLifecycle() { assertThat( context .transaction() - .execute( - status -> - restrictionRepository(context.dsl()) - .readCurrent(account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK)) + .execute(status -> + restrictionRepository(context.dsl()) + .readCurrent(account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK)) .state()) .isEqualTo(RestrictionState.RESTRICTED); @@ -315,10 +300,9 @@ void restrictedSecurityLockOnActiveAccountProjectsLockedLifecycle() { assertThat( context .transaction() - .execute( - status -> - restrictionRepository(context.dsl()) - .readCurrent(account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK)) + .execute(status -> + restrictionRepository(context.dsl()) + .readCurrent(account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK)) .state()) .isEqualTo(RestrictionState.NONRESTRICTED); } @@ -361,10 +345,9 @@ void legacyLifecycleExitRejectsFinalRestrictedMismatchAndRollsBackItsReceipt() { commitDraft(context, account, Category.ACCOUNT_SECURITY_LOCK, RestrictionState.RESTRICTED); Map before = restrictionWriteSnapshot(context.dsl()); - assertThatThrownBy( - () -> - transitionLifecycleWithLegacyAuthorityReceipt( - context, account, AccountLifecycleState.DEACTIVATED_PENDING_DELETE)) + assertThatThrownBy(() -> + transitionLifecycleWithLegacyAuthorityReceipt( + context, account, AccountLifecycleState.DEACTIVATED_PENDING_DELETE)) .isInstanceOf(TransactionSystemException.class) .rootCause() .isInstanceOf(org.postgresql.util.PSQLException.class) @@ -390,10 +373,9 @@ void nonrestrictedCurrentProjectionPreservesPendingDeletionAndDeletedThroughLega var retainedProjection = context .transaction() - .execute( - status -> - restrictionRepository(context.dsl()) - .readCurrent(account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK)); + .execute(status -> + restrictionRepository(context.dsl()) + .readCurrent(account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK)); assertThat(retainedProjection.state()).isEqualTo(RestrictionState.NONRESTRICTED); assertThat(retainedProjection.revision()).isEqualTo(4L); @@ -403,10 +385,9 @@ void nonrestrictedCurrentProjectionPreservesPendingDeletionAndDeletedThroughLega var pendingDeletionProjection = context .transaction() - .execute( - status -> - restrictionRepository(context.dsl()) - .readCurrent(account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK)); + .execute(status -> + restrictionRepository(context.dsl()) + .readCurrent(account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK)); assertThat(pendingDeletionProjection).isEqualTo(retainedProjection); transitionLifecycleWithLegacyAuthorityReceipt(context, account, AccountLifecycleState.DELETED); @@ -414,10 +395,9 @@ void nonrestrictedCurrentProjectionPreservesPendingDeletionAndDeletedThroughLega var deletedProjection = context .transaction() - .execute( - status -> - restrictionRepository(context.dsl()) - .readCurrent(account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK)); + .execute(status -> + restrictionRepository(context.dsl()) + .readCurrent(account.getAccountUuid(), Category.ACCOUNT_SECURITY_LOCK)); assertThat(deletedProjection).isEqualTo(retainedProjection); } @@ -433,23 +413,21 @@ void restrictedDraftWaitsForLifecycleRowAndRejectsTheCommittedNonactiveState() t ExecutorService executor = Executors.newFixedThreadPool(2); try { Future lifecycleTransition = - executor.submit( - () -> - transitionLifecycleWithLegacyAuthorityReceipt( - context, - account, - AccountLifecycleState.DEACTIVATED_PENDING_DELETE, - lifecycleReceiptReady, - allowLifecycleCommit)); + executor.submit(() -> + transitionLifecycleWithLegacyAuthorityReceipt( + context, + account, + AccountLifecycleState.DEACTIVATED_PENDING_DELETE, + lifecycleReceiptReady, + allowLifecycleCommit)); assertThat(lifecycleReceiptReady.await(10, TimeUnit.SECONDS)).isTrue(); CountDownLatch restrictionAttemptStarted = new CountDownLatch(1); Future restrictedDraft = - executor.submit( - () -> { - restrictionAttemptStarted.countDown(); - attemptRestrictedDraft(context, account); - }); + executor.submit(() -> { + restrictionAttemptStarted.countDown(); + attemptRestrictedDraft(context, account); + }); assertThat(restrictionAttemptStarted.await(10, TimeUnit.SECONDS)).isTrue(); allowLifecycleCommit.countDown(); lifecycleTransition.get(10, TimeUnit.SECONDS); @@ -486,28 +464,24 @@ void deferredProjectionAndAccountGuardsReadFinalRowsWhenForcedIndependently() { status -> new AccountRepository(projectionContext.dsl()).save(projectionAccount)); Map projectionBefore = restrictionWriteSnapshot(projectionContext.dsl()); - assertThatThrownBy( - () -> - projectionContext - .transaction() - .executeWithoutResult( - status -> { - commitDraft( - projectionContext, - projectionAccount, - Category.ACCOUNT_SECURITY_LOCK, - RestrictionState.NONRESTRICTED); - transitionLifecycleWithLegacyAuthorityReceipt( - projectionContext, - projectionAccount, - AccountLifecycleState.SECURITY_LOCKED); - projectionContext - .dsl() - .execute( - "SET CONSTRAINTS " - + "account_platform_restriction_current_lifecycle_consistency " - + "IMMEDIATE"); - })) + assertThatThrownBy(() -> + projectionContext + .transaction() + .executeWithoutResult(status -> { + commitDraft( + projectionContext, + projectionAccount, + Category.ACCOUNT_SECURITY_LOCK, + RestrictionState.NONRESTRICTED); + transitionLifecycleWithLegacyAuthorityReceipt( + projectionContext, projectionAccount, AccountLifecycleState.SECURITY_LOCKED); + projectionContext + .dsl() + .execute( + "SET CONSTRAINTS " + + "account_platform_restriction_current_lifecycle_consistency " + + "IMMEDIATE"); + })) .isInstanceOf(DataAccessException.class) .hasMessageContaining("Current Account security-lock projection and lifecycle disagree"); assertThat(restrictionWriteSnapshot(projectionContext.dsl())) @@ -523,21 +497,19 @@ void deferredProjectionAndAccountGuardsReadFinalRowsWhenForcedIndependently() { accountContext, account, Category.ACCOUNT_SECURITY_LOCK, RestrictionState.NONRESTRICTED); Map accountBefore = restrictionWriteSnapshot(accountContext.dsl()); - assertThatThrownBy( - () -> - accountContext - .transaction() - .executeWithoutResult( - status -> { - transitionLifecycleWithLegacyAuthorityReceipt( - accountContext, account, AccountLifecycleState.SECURITY_LOCKED); - accountContext - .dsl() - .execute( - "SET CONSTRAINTS " - + "account_platform_restriction_account_lifecycle_consistency " - + "IMMEDIATE"); - })) + assertThatThrownBy(() -> + accountContext + .transaction() + .executeWithoutResult(status -> { + transitionLifecycleWithLegacyAuthorityReceipt( + accountContext, account, AccountLifecycleState.SECURITY_LOCKED); + accountContext + .dsl() + .execute( + "SET CONSTRAINTS " + + "account_platform_restriction_account_lifecycle_consistency " + + "IMMEDIATE"); + })) .isInstanceOf(DataAccessException.class) .hasMessageContaining("Current Account security-lock projection and lifecycle disagree"); assertThat(restrictionWriteSnapshot(accountContext.dsl())) @@ -549,63 +521,62 @@ private static void commitDraft( Context context, Account account, Category category, RestrictionState state) { context .transaction() - .executeWithoutResult( - status -> { - var birthSource = new AccountPlatformRestrictionBirthRepository(context.dsl()); - var birth = birthSource.readCurrentBirthSource(account.getAccountUuid()); - var categoryBirth = - category == Category.ACCOUNT_SECURITY_LOCK - ? birth.accountSecurityLock() - : birth.platformAccessBan(); - var currentProjection = - context - .dsl() - .fetchOne( - "SELECT revision, enforcement_epoch, result_id FROM " - + "account_platform_restriction_current_projections " - + "WHERE account_uuid = ? AND category = ?", - account.getAccountUuid(), - category.storageValue()); - long expectedRevision = - currentProjection == null - ? categoryBirth.revision() - : currentProjection.get("revision", Long.class); - long expectedEpoch = - currentProjection == null - ? categoryBirth.enforcementEpoch() - : currentProjection.get("enforcement_epoch", Long.class); - UUID expectedResult = - currentProjection == null - ? categoryBirth.resultId() - : currentProjection.get("result_id", UUID.class); - var sourceKind = - category == Category.ACCOUNT_SECURITY_LOCK - ? (state == RestrictionState.RESTRICTED - ? SourceKind.ACCOUNT_SECURITY_POLICY - : SourceKind.ACCOUNT_SECURITY_RECOVERY) - : SourceKind.LOGGING_ADMIN_MODERATION; - var request = - new AccountPlatformRestrictionMutationRequest( - UUID.randomUUID(), + .executeWithoutResult(status -> { + var birthSource = new AccountPlatformRestrictionBirthRepository(context.dsl()); + var birth = birthSource.readCurrentBirthSource(account.getAccountUuid()); + var categoryBirth = + category == Category.ACCOUNT_SECURITY_LOCK + ? birth.accountSecurityLock() + : birth.platformAccessBan(); + var currentProjection = + context + .dsl() + .fetchOne( + "SELECT revision, enforcement_epoch, result_id FROM " + + "account_platform_restriction_current_projections " + + "WHERE account_uuid = ? AND category = ?", account.getAccountUuid(), - category, - birth.currentAuthority().generation(), - birth.currentAuthority().sourceVersion(), - expectedRevision, - expectedEpoch, - expectedResult, - state, - sourceKind, - UUID.randomUUID(), - "sha256:" + "1".repeat(64)); - try { - var repository = restrictionRepository(context.dsl()); - invokeDraftPersistence(repository, request); - } catch (ReflectiveOperationException failure) { - throw new IllegalStateException( - "Could not invoke the closed restriction draft", failure); - } - }); + category.storageValue()); + long expectedRevision = + currentProjection == null + ? categoryBirth.revision() + : currentProjection.get("revision", Long.class); + long expectedEpoch = + currentProjection == null + ? categoryBirth.enforcementEpoch() + : currentProjection.get("enforcement_epoch", Long.class); + UUID expectedResult = + currentProjection == null + ? categoryBirth.resultId() + : currentProjection.get("result_id", UUID.class); + var sourceKind = + category == Category.ACCOUNT_SECURITY_LOCK + ? (state == RestrictionState.RESTRICTED + ? SourceKind.ACCOUNT_SECURITY_POLICY + : SourceKind.ACCOUNT_SECURITY_RECOVERY) + : SourceKind.LOGGING_ADMIN_MODERATION; + var request = + new AccountPlatformRestrictionMutationRequest( + UUID.randomUUID(), + account.getAccountUuid(), + category, + birth.currentAuthority().generation(), + birth.currentAuthority().sourceVersion(), + expectedRevision, + expectedEpoch, + expectedResult, + state, + sourceKind, + UUID.randomUUID(), + "sha256:" + "1".repeat(64)); + try { + var repository = restrictionRepository(context.dsl()); + invokeDraftPersistence(repository, request); + } catch (ReflectiveOperationException failure) { + throw new IllegalStateException( + "Could not invoke the closed restriction draft", failure); + } + }); } private static long currentRevision(Context context, Account account, Category category) { @@ -643,44 +614,43 @@ private static void transitionLifecycleWithLegacyAuthorityReceipt( CountDownLatch allowCommit) { context .transaction() - .executeWithoutResult( - status -> { - AccountsRecord beforeRecord = - context - .dsl() - .selectFrom(ACCOUNTS) - .where(ACCOUNTS.ACCOUNT_UUID.eq(account.getAccountUuid())) - .fetchOne(); - if (beforeRecord == null) { - throw new AssertionError("Expected Account before legacy lifecycle update"); - } + .executeWithoutResult(status -> { + AccountsRecord beforeRecord = context .dsl() - .execute( - "UPDATE accounts SET lifecycle_state = ? WHERE account_uuid = ?", - nextLifecycle.storageValue(), - account.getAccountUuid()); - AccountsRecord afterRecord = - context - .dsl() - .selectFrom(ACCOUNTS) - .where(ACCOUNTS.ACCOUNT_UUID.eq(account.getAccountUuid())) - .fetchOne(); - if (afterRecord == null) { - throw new AssertionError("Expected Account after legacy lifecycle update"); - } - var evidence = - legacyAccountUpdateEvidence( - beforeRecord, afterRecord, account.getId(), account.getAccountUuid()); - var generations = new AccountAuthorityGenerationRepository(context.dsl()); - var outbox = new AccountAuthorityOutboxRepository(context.dsl()); - new AccountAuthoritySourceEvidenceRepository(context.dsl(), generations, outbox) - .recordAccountUpdate(evidence); - if (receiptReady != null && allowCommit != null) { - receiptReady.countDown(); - awaitCommitGate(allowCommit); - } - }); + .selectFrom(ACCOUNTS) + .where(ACCOUNTS.ACCOUNT_UUID.eq(account.getAccountUuid())) + .fetchOne(); + if (beforeRecord == null) { + throw new AssertionError("Expected Account before legacy lifecycle update"); + } + context + .dsl() + .execute( + "UPDATE accounts SET lifecycle_state = ? WHERE account_uuid = ?", + nextLifecycle.storageValue(), + account.getAccountUuid()); + AccountsRecord afterRecord = + context + .dsl() + .selectFrom(ACCOUNTS) + .where(ACCOUNTS.ACCOUNT_UUID.eq(account.getAccountUuid())) + .fetchOne(); + if (afterRecord == null) { + throw new AssertionError("Expected Account after legacy lifecycle update"); + } + var evidence = + legacyAccountUpdateEvidence( + beforeRecord, afterRecord, account.getId(), account.getAccountUuid()); + var generations = new AccountAuthorityGenerationRepository(context.dsl()); + var outbox = new AccountAuthorityOutboxRepository(context.dsl()); + new AccountAuthoritySourceEvidenceRepository(context.dsl(), generations, outbox) + .recordAccountUpdate(evidence); + if (receiptReady != null && allowCommit != null) { + receiptReady.countDown(); + awaitCommitGate(allowCommit); + } + }); } private static void awaitCommitGate(CountDownLatch allowCommit) { @@ -737,15 +707,14 @@ private static void attemptRestrictedDraft(Context context, Account account) { "sha256:" + "2".repeat(64)); context .transaction() - .executeWithoutResult( - status -> { - try { - invokeDraftPersistence(restrictionRepository(context.dsl()), request); - } catch (ReflectiveOperationException failure) { - throw new IllegalStateException( - "Could not invoke the closed restriction draft", failure); - } - }); + .executeWithoutResult(status -> { + try { + invokeDraftPersistence(restrictionRepository(context.dsl()), request); + } catch (ReflectiveOperationException failure) { + throw new IllegalStateException( + "Could not invoke the closed restriction draft", failure); + } + }); } private static void invokeDraftPersistence( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java index 6308e443e7..22a454ebb0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlayerAdmissionCommittedLoginCompositionIntegrationTest.java @@ -221,10 +221,9 @@ void actualRecoveredLoginFlowsThroughPlayerAdmissionOwnerAndConsumer() throws Ex assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> false)) .isExactlyInstanceOf(StatusRuntimeException.class) .hasMessage("CANCELLED: Account player-admission entitlement read did not complete") - .satisfies( - failure -> - assertThat(((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.CANCELLED)); + .satisfies(failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.CANCELLED)); verify(receiver).readPlayerAdmissionEntitlement(any(), any()); // Retaining valid signature bytes and local custody is insufficient after Account moves. // The actual caller verifier and receiver classify this currentness loss as UNAVAILABLE. @@ -232,10 +231,9 @@ void actualRecoveredLoginFlowsThroughPlayerAdmissionOwnerAndConsumer() throws Ex assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> true)) .isExactlyInstanceOf(StatusRuntimeException.class) .hasMessage("UNAVAILABLE: Account player-admission entitlement read did not complete") - .satisfies( - failure -> - assertThat(((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); + .satisfies(failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); verify(receiver, times(2)).readPlayerAdmissionEntitlement(any(), any()); login.close(); assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> true)) @@ -253,91 +251,83 @@ void actualRecoveredLoginFlowsThroughPlayerAdmissionOwnerAndConsumer() throws Ex /** Controlled protected-client double: no physical GS/World source provenance is claimed. */ private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClient targets) { when(targets.resolvePublishedRealmAdmissionTarget(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - var selector = - invocation.getArgument( - 0, - CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); - var target = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); - when(target.targetNamespace()).thenReturn(selector.targetNamespace()); - when(target.canonicalTenantId()).thenReturn(selector.tenantId()); - when(target.tenantSlug()).thenReturn(selector.tenantSlug()); - when(target.worldSlug()).thenReturn(selector.worldSlug()); - when(target.realmId()).thenReturn(selector.realmId()); - when(target.realmSlug()).thenReturn(selector.realmSlug()); - when(target.playableStateNamespaceId()) - .thenReturn(selector.playableStateNamespaceId()); - when(target.playableStateScope()).thenReturn(selector.playableStateScope()); - when(target.canonicalGameInstanceId()).thenReturn(selector.gameInstanceId()); - when(target.catalogRevision()).thenReturn(selector.catalogRevision()); - when(target.pointerVersion()).thenReturn(selector.pointerVersion()); - when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); - when(target.ownerProofOutcome()) - .thenReturn( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED); - UUID version = UUID.fromString("33333333-3333-4333-8333-333333333333"); - when(target.canonicalVersionId()).thenReturn(version); - when(target.activeWorldEpoch()).thenReturn(5L); - var strict = - new CanonicalGameplayRosterOwnerReadEvidence.Request( - selector.readRequestId(), - selector.accountId(), - selector.targetNamespace(), - selector.tenantId(), - selector.worldSlug(), - selector.realmId(), - selector.realmSlug(), - selector.playableStateNamespaceId(), - selector.playableStateScope(), - selector.gameInstanceId(), - version, - selector.catalogRevision(), - selector.pointerVersion(), - 5L); - var resolved = - mock( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget - .class); - when(resolved.selector()).thenReturn(selector); - when(resolved.currentTarget()).thenReturn(target); - when(resolved.strictSelector()).thenReturn(strict); - var read = - mock( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); - when(read.selector()).thenReturn(strict); - when(read.currentTarget()).thenReturn(target); - var source = mock(CanonicalGameplayRosterOwnerReadEvidence.class); - when(source.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); - var policies = mock(PublishedRealmEntryPolicySetEvidence.class); - when(policies.policySetDigest()).thenReturn("sha256:" + "b".repeat(64)); - when(source.publishedPolicySetEvidence()).thenReturn(policies); - var ownerProof = - mock( - net.firedevops.firemud.common.world - .GameSessionCanonicalInitialAdmissionOwnerProof.class); - when(ownerProof.proofDigest()).thenReturn("sha256:" + "c".repeat(64)); - when(source.gameSessionOwnerProof()).thenReturn(ownerProof); - when(read.sourceEvidence()).thenReturn(source); - var world = mock(WorldCanonicalInstanceLifecycleEvidence.class); - when(world.canonicalBytes()) - .thenReturn( - "controlled-complete-world-source" - .getBytes(java.nio.charset.StandardCharsets.UTF_8)); - when(world.captureId()) - .thenReturn(UUID.fromString("44444444-4444-4444-8444-444444444444")); - when(world.rowVersion()).thenReturn(2L); - when(read.worldLifecycleEvidence()).thenReturn(world); - when(targets.readPublishedRealmAdmissionOwner(strict)) - .thenAnswer( - readCall -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()) - .isFalse(); - return read; - }); - return resolved; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var selector = + invocation.getArgument( + 0, CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); + var target = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); + when(target.targetNamespace()).thenReturn(selector.targetNamespace()); + when(target.canonicalTenantId()).thenReturn(selector.tenantId()); + when(target.tenantSlug()).thenReturn(selector.tenantSlug()); + when(target.worldSlug()).thenReturn(selector.worldSlug()); + when(target.realmId()).thenReturn(selector.realmId()); + when(target.realmSlug()).thenReturn(selector.realmSlug()); + when(target.playableStateNamespaceId()).thenReturn(selector.playableStateNamespaceId()); + when(target.playableStateScope()).thenReturn(selector.playableStateScope()); + when(target.canonicalGameInstanceId()).thenReturn(selector.gameInstanceId()); + when(target.catalogRevision()).thenReturn(selector.catalogRevision()); + when(target.pointerVersion()).thenReturn(selector.pointerVersion()); + when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + when(target.ownerProofOutcome()) + .thenReturn( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED); + UUID version = UUID.fromString("33333333-3333-4333-8333-333333333333"); + when(target.canonicalVersionId()).thenReturn(version); + when(target.activeWorldEpoch()).thenReturn(5L); + var strict = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + selector.readRequestId(), + selector.accountId(), + selector.targetNamespace(), + selector.tenantId(), + selector.worldSlug(), + selector.realmId(), + selector.realmSlug(), + selector.playableStateNamespaceId(), + selector.playableStateScope(), + selector.gameInstanceId(), + version, + selector.catalogRevision(), + selector.pointerVersion(), + 5L); + var resolved = + mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget.class); + when(resolved.selector()).thenReturn(selector); + when(resolved.currentTarget()).thenReturn(target); + when(resolved.strictSelector()).thenReturn(strict); + var read = + mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + when(read.selector()).thenReturn(strict); + when(read.currentTarget()).thenReturn(target); + var source = mock(CanonicalGameplayRosterOwnerReadEvidence.class); + when(source.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); + var policies = mock(PublishedRealmEntryPolicySetEvidence.class); + when(policies.policySetDigest()).thenReturn("sha256:" + "b".repeat(64)); + when(source.publishedPolicySetEvidence()).thenReturn(policies); + var ownerProof = + mock( + net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof + .class); + when(ownerProof.proofDigest()).thenReturn("sha256:" + "c".repeat(64)); + when(source.gameSessionOwnerProof()).thenReturn(ownerProof); + when(read.sourceEvidence()).thenReturn(source); + var world = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(world.canonicalBytes()) + .thenReturn( + "controlled-complete-world-source" + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + when(world.captureId()) + .thenReturn(UUID.fromString("44444444-4444-4444-8444-444444444444")); + when(world.rowVersion()).thenReturn(2L); + when(read.worldLifecycleEvidence()).thenReturn(world); + when(targets.readPublishedRealmAdmissionOwner(strict)) + .thenAnswer(readCall -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return read; + }); + return resolved; + }); } private static AuthenticateResponse projectRecoveredInitial(InitialGameplayLoginResult result) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixtureTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixtureTest.java index 0e94595d78..1ab8d8a105 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixtureTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPostgresIntegrationFixtureTest.java @@ -15,9 +15,8 @@ void durablePrimaryCommandRequiresFlushedLocalCommits() { @Test void acceptsDurablePrimarySettings() { - assertThatCode( - () -> - AccountPostgresIntegrationFixture.validateDurablePrimarySettings(false, "on", "on")) + assertThatCode(() -> + AccountPostgresIntegrationFixture.validateDurablePrimarySettings(false, "on", "on")) .doesNotThrowAnyException(); } @@ -30,10 +29,9 @@ void rejectsRecoveryAndUnflushedCommitSettings() { private static void assertRejectedSettings( boolean inRecovery, String fsync, String synchronousCommit) { - assertThatThrownBy( - () -> - AccountPostgresIntegrationFixture.validateDurablePrimarySettings( - inRecovery, fsync, synchronousCommit)) + assertThatThrownBy(() -> + AccountPostgresIntegrationFixture.validateDurablePrimarySettings( + inRecovery, fsync, synchronousCommit)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Durable PostgreSQL primary required"); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java index 8e9c5d1650..86f8655cbd 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java @@ -195,20 +195,18 @@ void joinIntentCommitsBeforePolicyAndMembershipAuditOutcomeCommitAtomically() { UUID auditEventId = UUID.randomUUID(); Account account = new Account(); account.setId(accountId); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - status -> - commitJoinOutcome( - joinOperations, - memberships, - outbox, - account, - requestId, - scope, - policyDigest, - auditEventId, - true))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(status -> + commitJoinOutcome( + joinOperations, + memberships, + outbox, + account, + requestId, + scope, + policyDigest, + auditEventId, + true))) .isInstanceOf(IllegalStateException.class) .hasMessage("simulate second-transaction rollback"); @@ -229,18 +227,17 @@ void joinIntentCommitsBeforePolicyAndMembershipAuditOutcomeCommitAtomically() { auditEventId)) .isZero(); - transaction.executeWithoutResult( - status -> - commitJoinOutcome( - joinOperations, - memberships, - outbox, - account, - requestId, - scope, - policyDigest, - auditEventId, - false)); + transaction.executeWithoutResult(status -> + commitJoinOutcome( + joinOperations, + memberships, + outbox, + account, + requestId, + scope, + policyDigest, + auditEventId, + false)); assertThat(joinOperation(joinOperations, requestId).status()).isEqualTo("COMMITTED"); assertThat(joinOperation(joinOperations, requestId).outcome()).isEqualTo("JOINED"); @@ -289,9 +286,8 @@ void minimizedAuditReceiptClearsPayloadAndRetainsCompactIdentity() { () -> outbox.markDelivered(minimizedEventId, "receipt-minimized", "other-log", true)) .isInstanceOf(IllegalStateException.class) .hasMessage("Audit delivery state changed concurrently"); - assertThatThrownBy( - () -> - outbox.markDelivered(minimizedEventId, "receipt-minimized", "log-minimized", false)) + assertThatThrownBy(() -> + outbox.markDelivered(minimizedEventId, "receipt-minimized", "log-minimized", false)) .isInstanceOf(IllegalStateException.class) .hasMessage("Audit delivery state changed concurrently"); assertThatThrownBy( @@ -430,13 +426,12 @@ void pendingLegacyAuditDeliverySkipsCanonicalRowsBeforeApplyingLimit() { TransactionTemplate transaction = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); - transaction.executeWithoutResult( - status -> - outbox.appendCanonicalTenant( - canonicalEventId, - "ba819905-1a20-48a0-b9de-7f34f8b8ad3d", - "ACCOUNT_JOINED_PUBLIC_PRODUCTION", - canonicalPayload)); + transaction.executeWithoutResult(status -> + outbox.appendCanonicalTenant( + canonicalEventId, + "ba819905-1a20-48a0-b9de-7f34f8b8ad3d", + "ACCOUNT_JOINED_PUBLIC_PRODUCTION", + canonicalPayload)); outbox.append(legacyEventId, "platform", null, "ACCOUNT_REGISTERED", legacyPayload); assertThat(outbox.pending(1, Instant.now())) @@ -474,51 +469,47 @@ void auditAttemptTimesUseUtcLocalDateTimeUnderNonUtcDatabaseSession() { UUID appendedEventId = UUID.randomUUID(); UUID defaultedEventId = UUID.randomUUID(); - transaction.executeWithoutResult( - status -> { - transactionJdbc.execute("SET LOCAL TIME ZONE 'Pacific/Auckland'"); - assertThat( - transactionJdbc.queryForObject( - "SELECT current_setting('TimeZone')", String.class)) - .isEqualTo("Pacific/Auckland"); - - outbox.append(appendedEventId, "platform", null, "ACCOUNT_REGISTERED", "{}"); - LocalDateTime occurredAt = - transactionJdbc.queryForObject( - "SELECT occurred_at FROM account_audit_outbox WHERE audit_event_id = ?", - LocalDateTime.class, - appendedEventId); - LocalDateTime retryAt = + transaction.executeWithoutResult(status -> { + transactionJdbc.execute("SET LOCAL TIME ZONE 'Pacific/Auckland'"); + assertThat(transactionJdbc.queryForObject("SELECT current_setting('TimeZone')", String.class)) + .isEqualTo("Pacific/Auckland"); + + outbox.append(appendedEventId, "platform", null, "ACCOUNT_REGISTERED", "{}"); + LocalDateTime occurredAt = + transactionJdbc.queryForObject( + "SELECT occurred_at FROM account_audit_outbox WHERE audit_event_id = ?", + LocalDateTime.class, + appendedEventId); + LocalDateTime retryAt = + transactionJdbc.queryForObject( + "SELECT next_attempt_at FROM account_audit_outbox WHERE audit_event_id = ?", + LocalDateTime.class, + appendedEventId); + assertThat(retryAt).isEqualTo(occurredAt); + + Instant beforeDefaultInsert = Instant.now(); + transactionJdbc.update( + "INSERT INTO account_audit_outbox " + + "(audit_event_id, scope, producer_service, event_type, occurred_at, " + + "tenant_identity_version, schema_version, payload_digest_version, payload_digest, payload, delivery_status) " + + "VALUES (?, 'platform', 'account-service', 'ACCOUNT_REGISTERED', ?, 1, 1, 1, ?, '{}', 'PENDING')", + defaultedEventId, + LocalDateTime.ofInstant(beforeDefaultInsert, ZoneOffset.UTC), + AccountAuditDigest.ofPayload("{}")); + LocalDateTime defaultRetryAt = + Objects.requireNonNull( transactionJdbc.queryForObject( "SELECT next_attempt_at FROM account_audit_outbox WHERE audit_event_id = ?", LocalDateTime.class, - appendedEventId); - assertThat(retryAt).isEqualTo(occurredAt); - - Instant beforeDefaultInsert = Instant.now(); - transactionJdbc.update( - "INSERT INTO account_audit_outbox " - + "(audit_event_id, scope, producer_service, event_type, occurred_at, " - + "tenant_identity_version, schema_version, payload_digest_version, payload_digest, payload, delivery_status) " - + "VALUES (?, 'platform', 'account-service', 'ACCOUNT_REGISTERED', ?, 1, 1, 1, ?, '{}', 'PENDING')", - defaultedEventId, - LocalDateTime.ofInstant(beforeDefaultInsert, ZoneOffset.UTC), - AccountAuditDigest.ofPayload("{}")); - LocalDateTime defaultRetryAt = - Objects.requireNonNull( - transactionJdbc.queryForObject( - "SELECT next_attempt_at FROM account_audit_outbox WHERE audit_event_id = ?", - LocalDateTime.class, - defaultedEventId), - "next_attempt_at database default should be populated"); - assertThat( - Duration.between(beforeDefaultInsert, defaultRetryAt.toInstant(ZoneOffset.UTC))) - .isLessThan(Duration.ofSeconds(10)); - assertThat( - Duration.between(defaultRetryAt, LocalDateTime.now(ZoneId.of("Pacific/Auckland"))) - .abs()) - .isGreaterThan(Duration.ofHours(1)); - }); + defaultedEventId), + "next_attempt_at database default should be populated"); + assertThat(Duration.between(beforeDefaultInsert, defaultRetryAt.toInstant(ZoneOffset.UTC))) + .isLessThan(Duration.ofSeconds(10)); + assertThat( + Duration.between(defaultRetryAt, LocalDateTime.now(ZoneId.of("Pacific/Auckland"))) + .abs()) + .isGreaterThan(Duration.ofHours(1)); + }); } @Test @@ -558,30 +549,26 @@ void canonicalSubscriptionOriginalBindingLocksRequiredOwnerChainThroughCommit() CountDownLatch releaseSubscriptionLock = new CountDownLatch(1); ExecutorService executor = Executors.newSingleThreadExecutor(); Future lockHolder = - executor.submit( - () -> - lockTransaction.executeWithoutResult( - status -> { - assertThat( - fixture - .intents() - .lockForLifecycle( - fixture.creation().requestId(), - receipt.current().rowVersion())) - .isEqualTo(receipt.current()); - assertThat(fixture.intents().findCreation(fixture.creation().requestId())) - .contains(fixture.creation()); - subscriptionLocked.countDown(); - try { - if (!releaseSubscriptionLock.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException( - "Timed out holding subscription row lock"); - } - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("Interrupted while holding row lock", ex); - } - })); + executor.submit(() -> + lockTransaction.executeWithoutResult(status -> { + assertThat( + fixture + .intents() + .lockForLifecycle( + fixture.creation().requestId(), receipt.current().rowVersion())) + .isEqualTo(receipt.current()); + assertThat(fixture.intents().findCreation(fixture.creation().requestId())) + .contains(fixture.creation()); + subscriptionLocked.countDown(); + try { + if (!releaseSubscriptionLock.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out holding subscription row lock"); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while holding row lock", ex); + } + })); try { assertThat(subscriptionLocked.await(5, TimeUnit.SECONDS)).isTrue(); @@ -605,27 +592,23 @@ void canonicalSubscriptionOriginalBindingLocksRequiredOwnerChainThroughCommit() "SELECT 1 FROM subscription_instrument_reservations WHERE request_id = ? FOR UPDATE", fixture.creation().requestId()); for (var row : lockedRows.entrySet()) { - assertThatThrownBy( - () -> - conflictingTransaction.executeWithoutResult( - status -> { - conflictingJdbc.execute("SET LOCAL lock_timeout = '250ms'"); - conflictingJdbc.queryForObject( - row.getKey(), Integer.class, row.getValue()); - })) + assertThatThrownBy(() -> + conflictingTransaction.executeWithoutResult(status -> { + conflictingJdbc.execute("SET LOCAL lock_timeout = '250ms'"); + conflictingJdbc.queryForObject(row.getKey(), Integer.class, row.getValue()); + })) .as("owner-chain lock retained: %s", row.getKey()) .hasMessageContaining("lock timeout"); } Integer updatedAccounts = - conflictingTransaction.execute( - status -> { - conflictingJdbc.execute("SET LOCAL lock_timeout = '2s'"); - return conflictingJdbc.update( - "UPDATE accounts SET email = ? WHERE id = ?", - "unrelated-subscription-lock-updated@example.com", - unrelatedAccountId); - }); + conflictingTransaction.execute(status -> { + conflictingJdbc.execute("SET LOCAL lock_timeout = '2s'"); + return conflictingJdbc.update( + "UPDATE accounts SET email = ? WHERE id = ?", + "unrelated-subscription-lock-updated@example.com", + unrelatedAccountId); + }); assertThat(updatedAccounts).isEqualTo(1); } finally { releaseSubscriptionLock.countDown(); @@ -636,16 +619,14 @@ void canonicalSubscriptionOriginalBindingLocksRequiredOwnerChainThroughCommit() } } // The same real owner operation succeeds from an independent transaction after holder commit. - lockTransaction.executeWithoutResult( - status -> { - jdbc.execute("SET LOCAL lock_timeout = '2s'"); - assertThat( - fixture - .intents() - .lockForLifecycle( - fixture.creation().requestId(), receipt.current().rowVersion())) - .isEqualTo(receipt.current()); - }); + lockTransaction.executeWithoutResult(status -> { + jdbc.execute("SET LOCAL lock_timeout = '2s'"); + assertThat( + fixture + .intents() + .lockForLifecycle(fixture.creation().requestId(), receipt.current().rowVersion())) + .isEqualTo(receipt.current()); + }); assertThat(fixture.intents().findCreation(fixture.creation().requestId())) .contains(fixture.creation()); } @@ -744,17 +725,10 @@ void privateRealmGrantRevocationRetainsMonotonicCurrentnessForRevalidation() { UUID revokedGeneration = revoked.getGrantAuthorityGeneration(); var regrantResult = - transaction.execute( - status -> - accountService.grantRealmAccess( - new RealmAccessGrantRequest( - accountId, - 7654323L, - "world", - "private", - "test", - "regrant", - "req-regrant-1"))); + transaction.execute(status -> + accountService.grantRealmAccess( + new RealmAccessGrantRequest( + accountId, 7654323L, "world", "private", "test", "regrant", "req-regrant-1"))); AccountRealmAccessGrant regranted = grants .findByAccountIdAndTenantIdAndWorldSlugAndRealmSlug( @@ -975,11 +949,10 @@ void expiredConnectScopeCleanupPreservesEveryReferencedStatusAndMalformedEvidenc assertThat(scopeCount(jdbc, future)).isEqualTo(1); assertThat(scopeCount(jdbc, malformed)).isEqualTo(1); assertThat(scopeCount(jdbc, invalidCalendarDate)).isEqualTo(1); - assertThatThrownBy( - () -> - jdbc.update( - "DELETE FROM account_connect_scope_records WHERE scope_token_hash = ?", - AccountJoinDigest.tokenHash(pending.connectScopeId()))) + assertThatThrownBy(() -> + jdbc.update( + "DELETE FROM account_connect_scope_records WHERE scope_token_hash = ?", + AccountJoinDigest.tokenHash(pending.connectScopeId()))) .isInstanceOf(org.springframework.dao.DataIntegrityViolationException.class); assertThatThrownBy( () -> insertJoinIntent(joinOperations, unreferenced, "join-scope-after-cleanup")) @@ -1259,31 +1232,29 @@ void repositoryPersistsAndReadsBackUniqueAccountUuidAndProvenance() { .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); assertThat(updated.getAccountUuidSourceNumericId()).isEqualTo(updated.getId()); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO accounts " - + "(username, email, password_hash, account_uuid, account_uuid_provenance) " - + "VALUES (?, ?, ?, ?, ?)", - "duplicate-uuid-account", - "duplicate-uuid-account@example.com", - "hash", - accountUuid, - AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT.name())) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO accounts " + + "(username, email, password_hash, account_uuid, account_uuid_provenance) " + + "VALUES (?, ?, ?, ?, ?)", + "duplicate-uuid-account", + "duplicate-uuid-account@example.com", + "hash", + accountUuid, + AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT.name())) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("accounts_account_uuid_unique"); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO accounts " - + "(username, email, password_hash, account_uuid, account_uuid_provenance) " - + "VALUES (?, ?, ?, ?, ?)", - "nil-uuid-account", - "nil-uuid-account@example.com", - "hash", - new UUID(0L, 0L), - AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT.name())) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO accounts " + + "(username, email, password_hash, account_uuid, account_uuid_provenance) " + + "VALUES (?, ?, ?, ?, ?)", + "nil-uuid-account", + "nil-uuid-account@example.com", + "hash", + new UUID(0L, 0L), + AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT.name())) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("accounts_account_uuid_non_nil_check"); @@ -1300,28 +1271,26 @@ void repositoryPersistsAndReadsBackUniqueAccountUuidAndProvenance() { assertThat(databaseInserted.get("account_uuid_source_numeric_id", Long.class)) .isEqualTo(databaseInserted.get("id", Long.class)); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO accounts " - + "(username, email, password_hash, account_uuid, " - + "account_uuid_provenance) VALUES (?, ?, ?, ?, ?)", - "migration-origin-account", - "migration-origin@example.com", - "hash", - UUID.randomUUID(), - AccountIdentityProvenance.ACCOUNT_V29_MIGRATION.name())) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO accounts " + + "(username, email, password_hash, account_uuid, " + + "account_uuid_provenance) VALUES (?, ?, ?, ?, ?)", + "migration-origin-account", + "migration-origin@example.com", + "hash", + UUID.randomUUID(), + AccountIdentityProvenance.ACCOUNT_V29_MIGRATION.name())) .isInstanceOf(DataAccessException.class) .hasMessageContaining("ACCOUNT_V29_MIGRATION provenance is reserved for retained rows") - .satisfies( - failure -> { - Throwable rootCause = failure; - while (rootCause.getCause() != null) { - rootCause = rootCause.getCause(); - } - assertThat(rootCause).isInstanceOf(SQLException.class); - assertThat(((SQLException) rootCause).getSQLState()).isEqualTo("23514"); - }); + .satisfies(failure -> { + Throwable rootCause = failure; + while (rootCause.getCause() != null) { + rootCause = rootCause.getCause(); + } + assertThat(rootCause).isInstanceOf(SQLException.class); + assertThat(((SQLException) rootCause).getSQLState()).isEqualTo("23514"); + }); assertThat( dsl.fetchValue( "SELECT COUNT(*) FROM accounts WHERE username = 'migration-origin-account'", @@ -1355,13 +1324,12 @@ void batchAccountUuidReadReturnsOnlyRequestedRowsWithPersistedIdentityEvidence() .extracting(Account::getAccountUuid) .containsExactlyInAnyOrder(first.getAccountUuid(), second.getAccountUuid()); assertThat(owners) - .allSatisfy( - owner -> { - assertThat(owner.getId()).isPositive(); - assertThat(owner.getAccountUuidProvenance()) - .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); - assertThat(owner.getAccountUuidSourceNumericId()).isEqualTo(owner.getId()); - }); + .allSatisfy(owner -> { + assertThat(owner.getId()).isPositive(); + assertThat(owner.getAccountUuidProvenance()) + .isEqualTo(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + assertThat(owner.getAccountUuidSourceNumericId()).isEqualTo(owner.getId()); + }); assertThat(repository.findByAccountUuids(List.of())).isEmpty(); } @@ -1441,13 +1409,12 @@ void flywayCanonicalizesLegacyEmailAndRejectsNonCanonicalValues() { + MIGRATION_PROOF_SCHEMA + ".accounts WHERE username = 'legacy-migration'")) .isEqualTo("legacy@example.com"); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO " - + MIGRATION_PROOF_SCHEMA - + ".accounts (username, email, password_hash) " - + "VALUES ('noncanonical', ' Another@Example.COM ', 'hash')")) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO " + + MIGRATION_PROOF_SCHEMA + + ".accounts (username, email, password_hash) " + + "VALUES ('noncanonical', ' Another@Example.COM ', 'hash')")) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("accounts_email_canonical_check"); } @@ -1480,16 +1447,15 @@ void flywayRejectsCanonicalEmailCollisionsBeforeRewriting() { + ".accounts (username, email, password_hash) " + "VALUES ('collision-second', ' player@example.com ', 'hash')"); - assertThatThrownBy( - () -> - Flyway.configure() - .dataSource(dataSource) - .locations(MIGRATION_LOCATION) - .schemas(COLLISION_MIGRATION_PROOF_SCHEMA) - .defaultSchema(COLLISION_MIGRATION_PROOF_SCHEMA) - .placeholders(Map.of("serviceSchema", COLLISION_MIGRATION_PROOF_SCHEMA)) - .load() - .migrate()) + assertThatThrownBy(() -> + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(COLLISION_MIGRATION_PROOF_SCHEMA) + .defaultSchema(COLLISION_MIGRATION_PROOF_SCHEMA) + .placeholders(Map.of("serviceSchema", COLLISION_MIGRATION_PROOF_SCHEMA)) + .load() + .migrate()) .isInstanceOf(FlywayException.class) .hasStackTraceContaining("accounts_email_canonicalization_collision"); @@ -1533,14 +1499,12 @@ void profilesAllowOneGlobalAccountAcrossTenantsButRejectDuplicateTenantIdentity( dsl.resultQuery("SELECT COUNT(*) FROM profiles WHERE account_id = ?", accountId) .fetchOne(0, Long.class)) .isEqualTo(2L); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO profiles (account_id, tenant_id, display_name) " - + "VALUES (?, ?, ?)", - accountId, - 101L, - "Tenant One Duplicate")) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO profiles (account_id, tenant_id, display_name) " + "VALUES (?, ?, ?)", + accountId, + 101L, + "Tenant One Duplicate")) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("profiles_tenant_account_unique"); } @@ -1588,16 +1552,15 @@ void flywayRejectsRetainedDuplicateProfileTenantIdentityBeforeAddingConstraint() 303L, "Retained Duplicate"); - assertThatThrownBy( - () -> - Flyway.configure() - .dataSource(dataSource) - .locations(MIGRATION_LOCATION) - .schemas(PROFILE_IDENTITY_MIGRATION_PROOF_SCHEMA) - .defaultSchema(PROFILE_IDENTITY_MIGRATION_PROOF_SCHEMA) - .placeholders(Map.of("serviceSchema", PROFILE_IDENTITY_MIGRATION_PROOF_SCHEMA)) - .load() - .migrate()) + assertThatThrownBy(() -> + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .schemas(PROFILE_IDENTITY_MIGRATION_PROOF_SCHEMA) + .defaultSchema(PROFILE_IDENTITY_MIGRATION_PROOF_SCHEMA) + .placeholders(Map.of("serviceSchema", PROFILE_IDENTITY_MIGRATION_PROOF_SCHEMA)) + .load() + .migrate()) .isInstanceOf(FlywayException.class) .hasStackTraceContaining("profiles_tenant_account_identity_collision"); @@ -2228,59 +2191,53 @@ void accountUuidMigrationPreservesRetainedRowsAndRecordsExactSourceIdentity() { .fetchOne(0, Long.class)) .isEqualTo(1L); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE " + schema + ".accounts SET account_uuid = ? WHERE id = ?", - UUID.randomUUID(), - firstAccountId)) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE " + schema + ".accounts SET account_uuid = ? WHERE id = ?", + UUID.randomUUID(), + firstAccountId)) .isInstanceOf(DataAccessException.class) .hasMessageContaining("Account identity cannot be reassigned") - .satisfies( - failure -> { - Throwable rootCause = failure; - while (rootCause.getCause() != null) { - rootCause = rootCause.getCause(); - } - assertThat(rootCause).isInstanceOf(SQLException.class); - assertThat(((SQLException) rootCause).getSQLState()).isEqualTo("23514"); - }); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE " + schema + ".accounts SET account_uuid_provenance = ? WHERE id = ?", - AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT.name(), - firstAccountId)) + .satisfies(failure -> { + Throwable rootCause = failure; + while (rootCause.getCause() != null) { + rootCause = rootCause.getCause(); + } + assertThat(rootCause).isInstanceOf(SQLException.class); + assertThat(((SQLException) rootCause).getSQLState()).isEqualTo("23514"); + }); + assertThatThrownBy(() -> + dsl.execute( + "UPDATE " + schema + ".accounts SET account_uuid_provenance = ? WHERE id = ?", + AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT.name(), + firstAccountId)) .isInstanceOf(DataAccessException.class) .hasMessageContaining("Account identity cannot be reassigned") - .satisfies( - failure -> { - Throwable rootCause = failure; - while (rootCause.getCause() != null) { - rootCause = rootCause.getCause(); - } - assertThat(rootCause).isInstanceOf(SQLException.class); - assertThat(((SQLException) rootCause).getSQLState()).isEqualTo("23514"); - }); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE " - + schema - + ".accounts SET account_uuid_source_numeric_id = ? WHERE id = ?", - firstAccountId + 10, - firstAccountId)) + .satisfies(failure -> { + Throwable rootCause = failure; + while (rootCause.getCause() != null) { + rootCause = rootCause.getCause(); + } + assertThat(rootCause).isInstanceOf(SQLException.class); + assertThat(((SQLException) rootCause).getSQLState()).isEqualTo("23514"); + }); + assertThatThrownBy(() -> + dsl.execute( + "UPDATE " + + schema + + ".accounts SET account_uuid_source_numeric_id = ? WHERE id = ?", + firstAccountId + 10, + firstAccountId)) .isInstanceOf(DataAccessException.class) .hasMessageContaining("Account identity cannot be reassigned") - .satisfies( - failure -> { - Throwable rootCause = failure; - while (rootCause.getCause() != null) { - rootCause = rootCause.getCause(); - } - assertThat(rootCause).isInstanceOf(SQLException.class); - assertThat(((SQLException) rootCause).getSQLState()).isEqualTo("23514"); - }); + .satisfies(failure -> { + Throwable rootCause = failure; + while (rootCause.getCause() != null) { + rootCause = rootCause.getCause(); + } + assertThat(rootCause).isInstanceOf(SQLException.class); + assertThat(((SQLException) rootCause).getSQLState()).isEqualTo("23514"); + }); assertThat( dsl.resultQuery( "SELECT account_uuid FROM " + schema + ".accounts WHERE id = ?", firstAccountId) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java index 529cca5037..06eb4e4a9d 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSecuritySourceOwnerGuardPostgresIntegrationTest.java @@ -110,20 +110,17 @@ void closedResetAndLogoutEventsPassExactGuardsAndRejectUnbackedMutations() { Account afterReset = accounts.findByAccountUuid(seed.account().getAccountUuid()).orElseThrow(); PasswordResetReceipt resetReceipt = - transaction.execute( - status -> - resetOperations.findByTokenHash(sha256Hex(seed.rawResetToken())).orElseThrow()); + transaction.execute(status -> + resetOperations.findByTokenHash(sha256Hex(seed.rawResetToken())).orElseThrow()); ScopeState resetState = readState(transaction, generations, seed.account().getAccountUuid()); CurrentSourceEvidence resetEvidence = - transaction.execute( - status -> - sources.readCurrentAccountSource(seed.account().getAccountUuid(), resetState)); + transaction.execute(status -> + sources.readCurrentAccountSource(seed.account().getAccountUuid(), resetState)); var resetEvent = - transaction.execute( - status -> - outbox - .findEvent(resetReceipt.outboxStreamKey(), resetReceipt.outboxSequence()) - .orElseThrow()); + transaction.execute(status -> + outbox + .findEvent(resetReceipt.outboxStreamKey(), resetReceipt.outboxSequence()) + .orElseThrow()); var decodedReset = PasswordResetAuthorityEventV1Codec.verify( new String(resetEvent.payload(), StandardCharsets.UTF_8)); @@ -139,12 +136,11 @@ void closedResetAndLogoutEventsPassExactGuardsAndRejectUnbackedMutations() { assertThat(resetEvidence.checkpoint().sequence()).isEqualTo(1L); assertThat(afterReset.getPasswordHash()).startsWith("$argon2"); - assertDatabaseWriteRejected( - () -> - dsl.execute( - "UPDATE accounts SET password_hash = ? WHERE account_uuid = ?", - "unbacked-password-verifier", - seed.account().getAccountUuid())); + assertDatabaseWriteRejected(() -> + dsl.execute( + "UPDATE accounts SET password_hash = ? WHERE account_uuid = ?", + "unbacked-password-verifier", + seed.account().getAccountUuid())); assertThat( accounts .findByAccountUuid(seed.account().getAccountUuid()) @@ -152,19 +148,17 @@ void closedResetAndLogoutEventsPassExactGuardsAndRejectUnbackedMutations() { .getPasswordHash()) .isEqualTo(afterReset.getPasswordHash()); - assertDatabaseWriteRejected( - () -> - dsl.execute( - "UPDATE account_password_reset_operation_receipts " - + "SET request_digest = request_digest WHERE token_hash = ?", - HEX.parseHex(resetReceipt.tokenHash()))); - assertDatabaseWriteRejected( - () -> - dsl.execute( - "UPDATE account_authority_issuance_fences " - + "SET issuance_fence = issuance_fence + 1, source_version = source_version + 1 " - + "WHERE account_uuid = ?", - seed.account().getAccountUuid())); + assertDatabaseWriteRejected(() -> + dsl.execute( + "UPDATE account_password_reset_operation_receipts " + + "SET request_digest = request_digest WHERE token_hash = ?", + HEX.parseHex(resetReceipt.tokenHash()))); + assertDatabaseWriteRejected(() -> + dsl.execute( + "UPDATE account_authority_issuance_fences " + + "SET issuance_fence = issuance_fence + 1, source_version = source_version + 1 " + + "WHERE account_uuid = ?", + seed.account().getAccountUuid())); assertThat(readState(transaction, generations, seed.account().getAccountUuid())) .isEqualTo(resetState); @@ -203,19 +197,17 @@ void closedResetAndLogoutEventsPassExactGuardsAndRejectUnbackedMutations() { transaction.execute( status -> logoutOperations.findByRequestId(logoutRequestId).orElseThrow()); var logoutEvent = - transaction.execute( - status -> - outbox - .findEvent(logoutReceipt.outboxStreamKey(), logoutReceipt.outboxSequence()) - .orElseThrow()); + transaction.execute(status -> + outbox + .findEvent(logoutReceipt.outboxStreamKey(), logoutReceipt.outboxSequence()) + .orElseThrow()); var decodedLogout = AccountLogoutAllAuthorityEventV1Codec.verify( new String(logoutEvent.payload(), StandardCharsets.UTF_8)); ScopeState finalState = readState(transaction, generations, seed.account().getAccountUuid()); CurrentSourceEvidence finalEvidence = - transaction.execute( - status -> - sources.readCurrentAccountSource(seed.account().getAccountUuid(), finalState)); + transaction.execute(status -> + sources.readCurrentAccountSource(seed.account().getAccountUuid(), finalState)); assertThat(decodedLogout.accountId()).isEqualTo(seed.account().getAccountUuid().toString()); assertThat(decodedLogout.accountAuthorityGeneration()).isEqualTo("3"); @@ -228,12 +220,11 @@ void closedResetAndLogoutEventsPassExactGuardsAndRejectUnbackedMutations() { assertThat(finalState.sourceVersion()).isEqualTo(3L); assertThat(finalState.issuanceFence().value()).isEqualTo(3L); - assertDatabaseWriteRejected( - () -> - dsl.execute( - "UPDATE accounts SET password_hash = ? WHERE account_uuid = ?", - "logout-is-not-password-reset-authority", - seed.account().getAccountUuid())); + assertDatabaseWriteRejected(() -> + dsl.execute( + "UPDATE accounts SET password_hash = ? WHERE account_uuid = ?", + "logout-is-not-password-reset-authority", + seed.account().getAccountUuid())); assertThat( accounts .findByAccountUuid(seed.account().getAccountUuid()) @@ -263,24 +254,23 @@ private Seed seedAccountAndResetToken( TransactionTemplate transaction, AccountRepository accounts, PasswordResetTokenRepository tokens) { - return transaction.execute( - status -> { - String suffix = UUID.randomUUID().toString(); - Account account = new Account(); - account.setUsername("source-guard-" + suffix); - account.setEmail("source-guard-" + suffix + "@example.test"); - account.setPasswordHash("initial-password-verifier-" + suffix); - account.setRole("player"); - Account saved = accounts.save(account); + return transaction.execute(status -> { + String suffix = UUID.randomUUID().toString(); + Account account = new Account(); + account.setUsername("source-guard-" + suffix); + account.setEmail("source-guard-" + suffix + "@example.test"); + account.setPasswordHash("initial-password-verifier-" + suffix); + account.setRole("player"); + Account saved = accounts.save(account); - String rawToken = "reset-token-" + suffix; - PasswordResetToken token = new PasswordResetToken(); - token.setAccount(saved); - token.setToken(rawToken); - token.setExpiresAt(LocalDateTime.now().plusHours(2)); - tokens.save(token); - return new Seed(saved, rawToken); - }); + String rawToken = "reset-token-" + suffix; + PasswordResetToken token = new PasswordResetToken(); + token.setAccount(saved); + token.setToken(rawToken); + token.setExpiresAt(LocalDateTime.now().plusHours(2)); + tokens.save(token); + return new Seed(saved, rawToken); + }); } private AccountServiceImpl newPasswordResetService( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java index 012428b62e..d29ac7b743 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java @@ -244,39 +244,38 @@ void controlUiIssuanceMustStartPreparedAndCanCommitAfterProtectedResponseReadbac // This row satisfies the table CHECKs. The INSERT guard must still reject a direct terminal // state before it can bypass the protected response readback transition. - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "INSERT INTO account_control_ui_issuance_operations " - + "(request_id, operation_id, token_jti, account_uuid, tenant_uuid, " - + "caller_workload, caller_context_id, request_mac_key_id, request_digest, " - + "claims_payload, source_payload, bundle_payload, signer_receipt, " - + "issued_at_epoch_second, expires_at_epoch_second, " - + "registry_cleanup_deadline_epoch_millis, recovery_expires_at, " - + "status, token_hash, pending_registry, active_registry, pending_receipt, " - + "committed_at) VALUES (?, ?, ?, ?, ?, 'test', ?, 'test-key', ?, ?, ?, ?, ?, ?, ?, " - + "?, ?::timestamptz, 'COMMITTED', ?, ?, ?, ?, CURRENT_TIMESTAMP)", - UUID.randomUUID(), - rejectedOperationId, - UUID.randomUUID(), - identity.accountUuid(), - identity.tenantUuid(), - UUID.randomUUID(), - "a".repeat(64), - candidate, - sourcePayload, - bundlePayload, - candidate, - issuedAt, - issuedAt + 300, - (issuedAt + 300) * 1000L, - recoveryExpiresAt, - "b".repeat(64), - candidate, - candidate, - candidate)) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "INSERT INTO account_control_ui_issuance_operations " + + "(request_id, operation_id, token_jti, account_uuid, tenant_uuid, " + + "caller_workload, caller_context_id, request_mac_key_id, request_digest, " + + "claims_payload, source_payload, bundle_payload, signer_receipt, " + + "issued_at_epoch_second, expires_at_epoch_second, " + + "registry_cleanup_deadline_epoch_millis, recovery_expires_at, " + + "status, token_hash, pending_registry, active_registry, pending_receipt, " + + "committed_at) VALUES (?, ?, ?, ?, ?, 'test', ?, 'test-key', ?, ?, ?, ?, ?, ?, ?, " + + "?, ?::timestamptz, 'COMMITTED', ?, ?, ?, ?, CURRENT_TIMESTAMP)", + UUID.randomUUID(), + rejectedOperationId, + UUID.randomUUID(), + identity.accountUuid(), + identity.tenantUuid(), + UUID.randomUUID(), + "a".repeat(64), + candidate, + sourcePayload, + bundlePayload, + candidate, + issuedAt, + issuedAt + 300, + (issuedAt + 300) * 1000L, + recoveryExpiresAt, + "b".repeat(64), + candidate, + candidate, + candidate)) .isInstanceOf(DataAccessException.class); ControlUiIssuance committed = @@ -552,26 +551,25 @@ void gameLogicSettlementAcceptsCompleteTerminalAndUsesCanonicalSourceLockOrder() new DraftAuthorizationFenceRepository(context.dsl()); context .transaction() - .executeWithoutResult( - status -> { - draftFences.reserve(originalDraftBinding); - draftFences.claimCommitOrder(originalDraftBinding); - for (Owner owner : originalDraftBinding.requiredOwners()) { - draftFences.recordOwnerReadback( - originalDraftBinding, - new OwnerReadback( - owner, - Outcome.COMMITTED, - originalDraftBinding.operationId(), - originalDraftBinding.commitId(), - originalDraftBinding.fenceId(), - originalDraftBinding.inputDigest(), - originalDraftBinding.canonicalBytes(), - utf8("test-only settled original owner fixture"))); - } - assertThat(draftFences.readSettlement(originalDraftBinding)) - .isEqualTo(DraftAuthorizationFenceRepository.Settlement.COMMITTED); - }); + .executeWithoutResult(status -> { + draftFences.reserve(originalDraftBinding); + draftFences.claimCommitOrder(originalDraftBinding); + for (Owner owner : originalDraftBinding.requiredOwners()) { + draftFences.recordOwnerReadback( + originalDraftBinding, + new OwnerReadback( + owner, + Outcome.COMMITTED, + originalDraftBinding.operationId(), + originalDraftBinding.commitId(), + originalDraftBinding.fenceId(), + originalDraftBinding.inputDigest(), + originalDraftBinding.canonicalBytes(), + utf8("test-only settled original owner fixture"))); + } + assertThat(draftFences.readSettlement(originalDraftBinding)) + .isEqualTo(DraftAuthorizationFenceRepository.Settlement.COMMITTED); + }); byte[] sourceReadScope = encodeFrames( @@ -589,80 +587,78 @@ void gameLogicSettlementAcceptsCompleteTerminalAndUsesCanonicalSourceLockOrder() byte[] outboxCheckpoints = "[]".getBytes(StandardCharsets.UTF_8); context .transaction() - .executeWithoutResult( - status -> { - context - .dsl() - .execute( - "INSERT INTO account_game_logic_intake_source_read_reservations " - + "(operation_id, fence_id, intake_request_id, actor_account_uuid, " - + "tenant_uuid, version_uuid, scope_bytes, scope_digest, " - + "issuance_operation_id, issuance_fence, source_payload, " - + "issuance_bundle, outbox_checkpoints) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - operationId, - fenceId, - requestId, - identity.accountUuid(), - identity.tenantUuid(), - versionUuid, - sourceReadScope, - sha256(sourceReadScope), - issuance.operationId(), - issuance.fence(), - sourcePayloadBytes, - bundlePayloadBytes, - outboxCheckpoints); - context - .dsl() - .execute( - "INSERT INTO account_game_logic_intake_source_read_sources " - + "(operation_id, source_key, source_evidence) " - + "VALUES (?, ?, ?), (?, ?, ?)", - operationId, - supplementaryKey, - supplementarySource, - operationId, - bmpKey, - bmpSource); - }); + .executeWithoutResult(status -> { + context + .dsl() + .execute( + "INSERT INTO account_game_logic_intake_source_read_reservations " + + "(operation_id, fence_id, intake_request_id, actor_account_uuid, " + + "tenant_uuid, version_uuid, scope_bytes, scope_digest, " + + "issuance_operation_id, issuance_fence, source_payload, " + + "issuance_bundle, outbox_checkpoints) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + fenceId, + requestId, + identity.accountUuid(), + identity.tenantUuid(), + versionUuid, + sourceReadScope, + sha256(sourceReadScope), + issuance.operationId(), + issuance.fence(), + sourcePayloadBytes, + bundlePayloadBytes, + outboxCheckpoints); + context + .dsl() + .execute( + "INSERT INTO account_game_logic_intake_source_read_sources " + + "(operation_id, source_key, source_evidence) " + + "VALUES (?, ?, ?), (?, ?, ?)", + operationId, + supplementaryKey, + supplementarySource, + operationId, + bmpKey, + bmpSource); + }); context .transaction() - .executeWithoutResult( - status -> { - context - .dsl() - .execute( - "INSERT INTO account_game_logic_intake_authorizations " - + "(operation_id, fence_id, actor_account_uuid, tenant_uuid, version_uuid, " - + "intake_request_id, source_digest, binding, issuance_operation_id, " - + "issuance_fence, source_payload, issuance_bundle, outbox_checkpoints) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - operationId, - fenceId, - identity.accountUuid(), - identity.tenantUuid(), - versionUuid, - requestId, - sha256(snapshot), - intakeBinding, - issuance.operationId(), - issuance.fence(), - sourcePayloadBytes, - bundlePayloadBytes, - outboxCheckpoints); - context - .dsl() - .execute( - "INSERT INTO account_game_logic_intake_sources " - + "(operation_id, source_key, source_evidence) VALUES (?, ?, ?), (?, ?, ?)", - operationId, - supplementaryKey, - supplementarySource, - operationId, - bmpKey, - bmpSource); - }); + .executeWithoutResult(status -> { + context + .dsl() + .execute( + "INSERT INTO account_game_logic_intake_authorizations " + + "(operation_id, fence_id, actor_account_uuid, tenant_uuid, version_uuid, " + + "intake_request_id, source_digest, binding, issuance_operation_id, " + + "issuance_fence, source_payload, issuance_bundle, outbox_checkpoints) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + fenceId, + identity.accountUuid(), + identity.tenantUuid(), + versionUuid, + requestId, + sha256(snapshot), + intakeBinding, + issuance.operationId(), + issuance.fence(), + sourcePayloadBytes, + bundlePayloadBytes, + outboxCheckpoints); + context + .dsl() + .execute( + "INSERT INTO account_game_logic_intake_sources " + + "(operation_id, source_key, source_evidence) VALUES (?, ?, ?), (?, ?, ?)", + operationId, + supplementaryKey, + supplementarySource, + operationId, + bmpKey, + bmpSource); + }); var orderedKeys = context @@ -852,39 +848,38 @@ private static void exerciseSelectedPublicationV2Settlement( sourceKey); context .transaction() - .executeWithoutResult( - status -> { - context - .dsl() - .execute( - "INSERT INTO account_selected_publication_authorizations " - + "(operation_id, fence_id, actor_account_uuid, tenant_uuid, " - + "publish_request_id, input_digest, binding, world_evidence, " - + "issuance_operation_id, issuance_fence, " - + "source_payload, issuance_bundle, " - + "outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - operationId, - fenceId, - identity.accountUuid(), - identity.tenantUuid(), - publishRequestId.toString(), - sha256(inputBytes), - accountBinding, - null, - issuance.operationId(), - issuance.fence(), - sourcePayloadBytes, - bundlePayloadBytes, - outboxCheckpoints); - context - .dsl() - .execute( - "INSERT INTO account_selected_publication_sources " - + "(operation_id, source_key, source_evidence) VALUES (?, ?, ?)", - operationId, - sourceKey, - source); - }); + .executeWithoutResult(status -> { + context + .dsl() + .execute( + "INSERT INTO account_selected_publication_authorizations " + + "(operation_id, fence_id, actor_account_uuid, tenant_uuid, " + + "publish_request_id, input_digest, binding, world_evidence, " + + "issuance_operation_id, issuance_fence, " + + "source_payload, issuance_bundle, " + + "outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + fenceId, + identity.accountUuid(), + identity.tenantUuid(), + publishRequestId.toString(), + sha256(inputBytes), + accountBinding, + null, + issuance.operationId(), + issuance.fence(), + sourcePayloadBytes, + bundlePayloadBytes, + outboxCheckpoints); + context + .dsl() + .execute( + "INSERT INTO account_selected_publication_sources " + + "(operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + operationId, + sourceKey, + source); + }); String requestDigest = sha256(selectedBytes).substring("sha256:".length()); String contentDigest = sha256(utf8("test-only content digest")).substring("sha256:".length()); @@ -1129,30 +1124,29 @@ private static void assertGameLogicSourceParticipationRejected( try { context .transaction() - .executeWithoutResult( - status -> - context - .dsl() - .execute( - "INSERT INTO account_game_logic_intake_source_read_reservations " - + "(operation_id, fence_id, intake_request_id, actor_account_uuid, " - + "tenant_uuid, version_uuid, scope_bytes, scope_digest, " - + "issuance_operation_id, issuance_fence, source_payload, " - + "issuance_bundle, outbox_checkpoints) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - operationId, - fenceId, - requestId, - identity.accountUuid(), - identity.tenantUuid(), - versionUuid, - scopeBytes, - sha256(scopeBytes), - issuance.operationId(), - issuance.fence(), - sourcePayloadBytes, - bundlePayloadBytes, - utf8("[]"))); + .executeWithoutResult(status -> + context + .dsl() + .execute( + "INSERT INTO account_game_logic_intake_source_read_reservations " + + "(operation_id, fence_id, intake_request_id, actor_account_uuid, " + + "tenant_uuid, version_uuid, scope_bytes, scope_digest, " + + "issuance_operation_id, issuance_fence, source_payload, " + + "issuance_bundle, outbox_checkpoints) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + fenceId, + requestId, + identity.accountUuid(), + identity.tenantUuid(), + versionUuid, + scopeBytes, + sha256(scopeBytes), + issuance.operationId(), + issuance.fence(), + sourcePayloadBytes, + bundlePayloadBytes, + utf8("[]"))); } catch (RuntimeException failure) { reservationFailure = failure; } @@ -1239,63 +1233,62 @@ private static ControlUiIssuance insertCommittedControlUiIssuance( context .transaction() - .executeWithoutResult( - status -> { - context - .dsl() - .execute( - "INSERT INTO account_control_ui_issuance_operations " - + "(request_id, operation_id, token_jti, account_uuid, tenant_uuid, " - + "caller_workload, caller_context_id, request_mac_key_id, request_digest, " - + "claims_payload, source_payload, bundle_payload, signer_receipt, " - + "issued_at_epoch_second, expires_at_epoch_second, " - + "registry_cleanup_deadline_epoch_millis, recovery_expires_at, status) " - + "VALUES (?, ?, ?, ?, ?, 'test-workload', ?, 'test-key', ?, ?, ?, ?, ?, ?, ?, " - + "?, ?::timestamptz, 'PREPARED')", - requestId, - operationId, - tokenJti, - identity.accountUuid(), - identity.tenantUuid(), - UUID.randomUUID(), - "a".repeat(64), - candidate, - sourcePayload, - bundlePayload, - candidate, - issuedAt, - expiresAt, - cleanupDeadlineEpochMillis, - recoveryExpiresAt); - context - .dsl() - .execute( - "UPDATE account_control_ui_issuance_operations " - + "SET status = 'CANDIDATE', token_hash = ?, pending_registry = ?, " - + "active_registry = ? WHERE operation_id = ?", - tokenHash, - candidate, - candidate, - operationId); - context - .dsl() - .execute( - "INSERT INTO account_control_ui_response_envelopes " - + "(operation_id, encrypted_response, owner_binding, recovery_expires_at) " - + "VALUES (?, ?, ?, ?::timestamptz)", - operationId, - response, - ownerBinding, - recoveryExpiresAt); - context - .dsl() - .execute( - "UPDATE account_control_ui_issuance_operations SET status = 'COMMITTED', " - + "pending_receipt = ?, committed_at = CURRENT_TIMESTAMP " - + "WHERE operation_id = ?", - response, - operationId); - }); + .executeWithoutResult(status -> { + context + .dsl() + .execute( + "INSERT INTO account_control_ui_issuance_operations " + + "(request_id, operation_id, token_jti, account_uuid, tenant_uuid, " + + "caller_workload, caller_context_id, request_mac_key_id, request_digest, " + + "claims_payload, source_payload, bundle_payload, signer_receipt, " + + "issued_at_epoch_second, expires_at_epoch_second, " + + "registry_cleanup_deadline_epoch_millis, recovery_expires_at, status) " + + "VALUES (?, ?, ?, ?, ?, 'test-workload', ?, 'test-key', ?, ?, ?, ?, ?, ?, ?, " + + "?, ?::timestamptz, 'PREPARED')", + requestId, + operationId, + tokenJti, + identity.accountUuid(), + identity.tenantUuid(), + UUID.randomUUID(), + "a".repeat(64), + candidate, + sourcePayload, + bundlePayload, + candidate, + issuedAt, + expiresAt, + cleanupDeadlineEpochMillis, + recoveryExpiresAt); + context + .dsl() + .execute( + "UPDATE account_control_ui_issuance_operations " + + "SET status = 'CANDIDATE', token_hash = ?, pending_registry = ?, " + + "active_registry = ? WHERE operation_id = ?", + tokenHash, + candidate, + candidate, + operationId); + context + .dsl() + .execute( + "INSERT INTO account_control_ui_response_envelopes " + + "(operation_id, encrypted_response, owner_binding, recovery_expires_at) " + + "VALUES (?, ?, ?, ?::timestamptz)", + operationId, + response, + ownerBinding, + recoveryExpiresAt); + context + .dsl() + .execute( + "UPDATE account_control_ui_issuance_operations SET status = 'COMMITTED', " + + "pending_receipt = ?, committed_at = CURRENT_TIMESTAMP " + + "WHERE operation_id = ?", + response, + operationId); + }); return new ControlUiIssuance(operationId, 1L); } @@ -1343,39 +1336,38 @@ private static void exerciseSelectedPublication( try { context .transaction() - .executeWithoutResult( - status -> { - context - .dsl() - .execute( - "INSERT INTO account_selected_publication_authorizations " - + "(operation_id, fence_id, actor_account_uuid, tenant_uuid, " - + "publish_request_id, input_digest, binding, world_evidence, " - + "issuance_operation_id, issuance_fence, " - + "source_payload, issuance_bundle, " - + "outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - operationId, - fenceId, - identity.accountUuid(), - identity.tenantUuid(), - publishRequestId, - sha256(input), - binding, - new byte[] {1}, - issuance.operationId(), - issuance.fence(), - sourcePayloadBytes, - bundlePayloadBytes, - outboxCheckpoints); - context - .dsl() - .execute( - "INSERT INTO account_selected_publication_sources " - + "(operation_id, source_key, source_evidence) VALUES (?, ?, ?)", - operationId, - sourceKey, - evidenceCopy); - }); + .executeWithoutResult(status -> { + context + .dsl() + .execute( + "INSERT INTO account_selected_publication_authorizations " + + "(operation_id, fence_id, actor_account_uuid, tenant_uuid, " + + "publish_request_id, input_digest, binding, world_evidence, " + + "issuance_operation_id, issuance_fence, " + + "source_payload, issuance_bundle, " + + "outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + fenceId, + identity.accountUuid(), + identity.tenantUuid(), + publishRequestId, + sha256(input), + binding, + new byte[] {1}, + issuance.operationId(), + issuance.fence(), + sourcePayloadBytes, + bundlePayloadBytes, + outboxCheckpoints); + context + .dsl() + .execute( + "INSERT INTO account_selected_publication_sources " + + "(operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + operationId, + sourceKey, + evidenceCopy); + }); assertThat(accepted) .as("selected publication should satisfy its deferred completeness guard") .isTrue(); @@ -1500,33 +1492,31 @@ void draftFenceInspectionDoesNotLockOperationRowsAndOwnerWriteKeepsSourceLocks() context .transaction() - .executeWithoutResult( - status -> { - assertThat(fences.read(binding).ordering()) - .isEqualTo(DraftAuthorizationFenceRepository.Ordering.RESERVED); - assertThat(fences.readSettlement(binding)) - .isEqualTo(DraftAuthorizationFenceRepository.Settlement.PENDING); - assertThat(fences.readOriginalBinding(binding.operationId())).contains(binding); - assertThat(fences.readOwnerResult(binding, Owner.GAME_DESIGN)).isEmpty(); - assertThat(fences.readUnresolvedOperations(null, 10)) - .extracting(DraftAuthorizationFenceRepository.UnresolvedOperation::binding) - .containsExactly(binding); - assertThatThrownBy(() -> fences.read(changedBinding)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("changed immutable Draft operation"); - - // This separate connection can take the operation row while every inspection above - // remains in its caller transaction; no timing or thread scheduling is involved. - assertThat(lockFenceNowait(context, binding.operationId())) - .isEqualTo(binding.operationId()); - }); + .executeWithoutResult(status -> { + assertThat(fences.read(binding).ordering()) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.RESERVED); + assertThat(fences.readSettlement(binding)) + .isEqualTo(DraftAuthorizationFenceRepository.Settlement.PENDING); + assertThat(fences.readOriginalBinding(binding.operationId())).contains(binding); + assertThat(fences.readOwnerResult(binding, Owner.GAME_DESIGN)).isEmpty(); + assertThat(fences.readUnresolvedOperations(null, 10)) + .extracting(DraftAuthorizationFenceRepository.UnresolvedOperation::binding) + .containsExactly(binding); + assertThatThrownBy(() -> fences.read(changedBinding)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed immutable Draft operation"); + + // This separate connection can take the operation row while every inspection above + // remains in its caller transaction; no timing or thread scheduling is involved. + assertThat(lockFenceNowait(context, binding.operationId())) + .isEqualTo(binding.operationId()); + }); context .transaction() - .executeWithoutResult( - status -> - assertThat(fences.claimCommitOrder(binding).ordering()) - .isEqualTo(DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER)); + .executeWithoutResult(status -> + assertThat(fences.claimCommitOrder(binding).ordering()) + .isEqualTo(DraftAuthorizationFenceRepository.Ordering.COMMIT_ORDER)); OwnerReadback ownerReadback = new OwnerReadback( @@ -1540,17 +1530,16 @@ void draftFenceInspectionDoesNotLockOperationRowsAndOwnerWriteKeepsSourceLocks() utf8("test-only exact owner result")); context .transaction() - .executeWithoutResult( - status -> { - fences.recordOwnerReadback(binding, ownerReadback); - assertThat(fences.readOwnerResult(binding, Owner.GAME_DESIGN)) - .hasValueSatisfying( - result -> assertThat(result.outcome()).isEqualTo(Outcome.COMMITTED)); - assertThatThrownBy(() -> lockSourceNowait(context, source.key())) - .isInstanceOf(DataAccessException.class); - assertThatThrownBy(() -> lockFenceNowait(context, binding.operationId())) - .isInstanceOf(DataAccessException.class); - }); + .executeWithoutResult(status -> { + fences.recordOwnerReadback(binding, ownerReadback); + assertThat(fences.readOwnerResult(binding, Owner.GAME_DESIGN)) + .hasValueSatisfying( + result -> assertThat(result.outcome()).isEqualTo(Outcome.COMMITTED)); + assertThatThrownBy(() -> lockSourceNowait(context, source.key())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy(() -> lockFenceNowait(context, binding.operationId())) + .isInstanceOf(DataAccessException.class); + }); } @Test @@ -1584,14 +1573,12 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { byte[][] persistedCatalogEvidence = new byte[1][]; context .transaction() - .executeWithoutResult( - status -> { - hostedTerms.ensureScope(hostedScopeId); - hostedTerms.insertCandidate(candidate); - persistedCatalogEvidence[0] = - HostedTermsEncoding.catalog( - hostedTerms.readCatalog(hostedScopeId, termsVersionId)); - }); + .executeWithoutResult(status -> { + hostedTerms.ensureScope(hostedScopeId); + hostedTerms.insertCandidate(candidate); + persistedCatalogEvidence[0] = + HostedTermsEncoding.catalog(hostedTerms.readCatalog(hostedScopeId, termsVersionId)); + }); SourceEvidence exactSource = new SourceEvidence( SourceKind.HOSTED_TERMS, @@ -1638,56 +1625,53 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { sha256(handoffBinding)); byte[] directTerminalPayload = "direct terminal fixture".getBytes(StandardCharsets.UTF_8); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "INSERT INTO account_hosted_terms_disclosure_handoffs " - + "(handoff_id, request_id, kind, source_key, predecessor_digest, " - + "candidate_digest, effective_at, binding, binding_digest, status, " - + "dispatch_attempts, result_outcome, result_payload, result_digest, " - + "result_recorded_at) VALUES (?, ?, 'CATALOG', ?, ?, ?, ?::timestamptz, ?, ?, " - + "'DISCLOSED', 1, 'DISCLOSED', ?, ?, CURRENT_TIMESTAMP)", - UUID.randomUUID(), - UUID.randomUUID(), - exactSource.key(), - sha256("direct predecessor".getBytes(StandardCharsets.UTF_8)), - HostedTermsEncoding.digest(document), - effectiveAt, - handoffBinding, - sha256(handoffBinding), - directTerminalPayload, - sha256(directTerminalPayload))) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_disclosure_handoffs " + + "(handoff_id, request_id, kind, source_key, predecessor_digest, " + + "candidate_digest, effective_at, binding, binding_digest, status, " + + "dispatch_attempts, result_outcome, result_payload, result_digest, " + + "result_recorded_at) VALUES (?, ?, 'CATALOG', ?, ?, ?, ?::timestamptz, ?, ?, " + + "'DISCLOSED', 1, 'DISCLOSED', ?, ?, CURRENT_TIMESTAMP)", + UUID.randomUUID(), + UUID.randomUUID(), + exactSource.key(), + sha256("direct predecessor".getBytes(StandardCharsets.UTF_8)), + HostedTermsEncoding.digest(document), + effectiveAt, + handoffBinding, + sha256(handoffBinding), + directTerminalPayload, + sha256(directTerminalPayload))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "INSERT INTO account_hosted_terms_disclosure_handoffs " - + "(handoff_id, request_id, kind, source_key, predecessor_digest, " - + "candidate_digest, effective_at, binding, binding_digest, status, " - + "dispatch_attempts) VALUES (?, ?, 'CATALOG', ?, ?, ?, ?::timestamptz, ?, ?, " - + "'DISPATCH_AUTHORIZED', 1)", - UUID.randomUUID(), - UUID.randomUUID(), - exactSource.key(), - sha256("direct authorization predecessor".getBytes(StandardCharsets.UTF_8)), - HostedTermsEncoding.digest(document), - effectiveAt, - handoffBinding, - sha256(handoffBinding))) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_disclosure_handoffs " + + "(handoff_id, request_id, kind, source_key, predecessor_digest, " + + "candidate_digest, effective_at, binding, binding_digest, status, " + + "dispatch_attempts) VALUES (?, ?, 'CATALOG', ?, ?, ?, ?::timestamptz, ?, ?, " + + "'DISPATCH_AUTHORIZED', 1)", + UUID.randomUUID(), + UUID.randomUUID(), + exactSource.key(), + sha256("direct authorization predecessor".getBytes(StandardCharsets.UTF_8)), + HostedTermsEncoding.digest(document), + effectiveAt, + handoffBinding, + sha256(handoffBinding))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "UPDATE account_hosted_terms_disclosure_handoffs " - + "SET status = 'DISPATCH_AUTHORIZED', dispatch_attempts = 1 " - + "WHERE handoff_id = ?", - handoffId)) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs " + + "SET status = 'DISPATCH_AUTHORIZED', dispatch_attempts = 1 " + + "WHERE handoff_id = ?", + handoffId)) .isInstanceOf(DataAccessException.class); assertThat( context @@ -1726,15 +1710,14 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { exactSource.key(), exactSourceEvidence, sha256(exactSourceEvidence)); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "UPDATE account_hosted_terms_disclosure_handoffs " - + "SET status = 'DISPATCH_AUTHORIZED', dispatch_attempts = 1 " - + "WHERE handoff_id = ?", - handoffId)) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs " + + "SET status = 'DISPATCH_AUTHORIZED', dispatch_attempts = 1 " + + "WHERE handoff_id = ?", + handoffId)) .isInstanceOf(DataAccessException.class); assertThat( context @@ -1794,13 +1777,12 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { sha256(exactSourceEvidence)); String oversizedSourceKey = "é".repeat(1025); assertThat(oversizedSourceKey.getBytes(StandardCharsets.UTF_8)).hasSize(2050); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", - oversizedSourceKey)) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?)", + oversizedSourceKey)) .isInstanceOf(DataAccessException.class); var persisted = @@ -1829,53 +1811,48 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { assertThat(persisted.get("source_evidence_digest", String.class)) .isEqualTo(sha256(exactSourceEvidence)); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "UPDATE account_hosted_terms_disclosure_sources " - + "SET source_evidence = ? WHERE handoff_id = ? AND source_key = ?", - new byte[] {1}, - handoffId, - exactSource.key())) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_sources " + + "SET source_evidence = ? WHERE handoff_id = ? AND source_key = ?", + new byte[] {1}, + handoffId, + exactSource.key())) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "DELETE FROM account_hosted_terms_disclosure_sources " - + "WHERE handoff_id = ? AND source_key = ?", - handoffId, - exactSource.key())) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "DELETE FROM account_hosted_terms_disclosure_sources " + + "WHERE handoff_id = ? AND source_key = ?", + handoffId, + exactSource.key())) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "UPDATE account_hosted_terms_disclosure_handoffs SET status = 'AMBIGUOUS', " - + "dispatch_attempts = 1 WHERE handoff_id = ?", - handoffId)) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs SET status = 'AMBIGUOUS', " + + "dispatch_attempts = 1 WHERE handoff_id = ?", + handoffId)) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "UPDATE account_hosted_terms_disclosure_handoffs " - + "SET binding = ? WHERE handoff_id = ?", - new byte[] {2}, - handoffId)) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs " + + "SET binding = ? WHERE handoff_id = ?", + new byte[] {2}, + handoffId)) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "DELETE FROM account_hosted_terms_disclosure_handoffs WHERE handoff_id = ?", - handoffId)) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "DELETE FROM account_hosted_terms_disclosure_handoffs WHERE handoff_id = ?", + handoffId)) .isInstanceOf(DataAccessException.class); assertThat( context @@ -1935,9 +1912,8 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { context.transaction().executeWithoutResult(status -> fences.reserve(mismatchedCapture)); DraftAuthorizationFenceBinding exactCapture = draftBinding(exactSource); - assertThatThrownBy( - () -> - context.transaction().executeWithoutResult(status -> fences.reserve(exactCapture))) + assertThatThrownBy(() -> + context.transaction().executeWithoutResult(status -> fences.reserve(exactCapture))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Exact hosted terms source has authorized disclosure"); assertThat( @@ -1949,9 +1925,8 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { .fetchOne(0, Long.class)) .isZero(); - assertThatThrownBy( - () -> - context.dsl().execute("TRUNCATE account_hosted_terms_disclosure_handoffs CASCADE")) + assertThatThrownBy(() -> + context.dsl().execute("TRUNCATE account_hosted_terms_disclosure_handoffs CASCADE")) .isInstanceOf(DataAccessException.class); assertThatThrownBy( () -> context.dsl().execute("TRUNCATE account_hosted_terms_disclosure_sources")) @@ -1992,17 +1967,16 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { "test-only terminal disclosure result".getBytes(StandardCharsets.UTF_8); byte[] mismatchedDigestPayload = "different test-only terminal disclosure result".getBytes(StandardCharsets.UTF_8); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "UPDATE account_hosted_terms_disclosure_handoffs SET status = 'DISCLOSED', " - + "result_outcome = 'DISCLOSED', result_payload = ?, result_digest = ?, " - + "result_recorded_at = CURRENT_TIMESTAMP WHERE handoff_id = ?", - disclosedPayload, - sha256(mismatchedDigestPayload), - handoffId)) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs SET status = 'DISCLOSED', " + + "result_outcome = 'DISCLOSED', result_payload = ?, result_digest = ?, " + + "result_recorded_at = CURRENT_TIMESTAMP WHERE handoff_id = ?", + disclosedPayload, + sha256(mismatchedDigestPayload), + handoffId)) .isInstanceOf(DataAccessException.class); assertThat( context @@ -2031,11 +2005,10 @@ void hostedTermsDisclosureHandoffPersistsExactSourceAndFencesOnlyThatSource() { + "WHERE handoff_id = ?", handoffId) .fetchOne()) - .satisfies( - row -> { - assertThat(row.get("status", String.class)).isEqualTo("DISCLOSED"); - assertThat(row.get("dispatch_attempts", Integer.class)).isEqualTo(2); - }); + .satisfies(row -> { + assertThat(row.get("status", String.class)).isEqualTo("DISCLOSED"); + assertThat(row.get("dispatch_attempts", Integer.class)).isEqualTo(2); + }); } @Test @@ -2137,25 +2110,23 @@ void v73RetainedAccountStaysUnenrolledWhileFreshRepositoryAccountGetsExactBirthS fresh.getAccountUuid())) .isEqualTo(2L); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "UPDATE account_global_role_sources " - + "SET global_roles = ARRAY['moderator']::TEXT[] " - + "WHERE account_uuid = ?", - fresh.getAccountUuid())) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "UPDATE account_global_role_sources " + + "SET global_roles = ARRAY['moderator']::TEXT[] " + + "WHERE account_uuid = ?", + fresh.getAccountUuid())) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "UPDATE account_platform_restriction_births " - + "SET payload_digest = repeat('0', 64) " - + "WHERE account_uuid = ? AND category = 'account_security_lock'", - fresh.getAccountUuid())) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "UPDATE account_platform_restriction_births " + + "SET payload_digest = repeat('0', 64) " + + "WHERE account_uuid = ? AND category = 'account_security_lock'", + fresh.getAccountUuid())) .isInstanceOf(DataAccessException.class); } @@ -2212,34 +2183,31 @@ void malformedDraftOwnerEvidenceCannotSettleOrRewriteItsSourceChange() { changeId, sourceKey); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "INSERT INTO account_draft_authorization_owner_readbacks " - + "(operation_id, owner, outcome, readback) " - + "VALUES (?, 'GAME_DESIGN', 'COMMITTED', ?)", - operationId, - new byte[] {1})) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "INSERT INTO account_draft_authorization_owner_readbacks " + + "(operation_id, owner, outcome, readback) " + + "VALUES (?, 'GAME_DESIGN', 'COMMITTED', ?)", + operationId, + new byte[] {1})) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "UPDATE account_draft_authorization_source_changes " - + "SET status = 'SOURCE_COMMITTED', committed_at = CURRENT_TIMESTAMP " - + "WHERE change_id = ?", - changeId)) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "UPDATE account_draft_authorization_source_changes " + + "SET status = 'SOURCE_COMMITTED', committed_at = CURRENT_TIMESTAMP " + + "WHERE change_id = ?", + changeId)) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "DELETE FROM account_draft_authorization_source_changes WHERE change_id = ?", - changeId)) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "DELETE FROM account_draft_authorization_source_changes WHERE change_id = ?", + changeId)) .isInstanceOf(DataAccessException.class); assertThat( context @@ -2279,41 +2247,38 @@ void nonoperativeTermsAndUnverifiedCreatorSourcesStayImmutableAndRejectContradic creatorPayload, sha256(creatorPayload)); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "UPDATE account_individual_creator_party_sources " - + "SET source_version = source_version WHERE creator_party_id = ?", - creatorPartyId)) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "UPDATE account_individual_creator_party_sources " + + "SET source_version = source_version WHERE creator_party_id = ?", + creatorPartyId)) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "DELETE FROM account_individual_creator_party_sources " - + "WHERE creator_party_id = ?", - creatorPartyId)) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "DELETE FROM account_individual_creator_party_sources " + + "WHERE creator_party_id = ?", + creatorPartyId)) .isInstanceOf(DataAccessException.class); UUID missingTenantSource = UUID.randomUUID(); byte[] creatorHistory = "no canonical tenant owner source".getBytes(StandardCharsets.UTF_8); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "INSERT INTO account_tenant_creator_party_history " - + "(history_id, tenant_uuid, origin, creator_party_id, source_version, " - + "evidence_payload, evidence_digest) " - + "VALUES (?, ?, 'FRESH_INITIAL', ?, 1, ?, ?)", - UUID.randomUUID(), - missingTenantSource, - creatorPartyId, - creatorHistory, - sha256(creatorHistory))) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "INSERT INTO account_tenant_creator_party_history " + + "(history_id, tenant_uuid, origin, creator_party_id, source_version, " + + "evidence_payload, evidence_digest) " + + "VALUES (?, ?, 'FRESH_INITIAL', ?, 1, ?, ?)", + UUID.randomUUID(), + missingTenantSource, + creatorPartyId, + creatorHistory, + sha256(creatorHistory))) .isInstanceOf(DataAccessException.class); assertThat( context @@ -2341,18 +2306,14 @@ void nonoperativeTermsAndUnverifiedCreatorSourcesStayImmutableAndRejectContradic retainedHistoryPayload, sha256(retainedHistoryPayload)); - assertThatThrownBy( - () -> - context.dsl().execute("TRUNCATE account_individual_creator_party_sources CASCADE")) + assertThatThrownBy(() -> + context.dsl().execute("TRUNCATE account_individual_creator_party_sources CASCADE")) .isInstanceOf(DataAccessException.class); assertThatThrownBy( () -> context.dsl().execute("TRUNCATE account_tenant_creator_party_history CASCADE")) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - context - .dsl() - .execute("TRUNCATE account_fresh_creator_party_association_operations")) + assertThatThrownBy(() -> + context.dsl().execute("TRUNCATE account_fresh_creator_party_association_operations")) .isInstanceOf(DataAccessException.class); assertThat( context @@ -2409,22 +2370,20 @@ void nonoperativeTermsAndUnverifiedCreatorSourcesStayImmutableAndRejectContradic versionPayload, sha256(versionPayload)); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "UPDATE account_hosted_terms_catalog_versions " - + "SET operator_legal_identity = 'changed fixture' WHERE version_id = ?", - termsVersionId)) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "UPDATE account_hosted_terms_catalog_versions " + + "SET operator_legal_identity = 'changed fixture' WHERE version_id = ?", + termsVersionId)) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "DELETE FROM account_hosted_terms_catalog_versions WHERE version_id = ?", - termsVersionId)) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "DELETE FROM account_hosted_terms_catalog_versions WHERE version_id = ?", + termsVersionId)) .isInstanceOf(DataAccessException.class); assertThat( context @@ -2443,31 +2402,30 @@ void nonoperativeTermsAndUnverifiedCreatorSourcesStayImmutableAndRejectContradic .isZero(); byte[] affirmativeAction = "{}".getBytes(StandardCharsets.UTF_8); - assertThatThrownBy( - () -> - context - .dsl() - .execute( - "INSERT INTO account_individual_hosted_terms_acceptances " - + "(evidence_id, action_request_id, creator_party_id, account_uuid, " - + "hosted_scope_id, terms_version_id, document_digest, " - + "operator_legal_identity, operator_identity_version, source_version, " - + "material_generation, individual_party_source, " - + "individual_party_source_digest, " - + "affirmative_action_evidence, affirmative_action_digest, accepted_at) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, 'TEST FIXTURE ONLY', 1, 1, 1, ?, ?, ?, ?, " - + "CURRENT_TIMESTAMP)", - UUID.randomUUID(), - UUID.randomUUID(), - creatorPartyId, - identity.accountUuid(), - hostedScopeId, - termsVersionId, - sha256(nonoperativeDocument), - creatorPayload, - sha256(creatorPayload), - affirmativeAction, - sha256(affirmativeAction))) + assertThatThrownBy(() -> + context + .dsl() + .execute( + "INSERT INTO account_individual_hosted_terms_acceptances " + + "(evidence_id, action_request_id, creator_party_id, account_uuid, " + + "hosted_scope_id, terms_version_id, document_digest, " + + "operator_legal_identity, operator_identity_version, source_version, " + + "material_generation, individual_party_source, " + + "individual_party_source_digest, " + + "affirmative_action_evidence, affirmative_action_digest, accepted_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, 'TEST FIXTURE ONLY', 1, 1, 1, ?, ?, ?, ?, " + + "CURRENT_TIMESTAMP)", + UUID.randomUUID(), + UUID.randomUUID(), + creatorPartyId, + identity.accountUuid(), + hostedScopeId, + termsVersionId, + sha256(nonoperativeDocument), + creatorPayload, + sha256(creatorPayload), + affirmativeAction, + sha256(affirmativeAction))) .isInstanceOf(DataAccessException.class); assertThat( context @@ -2528,158 +2486,157 @@ void syntheticHostedTermsAndEnvironmentEvidenceSurvivesTruncateAttempts() { // runtime activation is involved. context .transaction() - .executeWithoutResult( - status -> { - context - .dsl() - .execute( - "INSERT INTO account_hosted_terms_scopes (hosted_scope_id) VALUES (?)", - hostedScopeId); - context - .dsl() - .execute( - "INSERT INTO account_hosted_terms_catalog_versions " - + "(version_id, hosted_scope_id, predecessor_version_id, " - + "operator_legal_identity, operator_identity_version, document_bytes, " - + "document_digest, source_version, material_generation, materiality, " - + "publication_evidence_reference, publication_evidence_version, " - + "notice_evidence_reference, notice_evidence_version, effective_at, " - + "version_payload, version_digest) " - + "VALUES (?, ?, NULL, 'TEST FIXTURE ONLY', 1, ?, ?, 1, 1, 'INITIAL', " - + "'test-only/publication', 1, 'test-only/notice', 1, ?::timestamptz, ?, ?)", - termsVersionId, - hostedScopeId, - document, - sha256(document), - effectiveAt, - versionPayload, - sha256(versionPayload)); - context - .dsl() - .execute( - "INSERT INTO account_hosted_terms_publication_operations " - + "(request_id, hosted_scope_id, request_payload, request_digest, status) " - + "VALUES (?, ?, ?, ?, 'RECEIVED')", - termsPublicationRequestId, - hostedScopeId, - termsPublicationPayload, - sha256(termsPublicationPayload)); - context - .dsl() - .execute( - "UPDATE account_hosted_terms_publication_operations " - + "SET status = 'SCHEDULED', candidate_version_id = ? " - + "WHERE request_id = ?", - termsVersionId, - termsPublicationRequestId); - context - .dsl() - .execute( - "UPDATE account_hosted_terms_scopes SET current_version_id = ?, " - + "current_source_version = 1, current_material_generation = 1 " - + "WHERE hosted_scope_id = ?", - termsVersionId, - hostedScopeId); - context - .dsl() - .execute( - "UPDATE account_hosted_terms_publication_operations SET status = 'COMMITTED', " - + "result_payload = ?, result_digest = ?, committed_at = CURRENT_TIMESTAMP " - + "WHERE request_id = ?", - versionPayload, - sha256(versionPayload), - termsPublicationRequestId); - context - .dsl() - .execute( - "INSERT INTO account_individual_creator_party_sources " - + "(creator_party_id, account_uuid, verification_status, identity_version, " - + "policy_reference, policy_version, verification_evidence_reference, " - + "verification_evidence_version, source_version, source_payload, source_digest) " - + "VALUES (?, ?, 'VERIFIED', 1, 'test-only/policy', 1, " - + "'test-only/verification', 1, 1, ?, ?)", - creatorPartyId, - identity.accountUuid(), - creatorSource, - sha256(creatorSource)); - context - .dsl() - .execute( - "INSERT INTO account_individual_hosted_terms_acceptances " - + "(evidence_id, action_request_id, creator_party_id, account_uuid, " - + "hosted_scope_id, terms_version_id, document_digest, " - + "operator_legal_identity, operator_identity_version, source_version, " - + "material_generation, individual_party_source, " - + "individual_party_source_digest, affirmative_action_evidence, " - + "affirmative_action_digest, accepted_at) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, 'TEST FIXTURE ONLY', 1, 1, 1, ?, ?, ?, ?, " - + "CURRENT_TIMESTAMP)", - acceptanceEvidenceId, - acceptanceActionRequestId, - creatorPartyId, - identity.accountUuid(), - hostedScopeId, - termsVersionId, - sha256(document), - creatorSource, - sha256(creatorSource), - affirmativeAction, - sha256(affirmativeAction)); - context - .dsl() - .execute( - "INSERT INTO account_hosted_terms_environment_binding_heads " - + "(environment_boundary) VALUES (?)", - environmentBoundary); - context - .dsl() - .execute( - "INSERT INTO account_hosted_terms_environment_binding_publications " - + "(request_id, environment_boundary, request_payload, request_digest, status) " - + "VALUES (?, ?, ?, ?, 'RECEIVED')", - bindingPublicationRequestId, - environmentBoundary, - bindingPublicationPayload, - sha256(bindingPublicationPayload)); - context - .dsl() - .execute( - "INSERT INTO account_hosted_terms_environment_bindings " - + "(binding_id, publication_request_id, environment_boundary, hosted_scope_id, " - + "operator_legal_identity, operator_identity_version, catalog_version_id, " - + "catalog_source_version, authenticated_publisher_identity, " - + "publication_event_identity, publication_evidence_digest, " - + "predecessor_binding_id, predecessor_source_version, source_version, " - + "binding_payload, binding_digest) " - + "VALUES (?, ?, ?, ?, 'TEST FIXTURE ONLY', 1, ?, 1, 'test-only/publisher', " - + "'test-only/event', ?, NULL, NULL, 1, ?, ?)", - bindingId, - bindingPublicationRequestId, - environmentBoundary, - hostedScopeId, - termsVersionId, - sha256(bindingPublicationPayload), - bindingPayload, - sha256(bindingPayload)); - context - .dsl() - .execute( - "UPDATE account_hosted_terms_environment_binding_publications " - + "SET status = 'COMMITTED', candidate_binding_id = ?, result_payload = ?, " - + "result_digest = ?, committed_at = CURRENT_TIMESTAMP WHERE request_id = ?", - bindingId, - bindingPayload, - sha256(bindingPayload), - bindingPublicationRequestId); - context - .dsl() - .execute( - "UPDATE account_hosted_terms_environment_binding_heads " - + "SET current_binding_id = ?, current_source_version = 1 " - + "WHERE environment_boundary = ?", - bindingId, - environmentBoundary); - }); + .executeWithoutResult(status -> { + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_scopes (hosted_scope_id) VALUES (?)", + hostedScopeId); + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_catalog_versions " + + "(version_id, hosted_scope_id, predecessor_version_id, " + + "operator_legal_identity, operator_identity_version, document_bytes, " + + "document_digest, source_version, material_generation, materiality, " + + "publication_evidence_reference, publication_evidence_version, " + + "notice_evidence_reference, notice_evidence_version, effective_at, " + + "version_payload, version_digest) " + + "VALUES (?, ?, NULL, 'TEST FIXTURE ONLY', 1, ?, ?, 1, 1, 'INITIAL', " + + "'test-only/publication', 1, 'test-only/notice', 1, ?::timestamptz, ?, ?)", + termsVersionId, + hostedScopeId, + document, + sha256(document), + effectiveAt, + versionPayload, + sha256(versionPayload)); + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_publication_operations " + + "(request_id, hosted_scope_id, request_payload, request_digest, status) " + + "VALUES (?, ?, ?, ?, 'RECEIVED')", + termsPublicationRequestId, + hostedScopeId, + termsPublicationPayload, + sha256(termsPublicationPayload)); + context + .dsl() + .execute( + "UPDATE account_hosted_terms_publication_operations " + + "SET status = 'SCHEDULED', candidate_version_id = ? " + + "WHERE request_id = ?", + termsVersionId, + termsPublicationRequestId); + context + .dsl() + .execute( + "UPDATE account_hosted_terms_scopes SET current_version_id = ?, " + + "current_source_version = 1, current_material_generation = 1 " + + "WHERE hosted_scope_id = ?", + termsVersionId, + hostedScopeId); + context + .dsl() + .execute( + "UPDATE account_hosted_terms_publication_operations SET status = 'COMMITTED', " + + "result_payload = ?, result_digest = ?, committed_at = CURRENT_TIMESTAMP " + + "WHERE request_id = ?", + versionPayload, + sha256(versionPayload), + termsPublicationRequestId); + context + .dsl() + .execute( + "INSERT INTO account_individual_creator_party_sources " + + "(creator_party_id, account_uuid, verification_status, identity_version, " + + "policy_reference, policy_version, verification_evidence_reference, " + + "verification_evidence_version, source_version, source_payload, source_digest) " + + "VALUES (?, ?, 'VERIFIED', 1, 'test-only/policy', 1, " + + "'test-only/verification', 1, 1, ?, ?)", + creatorPartyId, + identity.accountUuid(), + creatorSource, + sha256(creatorSource)); + context + .dsl() + .execute( + "INSERT INTO account_individual_hosted_terms_acceptances " + + "(evidence_id, action_request_id, creator_party_id, account_uuid, " + + "hosted_scope_id, terms_version_id, document_digest, " + + "operator_legal_identity, operator_identity_version, source_version, " + + "material_generation, individual_party_source, " + + "individual_party_source_digest, affirmative_action_evidence, " + + "affirmative_action_digest, accepted_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, 'TEST FIXTURE ONLY', 1, 1, 1, ?, ?, ?, ?, " + + "CURRENT_TIMESTAMP)", + acceptanceEvidenceId, + acceptanceActionRequestId, + creatorPartyId, + identity.accountUuid(), + hostedScopeId, + termsVersionId, + sha256(document), + creatorSource, + sha256(creatorSource), + affirmativeAction, + sha256(affirmativeAction)); + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_environment_binding_heads " + + "(environment_boundary) VALUES (?)", + environmentBoundary); + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_environment_binding_publications " + + "(request_id, environment_boundary, request_payload, request_digest, status) " + + "VALUES (?, ?, ?, ?, 'RECEIVED')", + bindingPublicationRequestId, + environmentBoundary, + bindingPublicationPayload, + sha256(bindingPublicationPayload)); + context + .dsl() + .execute( + "INSERT INTO account_hosted_terms_environment_bindings " + + "(binding_id, publication_request_id, environment_boundary, hosted_scope_id, " + + "operator_legal_identity, operator_identity_version, catalog_version_id, " + + "catalog_source_version, authenticated_publisher_identity, " + + "publication_event_identity, publication_evidence_digest, " + + "predecessor_binding_id, predecessor_source_version, source_version, " + + "binding_payload, binding_digest) " + + "VALUES (?, ?, ?, ?, 'TEST FIXTURE ONLY', 1, ?, 1, 'test-only/publisher', " + + "'test-only/event', ?, NULL, NULL, 1, ?, ?)", + bindingId, + bindingPublicationRequestId, + environmentBoundary, + hostedScopeId, + termsVersionId, + sha256(bindingPublicationPayload), + bindingPayload, + sha256(bindingPayload)); + context + .dsl() + .execute( + "UPDATE account_hosted_terms_environment_binding_publications " + + "SET status = 'COMMITTED', candidate_binding_id = ?, result_payload = ?, " + + "result_digest = ?, committed_at = CURRENT_TIMESTAMP WHERE request_id = ?", + bindingId, + bindingPayload, + sha256(bindingPayload), + bindingPublicationRequestId); + context + .dsl() + .execute( + "UPDATE account_hosted_terms_environment_binding_heads " + + "SET current_binding_id = ?, current_source_version = 1 " + + "WHERE environment_boundary = ?", + bindingId, + environmentBoundary); + }); assertTruncateRejected(context, "account_hosted_terms_catalog_versions"); assertTruncateRejected(context, "account_hosted_terms_scopes"); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java index b73c907fc6..a057017bec 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java @@ -107,18 +107,16 @@ void settlementLocksCanonicalSourceKeysBeforeProtectionRowAccess() throws Except .configuration() .setAppending( new DefaultExecuteListenerProvider( - ExecuteListener.onExecuteStart( - context -> { - String sql = context.sql(); - var query = context.query(); - if (sql == null || query == null || !sql.contains("FOR UPDATE NOWAIT")) - return; - if (sql.contains("account_draft_authorization_source_locks")) { - sourceLocks.add((String) query.getBindValues().getFirst()); - } else if (sql.contains("account_start_session_activation_protections")) { - protectionLocks.add(query.getBindValues().getFirst()); - } - }))); + ExecuteListener.onExecuteStart(context -> { + String sql = context.sql(); + var query = context.query(); + if (sql == null || query == null || !sql.contains("FOR UPDATE NOWAIT")) return; + if (sql.contains("account_draft_authorization_source_locks")) { + sourceLocks.add((String) query.getBindValues().getFirst()); + } else if (sql.contains("account_start_session_activation_protections")) { + protectionLocks.add(query.getBindValues().getFirst()); + } + }))); for (var contended : List.of(first, last)) { sourceLocks.clear(); protectionLocks.clear(); @@ -132,19 +130,17 @@ void settlementLocksCanonicalSourceKeysBeforeProtectionRowAccess() throws Except assertThat(rows.next()).isTrue(); } } - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult(ignored -> repository.settleExact(terminal))) + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(ignored -> repository.settleExact(terminal))) .hasRootCauseInstanceOf(org.postgresql.util.PSQLException.class) - .satisfies( - failure -> { - Throwable root = failure; - while (root.getCause() != null) root = root.getCause(); - assertThat(((org.postgresql.util.PSQLException) root).getSQLState()) - .isEqualTo("55P03"); - }); + .satisfies(failure -> { + Throwable root = failure; + while (root.getCause() != null) root = root.getCause(); + assertThat(((org.postgresql.util.PSQLException) root).getSQLState()) + .isEqualTo("55P03"); + }); assertThat(protectionLocks).isEmpty(); assertThat(sourceLocks) .containsExactlyElementsOf( @@ -162,11 +158,8 @@ void settlementLocksCanonicalSourceKeysBeforeProtectionRowAccess() throws Except protectionLocks.clear(); // Once both sources are available, row lookup follows them; no parent is manufactured by this // test. - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult(ignored -> repository.settleExact(terminal))) + assertThatThrownBy(() -> + fixture.transaction().executeWithoutResult(ignored -> repository.settleExact(terminal))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Exact original StartSession activation protection unavailable"); assertThat(sourceLocks).containsExactly(first.key(), last.key()); @@ -278,24 +271,21 @@ void digestAlignmentUpgradePreservesRetainedParentAndRequiresCanonicalWorldPrefi var changed = readJson(canonicalTerminal); changed.put("activationResultSha256", invalidDigest); byte[] invalidTerminal = jsonBytes(changed); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - insertActivationSettlement( - fixture, id, fence, activationId, evidence, invalidTerminal))) + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + insertActivationSettlement( + fixture, id, fence, activationId, evidence, invalidTerminal))) .isInstanceOf(RuntimeException.class) - .satisfies( - failure -> { - Throwable root = failure; - while (root.getCause() != null) root = root.getCause(); - assertThat(root) - .isInstanceOfSatisfying( - org.postgresql.util.PSQLException.class, - rejected -> assertThat(rejected.getSQLState()).isEqualTo("23514")); - }); + .satisfies(failure -> { + Throwable root = failure; + while (root.getCause() != null) root = root.getCause(); + assertThat(root) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + rejected -> assertThat(rejected.getSQLState()).isEqualTo("23514")); + }); assertThat(retainedActivationRows(fixture)).isEqualTo(parents); assertThat( fixture @@ -305,10 +295,9 @@ void digestAlignmentUpgradePreservesRetainedParentAndRequiresCanonicalWorldPrefi } fixture .transaction() - .executeWithoutResult( - status -> - insertActivationSettlement( - fixture, id, fence, activationId, evidence, canonicalTerminal)); + .executeWithoutResult(status -> + insertActivationSettlement( + fixture, id, fence, activationId, evidence, canonicalTerminal)); assertThat(retainedActivationRows(fixture)).isEqualTo(parents); var settlement = fixture @@ -452,33 +441,29 @@ void lifecycleUpgradePreservesPendingProtectionAndBlocksInvalidSettlement() thro assertThat(stored.get("activation_protection_fence", Long.class)).isPositive(); assertThat(stored.get("acquired_at", OffsetDateTime.class)).isNotNull(); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "UPDATE account_start_session_activation_protections " - + "SET acquired_at = acquired_at " - + "WHERE activation_protection_id = ?", - id))) + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "UPDATE account_start_session_activation_protections " + + "SET acquired_at = acquired_at " + + "WHERE activation_protection_id = ?", + id))) .hasMessageContaining("immutable; terminal settlement is separate"); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT account_control_ui_hold_required_sources(" - + "ARRAY[?]::text[])", - sourceKey))) + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(" + + "ARRAY[?]::text[])", + sourceKey))) .hasMessageContaining("Original StartSession activation protection remains pending"); assertThat( @@ -737,17 +722,15 @@ void lifecycleUpgradePreservesPendingProtectionAndBlocksInvalidSettlement() thro .dsl() .fetchCount(DSL.table("account_start_session_activation_protection_settlements"))) .isZero(); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", - sourceKey))) + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey))) .hasMessageContaining("Original StartSession activation protection remains pending"); } @@ -775,17 +758,15 @@ void lifecycleUpgradePreservesPendingProtectionAndBlocksInvalidSettlement() thro .dsl() .fetchCount(DSL.table("account_start_session_activation_protection_settlements"))) .isZero(); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", - sourceKey))) + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey))) .hasMessageContaining("Original StartSession activation protection remains pending"); } @@ -857,73 +838,65 @@ void lifecycleUpgradePreservesPendingProtectionAndBlocksInvalidSettlement() thro activationResultBytes); fixture .transaction() - .executeWithoutResult( - status -> - insert( - fixture.dsl(), - "account_start_session_activation_protection_settlements", - "activation_protection_id", - id, - "activation_protection_fence", - protectionFence, - "world_activation_request_id", - activationRequestId, - "world_activation_fence", - 29L, - "outcome", - "COMMITTED", - "account_protection_evidence_bytes", - accountEvidenceBytes, - "terminal_bytes", - terminalBytes, - "terminal_digest", - "sha256:" + hash(terminalBytes))); + .executeWithoutResult(status -> + insert( + fixture.dsl(), + "account_start_session_activation_protection_settlements", + "activation_protection_id", + id, + "activation_protection_fence", + protectionFence, + "world_activation_request_id", + activationRequestId, + "world_activation_fence", + 29L, + "outcome", + "COMMITTED", + "account_protection_evidence_bytes", + accountEvidenceBytes, + "terminal_bytes", + terminalBytes, + "terminal_digest", + "sha256:" + hash(terminalBytes))); fixture .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", - sourceKey)); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "UPDATE account_start_session_activation_protection_settlements " - + "SET outcome = outcome WHERE activation_protection_id = ?", - id))) + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey)); + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "UPDATE account_start_session_activation_protection_settlements " + + "SET outcome = outcome WHERE activation_protection_id = ?", + id))) .hasMessageContaining("activation settlement is immutable"); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "DELETE FROM account_start_session_activation_protection_settlements " - + "WHERE activation_protection_id = ?", - id))) + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "DELETE FROM account_start_session_activation_protection_settlements " + + "WHERE activation_protection_id = ?", + id))) .hasMessageContaining("activation settlement is immutable"); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "TRUNCATE account_start_session_activation_protection_settlements"))) + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "TRUNCATE account_start_session_activation_protection_settlements"))) .hasMessageContaining("activation settlement is immutable"); for (String guard : @@ -1017,17 +990,15 @@ void retainedMalformedPreparingLifecycleCannotSettleAfterV1004_2Upgrade() throws assertThat(pendingRows).hasSize(1); assertThat(retainedSources).hasSize(2); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", - sourceKey))) + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey))) .hasMessageContaining("Original StartSession activation protection remains pending"); Flyway v1004 = activationFlyway(fixture.dataSource(), "1004"); @@ -1057,17 +1028,15 @@ void retainedMalformedPreparingLifecycleCannotSettleAfterV1004_2Upgrade() throws "SELECT world_preparing_evidence FROM account_start_session_activation_protections") .get(0, byte[].class)) .isEqualTo(malformedPreparingBytes); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", - sourceKey))) + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey))) .hasMessageContaining("Original StartSession activation protection remains pending"); UUID activationRequestId = UUID.fromString((String) request.get("worldActivationRequestId")); @@ -1103,17 +1072,15 @@ void retainedMalformedPreparingLifecycleCannotSettleAfterV1004_2Upgrade() throws .dsl() .fetchCount(DSL.table("account_start_session_activation_protection_settlements"))) .isZero(); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", - sourceKey))) + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey))) .hasMessageContaining("Original StartSession activation protection remains pending"); } } @@ -1144,17 +1111,16 @@ void noncanonicalActivationRequestUuidCannotAcquireProtectionOrBlockSourceWriter .isInstanceOf(RuntimeException.class) .hasMessageContaining( "Activation protection does not retain its exact canonical request fields") - .satisfies( - failure -> { - Throwable postgresFailure = failure; - while (postgresFailure.getCause() != null) { - postgresFailure = postgresFailure.getCause(); - } - assertThat(postgresFailure) - .isInstanceOfSatisfying( - org.postgresql.util.PSQLException.class, - sqlFailure -> assertThat(sqlFailure.getSQLState()).isEqualTo("23514")); - }); + .satisfies(failure -> { + Throwable postgresFailure = failure; + while (postgresFailure.getCause() != null) { + postgresFailure = postgresFailure.getCause(); + } + assertThat(postgresFailure) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + sqlFailure -> assertThat(sqlFailure.getSQLState()).isEqualTo("23514")); + }); assertThat(fixture.dsl().fetchCount(DSL.table("account_start_session_activation_protections"))) .isZero(); assertThat( @@ -1171,13 +1137,12 @@ void noncanonicalActivationRequestUuidCannotAcquireProtectionOrBlockSourceWriter .get("source_key", String.class); fixture .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", - sourceKey)); + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey)); } @Test @@ -1222,17 +1187,16 @@ void noncanonicalActivationBase64CarriersCannotAcquireProtectionOrBlockSourceWri .isInstanceOf(RuntimeException.class) .hasMessageContaining( "Activation protection Base64 fields must use canonical encodings") - .satisfies( - failure -> { - Throwable postgresFailure = failure; - while (postgresFailure.getCause() != null) { - postgresFailure = postgresFailure.getCause(); - } - assertThat(postgresFailure) - .isInstanceOfSatisfying( - org.postgresql.util.PSQLException.class, - sqlFailure -> assertThat(sqlFailure.getSQLState()).isEqualTo("23514")); - }); + .satisfies(failure -> { + Throwable postgresFailure = failure; + while (postgresFailure.getCause() != null) { + postgresFailure = postgresFailure.getCause(); + } + assertThat(postgresFailure) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + sqlFailure -> assertThat(sqlFailure.getSQLState()).isEqualTo("23514")); + }); assertThat( fixture.dsl().fetchCount(DSL.table("account_start_session_activation_protections"))) .isZero(); @@ -1250,13 +1214,12 @@ void noncanonicalActivationBase64CarriersCannotAcquireProtectionOrBlockSourceWri .get("source_key", String.class); fixture .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", - sourceKey)); + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey)); } } } @@ -1340,17 +1303,15 @@ void malformedPreparingLifecycleCannotAcquireProtectionOrBlockSourceWriters() th // 128 Unicode code points occupy 129 Java UTF-16 units. oversizedLifecycleRequest.put("controlPlaneRequestId", "a".repeat(127) + "\uD83D\uDE00"); byte[] oversizedRequestIdBytes = jsonBytes(oversizedRequestId); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT account_ss_activation_validate_lifecycle(?, 'PREPARING')", - oversizedRequestIdBytes))) + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_validate_lifecycle(?, 'PREPARING')", + oversizedRequestIdBytes))) .hasMessageContaining("Activation lifecycle request text is invalid"); malformed.add(oversizedRequestIdBytes); String sourceKey = @@ -1374,19 +1335,17 @@ void malformedPreparingLifecycleCannotAcquireProtectionOrBlockSourceWriters() th current.expiryText()); assertThatThrownBy(() -> acquireProtection(fixture, changed)) .isInstanceOf(RuntimeException.class) - .satisfies( - failure -> { - Throwable postgresFailure = failure; - while (postgresFailure.getCause() != null) - postgresFailure = postgresFailure.getCause(); - assertThat(postgresFailure) - .isInstanceOfSatisfying( - org.postgresql.util.PSQLException.class, - sqlFailure -> - assertThat(sqlFailure.getSQLState()) - .as(sqlFailure.getMessage()) - .isEqualTo("23514")); - }); + .satisfies(failure -> { + Throwable postgresFailure = failure; + while (postgresFailure.getCause() != null) postgresFailure = postgresFailure.getCause(); + assertThat(postgresFailure) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + sqlFailure -> + assertThat(sqlFailure.getSQLState()) + .as(sqlFailure.getMessage()) + .isEqualTo("23514")); + }); assertThat( fixture.dsl().fetchCount(DSL.table("account_start_session_activation_protections"))) .isZero(); @@ -1397,28 +1356,25 @@ void malformedPreparingLifecycleCannotAcquireProtectionOrBlockSourceWriters() th .isZero(); fixture .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", - sourceKey)); + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey)); } acquireProtection(fixture, current); assertThat(fixture.dsl().fetchCount(DSL.table("account_start_session_activation_protections"))) .isEqualTo(1); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", - sourceKey))) + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sourceKey))) .hasMessageContaining("Original StartSession activation protection remains pending"); } @@ -1428,15 +1384,14 @@ void currentnessRequiresCommittedPreparationExactAttemptAndUnexpiredLease() thro CurrentnessCase valid = currentnessCase(fixture, Instant.now().plusSeconds(60)); fixture .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", - valid.requestBytes(), - valid.operationIdentityBytes(), - valid.operationIdentityDigest())); + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + valid.requestBytes(), + valid.operationIdentityBytes(), + valid.operationIdentityDigest())); Map changedProjectionRequest = JSON.readValue(valid.requestBytes(), new tools.jackson.core.type.TypeReference<>() {}); @@ -1450,19 +1405,17 @@ void currentnessRequiresCommittedPreparationExactAttemptAndUnexpiredLease() thro "accountRedemptionProjectionBytesBase64", Base64.getEncoder().encodeToString(differentSpelling)); byte[] changedProjection = jsonBytes(changedProjectionRequest); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", - changedProjection, - valid.operationIdentityBytes(), - valid.operationIdentityDigest()))) + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + changedProjection, + valid.operationIdentityBytes(), + valid.operationIdentityDigest()))) .hasMessageContaining( "Activation protection differs from original Account redemption or capture"); @@ -1495,33 +1448,31 @@ void fullTupleDoesNotBypassIndependentActivationIssuanceOperationBinding() throw fixture .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", - current.requestBytes(), - current.operationIdentityBytes(), - current.operationIdentityDigest())); + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + current.requestBytes(), + current.operationIdentityBytes(), + current.operationIdentityDigest())); // Stipulate one contradictory retained owner row to isolate the independent SQL conjunct. // Current activation/acquisition guards stay enabled; this is not authenticated producer proof. fixture .transaction() - .executeWithoutResult( - status -> { - fixture.dsl().execute("SET LOCAL session_replication_role = replica"); - assertThat( - fixture - .dsl() - .execute( - "UPDATE account_start_session_operator_authorizations SET issuance_operation_id = ? " - + "WHERE control_plane_request_id = ?", - UUID.randomUUID(), - requestId)) - .isEqualTo(1); - fixture.dsl().execute("SET LOCAL session_replication_role = origin"); - }); + .executeWithoutResult(status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + assertThat( + fixture + .dsl() + .execute( + "UPDATE account_start_session_operator_authorizations SET issuance_operation_id = ? " + + "WHERE control_plane_request_id = ?", + UUID.randomUUID(), + requestId)) + .isEqualTo(1); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); assertThatThrownBy(() -> acquireProtection(fixture, current)) .hasMessageContaining( "Activation protection differs from original Account redemption or capture"); @@ -1583,36 +1534,34 @@ void abortedSettlementPreservesTerminalCodeFenceWithoutRequiringActiveLifecycle( byte[] terminal = terminalBytes(fixture, id, fence, activationId, evidence, jsonBytes(result)); fixture .transaction() - .executeWithoutResult( - status -> - insert( - fixture.dsl(), - "account_start_session_activation_protection_settlements", - "activation_protection_id", - id, - "activation_protection_fence", - fence, - "world_activation_request_id", - activationId, - "world_activation_fence", - 29L, - "outcome", - "ABORTED", - "account_protection_evidence_bytes", - evidence, - "terminal_bytes", - terminal, - "terminal_digest", - "sha256:" + hash(terminal))); + .executeWithoutResult(status -> + insert( + fixture.dsl(), + "account_start_session_activation_protection_settlements", + "activation_protection_id", + id, + "activation_protection_fence", + fence, + "world_activation_request_id", + activationId, + "world_activation_fence", + 29L, + "outcome", + "ABORTED", + "account_protection_evidence_bytes", + evidence, + "terminal_bytes", + terminal, + "terminal_digest", + "sha256:" + hash(terminal))); fixture .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", - sources.get(0).get("source_key", String.class))); + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + sources.get(0).get("source_key", String.class))); } private static void assertSettlementInsertRejected( @@ -1668,47 +1617,44 @@ private static void assertSettlementInsertRejected( activationRequestId, protectionEvidenceBytes, activationResultBytes); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - insert( - fixture.dsl(), - "account_start_session_activation_protection_settlements", - "activation_protection_id", - protectionId, - "activation_protection_fence", - protectionFence, - "world_activation_request_id", - activationRequestId, - "world_activation_fence", - 29L, - "outcome", - outcome, - "account_protection_evidence_bytes", - protectionEvidenceBytes, - "terminal_bytes", - terminalBytes, - "terminal_digest", - "sha256:" + hash(terminalBytes)))) + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + insert( + fixture.dsl(), + "account_start_session_activation_protection_settlements", + "activation_protection_id", + protectionId, + "activation_protection_fence", + protectionFence, + "world_activation_request_id", + activationRequestId, + "world_activation_fence", + 29L, + "outcome", + outcome, + "account_protection_evidence_bytes", + protectionEvidenceBytes, + "terminal_bytes", + terminalBytes, + "terminal_digest", + "sha256:" + hash(terminalBytes)))) .as(assertionDescription) .isInstanceOf(RuntimeException.class) - .satisfies( - failure -> { - Throwable postgresFailure = failure; - while (postgresFailure.getCause() != null) { - postgresFailure = postgresFailure.getCause(); - } - assertThat(postgresFailure) - .isInstanceOfSatisfying( - org.postgresql.util.PSQLException.class, - sqlFailure -> - assertThat(sqlFailure.getSQLState()) - .as(sqlFailure.getMessage()) - .isEqualTo("23514")); - }); + .satisfies(failure -> { + Throwable postgresFailure = failure; + while (postgresFailure.getCause() != null) { + postgresFailure = postgresFailure.getCause(); + } + assertThat(postgresFailure) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + sqlFailure -> + assertThat(sqlFailure.getSQLState()) + .as(sqlFailure.getMessage()) + .isEqualTo("23514")); + }); } private static byte[] accountEvidence( @@ -1823,34 +1769,31 @@ private static String timestamp(OffsetDateTime value) { private static void assertCurrentnessRejected( Fixture fixture, byte[] requestBytes, byte[] operationIdentityBytes) { String operationDigest = "sha256:" + hash(operationIdentityBytes); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", - requestBytes, - operationIdentityBytes, - operationDigest))) + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + requestBytes, + operationIdentityBytes, + operationDigest))) .isInstanceOf(RuntimeException.class) - .satisfies( - failure -> { - Throwable postgresFailure = failure; - while (postgresFailure.getCause() != null) { - postgresFailure = postgresFailure.getCause(); - } - assertThat(postgresFailure) - .isInstanceOfSatisfying( - org.postgresql.util.PSQLException.class, - sqlFailure -> - assertThat(sqlFailure.getSQLState()) - .as(sqlFailure.getMessage()) - .isEqualTo("23514")); - }); + .satisfies(failure -> { + Throwable postgresFailure = failure; + while (postgresFailure.getCause() != null) { + postgresFailure = postgresFailure.getCause(); + } + assertThat(postgresFailure) + .isInstanceOfSatisfying( + org.postgresql.util.PSQLException.class, + sqlFailure -> + assertThat(sqlFailure.getSQLState()) + .as(sqlFailure.getMessage()) + .isEqualTo("23514")); + }); } private static CurrentnessCase currentnessCase(Fixture fixture, Instant originalLease) @@ -1980,207 +1923,206 @@ private static CurrentnessCase currentnessCase( String operationDigest = "sha256:" + hash(operationIdentity); fixture .transaction() - .executeWithoutResult( - status -> { - fixture - .dsl() - .execute( - "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", - sourceEvidence.get(0).key()); - fixture - .dsl() - .execute( - "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", - sourceEvidence.get(1).key()); - fixture.dsl().execute("SET LOCAL session_replication_role = replica"); - insert( - fixture.dsl(), - "account_canonical_tenant_identity_claims", - "canonical_tenant_id", - tenantId, - "identity_kind", - "APPROVED_RETAINED", - "source_operation_id", - UUID.randomUUID(), - "source_account_legacy_tenant_id", - 1L, - "source_target_namespace", - "test", - "source_game_row_id", - 1L, - "source_game_tenant_key", - tenantId.toString()); - insert( - fixture.dsl(), - "account_start_session_authority_captures", - "control_plane_request_id", - requestId, - "account_uuid", - accountId, - "tenant_uuid", - tenantId, - "target_owner", - "game-session-service", - "logging_workload_uri", - "spiffe://firemud/ns/test/sa/logging-admin-service", - "reservation_owner_id", - UUID.randomUUID(), - "reservation_claim_fence", - 7L, - "pre_authorization_tuple", - preAuthorization, - "mutation_digest", - "c".repeat(64), - "control_ui_operation_id", - UUID.randomUUID(), - "control_ui_token_jti", - UUID.randomUUID(), - "control_ui_token_hash", - "d".repeat(64), - "control_ui_signer_receipt_sha256", - "e".repeat(64), - "issuance_fence", - issuanceFence, - "issuance_fence_source_version", - sourceVersion, - "captured_at", - OffsetDateTime.ofInstant( - normalizedNow.truncatedTo(ChronoUnit.MILLIS), ZoneOffset.UTC), - "snapshot_sha256", - snapshotDigest, - "canonical_snapshot_bytes", - snapshot, - "source_version", - sourceVersion, - "source_fence", - sourceFence, - "linearization", - "19", - "canonical_sha256", - captureDigest, - "canonical_capture_bytes", - captureReference); - insert( - fixture.dsl(), - "account_start_session_operator_authorizations", - "control_plane_request_id", - requestId, - "pre_authorization_tuple", - preAuthorization, - "mutation_digest", - "c".repeat(64), - "issuance_workload_uri", - "spiffe://firemud/ns/test/sa/logging-admin-service", - "reservation_owner_id", - UUID.randomUUID(), - "reservation_claim_fence", - 7L, - "issuance_operation_id", - issuanceOperationId, - "issuance_fence", - issuanceFence, - "bundle_version", - "authorityEvidenceBundle/v1", - "bundle_source_version", - Long.toString(sourceVersion), - "bundle_source_fence", - Long.toString(sourceFence), - "bundle_linearization", - "19", - "authority_evidence_bundle", - authorityBundle, - "authorization_reference_fingerprint", - fingerprint, - "encrypted_response_envelope", - bytes("synthetic response"), - "issued_at", - OffsetDateTime.ofInstant(issuedAt, ZoneOffset.UTC), - "reference_expires_at", - OffsetDateTime.ofInstant(referenceExpiry, ZoneOffset.UTC), - "response_envelope_expires_at", - OffsetDateTime.ofInstant(responseExpiry, ZoneOffset.UTC), - "status", - "REDEEMED", - "redemption_redeemer_workload_uri", - "spiffe://firemud/ns/test/sa/game-session-service", - "redemption_owner_attempt_id", - ownerAttemptId, - "redemption_owner_fence", - ownerFence, - "redeemed_at", - OffsetDateTime.ofInstant(redeemedAt, ZoneOffset.UTC), - "redemption_reference_fingerprint", - fingerprint, - "redemption_authority_evidence_bundle", - authorityBundle); - insert( - fixture.dsl(), - "account_start_session_world_participations", - "participation_id", - participationId, - "control_plane_request_id", - requestId, - "original_post_authorization_tuple", - tuple, - "target_namespace", - "test", - "canonical_tenant_id", - tenantId, - "canonical_game_instance_id", - gameInstanceId, - "game_session_owner_attempt_id", - ownerAttemptId, - "game_session_owner_fence", - ownerFence, - "preparation_input_json", - preparationInput, - "preparation_input_digest", - preparationDigest); - for (SourceEvidence source : sourceEvidence) { - insert( - fixture.dsl(), - "account_start_session_world_participation_sources", - "participation_id", - participationId, - "source_key", - source.key(), - "source_evidence", - source.canonicalBytes()); - } - insert( - fixture.dsl(), - "account_start_session_world_original_attempt_evidence", - "participation_id", - participationId, - "target_namespace", - "test", - "game_session_owner_mutation_id", - ownerMutationId, - "game_session_owner_attempt_id", - ownerAttemptId, - "game_session_owner_fence", - ownerFence, - "original_lease_expires_at", - OffsetDateTime.ofInstant(normalizedLease, ZoneOffset.UTC), - "original_response_bytes", - attemptBytes, - "original_response_digest", - "sha256:" + hash(attemptBytes)); - insert( - fixture.dsl(), - "account_start_session_world_participation_settlements", - "participation_id", - participationId, - "outcome", - "COMMITTED", - "world_execution_fence", - 3L, - "terminal_bytes", - bytes("synthetic committed preparation"), - "terminal_digest", - "sha256:" + hash(bytes("synthetic committed preparation"))); - fixture.dsl().execute("SET LOCAL session_replication_role = origin"); - }); + .executeWithoutResult(status -> { + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + sourceEvidence.get(0).key()); + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + sourceEvidence.get(1).key()); + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + insert( + fixture.dsl(), + "account_canonical_tenant_identity_claims", + "canonical_tenant_id", + tenantId, + "identity_kind", + "APPROVED_RETAINED", + "source_operation_id", + UUID.randomUUID(), + "source_account_legacy_tenant_id", + 1L, + "source_target_namespace", + "test", + "source_game_row_id", + 1L, + "source_game_tenant_key", + tenantId.toString()); + insert( + fixture.dsl(), + "account_start_session_authority_captures", + "control_plane_request_id", + requestId, + "account_uuid", + accountId, + "tenant_uuid", + tenantId, + "target_owner", + "game-session-service", + "logging_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "pre_authorization_tuple", + preAuthorization, + "mutation_digest", + "c".repeat(64), + "control_ui_operation_id", + UUID.randomUUID(), + "control_ui_token_jti", + UUID.randomUUID(), + "control_ui_token_hash", + "d".repeat(64), + "control_ui_signer_receipt_sha256", + "e".repeat(64), + "issuance_fence", + issuanceFence, + "issuance_fence_source_version", + sourceVersion, + "captured_at", + OffsetDateTime.ofInstant( + normalizedNow.truncatedTo(ChronoUnit.MILLIS), ZoneOffset.UTC), + "snapshot_sha256", + snapshotDigest, + "canonical_snapshot_bytes", + snapshot, + "source_version", + sourceVersion, + "source_fence", + sourceFence, + "linearization", + "19", + "canonical_sha256", + captureDigest, + "canonical_capture_bytes", + captureReference); + insert( + fixture.dsl(), + "account_start_session_operator_authorizations", + "control_plane_request_id", + requestId, + "pre_authorization_tuple", + preAuthorization, + "mutation_digest", + "c".repeat(64), + "issuance_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "issuance_operation_id", + issuanceOperationId, + "issuance_fence", + issuanceFence, + "bundle_version", + "authorityEvidenceBundle/v1", + "bundle_source_version", + Long.toString(sourceVersion), + "bundle_source_fence", + Long.toString(sourceFence), + "bundle_linearization", + "19", + "authority_evidence_bundle", + authorityBundle, + "authorization_reference_fingerprint", + fingerprint, + "encrypted_response_envelope", + bytes("synthetic response"), + "issued_at", + OffsetDateTime.ofInstant(issuedAt, ZoneOffset.UTC), + "reference_expires_at", + OffsetDateTime.ofInstant(referenceExpiry, ZoneOffset.UTC), + "response_envelope_expires_at", + OffsetDateTime.ofInstant(responseExpiry, ZoneOffset.UTC), + "status", + "REDEEMED", + "redemption_redeemer_workload_uri", + "spiffe://firemud/ns/test/sa/game-session-service", + "redemption_owner_attempt_id", + ownerAttemptId, + "redemption_owner_fence", + ownerFence, + "redeemed_at", + OffsetDateTime.ofInstant(redeemedAt, ZoneOffset.UTC), + "redemption_reference_fingerprint", + fingerprint, + "redemption_authority_evidence_bundle", + authorityBundle); + insert( + fixture.dsl(), + "account_start_session_world_participations", + "participation_id", + participationId, + "control_plane_request_id", + requestId, + "original_post_authorization_tuple", + tuple, + "target_namespace", + "test", + "canonical_tenant_id", + tenantId, + "canonical_game_instance_id", + gameInstanceId, + "game_session_owner_attempt_id", + ownerAttemptId, + "game_session_owner_fence", + ownerFence, + "preparation_input_json", + preparationInput, + "preparation_input_digest", + preparationDigest); + for (SourceEvidence source : sourceEvidence) { + insert( + fixture.dsl(), + "account_start_session_world_participation_sources", + "participation_id", + participationId, + "source_key", + source.key(), + "source_evidence", + source.canonicalBytes()); + } + insert( + fixture.dsl(), + "account_start_session_world_original_attempt_evidence", + "participation_id", + participationId, + "target_namespace", + "test", + "game_session_owner_mutation_id", + ownerMutationId, + "game_session_owner_attempt_id", + ownerAttemptId, + "game_session_owner_fence", + ownerFence, + "original_lease_expires_at", + OffsetDateTime.ofInstant(normalizedLease, ZoneOffset.UTC), + "original_response_bytes", + attemptBytes, + "original_response_digest", + "sha256:" + hash(attemptBytes)); + insert( + fixture.dsl(), + "account_start_session_world_participation_settlements", + "participation_id", + participationId, + "outcome", + "COMMITTED", + "world_execution_fence", + 3L, + "terminal_bytes", + bytes("synthetic committed preparation"), + "terminal_digest", + "sha256:" + hash(bytes("synthetic committed preparation"))); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); byte[] requestBytes = activationRequest( tuple, @@ -2207,55 +2149,54 @@ private static CurrentnessCase currentnessCase( private static void acquireProtection(Fixture fixture, CurrentnessCase current) { fixture .transaction() - .executeWithoutResult( - status -> { - fixture - .dsl() - .execute( - """ - INSERT INTO account_start_session_activation_protections( - control_plane_request_id, account_world_participation_id, account_world_participation_fence, - original_post_authorization_tuple, account_redemption_projection, - game_session_owner_mutation_id, game_session_owner_attempt_id, game_session_owner_fence, - original_lease_expires_at, target_namespace, canonical_tenant_id, canonical_game_instance_id, - world_activation_request_id, game_session_launch_read_evidence, world_preparing_evidence, - capture_source_version, capture_source_fence, capture_sha256, - capture_reference_bytes, capture_reference_sha256, operation_identity_bytes, - operation_identity_digest, request_binding_bytes, request_binding_digest) - SELECT w.control_plane_request_id, w.participation_id, w.participation_fence, - w.original_post_authorization_tuple, w.original_post_authorization_tuple, - o.game_session_owner_mutation_id, o.game_session_owner_attempt_id, o.game_session_owner_fence, - o.original_lease_expires_at, w.target_namespace, w.canonical_tenant_id, w.canonical_game_instance_id, - (r.value->>'worldActivationRequestId')::uuid, - decode(r.value->>'gameSessionLaunchReadEvidenceBytesBase64', 'base64'), - decode(r.value->>'preparingEvidenceBytesBase64', 'base64'), - c.source_version, c.source_fence, c.canonical_sha256, - c.canonical_capture_bytes, c.canonical_sha256, ?, ?, ?, ? - FROM account_start_session_world_participations w - JOIN account_start_session_world_original_attempt_evidence o USING(participation_id) - JOIN account_start_session_authority_captures c USING(control_plane_request_id) - CROSS JOIN (SELECT convert_from(?::bytea, 'UTF8')::jsonb AS value) r - WHERE w.participation_id = (r.value->>'accountWorldParticipationId')::uuid - """, - current.operationIdentityBytes(), - current.operationIdentityDigest(), - current.requestBytes(), - "sha256:" + hash(current.requestBytes()), - current.requestBytes()); - fixture - .dsl() - .execute( - """ - INSERT INTO account_start_session_activation_protection_sources( - activation_protection_id, source_key, source_evidence) - SELECT p.activation_protection_id, s.source_key, s.source_evidence - FROM account_start_session_activation_protections p - JOIN account_start_session_world_participation_sources s - ON s.participation_id = p.account_world_participation_id - WHERE p.operation_identity_digest = ? - """, - current.operationIdentityDigest()); - }); + .executeWithoutResult(status -> { + fixture + .dsl() + .execute( + """ + INSERT INTO account_start_session_activation_protections( + control_plane_request_id, account_world_participation_id, account_world_participation_fence, + original_post_authorization_tuple, account_redemption_projection, + game_session_owner_mutation_id, game_session_owner_attempt_id, game_session_owner_fence, + original_lease_expires_at, target_namespace, canonical_tenant_id, canonical_game_instance_id, + world_activation_request_id, game_session_launch_read_evidence, world_preparing_evidence, + capture_source_version, capture_source_fence, capture_sha256, + capture_reference_bytes, capture_reference_sha256, operation_identity_bytes, + operation_identity_digest, request_binding_bytes, request_binding_digest) + SELECT w.control_plane_request_id, w.participation_id, w.participation_fence, + w.original_post_authorization_tuple, w.original_post_authorization_tuple, + o.game_session_owner_mutation_id, o.game_session_owner_attempt_id, o.game_session_owner_fence, + o.original_lease_expires_at, w.target_namespace, w.canonical_tenant_id, w.canonical_game_instance_id, + (r.value->>'worldActivationRequestId')::uuid, + decode(r.value->>'gameSessionLaunchReadEvidenceBytesBase64', 'base64'), + decode(r.value->>'preparingEvidenceBytesBase64', 'base64'), + c.source_version, c.source_fence, c.canonical_sha256, + c.canonical_capture_bytes, c.canonical_sha256, ?, ?, ?, ? + FROM account_start_session_world_participations w + JOIN account_start_session_world_original_attempt_evidence o USING(participation_id) + JOIN account_start_session_authority_captures c USING(control_plane_request_id) + CROSS JOIN (SELECT convert_from(?::bytea, 'UTF8')::jsonb AS value) r + WHERE w.participation_id = (r.value->>'accountWorldParticipationId')::uuid + """, + current.operationIdentityBytes(), + current.operationIdentityDigest(), + current.requestBytes(), + "sha256:" + hash(current.requestBytes()), + current.requestBytes()); + fixture + .dsl() + .execute( + """ + INSERT INTO account_start_session_activation_protection_sources( + activation_protection_id, source_key, source_evidence) + SELECT p.activation_protection_id, s.source_key, s.source_evidence + FROM account_start_session_activation_protections p + JOIN account_start_session_world_participation_sources s + ON s.participation_id = p.account_world_participation_id + WHERE p.operation_identity_digest = ? + """, + current.operationIdentityDigest()); + }); } private static byte[] activationRequest( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java index dbb5872a20..91e6044b09 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java @@ -275,11 +275,10 @@ private static void assertCurrentMigrationsInstalled(Flyway flyway) { var migrations = flyway.info().all(); assertThat(migrations) .isNotEmpty() - .allSatisfy( - migration -> - assertThat(migration.getState()) - .as(migration.getScript()) - .isEqualTo(MigrationState.SUCCESS)); + .allSatisfy(migration -> + assertThat(migration.getState()) + .as(migration.getScript()) + .isEqualTo(MigrationState.SUCCESS)); assertThat(migrations) .extracting(MigrationInfo::getVersion) .contains(MigrationVersion.fromVersion("1003"), MigrationVersion.fromVersion("1004")); @@ -307,17 +306,16 @@ void forwardMigrationAddsSourceProtectionsWithoutChangingRetainedCanonicalParent // capture/World rows in this fixture. This does not establish authenticated producer proof. parent .transaction() - .executeWithoutResult( - status -> { - parent.dsl().execute("SET LOCAL session_replication_role = replica"); - parent - .dsl() - .execute( - "INSERT INTO account_jwt_signer_desired_states " - + "(environment_id, cluster_id, kubernetes_namespace, custody_mode) " - + "VALUES ('test', 'test-cluster', 'test', 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK')"); - parent.dsl().execute("SET LOCAL session_replication_role = origin"); - }); + .executeWithoutResult(status -> { + parent.dsl().execute("SET LOCAL session_replication_role = replica"); + parent + .dsl() + .execute( + "INSERT INTO account_jwt_signer_desired_states " + + "(environment_id, cluster_id, kubernetes_namespace, custody_mode) " + + "VALUES ('test', 'test-cluster', 'test', 'INTERIM_ACCOUNT_ONLY_MOUNTED_FALLBACK')"); + parent.dsl().execute("SET LOCAL session_replication_role = origin"); + }); List retainedTables = List.of( "account_jwt_signer_desired_states", @@ -464,18 +462,17 @@ void fullTupleDoesNotBypassIndependentOwnerIssuanceOperationBinding() { // The parent immutable writer remains enabled outside this deliberate corruption fixture. fixture .transaction() - .executeWithoutResult( - status -> { - fixture.dsl().execute("SET LOCAL session_replication_role = replica"); - fixture - .dsl() - .execute( - "UPDATE account_start_session_operator_authorizations SET issuance_operation_id = ? " - + "WHERE control_plane_request_id = ?", - UUID.randomUUID(), - fixture.requestId()); - fixture.dsl().execute("SET LOCAL session_replication_role = origin"); - }); + .executeWithoutResult(status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + fixture + .dsl() + .execute( + "UPDATE account_start_session_operator_authorizations SET issuance_operation_id = ? " + + "WHERE control_plane_request_id = ?", + UUID.randomUUID(), + fixture.requestId()); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); assertThat(fixture.projection()).containsExactly(fixture.tuple()); assertThatThrownBy(() -> acquire(fixture)) .hasMessageContaining( @@ -543,15 +540,14 @@ void exactCurrentReadPreservesIdentityWithoutAllocatingAndWorldCommitCannotRelea var current = fixture .transaction() - .execute( - status -> - fixture - .dsl() - .fetchSingle( - "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", - fixture.protectionId(), - 1L, - fixture.request())); + .execute(status -> + fixture + .dsl() + .fetchSingle( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + fixture.request())); assertThat(current.get("protection_id", UUID.class)).isEqualTo(fixture.protectionId()); assertThat(current.get("request_binding_bytes", byte[].class)) .containsExactly(fixture.request()); @@ -569,17 +565,15 @@ void exactCurrentReadPreservesIdentityWithoutAllocatingAndWorldCommitCannotRelea fixture.worldId()) .get(0, Boolean.class)) .isTrue(); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", - fixture.source().key()))) + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + fixture.source().key()))) .hasMessageContaining("Original StartSession admission protection remains pending"); } @@ -603,19 +597,17 @@ void changedSubmillisecondOriginalExpiryCannotRecoverRetainedProtection() { .getBytes(StandardCharsets.UTF_8); assertThat(changedRequest).isNotEqualTo(fixture.request()); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", - fixture.protectionId(), - 1L, - changedRequest))) + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + changedRequest))) .hasMessageContaining("Original admission recovery binding differs"); var storedRowAfter = fixture @@ -651,12 +643,11 @@ void forgedWorldHoldDigestWithoutCanonicalPrefixCannotBecomeProtection() { .replace(base64(fixture.hold()), base64(forgedHold)) .getBytes(StandardCharsets.UTF_8); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> insertProtection(fixture, 11L, forgedHold, forgedRequest))) + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult( + status -> insertProtection(fixture, 11L, forgedHold, forgedRequest))) .hasMessageContaining( "Original StartSession admission hold request differs from retained protection"); assertThat( @@ -674,100 +665,87 @@ void pendingAdmissionExcludesRealSourceChangeCompletionAndDisclosureDispatch() { UUID changeId = UUID.randomUUID(); fixture .transaction() - .executeWithoutResult( - status -> { - insert( - fixture.dsl(), - "account_draft_authorization_source_changes", - "change_id", - changeId, - "binding", - bytes("change"), - "status", - "WAITING"); - insert( - fixture.dsl(), - "account_draft_authorization_changed_scopes", - "change_id", - changeId, - "source_key", - fixture.source().key()); - }); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "UPDATE account_draft_authorization_source_changes SET status = 'SOURCE_COMMITTED', committed_at = clock_timestamp() WHERE change_id = ?", - changeId))) + .executeWithoutResult(status -> { + insert( + fixture.dsl(), + "account_draft_authorization_source_changes", + "change_id", + changeId, + "binding", + bytes("change"), + "status", + "WAITING"); + insert( + fixture.dsl(), + "account_draft_authorization_changed_scopes", + "change_id", + changeId, + "source_key", + fixture.source().key()); + }); + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "UPDATE account_draft_authorization_source_changes SET status = 'SOURCE_COMMITTED', committed_at = clock_timestamp() WHERE change_id = ?", + changeId))) .hasMessageContaining("Original StartSession admission protection remains pending"); UUID handoffId = UUID.randomUUID(); fixture .transaction() - .executeWithoutResult( - status -> - insert( - fixture.dsl(), - "account_hosted_terms_disclosure_handoffs", - "handoff_id", - handoffId, - "request_id", - UUID.randomUUID(), - "kind", - "CATALOG", - "source_key", - fixture.source().key(), - "predecessor_digest", - "sha256:" + "a".repeat(64), - "candidate_digest", - "sha256:" + "b".repeat(64), - "effective_at", - OffsetDateTime.now().plusDays(1), - "binding", - bytes("disclosure"), - "binding_digest", - "sha256:" + hash(bytes("disclosure")), - "status", - "PREPARED")); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "UPDATE account_hosted_terms_disclosure_handoffs SET status = 'DISPATCH_AUTHORIZED', dispatch_attempts = 1 WHERE handoff_id = ?", - handoffId))) + .executeWithoutResult(status -> + insert( + fixture.dsl(), + "account_hosted_terms_disclosure_handoffs", + "handoff_id", + handoffId, + "request_id", + UUID.randomUUID(), + "kind", + "CATALOG", + "source_key", + fixture.source().key(), + "predecessor_digest", + "sha256:" + "a".repeat(64), + "candidate_digest", + "sha256:" + "b".repeat(64), + "effective_at", + OffsetDateTime.now().plusDays(1), + "binding", + bytes("disclosure"), + "binding_digest", + "sha256:" + hash(bytes("disclosure")), + "status", + "PREPARED")); + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "UPDATE account_hosted_terms_disclosure_handoffs SET status = 'DISPATCH_AUTHORIZED', dispatch_attempts = 1 WHERE handoff_id = ?", + handoffId))) .hasMessageContaining("Original StartSession admission protection remains pending"); } @Test void rawChangedCaptureAndIncompleteChildrenCannotBecomeProtection() { Fixture changed = fixture(); - assertThatThrownBy( - () -> - changed - .transaction() - .executeWithoutResult(status -> insertProtection(changed, 99L))) + assertThatThrownBy(() -> + changed.transaction().executeWithoutResult(status -> insertProtection(changed, 99L))) .hasMessageContaining("retained owner bindings"); Fixture incomplete = fixture(); - assertThatThrownBy( - () -> - incomplete - .transaction() - .executeWithoutResult(status -> insertProtection(incomplete, 11L))) - .satisfies( - failure -> - assertDatabaseGuardFailure( - failure, - "Admission protection has incomplete or extra source children", - "23514")); + assertThatThrownBy(() -> + incomplete + .transaction() + .executeWithoutResult(status -> insertProtection(incomplete, 11L))) + .satisfies(failure -> + assertDatabaseGuardFailure( + failure, "Admission protection has incomplete or extra source children", "23514")); assertThat( incomplete .dsl() @@ -789,23 +767,21 @@ void immutableRowsAndUnprovedTerminalCannotReleaseProtection() { assertThatThrownBy(() -> fixture.dsl().execute("TRUNCATE " + table + " CASCADE")) .hasMessageContaining("append-only"); } - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "UPDATE account_start_session_admission_protection_sources SET source_evidence = ?", - bytes("changed"))) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "UPDATE account_start_session_admission_protection_sources SET source_evidence = ?", + bytes("changed"))) .hasMessageContaining("append-only"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "INSERT INTO account_start_session_admission_protection_settlements (protection_id, outcome, terminal_bytes, terminal_digest) VALUES (?, 'ABORTED', ?, ?)", - fixture.protectionId(), - malformedSettlementBytes(), - "sha256:" + hash(malformedSettlementBytes()))) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "INSERT INTO account_start_session_admission_protection_settlements (protection_id, outcome, terminal_bytes, terminal_digest) VALUES (?, 'ABORTED', ?, ?)", + fixture.protectionId(), + malformedSettlementBytes(), + "sha256:" + hash(malformedSettlementBytes()))) .hasMessageContaining("not the closed envelope"); assertThat( fixture @@ -823,13 +799,12 @@ void genuineFramedTerminalReceiptsReleaseRequiredSource() { GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED)) { Fixture fixture = fixture(); acquire(fixture); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", - fixture.source().key())) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::text[])", + fixture.source().key())) .hasMessageContaining("Original StartSession admission protection remains pending"); var proof = new GameSessionCanonicalInitialAdmissionOwnerProof( @@ -901,29 +876,26 @@ void expiredOriginalCannotRecoverEvenWhenRetainedIdentityAndSourcesRemain() { // rewriting the fixture row requires disabling the immutable upstream/new triggers. fixture .transaction() - .executeWithoutResult( - status -> { - fixture.dsl().execute("SET LOCAL session_replication_role = replica"); - fixture - .dsl() - .execute( - "UPDATE account_start_session_admission_protections SET original_lease_expires_at = date_trunc('milliseconds', clock_timestamp() - INTERVAL '1 second') WHERE protection_id = ?", - fixture.protectionId()); - fixture.dsl().execute("SET LOCAL session_replication_role = origin"); - }); - assertThatThrownBy( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", - fixture.protectionId(), - 1L, - fixture.request()))) + .executeWithoutResult(status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + fixture + .dsl() + .execute( + "UPDATE account_start_session_admission_protections SET original_lease_expires_at = date_trunc('milliseconds', clock_timestamp() - INTERVAL '1 second') WHERE protection_id = ?", + fixture.protectionId()); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + assertThatThrownBy(() -> + fixture + .transaction() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + fixture.request()))) .hasMessageContaining("not current"); assertThat( fixture @@ -947,30 +919,28 @@ void currentRecoveryRechecksDatabaseExpiryAfterTheCallerWaitsForOriginalCaptureL "SELECT control_plane_request_id FROM account_start_session_authority_captures WHERE control_plane_request_id = ? FOR UPDATE", fixture.requestId()); var waiting = - executor.submit( - () -> - fixture - .transaction() - .executeWithoutResult( - status -> { - entered.countDown(); - // The currentness producer's original-capture lock can wait before the - // V165 - // boundary. V165 itself uses NOWAIT to avoid reversing source lock - // order. - fixture - .dsl() - .fetch( - "SELECT control_plane_request_id FROM account_start_session_authority_captures WHERE control_plane_request_id = ? FOR UPDATE", - fixture.requestId()); - fixture - .dsl() - .execute( - "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", - fixture.protectionId(), - 1L, - fixture.request()); - })); + executor.submit(() -> + fixture + .transaction() + .executeWithoutResult(status -> { + entered.countDown(); + // The currentness producer's original-capture lock can wait before the + // V165 + // boundary. V165 itself uses NOWAIT to avoid reversing source lock + // order. + fixture + .dsl() + .fetch( + "SELECT control_plane_request_id FROM account_start_session_authority_captures WHERE control_plane_request_id = ? FOR UPDATE", + fixture.requestId()); + fixture + .dsl() + .execute( + "SELECT * FROM account_ss_admission_read_current_exact(?, ?, ?)", + fixture.protectionId(), + 1L, + fixture.request()); + })); assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); long expiryDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); while (fixture @@ -1018,23 +988,21 @@ void acquisitionRejectsUnsettleableHoldRequestAndSourceSnapshotBounds() throws E () -> fixture .transaction() - .executeWithoutResult( - status -> - insertProtection(fixture, 11L, oversizedHold, json(oversizedHoldRequest))), + .executeWithoutResult(status -> + insertProtection(fixture, 11L, oversizedHold, json(oversizedHoldRequest))), "23514"); assertDatabaseGuardFailure( () -> fixture .transaction() - .executeWithoutResult( - status -> - insertProtection( - fixture, - 11L, - fixture.hold(), - bytes( - new String(fixture.request(), StandardCharsets.UTF_8) - + " ".repeat(786433)))), + .executeWithoutResult(status -> + insertProtection( + fixture, + 11L, + fixture.hold(), + bytes( + new String(fixture.request(), StandardCharsets.UTF_8) + + " ".repeat(786433)))), "23514"); for (List vector : @@ -1174,28 +1142,27 @@ void acquisitionAccepts256CompleteSourcesAndRejects257CompleteSources() { sources.sort(java.util.Comparator.comparing(SourceEvidence::key)); fixture .transaction() - .executeWithoutResult( - status -> { - fixture.dsl().execute("SET LOCAL session_replication_role = replica"); - for (SourceEvidence source : sources) { - if (source.key().equals(fixture.source().key())) continue; - fixture - .dsl() - .execute( - "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", - source.key()); - insert( - fixture.dsl(), - "account_start_session_world_participation_sources", - "participation_id", - fixture.worldId(), - "source_key", - source.key(), - "source_evidence", - source.canonicalBytes()); - } - fixture.dsl().execute("SET LOCAL session_replication_role = origin"); - }); + .executeWithoutResult(status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + for (SourceEvidence source : sources) { + if (source.key().equals(fixture.source().key())) continue; + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + source.key()); + insert( + fixture.dsl(), + "account_start_session_world_participation_sources", + "participation_id", + fixture.worldId(), + "source_key", + source.key(), + "source_evidence", + source.canonicalBytes()); + } + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); replaceSnapshot( fixture, json( @@ -1243,27 +1210,26 @@ void acquisitionRequiresCanonicalUtf16OrderForMultipleUnicodeSources() { .toList(); fixture .transaction() - .executeWithoutResult( - status -> { - fixture.dsl().execute("SET LOCAL session_replication_role = replica"); - for (SourceEvidence source : List.of(supplementary, bmp)) { - fixture - .dsl() - .execute( - "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", - source.key()); - insert( - fixture.dsl(), - "account_start_session_world_participation_sources", - "participation_id", - fixture.worldId(), - "source_key", - source.key(), - "source_evidence", - source.canonicalBytes()); - } - fixture.dsl().execute("SET LOCAL session_replication_role = origin"); - }); + .executeWithoutResult(status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + for (SourceEvidence source : List.of(supplementary, bmp)) { + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + source.key()); + insert( + fixture.dsl(), + "account_start_session_world_participation_sources", + "participation_id", + fixture.worldId(), + "source_key", + source.key(), + "source_evidence", + source.canonicalBytes()); + } + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); var reversed = new java.util.ArrayList<>(sources); java.util.Collections.reverse(reversed); replaceSnapshot( @@ -1307,33 +1273,31 @@ private static void assertDatabaseGuardFailure(Runnable operation, String expect private static void replaceSnapshot(Fixture fixture, byte[] snapshot) { fixture .transaction() - .executeWithoutResult( - status -> { - fixture.dsl().execute("SET LOCAL session_replication_role = replica"); - fixture - .dsl() - .execute( - "UPDATE account_start_session_authority_captures SET canonical_snapshot_bytes = ?, snapshot_sha256 = ? WHERE control_plane_request_id = ?", - snapshot, - hash(snapshot), - fixture.requestId()); - fixture.dsl().execute("SET LOCAL session_replication_role = origin"); - }); + .executeWithoutResult(status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + fixture + .dsl() + .execute( + "UPDATE account_start_session_authority_captures SET canonical_snapshot_bytes = ?, snapshot_sha256 = ? WHERE control_plane_request_id = ?", + snapshot, + hash(snapshot), + fixture.requestId()); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); } private static void acquire(Fixture fixture) { fixture .transaction() - .executeWithoutResult( - status -> { - insertProtection(fixture, 11L); - fixture - .dsl() - .execute( - "INSERT INTO account_start_session_admission_protection_sources(protection_id, source_key, source_evidence) SELECT ?, source_key, source_evidence FROM account_start_session_world_participation_sources WHERE participation_id = ?", - fixture.protectionId(), - fixture.worldId()); - }); + .executeWithoutResult(status -> { + insertProtection(fixture, 11L); + fixture + .dsl() + .execute( + "INSERT INTO account_start_session_admission_protection_sources(protection_id, source_key, source_evidence) SELECT ?, source_key, source_evidence FROM account_start_session_world_participation_sources WHERE participation_id = ?", + fixture.protectionId(), + fixture.worldId()); + }); } private static void insertProtection(Fixture fixture, long version) { @@ -1532,195 +1496,194 @@ private static Fixture fixture(long leaseMillis, String target, boolean scalarPr requestId, "sourceVector", List.of(base64(evidence.canonicalBytes())))); - transaction.executeWithoutResult( - status -> { - dsl.execute("SET LOCAL session_replication_role = replica"); - insert( - dsl, - "account_canonical_tenant_identity_claims", - "canonical_tenant_id", - tenant, - "identity_kind", - "APPROVED_RETAINED", - "source_operation_id", - UUID.randomUUID(), - "source_account_legacy_tenant_id", - 1L, - "source_target_namespace", - "test", - "source_game_row_id", - 1L, - "source_game_tenant_key", - tenant.toString()); - insert(dsl, "account_draft_authorization_source_locks", "source_key", evidence.key()); - insert( - dsl, - "account_start_session_authority_captures", - "control_plane_request_id", - requestId, - "account_uuid", - actor, - "tenant_uuid", - tenant, - "target_owner", - "game-session-service", - "logging_workload_uri", - "spiffe://firemud/ns/test/sa/logging-admin-service", - "reservation_owner_id", - UUID.randomUUID(), - "reservation_claim_fence", - 7L, - "pre_authorization_tuple", - bytes("{}"), - "mutation_digest", - "c".repeat(64), - "control_ui_operation_id", - UUID.randomUUID(), - "control_ui_token_jti", - UUID.randomUUID(), - "control_ui_token_hash", - "d".repeat(64), - "control_ui_signer_receipt_sha256", - "e".repeat(64), - "issuance_fence", - 9L, - "issuance_fence_source_version", - 1L, - "captured_at", - capturedAt, - "snapshot_sha256", - hash(snapshot), - "canonical_snapshot_bytes", - snapshot, - "source_version", - 11L, - "source_fence", - 13L, - "linearization", - "17", - "canonical_sha256", - hash(bytes("{}")), - "canonical_capture_bytes", - bytes("{}")); - insert( - dsl, - "account_start_session_operator_authorizations", - "control_plane_request_id", - requestId, - "pre_authorization_tuple", - bytes("{}"), - "mutation_digest", - "c".repeat(64), - "issuance_workload_uri", - "spiffe://firemud/ns/test/sa/logging-admin-service", - "reservation_owner_id", - UUID.randomUUID(), - "reservation_claim_fence", - 7L, - "issuance_operation_id", - issuance, - "issuance_fence", - 9L, - "bundle_version", - "authorityEvidenceBundle/v1", - "bundle_source_version", - "11", - "bundle_source_fence", - "13", - "bundle_linearization", - "17", - "authority_evidence_bundle", - json(authorityBundle), - "authorization_reference_fingerprint", - "arfp/v1/key-1/" + "a".repeat(64), - "encrypted_response_envelope", - bytes("synthetic"), - "issued_at", - now.minusSeconds(10), - "reference_expires_at", - now.plusSeconds(90), - "response_envelope_expires_at", - now.plusSeconds(120), - "status", - "REDEEMED", - "redemption_redeemer_workload_uri", - "spiffe://firemud/ns/test/sa/game-session-service", - "redemption_owner_attempt_id", - attempt, - "redemption_owner_fence", - 47L, - "redeemed_at", - now.minusSeconds(5), - "redemption_reference_fingerprint", - "arfp/v1/key-1/" + "a".repeat(64), - "redemption_authority_evidence_bundle", - json(authorityBundle)); - insert( - dsl, - "account_start_session_world_participations", - "participation_id", - world, - "control_plane_request_id", - requestId, - "original_post_authorization_tuple", - tuple, - "target_namespace", - "test", - "canonical_tenant_id", - tenant, - "canonical_game_instance_id", - instance, - "game_session_owner_attempt_id", - attempt, - "game_session_owner_fence", - 47L, - "preparation_input_json", - "{}", - "preparation_input_digest", - "sha256:" + hash(bytes("{}"))); - insert( - dsl, - "account_start_session_world_participation_sources", - "participation_id", - world, - "source_key", - evidence.key(), - "source_evidence", - evidence.canonicalBytes()); - insert( - dsl, - "account_start_session_world_original_attempt_evidence", - "participation_id", - world, - "target_namespace", - "test", - "game_session_owner_mutation_id", - mutation, - "game_session_owner_attempt_id", - attempt, - "game_session_owner_fence", - 47L, - "original_lease_expires_at", - expiry, - "original_response_bytes", - bytes("synthetic-observation"), - "original_response_digest", - "sha256:" + hash(bytes("synthetic-observation"))); - insert( - dsl, - "account_start_session_world_participation_settlements", - "participation_id", - world, - "outcome", - "COMMITTED", - "world_execution_fence", - 1L, - "terminal_bytes", - bytes("synthetic-terminal"), - "terminal_digest", - "sha256:" + hash(bytes("synthetic-terminal"))); - dsl.execute("SET LOCAL session_replication_role = origin"); - }); + transaction.executeWithoutResult(status -> { + dsl.execute("SET LOCAL session_replication_role = replica"); + insert( + dsl, + "account_canonical_tenant_identity_claims", + "canonical_tenant_id", + tenant, + "identity_kind", + "APPROVED_RETAINED", + "source_operation_id", + UUID.randomUUID(), + "source_account_legacy_tenant_id", + 1L, + "source_target_namespace", + "test", + "source_game_row_id", + 1L, + "source_game_tenant_key", + tenant.toString()); + insert(dsl, "account_draft_authorization_source_locks", "source_key", evidence.key()); + insert( + dsl, + "account_start_session_authority_captures", + "control_plane_request_id", + requestId, + "account_uuid", + actor, + "tenant_uuid", + tenant, + "target_owner", + "game-session-service", + "logging_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "pre_authorization_tuple", + bytes("{}"), + "mutation_digest", + "c".repeat(64), + "control_ui_operation_id", + UUID.randomUUID(), + "control_ui_token_jti", + UUID.randomUUID(), + "control_ui_token_hash", + "d".repeat(64), + "control_ui_signer_receipt_sha256", + "e".repeat(64), + "issuance_fence", + 9L, + "issuance_fence_source_version", + 1L, + "captured_at", + capturedAt, + "snapshot_sha256", + hash(snapshot), + "canonical_snapshot_bytes", + snapshot, + "source_version", + 11L, + "source_fence", + 13L, + "linearization", + "17", + "canonical_sha256", + hash(bytes("{}")), + "canonical_capture_bytes", + bytes("{}")); + insert( + dsl, + "account_start_session_operator_authorizations", + "control_plane_request_id", + requestId, + "pre_authorization_tuple", + bytes("{}"), + "mutation_digest", + "c".repeat(64), + "issuance_workload_uri", + "spiffe://firemud/ns/test/sa/logging-admin-service", + "reservation_owner_id", + UUID.randomUUID(), + "reservation_claim_fence", + 7L, + "issuance_operation_id", + issuance, + "issuance_fence", + 9L, + "bundle_version", + "authorityEvidenceBundle/v1", + "bundle_source_version", + "11", + "bundle_source_fence", + "13", + "bundle_linearization", + "17", + "authority_evidence_bundle", + json(authorityBundle), + "authorization_reference_fingerprint", + "arfp/v1/key-1/" + "a".repeat(64), + "encrypted_response_envelope", + bytes("synthetic"), + "issued_at", + now.minusSeconds(10), + "reference_expires_at", + now.plusSeconds(90), + "response_envelope_expires_at", + now.plusSeconds(120), + "status", + "REDEEMED", + "redemption_redeemer_workload_uri", + "spiffe://firemud/ns/test/sa/game-session-service", + "redemption_owner_attempt_id", + attempt, + "redemption_owner_fence", + 47L, + "redeemed_at", + now.minusSeconds(5), + "redemption_reference_fingerprint", + "arfp/v1/key-1/" + "a".repeat(64), + "redemption_authority_evidence_bundle", + json(authorityBundle)); + insert( + dsl, + "account_start_session_world_participations", + "participation_id", + world, + "control_plane_request_id", + requestId, + "original_post_authorization_tuple", + tuple, + "target_namespace", + "test", + "canonical_tenant_id", + tenant, + "canonical_game_instance_id", + instance, + "game_session_owner_attempt_id", + attempt, + "game_session_owner_fence", + 47L, + "preparation_input_json", + "{}", + "preparation_input_digest", + "sha256:" + hash(bytes("{}"))); + insert( + dsl, + "account_start_session_world_participation_sources", + "participation_id", + world, + "source_key", + evidence.key(), + "source_evidence", + evidence.canonicalBytes()); + insert( + dsl, + "account_start_session_world_original_attempt_evidence", + "participation_id", + world, + "target_namespace", + "test", + "game_session_owner_mutation_id", + mutation, + "game_session_owner_attempt_id", + attempt, + "game_session_owner_fence", + 47L, + "original_lease_expires_at", + expiry, + "original_response_bytes", + bytes("synthetic-observation"), + "original_response_digest", + "sha256:" + hash(bytes("synthetic-observation"))); + insert( + dsl, + "account_start_session_world_participation_settlements", + "participation_id", + world, + "outcome", + "COMMITTED", + "world_execution_fence", + 1L, + "terminal_bytes", + bytes("synthetic-terminal"), + "terminal_digest", + "sha256:" + hash(bytes("synthetic-terminal"))); + dsl.execute("SET LOCAL session_replication_role = origin"); + }); return fixture; } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java index ba7d05fdbe..553c14dda0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java @@ -116,23 +116,17 @@ void realPostgresCreateRetryAndRedemptionRetainTheOriginalAuthorityRecord() { assertThat(retainedAfterRedemption.bundleReference().linearization()).isEqualTo("123456789"); assertImmutableGuardRejected( () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "UPDATE account_start_session_operator_authorizations " - + "SET bundle_linearization = ? WHERE control_plane_request_id = ?", - "123456788", - REQUEST_ID)), + context.inTransactionWithoutResult(() -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET bundle_linearization = ? WHERE control_plane_request_id = ?", + "123456788", + REQUEST_ID)), "StartSession authorization evidence is immutable except one exact redemption " + "or expired envelope erasure"); assertThat( - context.inTransaction( - () -> - context - .repository - .findByControlPlaneRequestId(REQUEST_ID) - .orElseThrow() - .status())) + context.inTransaction(() -> + context.repository.findByControlPlaneRequestId(REQUEST_ID).orElseThrow().status())) .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); } @@ -232,19 +226,18 @@ void realPostgresEnforcesCanonicalPositiveLongRangeForBundleSourceFence() { assertThatThrownBy( () -> insertCandidateWithSourceFence(context, candidate, invalidSourceFence)) .isInstanceOf(IntegrityConstraintViolationException.class) - .satisfies( - failure -> { - SQLException sqlFailure = findSqlException(failure); - assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); - if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { - throw new AssertionError( - "Source-fence rejection must be a PostgreSQL exception", sqlFailure); - } - var serverError = postgresFailure.getServerErrorMessage(); - assertThat(serverError).isNotNull(); - assertThat(serverError.getConstraint()) - .isEqualTo("account_ss_operator_bundle_source_fence_canonical_check"); - }); + .satisfies(failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); + if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { + throw new AssertionError( + "Source-fence rejection must be a PostgreSQL exception", sqlFailure); + } + var serverError = postgresFailure.getServerErrorMessage(); + assertThat(serverError).isNotNull(); + assertThat(serverError.getConstraint()) + .isEqualTo("account_ss_operator_bundle_source_fence_canonical_check"); + }); assertThat(context.countRows()).isEqualTo(beforeInvalidFence); } } @@ -495,10 +488,8 @@ void realPostgresFingerprintConstraintAllowsMaximumKeyIdAndRejectsDot() { .isTrue(); assertThat( context - .inTransaction( - () -> - context.repository.redeemExact( - redemption(maximumKeyId, OWNER_ATTEMPT_ID, 11L))) + .inTransaction(() -> + context.repository.redeemExact(redemption(maximumKeyId, OWNER_ATTEMPT_ID, 11L))) .replay()) .isFalse(); @@ -511,43 +502,40 @@ void realPostgresFingerprintConstraintAllowsMaximumKeyIdAndRejectsDot() { "arfp/v1/key.with.dot/" + "b".repeat(64), UUID.randomUUID()); - assertThatThrownBy( - () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "INSERT INTO account_start_session_operator_authorizations " - + "(control_plane_request_id, pre_authorization_tuple, " - + "mutation_digest, issuance_workload_uri, reservation_owner_id, " - + "reservation_claim_fence, " - + "issuance_operation_id, issuance_fence, bundle_version, " - + "bundle_source_version, bundle_source_fence, " - + "bundle_linearization, authority_evidence_bundle, " - + "authorization_reference_fingerprint, " - + "encrypted_response_envelope, issued_at, reference_expires_at, " - + "response_envelope_expires_at, status) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " - + "'ISSUED')", - dottedKeyId.controlPlaneRequestId(), - dottedKeyId.preAuthorizationTuple(), - dottedKeyId.mutationDigest(), - dottedKeyId.issuanceWorkloadUri(), - dottedKeyId.reservationOwnerId(), - dottedKeyId.reservationClaimFence(), - dottedKeyId.issuanceOperationId(), - dottedKeyId.issuanceFence(), - dottedKeyId.bundleReference().bundleVersion(), - dottedKeyId.bundleReference().sourceVersion(), - dottedKeyId.bundleReference().sourceFence(), - dottedKeyId.bundleReference().linearization(), - dottedKeyId.authorityEvidenceBundle(), - dottedKeyId.authorizationReferenceFingerprint(), - dottedKeyId.encryptedResponseEnvelope(), - OffsetDateTime.ofInstant(dottedKeyId.issuedAt(), ZoneOffset.UTC), - OffsetDateTime.ofInstant( - dottedKeyId.referenceExpiresAt(), ZoneOffset.UTC), - OffsetDateTime.ofInstant( - dottedKeyId.responseEnvelopeExpiresAt(), ZoneOffset.UTC)))) + assertThatThrownBy(() -> + context.inTransactionWithoutResult(() -> + context.transactionDsl.execute( + "INSERT INTO account_start_session_operator_authorizations " + + "(control_plane_request_id, pre_authorization_tuple, " + + "mutation_digest, issuance_workload_uri, reservation_owner_id, " + + "reservation_claim_fence, " + + "issuance_operation_id, issuance_fence, bundle_version, " + + "bundle_source_version, bundle_source_fence, " + + "bundle_linearization, authority_evidence_bundle, " + + "authorization_reference_fingerprint, " + + "encrypted_response_envelope, issued_at, reference_expires_at, " + + "response_envelope_expires_at, status) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "'ISSUED')", + dottedKeyId.controlPlaneRequestId(), + dottedKeyId.preAuthorizationTuple(), + dottedKeyId.mutationDigest(), + dottedKeyId.issuanceWorkloadUri(), + dottedKeyId.reservationOwnerId(), + dottedKeyId.reservationClaimFence(), + dottedKeyId.issuanceOperationId(), + dottedKeyId.issuanceFence(), + dottedKeyId.bundleReference().bundleVersion(), + dottedKeyId.bundleReference().sourceVersion(), + dottedKeyId.bundleReference().sourceFence(), + dottedKeyId.bundleReference().linearization(), + dottedKeyId.authorityEvidenceBundle(), + dottedKeyId.authorizationReferenceFingerprint(), + dottedKeyId.encryptedResponseEnvelope(), + OffsetDateTime.ofInstant(dottedKeyId.issuedAt(), ZoneOffset.UTC), + OffsetDateTime.ofInstant(dottedKeyId.referenceExpiresAt(), ZoneOffset.UTC), + OffsetDateTime.ofInstant( + dottedKeyId.responseEnvelopeExpiresAt(), ZoneOffset.UTC)))) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(context.countRows()).isEqualTo(1); } @@ -562,25 +550,23 @@ void concurrentExactIssuanceRetriesReturnOneOriginalOutput() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(2); try { Future first = - executor.submit( - () -> { - ready.countDown(); - if (!start.await(5, TimeUnit.SECONDS)) { - throw new IllegalStateException("Timed out waiting to race exact issuance retry"); - } - return context.inTransaction( - () -> context.repository.createOrReadExact(firstCandidate)); - }); + executor.submit(() -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to race exact issuance retry"); + } + return context.inTransaction( + () -> context.repository.createOrReadExact(firstCandidate)); + }); Future second = - executor.submit( - () -> { - ready.countDown(); - if (!start.await(5, TimeUnit.SECONDS)) { - throw new IllegalStateException("Timed out waiting to race exact issuance retry"); - } - return context.inTransaction( - () -> context.repository.createOrReadExact(secondCandidate)); - }); + executor.submit(() -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to race exact issuance retry"); + } + return context.inTransaction( + () -> context.repository.createOrReadExact(secondCandidate)); + }); assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); start.countDown(); var firstResult = first.get(10, TimeUnit.SECONDS); @@ -626,10 +612,9 @@ void changedTupleOrReservationBindingConflictsAndMalformedTupleNeverWrites() { RESERVATION_OWNER_ID, candidate.reservationClaimFence() + 1L); - assertThatThrownBy( - () -> - context.inTransaction( - () -> context.repository.createOrReadExact(changedTupleCandidate))) + assertThatThrownBy(() -> + context.inTransaction( + () -> context.repository.createOrReadExact(changedTupleCandidate))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("conflicts"); assertThatThrownBy( @@ -716,50 +701,44 @@ void expiredReferenceCannotBeConsumedAndSqlGuardsRetainEvidence() { assertImmutableGuardRejected( () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "UPDATE account_start_session_operator_authorizations " - + "SET authority_evidence_bundle = ? WHERE control_plane_request_id = ?", - bytes("rewritten"), - REQUEST_ID)), + context.inTransactionWithoutResult(() -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET authority_evidence_bundle = ? WHERE control_plane_request_id = ?", + bytes("rewritten"), + REQUEST_ID)), "StartSession authorization evidence is immutable except one exact redemption " + "or expired envelope erasure"); assertImmutableGuardRejected( () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "DELETE FROM account_start_session_operator_authorizations " - + "WHERE control_plane_request_id = ?", - REQUEST_ID)), + context.inTransactionWithoutResult(() -> + context.transactionDsl.execute( + "DELETE FROM account_start_session_operator_authorizations " + + "WHERE control_plane_request_id = ?", + REQUEST_ID)), "StartSession operator authorization evidence cannot be deleted"); - assertThatThrownBy( - () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "TRUNCATE account_start_session_operator_authorizations"))) + assertThatThrownBy(() -> + context.inTransactionWithoutResult(() -> + context.transactionDsl.execute( + "TRUNCATE account_start_session_operator_authorizations"))) .isInstanceOf(org.jooq.exception.DataAccessException.class) - .satisfies( - failure -> { - SQLException sqlFailure = findSqlException(failure); - assertThat(sqlFailure.getSQLState()).isEqualTo("0A000"); - if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { - throw new AssertionError( - "Foreign-key truncate rejection must be a PostgreSQL exception", sqlFailure); - } - var serverError = postgresFailure.getServerErrorMessage(); - assertThat(serverError).isNotNull(); - assertThat(serverError.getMessage()) - .isEqualTo("cannot truncate a table referenced in a foreign key constraint"); - }); + .satisfies(failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("0A000"); + if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { + throw new AssertionError( + "Foreign-key truncate rejection must be a PostgreSQL exception", sqlFailure); + } + var serverError = postgresFailure.getServerErrorMessage(); + assertThat(serverError).isNotNull(); + assertThat(serverError.getMessage()) + .isEqualTo("cannot truncate a table referenced in a foreign key constraint"); + }); assertImmutableGuardRejected( () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "TRUNCATE account_start_session_operator_authorizations CASCADE")), + context.inTransactionWithoutResult(() -> + context.transactionDsl.execute( + "TRUNCATE account_start_session_operator_authorizations CASCADE")), "StartSession operator authorization evidence cannot be truncated"); var retained = @@ -783,41 +762,36 @@ void responseEnvelopeErasureUsesDatabaseWallClockAndPreservesRedeemedCompactEvid databaseNow.plusSeconds(12)); context.inTransaction(() -> context.repository.createOrReadExact(candidate)); - assertThatThrownBy( - () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "UPDATE account_start_session_operator_authorizations " - + "SET encrypted_response_envelope = NULL " - + "WHERE control_plane_request_id = ?", - candidate.controlPlaneRequestId()))) + assertThatThrownBy(() -> + context.inTransactionWithoutResult(() -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET encrypted_response_envelope = NULL " + + "WHERE control_plane_request_id = ?", + candidate.controlPlaneRequestId()))) .isInstanceOf(IntegrityConstraintViolationException.class); var erased = - context.inTransaction( - () -> { - assertThat( - ((OffsetDateTime) - context.transactionDsl.fetchValue("SELECT transaction_timestamp()")) - .toInstant()) - .isBefore(candidate.responseEnvelopeExpiresAt()); - var redeemed = - context.repository.redeemExact( - redemption( - candidate, OWNER_ATTEMPT_ID, 11L, candidate.issuedAt().plusSeconds(1))); - assertThat(redeemed.replay()).isFalse(); - assertThatThrownBy( - () -> - context.repository.eraseExpiredResponseEnvelope( - candidate.controlPlaneRequestId())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("evidence unavailable"); - - waitUntilDatabaseTime(context, candidate.responseEnvelopeExpiresAt()); - return context.repository.eraseExpiredResponseEnvelope( - candidate.controlPlaneRequestId()); - }); + context.inTransaction(() -> { + assertThat( + ((OffsetDateTime) + context.transactionDsl.fetchValue("SELECT transaction_timestamp()")) + .toInstant()) + .isBefore(candidate.responseEnvelopeExpiresAt()); + var redeemed = + context.repository.redeemExact( + redemption( + candidate, OWNER_ATTEMPT_ID, 11L, candidate.issuedAt().plusSeconds(1))); + assertThat(redeemed.replay()).isFalse(); + assertThatThrownBy(() -> + context.repository.eraseExpiredResponseEnvelope( + candidate.controlPlaneRequestId())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("evidence unavailable"); + + waitUntilDatabaseTime(context, candidate.responseEnvelopeExpiresAt()); + return context.repository.eraseExpiredResponseEnvelope(candidate.controlPlaneRequestId()); + }); assertThat(erased.erasedNow()).isTrue(); assertThat(erased.issuance().encryptedResponseEnvelope()).isNull(); @@ -843,33 +817,28 @@ void responseEnvelopeErasureUsesDatabaseWallClockAndPreservesRedeemedCompactEvid .containsExactly(candidate.authorityEvidenceBundle()); var retry = - context.inTransaction( - () -> - context.repository.eraseExpiredResponseEnvelope(candidate.controlPlaneRequestId())); + context.inTransaction(() -> + context.repository.eraseExpiredResponseEnvelope(candidate.controlPlaneRequestId())); assertThat(retry.erasedNow()).isFalse(); assertThat(retry.issuance().responseEnvelopeErasedAt()) .isEqualTo(erased.issuance().responseEnvelopeErasedAt()); - assertThatThrownBy( - () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "UPDATE account_start_session_operator_authorizations " - + "SET encrypted_response_envelope = ? " - + "WHERE control_plane_request_id = ?", - candidate.encryptedResponseEnvelope(), - candidate.controlPlaneRequestId()))) + assertThatThrownBy(() -> + context.inTransactionWithoutResult(() -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET encrypted_response_envelope = ? " + + "WHERE control_plane_request_id = ?", + candidate.encryptedResponseEnvelope(), + candidate.controlPlaneRequestId()))) .isInstanceOf(IntegrityConstraintViolationException.class); - assertThatThrownBy( - () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "UPDATE account_start_session_operator_authorizations " - + "SET redemption_owner_fence = redemption_owner_fence + 1 " - + "WHERE control_plane_request_id = ?", - candidate.controlPlaneRequestId()))) + assertThatThrownBy(() -> + context.inTransactionWithoutResult(() -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET redemption_owner_fence = redemption_owner_fence + 1 " + + "WHERE control_plane_request_id = ?", + candidate.controlPlaneRequestId()))) .isInstanceOf(IntegrityConstraintViolationException.class); Instant expiredAt = canonicalDatabaseNow(context); @@ -878,35 +847,32 @@ void responseEnvelopeErasureUsesDatabaseWallClockAndPreservesRedeemedCompactEvid IssuanceCandidate expiredUnredeemed = expiredCandidate(expiredTuple, expiredAt); context.inTransaction(() -> context.repository.createOrReadExact(expiredUnredeemed)); Instant redeemedAt = expiredUnredeemed.issuedAt().plusSeconds(1); - assertThatThrownBy( - () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "UPDATE account_start_session_operator_authorizations " - + "SET encrypted_response_envelope = NULL, status = 'REDEEMED', " - + "redemption_redeemer_workload_uri = ?, " - + "redemption_owner_attempt_id = ?, redemption_owner_fence = ?, " - + "redeemed_at = CAST(? AS TIMESTAMPTZ), " - + "redemption_reference_fingerprint = ?, " - + "redemption_authority_evidence_bundle = ? " - + "WHERE control_plane_request_id = ?", - OWNER_URI, - OWNER_ATTEMPT_ID, - 11L, - OffsetDateTime.ofInstant(redeemedAt, ZoneOffset.UTC), - expiredUnredeemed.authorizationReferenceFingerprint(), - expiredUnredeemed.authorityEvidenceBundle(), - expiredUnredeemed.controlPlaneRequestId()))) + assertThatThrownBy(() -> + context.inTransactionWithoutResult(() -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET encrypted_response_envelope = NULL, status = 'REDEEMED', " + + "redemption_redeemer_workload_uri = ?, " + + "redemption_owner_attempt_id = ?, redemption_owner_fence = ?, " + + "redeemed_at = CAST(? AS TIMESTAMPTZ), " + + "redemption_reference_fingerprint = ?, " + + "redemption_authority_evidence_bundle = ? " + + "WHERE control_plane_request_id = ?", + OWNER_URI, + OWNER_ATTEMPT_ID, + 11L, + OffsetDateTime.ofInstant(redeemedAt, ZoneOffset.UTC), + expiredUnredeemed.authorizationReferenceFingerprint(), + expiredUnredeemed.authorityEvidenceBundle(), + expiredUnredeemed.controlPlaneRequestId()))) .isInstanceOf(IntegrityConstraintViolationException.class); var retained = - context.inTransaction( - () -> - context - .repository - .findByControlPlaneRequestId(candidate.controlPlaneRequestId()) - .orElseThrow()); + context.inTransaction(() -> + context + .repository + .findByControlPlaneRequestId(candidate.controlPlaneRequestId()) + .orElseThrow()); assertThat(retained.encryptedResponseEnvelope()).isNull(); assertThat(retained.responseEnvelopeErasedAt()) .isEqualTo(erased.issuance().responseEnvelopeErasedAt()); @@ -970,25 +936,22 @@ void v1262RetainedMaximumLegacyEnvelopeSurvivesForwardSizeMigration() { assertThat(retained.status()) .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.ISSUED); - assertThatThrownBy( - () -> - context.inTransactionWithoutResult( - () -> - context.transactionDsl.execute( - "UPDATE account_start_session_operator_authorizations " - + "SET authority_evidence_bundle = ? " - + "WHERE control_plane_request_id = ?", - bytes("changed-retained-evidence"), - legacy.controlPlaneRequestId()))) + assertThatThrownBy(() -> + context.inTransactionWithoutResult(() -> + context.transactionDsl.execute( + "UPDATE account_start_session_operator_authorizations " + + "SET authority_evidence_bundle = ? " + + "WHERE control_plane_request_id = ?", + bytes("changed-retained-evidence"), + legacy.controlPlaneRequestId()))) .isInstanceOf(IntegrityConstraintViolationException.class); assertThat( - context.inTransaction( - () -> - context - .repository - .findByControlPlaneRequestId(legacy.controlPlaneRequestId()) - .orElseThrow() - .encryptedResponseEnvelope())) + context.inTransaction(() -> + context + .repository + .findByControlPlaneRequestId(legacy.controlPlaneRequestId()) + .orElseThrow() + .encryptedResponseEnvelope())) .containsExactly(retainedLegacyEnvelope); } @@ -1001,16 +964,15 @@ void v1263FailsClosedWhenLegacyEnvelopeSizeGuardIsAmbiguous() { + "CHECK (octet_length(encrypted_response_envelope) BETWEEN 1 AND 65536)"); assertThat(legacyEnvelopeSizeGuardCount(context)).isEqualTo(2L); - assertThatThrownBy( - () -> - Flyway.configure() - .dataSource(context.dataSource) - .schemas(context.schema) - .defaultSchema(context.schema) - .placeholders(Map.of("serviceSchema", context.schema)) - .locations("classpath:db/migration") - .load() - .migrate()) + assertThatThrownBy(() -> + Flyway.configure() + .dataSource(context.dataSource) + .schemas(context.schema) + .defaultSchema(context.schema) + .placeholders(Map.of("serviceSchema", context.schema)) + .locations("classpath:db/migration") + .load() + .migrate()) .isInstanceOf(FlywayException.class) .hasMessageContaining("V126.3"); @@ -1582,18 +1544,17 @@ private static void assertImmutableGuardRejected( ThrowingCallable action, String expectedDiagnostic) { assertThatThrownBy(action) .isInstanceOf(IntegrityConstraintViolationException.class) - .satisfies( - failure -> { - SQLException sqlFailure = findSqlException(failure); - assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); - if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { - throw new AssertionError( - "Immutable guard rejection must be a PostgreSQL exception", sqlFailure); - } - var serverError = postgresFailure.getServerErrorMessage(); - assertThat(serverError).isNotNull(); - assertThat(serverError.getMessage()).isEqualTo(expectedDiagnostic); - }); + .satisfies(failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); + if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { + throw new AssertionError( + "Immutable guard rejection must be a PostgreSQL exception", sqlFailure); + } + var serverError = postgresFailure.getServerErrorMessage(); + assertThat(serverError).isNotNull(); + assertThat(serverError.getMessage()).isEqualTo(expectedDiagnostic); + }); } private static SQLException findSqlException(Throwable failure) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java index f0e200adf9..47ca33b3df 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java @@ -113,11 +113,8 @@ void exactRetryPreservesFirstBytesAndExpiryAfterLockWaitCannotCreateOrRefreshEvi assertThat(exactRetry.result().request().readRequestId()) .isEqualTo(first.result().request().readRequestId()); StoredEvidence current = - transaction.execute( - status -> - repository - .findCurrentExact(parent, request(fixture, UUID.randomUUID())) - .orElseThrow()); + transaction.execute(status -> + repository.findCurrentExact(parent, request(fixture, UUID.randomUUID())).orElseThrow()); assertThat(current.originalResponseBytes()).containsExactly(first.originalResponseBytes()); assertThat(current.originalResponseDigest()).isEqualTo(first.originalResponseDigest()); @@ -132,10 +129,8 @@ void exactRetryPreservesFirstBytesAndExpiryAfterLockWaitCannotCreateOrRefreshEvi OWNER_FENCE), retryExpiry, fixture.accountProjection()); - assertThatThrownBy( - () -> - transaction.execute( - status -> repository.retainCurrentExact(parent, changedMutation))) + assertThatThrownBy(() -> + transaction.execute(status -> repository.retainCurrentExact(parent, changedMutation))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("conflicts"); @@ -143,18 +138,16 @@ void exactRetryPreservesFirstBytesAndExpiryAfterLockWaitCannotCreateOrRefreshEvi assertLeaseExpiresWhileParentLocked( dsl, transaction, repository, parent, fixture, exactRetryObservation); - assertThatThrownBy( - () -> - transaction.execute( - status -> repository.findCurrentExact(parent, freshCorrelation).orElseThrow())) + assertThatThrownBy(() -> + transaction.execute( + status -> repository.findCurrentExact(parent, freshCorrelation).orElseThrow())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("unavailable"); StoredEvidence historical = - transaction.execute( - status -> - repository - .findHistoricalExact(parent, request(fixture, UUID.randomUUID())) - .orElseThrow()); + transaction.execute(status -> + repository + .findHistoricalExact(parent, request(fixture, UUID.randomUUID())) + .orElseThrow()); assertThat(historical.originalLeaseExpiresAt()).isEqualTo(retryExpiry); assertThat(historical.originalResponseBytes()).containsExactly(first.originalResponseBytes()); } @@ -254,21 +247,16 @@ void settledParticipationCannotReceiveNewObservation() { Fixture fixture = fixture(); UUID participationId = UUID.randomUUID(); StoredParticipation parent = - transaction.execute( - status -> { - StoredParticipation inserted = - insertSyntheticParent(dsl, fixture, participationId, true); - return inserted; - }); - - assertThatThrownBy( - () -> - transaction.execute( - status -> - repository.retainCurrentExact( - parent, - observation( - fixture, UUID.randomUUID(), databaseNow(dsl).plusSeconds(30))))) + transaction.execute(status -> { + StoredParticipation inserted = insertSyntheticParent(dsl, fixture, participationId, true); + return inserted; + }); + + assertThatThrownBy(() -> + transaction.execute(status -> + repository.retainCurrentExact( + parent, + observation(fixture, UUID.randomUUID(), databaseNow(dsl).plusSeconds(30))))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("unavailable"); } @@ -301,18 +289,17 @@ private static void assertAppendOnly(DSLContext dsl, UUID participationId) { private static void assertGuardRejected( org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String expectedDiagnostic) { assertThatThrownBy(action) - .satisfies( - failure -> { - SQLException sqlFailure = findSqlException(failure); - assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); - if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { - throw new AssertionError( - "Attempt evidence guard rejection must be a PostgreSQL exception", sqlFailure); - } - var serverError = postgresFailure.getServerErrorMessage(); - assertThat(serverError).isNotNull(); - assertThat(serverError.getMessage()).isEqualTo(expectedDiagnostic); - }); + .satisfies(failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); + if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { + throw new AssertionError( + "Attempt evidence guard rejection must be a PostgreSQL exception", sqlFailure); + } + var serverError = postgresFailure.getServerErrorMessage(); + assertThat(serverError).isNotNull(); + assertThat(serverError.getMessage()).isEqualTo(expectedDiagnostic); + }); } private static SQLException findSqlException(Throwable failure) { @@ -335,27 +322,24 @@ private static void assertLeaseExpiresWhileParentLocked( CountDownLatch releaseParent = new CountDownLatch(1); try { Future holder = - executor.submit( - () -> - transaction.execute( - status -> { - dsl.fetchOne( - "SELECT participation_id FROM account_start_session_world_participations " - + "WHERE participation_id = ? FOR UPDATE", - parent.participationId()); - parentLocked.countDown(); - await(releaseParent); - return null; - })); + executor.submit(() -> + transaction.execute(status -> { + dsl.fetchOne( + "SELECT participation_id FROM account_start_session_world_participations " + + "WHERE participation_id = ? FOR UPDATE", + parent.participationId()); + parentLocked.countDown(); + await(releaseParent); + return null; + })); assertTrue(parentLocked.await(5, TimeUnit.SECONDS), "parent lock holder did not start"); CountDownLatch writerStarted = new CountDownLatch(1); Future writer = - executor.submit( - () -> { - writerStarted.countDown(); - return transaction.execute( - status -> repository.retainCurrentExact(parent, observation)); - }); + executor.submit(() -> { + writerStarted.countDown(); + return transaction.execute( + status -> repository.retainCurrentExact(parent, observation)); + }); assertTrue(writerStarted.await(5, TimeUnit.SECONDS), "evidence writer did not start"); awaitBlockedOnParentLock(dsl); while (observation.originalLeaseExpiresAt().isAfter(databaseNow(dsl))) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java index 6925708488..bf80aa01ed 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java @@ -157,27 +157,25 @@ void originalTupleRecoversCommittedParticipationAfterLostResponseAndLeaseExpiry( // The Game Session point-in-time observation is stipulated; Account's original issue, // redemption, source capture, acquisition gates, and PostgreSQL retention are real. var acquisition = - proof.worldParticipationAcquisitionService( - request -> - new Result( - request, - leaseExpiresAt, - StartSessionAccountRedemptionProjection.fromOriginalTuple( - original.originalTuple()))); + proof.worldParticipationAcquisitionService(request -> + new Result( + request, + leaseExpiresAt, + StartSessionAccountRedemptionProjection.fromOriginalTuple( + original.originalTuple()))); // Discard the owner response to model transport loss. The database row is used only as a // physical proof oracle; it is not supplied to the historical lookup request. - withWorldPeer( - () -> - acquisition.acquire( - new AcquisitionRequest( - originalTupleBytes, - gameSessionMutationId, - gameSessionAttemptId, - gameSessionOwnerFence, - gameInstanceId, - preparationInput, - preparationDigest))); + withWorldPeer(() -> + acquisition.acquire( + new AcquisitionRequest( + originalTupleBytes, + gameSessionMutationId, + gameSessionAttemptId, + gameSessionOwnerFence, + gameInstanceId, + preparationInput, + preparationDigest))); var sql = physicalSql(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword(), proof); @@ -198,11 +196,10 @@ void originalTupleRecoversCommittedParticipationAfterLostResponseAndLeaseExpiry( var attemptRepository = new AccountStartSessionWorldOriginalAttemptEvidenceRepository(sql.dsl()); var expiredParticipation = - transaction.execute( - status -> - new AccountStartSessionWorldParticipationRepository(sql.dsl()) - .findHistoricalExact(committedParticipationId, committedParticipationFence) - .orElseThrow()); + transaction.execute(status -> + new AccountStartSessionWorldParticipationRepository(sql.dsl()) + .findHistoricalExact(committedParticipationId, committedParticipationFence) + .orElseThrow()); var expiredAttemptRequest = new Request( UUID.randomUUID(), @@ -211,21 +208,18 @@ void originalTupleRecoversCommittedParticipationAfterLostResponseAndLeaseExpiry( gameSessionAttemptId, gameSessionMutationId, gameSessionOwnerFence); - assertThatThrownBy( - () -> - transaction.execute( - status -> - attemptRepository - .findCurrentExact(expiredParticipation, expiredAttemptRequest) - .orElseThrow())) + assertThatThrownBy(() -> + transaction.execute(status -> + attemptRepository + .findCurrentExact(expiredParticipation, expiredAttemptRequest) + .orElseThrow())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("unavailable"); var retainedAttempt = - transaction.execute( - status -> - attemptRepository - .findHistoricalExact(expiredParticipation, expiredAttemptRequest) - .orElseThrow()); + transaction.execute(status -> + attemptRepository + .findHistoricalExact(expiredParticipation, expiredAttemptRequest) + .orElseThrow()); assertThat(retainedAttempt.originalLeaseExpiresAt()).isEqualTo(leaseExpiresAt); assertThat(retainedAttempt.result().request().canonicalPostAuthorizationTuple()) .containsExactly(originalTupleBytes); @@ -442,18 +436,17 @@ void latestMigrationsInstallParticipationGuardsAndPreserveAssembledSourceExclusi private static void assertGuardRejected( org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String expectedDiagnostic) { assertThatThrownBy(action) - .satisfies( - failure -> { - SQLException sqlFailure = findSqlException(failure); - assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); - if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { - throw new AssertionError( - "Participation guard rejection must be a PostgreSQL exception", sqlFailure); - } - var serverError = postgresFailure.getServerErrorMessage(); - assertThat(serverError).isNotNull(); - assertThat(serverError.getMessage()).isEqualTo(expectedDiagnostic); - }); + .satisfies(failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); + if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { + throw new AssertionError( + "Participation guard rejection must be a PostgreSQL exception", sqlFailure); + } + var serverError = postgresFailure.getServerErrorMessage(); + assertThat(serverError).isNotNull(); + assertThat(serverError.getMessage()).isEqualTo(expectedDiagnostic); + }); } private static SQLException findSqlException(Throwable failure) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentPostgresIntegrationTest.java index 22f2b6903d..dd77303baa 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentPostgresIntegrationTest.java @@ -201,47 +201,42 @@ void claimRollbackAndStaleReservedWalletRetainOneTerminalOperatorItem( Seed seed = seed(c); var created = create(c, request(seed, UUID.randomUUID(), 1, null)); c.tx() - .executeWithoutResult( - s -> { - lifecycle(c).claim(created.requestId(), 1, UUID.randomUUID()); - s.setRollbackOnly(); - }); + .executeWithoutResult(s -> { + lifecycle(c).claim(created.requestId(), 1, UUID.randomUUID()); + s.setRollbackOnly(); + }); assertThat(count(c, "subscription_provisioning_work")).isZero(); assertThat(count(c, "subscription_provisioning_attempts")).isZero(); var pending = c.repository().findCurrentByTenant(seed.tenant()).orElseThrow(); assertThat(pending.status()).isEqualTo("pending"); var observed = c.tx() - .execute( - s -> - new AccountPaymentInstrumentRepository(c.dsl()) - .recordAvailability( - new AccountPaymentInstrumentRepository.AvailabilityObservation( - UUID.randomUUID(), - seed.instrument().instrumentUuid(), - seed.owner().accountUuid(), - 1L, - observedState, - seed.instrument().display(), - DIGEST))); + .execute(s -> + new AccountPaymentInstrumentRepository(c.dsl()) + .recordAvailability( + new AccountPaymentInstrumentRepository.AvailabilityObservation( + UUID.randomUUID(), + seed.instrument().instrumentUuid(), + seed.owner().accountUuid(), + 1L, + observedState, + seed.instrument().display(), + DIGEST))); // Upgrade the original pending intent and its changed wallet without recreating either row. configuration(c).load().migrate(); - assertThatThrownBy( - () -> - c.tx().execute(s -> lifecycle(c).claim(created.requestId(), 2, UUID.randomUUID()))) + assertThatThrownBy(() -> + c.tx().execute(s -> lifecycle(c).claim(created.requestId(), 2, UUID.randomUUID()))) .isInstanceOf(FenceRejectedException.class); // Provisioning boundaries use PostgreSQL clock_timestamp(); an injected Java clock cannot // move the database clock before this durable creation time. The wrong-version fence above // and rollback proof below exercise the supported database-owned claim boundaries. c.tx() - .executeWithoutResult( - s -> { - assertThat( - lifecycle(c).claim(created.requestId(), 1, UUID.randomUUID()).disposition()) - .isEqualTo( - AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); - s.setRollbackOnly(); - }); + .executeWithoutResult(s -> { + assertThat(lifecycle(c).claim(created.requestId(), 1, UUID.randomUUID()).disposition()) + .isEqualTo( + AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); + s.setRollbackOnly(); + }); assertThat(count(c, "subscription_provisioning_work")).isZero(); assertThat(count(c, "subscription_provisioning_operator_outbox")).isZero(); UUID firstAttempt = UUID.randomUUID(); @@ -336,10 +331,9 @@ void expiredIntentCreatesUnresolvedFailureWithoutClaimingProviderWork() { var expired = Objects.requireNonNull( c.tx() - .execute( - s -> - lifecycle(c, provisioningTimeout) - .claim(created.requestId(), 1, UUID.randomUUID()))); + .execute(s -> + lifecycle(c, provisioningTimeout) + .claim(created.requestId(), 1, UUID.randomUUID()))); assertThat(expired.disposition()) .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Disposition.TERMINAL_FAILURE); assertThat(expired.claim()).isNull(); @@ -563,10 +557,8 @@ private static void sleepUntil(Context c, Instant deadline) { var later = Objects.requireNonNull( c.tx() - .execute( - s -> - changedRepository.retainPending( - request(second, UUID.randomUUID(), 1, null)))); + .execute(s -> + changedRepository.retainPending(request(second, UUID.randomUUID(), 1, null)))); assertThat(later.planQuote()).isEqualTo(changedCatalog.resolve("basic-hosting")); assertThat(later.planQuote().digest()).isNotEqualTo(created.planQuote().digest()); assertThat(created.requestDigest()) @@ -603,11 +595,10 @@ void missingServerPlanConfigurationCreatesNoIntentReservationOrWorkItem() { Seed seed = seed(c); var unconfigured = new AccountSubscriptionIntentRepository(c.dsl(), new AccountHostingPlanCatalog(List.of())); - assertThatThrownBy( - () -> - c.tx() - .execute( - s -> unconfigured.retainPending(request(seed, UUID.randomUUID(), 1, null)))) + assertThatThrownBy(() -> + c.tx() + .execute( + s -> unconfigured.retainPending(request(seed, UUID.randomUUID(), 1, null)))) .isInstanceOf(AccountHostingPlanCatalog.PlanUnavailableException.class); assertThat(count(c, "subscription_create_operations")).isZero(); assertThat(count(c, "subscription")).isZero(); @@ -625,17 +616,16 @@ void directSqlQuoteBytesDigestAndProjectedFieldsMustAgreeAndRetainedQuoteCannotB "23514", () -> c.tx() - .executeWithoutResult( - s -> - insertBareOperationWithQuote( - c, - request, - seed, - UUID.randomUUID(), - UUID.randomUUID(), - quote, - quote.payload(), - "sha256:" + "0".repeat(64)))); + .executeWithoutResult(s -> + insertBareOperationWithQuote( + c, + request, + seed, + UUID.randomUUID(), + UUID.randomUUID(), + quote, + quote.payload(), + "sha256:" + "0".repeat(64)))); for (var changedFields : List.of( new AccountHostingPlanQuote( @@ -667,17 +657,16 @@ void directSqlQuoteBytesDigestAndProjectedFieldsMustAgreeAndRetainedQuoteCannotB "23514", () -> c.tx() - .executeWithoutResult( - s -> - insertBareOperationWithQuote( - c, - request, - seed, - UUID.randomUUID(), - UUID.randomUUID(), - changedFields, - quote.payload(), - quote.digest()))); + .executeWithoutResult(s -> + insertBareOperationWithQuote( + c, + request, + seed, + UUID.randomUUID(), + UUID.randomUUID(), + changedFields, + quote.payload(), + quote.digest()))); } byte[] alteredBytes = Arrays.copyOf(quote.payload(), quote.payload().length + 1); alteredBytes[alteredBytes.length - 1] = ' '; @@ -685,17 +674,16 @@ void directSqlQuoteBytesDigestAndProjectedFieldsMustAgreeAndRetainedQuoteCannotB "23514", () -> c.tx() - .executeWithoutResult( - s -> - insertBareOperationWithQuote( - c, - request, - seed, - UUID.randomUUID(), - UUID.randomUUID(), - quote, - alteredBytes, - quote.digest()))); + .executeWithoutResult(s -> + insertBareOperationWithQuote( + c, + request, + seed, + UUID.randomUUID(), + UUID.randomUUID(), + quote, + alteredBytes, + quote.digest()))); assertThat(count(c, "subscription_create_operations")).isZero(); var created = create(c, request); rejectSql( @@ -756,13 +744,12 @@ void unauditedOwnerAdvanceIsRefusedAndStaleOwnerCapturesCannotCreateIntent() { "23514", () -> c.tx() - .executeWithoutResult( - status -> - c.dsl() - .execute( - "UPDATE account_tenant_billing_owners SET owner_version = owner_version + 1, owner_generation = ? WHERE tenant_uuid = ?", - UUID.randomUUID(), - seed.tenant()))); + .executeWithoutResult(status -> + c.dsl() + .execute( + "UPDATE account_tenant_billing_owners SET owner_version = owner_version + 1, owner_generation = ? WHERE tenant_uuid = ?", + UUID.randomUUID(), + seed.tenant()))); assertThat( c.setup() .fetch( @@ -819,25 +806,23 @@ void commitRechecksSameTransactionOwnerAndWalletChangesAndClaimReadRejectsStaleR "23514", () -> c.tx() - .executeWithoutResult( - s -> { - c.repository().retainPending(request); - c.dsl() - .execute( - "UPDATE account_tenant_billing_owners SET owner_version = owner_version + 1, owner_generation = ? WHERE tenant_uuid = ?", - UUID.randomUUID(), - seed.tenant()); - })); + .executeWithoutResult(s -> { + c.repository().retainPending(request); + c.dsl() + .execute( + "UPDATE account_tenant_billing_owners SET owner_version = owner_version + 1, owner_generation = ? WHERE tenant_uuid = ?", + UUID.randomUUID(), + seed.tenant()); + })); assertThat(count(c, "subscription")).isZero(); rejectSql( "23514", () -> c.tx() - .executeWithoutResult( - s -> { - c.repository().retainPending(request); - advanceWallet(c, seed.instrument().instrumentUuid(), UUID.randomUUID()); - })); + .executeWithoutResult(s -> { + c.repository().retainPending(request); + advanceWallet(c, seed.instrument().instrumentUuid(), UUID.randomUUID()); + })); assertThat(count(c, "subscription_create_operations")).isZero(); create(c, request); c.tx() @@ -875,11 +860,10 @@ void canceledCurrentReplacementIsAtomicVersionedDistinctAndOneConcurrentReplacem 1, new ReplacementFence(original.subscriptionId(), canceled.rowVersion())); c.tx() - .executeWithoutResult( - s -> { - c.repository().retainPending(replacement); - s.setRollbackOnly(); - }); + .executeWithoutResult(s -> { + c.repository().retainPending(replacement); + s.setRollbackOnly(); + }); assertThat(c.repository().findCurrentByTenant(seed.tenant())).contains(canceled); assertThat(count(c, "subscription")).isOne(); assertThat(count(c, "subscription_current_observations")).isEqualTo(2); @@ -956,32 +940,29 @@ void directSqlRejectsIdentityMutationDuplicateCurrentProviderAndUnconfirmedActiv "23505", () -> c.tx() - .executeWithoutResult( - s -> - c.dsl() - .execute( - "UPDATE subscription SET provider_subscription_id = 'sub_duplicate', row_version = row_version + 1 WHERE subscription_id IN (?, ?)", - one.subscriptionId(), - two.subscriptionId()))); + .executeWithoutResult(s -> + c.dsl() + .execute( + "UPDATE subscription SET provider_subscription_id = 'sub_duplicate', row_version = row_version + 1 WHERE subscription_id IN (?, ?)", + one.subscriptionId(), + two.subscriptionId()))); rejectSql( "23503", () -> c.tx() - .executeWithoutResult( - s -> - c.dsl() - .execute( - "UPDATE subscription SET provider_subscription_id = 'sub_unmapped', row_version = row_version + 1 WHERE subscription_id = ?", - one.subscriptionId()))); + .executeWithoutResult(s -> + c.dsl() + .execute( + "UPDATE subscription SET provider_subscription_id = 'sub_unmapped', row_version = row_version + 1 WHERE subscription_id = ?", + one.subscriptionId()))); var duplicateTenant = request(first, UUID.randomUUID(), 1, null); rejectSql( "23514", () -> c.tx() - .executeWithoutResult( - s -> - insertBareOperation( - c, duplicateTenant, first, UUID.randomUUID(), UUID.randomUUID()))); + .executeWithoutResult(s -> + insertBareOperation( + c, duplicateTenant, first, UUID.randomUUID(), UUID.randomUUID()))); assertThat(indexDefinition(c, "uq_subscription_active_tenant")) .contains("UNIQUE", "superseded_at IS NULL"); assertThat( @@ -1010,23 +991,21 @@ void directSqlRejectsIdentityMutationDuplicateCurrentProviderAndUnconfirmedActiv "23503", () -> c.tx() - .executeWithoutResult( - s -> - insertBareOperation( - c, missingPair, empty, UUID.randomUUID(), UUID.randomUUID()))); + .executeWithoutResult(s -> + insertBareOperation( + c, missingPair, empty, UUID.randomUUID(), UUID.randomUUID()))); assertThat(c.repository().findCreation(missingPair.requestId())).isEmpty(); rejectSql( "23505", () -> c.tx() - .executeWithoutResult( - s -> - insertBareOperation( - c, - request(empty, UUID.randomUUID(), 1, null), - empty, - created.cleanupProviderIdentity(), - UUID.randomUUID()))); + .executeWithoutResult(s -> + insertBareOperation( + c, + request(empty, UUID.randomUUID(), 1, null), + empty, + created.cleanupProviderIdentity(), + UUID.randomUUID()))); for (String table : List.of( "subscription_create_operations", @@ -1057,27 +1036,26 @@ void directSqlRejectsIdentityMutationDuplicateCurrentProviderAndUnconfirmedActiv "23514", () -> c.tx() - .executeWithoutResult( - s -> { - c.repository().lockPendingForClaim(creation.requestId(), 1); - UUID resolution = UUID.randomUUID(); - c.dsl() - .execute( - "INSERT INTO subscription_provider_terminal_resolutions " - + "(resolution_id,request_id,subscription_id,cleanup_provider_identity,outcome,effective_at,evidence_digest) " - + "VALUES (?, ?, ?, ?, 'PROVIDER_ABSENT', ?::timestamptz, ?)", - resolution, - creation.requestId(), - creation.subscriptionId(), - creation.cleanupProviderIdentity(), - BOUNDARY, - DIGEST); - c.dsl() - .execute( - "UPDATE subscription SET status = 'canceled', terminal_resolution_id = ?, row_version = row_version + 1 WHERE subscription_id = ?", - resolution, - creation.subscriptionId()); - })); + .executeWithoutResult(s -> { + c.repository().lockPendingForClaim(creation.requestId(), 1); + UUID resolution = UUID.randomUUID(); + c.dsl() + .execute( + "INSERT INTO subscription_provider_terminal_resolutions " + + "(resolution_id,request_id,subscription_id,cleanup_provider_identity,outcome,effective_at,evidence_digest) " + + "VALUES (?, ?, ?, ?, 'PROVIDER_ABSENT', ?::timestamptz, ?)", + resolution, + creation.requestId(), + creation.subscriptionId(), + creation.cleanupProviderIdentity(), + BOUNDARY, + DIGEST); + c.dsl() + .execute( + "UPDATE subscription SET status = 'canceled', terminal_resolution_id = ?, row_version = row_version + 1 WHERE subscription_id = ?", + resolution, + creation.subscriptionId()); + })); assertThat(c.repository().findCurrentByTenant(seed.tenant()).orElseThrow().status()) .isEqualTo("pending"); assertThat(count(c, "subscription_provider_terminal_resolutions")).isZero(); @@ -1097,17 +1075,16 @@ void terminalCleanupAfterWalletAdvanceReleasesOnlyItsOriginalReservationWithoutR var advancedWallet = Objects.requireNonNull( c.tx() - .execute( - s -> - instruments.recordAvailability( - new AccountPaymentInstrumentRepository.AvailabilityObservation( - UUID.randomUUID(), - first.instrument().instrumentUuid(), - c.account(), - 1, - AccountPaymentInstrumentRecord.State.ATTACHABLE, - first.instrument().display(), - "sha256:" + "b".repeat(64))))); + .execute(s -> + instruments.recordAvailability( + new AccountPaymentInstrumentRepository.AvailabilityObservation( + UUID.randomUUID(), + first.instrument().instrumentUuid(), + c.account(), + 1, + AccountPaymentInstrumentRecord.State.ATTACHABLE, + first.instrument().display(), + "sha256:" + "b".repeat(64))))); assertThat(advancedWallet.rowVersion()).isEqualTo(2); Seed otherTenant = seed(c); Seed sharedWallet = new Seed(otherTenant.tenant(), otherTenant.owner(), first.instrument()); @@ -1154,31 +1131,30 @@ void terminalCleanupAfterWalletAdvanceReleasesOnlyItsOriginalReservationWithoutR // An old request/subscription tuple or the originally observed version cannot select the // independent version-2 reservation. Nor may a stale caller rewrite its immutable identity. c.tx() - .executeWithoutResult( - s -> { - assertThat( - c.dsl() - .execute( - "UPDATE subscription_instrument_reservations SET terminal_resolution_id = ?, released_at = clock_timestamp() " - + "WHERE request_id = ? AND subscription_id = ? AND payment_instrument_id = ? AND instrument_version = ? AND released_at IS NULL", - terminalResolution, - independent.requestId(), - independent.subscriptionId(), - original.paymentInstrumentId(), - original.reservedInstrumentVersion())) - .isZero(); - assertThat( - c.dsl() - .execute( - "UPDATE subscription_instrument_reservations SET terminal_resolution_id = ?, released_at = clock_timestamp() " - + "WHERE request_id = ? AND subscription_id = ? AND payment_instrument_id = ? AND instrument_version = ? AND released_at IS NULL", - terminalResolution, - original.requestId(), - independent.subscriptionId(), - original.paymentInstrumentId(), - independent.reservedInstrumentVersion())) - .isZero(); - }); + .executeWithoutResult(s -> { + assertThat( + c.dsl() + .execute( + "UPDATE subscription_instrument_reservations SET terminal_resolution_id = ?, released_at = clock_timestamp() " + + "WHERE request_id = ? AND subscription_id = ? AND payment_instrument_id = ? AND instrument_version = ? AND released_at IS NULL", + terminalResolution, + independent.requestId(), + independent.subscriptionId(), + original.paymentInstrumentId(), + original.reservedInstrumentVersion())) + .isZero(); + assertThat( + c.dsl() + .execute( + "UPDATE subscription_instrument_reservations SET terminal_resolution_id = ?, released_at = clock_timestamp() " + + "WHERE request_id = ? AND subscription_id = ? AND payment_instrument_id = ? AND instrument_version = ? AND released_at IS NULL", + terminalResolution, + original.requestId(), + independent.subscriptionId(), + original.paymentInstrumentId(), + independent.reservedInstrumentVersion())) + .isZero(); + }); for (String assignment : List.of( "request_id = '" + original.requestId() + "'::uuid", @@ -1199,14 +1175,13 @@ void terminalCleanupAfterWalletAdvanceReleasesOnlyItsOriginalReservationWithoutR "23505", () -> c.tx() - .executeWithoutResult( - s -> { - c.dsl() - .execute( - "UPDATE subscription_instrument_reservations SET terminal_resolution_id = ?, released_at = clock_timestamp() WHERE request_id = ?", - terminalResolution, - independent.requestId()); - })); + .executeWithoutResult(s -> { + c.dsl() + .execute( + "UPDATE subscription_instrument_reservations SET terminal_resolution_id = ?, released_at = clock_timestamp() WHERE request_id = ?", + terminalResolution, + independent.requestId()); + })); assertThat( Objects.requireNonNull( c.setup() @@ -1270,12 +1245,11 @@ void terminalCleanupAfterWalletAdvanceReleasesOnlyItsOriginalReservationWithoutR .providerSubscriptionId()) .isNull(); c.tx() - .executeWithoutResult( - s -> - c.dsl() - .execute( - "UPDATE subscription SET provider_subscription_id = 'sub_original', row_version = row_version + 1 WHERE subscription_id = ?", - creation.subscriptionId())); + .executeWithoutResult(s -> + c.dsl() + .execute( + "UPDATE subscription SET provider_subscription_id = 'sub_original', row_version = row_version + 1 WHERE subscription_id = ?", + creation.subscriptionId())); var mapped = c.repository().lookupProviderId("sub_original"); assertThat(mapped.disposition()).isEqualTo(MappingDisposition.CURRENT_MAPPING); assertThat(mapped.history().orElseThrow().providerOperationId()) @@ -1346,48 +1320,44 @@ private static void advanceBeforeCreate( var executor = Executors.newFixedThreadPool(2); try { var holder = - executor.submit( - () -> - c.tx() - .executeWithoutResult( - s -> { - holderPid.set( - Objects.requireNonNull(c.dsl().fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class)); - c.dsl() - .fetchOne( - "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", - c.account()); - controlledAdvance.run(); - advanced.countDown(); - await(release); - })); + executor.submit(() -> + c.tx() + .executeWithoutResult(s -> { + holderPid.set( + Objects.requireNonNull(c.dsl().fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + c.dsl() + .fetchOne( + "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE", + c.account()); + controlledAdvance.run(); + advanced.countDown(); + await(release); + })); if (!advanced.await(5, TimeUnit.SECONDS)) { // Expose a failed owner transaction instead of masking it as a coordination timeout. holder.get(1, TimeUnit.SECONDS); throw new AssertionError("Controlled owner advance did not reach its lock boundary"); } var contender = - executor.submit( - () -> { - // Classify rejections only after the original create transaction has rolled back. - try { - c.tx() - .executeWithoutResult( - s -> { - contenderPid.set( - Objects.requireNonNull(c.dsl().fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class)); - contenderStarted.countDown(); - c.repository().retainPending(request); - }); - return "APPLIED"; - } catch (ConflictException conflict) { - return "CONFLICT"; - } catch (FenceRejectedException stale) { - return "FENCED"; - } - }); + executor.submit(() -> { + // Classify rejections only after the original create transaction has rolled back. + try { + c.tx() + .executeWithoutResult(s -> { + contenderPid.set( + Objects.requireNonNull(c.dsl().fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + contenderStarted.countDown(); + c.repository().retainPending(request); + }); + return "APPLIED"; + } catch (ConflictException conflict) { + return "CONFLICT"; + } catch (FenceRejectedException stale) { + return "FENCED"; + } + }); assertThat(contenderStarted.await(5, TimeUnit.SECONDS)).isTrue(); awaitBlocked(c, contenderPid.get(), holderPid.get()); release.countDown(); @@ -1421,19 +1391,18 @@ private static void awaitBlocked(Context c, int waitingPid, int blockerPid) { private static void controlledProviderHistory( Context c, AccountSubscriptionCreationRecord creation, String providerId) { c.tx() - .executeWithoutResult( - s -> - c.dsl() - .execute( - "INSERT INTO subscription_provider_history " - + "(provider_subscription_id,subscription_id,operation_kind,request_id,provider_operation_id,role,effective_at,evidence_digest) " - + "VALUES (?, ?, 'SUBSCRIPTION_PROVISIONING', ?, ?, 'canonical', ?::timestamptz, ?)", - providerId, - creation.subscriptionId(), - creation.requestId(), - creation.subscriptionProvisioningRequestId(), - BOUNDARY, - DIGEST)); + .executeWithoutResult(s -> + c.dsl() + .execute( + "INSERT INTO subscription_provider_history " + + "(provider_subscription_id,subscription_id,operation_kind,request_id,provider_operation_id,role,effective_at,evidence_digest) " + + "VALUES (?, ?, 'SUBSCRIPTION_PROVISIONING', ?, ?, 'canonical', ?::timestamptz, ?)", + providerId, + creation.subscriptionId(), + creation.requestId(), + creation.subscriptionProvisioningRequestId(), + BOUNDARY, + DIGEST)); } /** @@ -1444,92 +1413,91 @@ private static UUID controlledTerminalCleanup( Context c, AccountSubscriptionCreationRecord creation) { return Objects.requireNonNull( c.tx() - .execute( - s -> { - // Cleanup is not a new provisioning claim. Lock the same sources without - // requiring - // the globally shared wallet to retain the original observed - // version/availability. - new AccountPaymentInstrumentRepository(c.dsl()) - .findByOwnerForUpdate( - creation.owner().accountUuid(), creation.paymentInstrumentId()) - .orElseThrow(); - c.dsl() - .fetchOne( - "SELECT * FROM account_tenant_billing_owners WHERE tenant_uuid = ? FOR UPDATE", - creation.tenantId()); - var current = - Objects.requireNonNull( - c.dsl() - .fetchOne( - "SELECT * FROM subscription WHERE subscription_id = ? AND tenant_id = ? AND creation_request_id = ? FOR UPDATE", - creation.subscriptionId(), - creation.tenantId(), - creation.requestId())); - var hold = - Objects.requireNonNull( - c.dsl() - .fetchOne( - "SELECT * FROM subscription_instrument_reservations WHERE request_id = ? AND subscription_id = ? AND payment_instrument_id = ? AND instrument_version = ? FOR UPDATE", - creation.requestId(), - creation.subscriptionId(), - creation.paymentInstrumentId(), - creation.reservedInstrumentVersion())); - if (hold.get("released_at") != null) { - UUID retainedResolution = hold.get("terminal_resolution_id", UUID.class); - assertThat(current.get("status", String.class)).isEqualTo("canceled"); - assertThat(current.get("terminal_resolution_id", UUID.class)) - .isEqualTo(retainedResolution); - var receipt = - Objects.requireNonNull( - c.dsl() - .fetchOne( - "SELECT * FROM subscription_provider_terminal_resolutions WHERE resolution_id = ? AND request_id = ? AND subscription_id = ? AND cleanup_provider_identity = ?", - retainedResolution, - creation.requestId(), - creation.subscriptionId(), - creation.cleanupProviderIdentity())); - assertThat(receipt.get("provider_subscription_id", String.class)) - .isEqualTo(current.get("provider_subscription_id", String.class)); - return retainedResolution; - } - UUID resolution = UUID.randomUUID(); - c.dsl() - .execute( - "INSERT INTO subscription_provider_terminal_resolutions " - + "(resolution_id,request_id,subscription_id,cleanup_provider_identity,provider_subscription_id,outcome,effective_at,evidence_digest) " - + "VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz, ?)", - resolution, - creation.requestId(), - creation.subscriptionId(), - creation.cleanupProviderIdentity(), - current.get("provider_subscription_id", String.class), - current.get("provider_subscription_id") == null - ? "PROVIDER_ABSENT" - : "CANCELED", - BOUNDARY, - DIGEST); - assertThat( - c.dsl() - .execute( - "UPDATE subscription SET status = 'canceled', terminal_resolution_id = ?, row_version = row_version + 1 WHERE subscription_id = ? AND creation_request_id = ? AND row_version = ? AND status = 'pending'", - resolution, - creation.subscriptionId(), - creation.requestId(), - current.get("row_version", Long.class))) - .isOne(); - assertThat( - c.dsl() - .execute( - "UPDATE subscription_instrument_reservations SET terminal_resolution_id = ?, released_at = clock_timestamp() WHERE request_id = ? AND subscription_id = ? AND payment_instrument_id = ? AND instrument_version = ? AND released_at IS NULL", - resolution, - creation.requestId(), - creation.subscriptionId(), - creation.paymentInstrumentId(), - creation.reservedInstrumentVersion())) - .isOne(); - return resolution; - })); + .execute(s -> { + // Cleanup is not a new provisioning claim. Lock the same sources without + // requiring + // the globally shared wallet to retain the original observed + // version/availability. + new AccountPaymentInstrumentRepository(c.dsl()) + .findByOwnerForUpdate( + creation.owner().accountUuid(), creation.paymentInstrumentId()) + .orElseThrow(); + c.dsl() + .fetchOne( + "SELECT * FROM account_tenant_billing_owners WHERE tenant_uuid = ? FOR UPDATE", + creation.tenantId()); + var current = + Objects.requireNonNull( + c.dsl() + .fetchOne( + "SELECT * FROM subscription WHERE subscription_id = ? AND tenant_id = ? AND creation_request_id = ? FOR UPDATE", + creation.subscriptionId(), + creation.tenantId(), + creation.requestId())); + var hold = + Objects.requireNonNull( + c.dsl() + .fetchOne( + "SELECT * FROM subscription_instrument_reservations WHERE request_id = ? AND subscription_id = ? AND payment_instrument_id = ? AND instrument_version = ? FOR UPDATE", + creation.requestId(), + creation.subscriptionId(), + creation.paymentInstrumentId(), + creation.reservedInstrumentVersion())); + if (hold.get("released_at") != null) { + UUID retainedResolution = hold.get("terminal_resolution_id", UUID.class); + assertThat(current.get("status", String.class)).isEqualTo("canceled"); + assertThat(current.get("terminal_resolution_id", UUID.class)) + .isEqualTo(retainedResolution); + var receipt = + Objects.requireNonNull( + c.dsl() + .fetchOne( + "SELECT * FROM subscription_provider_terminal_resolutions WHERE resolution_id = ? AND request_id = ? AND subscription_id = ? AND cleanup_provider_identity = ?", + retainedResolution, + creation.requestId(), + creation.subscriptionId(), + creation.cleanupProviderIdentity())); + assertThat(receipt.get("provider_subscription_id", String.class)) + .isEqualTo(current.get("provider_subscription_id", String.class)); + return retainedResolution; + } + UUID resolution = UUID.randomUUID(); + c.dsl() + .execute( + "INSERT INTO subscription_provider_terminal_resolutions " + + "(resolution_id,request_id,subscription_id,cleanup_provider_identity,provider_subscription_id,outcome,effective_at,evidence_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz, ?)", + resolution, + creation.requestId(), + creation.subscriptionId(), + creation.cleanupProviderIdentity(), + current.get("provider_subscription_id", String.class), + current.get("provider_subscription_id") == null + ? "PROVIDER_ABSENT" + : "CANCELED", + BOUNDARY, + DIGEST); + assertThat( + c.dsl() + .execute( + "UPDATE subscription SET status = 'canceled', terminal_resolution_id = ?, row_version = row_version + 1 WHERE subscription_id = ? AND creation_request_id = ? AND row_version = ? AND status = 'pending'", + resolution, + creation.subscriptionId(), + creation.requestId(), + current.get("row_version", Long.class))) + .isOne(); + assertThat( + c.dsl() + .execute( + "UPDATE subscription_instrument_reservations SET terminal_resolution_id = ?, released_at = clock_timestamp() WHERE request_id = ? AND subscription_id = ? AND payment_instrument_id = ? AND instrument_version = ? AND released_at IS NULL", + resolution, + creation.requestId(), + creation.subscriptionId(), + creation.paymentInstrumentId(), + creation.reservedInstrumentVersion())) + .isOne(); + return resolution; + })); } private static void advanceWallet(Context c, UUID instrument, UUID changeRequest) { @@ -1671,62 +1639,55 @@ private static Seed seed(Context c) { FreshTenantCreatorDigest.evidenceDigest( 1, creation, c.account(), authorityOperation, DIGEST)); c.tx() - .executeWithoutResult( - s -> - new FreshTenantIdentityAssociationRepository(c.dsl(), "prod") - .importVerified(creation)); + .executeWithoutResult(s -> + new FreshTenantIdentityAssociationRepository(c.dsl(), "prod").importVerified(creation)); var ownerResult = Objects.requireNonNull( c.tx() - .execute( - s -> - new AccountInitialTenantBillingOwnerRepository(c.dsl()) - .establishInitial( - new AccountInitialTenantBillingOwnerRepository.InitialRequest( - UUID.randomUUID(), creator, UUID.randomUUID(), 1, true)))); + .execute(s -> + new AccountInitialTenantBillingOwnerRepository(c.dsl()) + .establishInitial( + new AccountInitialTenantBillingOwnerRepository.InitialRequest( + UUID.randomUUID(), creator, UUID.randomUUID(), 1, true)))); var customers = new AccountBillingCustomerRepository(c.dsl()); var customer = Objects.requireNonNull( c.tx() - .execute( - s -> - customers.retainIntent( - c.account(), UUID.randomUUID(), UUID.randomUUID()))) + .execute(s -> + customers.retainIntent(c.account(), UUID.randomUUID(), UUID.randomUUID()))) .customer(); if (customer.state() != AccountBillingCustomerRecord.State.CONFIRMED) { var pending = customer; customer = Objects.requireNonNull( c.tx() - .execute( - s -> - customers.recordObservation( - c.account(), - pending.customerProvisioningRequestId(), - pending.rowVersion(), - UUID.randomUUID(), - AccountBillingCustomerRecord.Observation.CONFIRMED, - "cus_" + c.account().toString().replace("-", ""), - DIGEST))); + .execute(s -> + customers.recordObservation( + c.account(), + pending.customerProvisioningRequestId(), + pending.rowVersion(), + UUID.randomUUID(), + AccountBillingCustomerRecord.Observation.CONFIRMED, + "cus_" + c.account().toString().replace("-", ""), + DIGEST))); } var confirmed = customer; var instrument = Objects.requireNonNull( c.tx() - .execute( - s -> - new AccountPaymentInstrumentRepository(c.dsl()) - .retainAttachment( - new Attachment( - UUID.randomUUID(), - UUID.randomUUID(), - c.account(), - confirmed.customerProvisioningRequestId(), - confirmed.providerCustomerId(), - "pm_" + UUID.randomUUID().toString().replace("-", ""), - AccountPaymentInstrumentRecord.State.ATTACHABLE, - new DisplayMetadata("visa", "4242", 12, 2030), - DIGEST)))); + .execute(s -> + new AccountPaymentInstrumentRepository(c.dsl()) + .retainAttachment( + new Attachment( + UUID.randomUUID(), + UUID.randomUUID(), + c.account(), + confirmed.customerProvisioningRequestId(), + confirmed.providerCustomerId(), + "pm_" + UUID.randomUUID().toString().replace("-", ""), + AccountPaymentInstrumentRecord.State.ATTACHABLE, + new DisplayMetadata("visa", "4242", 12, 2030), + DIGEST)))); return new Seed( tenant, new OwnerFence(c.account(), ownerResult.ownerVersion(), ownerResult.ownerGeneration()), @@ -1739,19 +1700,17 @@ private static List race(Supplier left, Supplier right) throws Exce var executor = Executors.newFixedThreadPool(2); try { var first = - executor.submit( - () -> { - ready.countDown(); - await(start); - return left.get(); - }); + executor.submit(() -> { + ready.countDown(); + await(start); + return left.get(); + }); var second = - executor.submit( - () -> { - ready.countDown(); - await(start); - return right.get(); - }); + executor.submit(() -> { + ready.countDown(); + await(start); + return right.get(); + }); assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); start.countDown(); return List.of(first.get(15, TimeUnit.SECONDS), second.get(15, TimeUnit.SECONDS)); @@ -1774,16 +1733,15 @@ private static void await(CountDownLatch latch) { private static void rejectSql(String state, ThrowingCallable action) { assertThatThrownBy(action) - .satisfies( - failure -> { - for (Throwable cause = failure; cause != null; cause = cause.getCause()) { - if (cause instanceof SQLException sql) { - assertThat(sql.getSQLState()).isEqualTo(state); - return; - } - } - throw new AssertionError("Expected PostgreSQL invariant refusal", failure); - }); + .satisfies(failure -> { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sql) { + assertThat(sql.getSQLState()).isEqualTo(state); + return; + } + } + throw new AssertionError("Expected PostgreSQL invariant refusal", failure); + }); } private static long count(Context c, String table) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java index 965acade65..bc58778d4f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionPostgresIntegrationTest.java @@ -165,28 +165,25 @@ void immutableBillingReceiptAndHeadGuardsRejectMalformedOrMismatchingReplacement SourceSelection original = c.select(); // These corruptions cannot become committed source states under the production guards. - assertSqlState23514( - () -> - f.dsl() - .execute( - "UPDATE account_tenant_entitlement_outbox_events SET payload = ? WHERE tenant_uuid = ?", - "{\"schemaVersion\":\"unknown-source/v1\"}" - .getBytes(java.nio.charset.StandardCharsets.UTF_8), - f.tenantId())); - assertSqlState23514( - () -> - f.dsl() - .execute( - "UPDATE account_tenant_authority_source_records SET tenant_billing_event_digest = ? WHERE tenant_uuid = ?", - "sha256:" + "f".repeat(64), - f.tenantId())); - assertSqlState23514( - () -> - f.dsl() - .execute( - "UPDATE subscription_lifecycle_receipts SET receipt_payload = ? WHERE tenant_id = ?", - new byte[] {'{', '}'}, - f.tenantId())); + assertSqlState23514(() -> + f.dsl() + .execute( + "UPDATE account_tenant_entitlement_outbox_events SET payload = ? WHERE tenant_uuid = ?", + "{\"schemaVersion\":\"unknown-source/v1\"}" + .getBytes(java.nio.charset.StandardCharsets.UTF_8), + f.tenantId())); + assertSqlState23514(() -> + f.dsl() + .execute( + "UPDATE account_tenant_authority_source_records SET tenant_billing_event_digest = ? WHERE tenant_uuid = ?", + "sha256:" + "f".repeat(64), + f.tenantId())); + assertSqlState23514(() -> + f.dsl() + .execute( + "UPDATE subscription_lifecycle_receipts SET receipt_payload = ? WHERE tenant_id = ?", + new byte[] {'{', '}'}, + f.tenantId())); SourceSelection unchanged = c.select(); assertThat(unchanged.kind()).isEqualTo(SourceKind.PAID_HOSTING); @@ -217,11 +214,10 @@ private static void assertCurrentCheckpoint(Context c, SourceSelection selected) var checkpoint = Objects.requireNonNull( f.transaction() - .execute( - status -> - new AccountAuthorityOutboxRepository(f.dsl()) - .readCheckpoint(TenantAuthorityEventV1Codec.streamKey(f.tenantId())) - .orElseThrow())); + .execute(status -> + new AccountAuthorityOutboxRepository(f.dsl()) + .readCheckpoint(TenantAuthorityEventV1Codec.streamKey(f.tenantId())) + .orElseThrow())); assertThat(selected.checkpoint().outboxSequence()).isEqualTo(checkpoint.outboxSequence()); assertThat(selected.checkpoint().eventId().toString()).isEqualTo(checkpoint.sourceEventId()); assertThat(selected.checkpoint().eventDigest()).isEqualTo(checkpoint.sourceEventDigest()); @@ -302,28 +298,27 @@ private DemoTenantEntitlementSnapshot provisionDemo( return Objects.requireNonNull( fixture .transaction() - .execute( - status -> { - var source = - new FreshTenantIdentityAssociationRepository(fixture.dsl(), "prod") - .read(fixture.tenantId()) - .orElseThrow(); - return demos.provision( - new DemoTenantEntitlementRequest( - UUID.randomUUID(), - fixture.tenantId(), - source.creationRequestId(), - source.requestDigest(), - prior == null ? null : prior.entitlementVersion(), - prior == null ? null : prior.tenantAuthorityGeneration(), - prior == null ? null : prior.tenantAuthoritySourceVersion(), - true, - publicJoin, - true, - true, - new DemoTenantEntitlementRequest.Quotas(3, 1, 1024)), - source); - })); + .execute(status -> { + var source = + new FreshTenantIdentityAssociationRepository(fixture.dsl(), "prod") + .read(fixture.tenantId()) + .orElseThrow(); + return demos.provision( + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + fixture.tenantId(), + source.creationRequestId(), + source.requestDigest(), + prior == null ? null : prior.entitlementVersion(), + prior == null ? null : prior.tenantAuthorityGeneration(), + prior == null ? null : prior.tenantAuthoritySourceVersion(), + true, + publicJoin, + true, + true, + new DemoTenantEntitlementRequest.Quotas(3, 1, 1024)), + source); + })); } private UUID activatePaid() { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index 7f67a85b2e..94645ae5aa 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -67,12 +67,11 @@ void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { var existing = source(); var historical = Objects.requireNonNull( - transaction.execute( - status -> { - repository.importVerified(existing); - return claimBootstrap( - operations, new AccountRepository(dsl).save(creator()), existing); - })); + transaction.execute(status -> { + repository.importVerified(existing); + return claimBootstrap( + operations, new AccountRepository(dsl).save(creator()), existing); + })); assertThat(historical.status()).isEqualTo("IN_PROGRESS"); Flyway.configure() .dataSource(data) @@ -93,14 +92,13 @@ void historicalBootstrapCompletionAndPlainNewImportCannotInitializeCapacity() { .isNull(); var completed = Objects.requireNonNull( - transaction.execute( - status -> { - var operation = operations.findForUpdate(historical.requestId()).orElseThrow(); - assertThat(operation.status()).isEqualTo("IN_PROGRESS"); - assertThat(operation.creationOperationId()).isEqualTo(existing.operationId()); - assertThat(operation.requestPayload()).isEqualTo(historical.requestPayload()); - return operations.complete(operation.requestId(), completion(operation)); - })); + transaction.execute(status -> { + var operation = operations.findForUpdate(historical.requestId()).orElseThrow(); + assertThat(operation.status()).isEqualTo("IN_PROGRESS"); + assertThat(operation.creationOperationId()).isEqualTo(existing.operationId()); + assertThat(operation.requestPayload()).isEqualTo(historical.requestPayload()); + return operations.complete(operation.requestId(), completion(operation)); + })); assertThat(completed.status()).isEqualTo("COMMITTED"); assertThat(completed.tenantUuid()).isEqualTo(existing.canonicalTenantId()); assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))).isZero(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationIntegrationTest.java index 5c9ce4a225..1d27646706 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/ApprovedLegacyTenantAssociationIntegrationTest.java @@ -120,10 +120,9 @@ void exactOwnerClaimUsesSourceCaptureAndSurvivesPayloadExpiryWithoutRenewal() { OwnerApprovedAccountTenantAssociation changedCapture = withCapture(evidence, evidence.sourceCapturedAt().plusNanos(1_000)); - assertThatThrownBy( - () -> - transaction.execute( - status -> associations.importOwnerApproved(legacyId, changedCapture))) + assertThatThrownBy(() -> + transaction.execute( + status -> associations.importOwnerApproved(legacyId, changedCapture))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("differs"); @@ -145,10 +144,9 @@ void exactOwnerClaimUsesSourceCaptureAndSurvivesPayloadExpiryWithoutRenewal() { evidence.signedAt(), evidence.operationEntryCount(), evidence.manifestSchemaVersion()); - assertThatThrownBy( - () -> - transaction.execute( - status -> associations.importOwnerApproved(legacyId, changedApproval))) + assertThatThrownBy(() -> + transaction.execute( + status -> associations.importOwnerApproved(legacyId, changedApproval))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("conflicts"); @@ -157,11 +155,9 @@ void exactOwnerClaimUsesSourceCaptureAndSurvivesPayloadExpiryWithoutRenewal() { var duplicateProjection = sourceEvidence.projection(duplicateLegacyId); var duplicateEvidence = evidence(duplicateLegacyId, duplicateProjection, evidence.canonicalTenantId()); - assertThatThrownBy( - () -> - transaction.execute( - status -> - associations.importOwnerApproved(duplicateLegacyId, duplicateEvidence))) + assertThatThrownBy(() -> + transaction.execute( + status -> associations.importOwnerApproved(duplicateLegacyId, duplicateEvidence))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("another claim"); assertThat(associations.findByLegacyTenantId(duplicateLegacyId)).isEmpty(); @@ -175,13 +171,12 @@ void exactOwnerClaimUsesSourceCaptureAndSurvivesPayloadExpiryWithoutRenewal() { assertThatThrownBy( () -> dsl.execute("TRUNCATE account_approved_legacy_tenant_associations CASCADE")) .hasMessageContaining("immutable"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE account_approved_legacy_tenant_associations " - + "SET canonical_tenant_id = ? WHERE legacy_tenant_id = ?", - UUID.randomUUID(), - legacyId)) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE account_approved_legacy_tenant_associations " + + "SET canonical_tenant_id = ? WHERE legacy_tenant_id = ?", + UUID.randomUUID(), + legacyId)) .hasMessageContaining("immutable"); long expiredLegacyId = 89002; @@ -190,10 +185,9 @@ void exactOwnerClaimUsesSourceCaptureAndSurvivesPayloadExpiryWithoutRenewal() { insertLegacySource(insertAccount("association-expired"), expiredLegacyId, expiredAt); var expiredProjection = sourceEvidence.projection(expiredLegacyId); var expiredEvidence = evidence(expiredLegacyId, expiredProjection); - assertThatThrownBy( - () -> - transaction.execute( - status -> associations.importOwnerApproved(expiredLegacyId, expiredEvidence))) + assertThatThrownBy(() -> + transaction.execute( + status -> associations.importOwnerApproved(expiredLegacyId, expiredEvidence))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("expired"); @@ -230,12 +224,10 @@ void exactOwnerClaimUsesSourceCaptureAndSurvivesPayloadExpiryWithoutRenewal() { .isNotNull(); AccountConnectScopeRepository scopes = newConnectScopeRepository(); var scopeReadback = - transaction.execute( - status -> - scopes - .findCanonicalEvidenceByTokenHash( - AccountJoinDigest.tokenHash(referencedScopeId)) - .orElseThrow()); + transaction.execute(status -> + scopes + .findCanonicalEvidenceByTokenHash(AccountJoinDigest.tokenHash(referencedScopeId)) + .orElseThrow()); assertThat(scopeReadback.tenantProvenance().sourceOperationId()) .isEqualTo(referencedEvidence.operationId()); assertThat(scopeReadback.tenantProvenance().digest()).isEqualTo(MANIFEST_DIGEST); @@ -245,10 +237,9 @@ void exactOwnerClaimUsesSourceCaptureAndSurvivesPayloadExpiryWithoutRenewal() { assertThat(resolver.resolve(retainedEvidence.canonicalTenantId()).canonicalTenantId()) .isEqualTo(retainedEvidence.canonicalTenantId()); - assertThatThrownBy( - () -> - transaction.execute( - status -> associations.importOwnerApproved(retainedLegacyId, retainedEvidence))) + assertThatThrownBy(() -> + transaction.execute( + status -> associations.importOwnerApproved(retainedLegacyId, retainedEvidence))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("expired"); assertThat( @@ -284,10 +275,9 @@ void sourceProjectionRejectsConflictMixedCaptureAndImportRejectsFutureCapture() insertAccount("association-future"), futureLegacyId, Instant.now().plusSeconds(60)); var futureProjection = sourceEvidence.projection(futureLegacyId); var futureEvidence = evidence(futureLegacyId, futureProjection); - assertThatThrownBy( - () -> - transaction.execute( - status -> associations.importOwnerApproved(futureLegacyId, futureEvidence))) + assertThatThrownBy(() -> + transaction.execute( + status -> associations.importOwnerApproved(futureLegacyId, futureEvidence))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("future"); } @@ -309,15 +299,13 @@ void approvalPayloadReferenceInsertAndCleanupRaceCannotCommitDanglingEvidence() "approval_writer_first_" + UUID.randomUUID().toString().replace("-", ""); try { Future writerFirst = - executor.submit( - () -> - transaction.executeWithoutResult( - status -> { - setLocalApplicationName(writerFirstApplication); - insertApprovedMembership(writerFirstAccountId, writerFirstEvidence); - writerFirstInserted.countDown(); - awaitLatch(allowWriterFirstCommit, "writer-first Account reference"); - })); + executor.submit(() -> + transaction.executeWithoutResult(status -> { + setLocalApplicationName(writerFirstApplication); + insertApprovedMembership(writerFirstAccountId, writerFirstEvidence); + writerFirstInserted.countDown(); + awaitLatch(allowWriterFirstCommit, "writer-first Account reference"); + })); assertThat(writerFirstInserted.await(5, TimeUnit.SECONDS)).isTrue(); assertThat(associations.deleteExpiredApprovalPayloads(1)).isZero(); @@ -344,32 +332,28 @@ void approvalPayloadReferenceInsertAndCleanupRaceCannotCommitDanglingEvidence() String deleteFirstApplication = "approval_delete_first_" + UUID.randomUUID().toString().replace("-", ""); Future cleanup = - executor.submit( - () -> - transaction.execute( - status -> { - int removed = associations.deleteExpiredApprovalPayloads(1); - payloadDeletedInTransaction.countDown(); - awaitLatch(allowCleanupCommit, "payload cleanup commit"); - return removed; - })); + executor.submit(() -> + transaction.execute(status -> { + int removed = associations.deleteExpiredApprovalPayloads(1); + payloadDeletedInTransaction.countDown(); + awaitLatch(allowCleanupCommit, "payload cleanup commit"); + return removed; + })); try { assertThat(payloadDeletedInTransaction.await(5, TimeUnit.SECONDS)).isTrue(); Future writer = - executor.submit( - () -> { - try { - transaction.executeWithoutResult( - status -> { - setLocalApplicationName(deleteFirstApplication); - writerStarted.countDown(); - insertApprovedMembership(deleteFirstAccountId, deleteFirstEvidence); - }); - return null; - } catch (RuntimeException failure) { - return failure; - } + executor.submit(() -> { + try { + transaction.executeWithoutResult(status -> { + setLocalApplicationName(deleteFirstApplication); + writerStarted.countDown(); + insertApprovedMembership(deleteFirstAccountId, deleteFirstEvidence); }); + return null; + } catch (RuntimeException failure) { + return failure; + } + }); assertThat(writerStarted.await(5, TimeUnit.SECONDS)).isTrue(); assertThat(awaitTransactionLock(deleteFirstApplication)).isTrue(); @@ -427,11 +411,10 @@ private String insertApprovedRetainedReferences( Instant.now().minusSeconds(120).toString(), Instant.now().minusSeconds(60).toString()); AccountConnectScopeRepository scopes = newConnectScopeRepository(); - transaction.executeWithoutResult( - status -> { - insertApprovedMembership(accountId, evidence); - scopes.insertCanonical(accountId, scope, provenance); - }); + transaction.executeWithoutResult(status -> { + insertApprovedMembership(accountId, evidence); + scopes.insertCanonical(accountId, scope, provenance); + }); return connectScopeId; } @@ -451,11 +434,10 @@ void retainedPayloadReferenceIndexesArePartialOnGeneratedOperationColumns() { "account_connect_scope_records_approved_payload_operation_idx"); assertThat(indexes) .extracting(record -> record.get("indexdef", String.class)) - .allSatisfy( - definition -> { - assertThat(definition).contains("(approved_tenant_payload_operation_id)"); - assertThat(definition).contains("approved_tenant_payload_operation_id IS NOT NULL"); - }); + .allSatisfy(definition -> { + assertThat(definition).contains("(approved_tenant_payload_operation_id)"); + assertThat(definition).contains("approved_tenant_payload_operation_id IS NOT NULL"); + }); } private AccountConnectScopeRepository newConnectScopeRepository() { 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 fb911fdfbb..c673017952 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 @@ -479,13 +479,13 @@ private static String response(Fixture fixture, String status) { ? Long.toString(fixture.clock().instant().getEpochSecond()) : "null"; return """ - {"id":"%s","object":"subscription","customer":"%s","default_payment_method":"%s", - "livemode":false,"status":"%s","cancel_at_period_end":false,"cancel_at":null,"canceled_at":null,"ended_at":%s, - "metadata":{"firemud_metadata_schema_version":"1","firemud_operation_type":"subscription_provisioning", - "firemud_operation_id":"%s","firemud_subscription_id":"%s"}, - "items":{"object":"list","data":[{"id":"si_controlled","object":"subscription_item","subscription":"%s", - "quantity":1,"current_period_start":%d,"current_period_end":%d,"price":{"id":"%s","object":"price"}}],"has_more":false}} - """ + {"id":"%s","object":"subscription","customer":"%s","default_payment_method":"%s", + "livemode":false,"status":"%s","cancel_at_period_end":false,"cancel_at":null,"canceled_at":null,"ended_at":%s, + "metadata":{"firemud_metadata_schema_version":"1","firemud_operation_type":"subscription_provisioning", + "firemud_operation_id":"%s","firemud_subscription_id":"%s"}, + "items":{"object":"list","data":[{"id":"si_controlled","object":"subscription_item","subscription":"%s", + "quantity":1,"current_period_start":%d,"current_period_end":%d,"price":{"id":"%s","object":"price"}}],"has_more":false}} + """ .formatted( fixture.providerId(), fixture.creation().providerCustomerId(), diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/StripeWebhookIntakePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/StripeWebhookIntakePostgresIntegrationTest.java index dd5b4fecbb..546e76d920 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/StripeWebhookIntakePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/StripeWebhookIntakePostgresIntegrationTest.java @@ -321,11 +321,10 @@ void ambientTransactionIsRejectedBeforeVerificationOrInboxStorage() throws Excep String payload = eventPayload("evt_ambient_local", "unknown.event", "sub_unknown"); TransactionTemplate ambient = new TransactionTemplate(context.transactionManager()); - ambient.executeWithoutResult( - status -> - assertThatThrownBy(() -> service.accept(payload, "invalid-signature")) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("ambient transaction or synchronization")); + ambient.executeWithoutResult(status -> + assertThatThrownBy(() -> service.accept(payload, "invalid-signature")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient transaction or synchronization")); assertThat(serviceTransactions.requestCount()).isZero(); assertThat(countRows(context)).isZero(); @@ -344,11 +343,10 @@ void ownerTransactionRollbackRemovesInsertAndSqlPreventsMutationDeleteAndTruncat context .transaction() - .executeWithoutResult( - status -> { - repository.retainOrReplay(verified); - status.setRollbackOnly(); - }); + .executeWithoutResult(status -> { + repository.retainOrReplay(verified); + status.setRollbackOnly(); + }); assertThat(countRows(context)).isZero(); StripeWebhookIntakeService service = @@ -358,21 +356,19 @@ void ownerTransactionRollbackRemovesInsertAndSqlPreventsMutationDeleteAndTruncat assertThat(committed.rawPayload()).isEqualTo(payload); assertThat(committed.processingStatus()).isEqualTo(StripeEventInboxRecord.PENDING); - assertAppendOnlyRejected( - () -> - context - .setupDsl() - .execute( - "UPDATE stripe_event_inbox SET event_type = 'changed' " - + "WHERE provider_event_id = ?", - committed.providerEventId())); - assertAppendOnlyRejected( - () -> - context - .setupDsl() - .execute( - "DELETE FROM stripe_event_inbox WHERE provider_event_id = ?", - committed.providerEventId())); + assertAppendOnlyRejected(() -> + context + .setupDsl() + .execute( + "UPDATE stripe_event_inbox SET event_type = 'changed' " + + "WHERE provider_event_id = ?", + committed.providerEventId())); + assertAppendOnlyRejected(() -> + context + .setupDsl() + .execute( + "DELETE FROM stripe_event_inbox WHERE provider_event_id = ?", + committed.providerEventId())); assertAppendOnlyRejected(() -> context.setupDsl().execute("TRUNCATE stripe_event_inbox")); assertThat(service.accept(payload, signatureHeader(SECRET, payload, NOW.getEpochSecond()))) @@ -449,13 +445,12 @@ private static long countRows(Context context) { private static void assertAppendOnlyRejected( org.assertj.core.api.ThrowableAssert.ThrowingCallable action) { assertThatThrownBy(action) - .satisfies( - failure -> { - java.sql.SQLException sqlFailure = findSqlException(failure); - assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); - assertThat(sqlFailure.getMessage()) - .contains("Stripe event inbox evidence is append-only"); - }); + .satisfies(failure -> { + java.sql.SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); + assertThat(sqlFailure.getMessage()) + .contains("Stripe event inbox evidence is append-only"); + }); } private static java.sql.SQLException findSqlException(Throwable failure) { @@ -519,17 +514,17 @@ private static String eventPayload( private static String reorderedEventPayload(String id, String type, String providerObjectId) { return """ - { - "type": "$TYPE", - "pending_webhooks": 0, - "livemode": false, - "data": {"object": {"id": "$OBJECT"}}, - "created": $CREATED, - "api_version": "2025-02-24.acacia", - "object": "event", - "id": "$EVENT" - } - """ + { + "type": "$TYPE", + "pending_webhooks": 0, + "livemode": false, + "data": {"object": {"id": "$OBJECT"}}, + "created": $CREATED, + "api_version": "2025-02-24.acacia", + "object": "event", + "id": "$EVENT" + } + """ .replace("$TYPE", type) .replace("$OBJECT", providerObjectId) .replace("$CREATED", Long.toString(NOW.getEpochSecond())) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityPostgresIntegrationTest.java index 83af23aad0..76c98f756e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityPostgresIntegrationTest.java @@ -274,12 +274,11 @@ dsl, new LegacyTenantSourceEvidence(dsl), TEST_NAMESPACE), } private void seedTenantAndActiveEntitlement() { - transaction.executeWithoutResult( - status -> { - freshTenants.importVerified(tenantEvidence); - sourceEvidence.initializeIssuerIfAbsent(ACCOUNT_ISSUER); - generations.initializeTenantIfAbsent(tenantUuid); - }); + transaction.executeWithoutResult(status -> { + freshTenants.importVerified(tenantEvidence); + sourceEvidence.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + generations.initializeTenantIfAbsent(tenantUuid); + }); DemoTenantEntitlementRequest request = new DemoTenantEntitlementRequest( UUID.randomUUID(), @@ -308,38 +307,36 @@ private Account createAccount() { } private void seedMembershipOperation() { - transaction.executeWithoutResult( - status -> { - generations.initialize( - AccountAuthorityGenerationRepository.AuthorityScope.membership( - account.getAccountUuid(), tenantUuid)); - connectScopes.insertCanonical(account.getId(), scope, tenantProvenance); - joinOperations.insertCanonicalIntent(joinRequestId, scope, callerBinding); - DemoTenantEntitlementSnapshot currentEntitlement = entitlements.readCurrent(tenantUuid); - joinOperations.bindCanonicalPolicyEvidence( - joinRequestId, - scope, - callerBinding, - currentEntitlement.allowPublicJoin(), - currentEntitlement.entitlementVersion()); - }); + transaction.executeWithoutResult(status -> { + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.getAccountUuid(), tenantUuid)); + connectScopes.insertCanonical(account.getId(), scope, tenantProvenance); + joinOperations.insertCanonicalIntent(joinRequestId, scope, callerBinding); + DemoTenantEntitlementSnapshot currentEntitlement = entitlements.readCurrent(tenantUuid); + joinOperations.bindCanonicalPolicyEvidence( + joinRequestId, + scope, + callerBinding, + currentEntitlement.allowPublicJoin(), + currentEntitlement.entitlementVersion()); + }); } private void createAndPublishMembershipEvent() { - transaction.executeWithoutResult( - status -> { - var membership = - memberships.createFreshMembershipForJoin(account.getAccountUuid(), tenantUuid); - roles.replaceCanonical( - membership, - account.getAccountUuid(), - tenantUuid, - tenantProvenance, - 2L, - java.util.List.of("player")); - membershipEvents.publishCanonicalFirstJoinMembershipChange( - scope, joinRequestId, callerBinding); - }); + transaction.executeWithoutResult(status -> { + var membership = + memberships.createFreshMembershipForJoin(account.getAccountUuid(), tenantUuid); + roles.replaceCanonical( + membership, + account.getAccountUuid(), + tenantUuid, + tenantProvenance, + 2L, + java.util.List.of("player")); + membershipEvents.publishCanonicalFirstJoinMembershipChange( + scope, joinRequestId, callerBinding); + }); } private AccountActorStagingEligibilityEvidence resolveStaging(UUID requestId) { @@ -348,15 +345,14 @@ private AccountActorStagingEligibilityEvidence resolveStaging(UUID requestId) { dsl, accounts, freshTenants, memberships, pairs); AccountActorStagingEligibilityService service = new AccountActorStagingEligibilityService(sourceRepository, TEST_NAMESPACE); - return readOnlySnapshot.execute( - status -> - service.resolve( - AccountActorStagingEligibilityEvidence.SCHEMA_VERSION, - TEST_NAMESPACE, - requestId, - account.getAccountUuid(), - tenantUuid, - Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)); + return readOnlySnapshot.execute(status -> + service.resolve( + AccountActorStagingEligibilityEvidence.SCHEMA_VERSION, + TEST_NAMESPACE, + requestId, + account.getAccountUuid(), + tenantUuid, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)); } private PairAuthority readPositivePair() { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java index 7ab4a56190..60f54cf677 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountBillingPrerequisiteConfirmationPostgresIntegrationTest.java @@ -265,15 +265,13 @@ void concurrentHistoricalReplayReturnsOriginalReceiptsAfterObservationExpires() try { Future first = - executor.submit( - () -> - service(context, firstTransport, providerClock, ownerClock, MAX_OBSERVATION_AGE) - .confirm(request)); + executor.submit(() -> + service(context, firstTransport, providerClock, ownerClock, MAX_OBSERVATION_AGE) + .confirm(request)); Future second = - executor.submit( - () -> - service(context, secondTransport, providerClock, ownerClock, MAX_OBSERVATION_AGE) - .confirm(request)); + executor.submit(() -> + service(context, secondTransport, providerClock, ownerClock, MAX_OBSERVATION_AGE) + .confirm(request)); assertThat(paymentMethodReadsReady.await(10, TimeUnit.SECONDS)) .as("both exact retries pass preflight before either provider read completes") @@ -318,18 +316,17 @@ void exactProviderObservationReplayRetainsOriginalCustomerAndInstrumentReceipts( Objects.requireNonNull( context .transaction() - .execute( - status -> - context - .customers() - .recordObservation( - context.account(), - intent.customerProvisioningRequestId(), - intent.rowVersion(), - UUID.randomUUID(), - Observation.AMBIGUOUS, - null, - EVIDENCE_DIGEST))); + .execute(status -> + context + .customers() + .recordObservation( + context.account(), + intent.customerProvisioningRequestId(), + intent.rowVersion(), + UUID.randomUUID(), + Observation.AMBIGUOUS, + null, + EVIDENCE_DIGEST))); ConfirmationRequest request = request(context, advancedIntent); var firstTransport = new ControlledStripeTransport( @@ -343,19 +340,18 @@ void exactProviderObservationReplayRetainsOriginalCustomerAndInstrumentReceipts( Objects.requireNonNull( context .transaction() - .execute( - status -> - context - .instruments() - .recordAvailability( - new AccountPaymentInstrumentRepository.AvailabilityObservation( - UUID.randomUUID(), - request.instrumentUuid(), - context.account(), - first.instrument().rowVersion(), - AccountPaymentInstrumentRecord.State.UNAVAILABLE, - first.instrument().display(), - "sha256:" + "b".repeat(64))))); + .execute(status -> + context + .instruments() + .recordAvailability( + new AccountPaymentInstrumentRepository.AvailabilityObservation( + UUID.randomUUID(), + request.instrumentUuid(), + context.account(), + first.instrument().rowVersion(), + AccountPaymentInstrumentRecord.State.UNAVAILABLE, + first.instrument().display(), + "sha256:" + "b".repeat(64))))); assertThat(advancedInstrument.rowVersion()).isEqualTo(2); assertThat(advancedInstrument.state()) .isEqualTo(AccountPaymentInstrumentRecord.State.UNAVAILABLE); @@ -443,18 +439,17 @@ void changedCustomerVersionDuringRemoteReadsFailsCommitAndLeavesInstrumentUncrea () -> context .transaction() - .execute( - status -> - context - .customers() - .recordObservation( - context.account(), - intent.customerProvisioningRequestId(), - intent.rowVersion(), - concurrentObservationId, - Observation.AMBIGUOUS, - null, - EVIDENCE_DIGEST)); + .execute(status -> + context + .customers() + .recordObservation( + context.account(), + intent.customerProvisioningRequestId(), + intent.rowVersion(), + concurrentObservationId, + Observation.AMBIGUOUS, + null, + EVIDENCE_DIGEST)); ControlledStripeTransport transport = new ControlledStripeTransport( customerResponse(context.account(), intent.customerProvisioningRequestId()), @@ -483,18 +478,17 @@ void incompleteOriginalCustomerReceiptCannotBeOptimisticallyReplayed() { ConfirmationRequest request = request(context, intent); context .transaction() - .execute( - status -> - context - .customers() - .recordObservation( - context.account(), - intent.customerProvisioningRequestId(), - intent.rowVersion(), - request.customerObservationRequestId(), - Observation.CONFIRMED, - PROVIDER_CUSTOMER_ID, - EVIDENCE_DIGEST)); + .execute(status -> + context + .customers() + .recordObservation( + context.account(), + intent.customerProvisioningRequestId(), + intent.rowVersion(), + request.customerObservationRequestId(), + Observation.CONFIRMED, + PROVIDER_CUSTOMER_ID, + EVIDENCE_DIGEST)); ControlledStripeTransport transport = new ControlledStripeTransport( customerResponse(context.account(), intent.customerProvisioningRequestId()), @@ -516,34 +510,32 @@ void rolledBackCustomerAndAttachmentWritesDoNotCreateAReplayReceipt() { ConfirmationRequest request = request(context, intent); context .transaction() - .executeWithoutResult( - status -> { - context - .customers() - .recordObservation( - context.account(), - intent.customerProvisioningRequestId(), - intent.rowVersion(), - request.customerObservationRequestId(), - Observation.CONFIRMED, + .executeWithoutResult(status -> { + context + .customers() + .recordObservation( + context.account(), + intent.customerProvisioningRequestId(), + intent.rowVersion(), + request.customerObservationRequestId(), + Observation.CONFIRMED, + PROVIDER_CUSTOMER_ID, + EVIDENCE_DIGEST); + context + .instruments() + .retainAttachment( + new AccountPaymentInstrumentRepository.Attachment( + request.attachmentRequestId(), + request.instrumentUuid(), + request.accountUuid(), + request.customerProvisioningRequestId(), PROVIDER_CUSTOMER_ID, - EVIDENCE_DIGEST); - context - .instruments() - .retainAttachment( - new AccountPaymentInstrumentRepository.Attachment( - request.attachmentRequestId(), - request.instrumentUuid(), - request.accountUuid(), - request.customerProvisioningRequestId(), - PROVIDER_CUSTOMER_ID, - PROVIDER_PAYMENT_METHOD_ID, - AccountPaymentInstrumentRecord.State.ATTACHABLE, - new AccountPaymentInstrumentRecord.DisplayMetadata( - "visa", "4242", 12, 2030), - EVIDENCE_DIGEST)); - status.setRollbackOnly(); - }); + PROVIDER_PAYMENT_METHOD_ID, + AccountPaymentInstrumentRecord.State.ATTACHABLE, + new AccountPaymentInstrumentRecord.DisplayMetadata("visa", "4242", 12, 2030), + EVIDENCE_DIGEST)); + status.setRollbackOnly(); + }); assertThat(context.customers().findByAccount(context.account())).contains(intent); assertThat(context.customers().readHistory(context.account())).containsExactly(intent); @@ -700,18 +692,17 @@ void changedReplayTupleFieldsConflictBeforeAnyProviderRead() { @Test void expectedCustomerVersionCannotOverflowOriginalReceiptVersionCheck() { - assertThatThrownBy( - () -> - new ConfirmationRequest( - UUID.fromString("8a0f13b5-2189-4085-9aa9-bebd30e1d001"), - UUID.fromString("8a0f13b5-2189-4085-9aa9-bebd30e1d002"), - UUID.fromString("8a0f13b5-2189-4085-9aa9-bebd30e1d003"), - Long.MAX_VALUE, - UUID.fromString("8a0f13b5-2189-4085-9aa9-bebd30e1d004"), - PROVIDER_CUSTOMER_ID, - UUID.fromString("8a0f13b5-2189-4085-9aa9-bebd30e1d005"), - UUID.fromString("8a0f13b5-2189-4085-9aa9-bebd30e1d006"), - PROVIDER_PAYMENT_METHOD_ID)) + assertThatThrownBy(() -> + new ConfirmationRequest( + UUID.fromString("8a0f13b5-2189-4085-9aa9-bebd30e1d001"), + UUID.fromString("8a0f13b5-2189-4085-9aa9-bebd30e1d002"), + UUID.fromString("8a0f13b5-2189-4085-9aa9-bebd30e1d003"), + Long.MAX_VALUE, + UUID.fromString("8a0f13b5-2189-4085-9aa9-bebd30e1d004"), + PROVIDER_CUSTOMER_ID, + UUID.fromString("8a0f13b5-2189-4085-9aa9-bebd30e1d005"), + UUID.fromString("8a0f13b5-2189-4085-9aa9-bebd30e1d006"), + PROVIDER_PAYMENT_METHOD_ID)) .isInstanceOf(IllegalArgumentException.class); } @@ -873,11 +864,10 @@ private static AccountBillingCustomerRecord intent(Context context) { return Objects.requireNonNull( context .transaction() - .execute( - status -> - context - .customers() - .retainIntent(context.account(), UUID.randomUUID(), UUID.randomUUID()))) + .execute(status -> + context + .customers() + .retainIntent(context.account(), UUID.randomUUID(), UUID.randomUUID()))) .customer(); } @@ -887,11 +877,11 @@ private static AccountBillingCustomerRecord intent(Context context) { "This is a JSON test fixture whose text block intentionally retains LF characters independent of the host console line separator.") private static String customerResponse(UUID accountUuid, UUID customerOperationId) { return """ - {"id":"%s","object":"customer","deleted":false,"livemode":false, - "metadata":{"firemud_metadata_schema_version":"1", - "firemud_operation_type":"customer_provisioning", - "firemud_operation_id":"%s","firemud_account_id":"%s"}} - """ + {"id":"%s","object":"customer","deleted":false,"livemode":false, + "metadata":{"firemud_metadata_schema_version":"1", + "firemud_operation_type":"customer_provisioning", + "firemud_operation_id":"%s","firemud_account_id":"%s"}} + """ .formatted(PROVIDER_CUSTOMER_ID, customerOperationId, accountUuid); } @@ -901,10 +891,10 @@ private static String customerResponse(UUID accountUuid, UUID customerOperationI "This is a JSON test fixture whose text block intentionally retains LF characters independent of the host console line separator.") private static String paymentMethodResponse(String methodId, String customerId) { return """ - {"id":"%s","object":"payment_method","type":"card","livemode":false, - "customer":"%s","card":{"brand":"visa","last4":"4242", - "exp_month":12,"exp_year":2030}} - """ + {"id":"%s","object":"payment_method","type":"card","livemode":false, + "customer":"%s","card":{"brand":"visa","last4":"4242", + "exp_month":12,"exp_year":2030}} + """ .formatted(methodId, customerId); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java index 5f80a35681..95a9273d86 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java @@ -108,12 +108,11 @@ void commitsExactEventAndPairAndReplaysOnlyTheSameCallerOperation() { var decoded = MembershipAuthorityEventV1Codec.verify(new String(event.payload(), StandardCharsets.UTF_8)); PairAuthority pair = - fixture.inTransaction( - () -> - fixture - .pairs - .readForUpdate(fixture.account.getAccountUuid(), fixture.tenantUuid) - .orElseThrow()); + fixture.inTransaction(() -> + fixture + .pairs + .readForUpdate(fixture.account.getAccountUuid(), fixture.tenantUuid) + .orElseThrow()); assertThat(first.eventSequence()).isEqualTo(1L); assertThat(replay).isEqualTo(first); @@ -142,12 +141,10 @@ void commitsExactEventAndPairAndReplaysOnlyTheSameCallerOperation() { assertThat(fixture.count("account_audit_outbox", "audit_event_id", first.auditEventId())) .isEqualTo(1L); - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> - fixture.terminalCoordinator.commitCanonicalFirstJoin( - fixture.scope, fixture.requestId, "another-caller"))) + assertThatThrownBy(() -> + fixture.inTransaction(() -> + fixture.terminalCoordinator.commitCanonicalFirstJoin( + fixture.scope, fixture.requestId, "another-caller"))) .isInstanceOf(CanonicalJoinOperationConflictException.class) .hasMessage("Canonical JOIN intent conflicts"); assertThat(fixture.count("account_authority_outbox_events", "outbox_stream_key", stream)) @@ -169,12 +166,10 @@ void changedEntitlementPreventsAStalePendingJoinFromCommittingMembership() { fixture.inTransaction( () -> fixture.tenantAuthorityEvents.readCurrentByTenant(fixture.tenantUuid)); var pendingOperation = - fixture.inTransaction( - () -> { - fixture.operations.lockAccount(fixture.account.getId()); - return fixture.operations.findCanonicalEvidenceForUpdateByRequestId( - fixture.requestId); - }); + fixture.inTransaction(() -> { + fixture.operations.lockAccount(fixture.account.getId()); + return fixture.operations.findCanonicalEvidenceForUpdateByRequestId(fixture.requestId); + }); assertThat(entitlement.entitlementVersion()).isEqualTo(2L); assertThat(pendingOperation).isPresent(); @@ -232,12 +227,11 @@ void terminalCoordinatorCommitsAuditAndOperationWithTheFirstEventAndReplaysExact var replay = fixture.commitFirstJoin(); String stream = fixture.membershipStream(); var operation = - fixture.inTransaction( - () -> - fixture - .operations - .findCanonicalEvidenceForUpdateByRequestId(fixture.requestId) - .orElseThrow()); + fixture.inTransaction(() -> + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(fixture.requestId) + .orElseThrow()); assertThat(replay).isEqualTo(proof); assertThat(operation.status()).isEqualTo("COMMITTED"); @@ -254,12 +248,10 @@ void terminalCoordinatorCommitsAuditAndOperationWithTheFirstEventAndReplaysExact assertThat(fixture.count("account_audit_outbox", "audit_event_id", proof.auditEventId())) .isEqualTo(1L); - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> - fixture.terminalCoordinator.commitCanonicalFirstJoin( - fixture.scope, fixture.requestId, "another-caller"))) + assertThatThrownBy(() -> + fixture.inTransaction(() -> + fixture.terminalCoordinator.commitCanonicalFirstJoin( + fixture.scope, fixture.requestId, "another-caller"))) .isInstanceOf(CanonicalJoinOperationConflictException.class); assertThat(fixture.count("account_authority_outbox_events", "outbox_stream_key", stream)) .isEqualTo(1L); @@ -300,12 +292,11 @@ void terminalJournalFailureRollsBackMembershipEventPairAndAuditTogether() { .isZero(); assertThat(fixture.count("account_audit_outbox", "audit_event_id", auditEventId)).isZero(); var operation = - fixture.inTransaction( - () -> - fixture - .operations - .findCanonicalEvidenceForUpdateByRequestId(fixture.requestId) - .orElseThrow()); + fixture.inTransaction(() -> + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(fixture.requestId) + .orElseThrow()); assertThat(operation.status()).isEqualTo("PENDING"); assertThat(operation.terminalProof()).isNull(); } @@ -330,13 +321,11 @@ void activeJoinRetainsExactSnapshotWithoutAnotherEventOrAuditAndReplays() { "account_authority_outbox_events", "outbox_stream_key", fixture.membershipStream())) .isEqualTo(1L); assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> - fixture.dsl.execute( - "UPDATE account_join_operations SET outcome_membership_version = 3 WHERE request_id = ?", - nextRequest))) + assertThatThrownBy(() -> + fixture.inTransaction(() -> + fixture.dsl.execute( + "UPDATE account_join_operations SET outcome_membership_version = 3 WHERE request_id = ?", + nextRequest))) .isInstanceOf(RuntimeException.class) .rootCause() .isInstanceOfSatisfying( @@ -355,27 +344,25 @@ void nullCommittedOutcomeIsRejectedByTerminalReceiptShapeGuard() { String nextRequest = fixture.prepareAnotherJoin(); // Retain a valid current membership witness but omit only the required committed outcome. - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> - fixture.dsl.execute( - """ - UPDATE account_join_operations pending - SET status = 'COMMITTED', outcome = NULL, - last_attempt_authority_availability = 'AVAILABLE', - membership_id = original.membership_id, - outcome_membership_version = original.outcome_membership_version, - outcome_membership_authority_generation = original.outcome_membership_authority_generation, - membership_authority_outbox_stream_key = original.membership_authority_outbox_stream_key, - membership_authority_outbox_sequence = original.membership_authority_outbox_sequence, - membership_authority_event_id = original.membership_authority_event_id, - membership_authority_event_digest = original.membership_authority_event_digest - FROM account_join_operations original - WHERE pending.request_id = ? AND original.request_id = ? - """, - nextRequest, - fixture.requestId))) + assertThatThrownBy(() -> + fixture.inTransaction(() -> + fixture.dsl.execute( + """ + UPDATE account_join_operations pending + SET status = 'COMMITTED', outcome = NULL, + last_attempt_authority_availability = 'AVAILABLE', + membership_id = original.membership_id, + outcome_membership_version = original.outcome_membership_version, + outcome_membership_authority_generation = original.outcome_membership_authority_generation, + membership_authority_outbox_stream_key = original.membership_authority_outbox_stream_key, + membership_authority_outbox_sequence = original.membership_authority_outbox_sequence, + membership_authority_event_id = original.membership_authority_event_id, + membership_authority_event_digest = original.membership_authority_event_digest + FROM account_join_operations original + WHERE pending.request_id = ? AND original.request_id = ? + """, + nextRequest, + fixture.requestId))) .isInstanceOf(RuntimeException.class) .rootCause() .isInstanceOfSatisfying( @@ -396,14 +383,12 @@ void nullCommittedOutcomeIsRejectedByTerminalReceiptShapeGuard() { void closingEnrollmentPreservesAnActiveMembersEventFreeJoinSnapshot() { Fixture fixture = newFixture(); fixture.commitFirstJoin(); - fixture.inTransaction( - () -> { - var current = fixture.demoEntitlements.readCurrent(fixture.tenantUuid); - fixture.demoEntitlements.provision( - fixture.entitlementRequest(UUID.randomUUID(), current, false), - fixture.tenantEvidence); - return null; - }); + fixture.inTransaction(() -> { + var current = fixture.demoEntitlements.readCurrent(fixture.tenantUuid); + fixture.demoEntitlements.provision( + fixture.entitlementRequest(UUID.randomUUID(), current, false), fixture.tenantEvidence); + return null; + }); String requestId = fixture.prepareAnotherJoin(); var result = fixture.commitExistingJoin(requestId); assertThat(result.outcome()).isEqualTo("ALREADY_ACTIVE"); @@ -441,25 +426,22 @@ void activeNonAdmittingSnapshotWithoutPlayerRoleRemainsSuccessfulAndUnchanged() assertThat(replay.gameplayAdmissionAllowed()).isFalse(); assertThat(replay.replayed()).isTrue(); var member = - fixture.inTransaction( - () -> - fixture - .memberships - .findFreshMembershipForUpdate( - fixture.account.getAccountUuid(), fixture.tenantUuid) - .orElseThrow()); + fixture.inTransaction(() -> + fixture + .memberships + .findFreshMembershipForUpdate(fixture.account.getAccountUuid(), fixture.tenantUuid) + .orElseThrow()); var roles = - fixture.inTransaction( - () -> - fixture - .roles - .findForCanonicalUpdate( - fixture.account.getAccountUuid(), - fixture.tenantUuid, - fixture.provenance, - member.getId(), - 3L) - .orElseThrow()); + fixture.inTransaction(() -> + fixture + .roles + .findForCanonicalUpdate( + fixture.account.getAccountUuid(), + fixture.tenantUuid, + fixture.provenance, + member.getId(), + 3L) + .orElseThrow()); assertThat(roles.roles()).isEmpty(); assertThat(member.isGameplayAdmissionAllowed()).isFalse(); assertThat( @@ -477,13 +459,11 @@ void pendingSplitTransitionCannotBeReclassifiedAsAnEventFreeActiveJoin() { .isInstanceOf(IllegalStateException.class) .hasMessageContaining("precommitted transition"); var member = - fixture.inTransaction( - () -> - fixture - .memberships - .findFreshMembershipForUpdate( - fixture.account.getAccountUuid(), fixture.tenantUuid) - .orElseThrow()); + fixture.inTransaction(() -> + fixture + .memberships + .findFreshMembershipForUpdate(fixture.account.getAccountUuid(), fixture.tenantUuid) + .orElseThrow()); var proof = new AccountJoinOperationRepository.CanonicalJoinTerminalProof( checkpoint.outboxStreamKey(), @@ -497,16 +477,14 @@ void pendingSplitTransitionCannotBeReclassifiedAsAnEventFreeActiveJoin() { member.getId(), member.getMembershipVersion(), member.getMembershipAuthorityGeneration()); - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> - fixture.operations.commitCanonicalJoin( - fixture.requestId, - fixture.scope, - fixture.callerBinding, - "ALREADY_ACTIVE", - proof))) + assertThatThrownBy(() -> + fixture.inTransaction(() -> + fixture.operations.commitCanonicalJoin( + fixture.requestId, + fixture.scope, + fixture.callerBinding, + "ALREADY_ACTIVE", + proof))) .isInstanceOf(RuntimeException.class) .rootCause() .isInstanceOfSatisfying( @@ -520,12 +498,11 @@ void pendingSplitTransitionCannotBeReclassifiedAsAnEventFreeActiveJoin() { assertThat(fixture.countAll("account_audit_outbox")).isZero(); assertThat( fixture - .inTransaction( - () -> - fixture - .operations - .findCanonicalEvidenceForUpdateByRequestId(fixture.requestId) - .orElseThrow()) + .inTransaction(() -> + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(fixture.requestId) + .orElseThrow()) .status()) .isEqualTo("PENDING"); } @@ -553,15 +530,14 @@ void committedJoinReplaysStoredEvidenceAfterLaterMembershipChanges(boolean alrea java.util.function.Supplier storedRows = () -> tables.stream() - .map( - table -> - fixture - .dsl - .fetch( - "SELECT xmin::text AS row_version, to_jsonb(t)::text AS row_data FROM " - + table - + " t ORDER BY to_jsonb(t)::text") - .intoMaps()) + .map(table -> + fixture + .dsl + .fetch( + "SELECT xmin::text AS row_version, to_jsonb(t)::text AS row_data FROM " + + table + + " t ORDER BY to_jsonb(t)::text") + .intoMaps()) .toList(); var inactiveRows = storedRows.get(); assertThat(fixture.commitExistingJoin(originalRequest)).isEqualTo(committed); @@ -573,12 +549,10 @@ void committedJoinReplaysStoredEvidenceAfterLaterMembershipChanges(boolean alrea assertThat(restored.membershipVersion()).isEqualTo(4L); var restoredRows = storedRows.get(); assertThat(fixture.commitExistingJoin(originalRequest)).isEqualTo(committed); - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> - fixture.terminalCoordinator.commitCanonicalJoin( - fixture.scope, originalRequest, "different-caller", null, null, null))) + assertThatThrownBy(() -> + fixture.inTransaction(() -> + fixture.terminalCoordinator.commitCanonicalJoin( + fixture.scope, originalRequest, "different-caller", null, null, null))) .isInstanceOf(CanonicalJoinOperationConflictException.class); assertThat(storedRows.get()).isEqualTo(restoredRows); } @@ -607,13 +581,11 @@ void inactiveJoinRestoresOneVersionAndEventWithoutChangingIndependentGeneration( .isEqualTo(3L); assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(2L); var member = - fixture.inTransaction( - () -> - fixture - .memberships - .findFreshMembershipForUpdate( - fixture.account.getAccountUuid(), fixture.tenantUuid) - .orElseThrow()); + fixture.inTransaction(() -> + fixture + .memberships + .findFreshMembershipForUpdate(fixture.account.getAccountUuid(), fixture.tenantUuid) + .orElseThrow()); assertThat(member.getLifecycleState()).isEqualTo("ACTIVE"); assertThat(member.isGameplayAdmissionAllowed()).isTrue(); } @@ -636,13 +608,11 @@ void restoreTerminalFailureRollsBackMemberRolesPairEventAndAudit() { .isInstanceOf(RuntimeException.class) .hasMessageContaining("restore terminal failure"); var member = - fixture.inTransaction( - () -> - fixture - .memberships - .findFreshMembershipForUpdate( - fixture.account.getAccountUuid(), fixture.tenantUuid) - .orElseThrow()); + fixture.inTransaction(() -> + fixture + .memberships + .findFreshMembershipForUpdate(fixture.account.getAccountUuid(), fixture.tenantUuid) + .orElseThrow()); assertThat(member.getLifecycleState()).isEqualTo("INACTIVE"); assertThat(member.getMembershipVersion()).isEqualTo(3L); assertThat(member.getMembershipAuthorityGeneration()).isEqualTo(2L); @@ -652,12 +622,11 @@ void restoreTerminalFailureRollsBackMemberRolesPairEventAndAudit() { .isEqualTo(2L); assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); var operation = - fixture.inTransaction( - () -> - fixture - .operations - .findCanonicalEvidenceForUpdateByRequestId(restoreRequest) - .orElseThrow()); + fixture.inTransaction(() -> + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(restoreRequest) + .orElseThrow()); assertThat(operation.status()).isEqualTo("PENDING"); assertThat(operation.terminalProof()).isNull(); } @@ -693,12 +662,8 @@ void browserFacadeComposesRealV2ProducerReaderAndTerminalOwnersAndReplaysCommitt .isEqualTo(1L); assertThat(fixture.countAll("account_audit_outbox")).isEqualTo(1L); var stored = - fixture.inTransaction( - () -> - fixture - .operations - .findCanonicalEvidenceForUpdateByRequestId(requestId) - .orElseThrow()); + fixture.inTransaction(() -> + fixture.operations.findCanonicalEvidenceForUpdateByRequestId(requestId).orElseThrow()); assertThat(stored.status()).isEqualTo("COMMITTED"); assertThat(stored.operationRepresentationVersion()).isEqualTo(2); assertThat(stored.scopeEvidence().tenantUuid()).isEqualTo(fixture.tenantUuid); @@ -727,55 +692,48 @@ void browserFacadeReplaysOperationFinishedAfterPreparation(String terminalState) browser .sessions() .isAccountSessionActive(fixture.account.getId(), browser.bootstrapToken())) - .thenAnswer( - invocation -> { - // The second caller read occurs outside SQL, after preparation and immediately before - // the final transaction. Finish another exact attempt in this deterministic gap. - if (callerReads.incrementAndGet() == 2) { - if ("COMMITTED".equals(terminalState)) { - var first = - browser.service().joinPublicProduction(browser.bootstrapToken(), request); - assertThat(first.success()).isTrue(); - assertThat(first.replayed()).isFalse(); - } else { - fixture.inTransaction( - () -> { - fixture.operations.lockAccount(fixture.account.getId()); - var scope = - fixture - .connectScopes - .findCanonical(selected.connectScopeId()) - .orElseThrow(); - var pending = - fixture - .operations - .findCanonicalEvidenceForUpdateByRequestId(requestId) - .orElseThrow(); - assertThat(pending.status()).isEqualTo("PENDING"); - if ("FAILED_BOUND".equals(terminalState)) { - var policy = fixture.demoEntitlements.readCurrent(fixture.tenantUuid); - fixture.operations.bindCanonicalPolicyEvidence( - requestId, - scope, - pending.callerBinding(), - policy.allowPublicJoin(), - policy.entitlementVersion()); - } - fixture.operations.finishCanonicalFailure( - requestId, scope, pending.callerBinding(), "CONNECT_SCOPE_MISMATCH"); - return null; - }); + .thenAnswer(invocation -> { + // The second caller read occurs outside SQL, after preparation and immediately before + // the final transaction. Finish another exact attempt in this deterministic gap. + if (callerReads.incrementAndGet() == 2) { + if ("COMMITTED".equals(terminalState)) { + var first = browser.service().joinPublicProduction(browser.bootstrapToken(), request); + assertThat(first.success()).isTrue(); + assertThat(first.replayed()).isFalse(); + } else { + fixture.inTransaction(() -> { + fixture.operations.lockAccount(fixture.account.getId()); + var scope = + fixture.connectScopes.findCanonical(selected.connectScopeId()).orElseThrow(); + var pending = + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow(); + assertThat(pending.status()).isEqualTo("PENDING"); + if ("FAILED_BOUND".equals(terminalState)) { + var policy = fixture.demoEntitlements.readCurrent(fixture.tenantUuid); + fixture.operations.bindCanonicalPolicyEvidence( + requestId, + scope, + pending.callerBinding(), + policy.allowPublicJoin(), + policy.entitlementVersion()); } - retained.set( - fixture.inTransaction( - () -> - fixture - .operations - .findCanonicalEvidenceForUpdateByRequestId(requestId) - .orElseThrow())); - } - return true; - }); + fixture.operations.finishCanonicalFailure( + requestId, scope, pending.callerBinding(), "CONNECT_SCOPE_MISMATCH"); + return null; + }); + } + retained.set( + fixture.inTransaction(() -> + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow())); + } + return true; + }); var replay = browser.service().joinPublicProduction(browser.bootstrapToken(), request); @@ -784,12 +742,11 @@ void browserFacadeReplaysOperationFinishedAfterPreparation(String terminalState) assertThat(replay.success()).isEqualTo("COMMITTED".equals(terminalState)); assertThat(replay.outcomeCode()).isEqualTo(retained.get().outcome()); assertThat( - fixture.inTransaction( - () -> - fixture - .operations - .findCanonicalEvidenceForUpdateByRequestId(requestId) - .orElseThrow())) + fixture.inTransaction(() -> + fixture + .operations + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow())) .isEqualTo(retained.get()); assertThat(fixture.countAll("account_audit_outbox")) .isEqualTo("COMMITTED".equals(terminalState) ? 1L : 0L); @@ -828,13 +785,11 @@ void browserFacadeReplaysCommittedJoinProofAfterMembershipBecomesInactive() { assertThat(replay.replayed()).isTrue(); var currentMembership = - fixture.inTransaction( - () -> - fixture - .memberships - .findFreshMembershipForUpdate( - fixture.account.getAccountUuid(), fixture.tenantUuid) - .orElseThrow()); + fixture.inTransaction(() -> + fixture + .memberships + .findFreshMembershipForUpdate(fixture.account.getAccountUuid(), fixture.tenantUuid) + .orElseThrow()); assertThat(currentMembership.getLifecycleState()).isEqualTo("INACTIVE"); assertThat(currentMembership.getMembershipVersion()).isEqualTo(3L); assertThat(currentMembership.getMembershipAuthorityGeneration()).isEqualTo(2L); @@ -876,22 +831,21 @@ void directFacadeComposesItsOwnAuthenticatedProducerWithRealV2ReaderAndJoinOwner var context = io.grpc.Context.ROOT.withValue( net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, peer); - context.run( - () -> { - var scope = composed.service().issueDirectTextConnectScope(caller, selected); - var request = - new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( - scope.connectScopeId(), requestId); - var first = composed.service().joinPublicProductionFromGameSession(caller, request); - var replay = composed.service().joinPublicProductionFromGameSession(caller, request); - assertThat(first.success()).isTrue(); - assertThat(first.tenantId()).isEqualTo(fixture.tenantUuid); - assertThat(first.membershipVersion()).isEqualTo(2L); - assertThat(first.gameplayAdmissionAllowed()).isTrue(); - assertThat(replay.success()).isTrue(); - assertThat(replay.replayed()).isTrue(); - assertThat(replay.membershipId()).isEqualTo(first.membershipId()); - }); + context.run(() -> { + var scope = composed.service().issueDirectTextConnectScope(caller, selected); + var request = + new net.firedevops.firemud.accountservice.dto.JoinPublicProductionRequest( + scope.connectScopeId(), requestId); + var first = composed.service().joinPublicProductionFromGameSession(caller, request); + var replay = composed.service().joinPublicProductionFromGameSession(caller, request); + assertThat(first.success()).isTrue(); + assertThat(first.tenantId()).isEqualTo(fixture.tenantUuid); + assertThat(first.membershipVersion()).isEqualTo(2L); + assertThat(first.gameplayAdmissionAllowed()).isTrue(); + assertThat(replay.success()).isTrue(); + assertThat(replay.replayed()).isTrue(); + assertThat(replay.membershipId()).isEqualTo(first.membershipId()); + }); org.mockito.Mockito.verifyNoInteractions(composed.sessions()); assertThat( fixture.count( @@ -1013,42 +967,38 @@ private Account createAccount() { } private void seedOwnerRowsAndOperation() { - inTransaction( - () -> { - freshTenants.importVerified(tenantEvidence); - sourceEvidence.initializeIssuerIfAbsent(ACCOUNT_ISSUER); - generations.initializeTenantIfAbsent(tenantUuid); - generations.initialize( - AccountAuthorityGenerationRepository.AuthorityScope.membership( - account.getAccountUuid(), tenantUuid)); - connectScopes.insertCanonical(account.getId(), scope, provenance); - operations.insertCanonicalIntent(requestId, scope, callerBinding); - return null; - }); + inTransaction(() -> { + freshTenants.importVerified(tenantEvidence); + sourceEvidence.initializeIssuerIfAbsent(ACCOUNT_ISSUER); + generations.initializeTenantIfAbsent(tenantUuid); + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.getAccountUuid(), tenantUuid)); + connectScopes.insertCanonical(account.getId(), scope, provenance); + operations.insertCanonicalIntent(requestId, scope, callerBinding); + return null; + }); DemoTenantEntitlementSnapshot currentEntitlement = - inTransaction( - () -> - demoEntitlements.provision( - entitlementRequest(UUID.randomUUID(), null), tenantEvidence)); - inTransaction( - () -> { - operations.bindCanonicalPolicyEvidence( - requestId, - scope, - callerBinding, - currentEntitlement.allowPublicJoin(), - currentEntitlement.entitlementVersion()); - return null; - }); + inTransaction(() -> + demoEntitlements.provision( + entitlementRequest(UUID.randomUUID(), null), tenantEvidence)); + inTransaction(() -> { + operations.bindCanonicalPolicyEvidence( + requestId, + scope, + callerBinding, + currentEntitlement.allowPublicJoin(), + currentEntitlement.entitlementVersion()); + return null; + }); } private DemoTenantEntitlementSnapshot provisionCurrentTenantEntitlement() { DemoTenantEntitlementSnapshot current = inTransaction(() -> demoEntitlements.readCurrent(tenantUuid)); - return inTransaction( - () -> - demoEntitlements.provision( - entitlementRequest(UUID.randomUUID(), current), tenantEvidence)); + return inTransaction(() -> + demoEntitlements.provision( + entitlementRequest(UUID.randomUUID(), current), tenantEvidence)); } private DemoTenantEntitlementRequest entitlementRequest( @@ -1074,21 +1024,19 @@ private DemoTenantEntitlementRequest entitlementRequest( } private AccountAuthorityOutboxRepository.Checkpoint writeAndPublish() { - return inTransaction( - () -> { - var membership = - memberships.createFreshMembershipForJoin(account.getAccountUuid(), tenantUuid); - membershipId = membership.getId(); - roles.replaceCanonical( - membership, - account.getAccountUuid(), - tenantUuid, - provenance, - 2L, - java.util.List.of("player")); - return producer.publishCanonicalFirstJoinMembershipChange( - scope, requestId, callerBinding); - }); + return inTransaction(() -> { + var membership = + memberships.createFreshMembershipForJoin(account.getAccountUuid(), tenantUuid); + membershipId = membership.getId(); + roles.replaceCanonical( + membership, + account.getAccountUuid(), + tenantUuid, + provenance, + 2L, + java.util.List.of("player")); + return producer.publishCanonicalFirstJoinMembershipChange(scope, requestId, callerBinding); + }); } private AccountJoinOperationRepository.CanonicalJoinTerminalProof commitFirstJoin() { @@ -1098,28 +1046,26 @@ private AccountJoinOperationRepository.CanonicalJoinTerminalProof commitFirstJoi private String prepareAnotherJoin() { String nextRequest = UUID.randomUUID().toString(); - inTransaction( - () -> { - operations.lockAccount(account.getId()); - operations.insertCanonicalIntent(nextRequest, scope, callerBinding); - var policy = demoEntitlements.readCurrent(tenantUuid); - operations.bindCanonicalPolicyEvidence( - nextRequest, - scope, - callerBinding, - policy.allowPublicJoin(), - policy.entitlementVersion()); - return null; - }); + inTransaction(() -> { + operations.lockAccount(account.getId()); + operations.insertCanonicalIntent(nextRequest, scope, callerBinding); + var policy = demoEntitlements.readCurrent(tenantUuid); + operations.bindCanonicalPolicyEvidence( + nextRequest, + scope, + callerBinding, + policy.allowPublicJoin(), + policy.entitlementVersion()); + return null; + }); return nextRequest; } private AccountJoinOperationRepository.CanonicalJoinOperationEvidence commitExistingJoin( String nextRequest) { - return inTransaction( - () -> - terminalCoordinator.commitCanonicalJoin( - scope, nextRequest, callerBinding, null, null, null)); + return inTransaction(() -> + terminalCoordinator.commitCanonicalJoin( + scope, nextRequest, callerBinding, null, null, null)); } private BrowserFacade browserFacade() { @@ -1150,68 +1096,65 @@ private BrowserFacade browserFacade() { org.mockito.Mockito.when( targets.listVisiblePublicProductionAdmissionTargets( org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - var request = - new net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( - invocation.getArgument(0, UUID.class), TEST_NAMESPACE); - return net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( - request, - net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( - request, java.util.List.of(target))); - }); + .thenAnswer(invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var request = + new net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.DiscoveryRequest( + invocation.getArgument(0, UUID.class), TEST_NAMESPACE); + return net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, java.util.List.of(target))); + }); org.mockito.Mockito.when( targets.resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - var selector = - invocation.getArgument( - 0, - net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector - .class); - return net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( - selector, + .thenAnswer(invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var selector = + invocation.getArgument( + 0, net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( - selector, target)); - }); + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector + .class); + return net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( + selector, + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( + selector, target)); + }); // The protected client is the controlled upstream boundary in this Account SQL composition; // this fixture does not claim physical GS publication or World lifecycle validation. org.mockito.Mockito.when( targets.readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - var selector = - invocation.getArgument( - 0, - net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence - .Request.class); - var published = - org.mockito.Mockito.mock( - net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence - .class); - org.mockito.Mockito.when(published.selector()).thenReturn(selector); - org.mockito.Mockito.when(published.currentTarget()).thenReturn(target); - return published; - }); + .thenAnswer(invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + var selector = + invocation.getArgument( + 0, + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence + .Request.class); + var published = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence + .class); + org.mockito.Mockito.when(published.selector()).thenReturn(selector); + org.mockito.Mockito.when(published.currentTarget()).thenReturn(target); + return published; + }); var hosting = org.mockito.Mockito.mock( net.firedevops.firemud.accountservice.repository @@ -1387,161 +1330,155 @@ private void seedControlledMembershipSnapshot( org.springframework.transaction.TransactionDefinition.PROPAGATION_REQUIRES_NEW); historicalTransaction.setIsolationLevel( org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); - historicalTransaction.execute( - status -> { - operations.lockAccount(account.getId()); - var member = - memberships - .findFreshMembershipForUpdate(account.getAccountUuid(), tenantUuid) - .orElseThrow(); - var generation = - generations.read( - AccountAuthorityGenerationRepository.AuthorityScope.membership( - account.getAccountUuid(), tenantUuid)); - // This is controlled historical input, not an implemented leave/role-removal owner. - // One atomic invalidating transaction advances the closed Account source and fence; - // the member generation then advances under that same fence without inventing an - // Account event or weakening the V40 deferred source/fence checks. - var accountBefore = - sourceEvidence.readCurrentIssuerAccountSources( - ACCOUNT_ISSUER, account.getAccountUuid()); - commitControlledClosedAccountSecurityChange(accountBefore.account()); - assertThat( - dsl.execute( - "UPDATE account_authority_generations SET generation = generation + 1, " - + "source_version = source_version + 1, updated_at = CURRENT_TIMESTAMP " - + "WHERE scope_kind = 'MEMBERSHIP' AND account_uuid = ? AND tenant_uuid = ? " - + "AND generation = ? AND source_version = ?", - account.getAccountUuid(), - tenantUuid, - generation.generation(), - generation.sourceVersion())) - .isEqualTo(1); - var next = generations.read(generation.scope()); - var authority = - generations.readCompositeSnapshot( - ACCOUNT_ISSUER, + historicalTransaction.execute(status -> { + operations.lockAccount(account.getId()); + var member = + memberships + .findFreshMembershipForUpdate(account.getAccountUuid(), tenantUuid) + .orElseThrow(); + var generation = + generations.read( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.getAccountUuid(), tenantUuid)); + // This is controlled historical input, not an implemented leave/role-removal owner. + // One atomic invalidating transaction advances the closed Account source and fence; + // the member generation then advances under that same fence without inventing an + // Account event or weakening the V40 deferred source/fence checks. + var accountBefore = + sourceEvidence.readCurrentIssuerAccountSources( + ACCOUNT_ISSUER, account.getAccountUuid()); + commitControlledClosedAccountSecurityChange(accountBefore.account()); + assertThat( + dsl.execute( + "UPDATE account_authority_generations SET generation = generation + 1, " + + "source_version = source_version + 1, updated_at = CURRENT_TIMESTAMP " + + "WHERE scope_kind = 'MEMBERSHIP' AND account_uuid = ? AND tenant_uuid = ? " + + "AND generation = ? AND source_version = ?", account.getAccountUuid(), - java.util.List.of(tenantUuid), - java.util.List.of(tenantUuid)); - var accountSource = - sourceEvidence.readCurrentIssuerAccountSources( - ACCOUNT_ISSUER, account.getAccountUuid()); - assertThat(next.generation()).isEqualTo(generation.generation() + 1L); - assertThat(next.sourceVersion()).isEqualTo(generation.sourceVersion() + 1L); - assertThat(next.issuanceFence().value()) - .isEqualTo(generation.issuanceFence().value() + 1L); - assertThat(next.issuanceFence().sourceVersion()) - .isEqualTo(generation.issuanceFence().sourceVersion() + 1L); - assertThat(accountSource.issuanceFence()).isEqualTo(next.issuanceFence()); - assertThat(accountSource.account().generation()) - .isEqualTo(accountBefore.account().generation() + 1L); - assertThat(accountSource.account().sourceVersion()) - .isEqualTo(accountBefore.account().sourceVersion() + 1L); - assertThat(accountSource.account().checkpoint().sequence()) - .isEqualTo(accountBefore.account().checkpoint().sequence() + 1L); - var tenantSource = tenantAuthorityEvents.readCurrentByTenant(tenantUuid); - var prior = pairs.readForUpdate(account.getAccountUuid(), tenantUuid).orElseThrow(); - long nextMembershipVersion = member.getMembershipVersion() + 1L; - long nextEventSequence = prior.eventSequence() + 1L; - var previousEvent = - outbox.findEvent(membershipStream(), prior.eventSequence()).orElseThrow(); - var json = tools.jackson.databind.json.JsonMapper.builder().build(); - Map event = - json.readValue( - new String(previousEvent.payload(), StandardCharsets.UTF_8), Map.class); - String inactiveRequest = "controlled-inactive-" + UUID.randomUUID(); - event.remove("eventDigest"); - event.put("eventId", UUID.randomUUID().toString()); - event.put("requestId", inactiveRequest); - event.put("outboxSequence", Long.toString(nextEventSequence)); - event.put("membershipLifecycleState", lifecycle); - event.put("roles", currentRoles); - event.put( - "membershipVersion", - Map.of(tenantUuid.toString(), Long.toString(nextMembershipVersion))); - event.put("membershipAuthorityGeneration", Long.toString(next.generation())); - Map tuple = new java.util.LinkedHashMap<>(); - tuple.put("issuerAuthGeneration", Long.toString(authority.issuer().generation())); - tuple.put( - "accountAuthorityGeneration", Long.toString(authority.account().generation())); - tuple.put( - "tenantAuthorityGeneration", - Map.of( - tenantUuid.toString(), - Long.toString(authority.tenants().getFirst().generation()))); - tuple.put( - "membershipAuthorityGeneration", - Map.of(tenantUuid.toString(), Long.toString(next.generation()))); - tuple.put("privateRealmGrantVersions", java.util.List.of()); - var cutoff = accountSource.account().accountSecurityCutoff().orElseThrow(); - tuple.put( - "accountSecurityCutoff", - Map.of( - "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), - "outboxStreamKey", cutoff.outboxStreamKey(), - "outboxSequence", cutoff.outboxSequence())); - tuple.put( - "tenantBillingCutoff", - Map.of( - tenantUuid.toString(), - Map.of( - "tenantAuthorityGeneration", - Long.toString(tenantSource.tenantAuthorityGeneration()), - "tenantBillingSequence", - Long.toString(tenantSource.tenantBillingSequence()), - "outboxStreamKey", tenantSource.outboxStreamKey(), - "outboxSequence", Long.toString(tenantSource.outboxSequence())))); - event.put("authorityTuple", tuple); - event.put("issuanceFence", Long.toString(next.issuanceFence().value())); - event.put("gameplayAdmissionAllowed", false); - event.put("callerBoundAuthorityInvalidated", true); - var sealed = MembershipAuthorityEventV1Codec.seal(event); - var appended = - outbox.append( - membershipStream(), - inactiveRequest, - sequence -> { - if (sequence != nextEventSequence) - throw new IllegalStateException("Controlled inactive sequence changed"); - return new AccountAuthorityOutboxRepository.EventEvidence( - sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); - }); - assertThat( - dsl.execute( - "UPDATE account_tenant_membership SET lifecycle_state = ?, gameplay_admission_allowed = FALSE, " - + "membership_version = ?, membership_authority_generation = ? WHERE id = ?", - lifecycle, - nextMembershipVersion, - next.generation(), - member.getId())) - .isEqualTo(1); - var inactive = - memberships - .findCanonicalMembershipForUpdate(account.getAccountUuid(), tenantUuid) - .orElseThrow(); - roles.replaceCanonical( - inactive, + tenantUuid, + generation.generation(), + generation.sourceVersion())) + .isEqualTo(1); + var next = generations.read(generation.scope()); + var authority = + generations.readCompositeSnapshot( + ACCOUNT_ISSUER, account.getAccountUuid(), - tenantUuid, - provenance, - nextMembershipVersion, - currentRoles); - assertThat( - dsl.execute( - "UPDATE account_membership_pair_authority SET membership_version = ?, membership_authority_generation = ?, " - + "last_event_sequence = ?, last_event_id = ?, last_event_digest = ?, last_transition_invalidated = TRUE " - + "WHERE account_uuid = ? AND tenant_uuid = ?", - nextMembershipVersion, - next.generation(), - appended.outboxSequence(), - appended.eventId(), - appended.eventDigest(), - account.getAccountUuid(), - tenantUuid)) - .isEqualTo(1); - return null; - }); + java.util.List.of(tenantUuid), + java.util.List.of(tenantUuid)); + var accountSource = + sourceEvidence.readCurrentIssuerAccountSources( + ACCOUNT_ISSUER, account.getAccountUuid()); + assertThat(next.generation()).isEqualTo(generation.generation() + 1L); + assertThat(next.sourceVersion()).isEqualTo(generation.sourceVersion() + 1L); + assertThat(next.issuanceFence().value()).isEqualTo(generation.issuanceFence().value() + 1L); + assertThat(next.issuanceFence().sourceVersion()) + .isEqualTo(generation.issuanceFence().sourceVersion() + 1L); + assertThat(accountSource.issuanceFence()).isEqualTo(next.issuanceFence()); + assertThat(accountSource.account().generation()) + .isEqualTo(accountBefore.account().generation() + 1L); + assertThat(accountSource.account().sourceVersion()) + .isEqualTo(accountBefore.account().sourceVersion() + 1L); + assertThat(accountSource.account().checkpoint().sequence()) + .isEqualTo(accountBefore.account().checkpoint().sequence() + 1L); + var tenantSource = tenantAuthorityEvents.readCurrentByTenant(tenantUuid); + var prior = pairs.readForUpdate(account.getAccountUuid(), tenantUuid).orElseThrow(); + long nextMembershipVersion = member.getMembershipVersion() + 1L; + long nextEventSequence = prior.eventSequence() + 1L; + var previousEvent = + outbox.findEvent(membershipStream(), prior.eventSequence()).orElseThrow(); + var json = tools.jackson.databind.json.JsonMapper.builder().build(); + Map event = + json.readValue(new String(previousEvent.payload(), StandardCharsets.UTF_8), Map.class); + String inactiveRequest = "controlled-inactive-" + UUID.randomUUID(); + event.remove("eventDigest"); + event.put("eventId", UUID.randomUUID().toString()); + event.put("requestId", inactiveRequest); + event.put("outboxSequence", Long.toString(nextEventSequence)); + event.put("membershipLifecycleState", lifecycle); + event.put("roles", currentRoles); + event.put( + "membershipVersion", + Map.of(tenantUuid.toString(), Long.toString(nextMembershipVersion))); + event.put("membershipAuthorityGeneration", Long.toString(next.generation())); + Map tuple = new java.util.LinkedHashMap<>(); + tuple.put("issuerAuthGeneration", Long.toString(authority.issuer().generation())); + tuple.put("accountAuthorityGeneration", Long.toString(authority.account().generation())); + tuple.put( + "tenantAuthorityGeneration", + Map.of( + tenantUuid.toString(), Long.toString(authority.tenants().getFirst().generation()))); + tuple.put( + "membershipAuthorityGeneration", + Map.of(tenantUuid.toString(), Long.toString(next.generation()))); + tuple.put("privateRealmGrantVersions", java.util.List.of()); + var cutoff = accountSource.account().accountSecurityCutoff().orElseThrow(); + tuple.put( + "accountSecurityCutoff", + Map.of( + "accountAuthorityGeneration", cutoff.accountAuthorityGeneration(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence())); + tuple.put( + "tenantBillingCutoff", + Map.of( + tenantUuid.toString(), + Map.of( + "tenantAuthorityGeneration", + Long.toString(tenantSource.tenantAuthorityGeneration()), + "tenantBillingSequence", Long.toString(tenantSource.tenantBillingSequence()), + "outboxStreamKey", tenantSource.outboxStreamKey(), + "outboxSequence", Long.toString(tenantSource.outboxSequence())))); + event.put("authorityTuple", tuple); + event.put("issuanceFence", Long.toString(next.issuanceFence().value())); + event.put("gameplayAdmissionAllowed", false); + event.put("callerBoundAuthorityInvalidated", true); + var sealed = MembershipAuthorityEventV1Codec.seal(event); + var appended = + outbox.append( + membershipStream(), + inactiveRequest, + sequence -> { + if (sequence != nextEventSequence) + throw new IllegalStateException("Controlled inactive sequence changed"); + return new AccountAuthorityOutboxRepository.EventEvidence( + sealed.eventId(), sealed.eventDigest(), sealed.canonicalJsonUtf8()); + }); + assertThat( + dsl.execute( + "UPDATE account_tenant_membership SET lifecycle_state = ?, gameplay_admission_allowed = FALSE, " + + "membership_version = ?, membership_authority_generation = ? WHERE id = ?", + lifecycle, + nextMembershipVersion, + next.generation(), + member.getId())) + .isEqualTo(1); + var inactive = + memberships + .findCanonicalMembershipForUpdate(account.getAccountUuid(), tenantUuid) + .orElseThrow(); + roles.replaceCanonical( + inactive, + account.getAccountUuid(), + tenantUuid, + provenance, + nextMembershipVersion, + currentRoles); + assertThat( + dsl.execute( + "UPDATE account_membership_pair_authority SET membership_version = ?, membership_authority_generation = ?, " + + "last_event_sequence = ?, last_event_id = ?, last_event_digest = ?, last_transition_invalidated = TRUE " + + "WHERE account_uuid = ? AND tenant_uuid = ?", + nextMembershipVersion, + next.generation(), + appended.outboxSequence(), + appended.eventId(), + appended.eventDigest(), + account.getAccountUuid(), + tenantUuid)) + .isEqualTo(1); + return null; + }); } /** 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 aedb15b4be..5963fa19a1 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 @@ -154,28 +154,26 @@ void expiredPaidReceiptIsUnavailableAndNeverSelectsDemo() { void finalCommitFailureRollsBackMembershipRolesPairEventAuditAndTerminalReceipt() { Context c = context(false); var original = c.operation(); - assertThatThrownBy( - () -> - c.hosting - .transaction() - .execute( - status -> { - TransactionSynchronizationManager.registerSynchronization( - new TransactionSynchronization() { - @Override - public void beforeCommit(boolean readOnly) { - throw new IllegalStateException( - "controlled final paid JOIN commit refusal"); - } - }); - return c.coordinator.commitPaidCanonicalFirstJoin( - c.scope, - c.requestId, - CALLER, - c.hosting.lifecycleRepository(), - c.fence, - c.observed); - })) + assertThatThrownBy(() -> + c.hosting + .transaction() + .execute(status -> { + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void beforeCommit(boolean readOnly) { + throw new IllegalStateException( + "controlled final paid JOIN commit refusal"); + } + }); + return c.coordinator.commitPaidCanonicalFirstJoin( + c.scope, + c.requestId, + CALLER, + c.hosting.lifecycleRepository(), + c.fence, + c.observed); + })) .hasMessageContaining("controlled final paid JOIN commit refusal"); c.assertRolledBack(original); } @@ -299,43 +297,40 @@ private Context(CanonicalHostingSubscriptionTestFixture.Fixture hosting, boolean now.plusSeconds(120).toString()); hosting .transaction() - .executeWithoutResult( - status -> { - var source = fresh.read(hosting.tenantId()).orElseThrow(); - sources.initializeIssuerIfAbsent("firemud-account-service"); - generations.initialize( - AccountAuthorityGenerationRepository.AuthorityScope.membership( - player.getAccountUuid(), hosting.tenantId())); - scopes.insertCanonical( - player.getId(), - scope, - new VerifiedTenantProvenance( - null, - TenantProvenanceKind.FRESH_GAME_DESIGN, - source.operationId(), - source.evidenceDigest())); - operations.insertCanonicalIntent(requestId, scope, CALLER); - }); + .executeWithoutResult(status -> { + var source = fresh.read(hosting.tenantId()).orElseThrow(); + sources.initializeIssuerIfAbsent("firemud-account-service"); + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + player.getAccountUuid(), hosting.tenantId())); + scopes.insertCanonical( + player.getId(), + scope, + new VerifiedTenantProvenance( + null, + TenantProvenanceKind.FRESH_GAME_DESIGN, + source.operationId(), + source.evidenceDigest())); + operations.insertCanonicalIntent(requestId, scope, CALLER); + }); fence = Objects.requireNonNull( hosting .transaction() - .execute( - status -> - hosting.lifecycleRepository().prepareCurrentRead(hosting.tenantId()))); + .execute(status -> + hosting.lifecycleRepository().prepareCurrentRead(hosting.tenantId()))); observed = hosting.observer().observe(fence.binding()); hosting .transaction() - .executeWithoutResult( - status -> { - var receipt = hosting.lifecycleRepository().readCurrent(fence, observed); - operations.bindCanonicalPolicyEvidence( - requestId, - scope, - CALLER, - receipt.allowPublicJoin(), - receipt.entitlementVersion() + (wrongPolicy ? 1 : 0)); - }); + .executeWithoutResult(status -> { + var receipt = hosting.lifecycleRepository().readCurrent(fence, observed); + operations.bindCanonicalPolicyEvidence( + requestId, + scope, + CALLER, + receipt.allowPublicJoin(), + receipt.entitlementVersion() + (wrongPolicy ? 1 : 0)); + }); } private AccountJoinOperationRepository.CanonicalJoinTerminalProof commit( @@ -343,30 +338,28 @@ private AccountJoinOperationRepository.CanonicalJoinTerminalProof commit( return Objects.requireNonNull( hosting .transaction() - .execute( - status -> - coordinator.commitPaidCanonicalFirstJoin( - scope, requestId, CALLER, hosting.lifecycleRepository(), fence, result))); + .execute(status -> + coordinator.commitPaidCanonicalFirstJoin( + scope, requestId, CALLER, hosting.lifecycleRepository(), fence, result))); } private AccountJoinOperationRepository.CanonicalJoinOperationEvidence operation() { return Objects.requireNonNull( hosting .transaction() - .execute( - status -> { - operations.lockAccount( - Objects.requireNonNull( - hosting - .dsl() - .fetchOne( - "SELECT id FROM accounts WHERE account_uuid = ?", - scope.accountId())) - .get(0, Long.class)); - return operations - .findCanonicalEvidenceForUpdateByRequestId(requestId) - .orElseThrow(); - })); + .execute(status -> { + operations.lockAccount( + Objects.requireNonNull( + hosting + .dsl() + .fetchOne( + "SELECT id FROM accounts WHERE account_uuid = ?", + scope.accountId())) + .get(0, Long.class)); + return operations + .findCanonicalEvidenceForUpdateByRequestId(requestId) + .orElseThrow(); + })); } private String stream() { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java index ed1d16ec10..5417149891 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentPostgresIntegrationTest.java @@ -72,18 +72,17 @@ void sdkObservationCommitsExactHistoryAndRetryRetainsLaterAvailability() { UUID laterRequest = UUID.randomUUID(); var unavailable = f.tx() - .execute( - s -> - f.instruments() - .recordAvailability( - new AvailabilityObservation( - laterRequest, - f.request().instrumentUuid(), - f.request().accountUuid(), - 1, - State.UNAVAILABLE, - observed.receipt().display(), - "sha256:" + "c".repeat(64)))); + .execute(s -> + f.instruments() + .recordAvailability( + new AvailabilityObservation( + laterRequest, + f.request().instrumentUuid(), + f.request().accountUuid(), + 1, + State.UNAVAILABLE, + observed.receipt().display(), + "sha256:" + "c".repeat(64)))); f.transport().paths.clear(); var replay = (HistoricalAttachment) f.service().retainSavedMethod(f.request()); assertThat(replay.receipt()).isEqualTo(observed.receipt()); @@ -91,15 +90,14 @@ void sdkObservationCommitsExactHistoryAndRetryRetainsLaterAvailability() { assertThat(f.instruments().readHistory(f.request().accountUuid(), f.request().instrumentUuid())) .containsExactly(observed.receipt(), unavailable); assertThat(f.transport().paths).isEmpty(); - assertThatThrownBy( - () -> - f.service() - .retainSavedMethod( - new Request( - f.request().requestId(), - f.request().instrumentUuid(), - f.request().accountUuid(), - "pm_changed"))) + assertThatThrownBy(() -> + f.service() + .retainSavedMethod( + new Request( + f.request().requestId(), + f.request().instrumentUuid(), + f.request().accountUuid(), + "pm_changed"))) .hasMessageContaining("changed binding"); assertThat(f.instruments().readHistory(f.request().accountUuid(), f.request().instrumentUuid())) .containsExactly(observed.receipt(), unavailable); @@ -197,16 +195,15 @@ private static Fixture fixture() { tx.execute( s -> customers.retainIntent(account, operation, UUID.randomUUID()).customer())); // Controlled local customer setup only; the observer must independently match SDK metadata. - tx.executeWithoutResult( - s -> - customers.recordObservation( - account, - operation, - intent.rowVersion(), - UUID.randomUUID(), - AccountBillingCustomerRecord.Observation.CONFIRMED, - "cus_saved", - "sha256:" + "a".repeat(64))); + tx.executeWithoutResult(s -> + customers.recordObservation( + account, + operation, + intent.rowVersion(), + UUID.randomUUID(), + AccountBillingCustomerRecord.Observation.CONFIRMED, + "cus_saved", + "sha256:" + "a".repeat(64))); var transport = new Transport(account, operation, sql); Clock clock = Clock.fixed(Instant.parse("2026-11-02T00:00:00Z"), ZoneOffset.UTC); var service = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java index 32b82b90e3..b416eed6ae 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerPostgresIntegrationTest.java @@ -232,10 +232,9 @@ void controlledOwnerReceiverAndGameSessionClientComposeWithoutGrantingAdmission( .doesNotContain(CONTROLLED_COMPACT_TOKEN); assertThatThrownBy(() -> client.read(context, UUID.randomUUID(), login, () -> false)) .isExactlyInstanceOf(io.grpc.StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(((io.grpc.StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(io.grpc.Status.Code.CANCELLED)); + .satisfies(failure -> + assertThat(((io.grpc.StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.CANCELLED)); assertThat(f.dsl.fetchCount(DSL.table("account_tenant_membership"))) .isEqualTo(membershipsBefore); } finally { @@ -264,12 +263,11 @@ void tenantOperationDemoCapturesCurrentSourceOnActualWritableSerializableConnect assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) .isFalse(); - f.dsl.connection( - connection -> { - assertThat(connection.getTransactionIsolation()) - .isEqualTo(Connection.TRANSACTION_SERIALIZABLE); - assertThat(connection.isReadOnly()).isFalse(); - }); + f.dsl.connection(connection -> { + assertThat(connection.getTransactionIsolation()) + .isEqualTo(Connection.TRANSACTION_SERIALIZABLE); + assertThat(connection.isReadOnly()).isFalse(); + }); return invocation.callRealMethod(); }) .when(f.demos) @@ -315,11 +313,10 @@ void actualAbsenceBaselineReturnsNonadmittingPlayerEvidenceWithoutCreatingMember status -> f.memberships.findFreshMembership(f.account.getAccountUuid(), f.tenantId)); assertThat(missing).isEmpty(); assertThat(value.membershipSource().checkpoints()) - .anySatisfy( - checkpoint -> { - assertThat(checkpoint.outboxStreamKey()).contains("membership/"); - assertThat(checkpoint.outboxSequence()).isEqualTo("0"); - }); + .anySatisfy(checkpoint -> { + assertThat(checkpoint.outboxStreamKey()).contains("membership/"); + assertThat(checkpoint.outboxSequence()).isEqualTo("0"); + }); assertThat(value.membershipSource().sourceEvidence()).isNotEmpty(); } @@ -376,13 +373,12 @@ void blockedAccountSourceReadIsCancelledWithinOwnerTransactionBudget() throws Ex // jOOQ connection must propagate the owner's five-second JDBC query timeout. assertThatThrownBy(() -> f.owner.evaluate(f.request(), CONTROLLED_COMPACT_TOKEN)) .isInstanceOf(org.jooq.exception.DataAccessException.class) - .satisfies( - failure -> { - Throwable cause = failure; - while (cause.getCause() != null) cause = cause.getCause(); - assertThat(cause).isInstanceOf(SQLException.class); - assertThat(((SQLException) cause).getSQLState()).isEqualTo("57014"); - }); + .satisfies(failure -> { + Throwable cause = failure; + while (cause.getCause() != null) cause = cause.getCause(); + assertThat(cause).isInstanceOf(SQLException.class); + assertThat(((SQLException) cause).getSQLState()).isEqualTo("57014"); + }); } finally { blocker.rollback(); } @@ -459,91 +455,83 @@ private Fixture fixture(boolean join) { /** Controlled protected-client double: no physical GS/World source provenance is claimed. */ private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClient targets) { when(targets.resolvePublishedRealmAdmissionTarget(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - var selector = - invocation.getArgument( - 0, - CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); - var target = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); - when(target.targetNamespace()).thenReturn(selector.targetNamespace()); - when(target.canonicalTenantId()).thenReturn(selector.tenantId()); - when(target.tenantSlug()).thenReturn(selector.tenantSlug()); - when(target.worldSlug()).thenReturn(selector.worldSlug()); - when(target.realmId()).thenReturn(selector.realmId()); - when(target.realmSlug()).thenReturn(selector.realmSlug()); - when(target.playableStateNamespaceId()) - .thenReturn(selector.playableStateNamespaceId()); - when(target.playableStateScope()).thenReturn(selector.playableStateScope()); - when(target.canonicalGameInstanceId()).thenReturn(selector.gameInstanceId()); - when(target.catalogRevision()).thenReturn(selector.catalogRevision()); - when(target.pointerVersion()).thenReturn(selector.pointerVersion()); - when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); - when(target.ownerProofOutcome()) - .thenReturn( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED); - UUID version = UUID.fromString("33333333-3333-4333-8333-333333333333"); - when(target.canonicalVersionId()).thenReturn(version); - when(target.activeWorldEpoch()).thenReturn(5L); - var strict = - new CanonicalGameplayRosterOwnerReadEvidence.Request( - selector.readRequestId(), - selector.accountId(), - selector.targetNamespace(), - selector.tenantId(), - selector.worldSlug(), - selector.realmId(), - selector.realmSlug(), - selector.playableStateNamespaceId(), - selector.playableStateScope(), - selector.gameInstanceId(), - version, - selector.catalogRevision(), - selector.pointerVersion(), - 5L); - var resolved = - mock( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget - .class); - when(resolved.selector()).thenReturn(selector); - when(resolved.currentTarget()).thenReturn(target); - when(resolved.strictSelector()).thenReturn(strict); - var read = - mock( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); - when(read.selector()).thenReturn(strict); - when(read.currentTarget()).thenReturn(target); - var source = mock(CanonicalGameplayRosterOwnerReadEvidence.class); - when(source.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); - var policies = mock(PublishedRealmEntryPolicySetEvidence.class); - when(policies.policySetDigest()).thenReturn("sha256:" + "b".repeat(64)); - when(source.publishedPolicySetEvidence()).thenReturn(policies); - var ownerProof = - mock( - net.firedevops.firemud.common.world - .GameSessionCanonicalInitialAdmissionOwnerProof.class); - when(ownerProof.proofDigest()).thenReturn("sha256:" + "c".repeat(64)); - when(source.gameSessionOwnerProof()).thenReturn(ownerProof); - when(read.sourceEvidence()).thenReturn(source); - var world = mock(WorldCanonicalInstanceLifecycleEvidence.class); - when(world.canonicalBytes()) - .thenReturn( - "controlled-complete-world-source" - .getBytes(java.nio.charset.StandardCharsets.UTF_8)); - when(world.captureId()) - .thenReturn(UUID.fromString("44444444-4444-4444-8444-444444444444")); - when(world.rowVersion()).thenReturn(2L); - when(read.worldLifecycleEvidence()).thenReturn(world); - when(targets.readPublishedRealmAdmissionOwner(strict)) - .thenAnswer( - readCall -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()) - .isFalse(); - return read; - }); - return resolved; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var selector = + invocation.getArgument( + 0, CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); + var target = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); + when(target.targetNamespace()).thenReturn(selector.targetNamespace()); + when(target.canonicalTenantId()).thenReturn(selector.tenantId()); + when(target.tenantSlug()).thenReturn(selector.tenantSlug()); + when(target.worldSlug()).thenReturn(selector.worldSlug()); + when(target.realmId()).thenReturn(selector.realmId()); + when(target.realmSlug()).thenReturn(selector.realmSlug()); + when(target.playableStateNamespaceId()).thenReturn(selector.playableStateNamespaceId()); + when(target.playableStateScope()).thenReturn(selector.playableStateScope()); + when(target.canonicalGameInstanceId()).thenReturn(selector.gameInstanceId()); + when(target.catalogRevision()).thenReturn(selector.catalogRevision()); + when(target.pointerVersion()).thenReturn(selector.pointerVersion()); + when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + when(target.ownerProofOutcome()) + .thenReturn( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED); + UUID version = UUID.fromString("33333333-3333-4333-8333-333333333333"); + when(target.canonicalVersionId()).thenReturn(version); + when(target.activeWorldEpoch()).thenReturn(5L); + var strict = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + selector.readRequestId(), + selector.accountId(), + selector.targetNamespace(), + selector.tenantId(), + selector.worldSlug(), + selector.realmId(), + selector.realmSlug(), + selector.playableStateNamespaceId(), + selector.playableStateScope(), + selector.gameInstanceId(), + version, + selector.catalogRevision(), + selector.pointerVersion(), + 5L); + var resolved = + mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget.class); + when(resolved.selector()).thenReturn(selector); + when(resolved.currentTarget()).thenReturn(target); + when(resolved.strictSelector()).thenReturn(strict); + var read = + mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + when(read.selector()).thenReturn(strict); + when(read.currentTarget()).thenReturn(target); + var source = mock(CanonicalGameplayRosterOwnerReadEvidence.class); + when(source.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); + var policies = mock(PublishedRealmEntryPolicySetEvidence.class); + when(policies.policySetDigest()).thenReturn("sha256:" + "b".repeat(64)); + when(source.publishedPolicySetEvidence()).thenReturn(policies); + var ownerProof = + mock( + net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof + .class); + when(ownerProof.proofDigest()).thenReturn("sha256:" + "c".repeat(64)); + when(source.gameSessionOwnerProof()).thenReturn(ownerProof); + when(read.sourceEvidence()).thenReturn(source); + var world = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(world.canonicalBytes()) + .thenReturn( + "controlled-complete-world-source" + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + when(world.captureId()) + .thenReturn(UUID.fromString("44444444-4444-4444-8444-444444444444")); + when(world.rowVersion()).thenReturn(2L); + when(read.worldLifecycleEvidence()).thenReturn(world); + when(targets.readPublishedRealmAdmissionOwner(strict)) + .thenAnswer(readCall -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return read; + }); + return resolved; + }); } private static final class Fixture { @@ -651,53 +639,50 @@ private Fixture(DriverManagerDataSource dataSource, boolean join) { NOW.plusSeconds(120).toString()); String joinRequestId = UUID.randomUUID().toString(); String callerBinding = "controlled-join-caller"; - transaction.execute( - status -> { - tenants.importVerified(tenantSource); - sources.initializeIssuerIfAbsent(ISSUER); - generations.initializeTenantIfAbsent(tenantId); - generations.initialize( - AccountAuthorityGenerationRepository.AuthorityScope.membership( - account.getAccountUuid(), tenantId)); - scopes.insertCanonical(account.getId(), scope, provenance); - operations.insertCanonicalIntent(joinRequestId, scope, callerBinding); - return null; - }); + transaction.execute(status -> { + tenants.importVerified(tenantSource); + sources.initializeIssuerIfAbsent(ISSUER); + generations.initializeTenantIfAbsent(tenantId); + generations.initialize( + AccountAuthorityGenerationRepository.AuthorityScope.membership( + account.getAccountUuid(), tenantId)); + scopes.insertCanonical(account.getId(), scope, provenance); + operations.insertCanonicalIntent(joinRequestId, scope, callerBinding); + return null; + }); var entitlement = - transaction.execute( - status -> - demos.provision( - new DemoTenantEntitlementRequest( - UUID.randomUUID(), - tenantId, - tenantSource.creationRequestId(), - tenantSource.requestDigest(), - null, - null, - null, - true, - true, - true, - true, - new DemoTenantEntitlementRequest.Quotas(3, 2, 4096)), - tenantSource)); + transaction.execute(status -> + demos.provision( + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + tenantId, + tenantSource.creationRequestId(), + tenantSource.requestDigest(), + null, + null, + null, + true, + true, + true, + true, + new DemoTenantEntitlementRequest.Quotas(3, 2, 4096)), + tenantSource)); if (entitlement == null) throw new IllegalStateException("Demo source is absent"); - transaction.execute( - status -> { - operations.bindCanonicalPolicyEvidence( - joinRequestId, - scope, - callerBinding, - entitlement.allowPublicJoin(), - entitlement.entitlementVersion()); - if (join) { - terminal.commitCanonicalFirstJoin(scope, joinRequestId, callerBinding); - } else { - accounts.findByAccountUuidForUpdate(account.getAccountUuid()).orElseThrow(); - memberships.prepareFreshCreatorAbsence(account.getAccountUuid(), tenantId); - } - return null; - }); + transaction.execute(status -> { + operations.bindCanonicalPolicyEvidence( + joinRequestId, + scope, + callerBinding, + entitlement.allowPublicJoin(), + entitlement.entitlementVersion()); + if (join) { + terminal.commitCanonicalFirstJoin(scope, joinRequestId, callerBinding); + } else { + accounts.findByAccountUuidForUpdate(account.getAccountUuid()).orElseThrow(); + memberships.prepareFreshCreatorAbsence(account.getAccountUuid(), tenantId); + } + return null; + }); var issuances = mock(AccountGameplayDelegationIssuanceRepository.class); var callers = mock(AccountGameplayAdmissionCallerVerifier.class); var identity = @@ -734,17 +719,14 @@ private Fixture(DriverManagerDataSource dataSource, boolean join) { when(caller.currentCandidate()).thenReturn(candidate); when(callers.verifyPresentedCompactToken(CONTROLLED_COMPACT_TOKEN)).thenReturn(caller); when(issuances.readCurrentCommittedCandidateByJti(identity.tokenJti())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) - .isFalse(); - dsl.connection( - connection -> - assertThat(connection.getTransactionIsolation()) - .isEqualTo(Connection.TRANSACTION_SERIALIZABLE)); - return Optional.of(candidate); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + dsl.connection(connection -> + assertThat(connection.getTransactionIsolation()) + .isEqualTo(Connection.TRANSACTION_SERIALIZABLE)); + return Optional.of(candidate); + }); var targets = mock(CanonicalGameplayAdmissionDecisionReadClient.class); controlledTarget(targets); owner = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java index 9654b5bc97..4e03b5c7cd 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapDemoWorldsOwnerPostgresIntegrationTest.java @@ -192,12 +192,11 @@ void realDemoMutationBetweenSourceTransactionsInvalidatesTheOriginalSelectedHead DemoTenant tenant = f.demo("changing", true); f.targetReads(List.of(tenant.target()), List.of(tenant.target())); AtomicReference> afterMutation = new AtomicReference<>(); - f.clock.afterNextObservation.set( - () -> { - DemoTenantEntitlementSnapshot updated = f.update(tenant, false); - assertThat(updated.entitlementVersion()).isEqualTo(2L); - afterMutation.set(f.snapshot()); - }); + f.clock.afterNextObservation.set(() -> { + DemoTenantEntitlementSnapshot updated = f.update(tenant, false); + assertThat(updated.entitlementVersion()).isEqualTo(2L); + afterMutation.set(f.snapshot()); + }); assertCode("ENTITLEMENT_UNAVAILABLE", () -> f.worlds.listWorlds(f.token)); @@ -237,12 +236,11 @@ void repeatedWorldSlugAcrossTwoRealDemoTenantsReturnsBothQualifiedSelectorsInOrd .sorted( Comparator.comparing((DemoTenant tenant) -> tenant.target().worldSlug()) .thenComparing(tenant -> tenant.target().tenantSlug())) - .map( - tenant -> - new BootstrapWorldDto( - tenant.target().tenantSlug(), - tenant.target().worldSlug(), - tenant.target().worldDisplayName())) + .map(tenant -> + new BootstrapWorldDto( + tenant.target().tenantSlug(), + tenant.target().worldSlug(), + tenant.target().worldDisplayName())) .toList(); assertThat(f.worlds.listWorlds(f.token)).containsExactlyElementsOf(expected); @@ -357,12 +355,11 @@ void absentMembershipAndClosedEnrollmentPersistOnlyTheExactCanonicalPublicSelect assertThat(row.get("snapshot_digest", String.class)) .isEqualTo(AccountJoinDigest.scopeV2(scope)); Map after = f.snapshot(); - before.forEach( - (table, original) -> { - if (!table.equals("account_connect_scope_records")) { - assertThat(after.get(table)).as("unchanged %s", table).isEqualTo(original); - } - }); + before.forEach((table, original) -> { + if (!table.equals("account_connect_scope_records")) { + assertThat(after.get(table)).as("unchanged %s", table).isEqualTo(original); + } + }); assertThat( Objects.requireNonNull( f.dsl.fetchOne("SELECT COUNT(*) FROM account_connect_scope_records")) @@ -725,12 +722,11 @@ private FreshTenantCreationEvidence enrollTenant() { "NEW_GAME_ROW", GameTenantCreationDigest.evidenceDigest( NAMESPACE, requestId, operationId, digest, tenantId, rowId, key, "NEW_GAME_ROW")); - return inTransaction( - () -> { - tenants.importVerified(source); - generations.initializeTenantIfAbsent(tenantId); - return source; - }); + return inTransaction(() -> { + tenants.importVerified(source); + generations.initializeTenantIfAbsent(tenantId); + return source; + }); } private CanonicalJoinScopeV2 issueScope(String worldSlug) { @@ -751,10 +747,8 @@ private DemoTenant demo(String worldSlug, boolean available) { } private DemoTenantEntitlementSnapshot update(DemoTenant tenant, boolean available) { - return inTransaction( - () -> - demos.provision( - request(tenant.source(), tenant.snapshot(), available), tenant.source())); + return inTransaction(() -> + demos.provision(request(tenant.source(), tenant.snapshot(), available), tenant.source())); } private T inTransaction(Supplier operation) { @@ -763,20 +757,19 @@ private T inTransaction(Supplier operation) { private void targetReads(List first, List second) { when(targets.listVisiblePublicProductionAdmissionTargets(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - int read = targetReadCount.incrementAndGet(); - if (read == 2) onSecondTargetRead.run(); - List values = read == 1 ? first : second; - DiscoveryRequest request = - new DiscoveryRequest(invocation.getArgument(0, UUID.class), NAMESPACE); - return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( - request, - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( - request, values)); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + int read = targetReadCount.incrementAndGet(); + if (read == 2) onSecondTargetRead.run(); + List values = read == 1 ? first : second; + DiscoveryRequest request = + new DiscoveryRequest(invocation.getArgument(0, UUID.class), NAMESPACE); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, values)); + }); } private Map snapshot() { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java index b390cc7076..adfdf376d3 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerPostgresIntegrationTest.java @@ -167,21 +167,19 @@ void captureRunsInsideFinalWritableTransactionAndFailureRollsBackCapturedSql() { assertThat(committed.outcome()).isEqualTo(Outcome.COMMITTED); String marker = "capture_marker_" + UUID.randomUUID().toString().replace("-", ""); AtomicInteger captures = new AtomicInteger(); - assertThatThrownBy( - () -> - f.service() - .readCurrentAndCapture( - f.tenantId(), - receipt -> { - captures.incrementAndGet(); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()) - .isTrue(); - assertThat( - TransactionSynchronizationManager.isCurrentTransactionReadOnly()) - .isFalse(); - f.dsl().execute("CREATE TABLE " + marker + " (id bigint)"); - throw new IllegalStateException("controlled capture rollback"); - })) + assertThatThrownBy(() -> + f.service() + .readCurrentAndCapture( + f.tenantId(), + receipt -> { + captures.incrementAndGet(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + f.dsl().execute("CREATE TABLE " + marker + " (id bigint)"); + throw new IllegalStateException("controlled capture rollback"); + })) .hasMessageContaining("ENTITLEMENT_UNAVAILABLE") .hasCauseInstanceOf(IllegalStateException.class) .hasRootCauseMessage("controlled capture rollback"); @@ -203,26 +201,25 @@ void pendingDoesNotBecomePositiveAndExplicitDemoUsesOnlyItsActualCurrentOwner() var tenantSources = new FreshTenantIdentityAssociationRepository(f.dsl(), "prod"); var committed = f.transaction() - .execute( - status -> { - var source = tenantSources.read(f.tenantId()).orElseThrow(); - return c.demos() - .provision( - new DemoTenantEntitlementRequest( - UUID.randomUUID(), - f.tenantId(), - source.creationRequestId(), - source.requestDigest(), - null, - null, - null, - true, - false, - true, - false, - new DemoTenantEntitlementRequest.Quotas(3, 1, 500)), - source); - }); + .execute(status -> { + var source = tenantSources.read(f.tenantId()).orElseThrow(); + return c.demos() + .provision( + new DemoTenantEntitlementRequest( + UUID.randomUUID(), + f.tenantId(), + source.creationRequestId(), + source.requestDigest(), + null, + null, + null, + true, + false, + true, + false, + new DemoTenantEntitlementRequest.Quotas(3, 1, 500)), + source); + }); assertThat(committed).isNotNull(); int beforeReads = f.transport().reads(); var evaluated = c.owner().evaluateDemo(new Request(f.tenantId(), UUID.randomUUID(), WORLD)); @@ -245,21 +242,19 @@ void pendingDoesNotBecomePositiveAndExplicitDemoUsesOnlyItsActualCurrentOwner() void wrongWorkloadNamespaceAndPlayerRequestsFailBeforeSourceReads() { Context c = context(); var f = c.fixture(); - assertThatThrownBy( - () -> - c.owner() - .evaluatePaid( - new Request( - f.tenantId(), - UUID.randomUUID(), - "spiffe://firemud/ns/another/sa/world-management-service"))) + assertThatThrownBy(() -> + c.owner() + .evaluatePaid( + new Request( + f.tenantId(), + UUID.randomUUID(), + "spiffe://firemud/ns/another/sa/world-management-service"))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new Request( - f.tenantId(), - UUID.randomUUID(), - "spiffe://firemud/ns/prod/sa/game-session-service")) + assertThatThrownBy(() -> + new Request( + f.tenantId(), + UUID.randomUUID(), + "spiffe://firemud/ns/prod/sa/game-session-service")) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> new Request(new UUID(0L, 0L), UUID.randomUUID(), WORLD)) .isInstanceOf(IllegalArgumentException.class); @@ -272,12 +267,10 @@ private static void assertActualTenantCheckpoint( var expected = c.fixture() .transaction() - .execute( - status -> - new AccountAuthorityOutboxRepository(c.fixture().dsl()) - .readCheckpoint( - TenantAuthorityEventV1Codec.streamKey(c.fixture().tenantId())) - .orElseThrow()); + .execute(status -> + new AccountAuthorityOutboxRepository(c.fixture().dsl()) + .readCheckpoint(TenantAuthorityEventV1Codec.streamKey(c.fixture().tenantId())) + .orElseThrow()); assertThat(expected).isNotNull(); var actual = (List>) value.fields().get("outboxCheckpoints"); assertThat(actual) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java index d2d23bdc9c..b0d13305eb 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java @@ -135,30 +135,29 @@ void v126_2PreservesRetainedPreparedRowAndDeniesCurrentUseAndAdvance() { byte[] bundle = bytes("{\"authoritySourceVersions\":[],\"bundleRef\":{}}"); byte[] signerReceipt = bytes("test-only-historical-signer-receipt"); // Historical V126.1 fixture seeding uses real owner IDs but is not a production issuance path. - c.tx( - () -> - c.dsl.execute( - "INSERT INTO account_control_ui_issuance_operations" - + " (request_id, operation_id, token_jti, account_uuid, tenant_uuid, caller_workload, caller_context_id," - + " request_mac_key_id, request_digest, claims_payload, source_payload, bundle_payload, signer_receipt," - + " issued_at_epoch_second, expires_at_epoch_second, recovery_expires_at, status)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, 'PREPARED')", - f.request, - operationId, - tokenJti, - f.actor, - f.tenant, - "spiffe://test-only/control-ui", - UUID.randomUUID(), - "historical-test", - "c".repeat(64), - claims, - source, - bundle, - signerReceipt, - issuedAt.getEpochSecond(), - expiresAt.getEpochSecond(), - recoveryExpiresAt)); + c.tx(() -> + c.dsl.execute( + "INSERT INTO account_control_ui_issuance_operations" + + " (request_id, operation_id, token_jti, account_uuid, tenant_uuid, caller_workload, caller_context_id," + + " request_mac_key_id, request_digest, claims_payload, source_payload, bundle_payload, signer_receipt," + + " issued_at_epoch_second, expires_at_epoch_second, recovery_expires_at, status)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, 'PREPARED')", + f.request, + operationId, + tokenJti, + f.actor, + f.tenant, + "spiffe://test-only/control-ui", + UUID.randomUUID(), + "historical-test", + "c".repeat(64), + claims, + source, + bundle, + signerReceipt, + issuedAt.getEpochSecond(), + expiresAt.getEpochSecond(), + recoveryExpiresAt)); var before = Objects.requireNonNull( c.dsl.fetchOne( @@ -180,16 +179,14 @@ void v126_2PreservesRetainedPreparedRowAndDeniesCurrentUseAndAdvance() { var retained = c.tx(() -> c.operations.findRequest(f.request)); assertThat(retained.status).isEqualTo("PREPARED"); assertThatThrownBy(retained::expiryMillis).isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - c.tx( - () -> - c.operations.bindCandidate( - retained, - "d".repeat(64), - bytes("test-only-envelope"), - bytes("test-only-binding"), - f.signer))) + assertThatThrownBy(() -> + c.tx(() -> + c.operations.bindCandidate( + retained, + "d".repeat(64), + bytes("test-only-envelope"), + bytes("test-only-binding"), + f.signer))) .isInstanceOf(IllegalStateException.class); assertThat(c.dsl.fetchCount(DSL.table("account_control_ui_response_envelopes"))).isZero(); var afterDeniedAdvance = @@ -227,55 +224,47 @@ void changedOriginalAndDirectSqlByteOrTimingChangesCannotRewriteRetainedOperatio .isInstanceOf(IllegalStateException.class); for (String column : List.of("claims_payload", "source_payload", "bundle_payload", "signer_receipt")) { - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - "UPDATE account_control_ui_issuance_operations SET " - + column - + " = ? WHERE request_id = ?", - bytes("test-only-rewrite"), - prepared.requestId))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + "UPDATE account_control_ui_issuance_operations SET " + + column + + " = ? WHERE request_id = ?", + bytes("test-only-rewrite"), + prepared.requestId))) .isInstanceOf(DataAccessException.class); } - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - "UPDATE account_control_ui_issuance_operations" - + " SET recovery_expires_at = recovery_expires_at + INTERVAL '1 second' WHERE request_id = ?", - prepared.requestId))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + "UPDATE account_control_ui_issuance_operations" + + " SET recovery_expires_at = recovery_expires_at + INTERVAL '1 second' WHERE request_id = ?", + prepared.requestId))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - "UPDATE account_control_ui_response_envelopes" - + " SET encrypted_response = ? WHERE operation_id = ?", - bytes("test-only-envelope-rewrite"), - prepared.operationId))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + "UPDATE account_control_ui_response_envelopes" + + " SET encrypted_response = ? WHERE operation_id = ?", + bytes("test-only-envelope-rewrite"), + prepared.operationId))) .isInstanceOf(DataAccessException.class); // A new row cannot evade the actual PostgreSQL-specific recovery bound either. - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - "INSERT INTO account_control_ui_issuance_operations" - + " (request_id, operation_id, token_jti, account_uuid, tenant_uuid, caller_workload, caller_context_id," - + " request_mac_key_id, request_digest, claims_payload, source_payload, bundle_payload, signer_receipt," - + " issued_at_epoch_second, expires_at_epoch_second, registry_cleanup_deadline_epoch_millis, recovery_expires_at, status)" - + " SELECT ?, ?, ?, account_uuid, tenant_uuid, caller_workload, caller_context_id, request_mac_key_id," - + " request_digest, claims_payload, source_payload, bundle_payload, signer_receipt, issued_at_epoch_second," - + " expires_at_epoch_second, registry_cleanup_deadline_epoch_millis, to_timestamp(issued_at_epoch_second + 61), 'PREPARED'" - + " FROM account_control_ui_issuance_operations WHERE request_id = ?", - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - prepared.requestId))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + "INSERT INTO account_control_ui_issuance_operations" + + " (request_id, operation_id, token_jti, account_uuid, tenant_uuid, caller_workload, caller_context_id," + + " request_mac_key_id, request_digest, claims_payload, source_payload, bundle_payload, signer_receipt," + + " issued_at_epoch_second, expires_at_epoch_second, registry_cleanup_deadline_epoch_millis, recovery_expires_at, status)" + + " SELECT ?, ?, ?, account_uuid, tenant_uuid, caller_workload, caller_context_id, request_mac_key_id," + + " request_digest, claims_payload, source_payload, bundle_payload, signer_receipt, issued_at_epoch_second," + + " expires_at_epoch_second, registry_cleanup_deadline_epoch_millis, to_timestamp(issued_at_epoch_second + 61), 'PREPARED'" + + " FROM account_control_ui_issuance_operations WHERE request_id = ?", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + prepared.requestId))) .isInstanceOf(DataAccessException.class) .hasMessageContaining("account_control_ui_recovery_expiry_bound"); assertOriginal(prepared, c.tx(() -> c.operations.findRequest(prepared.requestId))); @@ -316,11 +305,10 @@ void changedOriginalAndDirectSqlByteOrTimingChangesCannotRewriteRetainedOperatio byte[] revoked = AccountControlUiIssuanceRepository.revokedRegistry(held); doReturn(held.pendingRegistry, revoked).when(transport.commands).get(any(byte[].class)); var receipt = transport.client.revoke(held); - c.tx( - () -> { - c.operations.finishRecoveryFailure(held, receipt); - return null; - }); + c.tx(() -> { + c.operations.finishRecoveryFailure(held, receipt); + return null; + }); assertThat(c.tx(() -> c.operations.findRequest(prepared.requestId)).status) .isEqualTo("REVOKED"); assertThatThrownBy(() -> c.tx(() -> c.operations.requireCommitted(committed.stored))) @@ -395,29 +383,27 @@ private static final class Fixture { Fixture(Context c) { this.c = c; actor = - c.tx( - () -> { - Account account = new Account(); - String suffix = UUID.randomUUID().toString(); - account.setUsername("control-ui-" + suffix); - account.setEmail(suffix + "@example.test"); - account.setPasswordHash("test-only-primary-hash"); - return new AccountRepository(c.dsl).save(account).getAccountUuid(); - }); + c.tx(() -> { + Account account = new Account(); + String suffix = UUID.randomUUID().toString(); + account.setUsername("control-ui-" + suffix); + account.setEmail(suffix + "@example.test"); + account.setPasswordHash("test-only-primary-hash"); + return new AccountRepository(c.dsl).save(account).getAccountUuid(); + }); // Stipulated external creation evidence only; real source/claim triggers still execute. - c.tx( - () -> - c.dsl.execute( - "INSERT INTO account_fresh_tenant_identity_associations" - + " (schema_version, target_namespace, creation_request_id, operation_id, request_digest," - + " canonical_tenant_id, source_game_row_id, source_game_tenant_key, provenance_kind, evidence_digest)" - + " VALUES (1, 'test-control', ?, ?, ?, ?, 1, ?, 'NEW_GAME_ROW', ?)", - UUID.randomUUID(), - UUID.randomUUID(), - "sha256:" + "a".repeat(64), - tenant, - tenant.toString(), - "sha256:" + "b".repeat(64))); + c.tx(() -> + c.dsl.execute( + "INSERT INTO account_fresh_tenant_identity_associations" + + " (schema_version, target_namespace, creation_request_id, operation_id, request_digest," + + " canonical_tenant_id, source_game_row_id, source_game_tenant_key, provenance_kind, evidence_digest)" + + " VALUES (1, 'test-control', ?, ?, ?, ?, 1, ?, 'NEW_GAME_ROW', ?)", + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + "a".repeat(64), + tenant, + tenant.toString(), + "sha256:" + "b".repeat(64))); when(primary.accountId()).thenReturn(actor); when(authority.actor()).thenReturn(actor); when(authority.tenant()).thenReturn(tenant); @@ -463,27 +449,25 @@ AccountControlUiIssuanceRepository.Stored prepare() { } AccountControlUiIssuanceRepository.Stored prepare(long sessionSafetyMarginMillis) { - return c.tx( - () -> - c.operations.prepare( - request, - "spiffe://test-only/control-ui", - UUID.randomUUID(), - "test-mac1", - "c".repeat(64), - primary, - authority, - signer, - Instant.ofEpochSecond(Instant.now().getEpochSecond()), - sessionSafetyMarginMillis)); + return c.tx(() -> + c.operations.prepare( + request, + "spiffe://test-only/control-ui", + UUID.randomUUID(), + "test-mac1", + "c".repeat(64), + primary, + authority, + signer, + Instant.ofEpochSecond(Instant.now().getEpochSecond()), + sessionSafetyMarginMillis)); } AccountControlUiIssuanceRepository.Stored candidate( AccountControlUiIssuanceRepository.Stored original) { - return c.tx( - () -> - c.operations.bindCandidate( - original, "d".repeat(64), encryptedResponse, ownerBinding, signer)); + return c.tx(() -> + c.operations.bindCandidate( + original, "d".repeat(64), encryptedResponse, ownerBinding, signer)); } } @@ -507,9 +491,8 @@ private static final class Transport { when(connection.sync()).thenReturn(commands); when(commands.aclWhoami()).thenReturn("account_coord_app"); when(commands.scriptLoad(any(byte[].class))) - .thenAnswer( - invocation -> - AccountControlUiCoordination.digest("SHA-1", invocation.getArgument(0))); + .thenAnswer(invocation -> + AccountControlUiCoordination.digest("SHA-1", invocation.getArgument(0))); doReturn(1L) .when(commands) .evalsha( diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java index 23dc02b9f1..07336a3803 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java @@ -539,19 +539,17 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() .setCurrentClaimFence(claimEvidence.currentClaimFence()) .build(); - assertThatThrownBy( - () -> - accountTransport - .gameDesign() - .issueHumanOperatorAuthorizationReference(issueRequest)) + assertThatThrownBy(() -> + accountTransport + .gameDesign() + .issueHumanOperatorAuthorizationReference(issueRequest)) .isInstanceOf(StatusRuntimeException.class) .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) .isEqualTo(Status.Code.PERMISSION_DENIED); assertThat( - f.tx( - () -> - operatorRepository.findByControlPlaneRequestId( - tuple.controlPlaneRequestId()))) + f.tx(() -> + operatorRepository.findByControlPlaneRequestId( + tuple.controlPlaneRequestId()))) .isEmpty(); var issuedOperator = @@ -568,11 +566,10 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() .setCurrentClaimFence(claimEvidence.currentClaimFence()) .build(); - assertThatThrownBy( - () -> - accountTransport - .logging() - .recoverOperatorAuthorizationReference(staleRecoveryRequest)) + assertThatThrownBy(() -> + accountTransport + .logging() + .recoverOperatorAuthorizationReference(staleRecoveryRequest)) .isInstanceOf(StatusRuntimeException.class) .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) .isEqualTo(Status.Code.INVALID_ARGUMENT); @@ -695,21 +692,17 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() ByteString.copyFrom( changedTuple.canonicalJson().getBytes(StandardCharsets.UTF_8))) .build(); - assertThatThrownBy( - () -> - accountTransport - .gameDesign() - .readRedeemedOperationProjection(wrongOperationRead)) + assertThatThrownBy(() -> + accountTransport.gameDesign().readRedeemedOperationProjection(wrongOperationRead)) .isInstanceOf(StatusRuntimeException.class) .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) .isEqualTo(Status.Code.FAILED_PRECONDITION); var storedAfterDeniedRead = - f.tx( - () -> - operatorRepository - .findByControlPlaneRequestId(tuple.controlPlaneRequestId()) - .orElseThrow()); + f.tx(() -> + operatorRepository + .findByControlPlaneRequestId(tuple.controlPlaneRequestId()) + .orElseThrow()); assertThat(storedAfterDeniedRead.status()) .isEqualTo(AccountStartSessionOperatorAuthorizationRepository.Status.REDEEMED); assertThat(storedAfterDeniedRead.redemptionRedeemerWorkloadUri()) @@ -883,16 +876,15 @@ private static void assertCertifiedAccountSignIn( assertThat(callbackSource).isEqualTo(originalSource.evidence()); // A mutation through the real Account owner shares the consumer transaction and rolls back // together with its generation, source, fence and outbox effects when the callback fails. - assertThatThrownBy( - () -> - actors.withCurrentAccount( - passwordCompact, - actor -> { - var mutation = f.accounts.findByAccountUuid(actor.accountId()).orElseThrow(); - mutation.setRole("admin"); - f.accounts.save(mutation); - throw new IllegalStateException("test-only Account callback rollback"); - })) + assertThatThrownBy(() -> + actors.withCurrentAccount( + passwordCompact, + actor -> { + var mutation = f.accounts.findByAccountUuid(actor.accountId()).orElseThrow(); + mutation.setRole("admin"); + f.accounts.save(mutation); + throw new IllegalStateException("test-only Account callback rollback"); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("test-only Account callback rollback"); assertThat(f.accounts.findById(account.getId()).orElseThrow().getRole()).isNull(); @@ -924,43 +916,39 @@ private static void assertCertifiedAccountSignIn( assertThat(retry.compactBytes()).isEqualTo(originalCompact); assertThat(retry.expiresAt()).isEqualTo(expiry); assertThat(retry.recoveryExpiresAt()).isEqualTo(recoveryExpiry); - assertThatThrownBy( - () -> - issuance.issueAccount( - new AccountControlUiIssuanceService.AccountSignInRequest( - otpRequest.requestId(), - account.getEmail(), - "changed-secret", - otpRequest.callerContextId()))) + assertThatThrownBy(() -> + issuance.issueAccount( + new AccountControlUiIssuanceService.AccountSignInRequest( + otpRequest.requestId(), + account.getEmail(), + "changed-secret", + otpRequest.callerContextId()))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Control-ui issuance idempotency conflict"); - assertThatThrownBy( - () -> - issuance.issueAccount( - new AccountControlUiIssuanceService.AccountSignInRequest( - otpRequest.requestId(), - "changed@example.test", - otp, - otpRequest.callerContextId()))) + assertThatThrownBy(() -> + issuance.issueAccount( + new AccountControlUiIssuanceService.AccountSignInRequest( + otpRequest.requestId(), + "changed@example.test", + otp, + otpRequest.callerContextId()))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Control-ui issuance idempotency conflict"); - assertThatThrownBy( - () -> - issuance.issueAccount( - new AccountControlUiIssuanceService.AccountSignInRequest( - otpRequest.requestId(), account.getEmail(), otp, UUID.randomUUID()))) + assertThatThrownBy(() -> + issuance.issueAccount( + new AccountControlUiIssuanceService.AccountSignInRequest( + otpRequest.requestId(), account.getEmail(), otp, UUID.randomUUID()))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Control-ui issuance idempotency conflict"); - assertThatThrownBy( - () -> - issuance.issue( - new AccountControlUiIssuanceService.Request( - otpRequest.requestId(), - account.getEmail(), - otp, - f.tenant, - otpRequest.callerContextId()), - environment)) + assertThatThrownBy(() -> + issuance.issue( + new AccountControlUiIssuanceService.Request( + otpRequest.requestId(), + account.getEmail(), + otp, + f.tenant, + otpRequest.callerContextId()), + environment)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Control-ui issuance idempotency conflict"); } @@ -992,12 +980,11 @@ private static void assertCertifiedAccountSignIn( } var generations = new AccountAuthorityGenerationRepository(f.dsl); var beforeMutation = f.tx(() -> generations.read(AuthorityScope.account(accountId))); - f.tx( - () -> { - var mutation = f.accounts.findById(account.getId()).orElseThrow(); - mutation.setRole("admin"); - return f.accounts.save(mutation); - }); + f.tx(() -> { + var mutation = f.accounts.findById(account.getId()).orElseThrow(); + mutation.setRole("admin"); + return f.accounts.save(mutation); + }); // A generic scalar-role mutation advances the retained owner history, but it is not a // receipt-bearing operation or canonical global-role authority. Current-source use must deny. var advanced = f.tx(() -> generations.read(AuthorityScope.account(accountId))); @@ -1029,14 +1016,13 @@ private static void assertCertifiedAccountSignIn( .isExactlyInstanceOf(SourceEvidenceUnavailableException.class); for (String compact : List.of(passwordCompact, otpCompact)) { var invoked = new java.util.concurrent.atomic.AtomicBoolean(); - assertThatThrownBy( - () -> - actors.withCurrentAccount( - compact, - actor -> { - invoked.set(true); - return actor.accountId(); - })) + assertThatThrownBy(() -> + actors.withCurrentAccount( + compact, + actor -> { + invoked.set(true); + return actor.accountId(); + })) .isExactlyInstanceOf(SourceEvidenceUnavailableException.class); assertThat(invoked).isFalse(); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java index 238822168b..8de410ce9c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationPostgresIntegrationTest.java @@ -74,20 +74,16 @@ void passwordAuthenticatesPersistedCanonicalUuidAndWrongSecretDoesNotMutate() { Account account = c.account("PASSWORD"); String before = c.accountBytes(account.getAccountUuid()); UUID authenticated = - c.tx( - () -> - c.primary - .authenticateControlUiPrimaryIdentity(account.getEmail(), PASSWORD) - .accountId()); + c.tx(() -> + c.primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), PASSWORD) + .accountId()); assertThat(authenticated).isEqualTo(account.getAccountUuid()); assertThat(account.getAccountUuidSourceNumericId()).isEqualTo(account.getId()); assertThat(c.accountBytes(account.getAccountUuid())).isEqualTo(before); - assertThatThrownBy( - () -> - c.tx( - () -> - c.primary.authenticateControlUiPrimaryIdentity( - account.getEmail(), "wrong-secret"))) + assertThatThrownBy(() -> + c.tx(() -> + c.primary.authenticateControlUiPrimaryIdentity(account.getEmail(), "wrong-secret"))) .isInstanceOf(AuthenticationException.class); assertThat(c.accountBytes(account.getAccountUuid())).isEqualTo(before); } @@ -96,13 +92,11 @@ void passwordAuthenticatesPersistedCanonicalUuidAndWrongSecretDoesNotMutate() { void freshAccountCannotBeCreatedInSecurityLockedStateAndLeavesNoRows() { Context c = context(); Account lockedAccount = c.accountCandidate("PASSWORD", AccountLifecycleState.SECURITY_LOCKED); - assertThatThrownBy( - () -> - c.tx( - () -> { - c.accounts.save(lockedAccount); - return null; - })) + assertThatThrownBy(() -> + c.tx(() -> { + c.accounts.save(lockedAccount); + return null; + })) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Fresh Accounts must be created in the ACTIVE lifecycle state"); @@ -119,36 +113,28 @@ void exactOtpConsumptionParticipatesInOwnerRollbackAndCannotBeReplayedAfterCommi Context c = context(); Account account = c.account("EMAIL_OTP"); AccountEmailLoginChallenge original = c.challenge(account); - assertThatThrownBy( - () -> - c.tx( - () -> - c.primary.authenticateControlUiPrimaryIdentity( - account.getEmail(), "wrong-otp"))) + assertThatThrownBy(() -> + c.tx(() -> + c.primary.authenticateControlUiPrimaryIdentity(account.getEmail(), "wrong-otp"))) .isInstanceOf(AuthenticationException.class); assertThat(c.challenges.findByAccountId(account.getId())).contains(original); - c.transaction.executeWithoutResult( - status -> { - assertThat( - c.primary - .authenticateControlUiPrimaryIdentity(account.getEmail(), OTP) - .accountId()) - .isEqualTo(account.getAccountUuid()); - assertThat(c.challenges.findByAccountId(account.getId())).isEmpty(); - status.setRollbackOnly(); - }); + c.transaction.executeWithoutResult(status -> { + assertThat( + c.primary.authenticateControlUiPrimaryIdentity(account.getEmail(), OTP).accountId()) + .isEqualTo(account.getAccountUuid()); + assertThat(c.challenges.findByAccountId(account.getId())).isEmpty(); + status.setRollbackOnly(); + }); assertThat(c.challenges.findByAccountId(account.getId())).contains(original); assertThat( - c.tx( - () -> - c.primary - .authenticateControlUiPrimaryIdentity(account.getEmail(), OTP) - .accountId())) + c.tx(() -> + c.primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), OTP) + .accountId())) .isEqualTo(account.getAccountUuid()); assertThat(c.challenges.findByAccountId(account.getId())).isEmpty(); - assertThatThrownBy( - () -> - c.tx(() -> c.primary.authenticateControlUiPrimaryIdentity(account.getEmail(), OTP))) + assertThatThrownBy(() -> + c.tx(() -> c.primary.authenticateControlUiPrimaryIdentity(account.getEmail(), OTP))) .isInstanceOf(AuthenticationException.class); assertThat(c.challenges.findByAccountId(account.getId())).isEmpty(); } @@ -167,31 +153,27 @@ void concurrentOtpAttemptsSerializeOnActualPostgresOwnerLockAndOnlyOneAuthentica var executor = Executors.newFixedThreadPool(2); try { var first = - executor.submit( - () -> - c.tx( - () -> { - firstPid.set(c.pid()); - UUID actor = - c.primary - .authenticateControlUiPrimaryIdentity(account.getEmail(), OTP) - .accountId(); - firstAuthenticated.countDown(); - awaitLatch(releaseFirst); - return actor; - })); + executor.submit(() -> + c.tx(() -> { + firstPid.set(c.pid()); + UUID actor = + c.primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), OTP) + .accountId(); + firstAuthenticated.countDown(); + awaitLatch(releaseFirst); + return actor; + })); awaitLatch(firstAuthenticated); var second = - executor.submit( - () -> - c.tx( - () -> { - secondPid.set(c.pid()); - secondEntered.countDown(); - return c.primary - .authenticateControlUiPrimaryIdentity(account.getEmail(), OTP) - .accountId(); - })); + executor.submit(() -> + c.tx(() -> { + secondPid.set(c.pid()); + secondEntered.countDown(); + return c.primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), OTP) + .accountId(); + })); awaitLatch(secondEntered); awaitBlocked(c, secondPid.get(), firstPid.get()); assertThat(first.isDone()).isFalse(); @@ -216,12 +198,11 @@ void resetThatOwnsTheAccountLockFirstMakesIssuanceVerifyTheCommittedNewPassword( var releaseReset = new CountDownLatch(1); var resetPid = new AtomicInteger(); Context c = - context( - dsl -> { - resetPid.set(backendPid(dsl)); - resetLocked.countDown(); - awaitLatch(releaseReset); - }); + context(dsl -> { + resetPid.set(backendPid(dsl)); + resetLocked.countDown(); + awaitLatch(releaseReset); + }); Account account = c.account("PASSWORD"); String resetToken = c.passwordResetToken(account); var issuerEntered = new CountDownLatch(1); @@ -229,22 +210,19 @@ void resetThatOwnsTheAccountLockFirstMakesIssuanceVerifyTheCommittedNewPassword( var executor = Executors.newFixedThreadPool(2); try { var reset = - executor.submit( - () -> - c.primary.completePasswordReset( - new CompletePasswordResetRequest(resetToken, RESET_PASSWORD))); + executor.submit(() -> + c.primary.completePasswordReset( + new CompletePasswordResetRequest(resetToken, RESET_PASSWORD))); awaitLatch(resetLocked); var issuance = - executor.submit( - () -> - c.tx( - () -> { - issuerPid.set(c.pid()); - issuerEntered.countDown(); - return c.primary - .authenticateControlUiPrimaryIdentity(account.getEmail(), PASSWORD) - .accountId(); - })); + executor.submit(() -> + c.tx(() -> { + issuerPid.set(c.pid()); + issuerEntered.countDown(); + return c.primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), PASSWORD) + .accountId(); + })); awaitLatch(issuerEntered); awaitBlocked(c, issuerPid.get(), resetPid.get()); assertThat(issuance.isDone()).isFalse(); @@ -255,11 +233,10 @@ void resetThatOwnsTheAccountLockFirstMakesIssuanceVerifyTheCommittedNewPassword( .isInstanceOf(ExecutionException.class) .hasCauseInstanceOf(AuthenticationException.class); assertThat( - c.tx( - () -> - c.primary - .authenticateControlUiPrimaryIdentity(account.getEmail(), RESET_PASSWORD) - .accountId())) + c.tx(() -> + c.primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), RESET_PASSWORD) + .accountId())) .isEqualTo(account.getAccountUuid()); assertResetAuthorityCommitted(c, account); } finally { @@ -280,44 +257,37 @@ void issuanceKeepsTheAccountLockUntilItsCallerTransactionCommitsBeforeReset() th var executor = Executors.newFixedThreadPool(2); try { var issuance = - executor.submit( - () -> - c.tx( - () -> { - issuerPid.set(c.pid()); - UUID actor = - c.primary - .authenticateControlUiPrimaryIdentity(account.getEmail(), PASSWORD) - .accountId(); - issuanceAuthenticated.countDown(); - awaitLatch(releaseIssuance); - return actor; - })); + executor.submit(() -> + c.tx(() -> { + issuerPid.set(c.pid()); + UUID actor = + c.primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), PASSWORD) + .accountId(); + issuanceAuthenticated.countDown(); + awaitLatch(releaseIssuance); + return actor; + })); awaitLatch(issuanceAuthenticated); var reset = - executor.submit( - () -> - c.primary.completePasswordReset( - new CompletePasswordResetRequest(resetToken, RESET_PASSWORD))); + executor.submit(() -> + c.primary.completePasswordReset( + new CompletePasswordResetRequest(resetToken, RESET_PASSWORD))); awaitAnyBlockedBy(c, issuerPid.get()); assertThat(reset.isDone()).isFalse(); releaseIssuance.countDown(); assertThat(issuance.get(10, TimeUnit.SECONDS)).isEqualTo(account.getAccountUuid()); reset.get(10, TimeUnit.SECONDS); - assertThatThrownBy( - () -> - c.tx( - () -> - c.primary.authenticateControlUiPrimaryIdentity( - account.getEmail(), PASSWORD))) + assertThatThrownBy(() -> + c.tx(() -> + c.primary.authenticateControlUiPrimaryIdentity(account.getEmail(), PASSWORD))) .isInstanceOf(AuthenticationException.class); assertThat( - c.tx( - () -> - c.primary - .authenticateControlUiPrimaryIdentity(account.getEmail(), RESET_PASSWORD) - .accountId())) + c.tx(() -> + c.primary + .authenticateControlUiPrimaryIdentity(account.getEmail(), RESET_PASSWORD) + .accountId())) .isEqualTo(account.getAccountUuid()); assertResetAuthorityCommitted(c, account); } finally { @@ -520,31 +490,29 @@ private long count(String query) { } AccountEmailLoginChallenge challenge(Account account) { - return tx( - () -> { - var challenge = new AccountEmailLoginChallenge(); - var now = LocalDateTime.now().withNano(0); - challenge.setAccountId(account.getId()); - challenge.setCodeHash(hash(OTP)); - challenge.setExpiresAt(now.plusMinutes(5)); - challenge.setResendAvailableAt(now.plusMinutes(1)); - challenge.setCreatedAt(now); - challenge.setUpdatedAt(now); - return challenges.save(challenge); - }); + return tx(() -> { + var challenge = new AccountEmailLoginChallenge(); + var now = LocalDateTime.now().withNano(0); + challenge.setAccountId(account.getId()); + challenge.setCodeHash(hash(OTP)); + challenge.setExpiresAt(now.plusMinutes(5)); + challenge.setResendAvailableAt(now.plusMinutes(1)); + challenge.setCreatedAt(now); + challenge.setUpdatedAt(now); + return challenges.save(challenge); + }); } String passwordResetToken(Account account) { String rawToken = "test-only-reset-token-" + UUID.randomUUID(); - tx( - () -> { - var token = new PasswordResetToken(); - token.setAccount(account); - token.setToken(rawToken); - token.setExpiresAt(LocalDateTime.now().plusHours(1)); - resetTokens.save(token); - return null; - }); + tx(() -> { + var token = new PasswordResetToken(); + token.setAccount(account); + token.setToken(rawToken); + token.setExpiresAt(LocalDateTime.now().plusHours(1)); + resetTokens.save(token); + return null; + }); return rawToken; } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java index bf01191e01..8b8b1667de 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationPostgresIntegrationTest.java @@ -120,10 +120,9 @@ void retainedOriginNamespaceFencesHeldTerminalDispatchAndSettlementReplay() thro new AccountGameLogicIntakeAuthorizationService( issued.actors(), f.fences, repository, sources, f.manager, "test"); var order = - asGameDesign( - () -> - authorizer.authorize( - issued.compact(), UUID.randomUUID(), selected, issued.environment())); + asGameDesign(() -> + authorizer.authorize( + issued.compact(), UUID.randomUUID(), selected, issued.environment())); var held = new AccountGameLogicIntakeAuthorizationReadService(repository, f.manager, "test"); asPeer( "test", @@ -139,22 +138,19 @@ void retainedOriginNamespaceFencesHeldTerminalDispatchAndSettlementReplay() thro var wrongSettlement = new AccountGameLogicIntakeSettlementService(repository, terminals, f.manager, "other"); var before = retainedIntakeRows(f.dsl); - assertThatThrownBy( - () -> - asPeer( - "other", - "game-logic-service", - () -> { - wrongHeld.requireHeld( - GameLogicIntakeAuthorizationReadEvidence.Request.create( - "other", order)); - return null; - })) + assertThatThrownBy(() -> + asPeer( + "other", + "game-logic-service", + () -> { + wrongHeld.requireHeld( + GameLogicIntakeAuthorizationReadEvidence.Request.create("other", order)); + return null; + })) .isInstanceOf(io.grpc.StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(io.grpc.Status.fromThrowable(failure).getCode()) - .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); assertThatThrownBy( () -> asPeer("other", "game-design-service", () -> wrongSettlement.settle(order))) .isInstanceOf(IllegalArgumentException.class) @@ -163,10 +159,8 @@ void retainedOriginNamespaceFencesHeldTerminalDispatchAndSettlementReplay() thro var wrongTerminal = GameLogicGameplayRuleIntakeTerminal.aborted( new GameLogicGameplayRuleIntakeOperation("other", order)); - assertThatThrownBy( - () -> - f.tx( - () -> repository.settle(new AccountGameLogicIntakeSettlement(wrongTerminal)))) + assertThatThrownBy(() -> + f.tx(() -> repository.settle(new AccountGameLogicIntakeSettlement(wrongTerminal)))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Changed original source namespace"); String genesis = @@ -180,13 +174,11 @@ void retainedOriginNamespaceFencesHeldTerminalDispatchAndSettlementReplay() thro new GameplayRuleSelectedSource( source.snapshotJson().replace(genesis, UUID.randomUUID().toString())), order.sources()); - assertThatThrownBy( - () -> - f.tx( - () -> { - repository.readHeld(changedOrder, "test"); - return null; - })) + assertThatThrownBy(() -> + f.tx(() -> { + repository.readHeld(changedOrder, "test"); + return null; + })) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Original intake order absent or changed"); assertThat(retainedIntakeRows(f.dsl)).isEqualTo(before); @@ -196,10 +188,9 @@ void retainedOriginNamespaceFencesHeldTerminalDispatchAndSettlementReplay() thro var terminal = GameLogicGameplayRuleIntakeTerminal.aborted( new GameLogicGameplayRuleIntakeOperation("test", order)); - doAnswer( - call -> - new GameLogicIntakeTerminalReadEvidence( - call.getArgument(0), java.util.Optional.of(terminal))) + doAnswer(call -> + new GameLogicIntakeTerminalReadEvidence( + call.getArgument(0), java.util.Optional.of(terminal))) .when(terminals) .read(any()); var settlement = @@ -287,42 +278,37 @@ void distinctPendingIntakeRequiresSettledAuthorAndBlocksRealSourceWritersAndDisc issued.actors(), f.fences, repository, gd, f.manager, "test"); var requestId = UUID.randomUUID(); - assertThatThrownBy( - () -> - asGameDesign( - () -> - service.authorize( - issued.compact(), requestId, selected, issued.environment()))) + assertThatThrownBy(() -> + asGameDesign(() -> + service.authorize(issued.compact(), requestId, selected, issued.environment()))) .isInstanceOf(IllegalStateException.class); verifyNoInteractions(gd); assertThat( f.dsl.fetchCount(org.jooq.impl.DSL.table("account_game_logic_intake_authorizations"))) .isZero(); - f.tx( - () -> { - f.fences.recordOwnerReadback( - original, - new DraftAuthorizationFenceBinding.OwnerReadback( - DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, - DraftAuthorizationFenceBinding.Outcome.COMMITTED, - original.operationId(), - original.commitId(), - original.fenceId(), - original.inputDigest(), - original.canonicalBytes(), - new byte[] {1})); - return null; - }); + f.tx(() -> { + f.fences.recordOwnerReadback( + original, + new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.canonicalBytes(), + new byte[] {1})); + return null; + }); var order = asGameDesign( () -> service.authorize(issued.compact(), requestId, selected, issued.environment())); assertThat(order.source()).isEqualTo(source); assertThat(order.sources()).hasSize(captured.sources().size()); assertThat( - asGameDesign( - () -> - service.authorize( - issued.compact(), requestId, selected, issued.environment())) + asGameDesign(() -> + service.authorize( + issued.compact(), requestId, selected, issued.environment())) .canonicalBytes()) .isEqualTo(order.canonicalBytes()); String genesis = @@ -335,10 +321,9 @@ void distinctPendingIntakeRequiresSettledAuthorAndBlocksRealSourceWritersAndDisc .read(any()); clearInvocations(gd); assertThat( - asGameDesign( - () -> - service.authorize( - issued.compact(), requestId, selected, issued.environment())) + asGameDesign(() -> + service.authorize( + issued.compact(), requestId, selected, issued.environment())) .canonicalBytes()) .isEqualTo(order.canonicalBytes()); verifyNoInteractions(gd); @@ -347,58 +332,51 @@ void distinctPendingIntakeRequiresSettledAuthorAndBlocksRealSourceWritersAndDisc .read(any()); UUID rolledBackRequest = UUID.randomUUID(); - assertThatThrownBy( - () -> - issued - .actors() - .withCurrent( - issued.compact(), - f.tenant, - issued.environment(), - current -> { - f.fences.lockProducerSourcesNowait(current.source().sources()); - repository.reserveSourceRead( - rolledBackRequest, - selected, - current, - "test", - () -> - f.fences.requireGameLogicIntakeAdmission( - current.source().sources(), selected)); - throw new IllegalStateException("rollback before owner commit"); - })) + assertThatThrownBy(() -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> { + f.fences.lockProducerSourcesNowait(current.source().sources()); + repository.reserveSourceRead( + rolledBackRequest, + selected, + current, + "test", + () -> + f.fences.requireGameLogicIntakeAdmission( + current.source().sources(), selected)); + throw new IllegalStateException("rollback before owner commit"); + })) .isInstanceOf(IllegalStateException.class); assertThat( f.dsl.fetchOne( "SELECT 1 FROM account_game_logic_intake_source_read_reservations WHERE intake_request_id = ?", rolledBackRequest)) .isNull(); - f.tx( - () -> { - repository.readHeld(order, "test"); - return null; - }); - assertThatThrownBy( - () -> - f.tx( - () -> { - f.fences.requireDisclosurePreparation(order.sources()); - return null; - })) + f.tx(() -> { + repository.readHeld(order, "test"); + return null; + }); + assertThatThrownBy(() -> + f.tx(() -> { + f.fences.requireDisclosurePreparation(order.sources()); + return null; + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("intake"); // Only the distinct intake is pending; original Draft settlement is already COMMITTED. assertThat(f.tx(() -> f.fences.readSettlement(original))) .isEqualTo(DraftAuthorizationFenceRepository.Settlement.COMMITTED); - assertThatThrownBy( - () -> - f.tx( - () -> { - f.dsl.execute( - "UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()); - return null; - })) + assertThatThrownBy(() -> + f.tx(() -> { + f.dsl.execute("UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()); + return null; + })) .hasStackTraceContaining("Distinct Game Logic intake remains pending"); var change = @@ -407,32 +385,24 @@ void distinctPendingIntakeRequiresSettledAuthorAndBlocksRealSourceWritersAndDisc assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isFalse(); assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isFalse(); assertThat(f.tx(() -> f.fences.sourceAbortPermitted(change))).isFalse(); - f.tx( - () -> { - repository.readHeld(order, "test"); - return null; - }); + f.tx(() -> { + repository.readHeld(order, "test"); + return null; + }); - assertThatThrownBy( - () -> - f.tx( - () -> { - f.dsl.execute( - "UPDATE account_game_logic_intake_authorizations SET source_digest = ? WHERE operation_id = ?", - "sha256:" + "0".repeat(64), - order.operationId()); - return null; - })) + assertThatThrownBy(() -> + f.tx(() -> { + f.dsl.execute( + "UPDATE account_game_logic_intake_authorizations SET source_digest = ? WHERE operation_id = ?", + "sha256:" + "0".repeat(64), + order.operationId()); + return null; + })) .hasStackTraceContaining("immutable"); - assertThatThrownBy( - () -> - asGameDesign( - () -> - service.authorize( - "invalid-credential", - UUID.randomUUID(), - selected, - issued.environment()))) + assertThatThrownBy(() -> + asGameDesign(() -> + service.authorize( + "invalid-credential", UUID.randomUUID(), selected, issued.environment()))) .isInstanceOf(RuntimeException.class); } } @@ -500,21 +470,17 @@ public Instant instant() { }) .when(gd) .read(any()); - assertThatThrownBy( - () -> - asGameDesign( - () -> - service.authorize( - issued.compact(), requestId, selected, issued.environment()))) + assertThatThrownBy(() -> + asGameDesign(() -> + service.authorize(issued.compact(), requestId, selected, issued.environment()))) .isInstanceOf(io.grpc.StatusRuntimeException.class); var recovered = asGameDesign(() -> service.recover(issued.compact(), requestId, selected)); assertThat(recovered.state()) .isEqualTo(AccountGameLogicIntakeSourceReadRecovery.State.RESERVED); assertThat( - asGameDesign( - () -> - service.reserveSourceRead( - issued.compact(), requestId, selected, issued.environment())) + asGameDesign(() -> + service.reserveSourceRead( + issued.compact(), requestId, selected, issued.environment())) .canonicalBytes()) .isEqualTo(recovered.scope().canonicalBytes()); doAnswer( @@ -523,74 +489,58 @@ public Instant instant() { }) .when(gd) .read(any()); - assertThatThrownBy( - () -> - asGameDesign( - () -> - service.authorize( - issued.compact(), requestId, selected, issued.environment()))) + assertThatThrownBy(() -> + asGameDesign(() -> + service.authorize(issued.compact(), requestId, selected, issued.environment()))) .isInstanceOf(io.grpc.StatusRuntimeException.class) .hasMessageContaining("PERMISSION_DENIED"); assertThat(asGameDesign(() -> service.recover(issued.compact(), requestId, selected)).scope()) .isEqualTo(recovered.scope()); var originalSources = f.tx(() -> f.authority.captureInitial(f.tenant, issued.environment())).sources(); - assertThatThrownBy( - () -> - f.tx( - () -> { - f.fences.requireDisclosurePreparation(originalSources); - return null; - })) + assertThatThrownBy(() -> + f.tx(() -> { + f.fences.requireDisclosurePreparation(originalSources); + return null; + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("intake"); - assertThatThrownBy( - () -> - f.tx( - () -> { - f.dsl.execute( - "UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()); - return null; - })) + assertThatThrownBy(() -> + f.tx(() -> { + f.dsl.execute("UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()); + return null; + })) .hasStackTraceContaining("Preliminary Game Logic source read remains pending"); - assertThatThrownBy( - () -> - asGameDesign( - () -> service.recover("different-original-credential", requestId, selected))) + assertThatThrownBy(() -> + asGameDesign( + () -> service.recover("different-original-credential", requestId, selected))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("conflicts"); - assertThatThrownBy( - () -> - asGameDesign( - () -> service.recover(issued.compact(), requestId, selected(f.tenant)))) + assertThatThrownBy(() -> + asGameDesign(() -> service.recover(issued.compact(), requestId, selected(f.tenant)))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("conflicts"); clearInvocations(gd); offsetSeconds.set(600); assertThat(asGameDesign(() -> service.recover(issued.compact(), requestId, selected)).scope()) .isEqualTo(recovered.scope()); - assertThatThrownBy( - () -> - asGameDesign( - () -> - service.authorize( - issued.compact(), requestId, selected, issued.environment()))) + assertThatThrownBy(() -> + asGameDesign(() -> + service.authorize(issued.compact(), requestId, selected, issued.environment()))) .isInstanceOf(RuntimeException.class); verifyNoInteractions(gd); var aborted = asGameDesign(() -> service.abortSourceRead(issued.compact(), requestId, selected)); assertThat(aborted.state()).isEqualTo(AccountGameLogicIntakeSourceReadRecovery.State.ABORTED); assertThat(asGameDesign(() -> service.abortSourceRead(recovered.scope()))).isEqualTo(aborted); - f.tx( - () -> { - f.fences.requireDisclosurePreparation(originalSources); - return null; - }); - f.tx( - () -> { - f.changeRoleToAdmin(); - return null; - }); + f.tx(() -> { + f.fences.requireDisclosurePreparation(originalSources); + return null; + }); + f.tx(() -> { + f.changeRoleToAdmin(); + return null; + }); assertThat( f.dsl.fetchOne( "SELECT binding FROM account_game_logic_intake_authorizations WHERE operation_id = ?", @@ -653,12 +603,9 @@ public Instant instant() { .read(any()); var requestId = UUID.randomUUID(); var inFlight = - java.util.concurrent.CompletableFuture.supplyAsync( - () -> - asGameDesign( - () -> - service.authorize( - issued.compact(), requestId, selected, issued.environment()))); + java.util.concurrent.CompletableFuture.supplyAsync(() -> + asGameDesign(() -> + service.authorize(issued.compact(), requestId, selected, issued.environment()))); assertThat(arrived.await(20, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); var aborted = asGameDesign(() -> service.abortSourceRead(issued.compact(), requestId, selected)); @@ -676,10 +623,8 @@ public Instant instant() { .read(any()); var finalRequest = UUID.randomUUID(); var order = - asGameDesign( - () -> - service.authorize( - issued.compact(), finalRequest, selected, issued.environment())); + asGameDesign(() -> + service.authorize(issued.compact(), finalRequest, selected, issued.environment())); var recovery = asGameDesign(() -> service.recover(issued.compact(), finalRequest, selected)); assertThat(order.operationId()).isEqualTo(recovery.scope().operationId()); assertThat(order.fenceId()).isEqualTo(recovery.scope().fenceId()); @@ -691,33 +636,29 @@ public Instant instant() { Clock.systemUTC(), "test"); assertThat( - asGameDesign( - () -> - readOwner.readFinalizedIntake( - order, - "spiffe://firemud/ns/test/sa/game-logic-service", - GameLogicIntakeSourceReadScope.PURPOSE)) + asGameDesign(() -> + readOwner.readFinalizedIntake( + order, + "spiffe://firemud/ns/test/sa/game-logic-service", + GameLogicIntakeSourceReadScope.PURPOSE)) .canonicalBytes()) .isEqualTo(order.canonicalBytes()); - assertThatThrownBy( - () -> - f.tx( - () -> { - f.dsl.execute( - "INSERT INTO account_game_logic_intake_source_read_aborts (operation_id) VALUES (?)", - order.operationId()); - return null; - })) + assertThatThrownBy(() -> + f.tx(() -> { + f.dsl.execute( + "INSERT INTO account_game_logic_intake_source_read_aborts (operation_id) VALUES (?)", + order.operationId()); + return null; + })) .hasStackTraceContaining("Finalized intake cannot be preliminarily aborted"); assertThat(asGameDesign(() -> service.abortSourceRead(recovery.scope())).state()) .isEqualTo(AccountGameLogicIntakeSourceReadRecovery.State.FINALIZED); offsetSeconds.set(600); clearInvocations(gd); assertThat( - asGameDesign( - () -> - service.authorize( - issued.compact(), finalRequest, selected, issued.environment())) + asGameDesign(() -> + service.authorize( + issued.compact(), finalRequest, selected, issued.environment())) .canonicalBytes()) .isEqualTo(order.canonicalBytes()); verifyNoInteractions(gd); @@ -745,21 +686,20 @@ private static void settleOriginal( captured.sources()) .withRequiredOwners(); issued.actors().claimOriginalDraft(issued.compact(), original, issued.environment()); - f.tx( - () -> { - f.fences.recordOwnerReadback( - original, - new DraftAuthorizationFenceBinding.OwnerReadback( - DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, - DraftAuthorizationFenceBinding.Outcome.COMMITTED, - original.operationId(), - original.commitId(), - original.fenceId(), - original.inputDigest(), - original.canonicalBytes(), - new byte[] {1})); - return null; - }); + f.tx(() -> { + f.fences.recordOwnerReadback( + original, + new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.canonicalBytes(), + new byte[] {1})); + return null; + }); } @Test @@ -804,28 +744,21 @@ void sourceReadbackProvesExactCurrentScopeAndChangedAuthorityBetweenPhasesCannot issued.actors(), f.fences, repository, gd, f.manager, "test"); var request = UUID.randomUUID(); var scope = - asGameDesign( - () -> - service.reserveSourceRead( - issued.compact(), request, selected, issued.environment())); + asGameDesign(() -> + service.reserveSourceRead(issued.compact(), request, selected, issued.environment())); assertThat( asGameDesign( () -> owner.readSourceScope(scope, scope.intendedReader(), scope.purpose())) .canonicalBytes()) .isEqualTo(scope.canonicalBytes()); - assertThatThrownBy( - () -> - asGameDesign( - () -> - owner.readSourceScope( - scope, - "spiffe://firemud/ns/test/sa/game-logic-service", - scope.purpose()))) + assertThatThrownBy(() -> + asGameDesign(() -> + owner.readSourceScope( + scope, "spiffe://firemud/ns/test/sa/game-logic-service", scope.purpose()))) .isInstanceOf(io.grpc.StatusRuntimeException.class); - assertThatThrownBy( - () -> - asGameDesign( - () -> owner.readSourceScope(scope, scope.intendedReader(), "PUBLICATION"))) + assertThatThrownBy(() -> + asGameDesign( + () -> owner.readSourceScope(scope, scope.intendedReader(), "PUBLICATION"))) .isInstanceOf(io.grpc.StatusRuntimeException.class); var changed = new GameLogicIntakeSourceReadScope( @@ -837,12 +770,9 @@ void sourceReadbackProvesExactCurrentScopeAndChangedAuthorityBetweenPhasesCannot scope.selected(), scope.intendedReader(), scope.purpose()); - assertThatThrownBy( - () -> - asGameDesign( - () -> - owner.readSourceScope( - changed, changed.intendedReader(), changed.purpose()))) + assertThatThrownBy(() -> + asGameDesign(() -> + owner.readSourceScope(changed, changed.intendedReader(), changed.purpose()))) .isInstanceOf(IllegalArgumentException.class); var expiredReader = new AccountGameLogicIntakeSourceReadService( @@ -851,12 +781,9 @@ void sourceReadbackProvesExactCurrentScopeAndChangedAuthorityBetweenPhasesCannot f.manager, Clock.offset(Clock.systemUTC(), java.time.Duration.ofMinutes(10)), "test"); - assertThatThrownBy( - () -> - asGameDesign( - () -> - expiredReader.readSourceScope( - scope, scope.intendedReader(), scope.purpose()))) + assertThatThrownBy(() -> + asGameDesign(() -> + expiredReader.readSourceScope(scope, scope.intendedReader(), scope.purpose()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("current held"); // Direct SQL cannot establish a changed purpose even with exact committed issuance bytes. @@ -873,28 +800,26 @@ void sourceReadbackProvesExactCurrentScopeAndChangedAuthorityBetweenPhasesCannot DraftAuthorizationFenceBinding.frame(changedPurpose, scope.intendedReader()); DraftAuthorizationFenceBinding.frame(changedPurpose, "PUBLICATION"); var malformed = changedPurpose.toByteArray(); - assertThatThrownBy( - () -> - f.tx( - () -> { - f.dsl.execute( - "INSERT INTO account_game_logic_intake_source_read_reservations " - + "(operation_id, fence_id, intake_request_id, actor_account_uuid, tenant_uuid, version_uuid, scope_bytes, scope_digest, " - + "issuance_operation_id, issuance_fence, source_payload, issuance_bundle, outbox_checkpoints) " - + "SELECT ?, ?, ?, actor_account_uuid, tenant_uuid, version_uuid, ?, ?, issuance_operation_id, issuance_fence, source_payload, issuance_bundle, outbox_checkpoints " - + "FROM account_game_logic_intake_source_read_reservations WHERE operation_id = ?", - badOperation, - badFence, - badRequest, - malformed, - DraftAuthorizationFenceBinding.digest(malformed), - scope.operationId()); - f.dsl.execute( - "INSERT INTO account_game_logic_intake_source_read_sources SELECT ?, source_key, source_evidence FROM account_game_logic_intake_source_read_sources WHERE operation_id = ?", - badOperation, - scope.operationId()); - return null; - })) + assertThatThrownBy(() -> + f.tx(() -> { + f.dsl.execute( + "INSERT INTO account_game_logic_intake_source_read_reservations " + + "(operation_id, fence_id, intake_request_id, actor_account_uuid, tenant_uuid, version_uuid, scope_bytes, scope_digest, " + + "issuance_operation_id, issuance_fence, source_payload, issuance_bundle, outbox_checkpoints) " + + "SELECT ?, ?, ?, actor_account_uuid, tenant_uuid, version_uuid, ?, ?, issuance_operation_id, issuance_fence, source_payload, issuance_bundle, outbox_checkpoints " + + "FROM account_game_logic_intake_source_read_reservations WHERE operation_id = ?", + badOperation, + badFence, + badRequest, + malformed, + DraftAuthorizationFenceBinding.digest(malformed), + scope.operationId()); + f.dsl.execute( + "INSERT INTO account_game_logic_intake_source_read_sources SELECT ?, source_key, source_evidence FROM account_game_logic_intake_source_read_sources WHERE operation_id = ?", + badOperation, + scope.operationId()); + return null; + })) .hasStackTraceContaining("Invalid preliminary purpose"); assertThat( f.dsl.fetchOne( @@ -916,15 +841,13 @@ void sourceReadbackProvesExactCurrentScopeAndChangedAuthorityBetweenPhasesCannot }) .when(gd) .read(any()); - assertThatThrownBy( - () -> - asGameDesign( - () -> - service.authorizeWithEnvironmentCapture( - issued.compact(), - request, - selected, - f.terms::captureCurrentEnvironmentBoundary))) + assertThatThrownBy(() -> + asGameDesign(() -> + service.authorizeWithEnvironmentCapture( + issued.compact(), + request, + selected, + f.terms::captureCurrentEnvironmentBoundary))) .isInstanceOf(RuntimeException.class); assertThat(asGameDesign(() -> service.recover(issued.compact(), request, selected)).state()) .isEqualTo(AccountGameLogicIntakeSourceReadRecovery.State.RESERVED); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommitSignerFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommitSignerFixture.java index ce664a8c7f..c02c04e6d0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommitSignerFixture.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommitSignerFixture.java @@ -182,10 +182,9 @@ private AccountGameplayDelegationCommitSignerFixture( trustedJwksSource = mock(AccountJwtJwksTrustedSource.class); when(trustedJwksSource.sourceIdentity()).thenReturn(sourceIdentity); when(trustedJwksSource.load()) - .thenAnswer( - invocation -> - new PublicJwksSnapshot( - sourceIdentity, trustedJwksJson.get().getBytes(StandardCharsets.UTF_8))); + .thenAnswer(invocation -> + new PublicJwksSnapshot( + sourceIdentity, trustedJwksJson.get().getBytes(StandardCharsets.UTF_8))); AccountJwtSignerDesiredStateRepository desiredState = mock(AccountJwtSignerDesiredStateRepository.class); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java index 88edc2d1c8..484e4f87b4 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisIntegrationTest.java @@ -341,10 +341,9 @@ void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenant net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( JSON.writeValueAsString(changedFields)); int changedBytesConnection = writerProvider.openedConnections(); - assertThatThrownBy( - () -> - redis.registerPending( - pending.record().tokenHash(), changedRecord, pending.absoluteExpiryMillis())) + assertThatThrownBy(() -> + redis.registerPending( + pending.record().tokenHash(), changedRecord, pending.absoluteExpiryMillis())) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat(writerProvider.trace(changedBytesConnection)) @@ -354,12 +353,11 @@ void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenant assertThat(admin.pexpiretime(ascii(pendingKey))).isEqualTo(pending.absoluteExpiryMillis()); int changedDeadlineConnection = writerProvider.openedConnections(); - assertThatThrownBy( - () -> - redis.registerPending( - pending.record().tokenHash(), - pending.recordBytes(), - Math.addExact(pending.absoluteExpiryMillis(), 1_000L))) + assertThatThrownBy(() -> + redis.registerPending( + pending.record().tokenHash(), + pending.recordBytes(), + Math.addExact(pending.absoluteExpiryMillis(), 1_000L))) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat(writerProvider.trace(changedDeadlineConnection)) @@ -371,12 +369,11 @@ void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenant int insufficientReplicaAofConnection = writerProvider.openedConnections(); AccountGameplayDelegationRedisClient insufficientReplicaAofClient = redisClient(writerProvider, new AcknowledgementRequirements(1, 2, 250)); - assertThatThrownBy( - () -> - insufficientReplicaAofClient.registerPending( - pending.record().tokenHash(), - pending.recordBytes(), - pending.absoluteExpiryMillis())) + assertThatThrownBy(() -> + insufficientReplicaAofClient.registerPending( + pending.record().tokenHash(), + pending.recordBytes(), + pending.absoluteExpiryMillis())) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat(writerProvider.trace(insufficientReplicaAofConnection)) @@ -431,10 +428,9 @@ void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenant projectionPair(accountId, 6L, 8L, "issuer-stale", "account-newer"); byte[] accountBeforeIssuerRegression = admin.get(ascii(accountKey)); int issuerRegressionConnection = writerProvider.openedConnections(); - assertThatThrownBy( - () -> - redis.publishAuthorityProjections( - accountId, regressedProjection[0], regressedProjection[1])) + assertThatThrownBy(() -> + redis.publishAuthorityProjections( + accountId, regressedProjection[0], regressedProjection[1])) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat(writerProvider.trace(issuerRegressionConnection)) @@ -446,10 +442,9 @@ void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenant byte[][] equalIssuerConflict = projectionPair(accountId, 7L, 7L, "issuer-conflict", "account-base"); int equalIssuerConflictConnection = writerProvider.openedConnections(); - assertThatThrownBy( - () -> - redis.publishAuthorityProjections( - accountId, equalIssuerConflict[0], equalIssuerConflict[1])) + assertThatThrownBy(() -> + redis.publishAuthorityProjections( + accountId, equalIssuerConflict[0], equalIssuerConflict[1])) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat(writerProvider.trace(equalIssuerConflictConnection)) @@ -459,10 +454,9 @@ void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenant byte[][] equalAccountConflict = projectionPair(accountId, 7L, 7L, "issuer-base", "account-conflict"); int equalAccountConflictConnection = writerProvider.openedConnections(); - assertThatThrownBy( - () -> - redis.publishAuthorityProjections( - accountId, equalAccountConflict[0], equalAccountConflict[1])) + assertThatThrownBy(() -> + redis.publishAuthorityProjections( + accountId, equalAccountConflict[0], equalAccountConflict[1])) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat(writerProvider.trace(equalAccountConflictConnection)) @@ -496,10 +490,9 @@ void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenant "issuer-below-max", "account-below-max"); int boundaryRegressionConnection = writerProvider.openedConnections(); - assertThatThrownBy( - () -> - redis.publishAuthorityProjections( - accountId, belowSignedBigintBoundary[0], belowSignedBigintBoundary[1])) + assertThatThrownBy(() -> + redis.publishAuthorityProjections( + accountId, belowSignedBigintBoundary[0], belowSignedBigintBoundary[1])) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat(writerProvider.trace(boundaryRegressionConnection)) @@ -509,10 +502,9 @@ void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenant TrackedProvider wrongRoleProvider = new TrackedProvider(fixtureAdmin); AccountGameplayDelegationRedisClient wrongRoleClient = redisClient(wrongRoleProvider); int wrongRoleConnection = wrongRoleProvider.openedConnections(); - assertThatThrownBy( - () -> - wrongRoleClient.publishAuthorityProjections( - accountId, signedBigintBoundary[0], signedBigintBoundary[1])) + assertThatThrownBy(() -> + wrongRoleClient.publishAuthorityProjections( + accountId, signedBigintBoundary[0], signedBigintBoundary[1])) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat(wrongRoleProvider.trace(wrongRoleConnection)) @@ -552,21 +544,19 @@ void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenant byte[] membershipSequenceTwo = membershipProjectionFixture(accountId, selectedTenant, "2", "3", "1"); int beforeFirstPublicationAboveOne = writerProvider.openedConnections(); - assertThatThrownBy( - () -> - redis.publishSelectedAuthorityEvent( - accountId, selectedTenant, false, null, membershipSequenceTwo)) + assertThatThrownBy(() -> + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, false, null, membershipSequenceTwo)) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat(writerProvider.openedConnections()).isEqualTo(beforeFirstPublicationAboveOne); - assertThatThrownBy( - () -> - redis.publishSelectedAuthorityEvent( - accountId, - selectedTenant, - false, - selected[3], - membershipProjectionFixture(accountId, selectedTenant, "3", "4", "1"))) + assertThatThrownBy(() -> + redis.publishSelectedAuthorityEvent( + accountId, + selectedTenant, + false, + selected[3], + membershipProjectionFixture(accountId, selectedTenant, "3", "4", "1"))) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat( @@ -585,34 +575,30 @@ void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenant redis.publishSelectedAuthorityEvent( accountId, selectedTenant, false, selected[3], membershipSequenceTwo)) .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.EXACT_RETRY); - assertThatThrownBy( - () -> - redis.publishSelectedAuthorityEvent( - accountId, selectedTenant, false, null, membershipSequenceTwo)) + assertThatThrownBy(() -> + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, false, null, membershipSequenceTwo)) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); - assertThatThrownBy( - () -> - redis.publishSelectedAuthorityEvent( - accountId, - selectedTenant, - false, - selected[3], - membershipProjectionFixture(accountId, selectedTenant, "3", "4", "1"))) + assertThatThrownBy(() -> + redis.publishSelectedAuthorityEvent( + accountId, + selectedTenant, + false, + selected[3], + membershipProjectionFixture(accountId, selectedTenant, "3", "4", "1"))) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); admin.del(ascii(tenantKey)); admin.del(ascii(memberKey)); - assertThatThrownBy( - () -> - redis.publishSelectedAuthorityEvent( - accountId, selectedTenant, true, selected[2], tenantSequenceTwo)) + assertThatThrownBy(() -> + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, true, selected[2], tenantSequenceTwo)) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); - assertThatThrownBy( - () -> - redis.publishSelectedAuthorityEvent( - accountId, selectedTenant, false, selected[3], membershipSequenceTwo)) + assertThatThrownBy(() -> + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, false, selected[3], membershipSequenceTwo)) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat( @@ -633,16 +619,14 @@ void pinnedRedisHelperRegistersPendingAndProjectsExactOwnerValues(boolean tenant .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); assertThat(admin.get(ascii(tenantKey))).containsExactly(tenantSequenceTwo); assertThat(admin.get(ascii(memberKey))).containsExactly(membershipSequenceTwo); - assertThatThrownBy( - () -> - redis.publishSelectedAuthorityEvent( - accountId, selectedTenant, false, null, selected[3])) + assertThatThrownBy(() -> + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, false, null, selected[3])) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); - assertThatThrownBy( - () -> - redis.publishSelectedAuthorityEvent( - accountId, selectedTenant, true, null, selected[2])) + assertThatThrownBy(() -> + redis.publishSelectedAuthorityEvent( + accountId, selectedTenant, true, null, selected[2])) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); byte[][] gap = selected.clone(); @@ -824,10 +808,9 @@ void retainedPostgresPagesReplayToRedisWithCapturedHeadLossAndGapRecovery() { assertThat(redis.publishSelectedAuthorityEvent(accountId, tenantId, false, null, sequenceOne)) .isEqualTo(AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED); assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThatThrownBy( - () -> - redis.publishSelectedAuthorityEvent( - accountId, tenantId, false, sequenceTwo, sequenceThree)) + assertThatThrownBy(() -> + redis.publishSelectedAuthorityEvent( + accountId, tenantId, false, sequenceTwo, sequenceThree)) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat(admin.get(ascii(redisKey))).containsExactly(sequenceOne); @@ -1027,25 +1010,23 @@ void initialLoginDisposalFencesEveryInterruptedIssuanceStage(String stage) throw identity.operationId()) .get("row_version", String.class)) .isEqualTo(pendingRevocationXmin); - assertThatThrownBy( - () -> - inTransaction( - database, - () -> - new net.firedevops.firemud.accountservice.repository - .AccountGameplayTokenIdentityFenceRepository(dsl) - .requireActiveForUpdate(identity))) + assertThatThrownBy(() -> + inTransaction( + database, + () -> + new net.firedevops.firemud.accountservice.repository + .AccountGameplayTokenIdentityFenceRepository(dsl) + .requireActiveForUpdate(identity))) .isInstanceOf( net.firedevops.firemud.accountservice.repository .AccountGameplayTokenIdentityFenceRepository.TokenRevokedException.class); } - assertThatThrownBy( - () -> - redis.registerPending( - candidate.tokenHash(), - candidate.canonicalRecordBytes(), - Math.addExact( - Math.multiplyExact(candidate.expiresAtEpochSecond(), 1000L), 30_000L))) + assertThatThrownBy(() -> + redis.registerPending( + candidate.tokenHash(), + candidate.canonicalRecordBytes(), + Math.addExact( + Math.multiplyExact(candidate.expiresAtEpochSecond(), 1000L), 30_000L))) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat(admin.get(ascii(tokenKey))).containsExactly(intent.tombstoneBytes()); @@ -1056,21 +1037,19 @@ void initialLoginDisposalFencesEveryInterruptedIssuanceStage(String stage) throw .Disposition.PENDING); } assertThatThrownBy(() -> signer.preparePendingCandidate(request)) - .satisfies( - failure -> - assertThat(failure.getClass().getName()) - .isEqualTo( - "net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner$SigningUnavailableException")); + .satisfies(failure -> + assertThat(failure.getClass().getName()) + .isEqualTo( + "net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner$SigningUnavailableException")); assertThatThrownBy( () -> inTransaction(database, () -> issuance.readCurrentGameplayLoginReplay(request))) .isInstanceOf( AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); - assertThatThrownBy( - () -> - disposal.retire( - new net.firedevops.firemud.accountservice.dto - .InitialGameplayLoginDisposalRequest(request, UUID.randomUUID(), null), - CALLER_WORKLOAD)) + assertThatThrownBy(() -> + disposal.retire( + new net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalRequest( + request, UUID.randomUUID(), null), + CALLER_WORKLOAD)) .isInstanceOf( net.firedevops.firemud.accountservice.repository .AccountInitialGameplayLoginDisposalRepository.DisposalConflictException.class); @@ -1149,11 +1128,10 @@ dsl, sources, new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox)) pausedManager, Clock.systemUTC()); assertThatThrownBy(() -> signer.preparePendingCandidate(request)) - .satisfies( - failure -> - assertThat(failure.getClass().getName()) - .isEqualTo( - "net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner$SigningUnavailableException")); + .satisfies(failure -> + assertThat(failure.getClass().getName()) + .isEqualTo( + "net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner$SigningUnavailableException")); assertThat( dsl.fetchSingle( "SELECT token_hash FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", @@ -1180,27 +1158,25 @@ dsl, sources, new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox)) assertThat(inTransaction(database, () -> disposals.readUnqualifiedNoBinding(intent))) .isEqualTo(first); for (UUID resolvedAccount : List.of(account, otherAccount)) { - assertThatThrownBy( - () -> - inTransaction( - database, - () -> - issuance.beginPendingForAccount( - request, - resolvedAccount, - CALLER_WORKLOAD, - context, - net.firedevops.firemud.accountservice.repository - .AccountGameplayCredentialRequestBindingFixture.binding()))) + assertThatThrownBy(() -> + inTransaction( + database, + () -> + issuance.beginPendingForAccount( + request, + resolvedAccount, + CALLER_WORKLOAD, + context, + net.firedevops.firemud.accountservice.repository + .AccountGameplayCredentialRequestBindingFixture.binding()))) .isInstanceOf( AccountGameplayDelegationIssuanceRepository.IdempotencyConflictException.class); } - assertThatThrownBy( - () -> - owner.retire( - new net.firedevops.firemud.accountservice.dto - .InitialGameplayLoginDisposalRequest(request, UUID.randomUUID(), null), - CALLER_WORKLOAD)) + assertThatThrownBy(() -> + owner.retire( + new net.firedevops.firemud.accountservice.dto.InitialGameplayLoginDisposalRequest( + request, UUID.randomUUID(), null), + CALLER_WORKLOAD)) .isInstanceOf( net.firedevops.firemud.accountservice.repository .AccountInitialGameplayLoginDisposalRepository.DisposalConflictException.class); @@ -1210,17 +1186,16 @@ dsl, sources, new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox)) net.firedevops.firemud.accountservice.repository .AccountInitialGameplayLoginDisposalRepository.DisposalConflictException.class); // A syntactically complete requested terminal proof cannot invent intact binding history. - assertThatThrownBy( - () -> - inTransaction( - database, - () -> - dsl.execute( - "UPDATE account_initial_gameplay_login_disposals SET state = 'NO_TOKEN', owner_proof_kind = 'NO_ISSUANCE_BINDING'," - + " owner_proof_canonical_bytes = ?, owner_proof_sha256 = ? WHERE request_id = ?", - "{}".getBytes(StandardCharsets.UTF_8), - "a".repeat(64), - request))) + assertThatThrownBy(() -> + inTransaction( + database, + () -> + dsl.execute( + "UPDATE account_initial_gameplay_login_disposals SET state = 'NO_TOKEN', owner_proof_kind = 'NO_ISSUANCE_BINDING'," + + " owner_proof_canonical_bytes = ?, owner_proof_sha256 = ? WHERE request_id = ?", + "{}".getBytes(StandardCharsets.UTF_8), + "a".repeat(64), + request))) .isInstanceOf(AssertionError.class) .hasMessageContaining("exceptionClass=PSQLException; sqlState=23514"); org.mockito.Mockito.verifyNoInteractions(registry); @@ -1232,20 +1207,18 @@ dsl, sources, new AccountAuthEvidenceBundleRepository(dsl, authorities, outbox)) var rolledBackIntent = database .transaction() - .execute( - status -> { - var pending = disposals.begin(rollbackIdentity, CALLER_WORKLOAD); - status.setRollbackOnly(); - return pending; - }); + .execute(status -> { + var pending = disposals.begin(rollbackIdentity, CALLER_WORKLOAD); + status.setRollbackOnly(); + return pending; + }); assertThat( dsl.fetchOne( "SELECT request_id FROM account_initial_gameplay_login_disposals WHERE request_id = ?", rolledBackRequest)) .isNull(); - assertThatThrownBy( - () -> - inTransaction(database, () -> disposals.readUnqualifiedNoBinding(rolledBackIntent))) + assertThatThrownBy(() -> + inTransaction(database, () -> disposals.readUnqualifiedNoBinding(rolledBackIntent))) .isInstanceOf( net.firedevops.firemud.accountservice.repository .AccountInitialGameplayLoginDisposalRepository.DisposalUnavailableException.class); @@ -1304,11 +1277,10 @@ void disposalReconcilesRolledBackBindingVersusLostBindingCommitAcknowledgement( manager, Clock.systemUTC()); assertThatThrownBy(() -> signer.preparePendingCandidate(request)) - .satisfies( - failure -> - assertThat(failure.getClass().getName()) - .isEqualTo( - "net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner$SigningUnavailableException")); + .satisfies(failure -> + assertThat(failure.getClass().getName()) + .isEqualTo( + "net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner$SigningUnavailableException")); var original = dsl.fetchOne( "SELECT * FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", @@ -1365,11 +1337,10 @@ void disposalReconcilesRolledBackBindingVersusLostBindingCommitAcknowledgement( assertThat(provider.openedConnections()).isZero(); } assertThatThrownBy(() -> signer.preparePendingCandidate(request)) - .satisfies( - failure -> - assertThat(failure.getClass().getName()) - .isEqualTo( - "net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner$SigningUnavailableException")); + .satisfies(failure -> + assertThat(failure.getClass().getName()) + .isEqualTo( + "net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner$SigningUnavailableException")); assertThat( dsl.fetchOne( "SELECT * FROM account_gameplay_delegation_issuance_operations WHERE request_id = ?", @@ -1719,12 +1690,11 @@ void physicalCommittedResponseRecoverySurvivesOrdinarySignerRotationAndReturnsSa sourceSnapshot .account() .accountSecurityCutoff() - .map( - cutoff -> - new GameSessionAccountDelegationProfile.AccountSecurityCutoff( - cutoff.accountAuthorityGeneration(), - cutoff.outboxStreamKey(), - cutoff.outboxSequence()))), + .map(cutoff -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence()))), net.firedevops.firemud.accountservice.repository .AccountGameplayCredentialRequestBindingFixture.binding()); inTransaction(database, () -> issuance.beginPending(pending)); @@ -1864,19 +1834,17 @@ void physicalCommittedResponseRecoverySurvivesOrdinarySignerRotationAndReturnsSa CallerIdentity caller = new CallerIdentity(CALLER_WORKLOAD, callerContextId); int connectionsBeforeCallerMismatch = writerProvider.openedConnections(); - assertThatThrownBy( - () -> - recoveryOwner.recoverInitialLoginResponse( - requestId, accountId, new CallerIdentity(CALLER_WORKLOAD, UUID.randomUUID()))) + assertThatThrownBy(() -> + recoveryOwner.recoverInitialLoginResponse( + requestId, accountId, new CallerIdentity(CALLER_WORKLOAD, UUID.randomUUID()))) .isInstanceOf(IdempotencyConflictException.class) .hasNoCause(); - assertThatThrownBy( - () -> - recoveryOwner.recoverInitialLoginResponse( - requestId, - accountId, - new CallerIdentity( - "spiffe://firemud/ns/other/sa/game-session-service", callerContextId))) + assertThatThrownBy(() -> + recoveryOwner.recoverInitialLoginResponse( + requestId, + accountId, + new CallerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", callerContextId))) .isInstanceOf(IdempotencyConflictException.class) .hasNoCause(); assertThatThrownBy( @@ -2296,10 +2264,9 @@ void canonicalPrimaryLoginCommitsActivatesAndRecoversDiscardedResponse(String au assertThatThrownBy(() -> login.authenticate(changed, CALLER_WORKLOAD, verifier)) .isInstanceOf(IdempotencyConflictException.class); } - assertThatThrownBy( - () -> - login.authenticate( - request, "spiffe://firemud/ns/other/sa/game-session-service", verifier)) + assertThatThrownBy(() -> + login.authenticate( + request, "spiffe://firemud/ns/other/sa/game-session-service", verifier)) .isInstanceOf(IdempotencyConflictException.class); assertThat(writerProvider.openedConnections()).isEqualTo(beforeConflicts); assertThat( @@ -2351,10 +2318,9 @@ void canonicalPrimaryLoginCommitsActivatesAndRecoversDiscardedResponse(String au discarded.tokenSha256(), Long.parseLong(discarded.tokenGeneration()), Long.parseLong(discarded.issuanceFence()))); - assertThatThrownBy( - () -> - disposalOwner.retire( - disposalRequest, "spiffe://firemud/ns/other/sa/game-session-service")) + assertThatThrownBy(() -> + disposalOwner.retire( + disposalRequest, "spiffe://firemud/ns/other/sa/game-session-service")) .isInstanceOf( net.firedevops.firemud.accountservice.repository .AccountInitialGameplayLoginDisposalRepository.DisposalConflictException.class); @@ -2367,12 +2333,9 @@ void canonicalPrimaryLoginCommitsActivatesAndRecoversDiscardedResponse(String au assertThatThrownBy(() -> committedOwner.activateCommittedIssuance(requestId)) .isInstanceOf( AccountGameplayDelegationCommittedIssuanceOwner.OwnerUnavailableException.class); - assertThatThrownBy( - () -> - recoveryOwner.recoverInitialLoginResponse( - requestId, - accountId, - new CallerIdentity(CALLER_WORKLOAD, context.contextId()))) + assertThatThrownBy(() -> + recoveryOwner.recoverInitialLoginResponse( + requestId, accountId, new CallerIdentity(CALLER_WORKLOAD, context.contextId()))) .isInstanceOf( AccountGameplayDelegationResponseRecoveryOwner.OwnerUnavailableException.class); // Unknown physical state must preserve PENDING and never delete somebody else's bytes. @@ -2393,10 +2356,9 @@ void canonicalPrimaryLoginCommitsActivatesAndRecoversDiscardedResponse(String au tokenRegistry.disposeInitialLogin(intent); assertThat(admin.get(ascii(tokenKey))).containsExactly(intent.tombstoneBytes()); assertThat(admin.pttl(ascii(tokenKey))).isEqualTo(-1L); - assertThatThrownBy( - () -> - GameSessionAccountDelegationRegistryRecord.decode( - admin.get(ascii(tokenKey)), REGISTRY_BYTES)) + assertThatThrownBy(() -> + GameSessionAccountDelegationRegistryRecord.decode( + admin.get(ascii(tokenKey)), REGISTRY_BYTES)) .as( "purpose-specific denied tombstone cannot be read as an authorizing registry projection") .isInstanceOf(GameSessionAccountDelegationRegistryRecord.InvalidRecordException.class); @@ -2417,10 +2379,9 @@ void canonicalPrimaryLoginCommitsActivatesAndRecoversDiscardedResponse(String au requestId)) .isEqualTo(storedEnvelope); // A captured pre-disposal physical registration cannot resurrect, even after SQL completion. - assertThatThrownBy( - () -> - redis.registerPending( - committed.tokenSha256(), intent.pendingBytes(), originalDeadline)) + assertThatThrownBy(() -> + redis.registerPending( + committed.tokenSha256(), intent.pendingBytes(), originalDeadline)) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat(admin.get(ascii(tokenKey))).containsExactly(intent.tombstoneBytes()); @@ -3024,36 +2985,35 @@ private TestContext newPostgresContext() { dsl.configuration() .setAppending( new DefaultExecuteListenerProvider( - ExecuteListener.onException( - context -> { - java.sql.SQLException sqlException = context.sqlException(); - if (sqlException == null) return; - String exceptionClass = sqlException.getClass().getSimpleName(); - if (!exceptionClass.matches("[A-Za-z0-9_$]+")) { - exceptionClass = "SQLException"; - } - String sqlState = sqlException.getSQLState(); - if (sqlState == null || !sqlState.matches("[A-Z0-9]{5}")) { - sqlState = "unknown"; - } - String constraint = "unknown"; - if (sqlException instanceof PSQLException postgresException) { - var serverError = postgresException.getServerErrorMessage(); - String candidateConstraint = - serverError == null ? null : serverError.getConstraint(); - if (candidateConstraint != null - && candidateConstraint.matches("[a-z][a-z0-9_]{0,62}")) { - constraint = candidateConstraint; - } - } - throw new AssertionError( - "Physical Account PostgreSQL failure: exceptionClass=" - + exceptionClass - + "; sqlState=" - + sqlState - + "; constraint=" - + constraint); - }))); + ExecuteListener.onException(context -> { + java.sql.SQLException sqlException = context.sqlException(); + if (sqlException == null) return; + String exceptionClass = sqlException.getClass().getSimpleName(); + if (!exceptionClass.matches("[A-Za-z0-9_$]+")) { + exceptionClass = "SQLException"; + } + String sqlState = sqlException.getSQLState(); + if (sqlState == null || !sqlState.matches("[A-Z0-9]{5}")) { + sqlState = "unknown"; + } + String constraint = "unknown"; + if (sqlException instanceof PSQLException postgresException) { + var serverError = postgresException.getServerErrorMessage(); + String candidateConstraint = + serverError == null ? null : serverError.getConstraint(); + if (candidateConstraint != null + && candidateConstraint.matches("[a-z][a-z0-9_]{0,62}")) { + constraint = candidateConstraint; + } + } + throw new AssertionError( + "Physical Account PostgreSQL failure: exceptionClass=" + + exceptionClass + + "; sqlState=" + + sqlState + + "; constraint=" + + constraint); + }))); DataSourceTransactionManager manager = new DataSourceTransactionManager(dataSource); return new TestContext(dsl, manager, new TransactionTemplate(manager)); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java index 124b9a3fac..ab52377eb1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierPostgresIntegrationTest.java @@ -273,13 +273,12 @@ private static Harness harness(String authModes, boolean expired) { seed.setPasswordHash(PASSWORD_HASH); seed.setLoginAuthModes(authModes); Account account = - tx.execute( - status -> { - sources.initializeIssuerIfAbsent("firemud-account-service"); - Account saved = accounts.save(seed); - challenges.save(challenge(saved, OTP_HASH, expired)); - return saved; - }); + tx.execute(status -> { + sources.initializeIssuerIfAbsent("firemud-account-service"); + Account saved = accounts.save(seed); + challenges.save(challenge(saved, OTP_HASH, expired)); + return saved; + }); var issuance = new AccountGameplayDelegationIssuanceRepository(dsl, sources); // Unused AccountService surfaces are absent; every collaborator on this credential path is // real. diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java index 57d5842106..1cd5d57cb1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiIssuancePostgresIntegrationTest.java @@ -46,9 +46,8 @@ void realPasswordAndOtpAuthenticateSeparateAccountWithoutCreatingTenantMembershi assertNoMembership(fixture, account); var passwordIdentity = - fixture.tx( - () -> - fixture.primary.authenticateControlUiPrimaryIdentity(account.getEmail(), PASSWORD)); + fixture.tx(() -> + fixture.primary.authenticateControlUiPrimaryIdentity(account.getEmail(), PASSWORD)); assertThat(passwordIdentity.accountId()).isEqualTo(account.getAccountUuid()); assertThat(passwordIdentity.accountId()).isNotEqualTo(fixture.account.getAccountUuid()); fixture.installGlobalOtp(account, OTP); @@ -90,10 +89,8 @@ void unavailableCurrentRestrictionRollsBackActualOtpAndRetainsSameChallengeAcros // it. assertThat( fixture - .tx( - () -> - fixture.primary.authenticateControlUiPrimaryIdentity( - account.getEmail(), OTP)) + .tx(() -> + fixture.primary.authenticateControlUiPrimaryIdentity(account.getEmail(), OTP)) .accountId()) .isEqualTo(account.getAccountUuid()); assertThat(fixture.challenges.findByAccountId(account.getId())).isEmpty(); @@ -134,12 +131,9 @@ void exactBirthPredecessorsCannotAuthorizePublicRestrictionCommitOrCurrentAbsenc .isInstanceOf( AccountPlatformRestrictionOperationRepository.OwnerAuthorizationUnresolvedException .class); - assertThatThrownBy( - () -> - fixture.tx( - () -> - fixture.restrictionOperations.readCurrent( - account.getAccountUuid(), category))) + assertThatThrownBy(() -> + fixture.tx(() -> + fixture.restrictionOperations.readCurrent(account.getAccountUuid(), category))) .isInstanceOf( AccountPlatformRestrictionOperationRepository .RestrictionProjectionUnavailableException.class); @@ -162,9 +156,8 @@ void accountSourceObservationCannotUseHistoricalNonrestrictedBirthAsCurrentAutho var fixture = fixture(); var account = fixture.createGlobalAccount(PASSWORD); var identity = - fixture.tx( - () -> - fixture.primary.authenticateControlUiPrimaryIdentity(account.getEmail(), PASSWORD)); + fixture.tx(() -> + fixture.primary.authenticateControlUiPrimaryIdentity(account.getEmail(), PASSWORD)); assertThatThrownBy( () -> fixture.tx(() -> fixture.authority.captureAccount(identity.accountId()))) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiScopePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiScopePostgresIntegrationTest.java index 61938a6fb5..595fb46f7f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiScopePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountGlobalControlUiScopePostgresIntegrationTest.java @@ -217,14 +217,13 @@ private static UUID account(DriverManagerDataSource source) { var dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); var transaction = new TransactionTemplate(new DataSourceTransactionManager(source)); return Objects.requireNonNull( - transaction.execute( - ignored -> { - var account = new Account(); - account.setUsername("scope-" + UUID.randomUUID()); - account.setEmail(UUID.randomUUID() + "@example.test"); - account.setPasswordHash("test-only unused verifier"); - return new AccountRepository(dsl).save(account).getAccountUuid(); - })); + transaction.execute(ignored -> { + var account = new Account(); + account.setUsername("scope-" + UUID.randomUUID()); + account.setEmail(UUID.randomUUID() + "@example.test"); + account.setPasswordHash("test-only unused verifier"); + return new AccountRepository(dsl).save(account).getAccountUuid(); + })); } private static UUID tenant(JdbcTemplate jdbc) { @@ -356,16 +355,15 @@ private static int historyVersionCount(JdbcTemplate jdbc, String version) { private static void assertSqlState(Runnable action, String state) { assertThatThrownBy(action::run) - .satisfies( - failure -> { - for (Throwable cause = failure; cause != null; cause = cause.getCause()) { - if (cause instanceof PSQLException postgres) { - assertThat(postgres.getSQLState()).isEqualTo(state); - return; - } - } - throw new AssertionError("Expected PostgreSQL failure", failure); - }); + .satisfies(failure -> { + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof PSQLException postgres) { + assertThat(postgres.getSQLState()).isEqualTo(state); + return; + } + } + throw new AssertionError("Expected PostgreSQL failure", failure); + }); } private static byte[] bytes(String value) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java index 5a122c2d0b..2a5623a190 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionCompositionPostgresIntegrationTest.java @@ -270,23 +270,17 @@ void genericAccountAuthorityAdvanceDuringSdkReadMakesSourceUnavailableAndKeepsOt .tx(() -> generations.read(AuthorityScope.account(hosting.accountUuid()))); hosting .transport() - .duringRead( - () -> - issued - .sources() - .tx( - () -> { - var account = - issued - .sources() - .accounts - .findById(hosting.accountId()) - .orElseThrow(); - account.setRole("admin"); - // Generic authority events lack the closed operation receipt required - // by current-source readback, so this advance must fail closed there. - return issued.sources().accounts.save(account); - })); + .duringRead(() -> + issued + .sources() + .tx(() -> { + var account = + issued.sources().accounts.findById(hosting.accountId()).orElseThrow(); + account.setRole("admin"); + // Generic authority events lack the closed operation receipt required + // by current-source readback, so this advance must fail closed there. + return issued.sources().accounts.save(account); + })); assertThatThrownBy(() -> resolve(failed, issued.account().getEmail(), OTP)) .isExactlyInstanceOf(SourceEvidenceUnavailableException.class) .hasMessage("Account authority source evidence is unavailable or inconsistent"); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java index 2b24d9de14..b2e64cb39c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java @@ -166,13 +166,12 @@ void rejectsMissingAndNullReadinessInventoryFieldsWithIndependentRawSqlAttempts( ReadinessProbePlan planTemplate = context .transaction() - .execute( - status -> { - ReadinessProbePlan candidate = - owner.readiness().planCurrent(BINDING, owner.trust(), plannedAt, inventory); - status.setRollbackOnly(); - return candidate; - }); + .execute(status -> { + ReadinessProbePlan candidate = + owner.readiness().planCurrent(BINDING, owner.trust(), plannedAt, inventory); + status.setRollbackOnly(); + return candidate; + }); assertThat(planTemplate).isNotNull(); assertThat(count(context, "account_jwt_readiness_probe_plans")).isZero(); @@ -190,13 +189,12 @@ void rejectsMissingAndNullReadinessInventoryFieldsWithIndependentRawSqlAttempts( ReadinessProbePlan legacyPlanTemplate = context .transaction() - .execute( - status -> { - ReadinessProbePlan candidate = - owner.readiness().planCurrent(BINDING, owner.trust(), plannedAt); - status.setRollbackOnly(); - return candidate; - }); + .execute(status -> { + ReadinessProbePlan candidate = + owner.readiness().planCurrent(BINDING, owner.trust(), plannedAt); + status.setRollbackOnly(); + return candidate; + }); assertThat(legacyPlanTemplate).isNotNull(); assertThat(legacyPlanTemplate.planVersion()).isEqualTo(1); assertThat(count(context, "account_jwt_readiness_probe_plans")).isZero(); @@ -520,11 +518,10 @@ void persistsExactV2PodProjectionAndClosesPerPodReceiptsAcrossRepositoryRestart( assertThat(plan.expectedFence().publishedActive()).isEmpty(); assertThat(plan.entries()) .hasSize(8) - .allSatisfy( - entry -> { - assertThat(entry.expectedActive()).isEmpty(); - assertThat(entry.state()).isEqualTo(ProbeState.PLANNED); - }); + .allSatisfy(entry -> { + assertThat(entry.expectedActive()).isEmpty(); + assertThat(entry.state()).isEqualTo(ProbeState.PLANNED); + }); assertThat(count(context, "account_jwt_readiness_validator_pods")).isEqualTo(12L); assertThat(count(context, "account_jwt_readiness_probe_plans")).isEqualTo(1L); assertThat(count(context, "account_jwt_readiness_probe_entries")).isEqualTo(8L); @@ -608,42 +605,39 @@ void persistsExactV2PodProjectionAndClosesPerPodReceiptsAcrossRepositoryRestart( observationContext.operationDigest()); InventorySnapshot wrongPurposeInventory = completeInventorySnapshot(Instant.ofEpochSecond(databaseNow), wrongPurpose); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - owner - .readiness() - .planCurrent( - BINDING, - owner.trust(), - Instant.ofEpochSecond(databaseNow), - wrongPurposeInventory))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + owner + .readiness() + .planCurrent( + BINDING, + owner.trust(), + Instant.ofEpochSecond(databaseNow), + wrongPurposeInventory))) .isInstanceOf(AccountJwtReadinessProbeRepository.InventoryPlanConflictException.class); InventorySnapshot changedInventory = completeInventorySnapshot( Instant.ofEpochSecond(databaseNow), "10.11.0.99", observationContext); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - owner - .readiness() - .planCurrent( - BINDING, - owner.trust(), - Instant.ofEpochSecond(databaseNow), - changedInventory))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + owner + .readiness() + .planCurrent( + BINDING, + owner.trust(), + Instant.ofEpochSecond(databaseNow), + changedInventory))) .isInstanceOf(AccountJwtReadinessProbeRepository.InventoryPlanConflictException.class); ProbeEntry plannedCanary = plan.entries().stream() - .filter( - entry -> - entry.validatorId().equals("account-service") - && entry.probeKind() == AccountMountedJwtSignerBundle.ProbeKind.CANARY) + .filter(entry -> + entry.validatorId().equals("account-service") + && entry.probeKind() == AccountMountedJwtSignerBundle.ProbeKind.CANARY) .findFirst() .orElseThrow(); Path privateMount = Files.createDirectory(tempDirectory.resolve("private-mount")); @@ -742,23 +736,21 @@ void persistsExactV2PodProjectionAndClosesPerPodReceiptsAcrossRepositoryRestart( .extracting(pod -> pod.target().exactPodEndpoint().orElseThrow().toString()) .containsExactly("grpcs://10.11.0.11:9443", "grpcs://10.11.0.12:9443"); assertThat(expectedPods) - .allSatisfy( - pod -> { - assertThat(pod.planDigest()).isEqualTo(plan.planDigest()); - assertThat(pod.jti()).isEqualTo(issuedEntry.jti()); - assertThat(pod.target().inventorySnapshotDigest()) - .isEqualTo(planningInventory.digest()); - assertThat(pod.target().inventoryBindingDigest()) - .isEqualTo(planningInventory.inventoryBindingDigest()); - assertThat(pod.target().applicabilityMatrixDigest()) - .isEqualTo(plan.applicabilityMatrixDigest()); - assertThat(pod.target().namespaceUid()).isEqualTo(NAMESPACE_UID); - assertThat(pod.target().exactPodEndpoint()).isPresent(); - assertThat(pod.target().canonicalServiceUri()) - .contains("spiffe://firemud/ns/firemud-prod/sa/account-jwt-validator"); - assertThat(pod.target().podLeafSpkiSha256()).isPresent(); - assertThat(pod.target().expectation()).isEqualTo(ProbeExpectation.ACCEPT); - }); + .allSatisfy(pod -> { + assertThat(pod.planDigest()).isEqualTo(plan.planDigest()); + assertThat(pod.jti()).isEqualTo(issuedEntry.jti()); + assertThat(pod.target().inventorySnapshotDigest()).isEqualTo(planningInventory.digest()); + assertThat(pod.target().inventoryBindingDigest()) + .isEqualTo(planningInventory.inventoryBindingDigest()); + assertThat(pod.target().applicabilityMatrixDigest()) + .isEqualTo(plan.applicabilityMatrixDigest()); + assertThat(pod.target().namespaceUid()).isEqualTo(NAMESPACE_UID); + assertThat(pod.target().exactPodEndpoint()).isPresent(); + assertThat(pod.target().canonicalServiceUri()) + .contains("spiffe://firemud/ns/firemud-prod/sa/account-jwt-validator"); + assertThat(pod.target().podLeafSpkiSha256()).isPresent(); + assertThat(pod.target().expectation()).isEqualTo(ProbeExpectation.ACCEPT); + }); var selector = ownerSelector(plan, issuedEntry, expectedPods.getFirst()); var ownerEvidence = @@ -772,65 +764,62 @@ void persistsExactV2PodProjectionAndClosesPerPodReceiptsAcrossRepositoryRestart( assertThat(ownerEvidence.plan().planDigest()).isEqualTo(plan.planDigest()); assertThat(ownerEvidence.entry()).isEqualTo(issuedEntry); assertThat(ownerEvidence.expectedPod()).isEqualTo(expectedPods.getFirst()); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - owner - .readiness() - .readCurrentProbeOwner( - BINDING, - owner.trust(), - ownerSelector( - plan, - issuedEntry, - expectedPods.getFirst(), - issuedEntry.expectedActive(), - "inventory-r2", - expectedPods.getFirst().target().inventorySnapshotDigest()), - refreshedInventory, - BINDING.namespace()))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + owner + .readiness() + .readCurrentProbeOwner( + BINDING, + owner.trust(), + ownerSelector( + plan, + issuedEntry, + expectedPods.getFirst(), + issuedEntry.expectedActive(), + "inventory-r2", + expectedPods.getFirst().target().inventorySnapshotDigest()), + refreshedInventory, + BINDING.namespace()))) .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - owner - .readiness() - .readCurrentProbeOwner( - BINDING, - owner.trust(), - ownerSelector( - plan, - issuedEntry, - expectedPods.getFirst(), - issuedEntry.expectedActive(), - "inventory-r1", - "e".repeat(64)), - refreshedInventory, - BINDING.namespace()))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + owner + .readiness() + .readCurrentProbeOwner( + BINDING, + owner.trust(), + ownerSelector( + plan, + issuedEntry, + expectedPods.getFirst(), + issuedEntry.expectedActive(), + "inventory-r1", + "e".repeat(64)), + refreshedInventory, + BINDING.namespace()))) .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - owner - .readiness() - .readCurrentProbeOwner( - BINDING, - owner.trust(), - ownerSelector( - plan, - issuedEntry, - expectedPods.getFirst(), - issuedEntry.expectedActive(), - expectedPods.getFirst().target().inventoryBindingRevision(), - expectedPods.getFirst().target().inventoryBindingDigest()), - refreshedInventory, - BINDING.namespace()))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + owner + .readiness() + .readCurrentProbeOwner( + BINDING, + owner.trust(), + ownerSelector( + plan, + issuedEntry, + expectedPods.getFirst(), + issuedEntry.expectedActive(), + expectedPods.getFirst().target().inventoryBindingRevision(), + expectedPods.getFirst().target().inventoryBindingDigest()), + refreshedInventory, + BINDING.namespace()))) .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); var inventedActiveFence = ownerSelector( @@ -838,37 +827,35 @@ void persistsExactV2PodProjectionAndClosesPerPodReceiptsAcrossRepositoryRestart( issuedEntry, expectedPods.getFirst(), Optional.of(new AccountJwtSignerDesiredStateRepository.ActiveSigner("2", "old-key"))); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - owner - .readiness() - .readCurrentProbeOwner( - BINDING, - owner.trust(), - inventedActiveFence, - refreshedInventory, - BINDING.namespace()))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + owner + .readiness() + .readCurrentProbeOwner( + BINDING, + owner.trust(), + inventedActiveFence, + refreshedInventory, + BINDING.namespace()))) .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); AuthenticatedAcceptance firstAcceptance = testAcceptance(issuedEntry, expectedPods.getFirst(), databaseNow); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - owner - .readiness() - .recordPodAcceptance( - BINDING, - owner.trust(), - issuedEntry, - expectedPods.getFirst(), - firstAcceptance, - changedInventory))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + owner + .readiness() + .recordPodAcceptance( + BINDING, + owner.trust(), + issuedEntry, + expectedPods.getFirst(), + firstAcceptance, + changedInventory))) .isInstanceOf(AccountJwtReadinessReceiverInvocationPort.ReceiverUnavailableException.class); assertThat(count(context, "account_jwt_readiness_pod_receipts")).isZero(); @@ -879,38 +866,36 @@ void persistsExactV2PodProjectionAndClosesPerPodReceiptsAcrossRepositoryRestart( databaseNow, issuedEntry.targetKid(), "grpcs://192.0.2.1:9443"); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - owner - .readiness() - .recordPodAcceptance( - BINDING, - owner.trust(), - issuedEntry, - expectedPods.getFirst(), - wrongEndpoint, - refreshedInventory))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + owner + .readiness() + .recordPodAcceptance( + BINDING, + owner.trust(), + issuedEntry, + expectedPods.getFirst(), + wrongEndpoint, + refreshedInventory))) .isInstanceOf(AccountJwtReadinessProbeRepository.IdempotencyConflictException.class); AuthenticatedAcceptance wrongKid = testAcceptance( issuedEntry, expectedPods.getFirst(), databaseNow, issuedEntry.targetKid() + "-wrong"); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - owner - .readiness() - .recordPodAcceptance( - BINDING, - owner.trust(), - issuedEntry, - expectedPods.getFirst(), - wrongKid, - refreshedInventory))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + owner + .readiness() + .recordPodAcceptance( + BINDING, + owner.trust(), + issuedEntry, + expectedPods.getFirst(), + wrongKid, + refreshedInventory))) .isInstanceOf(AccountJwtReadinessProbeRepository.IdempotencyConflictException.class); ProbeEntry partial = @@ -952,20 +937,19 @@ void persistsExactV2PodProjectionAndClosesPerPodReceiptsAcrossRepositoryRestart( databaseNow, issuedEntry.targetKid(), "grpcs://192.0.2.2:9443"); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - owner - .readiness() - .recordPodAcceptance( - BINDING, - owner.trust(), - issuedEntry, - expectedPods.getFirst(), - mismatchedDuplicate, - refreshedInventory))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + owner + .readiness() + .recordPodAcceptance( + BINDING, + owner.trust(), + issuedEntry, + expectedPods.getFirst(), + mismatchedDuplicate, + refreshedInventory))) .isInstanceOf(AccountJwtReadinessProbeRepository.IdempotencyConflictException.class); assertThat(count(context, "account_jwt_readiness_pod_receipts")).isEqualTo(1L); @@ -1018,20 +1002,19 @@ void persistsExactV2PodProjectionAndClosesPerPodReceiptsAcrossRepositoryRestart( databaseNow, issuedEntry.targetKid(), "grpcs://192.0.2.3:9443"); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - owner - .readiness() - .recordPodAcceptance( - BINDING, - owner.trust(), - verified, - expectedPods.get(1), - changedClosedReceipt, - refreshedInventory))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + owner + .readiness() + .recordPodAcceptance( + BINDING, + owner.trust(), + verified, + expectedPods.get(1), + changedClosedReceipt, + refreshedInventory))) .isInstanceOf(AccountJwtReadinessProbeRepository.IdempotencyConflictException.class); AccountJwtReadinessProbeRepository restartedRepository = @@ -1088,44 +1071,38 @@ void persistsExactV2PodProjectionAndClosesPerPodReceiptsAcrossRepositoryRestart( assertIndependentPartialPromotionInsertsRejected(context, owner, proof, exactPreimage); assertThatThrownBy( () -> insertDirectPromotion(context, owner, proof, "0".repeat(64), exactPreimage)) - .satisfies( - failure -> - assertThat(postgresConstraint(failure)) - .isEqualTo("account_jwt_signer_promotion_readiness_digest")); + .satisfies(failure -> + assertThat(postgresConstraint(failure)) + .isEqualTo("account_jwt_signer_promotion_readiness_digest")); String changedProofText = new String(exactPreimage, StandardCharsets.UTF_8) .replace( proof.inventoryEvidenceReference(), proof.inventoryEvidenceReference() + ":changed"); byte[] changedPreimage = changedProofText.getBytes(StandardCharsets.UTF_8); - assertThatThrownBy( - () -> - insertDirectPromotion( - context, owner, proof, sha256(changedPreimage), changedPreimage)) - .satisfies( - failure -> - assertThat(postgresConstraint(failure)) - .isEqualTo("account_jwt_signer_promotion_readiness_binding")); + assertThatThrownBy(() -> + insertDirectPromotion(context, owner, proof, sha256(changedPreimage), changedPreimage)) + .satisfies(failure -> + assertThat(postgresConstraint(failure)) + .isEqualTo("account_jwt_signer_promotion_readiness_binding")); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> { - insertDirectGenerationAbortReceipt(context, owner); - insertDirectPromotionInCurrentTransaction( - context, - owner, - proof, - UUID.randomUUID(), - proof.readinessEvidenceDigest(), - exactPreimage); - return null; - })) - .satisfies( - failure -> - assertThat(postgresConstraint(failure)) - .isEqualTo("account_jwt_signer_promotion_insert_binding")); + assertThatThrownBy(() -> + inTransaction( + context, + () -> { + insertDirectGenerationAbortReceipt(context, owner); + insertDirectPromotionInCurrentTransaction( + context, + owner, + proof, + UUID.randomUUID(), + proof.readinessEvidenceDigest(), + exactPreimage); + return null; + })) + .satisfies(failure -> + assertThat(postgresConstraint(failure)) + .isEqualTo("account_jwt_signer_promotion_insert_binding")); assertThat(count(context, "account_jwt_signer_generation_abort_receipts")).isZero(); var publicationEvidence = proof.publication(); @@ -1184,40 +1161,36 @@ context, owner, proof, sha256(changedPreimage), changedPreimage)) "Prepared promotion must retain its exact readiness preimage") .get("readiness_evidence_preimage", byte[].class); assertThat(persistedPreimage).isEqualTo(exactPreimage); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - context - .dsl() - .execute( - "UPDATE account_jwt_signer_promotion_operations " - + "SET readiness_evidence_digest = ? WHERE operation_id = ?", - "0".repeat(64), - prepared.operationId()))) - .satisfies( - failure -> - assertThat(postgresConstraint(failure)) - .isEqualTo("account_jwt_signer_operation_immutable")); + assertThatThrownBy(() -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_jwt_signer_promotion_operations " + + "SET readiness_evidence_digest = ? WHERE operation_id = ?", + "0".repeat(64), + prepared.operationId()))) + .satisfies(failure -> + assertThat(postgresConstraint(failure)) + .isEqualTo("account_jwt_signer_operation_immutable")); byte[] changedStoredPreimage = exactPreimage.clone(); changedStoredPreimage[0] ^= 1; - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - context - .dsl() - .execute( - "UPDATE account_jwt_signer_promotion_operations " - + "SET readiness_evidence_preimage = ? WHERE operation_id = ?", - changedStoredPreimage, - prepared.operationId()))) - .satisfies( - failure -> - assertThat(postgresConstraint(failure)) - .isEqualTo("account_jwt_signer_operation_immutable")); + assertThatThrownBy(() -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_jwt_signer_promotion_operations " + + "SET readiness_evidence_preimage = ? WHERE operation_id = ?", + changedStoredPreimage, + prepared.operationId()))) + .satisfies(failure -> + assertThat(postgresConstraint(failure)) + .isEqualTo("account_jwt_signer_operation_immutable")); AccountJwtSignerDesiredStateRepository restartedDesired = new AccountJwtSignerDesiredStateRepository(context.dsl()); @@ -1228,11 +1201,10 @@ context, owner, proof, sha256(changedPreimage), changedPreimage)) AccountJwtReadinessProbeRepository restartedReadiness = new AccountJwtReadinessProbeRepository( context.dsl(), restartedDesired, restartedPublication, restartedInventory); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> restartedDesired.readCurrentGenerationRequest(BINDING, owner.trust()))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> restartedDesired.readCurrentGenerationRequest(BINDING, owner.trust()))) .isInstanceOf( AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException.class) .hasMessage("Existing PREPARED signer state requires unavailable lifecycle evidence"); @@ -1448,12 +1420,11 @@ void producerFailureRetainsCompleteV2AbortedEvidenceWithoutRedeliveryOrReclaim() owner.readiness().readCurrentPlan(BINDING, owner.trust(), plan.operationId()))) .isEqualTo(plan); assertThat(plan.entries()) - .allSatisfy( - entry -> { - assertThat(entry.state()).isEqualTo(ProbeState.PLANNED); - assertThat(entry.signingAttemptedAtEpochSecond()).isEmpty(); - assertThat(entry.compactTokenSha256()).isEmpty(); - }); + .allSatisfy(entry -> { + assertThat(entry.state()).isEqualTo(ProbeState.PLANNED); + assertThat(entry.signingAttemptedAtEpochSecond()).isEmpty(); + assertThat(entry.compactTokenSha256()).isEmpty(); + }); assertThat(count(context, "account_jwt_readiness_delivery_claims")).isZero(); var harnessBinding = deliveryHarnessBinding(plan.expiresAtEpochSecond() + 600); @@ -1537,11 +1508,10 @@ void producerFailureRetainsCompleteV2AbortedEvidenceWithoutRedeliveryOrReclaim() () -> restarted.readCurrentPlan(BINDING, owner.trust(), plan.operationId())); assertThat(verifiedReadback.entries()) .hasSize(8) - .allSatisfy( - entry -> { - assertThat(entry.state()).isEqualTo(ProbeState.VERIFIED); - assertThat(entry).isEqualTo(verifiedBeforeFailure.get(entry.jti())); - }); + .allSatisfy(entry -> { + assertThat(entry.state()).isEqualTo(ProbeState.VERIFIED); + assertThat(entry).isEqualTo(verifiedBeforeFailure.get(entry.jti())); + }); assertThat(count(context, "account_jwt_readiness_pod_receipts")).isEqualTo(12L); verifiedInterruptionReached[0] = true; throw new IllegalStateException( @@ -1549,16 +1519,12 @@ void producerFailureRetainsCompleteV2AbortedEvidenceWithoutRedeliveryOrReclaim() + new String(compactJwt, StandardCharsets.US_ASCII)); } }; - assertThatThrownBy( - () -> - producer.issueCurrentPlan( - BINDING, owner.trust(), plan.operationId(), claim, delivery)) - .satisfies( - failure -> - assertThat(verifiedInterruptionReached[0]) - .as( - "the controlled interruption follows durable verification of all eight probes") - .isTrue()) + assertThatThrownBy(() -> + producer.issueCurrentPlan(BINDING, owner.trust(), plan.operationId(), claim, delivery)) + .satisfies(failure -> + assertThat(verifiedInterruptionReached[0]) + .as("the controlled interruption follows durable verification of all eight probes") + .isTrue()) // The mounted signer sanitizes callback RuntimeExceptions, including the producer's // delivery-quarantine exception, rather than exposing callback details or credentials. .isInstanceOf(AccountMountedJwtSignerBundle.InvalidMountedSignerBundleException.class) @@ -1576,19 +1542,18 @@ void producerFailureRetainsCompleteV2AbortedEvidenceWithoutRedeliveryOrReclaim() List cleaned = cleanedPlan.entries(); assertThat(cleaned) .hasSize(8) - .allSatisfy( - entry -> { - ProbeEntry verified = - java.util.Objects.requireNonNull( - verifiedBeforeFailure.get(entry.jti()), - "Every cleaned entry must retain its independently observed V2 receipt"); - assertThat(entry.state()).isEqualTo(ProbeState.CLEANED); - assertThat(entry.terminalOutcome()).contains("ABORTED"); - assertThat(entry.compactTokenSha256()).isEqualTo(verified.compactTokenSha256()); - assertThat(entry.signingAttemptedAtEpochSecond()) - .isEqualTo(verified.signingAttemptedAtEpochSecond()); - assertThat(entry.verificationReceipt()).isEqualTo(verified.verificationReceipt()); - }); + .allSatisfy(entry -> { + ProbeEntry verified = + java.util.Objects.requireNonNull( + verifiedBeforeFailure.get(entry.jti()), + "Every cleaned entry must retain its independently observed V2 receipt"); + assertThat(entry.state()).isEqualTo(ProbeState.CLEANED); + assertThat(entry.terminalOutcome()).contains("ABORTED"); + assertThat(entry.compactTokenSha256()).isEqualTo(verified.compactTokenSha256()); + assertThat(entry.signingAttemptedAtEpochSecond()) + .isEqualTo(verified.signingAttemptedAtEpochSecond()); + assertThat(entry.verificationReceipt()).isEqualTo(verified.verificationReceipt()); + }); assertThat( producer.issueCurrentPlan(BINDING, owner.trust(), plan.operationId(), claim, delivery)) .isEqualTo(cleaned); @@ -1600,47 +1565,44 @@ void producerFailureRetainsCompleteV2AbortedEvidenceWithoutRedeliveryOrReclaim() () -> owner.readiness().readCurrentPlan(BINDING, owner.trust(), plan.operationId()))) .isEqualTo(cleanedPlan); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - context - .dsl() - .execute( - "UPDATE account_jwt_readiness_probe_entries SET state = 'VERIFIED', " - + "entry_version = entry_version + 1 WHERE rotation_operation_id = ?", - plan.operationId()))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "UPDATE account_jwt_readiness_probe_entries SET state = 'VERIFIED', " + + "entry_version = entry_version + 1 WHERE rotation_operation_id = ?", + plan.operationId()))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - owner - .readiness() - .claimSingleDelivery( - BINDING, - owner.trust(), - cleanedPlan, - harnessBinding, - peer, - Instant.ofEpochSecond(now)))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + owner + .readiness() + .claimSingleDelivery( + BINDING, + owner.trust(), + cleanedPlan, + harnessBinding, + peer, + Instant.ofEpochSecond(now)))) .isInstanceOf(AccountJwtReadinessProbeRepository.DeliveryAlreadyClaimedException.class); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - owner - .readiness() - .claimSingleDelivery( - BINDING, - owner.trust(), - plan, - harnessBinding, - peer, - Instant.ofEpochSecond(now)))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + owner + .readiness() + .claimSingleDelivery( + BINDING, + owner.trust(), + plan, + harnessBinding, + peer, + Instant.ofEpochSecond(now)))) .isInstanceOf(AccountJwtReadinessProbeRepository.StaleOperationException.class); assertThat( inTransaction( @@ -1843,27 +1805,25 @@ private static void assertIndependentPartialPromotionInsertsRejected( String validRow = context .transaction() - .execute( - status -> { - insertDirectPromotionInCurrentTransaction( - context, - owner, - proof, - UUID.randomUUID(), - proof.readinessEvidenceDigest(), - exactPreimage); - String row = - java.util.Objects.requireNonNull( - context - .dsl() - .fetchOne( - "SELECT to_jsonb(promotion)::text FROM account_jwt_signer_promotion_operations AS promotion")) - .get(0, String.class); - assertThat(count(context, "account_jwt_signer_promotion_operations")) - .isEqualTo(1L); - status.setRollbackOnly(); - return row; - }); + .execute(status -> { + insertDirectPromotionInCurrentTransaction( + context, + owner, + proof, + UUID.randomUUID(), + proof.readinessEvidenceDigest(), + exactPreimage); + String row = + java.util.Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT to_jsonb(promotion)::text FROM account_jwt_signer_promotion_operations AS promotion")) + .get(0, String.class); + assertThat(count(context, "account_jwt_signer_promotion_operations")).isEqualTo(1L); + status.setRollbackOnly(); + return row; + }); assertThat(validRow).isNotNull(); for (String field : List.of( @@ -1871,22 +1831,21 @@ private static void assertIndependentPartialPromotionInsertsRejected( "api_config_revision", "expected_public_config_map_uid")) { for (boolean explicitNull : new boolean[] {false, true}) { - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - context - .dsl() - .execute( - "INSERT INTO account_jwt_signer_promotion_operations SELECT * FROM " - + "jsonb_populate_record(NULL::account_jwt_signer_promotion_operations, " - + (explicitNull - ? "?::jsonb || jsonb_build_object(?, NULL)" - : "?::jsonb - ?::text") - + ")", - validRow, - field))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_jwt_signer_promotion_operations SELECT * FROM " + + "jsonb_populate_record(NULL::account_jwt_signer_promotion_operations, " + + (explicitNull + ? "?::jsonb || jsonb_build_object(?, NULL)" + : "?::jsonb - ?::text") + + ")", + validRow, + field))) .as("independent promotion INSERT with %s %s", explicitNull ? "null" : "missing", field) .isInstanceOf(DataAccessException.class) .satisfies(failure -> assertThat(postgresSqlState(failure)).isEqualTo("23514")); @@ -1900,20 +1859,19 @@ private static void assertIndependentPartialPromotionInsertsRejected( "expected_private_secret_resource_version", "expected_public_jwks_resource_version")) { String invalid = field.endsWith("resource_version") ? "r\n" : "not-a-sha256"; - assertThatThrownBy( - () -> - inTransaction( - context, - () -> - context - .dsl() - .execute( - "INSERT INTO account_jwt_signer_promotion_operations SELECT * FROM " - + "jsonb_populate_record(NULL::account_jwt_signer_promotion_operations, " - + "?::jsonb || jsonb_build_object(?, ?))", - validRow, - field, - invalid))) + assertThatThrownBy(() -> + inTransaction( + context, + () -> + context + .dsl() + .execute( + "INSERT INTO account_jwt_signer_promotion_operations SELECT * FROM " + + "jsonb_populate_record(NULL::account_jwt_signer_promotion_operations, " + + "?::jsonb || jsonb_build_object(?, ?))", + validRow, + field, + invalid))) .as("independent malformed promotion INSERT: %s", field) .isInstanceOf(DataAccessException.class) .satisfies(failure -> assertThat(postgresSqlState(failure)).isEqualTo("23514")); @@ -2317,18 +2275,16 @@ private static void assertReadinessInventoryClosureGuardRejectsMatrixMismatch( ReadinessProbePlan plan, String mismatchedMatrixJson, String mismatchDescription) { - assertThatThrownBy( - () -> - inTransaction( - context, - () -> { - insertRawReadinessPlanClosure(context, plan, mismatchedMatrixJson, false); - assertThat(count(context, "account_jwt_readiness_probe_entries")) - .isEqualTo(plan.entries().size()); - assertThat(count(context, "account_jwt_readiness_validator_pods")) - .isEqualTo(12L); - return null; - })) + assertThatThrownBy(() -> + inTransaction( + context, + () -> { + insertRawReadinessPlanClosure(context, plan, mismatchedMatrixJson, false); + assertThat(count(context, "account_jwt_readiness_probe_entries")) + .isEqualTo(plan.entries().size()); + assertThat(count(context, "account_jwt_readiness_validator_pods")).isEqualTo(12L); + return null; + })) .as("deferred V2 closure must reject %s", mismatchDescription) .satisfies(failure -> assertThat(postgresSqlState(failure)).isEqualTo("23514")); assertThat(count(context, "account_jwt_readiness_probe_plans")).isZero(); @@ -2446,14 +2402,13 @@ private static void assertReadinessPlanInventoryGuardRejects( readinessMatrixWithMissingOrNullField( plan.applicabilityMatrixJson(), field, explicitNull); String fieldState = explicitNull ? "null " : "missing "; - assertThatThrownBy( - () -> - inTransaction( - context, - () -> { - insertRawReadinessPlan(context, plan, malformedMatrix); - return null; - })) + assertThatThrownBy(() -> + inTransaction( + context, + () -> { + insertRawReadinessPlan(context, plan, malformedMatrix); + return null; + })) .as("raw SQL must reject V%s %s%s", plan.planVersion(), fieldState, field) .satisfies(failure -> assertThat(postgresSqlState(failure)).isEqualTo("23514")); assertThat(count(context, "account_jwt_readiness_probe_plans")).isZero(); @@ -2462,13 +2417,12 @@ private static void assertReadinessPlanInventoryGuardRejects( context .transaction() - .execute( - status -> { - insertRawReadinessPlan(context, plan, plan.applicabilityMatrixJson()); - assertThat(count(context, "account_jwt_readiness_probe_plans")).isEqualTo(1L); - status.setRollbackOnly(); - return null; - }); + .execute(status -> { + insertRawReadinessPlan(context, plan, plan.applicabilityMatrixJson()); + assertThat(count(context, "account_jwt_readiness_probe_plans")).isEqualTo(1L); + status.setRollbackOnly(); + return null; + }); assertThat(count(context, "account_jwt_readiness_probe_plans")).isZero(); } @@ -2552,29 +2506,26 @@ private static void assertReadinessEvidenceTruncateDeniedWithoutLoss( for (String table : tables) { for (String cascade : List.of("", " CASCADE")) { - assertThatThrownBy( - () -> - inTransaction( - context, - () -> { - context.dsl().execute("TRUNCATE TABLE " + table + cascade); - return null; - })) + assertThatThrownBy(() -> + inTransaction( + context, + () -> { + context.dsl().execute("TRUNCATE TABLE " + table + cascade); + return null; + })) .as("raw TRUNCATE must retain readiness evidence in %s%s", table, cascade) - .satisfies( - failure -> { - String sqlState = postgresSqlState(failure); - List expectedSqlStates = - cascade.isEmpty() ? List.of("23514", "0A000") : List.of("23514"); - assertThat(sqlState).isIn(expectedSqlStates); - if ("23514".equals(sqlState)) { - assertThat(postgresServerMessage(failure)) - .contains("Account JWT readiness evidence"); - } - }); - retainedCounts.forEach( - (retainedTable, expectedCount) -> - assertThat(count(context, retainedTable)).isEqualTo(expectedCount)); + .satisfies(failure -> { + String sqlState = postgresSqlState(failure); + List expectedSqlStates = + cascade.isEmpty() ? List.of("23514", "0A000") : List.of("23514"); + assertThat(sqlState).isIn(expectedSqlStates); + if ("23514".equals(sqlState)) { + assertThat(postgresServerMessage(failure)) + .contains("Account JWT readiness evidence"); + } + }); + retainedCounts.forEach((retainedTable, expectedCount) -> + assertThat(count(context, retainedTable)).isEqualTo(expectedCount)); } } } @@ -2602,11 +2553,10 @@ private static void insertRawPodReceipt( expectedActive.put("present", entry.expectedActive().isPresent()); entry .expectedActive() - .ifPresent( - active -> { - expectedActive.put("generation", active.generation()); - expectedActive.put("kid", active.kid()); - }); + .ifPresent(active -> { + expectedActive.put("generation", active.generation()); + expectedActive.put("kid", active.kid()); + }); digestFields.put("expectedActive", expectedActive); digestFields.put("outcome", acceptance.result().name()); digestFields.put("observedPodUid", acceptance.podUid()); @@ -2668,43 +2618,42 @@ private static void assertReadinessVerifiedTransitionRejectsChangedSigningAttemp int expectedPodCount, long verifiedAtEpochSecond) { String alteredReceiptDigest = "f".repeat(64); - assertThatThrownBy( - () -> - inTransaction( - context, - () -> { - context - .dsl() - .execute( - "UPDATE account_jwt_readiness_probe_entries SET " - + "state = 'VERIFIED', entry_version = entry_version + 1, " - + "signing_attempted_at_epoch_seconds = " - + "signing_attempted_at_epoch_seconds + 1, " - + "verification_receipt_version = 2, " - + "verification_source_entry_version = entry_version, " - + "verified_at_epoch_seconds = ?, verified_kid = target_kid, " - + "validator_instance_id = 'raw-sql-validator-1', " - + "validator_binding_digest = ?, " - + "validator_config_revision = 'config-r1', " - + "validator_peer_uri = ?, validator_peer_spki_sha256 = ?, " - + "verification_receipt_sha256 = ?, pod_receipt_count = ?, " - + "pod_receipt_closure_sha256 = ? " - + "WHERE rotation_operation_id = ? AND validator_id = ? " - + "AND token_profile = ? AND audience = ? AND probe_kind = ?", - verifiedAtEpochSecond, - "d".repeat(64), - "spiffe://firemud/ns/firemud-prod/sa/account-jwt-validator", - "e".repeat(64), - alteredReceiptDigest, - expectedPodCount, - alteredReceiptDigest, - issuedEntry.rotationOperationId(), - issuedEntry.validatorId(), - issuedEntry.tokenProfile(), - issuedEntry.audience(), - issuedEntry.probeKind().name()); - return null; - })) + assertThatThrownBy(() -> + inTransaction( + context, + () -> { + context + .dsl() + .execute( + "UPDATE account_jwt_readiness_probe_entries SET " + + "state = 'VERIFIED', entry_version = entry_version + 1, " + + "signing_attempted_at_epoch_seconds = " + + "signing_attempted_at_epoch_seconds + 1, " + + "verification_receipt_version = 2, " + + "verification_source_entry_version = entry_version, " + + "verified_at_epoch_seconds = ?, verified_kid = target_kid, " + + "validator_instance_id = 'raw-sql-validator-1', " + + "validator_binding_digest = ?, " + + "validator_config_revision = 'config-r1', " + + "validator_peer_uri = ?, validator_peer_spki_sha256 = ?, " + + "verification_receipt_sha256 = ?, pod_receipt_count = ?, " + + "pod_receipt_closure_sha256 = ? " + + "WHERE rotation_operation_id = ? AND validator_id = ? " + + "AND token_profile = ? AND audience = ? AND probe_kind = ?", + verifiedAtEpochSecond, + "d".repeat(64), + "spiffe://firemud/ns/firemud-prod/sa/account-jwt-validator", + "e".repeat(64), + alteredReceiptDigest, + expectedPodCount, + alteredReceiptDigest, + issuedEntry.rotationOperationId(), + issuedEntry.validatorId(), + issuedEntry.tokenProfile(), + issuedEntry.audience(), + issuedEntry.probeKind().name()); + return null; + })) .satisfies(failure -> assertThat(postgresSqlState(failure)).isEqualTo("23514")); var retainedEntry = @@ -3053,28 +3002,26 @@ private static Map inventoryValidatorMap( result.put( "profiles", validator.profiles().stream() - .map( - profile -> - Map.of("tokenProfile", profile.tokenProfile(), "audience", profile.audience())) + .map(profile -> + Map.of("tokenProfile", profile.tokenProfile(), "audience", profile.audience())) .toList()); result.put( "pods", validator.pods().stream() - .map( - pod -> - Map.ofEntries( - Map.entry("name", pod.name()), - Map.entry("uid", pod.uid()), - Map.entry("resourceVersion", pod.resourceVersion()), - Map.entry("ownerReplicaSetName", pod.ownerName()), - Map.entry("ownerReplicaSetUid", pod.ownerUid()), - Map.entry("podTemplateHash", pod.podTemplateHash()), - Map.entry("image", pod.image()), - Map.entry("verifierConfigSha256", pod.verifierConfigSha256()), - Map.entry("podIp", pod.podIp()), - Map.entry("exactPodEndpoint", pod.endpoint().toString()), - Map.entry("canonicalServiceUri", pod.receiverServiceUri()), - Map.entry("leafSpkiSha256", pod.leafSpkiSha256()))) + .map(pod -> + Map.ofEntries( + Map.entry("name", pod.name()), + Map.entry("uid", pod.uid()), + Map.entry("resourceVersion", pod.resourceVersion()), + Map.entry("ownerReplicaSetName", pod.ownerName()), + Map.entry("ownerReplicaSetUid", pod.ownerUid()), + Map.entry("podTemplateHash", pod.podTemplateHash()), + Map.entry("image", pod.image()), + Map.entry("verifierConfigSha256", pod.verifierConfigSha256()), + Map.entry("podIp", pod.podIp()), + Map.entry("exactPodEndpoint", pod.endpoint().toString()), + Map.entry("canonicalServiceUri", pod.receiverServiceUri()), + Map.entry("leafSpkiSha256", pod.leafSpkiSha256()))) .toList()); result.put("receiverServiceUri", serviceUri); result.put("receiverPort", receiverPort); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java index e40b6882e8..5bddfc71e6 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java @@ -129,31 +129,28 @@ private void assertOriginalCreatorTimeAtFinalOwnerLock( AccountControlUiCoordination.digest( "SHA-256", issued.compact().getBytes(java.nio.charset.StandardCharsets.US_ASCII)); var jti = - f.tx( - () -> - f.dsl - .fetchSingle( - "SELECT token_jti FROM account_control_ui_issuance_operations " - + "WHERE token_hash=? AND status='COMMITTED'", - tokenHash) - .get("token_jti", UUID.class)); + f.tx(() -> + f.dsl + .fetchSingle( + "SELECT token_jti FROM account_control_ui_issuance_operations " + + "WHERE token_hash=? AND status='COMMITTED'", + tokenHash) + .get("token_jti", UUID.class)); long issuedAt = java.util.Objects.requireNonNull( - f.tx( - () -> - f.dsl - .fetchSingle( - "SELECT issued_at_epoch_second FROM account_control_ui_issuance_operations " - + "WHERE token_jti=?", - jti) - .get("issued_at_epoch_second", Long.class))); + f.tx(() -> + f.dsl + .fetchSingle( + "SELECT issued_at_epoch_second FROM account_control_ui_issuance_operations " + + "WHERE token_jti=?", + jti) + .get("issued_at_epoch_second", Long.class))); var before = - f.tx( - () -> - f.dsl.fetchSingle( - "SELECT row_to_json(a)::TEXT AS payload, a.xmin::TEXT AS row_version " - + "FROM account_control_ui_issuance_operations a WHERE token_jti=?", - jti)); + f.tx(() -> + f.dsl.fetchSingle( + "SELECT row_to_json(a)::TEXT AS payload, a.xmin::TEXT AS row_version " + + "FROM account_control_ui_issuance_operations a WHERE token_jti=?", + jti)); var callback = new AtomicBoolean(); var clockChanged = new AtomicBoolean(); var originalListeners = f.dsl.configuration().executeListenerProviders(); @@ -184,33 +181,32 @@ public void executeEnd(ExecuteContext context) { f.dsl.configuration().set(listeners); try { Throwable failure = - catchThrowable( - () -> { - if (signedCredential) { - issued - .actors() - .withCurrent( - issued.compact(), - f.tenant, - issued.environment(), - current -> { - callback.set(true); - return "callback invoked"; - }); - } else { - issued - .actors() - .withCurrentCommitted( - f.account.getAccountUuid(), - f.tenant, - jti, - issued.environment(), - current -> { - callback.set(true); - return "callback invoked"; - }); - } - }); + catchThrowable(() -> { + if (signedCredential) { + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> { + callback.set(true); + return "callback invoked"; + }); + } else { + issued + .actors() + .withCurrentCommitted( + f.account.getAccountUuid(), + f.tenant, + jti, + issued.environment(), + current -> { + callback.set(true); + return "callback invoked"; + }); + } + }); assertThat(clockChanged).isTrue(); assertThat(clock.instant().isBefore(Instant.ofEpochSecond(issuedAt))) .isEqualTo(clockChange.isNegative()); @@ -224,12 +220,11 @@ public void executeEnd(ExecuteContext context) { .hasMessage("Exact current authenticated initial creator required"); } assertThat( - f.tx( - () -> - f.dsl.fetchSingle( - "SELECT row_to_json(a)::TEXT AS payload, a.xmin::TEXT AS row_version " - + "FROM account_control_ui_issuance_operations a WHERE token_jti=?", - jti))) + f.tx(() -> + f.dsl.fetchSingle( + "SELECT row_to_json(a)::TEXT AS payload, a.xmin::TEXT AS row_version " + + "FROM account_control_ui_issuance_operations a WHERE token_jti=?", + jti))) .isEqualTo(before); } finally { f.dsl.configuration().set(originalListeners); @@ -266,13 +261,12 @@ void originalCreatorRequiresExactKeyInCurrentProtectedSnapshot( AccountControlUiCoordination.digest( "SHA-256", issued.compact().getBytes(java.nio.charset.StandardCharsets.US_ASCII)); var original = - f.tx( - () -> - f.dsl.fetchSingle( - "SELECT token_jti, signer_receipt, row_to_json(a)::TEXT AS payload, " - + "a.xmin::TEXT AS row_version FROM account_control_ui_issuance_operations a " - + "WHERE token_hash=? AND status='COMMITTED'", - tokenHash)); + f.tx(() -> + f.dsl.fetchSingle( + "SELECT token_jti, signer_receipt, row_to_json(a)::TEXT AS payload, " + + "a.xmin::TEXT AS row_version FROM account_control_ui_issuance_operations a " + + "WHERE token_hash=? AND status='COMMITTED'", + tokenHash)); UUID jti = original.get("token_jti", UUID.class); var receipt = AccountControlUiIssuanceRepository.object(original.get("signer_receipt", byte[].class)); @@ -388,30 +382,28 @@ void originalCreatorRequiresExactKeyInCurrentProtectedSnapshot( }); }; Throwable failure = - catchThrowable( - () -> { - if ("SQL".equals(keyState)) { - f.tx(action::get); - } else if ("SYNCHRONIZATION".equals(keyState)) { - org.springframework.transaction.support.TransactionSynchronizationManager - .initSynchronization(); - try { - action.get(); - } finally { - org.springframework.transaction.support.TransactionSynchronizationManager - .clearSynchronization(); - } - } else { - action.get(); - } - }); + catchThrowable(() -> { + if ("SQL".equals(keyState)) { + f.tx(action::get); + } else if ("SYNCHRONIZATION".equals(keyState)) { + org.springframework.transaction.support.TransactionSynchronizationManager + .initSynchronization(); + try { + action.get(); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager + .clearSynchronization(); + } + } else { + action.get(); + } + }); var after = - f.tx( - () -> - f.dsl.fetchSingle( - "SELECT row_to_json(a)::TEXT AS payload, a.xmin::TEXT AS row_version " - + "FROM account_control_ui_issuance_operations a WHERE token_hash=?", - tokenHash)); + f.tx(() -> + f.dsl.fetchSingle( + "SELECT row_to_json(a)::TEXT AS payload, a.xmin::TEXT AS row_version " + + "FROM account_control_ui_issuance_operations a WHERE token_hash=?", + tokenHash)); assertThat(after.get("payload", String.class)) .isEqualTo(original.get("payload", String.class)); assertThat(after.get("row_version", String.class)) @@ -547,12 +539,11 @@ void lostOriginalOrderResponseRecoversAfterSignedCreatorExpiryButCannotCreateOrS original.inputDigest(), original.sources()) .withRequiredOwners(); - assertThatThrownBy( - () -> - asPeer( - "test", - "game-design-service", - () -> owner.claim(issued.compact(), changed, issued.environment()))) + assertThatThrownBy(() -> + asPeer( + "test", + "game-design-service", + () -> owner.claim(issued.compact(), changed, issued.environment()))) .isInstanceOf(io.grpc.StatusRuntimeException.class) .extracting(failure -> io.grpc.Status.fromThrowable(failure).getCode()) .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION); @@ -572,12 +563,11 @@ void lostOriginalOrderResponseRecoversAfterSignedCreatorExpiryButCannotCreateOrS original.inputDigest(), original.sources()) .withRequiredOwners(); - assertThatThrownBy( - () -> - asPeer( - "test", - "game-design-service", - () -> owner.claim(issued.compact(), absent, issued.environment()))) + assertThatThrownBy(() -> + asPeer( + "test", + "game-design-service", + () -> owner.claim(issued.compact(), absent, issued.environment()))) .isInstanceOf( net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier .VerificationException.class); @@ -586,36 +576,33 @@ void lostOriginalOrderResponseRecoversAfterSignedCreatorExpiryButCannotCreateOrS List.of( new String[] {"other", "game-design-service"}, new String[] {"test", "world-management-service"})) { - assertThatThrownBy( - () -> - asPeer( - peer[0], - peer[1], - () -> owner.claim(issued.compact(), original, issued.environment()))) + assertThatThrownBy(() -> + asPeer( + peer[0], + peer[1], + () -> owner.claim(issued.compact(), original, issued.environment()))) .isInstanceOf(io.grpc.StatusRuntimeException.class); } // Explicit upstream terminal stipulation tests settled denial; it never fabricates HELD. - f.tx( - () -> { - f.fences.recordOwnerReadback( - original, - new DraftAuthorizationFenceBinding.OwnerReadback( - DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, - DraftAuthorizationFenceBinding.Outcome.COMMITTED, - original.operationId(), - original.commitId(), - original.fenceId(), - original.inputDigest(), - original.canonicalBytes(), - new byte[] {1})); - return null; - }); - assertThatThrownBy( - () -> - asPeer( - "test", - "game-design-service", - () -> owner.claim(issued.compact(), original, issued.environment()))) + f.tx(() -> { + f.fences.recordOwnerReadback( + original, + new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.canonicalBytes(), + new byte[] {1})); + return null; + }); + assertThatThrownBy(() -> + asPeer( + "test", + "game-design-service", + () -> owner.claim(issued.compact(), original, issued.environment()))) .isInstanceOf(io.grpc.StatusRuntimeException.class); var reservedInput = DraftCommitBinding.create( @@ -642,24 +629,22 @@ void lostOriginalOrderResponseRecoversAfterSignedCreatorExpiryButCannotCreateOrS sources) .withRequiredOwners(); f.tx(() -> f.fences.reserve(reserved)); - assertThatThrownBy( - () -> - asPeer( - "test", - "game-design-service", - () -> owner.claim(issued.compact(), reserved, issued.environment()))) + assertThatThrownBy(() -> + asPeer( + "test", + "game-design-service", + () -> owner.claim(issued.compact(), reserved, issued.environment()))) .isInstanceOf(io.grpc.StatusRuntimeException.class); var change = new net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository .SourceChange(UUID.randomUUID(), sources, new byte[] {9}); assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isFalse(); assertThat(f.tx(() -> f.fences.read(reserved)).ordering().name()).isEqualTo("REVOKE_ORDER"); - assertThatThrownBy( - () -> - asPeer( - "test", - "game-design-service", - () -> owner.claim(issued.compact(), reserved, issued.environment()))) + assertThatThrownBy(() -> + asPeer( + "test", + "game-design-service", + () -> owner.claim(issued.compact(), reserved, issued.environment()))) .isInstanceOf(io.grpc.StatusRuntimeException.class); } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksReadRegistrationMtlsIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksReadRegistrationMtlsIntegrationTest.java index 7e79c48e34..22078aed64 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksReadRegistrationMtlsIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksReadRegistrationMtlsIntegrationTest.java @@ -179,221 +179,209 @@ void actualRegistrationUsesExactTlsWorkloadRatherThanBearerOrRequestClaims(Strin var snapshot = new ReadResult(sourceIdentity(), publicJwks, false, false); when(source.sourceIdentity()).thenReturn(snapshot.sourceIdentity()); when(source.currentPublicRead()) - .thenAnswer( - ignored -> { - assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(GAME_SESSION_URI); - assertEmptyBearerContext(); - return snapshot; - }); + .thenAnswer(ignored -> { + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(GAME_SESSION_URI); + assertEmptyBearerContext(); + return snapshot; + }); int port = unusedLoopbackPort(); runner(resource, port, source, protectedBinding) .withPropertyValues("firemud.account.public-jwks-read.enabled=true") - .run( - context -> { - assertThat(context) - .hasNotFailed() - .hasSingleBean(AccountPublicJwksReadGrpcService.class); - assertThat(context).hasSingleBean(AccountPublicJwksReadService.class); - assertThat(context).hasSingleBean(AuthTokenInterceptor.class); - assertThat(context).hasSingleBean(GrpcPeerIdentityInterceptor.class); - assertThat(context.getBean(GrpcServerFactory.class)) - .isExactlyInstanceOf(BoundedGrpcServerFactory.class); - assertThat(context.getBean(GrpcServerLifecycle.class).isRunning()).isTrue(); - assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) - .contains(METHOD) - .doesNotContain(PROFILE_METHOD, "account.v1.AccountPublicJwksReadService/*"); - String accountId = "44444444-4444-4444-8444-444444444444"; - String token = - context - .getBean(JwtUtil.class) - .generateToken( - accountId, - Map.of("accountId", accountId, "globalRoles", List.of("platformAdmin"))); - try (var client = new Client(port, gameSession)) { - var response = - client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request()); - assertThat(response).isEqualTo(AccountPublicJwksReadCodec.response(snapshot)); - assertThat(AccountPublicJwksReadCodec.snapshot(response).jwksBytes()) - .isEqualTo(publicJwks); - assertThat(response.getSourceIdentity().getAllFields()).hasSize(9); - // A valid privileged bearer is ignored for this exact method. The actual guard - // still sees empty SessionContext in source.currentPublicRead(), not the bearer - // claims. - assertThat( - client - .withBearer(token) - .getCurrentPublicJwks(AccountPublicJwksReadCodec.request())) - .isEqualTo(response); - var adjacent = context.getBean(AdjacentAccountProfileService.class); - assertCode( - Status.Code.UNAUTHENTICATED, - () -> - AccountServiceGrpc.newBlockingStub(client.channel) - .getProfile(GetProfileRequest.getDefaultInstance())); - assertThat(adjacent.calls).hasValue(0); - assertThat( - AccountServiceGrpc.newBlockingStub(client.channel) - .withInterceptors( - MetadataUtils.newAttachHeadersInterceptor(headers(token))) - .getProfile(GetProfileRequest.getDefaultInstance()) - .getProfileJson()) - .isEqualTo("registered non-exempt handler"); - assertThat(adjacent.calls).hasValue(1); - // The authenticated adjacent call cannot contaminate the following exempt read. - assertThat(client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())) - .isEqualTo(response); - } - clearInvocations(source); - for (Identity peer : rejectedPeers) { - try (var client = new Client(port, peer)) { - assertCode( - Status.Code.PERMISSION_DENIED, - () -> - client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); - assertCode( - Status.Code.PERMISSION_DENIED, - () -> - client - .withBearer(token) - .getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); - } - verifyNoInteractions(source); - } - try (var client = new Client(port, null)) { - assertCode( - Status.Code.UNAVAILABLE, - () -> - client - .withBearer(token) - .getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); - } + .run(context -> { + assertThat(context).hasNotFailed().hasSingleBean(AccountPublicJwksReadGrpcService.class); + assertThat(context).hasSingleBean(AccountPublicJwksReadService.class); + assertThat(context).hasSingleBean(AuthTokenInterceptor.class); + assertThat(context).hasSingleBean(GrpcPeerIdentityInterceptor.class); + assertThat(context.getBean(GrpcServerFactory.class)) + .isExactlyInstanceOf(BoundedGrpcServerFactory.class); + assertThat(context.getBean(GrpcServerLifecycle.class).isRunning()).isTrue(); + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .contains(METHOD) + .doesNotContain(PROFILE_METHOD, "account.v1.AccountPublicJwksReadService/*"); + String accountId = "44444444-4444-4444-8444-444444444444"; + String token = + context + .getBean(JwtUtil.class) + .generateToken( + accountId, + Map.of("accountId", accountId, "globalRoles", List.of("platformAdmin"))); + try (var client = new Client(port, gameSession)) { + var response = client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request()); + assertThat(response).isEqualTo(AccountPublicJwksReadCodec.response(snapshot)); + assertThat(AccountPublicJwksReadCodec.snapshot(response).jwksBytes()) + .isEqualTo(publicJwks); + assertThat(response.getSourceIdentity().getAllFields()).hasSize(9); + // A valid privileged bearer is ignored for this exact method. The actual guard + // still sees empty SessionContext in source.currentPublicRead(), not the bearer + // claims. + assertThat( + client + .withBearer(token) + .getCurrentPublicJwks(AccountPublicJwksReadCodec.request())) + .isEqualTo(response); + var adjacent = context.getBean(AdjacentAccountProfileService.class); + assertCode( + Status.Code.UNAUTHENTICATED, + () -> + AccountServiceGrpc.newBlockingStub(client.channel) + .getProfile(GetProfileRequest.getDefaultInstance())); + assertThat(adjacent.calls).hasValue(0); + assertThat( + AccountServiceGrpc.newBlockingStub(client.channel) + .withInterceptors(MetadataUtils.newAttachHeadersInterceptor(headers(token))) + .getProfile(GetProfileRequest.getDefaultInstance()) + .getProfileJson()) + .isEqualTo("registered non-exempt handler"); + assertThat(adjacent.calls).hasValue(1); + // The authenticated adjacent call cannot contaminate the following exempt read. + assertThat(client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())) + .isEqualTo(response); + } + clearInvocations(source); + for (Identity peer : rejectedPeers) { + try (var client = new Client(port, peer)) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> + client + .withBearer(token) + .getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + } + verifyNoInteractions(source); + } + try (var client = new Client(port, null)) { + assertCode( + Status.Code.UNAVAILABLE, + () -> + client + .withBearer(token) + .getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + } + verifyNoInteractions(source); + try (var client = new Client(port, gameSession)) { + for (var malformed : + List.of( + GetCurrentAccountPublicJwksRequest.getDefaultInstance(), + AccountPublicJwksReadCodec.request().toBuilder().setSchemaVersion(1).build(), + AccountPublicJwksReadCodec.request().toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) { + assertCode( + Status.Code.INVALID_ARGUMENT, + () -> client.stub().getCurrentPublicJwks(malformed)); verifyNoInteractions(source); - try (var client = new Client(port, gameSession)) { - for (var malformed : - List.of( - GetCurrentAccountPublicJwksRequest.getDefaultInstance(), - AccountPublicJwksReadCodec.request().toBuilder() - .setSchemaVersion(1) - .build(), - AccountPublicJwksReadCodec.request().toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField( - 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) - .build()) - .build())) { - assertCode( - Status.Code.INVALID_ARGUMENT, - () -> client.stub().getCurrentPublicJwks(malformed)); - verifyNoInteractions(source); - } - doThrow(new IllegalStateException("private internal handler fault")) - .when(source) - .currentPublicRead(); - assertCode( - Status.Code.UNAVAILABLE, - () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); - doThrow(new AccountPublicJwksReadCodec.InvalidFrameException()) - .when(source) - .currentPublicRead(); - assertCode( - Status.Code.FAILED_PRECONDITION, - () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); - var deny = new ReadResult(sourceIdentity(), new byte[0], true, false); - doReturn(deny).when(source).currentPublicRead(); - assertThat( - AccountPublicJwksReadCodec.result( - client - .stub() - .getCurrentPublicJwks(AccountPublicJwksReadCodec.request())) - .preparedDeny()) - .isTrue(); - var committed = new ReadResult(sourceIdentity(), publicJwks, false, true); - doReturn(committed).when(source).currentPublicRead(); - assertThat( - AccountPublicJwksReadCodec.result( - client - .stub() - .getCurrentPublicJwks(AccountPublicJwksReadCodec.request())) - .committedRecoveryEligible()) - .isTrue(); - doReturn(snapshot).when(source).currentPublicRead(); - assertThat(client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())) - .isEqualTo(AccountPublicJwksReadCodec.response(snapshot)); - doThrow(new AccountPublicJwksCache.InvalidJwksException()) - .when(source) - .currentPublicRead(); - assertCode( - Status.Code.FAILED_PRECONDITION, - () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); - doThrow(new AccountPublicJwksCache.SourceUnavailableException()) - .when(source) - .currentPublicRead(); - assertCode( - Status.Code.UNAVAILABLE, - () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); - doReturn( - new ReadResult( - new SourceIdentity( - "test", - "cluster-a", - CLUSTER_UID, - NAMESPACE, - NAMESPACE_UID, - "55555555-5555-4555-8555-555555555555", - "api-r1", - "https://kubernetes.test:6443", - "b".repeat(64)), - publicJwks, - false, - false)) - .when(source) - .currentPublicRead(); - assertCode( - Status.Code.FAILED_PRECONDITION, - () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); - for (String mismatch : List.of("api-origin", "binding-revision")) { - var expected = sourceIdentity(); - var changed = - new SourceIdentity( - expected.environmentId(), - expected.clusterId(), - expected.clusterIncarnationUid(), - expected.namespace(), - expected.namespaceUid(), - expected.configMapUid(), - mismatch.equals("binding-revision") - ? "api-r2" - : expected.bindingRevision(), - mismatch.equals("api-origin") - ? "https://different-api.test:6443" - : expected.apiServerOrigin(), - expected.servingCaSha256()); - doReturn(new ReadResult(changed, publicJwks, false, false)) - .when(source) - .currentPublicRead(); - assertCode( - Status.Code.FAILED_PRECONDITION, - () -> - client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); - } - doAnswer( - ignored -> { - protectedBinding.trust.set(Optional.empty()); - return snapshot; - }) - .when(source) - .currentPublicRead(); - assertCode( - Status.Code.PERMISSION_DENIED, - () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); - clearInvocations(source); - assertCode( - Status.Code.PERMISSION_DENIED, - () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); - verifyNoInteractions(source); - } - }); + } + doThrow(new IllegalStateException("private internal handler fault")) + .when(source) + .currentPublicRead(); + assertCode( + Status.Code.UNAVAILABLE, + () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + doThrow(new AccountPublicJwksReadCodec.InvalidFrameException()) + .when(source) + .currentPublicRead(); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + var deny = new ReadResult(sourceIdentity(), new byte[0], true, false); + doReturn(deny).when(source).currentPublicRead(); + assertThat( + AccountPublicJwksReadCodec.result( + client + .stub() + .getCurrentPublicJwks(AccountPublicJwksReadCodec.request())) + .preparedDeny()) + .isTrue(); + var committed = new ReadResult(sourceIdentity(), publicJwks, false, true); + doReturn(committed).when(source).currentPublicRead(); + assertThat( + AccountPublicJwksReadCodec.result( + client + .stub() + .getCurrentPublicJwks(AccountPublicJwksReadCodec.request())) + .committedRecoveryEligible()) + .isTrue(); + doReturn(snapshot).when(source).currentPublicRead(); + assertThat(client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())) + .isEqualTo(AccountPublicJwksReadCodec.response(snapshot)); + doThrow(new AccountPublicJwksCache.InvalidJwksException()) + .when(source) + .currentPublicRead(); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + doThrow(new AccountPublicJwksCache.SourceUnavailableException()) + .when(source) + .currentPublicRead(); + assertCode( + Status.Code.UNAVAILABLE, + () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + doReturn( + new ReadResult( + new SourceIdentity( + "test", + "cluster-a", + CLUSTER_UID, + NAMESPACE, + NAMESPACE_UID, + "55555555-5555-4555-8555-555555555555", + "api-r1", + "https://kubernetes.test:6443", + "b".repeat(64)), + publicJwks, + false, + false)) + .when(source) + .currentPublicRead(); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + for (String mismatch : List.of("api-origin", "binding-revision")) { + var expected = sourceIdentity(); + var changed = + new SourceIdentity( + expected.environmentId(), + expected.clusterId(), + expected.clusterIncarnationUid(), + expected.namespace(), + expected.namespaceUid(), + expected.configMapUid(), + mismatch.equals("binding-revision") ? "api-r2" : expected.bindingRevision(), + mismatch.equals("api-origin") + ? "https://different-api.test:6443" + : expected.apiServerOrigin(), + expected.servingCaSha256()); + doReturn(new ReadResult(changed, publicJwks, false, false)) + .when(source) + .currentPublicRead(); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + } + doAnswer( + ignored -> { + protectedBinding.trust.set(Optional.empty()); + return snapshot; + }) + .when(source) + .currentPublicRead(); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + clearInvocations(source); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + verifyNoInteractions(source); + } + }); } @ParameterizedTest @@ -402,19 +390,18 @@ void publicReadReceiverIsAbsentWithoutItsSeparateExplicitOptIn(String resource) var source = mock(AccountJwtJwksTrustedSource.class); int port = unusedLoopbackPort(); runner(resource, port, source, new ControlledProtectedBinding()) - .run( - context -> { - assertThat(context) - .hasNotFailed() - .doesNotHaveBean(AccountPublicJwksReadGrpcService.class); - assertThat(context.getBean(GrpcServerLifecycle.class).isRunning()).isTrue(); - try (var client = new Client(port, gameSession)) { - assertCode( - Status.Code.UNIMPLEMENTED, - () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); - } - verifyNoInteractions(source); - }); + .run(context -> { + assertThat(context) + .hasNotFailed() + .doesNotHaveBean(AccountPublicJwksReadGrpcService.class); + assertThat(context.getBean(GrpcServerLifecycle.class).isRunning()).isTrue(); + try (var client = new Client(port, gameSession)) { + assertCode( + Status.Code.UNIMPLEMENTED, + () -> client.stub().getCurrentPublicJwks(AccountPublicJwksReadCodec.request())); + } + verifyNoInteractions(source); + }); } private static ApplicationContextRunner runner( @@ -430,11 +417,9 @@ private static ApplicationContextRunner runner( "actual-account-" + resource, new FileSystemResource(Path.of("src/main/resources").resolve(resource))); return new ApplicationContextRunner() - .withInitializer( - context -> - yaml.forEach( - propertySource -> - context.getEnvironment().getPropertySources().addLast(propertySource))) + .withInitializer(context -> + yaml.forEach(propertySource -> + context.getEnvironment().getPropertySources().addLast(propertySource))) .withConfiguration( AutoConfigurations.of( ConfigurationPropertiesAutoConfiguration.class, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksWriterWindowPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksWriterWindowPostgresIntegrationTest.java index dab77470c5..86e19330e2 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksWriterWindowPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicJwksWriterWindowPostgresIntegrationTest.java @@ -151,13 +151,11 @@ void initialPrepublicationCutsRemainUnavailableUntilExactFailedReceiptReconcilia harness.assertLiveMatchesCurrentPrepublicationIntent(); assertThat(harness.count("account_jwt_jwks_publication_receipts")).isZero(); harness.assertUnavailableRead(); - harness.manager.beforeCommit.set( - () -> - harness.observeBlockedPublicRead( - harness::assertUnavailableRead, - () -> - assertThat(harness.count("account_jwt_jwks_publication_receipts")) - .isZero())); + harness.manager.beforeCommit.set(() -> + harness.observeBlockedPublicRead( + harness::assertUnavailableRead, + () -> + assertThat(harness.count("account_jwt_jwks_publication_receipts")).isZero())); }; try { assertThatThrownBy(harness.prepublication::prepublishCurrentGeneration) @@ -193,10 +191,9 @@ void committedSignerRefusesNextPublicationWithoutDurableRotationRequestAndPreser var cachedKey = cache.keyFor(committedKid); var committed = harness - .tx( - () -> - harness.desired.readCurrentCommittedSigner( - harness.binding.accountBinding(), harness.trust, API_DIGEST, API_REVISION)) + .tx(() -> + harness.desired.readCurrentCommittedSigner( + harness.binding.accountBinding(), harness.trust, API_DIGEST, API_REVISION)) .orElseThrow(); var state = harness @@ -212,12 +209,10 @@ void committedSignerRefusesNextPublicationWithoutDurableRotationRequestAndPreser // A subsequent rotation-request entrypoint and its prepublication/pruning lifecycle are not // implemented or physically qualified. Neither a retained signer nor a test may invent it. - assertThatThrownBy( - () -> - harness.tx( - () -> - harness.desired.ensureCurrentGenerationRequest( - harness.binding.accountBinding(), harness.trust))) + assertThatThrownBy(() -> + harness.tx(() -> + harness.desired.ensureCurrentGenerationRequest( + harness.binding.accountBinding(), harness.trust))) .isExactlyInstanceOf( AccountJwtSignerDesiredStateRepository.MissingGenerationOperationException.class) .hasMessage("Account has no durable rotation request for its committed signer"); @@ -236,13 +231,9 @@ void committedSignerRefusesNextPublicationWithoutDurableRotationRequestAndPreser .isEqualTo(state); assertThat( harness - .tx( - () -> - harness.desired.readCurrentCommittedSigner( - harness.binding.accountBinding(), - harness.trust, - API_DIGEST, - API_REVISION)) + .tx(() -> + harness.desired.readCurrentCommittedSigner( + harness.binding.accountBinding(), harness.trust, API_DIGEST, API_REVISION)) .orElseThrow()) .isEqualTo(committed); assertThat(harness.transport.patches).isEqualTo(patchCount); @@ -286,19 +277,18 @@ void activeCasWithoutReceiptDeniesCachedKeysAcrossOutageAndRecoversAfterExactOwn harness.assertPreparedDeny(); assertThatThrownBy(transitionCache::refresh) .isInstanceOf(SourcePreparedDenyException.class); - harness.manager.beforeCommit.set( - () -> - harness.observeBlockedPublicRead( - harness::assertPreparedDeny, - () -> - assertThat( - harness - .dsl - .resultQuery( - "SELECT count(*) FROM account_jwt_signer_promotion_operations " - + "WHERE active_jwks_receipt_digest IS NOT NULL") - .fetchOne(0, Long.class)) - .isZero())); + harness.manager.beforeCommit.set(() -> + harness.observeBlockedPublicRead( + harness::assertPreparedDeny, + () -> + assertThat( + harness + .dsl + .resultQuery( + "SELECT count(*) FROM account_jwt_signer_promotion_operations " + + "WHERE active_jwks_receipt_digest IS NOT NULL") + .fetchOne(0, Long.class)) + .isZero())); }; try { assertThatThrownBy(harness::reconcilePromotion) @@ -329,10 +319,9 @@ void activeCasWithoutReceiptDeniesCachedKeysAcrossOutageAndRecoversAfterExactOwn () -> { var promotion = harness - .tx( - () -> - harness.desired.readPreparedGenerationForRecovery( - harness.binding.accountBinding(), harness.trust)) + .tx(() -> + harness.desired.readPreparedGenerationForRecovery( + harness.binding.accountBinding(), harness.trust)) .promotion(); if (promotion.activeJwksReceiptDigest().isPresent()) { exactReceiptPreparedReads.incrementAndGet(); @@ -347,10 +336,9 @@ void activeCasWithoutReceiptDeniesCachedKeysAcrossOutageAndRecoversAfterExactOwn assertThat(harness.transport.patches).isEqualTo(writtenPatches); var committed = harness - .tx( - () -> - harness.desired.readCurrentCommittedSigner( - harness.binding.accountBinding(), harness.trust, API_DIGEST, API_REVISION)) + .tx(() -> + harness.desired.readCurrentCommittedSigner( + harness.binding.accountBinding(), harness.trust, API_DIGEST, API_REVISION)) .orElseThrow(); assertThat(committed.promotion().status()).isEqualTo("COMMITTED"); assertThat(committed.publicReceipt().observedResourceVersion()) @@ -369,13 +357,9 @@ void activeCasWithoutReceiptDeniesCachedKeysAcrossOutageAndRecoversAfterExactOwn assertThat(harness.transport.patches).isEqualTo(writtenPatches); assertThat( harness - .tx( - () -> - harness.desired.readCurrentCommittedSigner( - harness.binding.accountBinding(), - harness.trust, - API_DIGEST, - API_REVISION)) + .tx(() -> + harness.desired.readCurrentCommittedSigner( + harness.binding.accountBinding(), harness.trust, API_DIGEST, API_REVISION)) .orElseThrow()) .isEqualTo(committed); @@ -410,12 +394,10 @@ void durableReceiptCommitAcknowledgementLossRetainsBothWriterImagesAcrossExactRe harness.transport.clearHooks(); var durablePublication = harness - .independent( - () -> - harness.tx( - () -> - harness.publication.readCurrentPublication( - harness.binding.accountBinding(), harness.trust))) + .independent(() -> + harness.tx(() -> + harness.publication.readCurrentPublication( + harness.binding.accountBinding(), harness.trust))) .orElseThrow(); var durableReceipt = durablePublication.receipt().orElseThrow(); assertThat(durableReceipt.observedResourceVersion()).isEqualTo(harness.transport.version); @@ -431,10 +413,9 @@ void durableReceiptCommitAcknowledgementLossRetainsBothWriterImagesAcrossExactRe assertThat(harness.transport.patches).isEqualTo(prepublicationPatches); assertThat( harness - .tx( - () -> - harness.publication.readCurrentPublication( - harness.binding.accountBinding(), harness.trust)) + .tx(() -> + harness.publication.readCurrentPublication( + harness.binding.accountBinding(), harness.trust)) .orElseThrow()) .isEqualTo(durablePublication); harness.mountAndObserve(); @@ -446,12 +427,10 @@ void durableReceiptCommitAcknowledgementLossRetainsBothWriterImagesAcrossExactRe harness.transport.clearHooks(); var durableActive = harness - .independent( - () -> - harness.tx( - () -> - harness.desired.readPreparedGenerationForRecovery( - harness.binding.accountBinding(), harness.trust))) + .independent(() -> + harness.tx(() -> + harness.desired.readPreparedGenerationForRecovery( + harness.binding.accountBinding(), harness.trust))) .promotion(); assertThat(durableActive.status()).isEqualTo("PREPARED"); assertThat(durableActive.activeJwksReceiptDigest()).isPresent(); @@ -472,15 +451,10 @@ void durableReceiptCommitAcknowledgementLossRetainsBothWriterImagesAcrossExactRe assertThat(harness.transport.patches).isEqualTo(activePatches); var committed = harness - .independent( - () -> - harness.tx( - () -> - harness.desired.readCurrentCommittedSigner( - harness.binding.accountBinding(), - harness.trust, - API_DIGEST, - API_REVISION))) + .independent(() -> + harness.tx(() -> + harness.desired.readCurrentCommittedSigner( + harness.binding.accountBinding(), harness.trust, API_DIGEST, API_REVISION))) .orElseThrow(); assertThat(committed.publicReceipt().receiptDigest()) .isEqualTo(durableActive.activeJwksReceiptDigest().orElseThrow()); @@ -528,10 +502,9 @@ void bothWritersReconcileLostCasRepliesFromExactLiveReadbackWithoutASecondMutati assertThat(harness.transport.patches).isEqualTo(2); var committed = harness - .tx( - () -> - harness.desired.readCurrentCommittedSigner( - harness.binding.accountBinding(), harness.trust, API_DIGEST, API_REVISION)) + .tx(() -> + harness.desired.readCurrentCommittedSigner( + harness.binding.accountBinding(), harness.trust, API_DIGEST, API_REVISION)) .orElseThrow(); assertThat(committed.publicReceipt().observedResourceVersion()) .isEqualTo(harness.transport.version); @@ -785,11 +758,10 @@ private Harness(DataSource dataSource, String schema, Path directory) throws Exc Path.of("jwt-generation.json"))); var inventory = mock(AccountJwtValidatorInventorySource.class); when(inventory.observe(any(AccountJwtValidatorInventorySource.ObservationContext.class))) - .thenAnswer( - invocation -> { - afterInventory.run(); - return readinessFixture.currentInventory(dsl, invocation.getArgument(0)); - }); + .thenAnswer(invocation -> { + afterInventory.run(); + return readinessFixture.currentInventory(dsl, invocation.getArgument(0)); + }); var beans = new DefaultListableBeanFactory(); beans.registerSingleton("controlledInventory", inventory); coordinator = @@ -815,29 +787,27 @@ private void generate() throws Exception { String prior = result == null ? "12" : "14"; String next = result == null ? "13" : "15"; var observed = - tx( - () -> - desired.recordSecretObservation( - binding.accountBinding(), - trust, - request.operationId(), - request.operationDigest(), - SECRET_UID, - prior)); + tx(() -> + desired.recordSecretObservation( + binding.accountBinding(), + trust, + request.operationId(), + request.operationDigest(), + SECRET_UID, + prior)); keyPair = generateRsa3072(); PublicJwk jwk = publicJwk(request.targetKid(), (RSAPublicKey) keyPair.getPublic()); result = - tx( - () -> - desired.recordGenerationResult( - binding.accountBinding(), - trust, - request.operationId(), - observed.generationRequestDigest(), - SECRET_UID, - prior, - next, - jwk.json())); + tx(() -> + desired.recordGenerationResult( + binding.accountBinding(), + trust, + request.operationId(), + observed.generationRequestDigest(), + SECRET_UID, + prior, + next, + jwk.json())); Files.writeString( privateMount.resolve("pending.key"), privateBundleJson(request, result, keyPair)); readinessFixture = @@ -874,10 +844,9 @@ private void prepareAndRecordPrivatePromotion() throws Exception { Optional.empty(), List.of("current")); privateReceipt = - tx( - () -> - desired.recordPrivatePromotionResult( - binding.accountBinding(), trust, privateObservation)); + tx(() -> + desired.recordPrivatePromotionResult( + binding.accountBinding(), trust, privateObservation)); Files.writeString( privateMount.resolve("current.key"), privateBundleJson(request, result, keyPair)); } @@ -903,10 +872,9 @@ private ReadResult read() { try { return Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .call( - () -> - AccountPublicJwksReadCodec.result( - publicRead.read(AccountPublicJwksReadCodec.request()))); + .call(() -> + AccountPublicJwksReadCodec.result( + publicRead.read(AccountPublicJwksReadCodec.request()))); } catch (RuntimeException failure) { throw failure; } catch (Exception failure) { @@ -1009,21 +977,17 @@ private void assertChangedPrivateReceiptReplayRefused() { privateObservation.current(), privateObservation.previous(), privateObservation.resultingSlots()); - assertThatThrownBy( - () -> - tx( - () -> - desired.recordPrivatePromotionResult( - binding.accountBinding(), trust, changed))) + assertThatThrownBy(() -> + tx(() -> + desired.recordPrivatePromotionResult(binding.accountBinding(), trust, changed))) .isExactlyInstanceOf( AccountJwtSignerDesiredStateRepository.IdempotencyConflictException.class) .hasMessage("Private promotion readback changed for the same Account operation"); assertThat(ownerHistoryImages()).isEqualTo(retained); assertThat( - tx( - () -> - desired.recordPrivatePromotionResult( - binding.accountBinding(), trust, privateObservation))) + tx(() -> + desired.recordPrivatePromotionResult( + binding.accountBinding(), trust, privateObservation))) .isEqualTo(privateReceipt); assertPreparedDeny(); } @@ -1084,18 +1048,16 @@ private void observeBlockedPublicRead( AtomicInteger readerPid = new AtomicInteger(); CountDownLatch readerBegan = new CountDownLatch(1); CompletableFuture reader = - CompletableFuture.runAsync( - () -> { - manager.readerBackend.set( - pid -> { - if (readerPid.compareAndSet(0, pid)) readerBegan.countDown(); - }); - try { - assertAfterRollback.run(); - } finally { - manager.readerBackend.remove(); - } - }); + CompletableFuture.runAsync(() -> { + manager.readerBackend.set(pid -> { + if (readerPid.compareAndSet(0, pid)) readerBegan.countDown(); + }); + try { + assertAfterRollback.run(); + } finally { + manager.readerBackend.remove(); + } + }); assertThat(blockedPublicRead.compareAndSet(null, reader)).isTrue(); try { assertThat(readerBegan.await(5, TimeUnit.SECONDS)).isTrue(); @@ -1106,23 +1068,20 @@ private void observeBlockedPublicRead( Awaitility.await() .alias("exact public reader waits on actual receipt writer") .atMost(Duration.ofSeconds(5)) - .until( - () -> - independent( - () -> - Boolean.TRUE.equals( - dsl.resultQuery( - "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE pid = ? " - + "AND wait_event_type = 'Lock' AND ? = ANY(pg_blocking_pids(pid)))", - readerPid.get(), - writerPid) - .fetchOne(0, Boolean.class)))); + .until(() -> + independent(() -> + Boolean.TRUE.equals( + dsl.resultQuery( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE pid = ? " + + "AND wait_event_type = 'Lock' AND ? = ANY(pg_blocking_pids(pid)))", + readerPid.get(), + writerPid) + .fetchOne(0, Boolean.class)))); assertThat(reader.isDone()).isFalse(); - independent( - () -> { - assertCommittedReceiptAbsent.run(); - return null; - }); + independent(() -> { + assertCommittedReceiptAbsent.run(); + return null; + }); } private void awaitBlockedPublicRead() { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java index 1acb484eb8..df601c71ca 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java @@ -548,10 +548,8 @@ public void readPublicationTerminal( () -> asGameDesign(() -> wrongGdComposition.settle(operation.canonicalBytes()))) .isInstanceOf(RuntimeException.class); assertPending(sources, repository, order); - assertThatThrownBy( - () -> - asGameDesign( - () -> wrongWorldComposition.settle(operation.canonicalBytes()))) + assertThatThrownBy(() -> + asGameDesign(() -> wrongWorldComposition.settle(operation.canonicalBytes()))) .isInstanceOf(RuntimeException.class); assertPending(sources, repository, order); } @@ -623,13 +621,12 @@ public void readPublicationTerminal( assertCode( Status.Code.FAILED_PRECONDITION, () -> - asGameDesign( - () -> { - heldReader.requireHeld( - AccountPublicationAuthorizationReadEvidence.Request.create( - NAMESPACE, order)); - return null; - })); + asGameDesign(() -> { + heldReader.requireHeld( + AccountPublicationAuthorizationReadEvidence.Request.create( + NAMESPACE, order)); + return null; + })); assertThat(sources.tx(sources::changeRoleToAdmin).getRole()).isEqualTo("admin"); corruptReadback.set(true); assertThatThrownBy( @@ -660,11 +657,10 @@ private static void assertPending( sources.dsl.fetchCount( org.jooq.impl.DSL.table("account_selected_publication_settlements"))) .isZero(); - sources.tx( - () -> { - repository.readHeld(order); - return null; - }); + sources.tx(() -> { + repository.readHeld(order); + return null; + }); assertThatThrownBy(() -> sources.tx(sources::changeRoleToAdmin)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("selected-publication"); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java index cf08297130..9fa96cf899 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java @@ -106,23 +106,20 @@ void exactTwoOwnerSettlementRollsBackAtomicallyThenReplaysAfterLostAcknowledgeme outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED ? "PUBLISHED" : "ABORTED"; - assertThatThrownBy( - () -> - f.tx( - () -> { - repository.settle(operation, terminal, phase, terminal.canonicalBytes()); - throw new IllegalStateException("rollback before owner commit"); - })) + assertThatThrownBy(() -> + f.tx(() -> { + repository.settle(operation, terminal, phase, terminal.canonicalBytes()); + throw new IllegalStateException("rollback before owner commit"); + })) .isInstanceOf(IllegalStateException.class); assertThat( f.dsl.fetchCount( org.jooq.impl.DSL.table("account_selected_publication_settlements"))) .isZero(); - f.tx( - () -> { - repository.readHeld(order); - return null; - }); + f.tx(() -> { + repository.readHeld(order); + return null; + }); assertThatThrownBy(() -> f.tx(f::changeRoleToAdmin)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("selected-publication"); @@ -149,30 +146,25 @@ void exactTwoOwnerSettlementRollsBackAtomicallyThenReplaysAfterLostAcknowledgeme order.operationId()) .get("binding", byte[].class)) .isEqualTo(originalBinding); - assertThatThrownBy( - () -> - f.tx( - () -> { - repository.readHeld(order); - return null; - })) + assertThatThrownBy(() -> + f.tx(() -> { + repository.readHeld(order); + return null; + })) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("already settled"); var readOwner = new AccountPublicationAuthorizationReadService(repository, f.manager, "test"); - assertThatThrownBy( - () -> - asGameDesign( - () -> - readOwner.requireHeld( - net.firedevops.firemud.common.publication - .AccountPublicationAuthorizationReadEvidence.Request.create( - "test", order)))) + assertThatThrownBy(() -> + asGameDesign(() -> + readOwner.requireHeld( + net.firedevops.firemud.common.publication + .AccountPublicationAuthorizationReadEvidence.Request.create( + "test", order)))) .isInstanceOf(io.grpc.StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(((io.grpc.StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat(((io.grpc.StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); assertThat(f.tx(f::changeRoleToAdmin).getRole()).isEqualTo("admin"); // Even after the source changes, the original committed issuance and receipt replay. assertThat( @@ -236,43 +228,33 @@ void missingAmbiguousSubstitutedAndDisagreeingOwnersKeepOriginalSourcesHeld() th wrongOperation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION) .canonicalBytes()))) { - assertThatThrownBy( - () -> - f.tx( - () -> { - rejected.run(); - return null; - })) + assertThatThrownBy(() -> + f.tx(() -> { + rejected.run(); + return null; + })) .isInstanceOf(RuntimeException.class); } - f.tx( - () -> { - repository.readHeld(order); - return null; - }); + f.tx(() -> { + repository.readHeld(order); + return null; + }); assertThat( f.dsl.fetchCount(org.jooq.impl.DSL.table("account_selected_publication_settlements"))) .isZero(); - assertThatThrownBy( - () -> - f.tx( - () -> - f.dsl.execute( - "UPDATE accounts SET role = 'admin' WHERE id = ?", - f.account.getId()))) + assertThatThrownBy(() -> + f.tx(() -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()))) .isInstanceOf(org.jooq.exception.DataAccessException.class); byte[] receipt = - f.tx( - () -> - repository.settle( - operation, noPublication, "ABORTED", noPublication.canonicalBytes())); - assertThatThrownBy( - () -> - f.tx( - () -> - repository.settle( - operation, published, "PUBLISHED", published.canonicalBytes()))) + f.tx(() -> + repository.settle( + operation, noPublication, "ABORTED", noPublication.canonicalBytes())); + assertThatThrownBy(() -> + f.tx(() -> + repository.settle(operation, published, "PUBLISHED", published.canonicalBytes()))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Changed original"); assertThat( @@ -302,24 +284,19 @@ void settlingOneOrderLeavesEveryOtherOriginalSourceParticipationPending() throws var terminal = terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); f.tx(() -> repository.settle(operation, terminal, "ABORTED", terminal.canonicalBytes())); - f.tx( - () -> { - repository.readHeld(second); - return null; - }); - assertThatThrownBy( - () -> - f.tx( - () -> - f.dsl.execute( - "UPDATE accounts SET role = 'admin' WHERE id = ?", - f.account.getId()))) + f.tx(() -> { + repository.readHeld(second); + return null; + }); + assertThatThrownBy(() -> + f.tx(() -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()))) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("selected-publication"); var captured = - f.tx( - () -> - f.authority.capture(f.account.getAccountUuid(), f.tenant, issued.environment())); + f.tx(() -> + f.authority.capture(f.account.getAccountUuid(), f.tenant, issued.environment())); var change = new DraftAuthorizationFenceRepository.SourceChange( UUID.randomUUID(), captured.sources(), new byte[] {1}); @@ -338,25 +315,19 @@ static GameDesignPublicationTerminalEvidence terminal( var request = operation.world().request(); var participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new GameDesignPublicationTerminalEvidence.Participant( - owner, - Long.toString( - operation - .account() - .input() - .selection() - .target() - .gameDesignVersionRowId()), - null, - request.appliedCommitId(), - request.contentDigest(), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - "GAME_LOGIC".equals(owner) ? "sha256:" + "a".repeat(64) : null, - null, - null)) + .map(owner -> + new GameDesignPublicationTerminalEvidence.Participant( + owner, + Long.toString( + operation.account().input().selection().target().gameDesignVersionRowId()), + null, + request.appliedCommitId(), + request.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner) ? "sha256:" + "a".repeat(64) : null, + null, + null)) .toList(); var release = new GameDesignPublicationTerminalEvidence.ReleaseContent( @@ -591,10 +562,9 @@ void directMalformedOrSubstitutedReceiptRowsDoNotRemovePendingProtection() throw receipt }; assertThatThrownBy(() -> f.tx(() -> f.dsl.execute(insert, unsortedRegionSettlement))) - .satisfies( - failure -> - assertSqlFailure( - failure, "23514", "Unsupported or unordered region generator input")); + .satisfies(failure -> + assertSqlFailure( + failure, "23514", "Unsupported or unordered region generator input")); String unsortedSpawnInputs = "[" + inventorySpawnBindingInput( @@ -642,10 +612,8 @@ void directMalformedOrSubstitutedReceiptRowsDoNotRemovePendingProtection() throw receipt }; assertThatThrownBy(() -> f.tx(() -> f.dsl.execute(insert, unsortedSpawnSettlement))) - .satisfies( - failure -> - assertSqlFailure( - failure, "23514", "Unsupported or unordered scoped spawn input")); + .satisfies(failure -> + assertSqlFailure(failure, "23514", "Unsupported or unordered scoped spawn input")); List invalidOperations = List.of( rawOperation( @@ -674,38 +642,32 @@ void directMalformedOrSubstitutedReceiptRowsDoNotRemovePendingProtection() throw null), java.util.Arrays.copyOf(validOperation, validOperation.length + 1)); for (byte[] invalidOperation : invalidOperations) { - assertThatThrownBy( - () -> - f.tx( - () -> - f.dsl.execute( - insert, - order.operationId(), - order.fenceId(), - order.canonicalBytes(), - invalidOperation, - "NO_PUBLICATION", - terminal.canonicalBytes(), - "ABORTED", - terminal.canonicalBytes(), - receipt))) + assertThatThrownBy(() -> + f.tx(() -> + f.dsl.execute( + insert, + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + invalidOperation, + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt))) .satisfies(failure -> assertSqlState(failure, "23514")); } assertThat( f.dsl.fetchCount(org.jooq.impl.DSL.table("account_selected_publication_settlements"))) .isZero(); - f.tx( - () -> { - repository.readHeld(order); - return null; - }); - assertThatThrownBy( - () -> - f.tx( - () -> - f.dsl.execute( - "UPDATE accounts SET role = 'admin' WHERE id = ?", - f.account.getId()))) + f.tx(() -> { + repository.readHeld(order); + return null; + }); + assertThatThrownBy(() -> + f.tx(() -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()))) .isInstanceOf(org.jooq.exception.DataAccessException.class); } } @@ -725,32 +687,29 @@ void sourceWriterCannotPassUncommittedSettlementAndCanRetryAfterItsCommit() thro terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); var executor = java.util.concurrent.Executors.newSingleThreadExecutor(); try { - f.tx( - () -> { - repository.settle(operation, terminal, "ABORTED", terminal.canonicalBytes()); - int settlementPid = - f.dsl.fetchSingle("SELECT pg_backend_pid() AS pid").get("pid", Integer.class); - var writer = - executor.submit( - () -> - f.tx( - () -> { - int writerPid = - f.dsl - .fetchSingle("SELECT pg_backend_pid() AS pid") - .get("pid", Integer.class); - assertThat(writerPid).isNotEqualTo(settlementPid); - // The actual source trigger takes the same source locks NOWAIT. A - // pending - // transaction cannot release its protection to a different writer - // connection. - return f.changeRoleToAdmin(); - })); - assertThatThrownBy(() -> writer.get(10, java.util.concurrent.TimeUnit.SECONDS)) - .isInstanceOf(java.util.concurrent.ExecutionException.class) - .hasCauseInstanceOf(org.jooq.exception.DataAccessException.class); - return null; - }); + f.tx(() -> { + repository.settle(operation, terminal, "ABORTED", terminal.canonicalBytes()); + int settlementPid = + f.dsl.fetchSingle("SELECT pg_backend_pid() AS pid").get("pid", Integer.class); + var writer = + executor.submit(() -> + f.tx(() -> { + int writerPid = + f.dsl + .fetchSingle("SELECT pg_backend_pid() AS pid") + .get("pid", Integer.class); + assertThat(writerPid).isNotEqualTo(settlementPid); + // The actual source trigger takes the same source locks NOWAIT. A + // pending + // transaction cannot release its protection to a different writer + // connection. + return f.changeRoleToAdmin(); + })); + assertThatThrownBy(() -> writer.get(10, java.util.concurrent.TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .hasCauseInstanceOf(org.jooq.exception.DataAccessException.class); + return null; + }); assertThat(f.tx(f::changeRoleToAdmin).getRole()).isEqualTo("admin"); } finally { executor.shutdownNow(); @@ -806,27 +765,22 @@ void authenticatesPreFreezeDistinctOrderReplaysExactlyAndBlocksSourceWritersAndD new net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding( UUID.randomUUID(), original.fenceId(), original.input(), original.sources()); for (var rejected : List.of(mismatched, unknown)) { - assertThatThrownBy( - () -> - asGameDesign( - () -> - readOwner.requireHeld( - net.firedevops.firemud.common.publication - .AccountPublicationAuthorizationReadEvidence.Request.create( - "test", rejected)))) + assertThatThrownBy(() -> + asGameDesign(() -> + readOwner.requireHeld( + net.firedevops.firemud.common.publication + .AccountPublicationAuthorizationReadEvidence.Request.create( + "test", rejected)))) .isInstanceOf(io.grpc.StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(io.grpc.Status.fromThrowable(failure).getCode()) - .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); } - assertThatThrownBy( - () -> - f.tx( - () -> { - f.fences.requireDisclosurePreparation(original.sources()); - return null; - })) + assertThatThrownBy(() -> + f.tx(() -> { + f.fences.requireDisclosurePreparation(original.sources()); + return null; + })) .hasMessageContaining("selected-publication"); var change = new DraftAuthorizationFenceRepository.SourceChange( @@ -840,22 +794,17 @@ void authenticatesPreFreezeDistinctOrderReplaysExactlyAndBlocksSourceWritersAndD .canonicalBytes()) .isEqualTo(original.canonicalBytes()); asGameDesign(() -> readOwner.requireHeld(readRequest)); - assertThatThrownBy( - () -> - f.tx( - () -> - f.dsl.execute( - "UPDATE accounts SET role = 'admin' WHERE id = ?", - f.account.getId()))) + assertThatThrownBy(() -> + f.tx(() -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()))) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("selected-publication"); - assertThatThrownBy( - () -> - f.tx( - () -> - f.dsl.execute( - "UPDATE account_selected_publication_authorizations SET fence_id = ?", - UUID.randomUUID()))) + assertThatThrownBy(() -> + f.tx(() -> + f.dsl.execute( + "UPDATE account_selected_publication_authorizations SET fence_id = ?", + UUID.randomUUID()))) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThatThrownBy( () -> f.tx(() -> f.dsl.execute("DELETE FROM account_selected_publication_sources"))) @@ -863,26 +812,21 @@ void authenticatesPreFreezeDistinctOrderReplaysExactlyAndBlocksSourceWritersAndD var changed = selection(proof.selection().selectedCommit(), "changed notes"); assertThatThrownBy(() -> service.authorize(issued.compact(), changed, issued.environment())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - service.authorize( - issued.compact() + "changed", proof.selection(), issued.environment())) + assertThatThrownBy(() -> + service.authorize( + issued.compact() + "changed", proof.selection(), issued.environment())) .isInstanceOf(RuntimeException.class); // Original source/issuance identity is immutable even if a privileged SQL caller tries it. - assertThatThrownBy( - () -> - f.tx( - () -> - f.dsl.execute( - "UPDATE account_selected_publication_authorizations SET issuance_fence = issuance_fence + 1"))) + assertThatThrownBy(() -> + f.tx(() -> + f.dsl.execute( + "UPDATE account_selected_publication_authorizations SET issuance_fence = issuance_fence + 1"))) .isInstanceOf(org.jooq.exception.DataAccessException.class); - assertThatThrownBy( - () -> - f.tx( - () -> - f.dsl.execute( - "UPDATE account_selected_publication_sources SET source_evidence = ?", - new byte[] {9}))) + assertThatThrownBy(() -> + f.tx(() -> + f.dsl.execute( + "UPDATE account_selected_publication_sources SET source_evidence = ?", + new byte[] {9}))) .isInstanceOf(org.jooq.exception.DataAccessException.class); } } @@ -894,9 +838,8 @@ void earlierWaitingSourceChangeWinsAndDeniedAuthenticationCreatesNoOperation() t var f = issued.sources(); var proof = proof(f, issued.environment()); var source = - f.tx( - () -> - f.authority.capture(f.account.getAccountUuid(), f.tenant, issued.environment())); + f.tx(() -> + f.authority.capture(f.account.getAccountUuid(), f.tenant, issued.environment())); var change = new DraftAuthorizationFenceRepository.SourceChange( UUID.randomUUID(), source.sources(), new byte[] {2}); @@ -908,10 +851,8 @@ void earlierWaitingSourceChangeWinsAndDeniedAuthenticationCreatesNoOperation() t () -> service.authorize(issued.compact(), proof.selection(), issued.environment())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("source change is waiting"); - assertThatThrownBy( - () -> - service.authorize( - "unsigned-caller-claim", proof.selection(), issued.environment())) + assertThatThrownBy(() -> + service.authorize("unsigned-caller-claim", proof.selection(), issued.environment())) .isInstanceOf(RuntimeException.class); assertThat( f.dsl.fetchCount( @@ -935,63 +876,59 @@ void actualSourceWriterBlocksCreatorCaptureThenWinsBeforePublication() throws Ex var attempt = new java.util.concurrent.atomic.AtomicReference>(); try { - f.tx( - () -> { - int blockerPid = - java.util.Objects.requireNonNull( - f.dsl.fetchOne("SELECT pg_backend_pid() AS pid"), - "Expected PostgreSQL source-writer connection") - .get("pid", Integer.class); - var account = - java.util.Objects.requireNonNull( - accounts.findByIdForUpdate(f.account.getId()).orElseThrow(), - "Expected locked Account source before canonical role mutation"); - assertThat(account.getRole()).isNotEqualTo("player"); - attempt.set( - executor.submit( - () -> - service.authorize( - issued.compact(), proof.selection(), issued.environment()))); - long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10); - Integer blockedPid = null; - while (System.nanoTime() < deadline && blockedPid == null) { - if (attempt.get().isDone()) { - try { - attempt.get().get(); - } catch (java.util.concurrent.ExecutionException failure) { - throw new AssertionError( - "Creator authorization failed before the Account-row wait was observed", - failure.getCause()); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new AssertionError( - "Interrupted while diagnosing completed creator authorization", - interrupted); - } - throw new AssertionError( - "Creator authorization succeeded before the source writer committed"); - } - // Activity snapshots are otherwise frozen for this blocker transaction. - f.dsl.fetch("SELECT pg_stat_clear_snapshot()"); - var blocked = - f.dsl.fetchOne( - "SELECT pid FROM pg_stat_activity WHERE datname = current_database()" - + " AND ? = ANY(pg_blocking_pids(pid)) AND wait_event_type = 'Lock' LIMIT 1", - blockerPid); - if (blocked != null) blockedPid = blocked.get("pid", Integer.class); - else Thread.onSpinWait(); + f.tx(() -> { + int blockerPid = + java.util.Objects.requireNonNull( + f.dsl.fetchOne("SELECT pg_backend_pid() AS pid"), + "Expected PostgreSQL source-writer connection") + .get("pid", Integer.class); + var account = + java.util.Objects.requireNonNull( + accounts.findByIdForUpdate(f.account.getId()).orElseThrow(), + "Expected locked Account source before canonical role mutation"); + assertThat(account.getRole()).isNotEqualTo("player"); + attempt.set( + executor.submit(() -> + service.authorize(issued.compact(), proof.selection(), issued.environment()))); + long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10); + Integer blockedPid = null; + while (System.nanoTime() < deadline && blockedPid == null) { + if (attempt.get().isDone()) { + try { + attempt.get().get(); + } catch (java.util.concurrent.ExecutionException failure) { + throw new AssertionError( + "Creator authorization failed before the Account-row wait was observed", + failure.getCause()); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError( + "Interrupted while diagnosing completed creator authorization", interrupted); } - assertThat(blockedPid) - .as("Distinct creator connection physically waits on source-writer Account row") - .isNotNull(); - assertThat(blockedPid).isNotEqualTo(blockerPid); - assertThat(attempt.get().isDone()).isFalse(); - // Actual guarded source write, held until this transaction commits. The old signed - // credential cannot authorize a publication from the newly changed Account state. - account.setRole("player"); - assertThat(accounts.save(account).getRole()).isEqualTo("player"); - return null; - }); + throw new AssertionError( + "Creator authorization succeeded before the source writer committed"); + } + // Activity snapshots are otherwise frozen for this blocker transaction. + f.dsl.fetch("SELECT pg_stat_clear_snapshot()"); + var blocked = + f.dsl.fetchOne( + "SELECT pid FROM pg_stat_activity WHERE datname = current_database()" + + " AND ? = ANY(pg_blocking_pids(pid)) AND wait_event_type = 'Lock' LIMIT 1", + blockerPid); + if (blocked != null) blockedPid = blocked.get("pid", Integer.class); + else Thread.onSpinWait(); + } + assertThat(blockedPid) + .as("Distinct creator connection physically waits on source-writer Account row") + .isNotNull(); + assertThat(blockedPid).isNotEqualTo(blockerPid); + assertThat(attempt.get().isDone()).isFalse(); + // Actual guarded source write, held until this transaction commits. The old signed + // credential cannot authorize a publication from the newly changed Account state. + account.setRole("player"); + assertThat(accounts.save(account).getRole()).isEqualTo("player"); + return null; + }); assertThatThrownBy(() -> attempt.get().get(10, java.util.concurrent.TimeUnit.SECONDS)) .isInstanceOf(java.util.concurrent.ExecutionException.class) .hasCauseInstanceOf(RuntimeException.class); @@ -1202,13 +1139,12 @@ static Proof proof( "GENERATION_RULE", "WORLD_ENTITY_SPAWN_BINDING") .stream() - .map( - family -> - Map.of( - "family", - "WORLD_DESIGN_AGGREGATE_TYPE_" + family, - "count", - families.contains(family) ? 1 : 0)) + .map(family -> + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_" + family, + "count", + families.contains(family) ? 1 : 0)) .toList())); revisions.add( new DraftCommitBinding.RevisionPayload( @@ -1319,21 +1255,20 @@ static Proof proof( applied.put( "appliedEpochs", draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - u -> - Map.of( - "aggregateType", - u.aggregateType(), - "aggregateId", - u.aggregateId(), - "scopeType", - u.scopeType(), - "scopeId", - u.scopeId(), - "expectedEpoch", - "0", - "resultingEpoch", - "1")) + .map(u -> + Map.of( + "aggregateType", + u.aggregateType(), + "aggregateId", + u.aggregateId(), + "scopeType", + u.scopeType(), + "scopeId", + u.scopeId(), + "expectedEpoch", + "0", + "resultingEpoch", + "1")) .toList()); var worldRequest = new WorldPublishedStartLocationEvidence.Request( @@ -1352,15 +1287,14 @@ static Proof proof( "b".repeat(64), 3, draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - u -> - new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( - u.owner().name(), - u.aggregateType(), - u.aggregateId(), - u.scopeType(), - u.scopeId(), - u.expectedEpoch())) + .map(u -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + u.owner().name(), + u.aggregateType(), + u.aggregateId(), + u.scopeType(), + u.scopeId(), + u.expectedEpoch())) .toList()); return new Proof( selection, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java index 8731b20cf2..4fdb8ddc3b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPostgresIntegrationTest.java @@ -179,23 +179,21 @@ void missingCurrentPolicyFailsBeforeValidOtpIsConsumedOrEvidenceIsRetained() { @Test void currentPolicyResolutionReturnsExactSortedValuesFromBothCurrentPointers() { Context c = context(); - c.tx( - () -> { - c.dsl.execute( - "INSERT INTO account_recent_reauthentication_policy_values " - + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " - + "VALUES ('DEPLOYMENT', 2, 100, 10)"); - c.dsl.execute( - "UPDATE account_recent_reauthentication_policy_current SET policy_version = 2 " - + "WHERE policy_scope = 'DEPLOYMENT'"); - return null; - }); + c.tx(() -> { + c.dsl.execute( + "INSERT INTO account_recent_reauthentication_policy_values " + + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " + + "VALUES ('DEPLOYMENT', 2, 100, 10)"); + c.dsl.execute( + "UPDATE account_recent_reauthentication_policy_current SET policy_version = 2 " + + "WHERE policy_scope = 'DEPLOYMENT'"); + return null; + }); var resolved = - c.tx( - () -> - new AccountRecentReauthenticationPolicyRepository(c.dsl) - .resolveCurrentSourcesForGameCreation()); + c.tx(() -> + new AccountRecentReauthenticationPolicyRepository(c.dsl) + .resolveCurrentSourcesForGameCreation()); var effective = resolved.effectivePolicy(); assertThat(effective.platformVersion()).isEqualTo(1L); assertThat(effective.deploymentVersion()).isEqualTo(2L); @@ -623,51 +621,44 @@ void originalTenantCreationIntentRejectsSqlMutationDeletionTruncationAndDigestCo c.request(account, reauthenticationRequestId, creationOperationId, PASSWORD)); var repository = new AccountTenantCreationIntentRepository(c.dsl, c.evidenceRepository); UUID intentRequestId = UUID.randomUUID(); - c.tx( - () -> - repository.claim( - intentRequest( - account, - intentRequestId, - creationOperationId, - UUID.randomUUID(), - evidence.evidenceId(), - UUID.randomUUID(), - UUID.randomUUID(), - 1))); + c.tx(() -> + repository.claim( + intentRequest( + account, + intentRequestId, + creationOperationId, + UUID.randomUUID(), + evidence.evidenceId(), + UUID.randomUUID(), + UUID.randomUUID(), + 1))); Record original = Objects.requireNonNull( c.dsl.fetchOne( "SELECT * FROM account_tenant_creation_original_intents WHERE request_id = ?", intentRequestId)); - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - "UPDATE account_tenant_creation_original_intents SET name = ? " - + "WHERE request_id = ?", - "Changed game name", - intentRequestId))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + "UPDATE account_tenant_creation_original_intents SET name = ? " + + "WHERE request_id = ?", + "Changed game name", + intentRequestId))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - "UPDATE account_tenant_creation_original_intents SET request_digest = ? " - + "WHERE request_id = ?", - "sha256:" + "0".repeat(64), - intentRequestId))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + "UPDATE account_tenant_creation_original_intents SET request_digest = ? " + + "WHERE request_id = ?", + "sha256:" + "0".repeat(64), + intentRequestId))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - "DELETE FROM account_tenant_creation_original_intents WHERE request_id = ?", - intentRequestId))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + "DELETE FROM account_tenant_creation_original_intents WHERE request_id = ?", + intentRequestId))) .isInstanceOf(DataAccessException.class); assertThatThrownBy( () -> c.tx(() -> c.dsl.execute("TRUNCATE account_tenant_creation_original_intents"))) @@ -706,23 +697,19 @@ void concurrentExactTenantCreationIntentClaimsReturnOneOriginalRow() throws Exce var executor = Executors.newFixedThreadPool(2); try { var first = - executor.submit( - () -> - c.tx( - () -> { - ready.countDown(); - awaitLatch(start); - return repository.claim(request); - })); + executor.submit(() -> + c.tx(() -> { + ready.countDown(); + awaitLatch(start); + return repository.claim(request); + })); var second = - executor.submit( - () -> - c.tx( - () -> { - ready.countDown(); - awaitLatch(start); - return repository.claim(request); - })); + executor.submit(() -> + c.tx(() -> { + ready.countDown(); + awaitLatch(start); + return repository.claim(request); + })); assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); start.countDown(); var firstResult = first.get(10, TimeUnit.SECONDS); @@ -750,44 +737,39 @@ void currentPolicyPointerWriterUsesOnlyItsExactSourceLock() throws Exception { var executor = Executors.newSingleThreadExecutor(); try { var sourceLockHolder = - executor.submit( - () -> - c.tx( - () -> { - c.dsl.fetchOne( - "SELECT account_control_ui_hold_required_sources(ARRAY[?]::TEXT[])", - platformKey); - sourceLockHeld.countDown(); - awaitLatch(releaseSourceLock); - return null; - })); + executor.submit(() -> + c.tx(() -> { + c.dsl.fetchOne( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::TEXT[])", + platformKey); + sourceLockHeld.countDown(); + awaitLatch(releaseSourceLock); + return null; + })); assertThat(sourceLockHeld.await(5, TimeUnit.SECONDS)).isTrue(); - c.tx( - () -> { - c.dsl.execute( - "INSERT INTO account_recent_reauthentication_policy_values " - + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " - + "VALUES ('DEPLOYMENT', 2, 100, 10)"); - c.dsl.execute( - "UPDATE account_recent_reauthentication_policy_current SET policy_version = 2 " - + "WHERE policy_scope = 'DEPLOYMENT'"); - return null; - }); - - assertThatThrownBy( - () -> - c.tx( - () -> { - c.dsl.execute( - "INSERT INTO account_recent_reauthentication_policy_values " - + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " - + "VALUES ('PLATFORM', 2, 240, 20)"); - c.dsl.execute( - "UPDATE account_recent_reauthentication_policy_current " - + "SET policy_version = 2 WHERE policy_scope = 'PLATFORM'"); - return null; - })) + c.tx(() -> { + c.dsl.execute( + "INSERT INTO account_recent_reauthentication_policy_values " + + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " + + "VALUES ('DEPLOYMENT', 2, 100, 10)"); + c.dsl.execute( + "UPDATE account_recent_reauthentication_policy_current SET policy_version = 2 " + + "WHERE policy_scope = 'DEPLOYMENT'"); + return null; + }); + + assertThatThrownBy(() -> + c.tx(() -> { + c.dsl.execute( + "INSERT INTO account_recent_reauthentication_policy_values " + + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " + + "VALUES ('PLATFORM', 2, 240, 20)"); + c.dsl.execute( + "UPDATE account_recent_reauthentication_policy_current " + + "SET policy_version = 2 WHERE policy_scope = 'PLATFORM'"); + return null; + })) .isInstanceOf(DataAccessException.class); assertThat( Objects.requireNonNull( @@ -800,17 +782,16 @@ void currentPolicyPointerWriterUsesOnlyItsExactSourceLock() throws Exception { releaseSourceLock.countDown(); sourceLockHolder.get(10, TimeUnit.SECONDS); - c.tx( - () -> { - c.dsl.execute( - "INSERT INTO account_recent_reauthentication_policy_values " - + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " - + "VALUES ('PLATFORM', 2, 240, 20)"); - c.dsl.execute( - "UPDATE account_recent_reauthentication_policy_current SET policy_version = 2 " - + "WHERE policy_scope = 'PLATFORM'"); - return null; - }); + c.tx(() -> { + c.dsl.execute( + "INSERT INTO account_recent_reauthentication_policy_values " + + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " + + "VALUES ('PLATFORM', 2, 240, 20)"); + c.dsl.execute( + "UPDATE account_recent_reauthentication_policy_current SET policy_version = 2 " + + "WHERE policy_scope = 'PLATFORM'"); + return null; + }); assertThat( c.count( "SELECT count(*) FROM account_recent_reauthentication_policy_current " @@ -931,21 +912,18 @@ void knownPublicIdsCannotRecoverEvidenceWithWrongEmailOrSecret() { UUID requestId = UUID.randomUUID(), operationId = UUID.randomUUID(); var original = c.service.reauthenticate(c.request(account, requestId, operationId, PASSWORD)); Record retained = c.evidenceRow(original.evidenceId()); - assertThatThrownBy( - () -> - c.service.reauthenticate( - c.request(account, requestId, operationId, "wrong-secret"))) + assertThatThrownBy(() -> + c.service.reauthenticate(c.request(account, requestId, operationId, "wrong-secret"))) .isInstanceOf(AuthenticationException.class); - assertThatThrownBy( - () -> - c.service.reauthenticate( - new AccountRecentReauthenticationService.Request( - requestId, - account.getAccountUuid(), - AccountRecentReauthenticationPolicy.PURPOSE, - operationId, - "different@example.test", - PASSWORD))) + assertThatThrownBy(() -> + c.service.reauthenticate( + new AccountRecentReauthenticationService.Request( + requestId, + account.getAccountUuid(), + AccountRecentReauthenticationPolicy.PURPOSE, + operationId, + "different@example.test", + PASSWORD))) .isInstanceOf(AuthenticationException.class); var exact = c.service.reauthenticate( @@ -1030,15 +1008,12 @@ void concurrentCredentialGuessesSerializeAndCommitOnlyFiveFailures() throws Exce try { for (int i = 0; i < 12; i++) { attempts.add( - executor.submit( - () -> { - awaitLatch(start); - assertThatThrownBy( - () -> - c.service.reauthenticate( - c.request(account, requestId, operationId, "wrong"))) - .isInstanceOf(AuthenticationException.class); - })); + executor.submit(() -> { + awaitLatch(start); + assertThatThrownBy(() -> + c.service.reauthenticate(c.request(account, requestId, operationId, "wrong"))) + .isInstanceOf(AuthenticationException.class); + })); } start.countDown(); for (var attempt : attempts) attempt.get(10, TimeUnit.SECONDS); @@ -1066,34 +1041,44 @@ void replayFailureHistoryRejectsResetGapsTupleSubstitutionAndExcessAndSupportsRo "INSERT INTO account_recent_reauthentication_replay_failures" + " (evidence_id, request_id, account_uuid, purpose, creation_operation_id, failure_number)" + " VALUES (?, ?, ?, ?, ?, ?)"; - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - insert, - original.evidenceId(), - original.requestId(), - original.accountId(), - original.purpose(), - original.creationOperationId(), - 2))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + insert, + original.evidenceId(), + original.requestId(), + original.accountId(), + original.purpose(), + original.creationOperationId(), + 2))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - insert, - original.evidenceId(), - UUID.randomUUID(), - original.accountId(), - original.purpose(), - original.creationOperationId(), - 1))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + insert, + original.evidenceId(), + UUID.randomUUID(), + original.accountId(), + original.purpose(), + original.creationOperationId(), + 1))) .isInstanceOf(DataAccessException.class); - c.transaction.executeWithoutResult( - status -> { + c.transaction.executeWithoutResult(status -> { + c.dsl.execute( + insert, + original.evidenceId(), + original.requestId(), + original.accountId(), + original.purpose(), + original.creationOperationId(), + 1); + status.setRollbackOnly(); + }); + assertThat(c.count("SELECT count(*) FROM account_recent_reauthentication_replay_failures")) + .isZero(); + for (int failure = 1; failure <= 5; failure++) { + int number = failure; + c.tx(() -> c.dsl.execute( insert, original.evidenceId(), @@ -1101,23 +1086,7 @@ void replayFailureHistoryRejectsResetGapsTupleSubstitutionAndExcessAndSupportsRo original.accountId(), original.purpose(), original.creationOperationId(), - 1); - status.setRollbackOnly(); - }); - assertThat(c.count("SELECT count(*) FROM account_recent_reauthentication_replay_failures")) - .isZero(); - for (int failure = 1; failure <= 5; failure++) { - int number = failure; - c.tx( - () -> - c.dsl.execute( - insert, - original.evidenceId(), - original.requestId(), - original.accountId(), - original.purpose(), - original.creationOperationId(), - number)); + number)); } for (String mutation : java.util.List.of( @@ -1127,18 +1096,16 @@ void replayFailureHistoryRejectsResetGapsTupleSubstitutionAndExcessAndSupportsRo assertThatThrownBy(() -> c.tx(() -> c.dsl.execute(mutation))) .isInstanceOf(DataAccessException.class); } - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - insert, - original.evidenceId(), - original.requestId(), - original.accountId(), - original.purpose(), - original.creationOperationId(), - 6))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + insert, + original.evidenceId(), + original.requestId(), + original.accountId(), + original.purpose(), + original.creationOperationId(), + 6))) .isInstanceOf(DataAccessException.class); assertThat(c.count("SELECT count(*) FROM account_recent_reauthentication_replay_failures")) .isEqualTo(5L); @@ -1193,19 +1160,17 @@ void migrationPreservesHistoricalEvidenceWithoutGrantingReplayOrAllowingBackfill assertThatThrownBy( () -> c.service.reauthenticate(c.request(account, requestId, operationId, PASSWORD))) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - "INSERT INTO account_recent_reauthentication_replay_credentials" - + " (evidence_id, request_id, account_uuid, purpose, creation_operation_id, key_id, credential_mac)" - + " VALUES (?, ?, ?, 'SELF_SERVICE_GAME_CREATION', ?, 'mac1', ?)", - evidenceId, - requestId, - account.getAccountUuid(), - operationId, - "a".repeat(64)))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + "INSERT INTO account_recent_reauthentication_replay_credentials" + + " (evidence_id, request_id, account_uuid, purpose, creation_operation_id, key_id, credential_mac)" + + " VALUES (?, ?, ?, 'SELF_SERVICE_GAME_CREATION', ?, 'mac1', ?)", + evidenceId, + requestId, + account.getAccountUuid(), + operationId, + "a".repeat(64)))) .isInstanceOf(DataAccessException.class); assertThat(c.evidenceRow(evidenceId)).isEqualTo(original); assertThat(c.count("SELECT count(*) FROM account_recent_reauthentication_evidence")) @@ -1220,20 +1185,19 @@ void forwardBudgetMigrationPreservesPreviouslyCommittedProofAndStartsWithNoFailu Account account = c.account("PASSWORD"); UUID requestId = UUID.randomUUID(), operationId = UUID.randomUUID(); UUID evidenceId = - c.tx( - () -> { - UUID id = insertEvidenceWithoutMac(c, account, requestId, operationId); - c.dsl.execute( - "INSERT INTO account_recent_reauthentication_replay_credentials" - + " (evidence_id, request_id, account_uuid, purpose, creation_operation_id, key_id, credential_mac)" - + " VALUES (?, ?, ?, 'SELF_SERVICE_GAME_CREATION', ?, 'mac1', ?)", - id, - requestId, - account.getAccountUuid(), - operationId, - "a".repeat(64)); - return id; - }); + c.tx(() -> { + UUID id = insertEvidenceWithoutMac(c, account, requestId, operationId); + c.dsl.execute( + "INSERT INTO account_recent_reauthentication_replay_credentials" + + " (evidence_id, request_id, account_uuid, purpose, creation_operation_id, key_id, credential_mac)" + + " VALUES (?, ?, ?, 'SELF_SERVICE_GAME_CREATION', ?, 'mac1', ?)", + id, + requestId, + account.getAccountUuid(), + operationId, + "a".repeat(64)); + return id; + }); Record original = c.evidenceRow(evidenceId); Record proof = c.dsl.fetchOne("SELECT * FROM account_recent_reauthentication_replay_credentials"); @@ -1285,26 +1249,22 @@ void changedAccountPurposeOrCreationOperationConflictsBeforeNewAuthentication() var original = c.request(account, requestId, operationId, PASSWORD); c.service.reauthenticate(original); - assertThatThrownBy( - () -> - c.service.reauthenticate( - c.request(other, requestId, operationId, "not-the-secret"))) + assertThatThrownBy(() -> + c.service.reauthenticate(c.request(other, requestId, operationId, "not-the-secret"))) .isInstanceOf(AccountRecentReauthenticationService.IdempotencyConflictException.class); - assertThatThrownBy( - () -> - c.service.reauthenticate( - new AccountRecentReauthenticationService.Request( - requestId, - account.getAccountUuid(), - "ACCOUNT_SECURITY_CHANGE", - operationId, - account.getEmail(), - "not-the-secret"))) + assertThatThrownBy(() -> + c.service.reauthenticate( + new AccountRecentReauthenticationService.Request( + requestId, + account.getAccountUuid(), + "ACCOUNT_SECURITY_CHANGE", + operationId, + account.getEmail(), + "not-the-secret"))) .isInstanceOf(AccountRecentReauthenticationService.IdempotencyConflictException.class); - assertThatThrownBy( - () -> - c.service.reauthenticate( - c.request(account, requestId, UUID.randomUUID(), "not-the-secret"))) + assertThatThrownBy(() -> + c.service.reauthenticate( + c.request(account, requestId, UUID.randomUUID(), "not-the-secret"))) .isInstanceOf(AccountRecentReauthenticationService.IdempotencyConflictException.class); assertThat(c.count("SELECT count(*) FROM account_recent_reauthentication_replay_failures")) .isZero(); @@ -1345,22 +1305,20 @@ void accountAuthorityAdvanceAndCurrentLockedLifecycleInvalidateUnconsumedEvidenc ScopeState before = c.tx(() -> c.generations.read(AuthorityScope.account(account.getAccountUuid()))); - c.tx( - () -> { - account.setEmailVerified(true); - c.accounts.save(account); - return null; - }); + c.tx(() -> { + account.setEmailVerified(true); + c.accounts.save(account); + return null; + }); ScopeState after = c.tx(() -> c.generations.read(AuthorityScope.account(account.getAccountUuid()))); assertThat(after.generation()).isGreaterThan(before.generation()); - assertThatThrownBy( - () -> - c.consume( - generationEvidence, - account.getAccountUuid(), - generationEvidence.purpose(), - generationEvidence.creationOperationId())) + assertThatThrownBy(() -> + c.consume( + generationEvidence, + account.getAccountUuid(), + generationEvidence.purpose(), + generationEvidence.creationOperationId())) .isInstanceOf(IllegalStateException.class); assertThat(c.count("SELECT count(*) FROM account_recent_reauthentication_consumptions")) .isZero(); @@ -1371,20 +1329,18 @@ void accountAuthorityAdvanceAndCurrentLockedLifecycleInvalidateUnconsumedEvidenc c.request(lifecycleAccount, UUID.randomUUID(), UUID.randomUUID(), PASSWORD)); // This fixture changes only the persisted current lifecycle to isolate the AccountRepository // current-state denial. It does not claim the separate security-lock transition producer. - c.transaction.executeWithoutResult( - status -> { - c.dsl.execute("SET LOCAL session_replication_role = 'replica'"); - c.dsl.execute( - "UPDATE accounts SET lifecycle_state = 'security_locked' WHERE account_uuid = ?", - lifecycleAccount.getAccountUuid()); - }); - assertThatThrownBy( - () -> - c.consume( - lifecycleEvidence, - lifecycleAccount.getAccountUuid(), - lifecycleEvidence.purpose(), - lifecycleEvidence.creationOperationId())) + c.transaction.executeWithoutResult(status -> { + c.dsl.execute("SET LOCAL session_replication_role = 'replica'"); + c.dsl.execute( + "UPDATE accounts SET lifecycle_state = 'security_locked' WHERE account_uuid = ?", + lifecycleAccount.getAccountUuid()); + }); + assertThatThrownBy(() -> + c.consume( + lifecycleEvidence, + lifecycleAccount.getAccountUuid(), + lifecycleEvidence.purpose(), + lifecycleEvidence.creationOperationId())) .isInstanceOf(IllegalStateException.class); assertThat(c.count("SELECT count(*) FROM account_recent_reauthentication_consumptions")) .isZero(); @@ -1399,13 +1355,12 @@ void exactExpiryFutureSkewAndPolicyVersionAdvanceFailClosed() { c.service.reauthenticate( c.request(exactDeadlineAccount, UUID.randomUUID(), UUID.randomUUID(), PASSWORD)); c.clock.set(BASE.plusSeconds(270)); - assertThatThrownBy( - () -> - c.consume( - exactDeadline, - exactDeadlineAccount.getAccountUuid(), - exactDeadline.purpose(), - exactDeadline.creationOperationId())) + assertThatThrownBy(() -> + c.consume( + exactDeadline, + exactDeadlineAccount.getAccountUuid(), + exactDeadline.purpose(), + exactDeadline.creationOperationId())) .isInstanceOf(IllegalStateException.class); Account futureAccount = c.account("PASSWORD"); @@ -1428,13 +1383,12 @@ void exactExpiryFutureSkewAndPolicyVersionAdvanceFailClosed() { c.service.reauthenticate( c.request(beyondSkewAccount, UUID.randomUUID(), UUID.randomUUID(), PASSWORD)); c.clock.set(BASE); - assertThatThrownBy( - () -> - c.consume( - beyondSkew, - beyondSkewAccount.getAccountUuid(), - beyondSkew.purpose(), - beyondSkew.creationOperationId())) + assertThatThrownBy(() -> + c.consume( + beyondSkew, + beyondSkewAccount.getAccountUuid(), + beyondSkew.purpose(), + beyondSkew.creationOperationId())) .isInstanceOf(IllegalStateException.class); Account policyAccount = c.account("PASSWORD"); @@ -1442,24 +1396,22 @@ void exactExpiryFutureSkewAndPolicyVersionAdvanceFailClosed() { var priorPolicy = c.service.reauthenticate( c.request(policyAccount, UUID.randomUUID(), UUID.randomUUID(), PASSWORD)); - c.tx( - () -> { - c.dsl.execute( - "INSERT INTO account_recent_reauthentication_policy_values " - + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " - + "VALUES ('DEPLOYMENT', 2, 100, 10)"); - c.dsl.execute( - "UPDATE account_recent_reauthentication_policy_current SET policy_version = 2 " - + "WHERE policy_scope = 'DEPLOYMENT'"); - return null; - }); - assertThatThrownBy( - () -> - c.consume( - priorPolicy, - policyAccount.getAccountUuid(), - priorPolicy.purpose(), - priorPolicy.creationOperationId())) + c.tx(() -> { + c.dsl.execute( + "INSERT INTO account_recent_reauthentication_policy_values " + + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " + + "VALUES ('DEPLOYMENT', 2, 100, 10)"); + c.dsl.execute( + "UPDATE account_recent_reauthentication_policy_current SET policy_version = 2 " + + "WHERE policy_scope = 'DEPLOYMENT'"); + return null; + }); + assertThatThrownBy(() -> + c.consume( + priorPolicy, + policyAccount.getAccountUuid(), + priorPolicy.purpose(), + priorPolicy.creationOperationId())) .isInstanceOf(IllegalStateException.class); var currentPolicy = c.service.reauthenticate( @@ -1486,37 +1438,33 @@ void consumeIsImmutableAndConcurrentExactRetryCannotConsumeForAnotherOperation() var executor = Executors.newFixedThreadPool(2); try { var first = - executor.submit( - () -> - c.transaction.execute( - status -> { - firstPid.set(c.pid()); - var result = - c.service.validateAndConsumeLocked( - evidence, - account.getAccountUuid(), - evidence.purpose(), - evidence.creationOperationId()); - enteredFirst.countDown(); - awaitLatch(releaseFirst); - return result.disposition(); - })); + executor.submit(() -> + c.transaction.execute(status -> { + firstPid.set(c.pid()); + var result = + c.service.validateAndConsumeLocked( + evidence, + account.getAccountUuid(), + evidence.purpose(), + evidence.creationOperationId()); + enteredFirst.countDown(); + awaitLatch(releaseFirst); + return result.disposition(); + })); awaitLatch(enteredFirst); var second = - executor.submit( - () -> - c.transaction.execute( - status -> { - secondPid.set(c.pid()); - secondEntered.countDown(); - return c.service - .validateAndConsumeLocked( - evidence, - account.getAccountUuid(), - evidence.purpose(), - evidence.creationOperationId()) - .disposition(); - })); + executor.submit(() -> + c.transaction.execute(status -> { + secondPid.set(c.pid()); + secondEntered.countDown(); + return c.service + .validateAndConsumeLocked( + evidence, + account.getAccountUuid(), + evidence.purpose(), + evidence.creationOperationId()) + .disposition(); + })); awaitLatch(secondEntered); awaitBlocked(c, secondPid.get(), firstPid.get()); releaseFirst.countDown(); @@ -1530,10 +1478,8 @@ void consumeIsImmutableAndConcurrentExactRetryCannotConsumeForAnotherOperation() assertThat(c.count("SELECT count(*) FROM account_recent_reauthentication_consumptions")) .isEqualTo(1L); assertThat(c.evidenceRow(evidence.evidenceId())).isEqualTo(locked); - assertThatThrownBy( - () -> - c.consume( - evidence, account.getAccountUuid(), evidence.purpose(), UUID.randomUUID())) + assertThatThrownBy(() -> + c.consume(evidence, account.getAccountUuid(), evidence.purpose(), UUID.randomUUID())) .isInstanceOf(AccountRecentReauthenticationService.IdempotencyConflictException.class); } @@ -1552,32 +1498,26 @@ void pendingCreationValidationReadsCurrentExactEvidenceWithoutConsumption() { assertThat(c.count("SELECT count(*) FROM account_recent_reauthentication_consumptions")) .isZero(); - assertThatThrownBy( - () -> - c.tx( - () -> - c.service.validatePendingCreationLocked( - evidence, - UUID.randomUUID(), - evidence.purpose(), - evidence.creationOperationId()))) + assertThatThrownBy(() -> + c.tx(() -> + c.service.validatePendingCreationLocked( + evidence, + UUID.randomUUID(), + evidence.purpose(), + evidence.creationOperationId()))) .isInstanceOf(AccountRecentReauthenticationService.IdempotencyConflictException.class); - assertThatThrownBy( - () -> - c.tx( - () -> - c.service.validatePendingCreationLocked( - evidence, - evidence.accountId(), - "ACCOUNT_SECURITY_CHANGE", - evidence.creationOperationId()))) + assertThatThrownBy(() -> + c.tx(() -> + c.service.validatePendingCreationLocked( + evidence, + evidence.accountId(), + "ACCOUNT_SECURITY_CHANGE", + evidence.creationOperationId()))) .isInstanceOf(AccountRecentReauthenticationService.IdempotencyConflictException.class); - assertThatThrownBy( - () -> - c.tx( - () -> - c.service.validatePendingCreationLocked( - evidence, evidence.accountId(), evidence.purpose(), UUID.randomUUID()))) + assertThatThrownBy(() -> + c.tx(() -> + c.service.validatePendingCreationLocked( + evidence, evidence.accountId(), evidence.purpose(), UUID.randomUUID()))) .isInstanceOf(AccountRecentReauthenticationService.IdempotencyConflictException.class); assertThat(c.count("SELECT count(*) FROM account_recent_reauthentication_consumptions")) .isZero(); @@ -1595,11 +1535,10 @@ void pendingCreationRechecksActualAccountAuthorityAfterEarlierSuccessfulValidati ScopeState before = c.tx(() -> c.generations.read(AuthorityScope.account(account.getAccountUuid()))); - c.tx( - () -> { - account.setEmailVerified(true); - return c.accounts.save(account); - }); + c.tx(() -> { + account.setEmailVerified(true); + return c.accounts.save(account); + }); ScopeState after = c.tx(() -> c.generations.read(AuthorityScope.account(account.getAccountUuid()))); @@ -1620,16 +1559,15 @@ void pendingCreationRechecksCurrentPolicyAfterEarlierSuccessfulValidation() { c.request(account, UUID.randomUUID(), UUID.randomUUID(), PASSWORD)); assertThat(c.validatePending(evidence)).usingRecursiveComparison().isEqualTo(evidence); - c.tx( - () -> { - c.dsl.execute( - "INSERT INTO account_recent_reauthentication_policy_values " - + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " - + "VALUES ('DEPLOYMENT', 2, 100, 10)"); - return c.dsl.execute( - "UPDATE account_recent_reauthentication_policy_current SET policy_version = 2 " - + "WHERE policy_scope = 'DEPLOYMENT'"); - }); + c.tx(() -> { + c.dsl.execute( + "INSERT INTO account_recent_reauthentication_policy_values " + + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " + + "VALUES ('DEPLOYMENT', 2, 100, 10)"); + return c.dsl.execute( + "UPDATE account_recent_reauthentication_policy_current SET policy_version = 2 " + + "WHERE policy_scope = 'DEPLOYMENT'"); + }); assertThatThrownBy(() -> c.validatePending(evidence)) .isInstanceOf(IllegalStateException.class) @@ -1701,22 +1639,18 @@ void retainedEvidenceAndConsumptionRejectSqlMutation() { c.request(account, UUID.randomUUID(), UUID.randomUUID(), PASSWORD)); Record original = c.evidenceRow(evidence.evidenceId()); - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - "UPDATE account_recent_reauthentication_evidence " - + "SET issued_at = clock_timestamp() WHERE evidence_id = ?", - evidence.evidenceId()))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + "UPDATE account_recent_reauthentication_evidence " + + "SET issued_at = clock_timestamp() WHERE evidence_id = ?", + evidence.evidenceId()))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - "DELETE FROM account_recent_reauthentication_evidence WHERE evidence_id = ?", - evidence.evidenceId()))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + "DELETE FROM account_recent_reauthentication_evidence WHERE evidence_id = ?", + evidence.evidenceId()))) .isInstanceOf(DataAccessException.class); assertThatThrownBy( () -> c.tx(() -> c.dsl.execute("TRUNCATE account_recent_reauthentication_evidence"))) @@ -1725,26 +1659,21 @@ void retainedEvidenceAndConsumptionRejectSqlMutation() { c.consume( evidence, account.getAccountUuid(), evidence.purpose(), evidence.creationOperationId()); - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - "UPDATE account_recent_reauthentication_consumptions " - + "SET consumed_at = clock_timestamp() WHERE evidence_id = ?", - evidence.evidenceId()))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + "UPDATE account_recent_reauthentication_consumptions " + + "SET consumed_at = clock_timestamp() WHERE evidence_id = ?", + evidence.evidenceId()))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - "DELETE FROM account_recent_reauthentication_consumptions WHERE evidence_id = ?", - evidence.evidenceId()))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + "DELETE FROM account_recent_reauthentication_consumptions WHERE evidence_id = ?", + evidence.evidenceId()))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - c.tx(() -> c.dsl.execute("TRUNCATE account_recent_reauthentication_consumptions"))) + assertThatThrownBy(() -> + c.tx(() -> c.dsl.execute("TRUNCATE account_recent_reauthentication_consumptions"))) .isInstanceOf(DataAccessException.class); assertThat(c.count("SELECT count(*) FROM account_recent_reauthentication_consumptions")) .isEqualTo(1L); @@ -1865,16 +1794,15 @@ private static Context contextAtVersion( var transaction = new TransactionTemplate(manager); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); if (installApprovedPolicySources) { - transaction.executeWithoutResult( - ignored -> { - dsl.execute( - "INSERT INTO account_recent_reauthentication_policy_values " - + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " - + "VALUES ('PLATFORM', 1, 300, 30), ('DEPLOYMENT', 1, 300, 30)"); - dsl.execute( - "INSERT INTO account_recent_reauthentication_policy_current " - + "(policy_scope, policy_version) VALUES ('PLATFORM', 1), ('DEPLOYMENT', 1)"); - }); + transaction.executeWithoutResult(ignored -> { + dsl.execute( + "INSERT INTO account_recent_reauthentication_policy_values " + + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " + + "VALUES ('PLATFORM', 1, 300, 30), ('DEPLOYMENT', 1, 300, 30)"); + dsl.execute( + "INSERT INTO account_recent_reauthentication_policy_current " + + "(policy_scope, policy_version) VALUES ('PLATFORM', 1), ('DEPLOYMENT', 1)"); + }); } var generations = new AccountAuthorityGenerationRepository(dsl); var outbox = new AccountAuthorityOutboxRepository(dsl); @@ -1997,33 +1925,32 @@ private static UUID insertEvidenceWithoutMac( AccountRecentReauthenticationPolicy.resolve( new AccountRecentReauthenticationPolicy.PlatformValue(1, 300, 30), new AccountRecentReauthenticationPolicy.DeploymentValue(1, 300, 30)); - c.tx( - () -> { - var authority = c.generations.read(AuthorityScope.account(account.getAccountUuid())); - var fence = authority.issuanceFence(); - return c.dsl.execute( - "INSERT INTO account_recent_reauthentication_evidence" - + " (evidence_id, request_id, account_uuid, purpose, creation_operation_id, request_payload, request_digest," - + " identity_provenance, account_uuid_source_numeric_id, account_lifecycle_state, account_authority_generation," - + " account_authority_source_version, issuance_fence, issuance_fence_source_version, platform_policy_version," - + " deployment_policy_version, effective_policy_version, recent_age_seconds, max_clock_skew_seconds, issued_at)" - + " VALUES (?, ?, ?, 'SELF_SERVICE_GAME_CREATION', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, ?, 300, 30, ?::timestamptz)", - evidenceId, - requestId, - account.getAccountUuid(), - operationId, - bytes, - digest, - account.getAccountUuidProvenance().name(), - account.getAccountUuidSourceNumericId(), - account.getLifecycleState().name(), - authority.generation(), - authority.sourceVersion(), - fence.value(), - fence.sourceVersion(), - policy.effectivePolicyVersion(), - java.time.OffsetDateTime.ofInstant(c.clock.instant(), ZoneOffset.UTC)); - }); + c.tx(() -> { + var authority = c.generations.read(AuthorityScope.account(account.getAccountUuid())); + var fence = authority.issuanceFence(); + return c.dsl.execute( + "INSERT INTO account_recent_reauthentication_evidence" + + " (evidence_id, request_id, account_uuid, purpose, creation_operation_id, request_payload, request_digest," + + " identity_provenance, account_uuid_source_numeric_id, account_lifecycle_state, account_authority_generation," + + " account_authority_source_version, issuance_fence, issuance_fence_source_version, platform_policy_version," + + " deployment_policy_version, effective_policy_version, recent_age_seconds, max_clock_skew_seconds, issued_at)" + + " VALUES (?, ?, ?, 'SELF_SERVICE_GAME_CREATION', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, 1, ?, 300, 30, ?::timestamptz)", + evidenceId, + requestId, + account.getAccountUuid(), + operationId, + bytes, + digest, + account.getAccountUuidProvenance().name(), + account.getAccountUuidSourceNumericId(), + account.getLifecycleState().name(), + authority.generation(), + authority.sourceVersion(), + fence.value(), + fence.sourceVersion(), + policy.effectivePolicyVersion(), + java.time.OffsetDateTime.ofInstant(c.clock.instant(), ZoneOffset.UTC)); + }); return evidenceId; } @@ -2088,18 +2015,17 @@ AccountRecentReauthenticationService.Request request( } AccountEmailLoginChallenge challenge(Account account) { - return tx( - () -> { - var challenge = new AccountEmailLoginChallenge(); - var now = LocalDateTime.now().withNano(0); - challenge.setAccountId(account.getId()); - challenge.setCodeHash(hash(OTP)); - challenge.setExpiresAt(now.plusMinutes(5)); - challenge.setResendAvailableAt(now.plusMinutes(1)); - challenge.setCreatedAt(now); - challenge.setUpdatedAt(now); - return challenges.save(challenge); - }); + return tx(() -> { + var challenge = new AccountEmailLoginChallenge(); + var now = LocalDateTime.now().withNano(0); + challenge.setAccountId(account.getId()); + challenge.setCodeHash(hash(OTP)); + challenge.setExpiresAt(now.plusMinutes(5)); + challenge.setResendAvailableAt(now.plusMinutes(1)); + challenge.setCreatedAt(now); + challenge.setUpdatedAt(now); + return challenges.save(challenge); + }); } AccountRecentReauthenticationService.Validation consume( @@ -2112,13 +2038,9 @@ AccountRecentReauthenticationService.Validation consume( AccountRecentReauthenticationEvidence validatePending( AccountRecentReauthenticationEvidence evidence) { - return tx( - () -> - service.validatePendingCreationLocked( - evidence, - evidence.accountId(), - evidence.purpose(), - evidence.creationOperationId())); + return tx(() -> + service.validatePendingCreationLocked( + evidence, evidence.accountId(), evidence.purpose(), evidence.creationOperationId())); } Record evidenceRow(UUID evidenceId) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSecurityStateOperationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSecurityStateOperationPostgresIntegrationTest.java index 1fa9e678d0..4e59bb328f 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSecurityStateOperationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSecurityStateOperationPostgresIntegrationTest.java @@ -140,11 +140,8 @@ void zeroReceiptRejectsAbsentMismatchedAndFabricatedV40BaselineWithoutMutation() } finally { fixture.dsl().execute("ALTER TABLE account_authority_source_records ENABLE TRIGGER USER"); } - assertThatThrownBy( - () -> - tx( - fixture, - () -> fixture.operations().claim(pending.request(), pending.capture()))) + assertThatThrownBy(() -> + tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture()))) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("Security-state pristine baseline is not proved"); assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))).isZero(); @@ -257,14 +254,13 @@ void accountRepositoryRoleSavePersistsGenericHistoryButNotCanonicalRoleAuthority assertThat(roleSourceAfter).isEqualTo(roleSourceBefore); assertThat(roleSourceAfter.get("global_roles", String[].class)).isEmpty(); assertThat(roleSourceAfter.get("global_role_source_version", Long.class)).isEqualTo(1L); - assertThatThrownBy( - () -> - tx( - fixture, - () -> { - sourceReadback(fixture).requireCurrentLatest(saved, current); - return null; - })) + assertThatThrownBy(() -> + tx( + fixture, + () -> { + sourceReadback(fixture).requireCurrentLatest(saved, current); + return null; + })) .isInstanceOf(IllegalStateException.class); assertThatThrownBy(() -> sourceReader(fixture).readCurrent(saved.getAccountUuid())) .isInstanceOf(IllegalStateException.class); @@ -315,27 +311,24 @@ void concurrentExactClaimsSerializeToOneOriginalRequest() throws Exception { try (var executor = Executors.newFixedThreadPool(2)) { var tasks = List.of(1, 2).stream() - .map( - ignored -> - executor.submit( - () -> - tx( - fixture, - () -> { - ready.countDown(); - try { - if (!ready.await(10, TimeUnit.SECONDS)) - throw new IllegalStateException( - "Concurrent claims did not start"); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(interrupted); - } - return fixture - .operations() - .claim(pending.request(), pending.capture()) - .claimed(); - }))) + .map(ignored -> + executor.submit(() -> + tx( + fixture, + () -> { + ready.countDown(); + try { + if (!ready.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("Concurrent claims did not start"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return fixture + .operations() + .claim(pending.request(), pending.capture()) + .claimed(); + }))) .toList(); assertThat( List.of( @@ -439,23 +432,22 @@ void unownedPrivateFenceAdvanceIsRejectedWithoutChangingSourceOrOriginalReceipt( .fetchOne( "SELECT * FROM account_security_state_operations WHERE request_id = ?", pending.request().requestId()); - assertThatThrownBy( - () -> - tx( - fixture, - () -> { - var source = fixture.generations().read(seed.source().scope()); - fixture - .dsl() - .execute( - "UPDATE account_authority_issuance_fences " - + "SET issuance_fence = issuance_fence + 1, source_version = source_version + 1, updated_at = CURRENT_TIMESTAMP " - + "WHERE account_uuid = ? AND issuance_fence = ? AND source_version = ?", - seed.account().getAccountUuid(), - source.issuanceFence().value(), - source.issuanceFence().sourceVersion()); - return null; - })) + assertThatThrownBy(() -> + tx( + fixture, + () -> { + var source = fixture.generations().read(seed.source().scope()); + fixture + .dsl() + .execute( + "UPDATE account_authority_issuance_fences " + + "SET issuance_fence = issuance_fence + 1, source_version = source_version + 1, updated_at = CURRENT_TIMESTAMP " + + "WHERE account_uuid = ? AND issuance_fence = ? AND source_version = ?", + seed.account().getAccountUuid(), + source.issuanceFence().value(), + source.issuanceFence().sourceVersion()); + return null; + })) .rootCause() .isInstanceOf(org.postgresql.util.PSQLException.class) .hasMessageContaining("Account issuance fence advance lacks exact owner source evidence"); @@ -543,11 +535,10 @@ void requestCaptureResultsDeletesAndTruncationRemainGuarded() { .isInstanceOf(org.jooq.exception.DataAccessException.class); } producerFixture(fixture, pending, false); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute("UPDATE account_security_state_operations SET event_id = 'changed'")) + assertThatThrownBy(() -> + fixture + .dsl() + .execute("UPDATE account_security_state_operations SET event_id = 'changed'")) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))) .isEqualTo(1); @@ -559,46 +550,45 @@ void substitutedEventStateCannotBecomeTheOriginalReceipt() { Seed seed = seed(fixture); Pending pending = pending(fixture, seed, state(false), state(true), 0L, new byte[0]); tx(fixture, () -> fixture.operations().claim(pending.request(), pending.capture())); - assertThatThrownBy( - () -> - tx( - fixture, - () -> { - var wrong = - AccountSecurityStateAuthorityEventV1Codec.seal( - AccountSecurityStateMutationRequest.eventPreimage( - pending.request().requestId(), - pending.request().accountUuid(), - "2", - "2", - "1", - pending.request().mutationKinds(), - state(false))); - var event = - fixture - .outbox() - .append( - stream(seed), - pending.request().requestId().toString(), - sequence -> - new EventEvidence( - wrong.eventId(), - wrong.eventDigest(), - wrong.canonicalJsonUtf8())); + assertThatThrownBy(() -> + tx( + fixture, + () -> { + var wrong = + AccountSecurityStateAuthorityEventV1Codec.seal( + AccountSecurityStateMutationRequest.eventPreimage( + pending.request().requestId(), + pending.request().accountUuid(), + "2", + "2", + "1", + pending.request().mutationKinds(), + state(false))); + var event = fixture - .operations() - .complete( - pending.request(), - event, - new ScopeState( - seed.source().scope(), - 2L, - 2L, - new AccountAuthorityGenerationRepository.IssuanceFence( - seed.account().getAccountUuid(), 2L, 2L)), - 1L); - return null; - })) + .outbox() + .append( + stream(seed), + pending.request().requestId().toString(), + sequence -> + new EventEvidence( + wrong.eventId(), + wrong.eventDigest(), + wrong.canonicalJsonUtf8())); + fixture + .operations() + .complete( + pending.request(), + event, + new ScopeState( + seed.source().scope(), + 2L, + 2L, + new AccountAuthorityGenerationRepository.IssuanceFence( + seed.account().getAccountUuid(), 2L, 2L)), + 1L); + return null; + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("receipt differs"); assertThat(fixture.dsl().fetchCount(DSL.table("account_authority_outbox_events"))).isZero(); @@ -651,9 +641,8 @@ void corruptPositiveCheckpointMetadataAndPayloadDenyBeforeNewIntentOrSourceMutat corruption.startsWith("payload = ") ? "Original checkpoint capture differs" : "Account source event readback is inconsistent"; - assertThatThrownBy( - () -> - tx(fixture, () -> fixture.operations().claim(second.request(), second.capture()))) + assertThatThrownBy(() -> + tx(fixture, () -> fixture.operations().claim(second.request(), second.capture()))) .isExactlyInstanceOf(IllegalStateException.class) .hasMessage(expectedMessage); assertThat(fixture.dsl().fetchCount(DSL.table("account_security_state_operations"))) @@ -709,11 +698,10 @@ void retainedReceiptCannotLeadRegressedCurrentAuthorityOrCheckpoint() { table.equals("account_authority_generations") ? IllegalArgumentException.class : IllegalStateException.class; - assertThatThrownBy( - () -> - tx( - fixture, - () -> fixture.operations().findByRequestId(pending.request().requestId()))) + assertThatThrownBy(() -> + tx( + fixture, + () -> fixture.operations().findByRequestId(pending.request().requestId()))) .isExactlyInstanceOf(expectedException) .hasMessage(expectedMessage); } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java index 9625545da1..d5f62d954e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java @@ -176,28 +176,26 @@ void finalizesBothOwnersExactlyAndKeepsTheirFullSourceVectorsPending() throws Ex for (Owner owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { UUID requestId = UUID.randomUUID(); var scope = - asGameDesign( - () -> - reservationService.reserveSourceRead( - issued.compact(), requestId, owner, selected, issued.environment())); + asGameDesign(() -> + reservationService.reserveSourceRead( + issued.compact(), requestId, owner, selected, issued.environment())); var content = content(scope, "stipulated-original"); var authorization = - asGameDesign( - () -> - issued - .actors() - .withCurrent( - issued.compact(), - f.tenant, - issued.environment(), - current -> - repository.finalizeSourceRead( - scope, - content, - current, - () -> - f.fences.requireSelectedOwnerIntakeAdmission( - current.source().sources(), selected)))); + asGameDesign(() -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, + content, + current, + () -> + f.fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected)))); assertThat(authorization.owner()).isEqualTo(owner); assertThat(authorization.content().canonicalBytes()).isEqualTo(content.canonicalBytes()); @@ -214,29 +212,27 @@ void finalizesBothOwnersExactlyAndKeepsTheirFullSourceVectorsPending() throws Ex assertThat(readback.canonicalBytes()).isEqualTo(authorization.canonicalBytes()); assertThat(readback.digest()).isEqualTo(authorization.digest()); var exactRetry = - asGameDesign( - () -> - issued - .actors() - .withCurrent( - issued.compact(), - f.tenant, - issued.environment(), - current -> - repository.finalizeSourceRead( - scope, - content, - current, - () -> { - throw new AssertionError( - "Exact finalization retry must not re-admit"); - }))); + asGameDesign(() -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, + content, + current, + () -> { + throw new AssertionError( + "Exact finalization retry must not re-admit"); + }))); assertThat(exactRetry.canonicalBytes()).isEqualTo(authorization.canonicalBytes()); - f.tx( - () -> { - repository.readFinalAuthorization(authorization); - return null; - }); + f.tx(() -> { + repository.readFinalAuthorization(authorization); + return null; + }); assertThatThrownBy(() -> f.tx(() -> repository.sourceReadCurrentness(scope))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("preliminary source read"); @@ -245,19 +241,17 @@ void finalizesBothOwnersExactlyAndKeepsTheirFullSourceVectorsPending() throws Ex .hasMessageContaining("cannot be preliminarily aborted"); var changedContent = content(scope, "stipulated-changed"); - assertThatThrownBy( - () -> - asGameDesign( - () -> - issued - .actors() - .withCurrent( - issued.compact(), - f.tenant, - issued.environment(), - current -> - repository.finalizeSourceRead( - scope, changedContent, current, () -> {})))) + assertThatThrownBy(() -> + asGameDesign(() -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, changedContent, current, () -> {})))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("conflicts with original selected content"); @@ -267,14 +261,13 @@ void finalizesBothOwnersExactlyAndKeepsTheirFullSourceVectorsPending() throws Ex UUID abortedRequest = UUID.randomUUID(); var abortedScope = - asGameDesign( - () -> - reservationService.reserveSourceRead( - issued.compact(), - abortedRequest, - Owner.ENTITY_MANAGEMENT, - selected, - issued.environment())); + asGameDesign(() -> + reservationService.reserveSourceRead( + issued.compact(), + abortedRequest, + Owner.ENTITY_MANAGEMENT, + selected, + issued.environment())); assertThat(f.tx(() -> repository.abortSourceRead(abortedScope).state())) .isEqualTo(State.ABORTED); assertThat( @@ -285,19 +278,17 @@ void finalizesBothOwnersExactlyAndKeepsTheirFullSourceVectorsPending() throws Ex .get(0, Boolean.class)) .isFalse(); var abortedContent = content(abortedScope, "stipulated-aborted"); - assertThatThrownBy( - () -> - asGameDesign( - () -> - issued - .actors() - .withCurrent( - issued.compact(), - f.tenant, - issued.environment(), - current -> - repository.finalizeSourceRead( - abortedScope, abortedContent, current, () -> {})))) + assertThatThrownBy(() -> + asGameDesign(() -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + abortedScope, abortedContent, current, () -> {})))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("scope aborted"); assertThat( @@ -339,23 +330,21 @@ void expiredRecoveryUsesDatabaseCutoffAndPreservesFinalizedOwnerUntilExactSettle new AccountSelectedOwnerIntakeSourceReservationService( issued.actors(), f.fences, repository, f.manager, "test"); var preliminary = - asGameDesign( - () -> - reservations.reserveSourceRead( - issued.compact(), - UUID.randomUUID(), - Owner.AUTOMATION_SCRIPTING, - selected, - issued.environment())); + asGameDesign(() -> + reservations.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.AUTOMATION_SCRIPTING, + selected, + issued.environment())); var finalizingScope = - asGameDesign( - () -> - reservations.reserveSourceRead( - issued.compact(), - UUID.randomUUID(), - Owner.ENTITY_MANAGEMENT, - selected, - issued.environment())); + asGameDesign(() -> + reservations.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + selected, + issued.environment())); var alreadyFinalized = finalizeEntityBinding(issued, reservations, repository, selected, "recovery-committed"); UUID issuanceOperationId = @@ -380,45 +369,40 @@ void expiredRecoveryUsesDatabaseCutoffAndPreservesFinalizedOwnerUntilExactSettle ExecutorService executor = Executors.newFixedThreadPool(2); try { var finalizing = - executor.submit( - () -> - asGameDesign( - () -> - issued - .actors() - .withCurrent( - issued.compact(), - f.tenant, - issued.environment(), - current -> { - var binding = - repository.finalizeSourceRead( - finalizingScope, - finalizationContent, - current, - () -> - f.fences.requireSelectedOwnerIntakeAdmission( - current.source().sources(), selected)); - finalizationBackendPid.set( - f.dsl - .fetchSingle("SELECT pg_backend_pid()") - .get(0, Integer.class)); - authorizationInserted.countDown(); - awaitFinalizationCommit(allowFinalizationCommit); - return binding; - }))); + executor.submit(() -> + asGameDesign(() -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> { + var binding = + repository.finalizeSourceRead( + finalizingScope, + finalizationContent, + current, + () -> + f.fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected)); + finalizationBackendPid.set( + f.dsl + .fetchSingle("SELECT pg_backend_pid()") + .get(0, Integer.class)); + authorizationInserted.countDown(); + awaitFinalizationCommit(allowFinalizationCommit); + return binding; + }))); assertThat(authorizationInserted.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(issuerExpiryReached(f.dsl, issuanceOperationId)).isFalse(); awaitIssuerExpiry(f.dsl, issuanceOperationId); var recovering = - executor.submit( - () -> { - recoveryStarted.countDown(); - return reservations - .recoverExpiredPreliminarySourceReads(128, null) - .abortedCount(); - }); + executor.submit(() -> { + recoveryStarted.countDown(); + return reservations.recoverExpiredPreliminarySourceReads(128, null).abortedCount(); + }); assertThat(recoveryStarted.await(10, TimeUnit.SECONDS)).isTrue(); awaitRecoverySourceLockWait(f.dsl, finalizationBackendPid.get()); assertThat(recovering.isDone()).isFalse(); @@ -523,23 +507,21 @@ void expiredPreliminaryRecoveryContinuesAcrossSameExpiryRowsByKeyset() throws Ex new AccountSelectedOwnerIntakeSourceReservationService( issued.actors(), f.fences, repository, f.manager, "test"); var firstScope = - asGameDesign( - () -> - reservations.reserveSourceRead( - issued.compact(), - UUID.randomUUID(), - Owner.ENTITY_MANAGEMENT, - selected, - issued.environment())); + asGameDesign(() -> + reservations.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + selected, + issued.environment())); var secondScope = - asGameDesign( - () -> - reservations.reserveSourceRead( - issued.compact(), - UUID.randomUUID(), - Owner.AUTOMATION_SCRIPTING, - selected, - issued.environment())); + asGameDesign(() -> + reservations.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.AUTOMATION_SCRIPTING, + selected, + issued.environment())); UUID issuanceOperationId = f.dsl .fetchSingle( @@ -605,14 +587,13 @@ void expiredPreliminaryRecoveryAcceptsRetainedExpiredIssuersAndKeepsFinalAuthori new AccountSelectedOwnerIntakeSourceReservationService( issued.actors(), f.fences, repository, f.manager, "test"); var preliminary = - asGameDesign( - () -> - reservations.reserveSourceRead( - issued.compact(), - UUID.randomUUID(), - Owner.AUTOMATION_SCRIPTING, - selected, - issued.environment())); + asGameDesign(() -> + reservations.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.AUTOMATION_SCRIPTING, + selected, + issued.environment())); var finalized = finalizeEntityBinding(issued, reservations, repository, selected, issuerStatus); var finalizedScope = finalized.content().scope(); @@ -629,11 +610,10 @@ void expiredPreliminaryRecoveryAcceptsRetainedExpiredIssuersAndKeepsFinalAuthori var issuanceRepository = new AccountControlUiIssuanceRepository(f.dsl); if ("REVOKING".equals(issuerStatus)) { var original = - f.tx( - () -> - issuanceRepository.findToken( - AccountControlUiIssuanceRepository.hash( - issued.compact().getBytes(StandardCharsets.US_ASCII)))); + f.tx(() -> + issuanceRepository.findToken( + AccountControlUiIssuanceRepository.hash( + issued.compact().getBytes(StandardCharsets.US_ASCII)))); assertThat(original).isNotNull(); var revoking = f.tx(() -> issuanceRepository.beginRecoveryFailure(original)); assertThat(revoking.status).isEqualTo("REVOKING"); @@ -732,32 +712,30 @@ void commitsExactAutomationEmptySettlementAndReleasesOnlyThatOperation() throws for (int index = 0; index < 2; index++) { UUID requestId = UUID.randomUUID(); var scope = - asGameDesign( - () -> - reservationService.reserveSourceRead( - issued.compact(), - requestId, - Owner.AUTOMATION_SCRIPTING, - selected, - issued.environment())); + asGameDesign(() -> + reservationService.reserveSourceRead( + issued.compact(), + requestId, + Owner.AUTOMATION_SCRIPTING, + selected, + issued.environment())); var content = content(scope, "automation-settlement-" + index); var binding = - asGameDesign( - () -> - issued - .actors() - .withCurrent( - issued.compact(), - f.tenant, - issued.environment(), - current -> - repository.finalizeSourceRead( - scope, - content, - current, - () -> - f.fences.requireSelectedOwnerIntakeAdmission( - current.source().sources(), selected)))); + asGameDesign(() -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, + content, + current, + () -> + f.fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected)))); bindings.add(binding); terminals.add(terminalEvidence(binding, 9001L + index, 9002L + index)); } @@ -798,18 +776,15 @@ void commitsExactAutomationEmptySettlementAndReleasesOnlyThatOperation() throws var exactReadback = f.tx(() -> repository.findSettlement(firstBinding).orElseThrow()); assertThat(exactReadback.canonicalBytes()).isEqualTo(committed.canonicalBytes()); - f.tx( - () -> { - repository.readFinalAuthorization(firstBinding); - return null; - }); - assertThatThrownBy( - () -> - f.tx( - () -> { - repository.readHeldFinalAuthorization(firstBinding); - return null; - })) + f.tx(() -> { + repository.readFinalAuthorization(firstBinding); + return null; + }); + assertThatThrownBy(() -> + f.tx(() -> { + repository.readHeldFinalAuthorization(firstBinding); + return null; + })) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("no longer held"); @@ -853,13 +828,12 @@ void commitsExactAutomationEmptySettlementAndReleasesOnlyThatOperation() throws assertThatThrownBy(() -> f.tx(() -> repository.settleCommittedEmpty(changedBindingEvidence))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Original finalized owner authorization absent or changed"); - assertThatThrownBy( - () -> - f.dsl.execute( - "UPDATE account_selected_owner_intake_settlements " - + "SET receipt_digest = ? WHERE operation_id = ?", - DraftAuthorizationFenceBinding.digest(new byte[] {1}), - firstBinding.operationId())) + assertThatThrownBy(() -> + f.dsl.execute( + "UPDATE account_selected_owner_intake_settlements " + + "SET receipt_digest = ? WHERE operation_id = ?", + DraftAuthorizationFenceBinding.digest(new byte[] {1}), + firstBinding.operationId())) .isInstanceOf(RuntimeException.class); assertThat( f.dsl @@ -895,27 +869,23 @@ void commitsExactAutomationEmptySettlementAndReleasesOnlyThatOperation() throws ExecutorService executor = Executors.newFixedThreadPool(2); try { var settling = - executor.submit( - () -> - f.transactions.execute( - ignored -> { - var result = repository.settleCommittedEmpty(terminals.getLast()); - settlementInserted.countDown(); - awaitLatch(allowSettlementCommit); - return result; - })); + executor.submit(() -> + f.transactions.execute(ignored -> { + var result = repository.settleCommittedEmpty(terminals.getLast()); + settlementInserted.countDown(); + awaitLatch(allowSettlementCommit); + return result; + })); assertThat(settlementInserted.await(10, TimeUnit.SECONDS)).isTrue(); var waitingWriter = - executor.submit( - () -> - f.transactions.execute( - ignored -> { - writerBackendPid.set( - f.dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); - writerStarted.countDown(); - return f.fences.requestSourceChange(writerWhileOtherOperationHeld); - })); + executor.submit(() -> + f.transactions.execute(ignored -> { + writerBackendPid.set( + f.dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + writerStarted.countDown(); + return f.fences.requestSourceChange(writerWhileOtherOperationHeld); + })); assertThat(writerStarted.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(writerBackendPid.get()).isPositive(); awaitSourceLockWait(f.dsl, writerBackendPid.get()); @@ -984,32 +954,30 @@ void commitsExactEntityEmptySettlementAndReleasesOnlyThatOperation() throws Exce for (int index = 0; index < 2; index++) { UUID requestId = UUID.randomUUID(); var scope = - asGameDesign( - () -> - reservationService.reserveSourceRead( - issued.compact(), - requestId, - Owner.ENTITY_MANAGEMENT, - selected, - issued.environment())); + asGameDesign(() -> + reservationService.reserveSourceRead( + issued.compact(), + requestId, + Owner.ENTITY_MANAGEMENT, + selected, + issued.environment())); var content = content(scope, "automation-settlement-" + index); var binding = - asGameDesign( - () -> - issued - .actors() - .withCurrent( - issued.compact(), - f.tenant, - issued.environment(), - current -> - repository.finalizeSourceRead( - scope, - content, - current, - () -> - f.fences.requireSelectedOwnerIntakeAdmission( - current.source().sources(), selected)))); + asGameDesign(() -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, + content, + current, + () -> + f.fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected)))); bindings.add(binding); terminals.add(entityTerminalEvidence(binding, 9001L + index, 9002L + index)); } @@ -1050,18 +1018,15 @@ void commitsExactEntityEmptySettlementAndReleasesOnlyThatOperation() throws Exce var exactReadback = f.tx(() -> repository.findSettlement(firstBinding).orElseThrow()); assertThat(exactReadback.canonicalBytes()).isEqualTo(committed.canonicalBytes()); - f.tx( - () -> { - repository.readFinalAuthorization(firstBinding); - return null; - }); - assertThatThrownBy( - () -> - f.tx( - () -> { - repository.readHeldFinalAuthorization(firstBinding); - return null; - })) + f.tx(() -> { + repository.readFinalAuthorization(firstBinding); + return null; + }); + assertThatThrownBy(() -> + f.tx(() -> { + repository.readHeldFinalAuthorization(firstBinding); + return null; + })) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("no longer held"); @@ -1105,13 +1070,12 @@ void commitsExactEntityEmptySettlementAndReleasesOnlyThatOperation() throws Exce () -> f.tx(() -> repository.settleEntityCommittedEmpty(changedBindingEvidence))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Original finalized owner authorization absent or changed"); - assertThatThrownBy( - () -> - f.dsl.execute( - "UPDATE account_selected_owner_intake_settlements " - + "SET receipt_digest = ? WHERE operation_id = ?", - DraftAuthorizationFenceBinding.digest(new byte[] {1}), - firstBinding.operationId())) + assertThatThrownBy(() -> + f.dsl.execute( + "UPDATE account_selected_owner_intake_settlements " + + "SET receipt_digest = ? WHERE operation_id = ?", + DraftAuthorizationFenceBinding.digest(new byte[] {1}), + firstBinding.operationId())) .isInstanceOf(RuntimeException.class); assertThat( f.dsl @@ -1147,27 +1111,23 @@ void commitsExactEntityEmptySettlementAndReleasesOnlyThatOperation() throws Exce ExecutorService executor = Executors.newFixedThreadPool(2); try { var settling = - executor.submit( - () -> - f.transactions.execute( - ignored -> { - var result = repository.settleEntityCommittedEmpty(terminals.getLast()); - settlementInserted.countDown(); - awaitLatch(allowSettlementCommit); - return result; - })); + executor.submit(() -> + f.transactions.execute(ignored -> { + var result = repository.settleEntityCommittedEmpty(terminals.getLast()); + settlementInserted.countDown(); + awaitLatch(allowSettlementCommit); + return result; + })); assertThat(settlementInserted.await(10, TimeUnit.SECONDS)).isTrue(); var waitingWriter = - executor.submit( - () -> - f.transactions.execute( - ignored -> { - writerBackendPid.set( - f.dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); - writerStarted.countDown(); - return f.fences.requestSourceChange(writerWhileOtherOperationHeld); - })); + executor.submit(() -> + f.transactions.execute(ignored -> { + writerBackendPid.set( + f.dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + writerStarted.countDown(); + return f.fences.requestSourceChange(writerWhileOtherOperationHeld); + })); assertThat(writerStarted.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(writerBackendPid.get()).isPositive(); awaitSourceLockWait(f.dsl, writerBackendPid.get()); @@ -1236,14 +1196,13 @@ void upgradesCombinedV1007ParentThroughFinalAuthorizationAndBothTerminalOwnersWi new AccountSelectedOwnerIntakeSourceReservationService( issued.actors(), f.fences, repository, f.manager, "test"); var scope = - asGameDesign( - () -> - reservations.reserveSourceRead( - issued.compact(), - UUID.randomUUID(), - Owner.ENTITY_MANAGEMENT, - selected, - issued.environment())); + asGameDesign(() -> + reservations.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + selected, + issued.environment())); seedRetainedCombinedParentRows(f.dsl); var retainedRows = retainedCombinedParentRows(f.dsl); assertThat(retainedRows.values()).allSatisfy(rows -> assertThat(rows).isNotEmpty()); @@ -1380,11 +1339,10 @@ void migratesRetainedV1009AutomationBytesWithoutReleasingPendingEntity() throws assertThatThrownBy(() -> f.tx(() -> repository.abortSourceRead(entity.content().scope()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("cannot be preliminarily aborted"); - assertThatThrownBy( - () -> - f.dsl.execute( - "DELETE FROM account_selected_owner_intake_settlements WHERE operation_id = ?", - automation.operationId())) + assertThatThrownBy(() -> + f.dsl.execute( + "DELETE FROM account_selected_owner_intake_settlements WHERE operation_id = ?", + automation.operationId())) .isInstanceOf(RuntimeException.class); assertThat(f.tx(() -> repository.findSettlement(automation).orElseThrow()).canonicalBytes()) .isEqualTo(original.canonicalBytes()); @@ -1599,14 +1557,13 @@ void postgresRejectsChangedNamespaceUnknownFamilyAndSelectedScopeEvidence() thro var scopes = new ArrayList(); for (int index = 0; index < 3; index++) { scopes.add( - asGameDesign( - () -> - reservationService.reserveSourceRead( - issued.compact(), - UUID.randomUUID(), - Owner.ENTITY_MANAGEMENT, - selected, - issued.environment()))); + asGameDesign(() -> + reservationService.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + selected, + issued.environment()))); } var original = scopes.get(0); @@ -1674,34 +1631,31 @@ private static void assertRejectedByPostgres( byte[] bindingBytes, String expectedDiagnostic) { var f = issued.sources(); - assertThatThrownBy( - () -> - asGameDesign( - () -> - issued - .actors() - .withCurrent( - issued.compact(), - f.tenant, - issued.environment(), - current -> { - insertRawAuthorization( - f.dsl, reservationScope, contentBytes, bindingBytes, current); - return null; - }))) + assertThatThrownBy(() -> + asGameDesign(() -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> { + insertRawAuthorization( + f.dsl, reservationScope, contentBytes, bindingBytes, current); + return null; + }))) .isInstanceOf(RuntimeException.class) - .satisfies( - failure -> { - Throwable root = failure; - while (root.getCause() != null) root = root.getCause(); - assertThat(root) - .isInstanceOfSatisfying( - java.sql.SQLException.class, - sql -> { - assertThat(sql.getSQLState()).isEqualTo("23514"); - assertThat(sql.getMessage()).contains(expectedDiagnostic); - }); - }); + .satisfies(failure -> { + Throwable root = failure; + while (root.getCause() != null) root = root.getCause(); + assertThat(root) + .isInstanceOfSatisfying( + java.sql.SQLException.class, + sql -> { + assertThat(sql.getSQLState()).isEqualTo("23514"); + assertThat(sql.getMessage()).contains(expectedDiagnostic); + }); + }); assertThat( f.dsl.fetchOne( "SELECT operation_id FROM account_selected_owner_intake_authorizations " @@ -1825,23 +1779,22 @@ private static void settleOriginal( captured.sources()) .withRequiredOwners(); issued.actors().claimOriginalDraft(issued.compact(), original, issued.environment()); - f.tx( - () -> { - for (var owner : original.requiredOwners()) { - f.fences.recordOwnerReadback( - original, - new DraftAuthorizationFenceBinding.OwnerReadback( - owner, - DraftAuthorizationFenceBinding.Outcome.COMMITTED, - original.operationId(), - original.commitId(), - original.fenceId(), - original.inputDigest(), - original.canonicalBytes(), - new byte[] {1})); - } - return null; - }); + f.tx(() -> { + for (var owner : original.requiredOwners()) { + f.fences.recordOwnerReadback( + original, + new DraftAuthorizationFenceBinding.OwnerReadback( + owner, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.canonicalBytes(), + new byte[] {1})); + } + return null; + }); } private static SelectedOwnerIntakeSourceContent content( @@ -1933,10 +1886,9 @@ private static TemplateConfigSourceSnapshot templateSnapshot( "0"))); TemplateConfigOwnerSourceInventoryDeclaration declaration = TemplateConfigSourceValues.mutations(authored).stream() - .filter( - mutation -> - mutation.operation() - == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .filter(mutation -> + mutation.operation() + == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) .findFirst() .orElseThrow(); @@ -1952,31 +1904,29 @@ private static SelectedOwnerIntakeAuthorizationBinding finalizeAutomationBinding String marker) { var f = issued.sources(); var scope = - asGameDesign( - () -> - reservationService.reserveSourceRead( - issued.compact(), - UUID.randomUUID(), - Owner.AUTOMATION_SCRIPTING, - selected, - issued.environment())); + asGameDesign(() -> + reservationService.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.AUTOMATION_SCRIPTING, + selected, + issued.environment())); var selectedContent = content(scope, marker); - return asGameDesign( - () -> - issued - .actors() - .withCurrent( - issued.compact(), - f.tenant, - issued.environment(), - current -> - repository.finalizeSourceRead( - scope, - selectedContent, - current, - () -> - f.fences.requireSelectedOwnerIntakeAdmission( - current.source().sources(), selected)))); + return asGameDesign(() -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, + selectedContent, + current, + () -> + f.fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected)))); } private static SelectedOwnerIntakeAuthorizationBinding finalizeEntityBinding( @@ -1987,31 +1937,29 @@ private static SelectedOwnerIntakeAuthorizationBinding finalizeEntityBinding( String marker) { var f = issued.sources(); var scope = - asGameDesign( - () -> - reservationService.reserveSourceRead( - issued.compact(), - UUID.randomUUID(), - Owner.ENTITY_MANAGEMENT, - selected, - issued.environment())); + asGameDesign(() -> + reservationService.reserveSourceRead( + issued.compact(), + UUID.randomUUID(), + Owner.ENTITY_MANAGEMENT, + selected, + issued.environment())); var selectedContent = content(scope, marker); - return asGameDesign( - () -> - issued - .actors() - .withCurrent( - issued.compact(), - f.tenant, - issued.environment(), - current -> - repository.finalizeSourceRead( - scope, - selectedContent, - current, - () -> - f.fences.requireSelectedOwnerIntakeAdmission( - current.source().sources(), selected)))); + return asGameDesign(() -> + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> + repository.finalizeSourceRead( + scope, + selectedContent, + current, + () -> + f.fences.requireSelectedOwnerIntakeAdmission( + current.source().sources(), selected)))); } private static void assertRejectedSettlementByPostgres( @@ -2021,26 +1969,23 @@ private static void assertRejectedSettlementByPostgres( byte[] changedOwnerReceiptBytes, String expectedDiagnostic) { var f = issued.sources(); - assertThatThrownBy( - () -> - f.tx( - () -> { - insertRawSettlement(f.dsl, binding, validEvidence, changedOwnerReceiptBytes); - return null; - })) + assertThatThrownBy(() -> + f.tx(() -> { + insertRawSettlement(f.dsl, binding, validEvidence, changedOwnerReceiptBytes); + return null; + })) .isInstanceOf(RuntimeException.class) - .satisfies( - failure -> { - Throwable root = failure; - while (root.getCause() != null) root = root.getCause(); - assertThat(root) - .isInstanceOfSatisfying( - java.sql.SQLException.class, - sql -> { - assertThat(sql.getSQLState()).isEqualTo("23514"); - assertThat(sql.getMessage()).contains(expectedDiagnostic); - }); - }); + .satisfies(failure -> { + Throwable root = failure; + while (root.getCause() != null) root = root.getCause(); + assertThat(root) + .isInstanceOfSatisfying( + java.sql.SQLException.class, + sql -> { + assertThat(sql.getSQLState()).isEqualTo("23514"); + assertThat(sql.getMessage()).contains(expectedDiagnostic); + }); + }); assertThat( f.dsl.fetchOne( "SELECT operation_id FROM account_selected_owner_intake_settlements " @@ -2116,26 +2061,23 @@ private static void assertRejectedSettlementByPostgres( byte[] changedOwnerReceiptBytes, String expectedDiagnostic) { var f = issued.sources(); - assertThatThrownBy( - () -> - f.tx( - () -> { - insertRawSettlement(f.dsl, binding, validEvidence, changedOwnerReceiptBytes); - return null; - })) + assertThatThrownBy(() -> + f.tx(() -> { + insertRawSettlement(f.dsl, binding, validEvidence, changedOwnerReceiptBytes); + return null; + })) .isInstanceOf(RuntimeException.class) - .satisfies( - failure -> { - Throwable root = failure; - while (root.getCause() != null) root = root.getCause(); - assertThat(root) - .isInstanceOfSatisfying( - java.sql.SQLException.class, - sql -> { - assertThat(sql.getSQLState()).isEqualTo("23514"); - assertThat(sql.getMessage()).contains(expectedDiagnostic); - }); - }); + .satisfies(failure -> { + Throwable root = failure; + while (root.getCause() != null) root = root.getCause(); + assertThat(root) + .isInstanceOfSatisfying( + java.sql.SQLException.class, + sql -> { + assertThat(sql.getSQLState()).isEqualTo("23514"); + assertThat(sql.getMessage()).contains(expectedDiagnostic); + }); + }); assertThat( f.dsl.fetchOne( "SELECT operation_id FROM account_selected_owner_intake_settlements " @@ -2291,19 +2233,18 @@ private static EntitySelectedSourceIntakeTerminalReadEvidence entityTerminalEvid binding, new SelectedOwnerWorldInventoryReadEvidence(request, inventory)); var states = ENTITY_FAMILIES.stream() - .map( - family -> - new FamilyCensus( - family, - FamilyState.EMPTY, - ENTITY_V1_FAMILIES.contains(family) - ? FamilyEvidenceKind.V1_SOURCE_CENSUS - : FamilyEvidenceKind.EMPTY_ONLY_OWNER_PROVIDER, - 0, - 0, - 0, - 0, - 0)) + .map(family -> + new FamilyCensus( + family, + FamilyState.EMPTY, + ENTITY_V1_FAMILIES.contains(family) + ? FamilyEvidenceKind.V1_SOURCE_CENSUS + : FamilyEvidenceKind.EMPTY_ONLY_OWNER_PROVIDER, + 0, + 0, + 0, + 0, + 0)) .toList(); var receipt = EntityEmptySelectedSourceIntakeReceipt.create( @@ -2487,15 +2428,14 @@ private static PublicEvidence publicInventory( 0, 0, selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .map(unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) .toList(), closure); var ownerScope = diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java index b4cf678e7c..724afa07dd 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java @@ -247,23 +247,22 @@ private static void assertInstalledOwnerReservationSchema(JdbcTemplate jdbc, Str private static void assertMalformedReservationCreatesNoSourceRows(JdbcTemplate jdbc) { UUID operationId = UUID.randomUUID(); - assertThatThrownBy( - () -> - jdbc.update( - "INSERT INTO account_selected_owner_intake_source_read_reservations (" - + "operation_id, fence_id, intake_request_id, owner, actor_account_uuid, " - + "tenant_uuid, version_uuid, scope_bytes, scope_digest, " - + "issuance_operation_id, issuance_fence, source_payload, issuance_bundle, " - + "outbox_checkpoints) VALUES (?, ?, ?, 'UNDECLARED_OWNER', ?, ?, ?, " - + "decode('00', 'hex'), 'sha256:' || repeat('0', 64), ?, 1, " - + "decode('7b7d', 'hex'), decode('7b7d', 'hex'), decode('7b7d', 'hex'))", - operationId, - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID())) + assertThatThrownBy(() -> + jdbc.update( + "INSERT INTO account_selected_owner_intake_source_read_reservations (" + + "operation_id, fence_id, intake_request_id, owner, actor_account_uuid, " + + "tenant_uuid, version_uuid, scope_bytes, scope_digest, " + + "issuance_operation_id, issuance_fence, source_payload, issuance_bundle, " + + "outbox_checkpoints) VALUES (?, ?, ?, 'UNDECLARED_OWNER', ?, ?, ?, " + + "decode('00', 'hex'), 'sha256:' || repeat('0', 64), ?, 1, " + + "decode('7b7d', 'hex'), decode('7b7d', 'hex'), decode('7b7d', 'hex'))", + operationId, + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID())) .isInstanceOf(RuntimeException.class); assertThat(count(jdbc, "account_selected_owner_intake_source_read_reservations")).isZero(); @@ -399,40 +398,37 @@ private static void assertDeferredCompletenessTriggerRejectsWrongScopeDigest( assertThat(wrongScopeDigest).matches("^sha256:[0-9a-f]{64}$").isNotEqualTo(correctScopeDigest); int[] insertedRows = {0}; - assertThatThrownBy( - () -> - transaction.execute( - status -> { - insertedRows[0] = - jdbc.update( - "INSERT INTO account_selected_owner_intake_source_read_reservations (" - + "operation_id, fence_id, intake_request_id, owner, actor_account_uuid, " - + "tenant_uuid, version_uuid, scope_bytes, scope_digest, " - + "issuance_operation_id, issuance_fence, source_payload, " - + "issuance_bundle, outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " - + "1, ?, ?, ?)", - operationId, - fenceId, - intakeRequestId, - scope.owner().name(), - actorAccountUuid, - tenantUuid, - versionUuid, - scope.canonicalBytes(), - wrongScopeDigest, - issuanceOperationId, - sourcePayload, - issuanceBundle, - outboxCheckpoints); - return null; - })) - .satisfies( - failure -> { - PSQLException postgresFailure = postgresException(failure); - assertThat(postgresFailure.getSQLState()).isEqualTo("23514"); - assertThat(postgresFailure.getServerErrorMessage().getMessage()) - .isEqualTo("Preliminary owner scope digest does not match canonical bytes"); - }); + assertThatThrownBy(() -> + transaction.execute(status -> { + insertedRows[0] = + jdbc.update( + "INSERT INTO account_selected_owner_intake_source_read_reservations (" + + "operation_id, fence_id, intake_request_id, owner, actor_account_uuid, " + + "tenant_uuid, version_uuid, scope_bytes, scope_digest, " + + "issuance_operation_id, issuance_fence, source_payload, " + + "issuance_bundle, outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "1, ?, ?, ?)", + operationId, + fenceId, + intakeRequestId, + scope.owner().name(), + actorAccountUuid, + tenantUuid, + versionUuid, + scope.canonicalBytes(), + wrongScopeDigest, + issuanceOperationId, + sourcePayload, + issuanceBundle, + outboxCheckpoints); + return null; + })) + .satisfies(failure -> { + PSQLException postgresFailure = postgresException(failure); + assertThat(postgresFailure.getSQLState()).isEqualTo("23514"); + assertThat(postgresFailure.getServerErrorMessage().getMessage()) + .isEqualTo("Preliminary owner scope digest does not match canonical bytes"); + }); assertThat(insertedRows[0]).isEqualTo(1); assertThat(ownerReservationRowCounts(jdbc)).isEqualTo(existingRows); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java index 886ca9b722..1c6a1d7ba5 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java @@ -221,17 +221,15 @@ public void attachAccountRedemptionProjection( assertThatThrownBy( () -> withPeer(WORLD_PEER_URI, () -> admissionAcquisition.acquire(request))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); assertThatThrownBy( () -> withPeer(GAME_SESSION_PEER_URI, () -> worldAcquisition.acquire(worldRequest))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); var acquired = withPeer(GAME_SESSION_PEER_URI, () -> admissionAcquisition.acquire(request)); assertThat(acquired.request().canonicalBytes()).containsExactly(request.canonicalBytes()); assertThat(acquired.accountProtectionId()).isNotEqualTo(new UUID(0L, 0L)); @@ -241,14 +239,13 @@ public void attachAccountRedemptionProjection( var protectionRepository = new AccountStartSessionAdmissionProtectionRepository(proof.sourceDsl()); var readback = - accountSources.transactions.execute( - ignored -> - protectionRepository - .findCurrentExact( - acquired.accountProtectionId(), - acquired.accountProtectionFence(), - request.canonicalBytes()) - .orElseThrow()); + accountSources.transactions.execute(ignored -> + protectionRepository + .findCurrentExact( + acquired.accountProtectionId(), + acquired.accountProtectionFence(), + request.canonicalBytes()) + .orElseThrow()); assertThat(readback.evidence().canonicalBytes()).containsExactly(acquired.canonicalBytes()); assertThat( proof @@ -278,10 +275,8 @@ public void attachAccountRedemptionProjection( participation.participation().participationFence(), changedHold); assertThat(changedRequest.canonicalBytes()).isNotEqualTo(request.canonicalBytes()); - assertThatThrownBy( - () -> - withPeer( - GAME_SESSION_PEER_URI, () -> admissionAcquisition.acquire(changedRequest))) + assertThatThrownBy(() -> + withPeer(GAME_SESSION_PEER_URI, () -> admissionAcquisition.acquire(changedRequest))) .isInstanceOf(IllegalStateException.class) .hasMessage( "Original StartSession admission protection conflicts with its immutable binding"); @@ -303,24 +298,20 @@ public void attachAccountRedemptionProjection( .sourceDsl() .fetchSingle("SELECT password_hash FROM accounts WHERE account_uuid = ?", accountId) .get("password_hash", String.class); - assertThatThrownBy( - () -> - accountSources.transactions.executeWithoutResult( - ignored -> - proof - .sourceDsl() - .execute( - "UPDATE accounts SET password_hash = password_hash || '-blocked' " - + "WHERE account_uuid = ?", - accountId))) - .satisfies( - failure -> { - SQLException sqlFailure = findSqlException(failure); - assertThat(sqlFailure.getSQLState()).isEqualTo("55P03"); - assertThat(sqlFailure.getMessage()) - .contains( - "StartSession World participation remains pending for a required source"); - }); + assertThatThrownBy(() -> + accountSources.transactions.executeWithoutResult(ignored -> + proof + .sourceDsl() + .execute( + "UPDATE accounts SET password_hash = password_hash || '-blocked' " + + "WHERE account_uuid = ?", + accountId))) + .satisfies(failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("55P03"); + assertThat(sqlFailure.getMessage()) + .contains("StartSession World participation remains pending for a required source"); + }); assertThat( proof .sourceDsl() @@ -336,39 +327,35 @@ public void attachAccountRedemptionProjection( String sourcePlaceholders = String.join(", ", java.util.Collections.nCopies(admissionSourceKeys.size(), "?")); Object[] sourceBindings = admissionSourceKeys.toArray(); - assertThatThrownBy( - () -> - accountSources.transactions.executeWithoutResult( - ignored -> { - var lockedKeys = - proof - .sourceDsl() - .fetch( - "SELECT source_key FROM account_draft_authorization_source_locks " - + "WHERE source_key IN (" - + sourcePlaceholders - + ") ORDER BY account_publication_authorization_source_sort_key(source_key) " - + "FOR UPDATE", - sourceBindings) - .getValues(0, String.class); - assertThat(lockedKeys) - .containsExactlyInAnyOrderElementsOf(admissionSourceKeys); - proof - .sourceDsl() - .execute( - "SELECT account_ss_admission_assert_no_pending(ARRAY[" - + sourcePlaceholders - + "]::text[])", - sourceBindings); - })) - .satisfies( - failure -> { - SQLException sqlFailure = findSqlException(failure); - assertThat(sqlFailure.getSQLState()).isEqualTo("55P03"); - assertThat(sqlFailure.getMessage()) - .contains( - "Original StartSession admission protection remains pending for a required source"); - }); + assertThatThrownBy(() -> + accountSources.transactions.executeWithoutResult(ignored -> { + var lockedKeys = + proof + .sourceDsl() + .fetch( + "SELECT source_key FROM account_draft_authorization_source_locks " + + "WHERE source_key IN (" + + sourcePlaceholders + + ") ORDER BY account_publication_authorization_source_sort_key(source_key) " + + "FOR UPDATE", + sourceBindings) + .getValues(0, String.class); + assertThat(lockedKeys).containsExactlyInAnyOrderElementsOf(admissionSourceKeys); + proof + .sourceDsl() + .execute( + "SELECT account_ss_admission_assert_no_pending(ARRAY[" + + sourcePlaceholders + + "]::text[])", + sourceBindings); + })) + .satisfies(failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("55P03"); + assertThat(sqlFailure.getMessage()) + .contains( + "Original StartSession admission protection remains pending for a required source"); + }); } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java index 317288a32f..45f440a2e1 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java @@ -103,73 +103,70 @@ void exactHistoricalRepositoryReadReconstructsProtectionAndTerminalBytes() { AccountStartSessionAdmissionProtectionSettlementEvidence.create( fixture.protection(), fixture.terminal()); - transaction.executeWithoutResult( - status -> { - dsl.execute("SET LOCAL session_replication_role = replica"); - insertCapture(dsl, fixture); - dsl.execute( - "INSERT INTO account_start_session_admission_protections " - + "(protection_id, protection_fence, control_plane_request_id, original_post_authorization_tuple, " - + "account_redemption_projection, game_session_owner_mutation_id, game_session_owner_attempt_id, " - + "game_session_owner_fence, original_lease_expires_at, account_world_participation_id, " - + "account_world_participation_fence, target_namespace, canonical_tenant_id, canonical_game_instance_id, " - + "capture_source_version, capture_source_fence, capture_sha256, world_admission_hold_identity_bytes, " - + "request_binding_bytes, request_binding_digest) OVERRIDING SYSTEM VALUE " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - fixture.protection().accountProtectionId(), - fixture.protection().accountProtectionFence(), - fixture.request().originalTuple().controlPlaneRequestId(), - fixture.request().originalPostAuthorizationTupleBytes(), - fixture.request().accountRedemptionProjectionBytes(), - fixture.request().gameSessionOwnerMutationId(), - fixture.request().gameSessionOwnerAttemptId(), - fixture.request().gameSessionOwnerFence(), - OffsetDateTime.ofInstant(fixture.request().originalLeaseExpiresAt(), ZoneOffset.UTC), - fixture.request().accountWorldParticipationId(), - fixture.request().accountWorldParticipationFence(), - NAMESPACE, - TENANT, - fixture.request().worldAdmissionHoldIdentity().request().canonicalGameInstanceId(), - 1L, - 1L, - digestHex(fixture.captureReference()), - fixture.request().worldAdmissionHoldIdentityBytes(), - fixture.request().canonicalBytes(), - digest(fixture.request().canonicalBytes())); - for (SourceEvidence evidence : fixture.protection().sourceEvidenceVector()) { - dsl.execute( - "INSERT INTO account_start_session_admission_protection_sources " - + "(protection_id, source_key, source_evidence) VALUES (?, ?, ?)", - fixture.protection().accountProtectionId(), - evidence.key(), - evidence.canonicalBytes()); - } - dsl.execute( - "INSERT INTO account_start_session_admission_protection_settlements " - + "(protection_id, outcome, terminal_bytes, terminal_digest) VALUES (?, ?, ?, ?)", - fixture.protection().accountProtectionId(), - settlement.outcome().name(), - settlement.canonicalBytes(), - settlement.digest()); - }); + transaction.executeWithoutResult(status -> { + dsl.execute("SET LOCAL session_replication_role = replica"); + insertCapture(dsl, fixture); + dsl.execute( + "INSERT INTO account_start_session_admission_protections " + + "(protection_id, protection_fence, control_plane_request_id, original_post_authorization_tuple, " + + "account_redemption_projection, game_session_owner_mutation_id, game_session_owner_attempt_id, " + + "game_session_owner_fence, original_lease_expires_at, account_world_participation_id, " + + "account_world_participation_fence, target_namespace, canonical_tenant_id, canonical_game_instance_id, " + + "capture_source_version, capture_source_fence, capture_sha256, world_admission_hold_identity_bytes, " + + "request_binding_bytes, request_binding_digest) OVERRIDING SYSTEM VALUE " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + fixture.protection().accountProtectionId(), + fixture.protection().accountProtectionFence(), + fixture.request().originalTuple().controlPlaneRequestId(), + fixture.request().originalPostAuthorizationTupleBytes(), + fixture.request().accountRedemptionProjectionBytes(), + fixture.request().gameSessionOwnerMutationId(), + fixture.request().gameSessionOwnerAttemptId(), + fixture.request().gameSessionOwnerFence(), + OffsetDateTime.ofInstant(fixture.request().originalLeaseExpiresAt(), ZoneOffset.UTC), + fixture.request().accountWorldParticipationId(), + fixture.request().accountWorldParticipationFence(), + NAMESPACE, + TENANT, + fixture.request().worldAdmissionHoldIdentity().request().canonicalGameInstanceId(), + 1L, + 1L, + digestHex(fixture.captureReference()), + fixture.request().worldAdmissionHoldIdentityBytes(), + fixture.request().canonicalBytes(), + digest(fixture.request().canonicalBytes())); + for (SourceEvidence evidence : fixture.protection().sourceEvidenceVector()) { + dsl.execute( + "INSERT INTO account_start_session_admission_protection_sources " + + "(protection_id, source_key, source_evidence) VALUES (?, ?, ?)", + fixture.protection().accountProtectionId(), + evidence.key(), + evidence.canonicalBytes()); + } + dsl.execute( + "INSERT INTO account_start_session_admission_protection_settlements " + + "(protection_id, outcome, terminal_bytes, terminal_digest) VALUES (?, ?, ?, ?)", + fixture.protection().accountProtectionId(), + settlement.outcome().name(), + settlement.canonicalBytes(), + settlement.digest()); + }); var repository = new AccountStartSessionAdmissionProtectionRepository(dsl); StoredProtection protection = - transaction.execute( - status -> - repository - .findHistoricalExact( - fixture.protection().accountProtectionId(), - fixture.protection().accountProtectionFence()) - .orElseThrow()); + transaction.execute(status -> + repository + .findHistoricalExact( + fixture.protection().accountProtectionId(), + fixture.protection().accountProtectionFence()) + .orElseThrow()); StoredSettlement storedSettlement = - transaction.execute( - status -> - repository - .findSettlementExact( - fixture.protection().accountProtectionId(), - fixture.protection().accountProtectionFence()) - .orElseThrow()); + transaction.execute(status -> + repository + .findSettlementExact( + fixture.protection().accountProtectionId(), + fixture.protection().accountProtectionFence()) + .orElseThrow()); assertThat(protection.evidence().canonicalBytes()) .containsExactly(fixture.protection().canonicalBytes()); @@ -210,42 +207,37 @@ void javaRepositoryAcquiresAndReadsUnderEnabledV1003SourceWriterGuards() { var attemptRepository = new AccountStartSessionWorldOriginalAttemptEvidenceRepository(dsl); var admissionRepository = new AccountStartSessionAdmissionProtectionRepository(dsl); var retainedParticipation = - transaction.execute( - ignored -> - participationRepository - .findHistoricalForOriginalTuple( - fixture.request().originalPostAuthorizationTupleBytes()) - .orElseThrow()); + transaction.execute(ignored -> + participationRepository + .findHistoricalForOriginalTuple( + fixture.request().originalPostAuthorizationTupleBytes()) + .orElseThrow()); assertThat(retainedParticipation.sources()).containsExactly(fixture.source()); var retainedAttempt = - transaction.execute( - ignored -> - attemptRepository - .findCurrentExact(retainedParticipation, fixture.attemptRequest()) - .orElseThrow()); + transaction.execute(ignored -> + attemptRepository + .findCurrentExact(retainedParticipation, fixture.attemptRequest()) + .orElseThrow()); assertThat(retainedAttempt.result().request()).isEqualTo(fixture.attemptRequest()); assertThat(retainedAttempt.result().accountRedemptionProjection()) .containsExactly(fixture.request().accountRedemptionProjectionBytes()); StoredProtection committed = - transaction.execute( - ignored -> - admissionRepository.acquireOrReadExact( - fixture.request(), fixture.capture(), retainedParticipation)); + transaction.execute(ignored -> + admissionRepository.acquireOrReadExact( + fixture.request(), fixture.capture(), retainedParticipation)); StoredProtection replayed = - transaction.execute( - ignored -> - admissionRepository.acquireOrReadExact( - fixture.request(), fixture.capture(), retainedParticipation)); + transaction.execute(ignored -> + admissionRepository.acquireOrReadExact( + fixture.request(), fixture.capture(), retainedParticipation)); StoredProtection readback = - transaction.execute( - ignored -> - admissionRepository - .findCurrentExact( - committed.evidence().accountProtectionId(), - committed.evidence().accountProtectionFence(), - fixture.request().canonicalBytes()) - .orElseThrow()); + transaction.execute(ignored -> + admissionRepository + .findCurrentExact( + committed.evidence().accountProtectionId(), + committed.evidence().accountProtectionFence(), + fixture.request().canonicalBytes()) + .orElseThrow()); assertThat(replayed.evidence().canonicalBytes()) .containsExactly(committed.evidence().canonicalBytes()); @@ -260,23 +252,21 @@ void javaRepositoryAcquiresAndReadsUnderEnabledV1003SourceWriterGuards() { // Direct installed admission-hook proof after canonical source-row locking. The older // World participation remains pending; this is not full writer causation after World // settlement. - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> { - var lockedKeys = - dsl.fetch( - "SELECT source_key FROM account_draft_authorization_source_locks " - + "WHERE source_key = ANY(ARRAY[?]::text[]) " - + "ORDER BY account_publication_authorization_source_sort_key(source_key) " - + "FOR UPDATE", - fixture.source().key()) - .getValues(0, String.class); - assertThat(lockedKeys).containsExactly(fixture.source().key()); - dsl.execute( - "SELECT account_ss_admission_assert_no_pending(ARRAY[?]::text[])", - fixture.source().key()); - })) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> { + var lockedKeys = + dsl.fetch( + "SELECT source_key FROM account_draft_authorization_source_locks " + + "WHERE source_key = ANY(ARRAY[?]::text[]) " + + "ORDER BY account_publication_authorization_source_sort_key(source_key) " + + "FOR UPDATE", + fixture.source().key()) + .getValues(0, String.class); + assertThat(lockedKeys).containsExactly(fixture.source().key()); + dsl.execute( + "SELECT account_ss_admission_assert_no_pending(ARRAY[?]::text[])", + fixture.source().key()); + })) .hasMessageContaining("Original StartSession admission protection remains pending"); AccountStartSessionAdmissionProtectionRequest changedRequest = @@ -290,14 +280,12 @@ void javaRepositoryAcquiresAndReadsUnderEnabledV1003SourceWriterGuards() { fixture.request().accountWorldParticipationId(), fixture.request().accountWorldParticipationFence(), fixture.request().worldAdmissionHoldIdentity()); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> - admissionRepository.findCurrentExact( - committed.evidence().accountProtectionId(), - committed.evidence().accountProtectionFence(), - changedRequest.canonicalBytes()))) + assertThatThrownBy(() -> + transaction.execute(ignored -> + admissionRepository.findCurrentExact( + committed.evidence().accountProtectionId(), + committed.evidence().accountProtectionFence(), + changedRequest.canonicalBytes()))) .hasMessageContaining("Original admission recovery binding differs"); } @@ -352,30 +340,28 @@ void settlementLocksCompleteCanonicalSourceSetBeforeProtectionAndRefusesMissingO dsl.configuration() .setAppending( new DefaultExecuteListenerProvider( - ExecuteListener.onResultEnd( - context -> { - String sql = context.sql(); - if (sql != null - && sql.contains("account_draft_authorization_source_locks") - && sql.contains("FOR UPDATE NOWAIT")) { - lockedSourceSets.add( - java.util.Objects.requireNonNull(context.result()) - .getValues(0, String.class)); - } - })), + ExecuteListener.onResultEnd(context -> { + String sql = context.sql(); + if (sql != null + && sql.contains("account_draft_authorization_source_locks") + && sql.contains("FOR UPDATE NOWAIT")) { + lockedSourceSets.add( + java.util.Objects.requireNonNull(context.result()) + .getValues(0, String.class)); + } + })), new DefaultExecuteListenerProvider( - ExecuteListener.onExecuteStart( - context -> { - String sql = context.sql(); - if (sql != null - && sql.contains("account_start_session_admission_protections") - && sql.contains("FOR UPDATE NOWAIT")) { - protectionLocks.add( - java.util.Objects.requireNonNull(context.query()) - .getBindValues() - .getFirst()); - } - }))); + ExecuteListener.onExecuteStart(context -> { + String sql = context.sql(); + if (sql != null + && sql.contains("account_start_session_admission_protections") + && sql.contains("FOR UPDATE NOWAIT")) { + protectionLocks.add( + java.util.Objects.requireNonNull(context.query()) + .getBindValues() + .getFirst()); + } + }))); dsl.execute( "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", last.key()); assertThatThrownBy( @@ -406,13 +392,12 @@ void settlementLocksCompleteCanonicalSourceSetBeforeProtectionAndRefusesMissingO assertThatThrownBy( () -> transaction.executeWithoutResult(ignored -> repository.settleExact(terminal))) .hasRootCauseInstanceOf(org.postgresql.util.PSQLException.class) - .satisfies( - failure -> { - Throwable root = failure; - while (root.getCause() != null) root = root.getCause(); - assertThat(((org.postgresql.util.PSQLException) root).getSQLState()) - .isEqualTo("55P03"); - }); + .satisfies(failure -> { + Throwable root = failure; + while (root.getCause() != null) root = root.getCause(); + assertThat(((org.postgresql.util.PSQLException) root).getSQLState()) + .isEqualTo("55P03"); + }); assertThat(protectionLocks).isEmpty(); holder.rollback(); } @@ -580,152 +565,151 @@ private static CurrentFixture seedControlledCurrentOwnerRows( OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(attemptResult).toByteArray(); CurrentFixture currentFixture = - transaction.execute( - status -> { - dsl.execute("SET LOCAL session_replication_role = replica"); - dsl.execute( - "INSERT INTO account_canonical_tenant_identity_claims " - + "(canonical_tenant_id, identity_kind, source_operation_id, " - + "source_account_legacy_tenant_id, source_target_namespace, " - + "source_game_row_id, source_game_tenant_key) VALUES (?, ?, ?, ?, ?, ?, ?)", - TENANT, - "APPROVED_RETAINED", - UUID.randomUUID(), - 1L, - NAMESPACE, - 1L, - TENANT.toString()); - dsl.execute( - "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", - sourceEvidence.key()); - dsl.execute( - "INSERT INTO account_start_session_authority_captures " - + "(control_plane_request_id, account_uuid, tenant_uuid, target_owner, " - + "logging_workload_uri, reservation_owner_id, reservation_claim_fence, " - + "pre_authorization_tuple, mutation_digest, control_ui_operation_id, " - + "control_ui_token_jti, control_ui_token_hash, " - + "control_ui_signer_receipt_sha256, issuance_fence, " - + "issuance_fence_source_version, captured_at, snapshot_sha256, " - + "canonical_snapshot_bytes, source_version, source_fence, linearization, " - + "canonical_sha256, canonical_capture_bytes) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?, ?, ?, ?, ?, ?)", - tuple.controlPlaneRequestId(), - ACCOUNT, - TENANT, - "game-session-service", - tuple.authenticatedWorkloadIdentity(), - reservationOwnerId, - tuple.reservationClaimFence(), - preTupleBytes, - tuple.mutationDigest(), - controlUiOperationId, - tokenJti, - tokenHash, - digestHex(signerReceipt), - Long.parseLong(tuple.issuanceFence()), - sourceVersion, - OffsetDateTime.ofInstant(capturedInstant, ZoneOffset.UTC), - capture.snapshotSha256(), - capture.snapshotBytes(), - capture.sourceVersion(), - capture.sourceFence(), - capture.linearization(), - capture.canonicalSha256(), - capture.canonicalBytes()); - dsl.execute( - "INSERT INTO account_start_session_operator_authorizations " - + "(control_plane_request_id, pre_authorization_tuple, mutation_digest, " - + "issuance_workload_uri, reservation_owner_id, reservation_claim_fence, " - + "issuance_operation_id, issuance_fence, bundle_version, bundle_source_version, " - + "bundle_source_fence, bundle_linearization, authority_evidence_bundle, " - + "authorization_reference_fingerprint, encrypted_response_envelope, issued_at, " - + "reference_expires_at, response_envelope_expires_at, status, " - + "redemption_redeemer_workload_uri, redemption_owner_attempt_id, " - + "redemption_owner_fence, redeemed_at, redemption_reference_fingerprint, " - + "redemption_authority_evidence_bundle) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), CAST(? AS TIMESTAMPTZ), CAST(? AS TIMESTAMPTZ), ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", - tuple.controlPlaneRequestId(), - preTupleBytes, - tuple.mutationDigest(), - tuple.authenticatedWorkloadIdentity(), - tuple.reservationOwnerId(), - tuple.reservationClaimFence(), - authorityBundle.issuanceOperationId(), - Long.parseLong(authorityBundle.issuanceFence()), - bundleReference.bundleVersion(), - bundleReference.sourceVersion(), - bundleReference.sourceFence(), - bundleReference.linearization(), - bundleBytes, - tuple.authorizationReferenceFingerprint(), - bytes("controlled owner response envelope"), - OffsetDateTime.ofInstant(databaseNow.minusSeconds(2L), ZoneOffset.UTC), - OffsetDateTime.ofInstant(referenceExpiry, ZoneOffset.UTC), - OffsetDateTime.ofInstant(referenceExpiry.plusSeconds(30L), ZoneOffset.UTC), - "REDEEMED", - "spiffe://firemud/ns/test/sa/game-session-service", - ownerAttemptId, - ownerFence, - OffsetDateTime.ofInstant(databaseNow.minusSeconds(1L), ZoneOffset.UTC), - tuple.authorizationReferenceFingerprint(), - bundleBytes); - dsl.execute( - "INSERT INTO account_start_session_world_participations " - + "(participation_id, control_plane_request_id, " - + "original_post_authorization_tuple, target_namespace, canonical_tenant_id, " - + "canonical_game_instance_id, game_session_owner_attempt_id, " - + "game_session_owner_fence, preparation_input_json, preparation_input_digest) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - participationId, - tuple.controlPlaneRequestId(), + transaction.execute(status -> { + dsl.execute("SET LOCAL session_replication_role = replica"); + dsl.execute( + "INSERT INTO account_canonical_tenant_identity_claims " + + "(canonical_tenant_id, identity_kind, source_operation_id, " + + "source_account_legacy_tenant_id, source_target_namespace, " + + "source_game_row_id, source_game_tenant_key) VALUES (?, ?, ?, ?, ?, ?, ?)", + TENANT, + "APPROVED_RETAINED", + UUID.randomUUID(), + 1L, + NAMESPACE, + 1L, + TENANT.toString()); + dsl.execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + sourceEvidence.key()); + dsl.execute( + "INSERT INTO account_start_session_authority_captures " + + "(control_plane_request_id, account_uuid, tenant_uuid, target_owner, " + + "logging_workload_uri, reservation_owner_id, reservation_claim_fence, " + + "pre_authorization_tuple, mutation_digest, control_ui_operation_id, " + + "control_ui_token_jti, control_ui_token_hash, " + + "control_ui_signer_receipt_sha256, issuance_fence, " + + "issuance_fence_source_version, captured_at, snapshot_sha256, " + + "canonical_snapshot_bytes, source_version, source_fence, linearization, " + + "canonical_sha256, canonical_capture_bytes) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?, ?, ?, ?, ?, ?)", + tuple.controlPlaneRequestId(), + ACCOUNT, + TENANT, + "game-session-service", + tuple.authenticatedWorkloadIdentity(), + reservationOwnerId, + tuple.reservationClaimFence(), + preTupleBytes, + tuple.mutationDigest(), + controlUiOperationId, + tokenJti, + tokenHash, + digestHex(signerReceipt), + Long.parseLong(tuple.issuanceFence()), + sourceVersion, + OffsetDateTime.ofInstant(capturedInstant, ZoneOffset.UTC), + capture.snapshotSha256(), + capture.snapshotBytes(), + capture.sourceVersion(), + capture.sourceFence(), + capture.linearization(), + capture.canonicalSha256(), + capture.canonicalBytes()); + dsl.execute( + "INSERT INTO account_start_session_operator_authorizations " + + "(control_plane_request_id, pre_authorization_tuple, mutation_digest, " + + "issuance_workload_uri, reservation_owner_id, reservation_claim_fence, " + + "issuance_operation_id, issuance_fence, bundle_version, bundle_source_version, " + + "bundle_source_fence, bundle_linearization, authority_evidence_bundle, " + + "authorization_reference_fingerprint, encrypted_response_envelope, issued_at, " + + "reference_expires_at, response_envelope_expires_at, status, " + + "redemption_redeemer_workload_uri, redemption_owner_attempt_id, " + + "redemption_owner_fence, redeemed_at, redemption_reference_fingerprint, " + + "redemption_authority_evidence_bundle) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), CAST(? AS TIMESTAMPTZ), CAST(? AS TIMESTAMPTZ), ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", + tuple.controlPlaneRequestId(), + preTupleBytes, + tuple.mutationDigest(), + tuple.authenticatedWorkloadIdentity(), + tuple.reservationOwnerId(), + tuple.reservationClaimFence(), + authorityBundle.issuanceOperationId(), + Long.parseLong(authorityBundle.issuanceFence()), + bundleReference.bundleVersion(), + bundleReference.sourceVersion(), + bundleReference.sourceFence(), + bundleReference.linearization(), + bundleBytes, + tuple.authorizationReferenceFingerprint(), + bytes("controlled owner response envelope"), + OffsetDateTime.ofInstant(databaseNow.minusSeconds(2L), ZoneOffset.UTC), + OffsetDateTime.ofInstant(referenceExpiry, ZoneOffset.UTC), + OffsetDateTime.ofInstant(referenceExpiry.plusSeconds(30L), ZoneOffset.UTC), + "REDEEMED", + "spiffe://firemud/ns/test/sa/game-session-service", + ownerAttemptId, + ownerFence, + OffsetDateTime.ofInstant(databaseNow.minusSeconds(1L), ZoneOffset.UTC), + tuple.authorizationReferenceFingerprint(), + bundleBytes); + dsl.execute( + "INSERT INTO account_start_session_world_participations " + + "(participation_id, control_plane_request_id, " + + "original_post_authorization_tuple, target_namespace, canonical_tenant_id, " + + "canonical_game_instance_id, game_session_owner_attempt_id, " + + "game_session_owner_fence, preparation_input_json, preparation_input_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + participationId, + tuple.controlPlaneRequestId(), + tupleBytes, + NAMESPACE, + TENANT, + gameInstanceId, + ownerAttemptId, + ownerFence, + "{}", + digest(bytes("{}"))); + long participationFence = + dsl.fetchSingle( + "SELECT participation_fence FROM account_start_session_world_participations " + + "WHERE participation_id = ?", + participationId) + .get(0, Long.class); + dsl.execute( + "INSERT INTO account_start_session_world_participation_sources " + + "(participation_id, source_key, source_evidence) VALUES (?, ?, ?)", + participationId, + sourceEvidence.key(), + sourceEvidence.canonicalBytes()); + dsl.execute( + "INSERT INTO account_start_session_world_original_attempt_evidence " + + "(participation_id, target_namespace, game_session_owner_attempt_id, " + + "game_session_owner_mutation_id, game_session_owner_fence, " + + "original_lease_expires_at, original_response_bytes, original_response_digest) " + + "VALUES (?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", + participationId, + NAMESPACE, + ownerAttemptId, + ownerMutationId, + ownerFence, + OffsetDateTime.ofInstant(originalLeaseExpiry, ZoneOffset.UTC), + attemptResponse, + digest(attemptResponse)); + var request = + AccountStartSessionAdmissionProtectionRequest.create( tupleBytes, - NAMESPACE, - TENANT, - gameInstanceId, + projection, + ownerMutationId, ownerAttemptId, ownerFence, - "{}", - digest(bytes("{}"))); - long participationFence = - dsl.fetchSingle( - "SELECT participation_fence FROM account_start_session_world_participations " - + "WHERE participation_id = ?", - participationId) - .get(0, Long.class); - dsl.execute( - "INSERT INTO account_start_session_world_participation_sources " - + "(participation_id, source_key, source_evidence) VALUES (?, ?, ?)", - participationId, - sourceEvidence.key(), - sourceEvidence.canonicalBytes()); - dsl.execute( - "INSERT INTO account_start_session_world_original_attempt_evidence " - + "(participation_id, target_namespace, game_session_owner_attempt_id, " - + "game_session_owner_mutation_id, game_session_owner_fence, " - + "original_lease_expires_at, original_response_bytes, original_response_digest) " - + "VALUES (?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", + originalLeaseExpiry, participationId, - NAMESPACE, - ownerAttemptId, - ownerMutationId, - ownerFence, - OffsetDateTime.ofInstant(originalLeaseExpiry, ZoneOffset.UTC), - attemptResponse, - digest(attemptResponse)); - var request = - AccountStartSessionAdmissionProtectionRequest.create( - tupleBytes, - projection, - ownerMutationId, - ownerAttemptId, - ownerFence, - originalLeaseExpiry, - participationId, - participationFence, - hold); - dsl.execute("SET LOCAL session_replication_role = origin"); - return new CurrentFixture(request, capture, sourceEvidence, attemptRequest); - }); + participationFence, + hold); + dsl.execute("SET LOCAL session_replication_role = origin"); + return new CurrentFixture(request, capture, sourceEvidence, attemptRequest); + }); return currentFixture; } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java index ea1e799ff4..41fb415a05 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java @@ -144,18 +144,17 @@ void migrationInstallsIndependentAllocatorsAndRejectsUnownedMutationAndTruncate( private static void assertGuardRejected( org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String expectedDiagnostic) { assertThatThrownBy(action) - .satisfies( - failure -> { - SQLException sqlFailure = findSqlException(failure); - assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); - if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { - throw new AssertionError( - "Capture guard rejection must be a PostgreSQL exception", sqlFailure); - } - var serverError = postgresFailure.getServerErrorMessage(); - assertThat(serverError).isNotNull(); - assertThat(serverError.getMessage()).isEqualTo(expectedDiagnostic); - }); + .satisfies(failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); + if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { + throw new AssertionError( + "Capture guard rejection must be a PostgreSQL exception", sqlFailure); + } + var serverError = postgresFailure.getServerErrorMessage(); + assertThat(serverError).isNotNull(); + assertThat(serverError.getMessage()).isEqualTo(expectedDiagnostic); + }); } private static SQLException findSqlException(Throwable failure) { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationPostgresIntegrationTest.java index 4c8a2fb06a..717bf66c2c 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationPostgresIntegrationTest.java @@ -418,24 +418,22 @@ void realAccountCaptureAndRedemptionBackExactParticipationAndTypedSettlement() t gameSessionOwnerFence, changedPreparation, digest(changedPreparation)); - assertThatThrownBy( - () -> - withWorldCurrentness( - operatorAuthorization, - originalTuple, - gameSessionAttemptId, - gameSessionOwnerFence, - ignored -> repository.createOrReadExact(changedCandidate))) + assertThatThrownBy(() -> + withWorldCurrentness( + operatorAuthorization, + originalTuple, + gameSessionAttemptId, + gameSessionOwnerFence, + ignored -> repository.createOrReadExact(changedCandidate))) .isInstanceOf(IllegalStateException.class) .hasMessage("StartSession World participation conflicts with its immutable binding"); - assertThatThrownBy( - () -> - withWorldCurrentness( - operatorAuthorization, - originalTuple, - UUID.randomUUID(), - gameSessionOwnerFence, - ignored -> repository.createOrReadExact(initialCandidate.get()))) + assertThatThrownBy(() -> + withWorldCurrentness( + operatorAuthorization, + originalTuple, + UUID.randomUUID(), + gameSessionOwnerFence, + ignored -> repository.createOrReadExact(initialCandidate.get()))) .isInstanceOf(IllegalStateException.class); assertThatThrownBy(() -> repository.createOrReadExact(initialCandidate.get())) @@ -444,11 +442,10 @@ void realAccountCaptureAndRedemptionBackExactParticipationAndTypedSettlement() t long fenceSequenceBeforeHistoricalRead = participationFenceSequence(account.dsl); StoredParticipation historical = - account.tx( - () -> - repository - .findHistoricalExact(first.participationId(), first.participationFence()) - .orElseThrow()); + account.tx(() -> + repository + .findHistoricalExact(first.participationId(), first.participationFence()) + .orElseThrow()); long fenceSequenceAfterHistoricalRead = participationFenceSequence(account.dsl); assertThat(historical.participationId()).isEqualTo(first.participationId()); assertThat(historical.participationFence()).isEqualTo(first.participationFence()); @@ -484,12 +481,10 @@ void realAccountCaptureAndRedemptionBackExactParticipationAndTypedSettlement() t assertThat(exactSettlementRetry.terminalDigest()).isEqualTo(committed.terminalDigest()); assertThat( account - .tx( - () -> - repository - .findSettlementExact( - first.participationId(), first.participationFence()) - .orElseThrow()) + .tx(() -> + repository + .findSettlementExact(first.participationId(), first.participationFence()) + .orElseThrow()) .terminalBytes()) .containsExactly(committed.terminalBytes()); @@ -506,12 +501,11 @@ void realAccountCaptureAndRedemptionBackExactParticipationAndTypedSettlement() t first.participationId()), "StartSession World participation evidence is append-only"); assertThat( - account.tx( - () -> - repository - .findSettlementExact(first.participationId(), first.participationFence()) - .orElseThrow() - .terminalBytes())) + account.tx(() -> + repository + .findSettlementExact(first.participationId(), first.participationFence()) + .orElseThrow() + .terminalBytes())) .containsExactly(committed.terminalBytes()); var absentParentTerminal = @@ -533,11 +527,10 @@ void realAccountCaptureAndRedemptionBackExactParticipationAndTypedSettlement() t .isInstanceOf(IllegalStateException.class) .hasMessage("Exact StartSession World participation evidence unavailable"); assertThat( - account.tx( - () -> - repository.findSettlementExact( - absentParentTerminal.accountWorldParticipationId(), - absentParentTerminal.accountWorldParticipationFence()))) + account.tx(() -> + repository.findSettlementExact( + absentParentTerminal.accountWorldParticipationId(), + absentParentTerminal.accountWorldParticipationFence()))) .isEmpty(); // The terminal is a typed test collaborator. Its validity proves Account storage binding, @@ -558,19 +551,18 @@ void realAccountCaptureAndRedemptionBackExactParticipationAndTypedSettlement() t private static void assertGuardRejected( org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String expectedDiagnostic) { assertThatThrownBy(action) - .satisfies( - failure -> { - SQLException sqlFailure = findSqlException(failure); - assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); - if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { - throw new AssertionError( - "Participation settlement guard rejection must be a PostgreSQL exception", - sqlFailure); - } - var serverError = postgresFailure.getServerErrorMessage(); - assertThat(serverError).isNotNull(); - assertThat(serverError.getMessage()).isEqualTo(expectedDiagnostic); - }); + .satisfies(failure -> { + SQLException sqlFailure = findSqlException(failure); + assertThat(sqlFailure.getSQLState()).isEqualTo("23514"); + if (!(sqlFailure instanceof org.postgresql.util.PSQLException postgresFailure)) { + throw new AssertionError( + "Participation settlement guard rejection must be a PostgreSQL exception", + sqlFailure); + } + var serverError = postgresFailure.getServerErrorMessage(); + assertThat(serverError).isNotNull(); + assertThat(serverError.getMessage()).isEqualTo(expectedDiagnostic); + }); } private static SQLException findSqlException(Throwable failure) { @@ -605,22 +597,21 @@ void predecessorScalarProjectionRemainsHistoricalAfterCurrentDefaultUpgrade() th // Controlled historical sender bytes, using the exact ccf0528c35^ scalar-v1 grammar. Account // issuance/redemption and the parent are actual owners; no current GS producer is asserted. // V160's intact parent/pending/lease/hash and append-only guards admit this predecessor row. - account.tx( - () -> { - account.dsl.execute( - "INSERT INTO account_start_session_world_original_attempt_evidence " - + "(participation_id,target_namespace,game_session_owner_attempt_id,game_session_owner_mutation_id,game_session_owner_fence,original_lease_expires_at,original_response_bytes,original_response_digest) " - + "VALUES (?,?,?,?,?,CAST(? AS TIMESTAMPTZ),?,?)", - parent.participationId(), - NAMESPACE, - original.attempt(), - request.expectedOwnerMutationId(), - original.ownerFence(), - OffsetDateTime.ofInstant(lease, java.time.ZoneOffset.UTC), - response, - responseDigest); - return null; - }); + account.tx(() -> { + account.dsl.execute( + "INSERT INTO account_start_session_world_original_attempt_evidence " + + "(participation_id,target_namespace,game_session_owner_attempt_id,game_session_owner_mutation_id,game_session_owner_fence,original_lease_expires_at,original_response_bytes,original_response_digest) " + + "VALUES (?,?,?,?,?,CAST(? AS TIMESTAMPTZ),?,?)", + parent.participationId(), + NAMESPACE, + original.attempt(), + request.expectedOwnerMutationId(), + original.ownerFence(), + OffsetDateTime.ofInstant(lease, java.time.ZoneOffset.UTC), + response, + responseDigest); + return null; + }); var before = retainedRows(account.dsl); account.upgradeToCurrent(); assertThat(retainedRows(account.dsl)).isEqualTo(before); @@ -636,12 +627,11 @@ void predecessorScalarProjectionRemainsHistoricalAfterCurrentDefaultUpgrade() th assertThat(historical.result().request()).isEqualTo(request); assertThat( account - .tx( - () -> - parentRepository - .findHistoricalExact( - parent.participationId(), parent.participationFence()) - .orElseThrow()) + .tx(() -> + parentRepository + .findHistoricalExact( + parent.participationId(), parent.participationFence()) + .orElseThrow()) .originalPostAuthorizationTuple()) .containsExactly(original.tuple().canonicalBytes()); assertThat( @@ -659,12 +649,11 @@ void predecessorScalarProjectionRemainsHistoricalAfterCurrentDefaultUpgrade() th .isInstanceOf(IllegalStateException.class) .hasMessage( "Original StartSession attempt evidence conflicts with its immutable binding"); - assertThatThrownBy( - () -> - OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( - request, - net.firedevops.firemud.gamesession.v1 - .ReadOriginalStartSessionCurrentAttemptResponse.parseFrom(response))) + assertThatThrownBy(() -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, + net.firedevops.firemud.gamesession.v1 + .ReadOriginalStartSessionCurrentAttemptResponse.parseFrom(response))) .isInstanceOf(IllegalArgumentException.class); assertThat(retainedRows(account.dsl)).isEqualTo(before); } @@ -770,23 +759,22 @@ void unsafeNumericPredecessorParentIsRetainedButNeverReinterpretedForTypedUse() () -> account.tx(() -> repository.findHistoricalForOriginalTuple(predecessorBytes))) .isInstanceOf(IllegalStateException.class) .hasMessage("Exact StartSession World participation evidence unavailable"); - assertThatThrownBy( - () -> - withWorldCurrentness( - original.authorizer(), - original.tuple(), - original.attempt(), - original.ownerFence(), - capture -> - repository.findCurrentExact( - candidate( - original.tuple(), - capture, - instance, - original.attempt(), - original.ownerFence(), - preparation, - preparationDigest)))) + assertThatThrownBy(() -> + withWorldCurrentness( + original.authorizer(), + original.tuple(), + original.attempt(), + original.ownerFence(), + capture -> + repository.findCurrentExact( + candidate( + original.tuple(), + capture, + instance, + original.attempt(), + original.ownerFence(), + preparation, + preparationDigest)))) .isInstanceOf(IllegalStateException.class) .hasMessage("Exact StartSession World participation evidence unavailable"); assertThatThrownBy(() -> StartSessionPostAuthorizationExecutionTuple.decode(predecessorBytes)) diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionPostgresIntegrationTest.java index 0b6d5c792c..542c5f09af 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionPostgresIntegrationTest.java @@ -94,35 +94,30 @@ void admittedTransactionHoldsActualIssuanceAgainstRecoveryFailureUpdate() { var binding = frozen(c, false); var executor = java.util.concurrent.Executors.newSingleThreadExecutor(); try { - c.tx( - () -> { - insertAdmission(c, binding); - java.util.concurrent.CompletableFuture.runAsync( - () -> - assertThatThrownBy( - () -> - c.tx( - () -> { - c.dsl.execute("SET LOCAL lock_timeout = '100ms'"); - var issuer = - new AccountControlUiIssuanceRepository(c.dsl); - return issuer.beginRecoveryFailure( - issuer.findToken(binding.tokenHash())); - })) - .isInstanceOf(DataAccessException.class), - executor) - .join(); - return null; - }); + c.tx(() -> { + insertAdmission(c, binding); + java.util.concurrent.CompletableFuture.runAsync( + () -> + assertThatThrownBy(() -> + c.tx(() -> { + c.dsl.execute("SET LOCAL lock_timeout = '100ms'"); + var issuer = new AccountControlUiIssuanceRepository(c.dsl); + return issuer.beginRecoveryFailure( + issuer.findToken(binding.tokenHash())); + })) + .isInstanceOf(DataAccessException.class), + executor) + .join(); + return null; + }); var issuer = new AccountControlUiIssuanceRepository(c.dsl); assertThat( c.tx(() -> issuer.beginRecoveryFailure(issuer.findToken(binding.tokenHash()))).status) .isEqualTo("REVOKING"); assertThat( - c.tx( - () -> - new AccountTenantCreationAdmissionRepository(c.dsl) - .readAdmitted(binding.creationOperationId()))) + c.tx(() -> + new AccountTenantCreationAdmissionRepository(c.dsl) + .readAdmitted(binding.creationOperationId()))) .isPresent(); } finally { executor.shutdownNow(); @@ -139,12 +134,11 @@ void exactFrozenDataRetryPreservesXminAndChangedTokenOrInputsCannotReplaceOrigin Objects.requireNonNull(c.dsl.fetchOne(query, binding.creationOperationId())) .get("xmin", String.class); assertThat( - c.tx( - () -> - c.dsl.execute( - "INSERT INTO account_tenant_creation_admission_requests SELECT * FROM account_tenant_creation_admission_requests " - + "WHERE creation_operation_id = ? ON CONFLICT DO NOTHING", - binding.creationOperationId()))) + c.tx(() -> + c.dsl.execute( + "INSERT INTO account_tenant_creation_admission_requests SELECT * FROM account_tenant_creation_admission_requests " + + "WHERE creation_operation_id = ? ON CONFLICT DO NOTHING", + binding.creationOperationId()))) .isZero(); assertThat( Objects.requireNonNull(c.dsl.fetchOne(query, binding.creationOperationId())) @@ -155,25 +149,22 @@ void exactFrozenDataRetryPreservesXminAndChangedTokenOrInputsCannotReplaceOrigin "token_hash", "target_namespace", "intent_digest", "reauthentication_evidence_id")) { String changed = field.equals("reauthentication_evidence_id") ? UUID.randomUUID().toString() : "changed"; - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - "INSERT INTO account_tenant_creation_admission_requests " - + "SELECT (jsonb_populate_record(NULL::account_tenant_creation_admission_requests, " - + "to_jsonb(r) || jsonb_build_object(?::text, ?::text))).* " - + "FROM account_tenant_creation_admission_requests r WHERE creation_operation_id = ?", - field, - changed, - binding.creationOperationId()))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + "INSERT INTO account_tenant_creation_admission_requests " + + "SELECT (jsonb_populate_record(NULL::account_tenant_creation_admission_requests, " + + "to_jsonb(r) || jsonb_build_object(?::text, ?::text))).* " + + "FROM account_tenant_creation_admission_requests r WHERE creation_operation_id = ?", + field, + changed, + binding.creationOperationId()))) .isInstanceOf(DataAccessException.class); } assertThat( - c.tx( - () -> - new AccountTenantCreationAdmissionRepository(c.dsl) - .readPrepared(binding.creationOperationId())) + c.tx(() -> + new AccountTenantCreationAdmissionRepository(c.dsl) + .readPrepared(binding.creationOperationId())) .orElseThrow() .binding()) .isEqualTo(binding); @@ -190,10 +181,9 @@ void earlierActualRecoveryFailureDeniesAdmissionDespiteUnchangedStoredActiveRegi .containsExactly(active); assertThatThrownBy(() -> insertAdmission(c, binding)).isInstanceOf(DataAccessException.class); assertThat( - c.tx( - () -> - new AccountTenantCreationAdmissionRepository(c.dsl) - .readAdmitted(binding.creationOperationId()))) + c.tx(() -> + new AccountTenantCreationAdmissionRepository(c.dsl) + .readAdmitted(binding.creationOperationId()))) .isEmpty(); } @@ -209,28 +199,24 @@ void logicalExpiryDeniesEvenWhilePhysicalCleanupDeadlineLives() { void directSqlCannotChangeBindingTupleReceiptOrRetainedRows() { Context c = context(); var binding = frozen(c, false); - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - "INSERT INTO account_tenant_creation_admissions " - + "(creation_operation_id, receipt_payload, receipt_digest, local_aof_count, replica_aof_count, protected_binding_id, qualification_fence) " - + "VALUES (?, ?, ?, 1, 1, 'test-stipulated', 1)", - binding.creationOperationId(), - "changed".getBytes(StandardCharsets.UTF_8), - AccountControlUiCoordination.digest( - "SHA-256", "changed".getBytes(StandardCharsets.UTF_8))))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + "INSERT INTO account_tenant_creation_admissions " + + "(creation_operation_id, receipt_payload, receipt_digest, local_aof_count, replica_aof_count, protected_binding_id, qualification_fence) " + + "VALUES (?, ?, ?, 1, 1, 'test-stipulated', 1)", + binding.creationOperationId(), + "changed".getBytes(StandardCharsets.UTF_8), + AccountControlUiCoordination.digest( + "SHA-256", "changed".getBytes(StandardCharsets.UTF_8))))) .isInstanceOf(DataAccessException.class); for (String field : List.of("token_hash", "target_namespace", "intent_digest")) { - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - "UPDATE account_tenant_creation_admission_requests SET " - + field - + " = 'changed'"))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + "UPDATE account_tenant_creation_admission_requests SET " + + field + + " = 'changed'"))) .isInstanceOf(DataAccessException.class); } insertAdmission(c, binding); @@ -242,12 +228,10 @@ void directSqlCannotChangeBindingTupleReceiptOrRetainedRows() { assertThatThrownBy(() -> c.tx(() -> c.dsl.execute("TRUNCATE " + table + " CASCADE"))) .isInstanceOf(DataAccessException.class); } - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - "UPDATE account_tenant_creation_admissions SET qualification_fence = qualification_fence + 1"))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + "UPDATE account_tenant_creation_admissions SET qualification_fence = qualification_fence + 1"))) .isInstanceOf(DataAccessException.class); } @@ -267,10 +251,9 @@ void admissionRequiresExactLocalAndPositiveReplicaAofAndRetainsSuccessfulEvidenc insertAdmission(c, admittedBinding); String admittedXmin = xmin(c, admittedBinding.creationOperationId()); byte[] admittedReceipt = - c.tx( - () -> - new AccountTenantCreationAdmissionRepository(c.dsl) - .readAdmitted(admittedBinding.creationOperationId())) + c.tx(() -> + new AccountTenantCreationAdmissionRepository(c.dsl) + .readAdmitted(admittedBinding.creationOperationId())) .orElseThrow() .receiptPayload(); long requestRowsBefore = @@ -328,17 +311,16 @@ private static void insertAdmission(Context c, AccountTenantCreationAdmissionBin private static void insertAdmission( Context c, AccountTenantCreationAdmissionBinding binding, int localAof, int replicaAof) { - c.tx( - () -> - c.dsl.execute( - "INSERT INTO account_tenant_creation_admissions " - + "(creation_operation_id, receipt_payload, receipt_digest, local_aof_count, replica_aof_count, protected_binding_id, qualification_fence) " - + "VALUES (?, ?, ?, ?, ?, 'test-stipulated-physical-evidence', 7)", - binding.creationOperationId(), - binding.canonicalReceipt(), - AccountControlUiCoordination.digest("SHA-256", binding.canonicalReceipt()), - localAof, - replicaAof)); + c.tx(() -> + c.dsl.execute( + "INSERT INTO account_tenant_creation_admissions " + + "(creation_operation_id, receipt_payload, receipt_digest, local_aof_count, replica_aof_count, protected_binding_id, qualification_fence) " + + "VALUES (?, ?, ?, ?, ?, 'test-stipulated-physical-evidence', 7)", + binding.creationOperationId(), + binding.canonicalReceipt(), + AccountControlUiCoordination.digest("SHA-256", binding.canonicalReceipt()), + localAof, + replicaAof)); } private record AofCounts(int local, int replicas) {} @@ -349,24 +331,23 @@ private static AccountTenantCreationAdmissionBinding frozen(Context c, boolean e var evidence = c.service.reauthenticate(c.request(account, UUID.randomUUID(), creation, PASSWORD)); var intent = - c.tx( - () -> - new AccountTenantCreationIntentRepository(c.dsl, c.evidenceRepository) - .claim( - new AccountTenantCreationIntentRepository.Request( - UUID.randomUUID(), - creation, - UUID.randomUUID(), - account.getAccountUuid(), - "test-game", - "source-game", - "Game", - null, - evidence.evidenceId(), - UUID.randomUUID(), - UUID.randomUUID(), - 1, - true))); + c.tx(() -> + new AccountTenantCreationIntentRepository(c.dsl, c.evidenceRepository) + .claim( + new AccountTenantCreationIntentRepository.Request( + UUID.randomUUID(), + creation, + UUID.randomUUID(), + account.getAccountUuid(), + "test-game", + "source-game", + "Game", + null, + evidence.evidenceId(), + UUID.randomUUID(), + UUID.randomUUID(), + 1, + true))); UUID issuance = UUID.randomUUID(); String tokenHash = AccountControlUiCoordination.digest( @@ -375,52 +356,48 @@ private static AccountTenantCreationAdmissionBinding frozen(Context c, boolean e long issued = Instant.now().getEpochSecond() - (expired ? 301 : 0); long expiry = (issued + 300) * 1000; long prepared = issued * 1000; - c.tx( - () -> - c.dsl.execute( - "INSERT INTO account_control_ui_issuance_operations " - + "(request_id, operation_id, token_jti, account_uuid, tenant_uuid, authorization_scope, caller_workload, " - + "caller_context_id, request_mac_key_id, request_digest, claims_payload, source_payload, bundle_payload, signer_receipt, " - + "issued_at_epoch_second, expires_at_epoch_second, registry_cleanup_deadline_epoch_millis, recovery_expires_at, status) " - + "VALUES (?, ?, ?, ?, NULL, 'ACCOUNT', 'spiffe://test-only/creation', ?, 'test-mac', ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, 'PREPARED')", - UUID.randomUUID(), - issuance, - UUID.randomUUID(), - account.getAccountUuid(), - UUID.randomUUID(), - "c".repeat(64), - active, - active, - active, - active, - issued, - issued + 300, - expiry + 300000, - OffsetDateTime.ofInstant(Instant.ofEpochSecond(issued + 60), ZoneOffset.UTC))); - c.tx( - () -> - c.dsl.execute( - "UPDATE account_control_ui_issuance_operations SET status = 'CANDIDATE', token_hash = ?, " - + "pending_registry = ?, active_registry = ? WHERE operation_id = ?", - tokenHash, - active, - active, - issuance)); - c.tx( - () -> - c.dsl.execute( - "INSERT INTO account_control_ui_response_envelopes (operation_id, encrypted_response, owner_binding, recovery_expires_at) " - + "SELECT operation_id, ?, ?, recovery_expires_at FROM account_control_ui_issuance_operations WHERE operation_id = ?", - active, - active, - issuance)); - c.tx( - () -> - c.dsl.execute( - "UPDATE account_control_ui_issuance_operations SET status = 'COMMITTED', pending_receipt = ?, " - + "committed_at = CURRENT_TIMESTAMP WHERE operation_id = ?", - active, - issuance)); + c.tx(() -> + c.dsl.execute( + "INSERT INTO account_control_ui_issuance_operations " + + "(request_id, operation_id, token_jti, account_uuid, tenant_uuid, authorization_scope, caller_workload, " + + "caller_context_id, request_mac_key_id, request_digest, claims_payload, source_payload, bundle_payload, signer_receipt, " + + "issued_at_epoch_second, expires_at_epoch_second, registry_cleanup_deadline_epoch_millis, recovery_expires_at, status) " + + "VALUES (?, ?, ?, ?, NULL, 'ACCOUNT', 'spiffe://test-only/creation', ?, 'test-mac', ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, 'PREPARED')", + UUID.randomUUID(), + issuance, + UUID.randomUUID(), + account.getAccountUuid(), + UUID.randomUUID(), + "c".repeat(64), + active, + active, + active, + active, + issued, + issued + 300, + expiry + 300000, + OffsetDateTime.ofInstant(Instant.ofEpochSecond(issued + 60), ZoneOffset.UTC))); + c.tx(() -> + c.dsl.execute( + "UPDATE account_control_ui_issuance_operations SET status = 'CANDIDATE', token_hash = ?, " + + "pending_registry = ?, active_registry = ? WHERE operation_id = ?", + tokenHash, + active, + active, + issuance)); + c.tx(() -> + c.dsl.execute( + "INSERT INTO account_control_ui_response_envelopes (operation_id, encrypted_response, owner_binding, recovery_expires_at) " + + "SELECT operation_id, ?, ?, recovery_expires_at FROM account_control_ui_issuance_operations WHERE operation_id = ?", + active, + active, + issuance)); + c.tx(() -> + c.dsl.execute( + "UPDATE account_control_ui_issuance_operations SET status = 'COMMITTED', pending_receipt = ?, " + + "committed_at = CURRENT_TIMESTAMP WHERE operation_id = ?", + active, + issuance)); var binding = new AccountTenantCreationAdmissionBinding( intent.requestId(), @@ -439,33 +416,32 @@ private static AccountTenantCreationAdmissionBinding frozen(Context c, boolean e prepared, expiry, expiry + 86400000); - c.tx( - () -> - c.dsl.execute( - "INSERT INTO account_tenant_creation_admission_requests " - + "(creation_operation_id, intent_request_id, issuance_operation_id, actor_account_id, target_namespace, " - + "game_design_creation_request_id, game_design_request_digest, intent_digest, active_registry_digest, " - + "reauthentication_evidence_id, token_hash, token_cleanup_deadline_epoch_millis, token_expires_at_epoch_millis, " - + "prepared_at_epoch_millis, operation_deadline_epoch_millis, receipt_cleanup_deadline_epoch_millis, binding_payload, binding_digest) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - creation, - intent.requestId(), - issuance, - account.getAccountUuid(), - binding.targetNamespace(), - binding.gameDesignCreationRequestId(), - binding.gameDesignRequestDigest(), - binding.intentDigest(), - binding.activeRegistryDigest(), - evidence.evidenceId(), - tokenHash, - binding.tokenCleanupDeadlineEpochMillis(), - expiry, - prepared, - expiry, - binding.receiptCleanupDeadlineEpochMillis(), - binding.canonicalReceipt(), - AccountControlUiCoordination.digest("SHA-256", binding.canonicalReceipt()))); + c.tx(() -> + c.dsl.execute( + "INSERT INTO account_tenant_creation_admission_requests " + + "(creation_operation_id, intent_request_id, issuance_operation_id, actor_account_id, target_namespace, " + + "game_design_creation_request_id, game_design_request_digest, intent_digest, active_registry_digest, " + + "reauthentication_evidence_id, token_hash, token_cleanup_deadline_epoch_millis, token_expires_at_epoch_millis, " + + "prepared_at_epoch_millis, operation_deadline_epoch_millis, receipt_cleanup_deadline_epoch_millis, binding_payload, binding_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + creation, + intent.requestId(), + issuance, + account.getAccountUuid(), + binding.targetNamespace(), + binding.gameDesignCreationRequestId(), + binding.gameDesignRequestDigest(), + binding.intentDigest(), + binding.activeRegistryDigest(), + evidence.evidenceId(), + tokenHash, + binding.tokenCleanupDeadlineEpochMillis(), + expiry, + prepared, + expiry, + binding.receiptCleanupDeadlineEpochMillis(), + binding.canonicalReceipt(), + AccountControlUiCoordination.digest("SHA-256", binding.canonicalReceipt()))); return binding; } @@ -487,16 +463,15 @@ private static Context context() { var manager = new DataSourceTransactionManager(source); var transaction = new TransactionTemplate(manager); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - transaction.executeWithoutResult( - ignored -> { - dsl.execute( - "INSERT INTO account_recent_reauthentication_policy_values " - + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " - + "VALUES ('PLATFORM', 1, 300, 30), ('DEPLOYMENT', 1, 300, 30)"); - dsl.execute( - "INSERT INTO account_recent_reauthentication_policy_current " - + "(policy_scope, policy_version) VALUES ('PLATFORM', 1), ('DEPLOYMENT', 1)"); - }); + transaction.executeWithoutResult(ignored -> { + dsl.execute( + "INSERT INTO account_recent_reauthentication_policy_values " + + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " + + "VALUES ('PLATFORM', 1, 300, 30), ('DEPLOYMENT', 1, 300, 30)"); + dsl.execute( + "INSERT INTO account_recent_reauthentication_policy_current " + + "(policy_scope, policy_version) VALUES ('PLATFORM', 1), ('DEPLOYMENT', 1)"); + }); var generations = new AccountAuthorityGenerationRepository(dsl); var outbox = new AccountAuthorityOutboxRepository(dsl); var sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionRedisIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionRedisIntegrationTest.java index 8026c2de82..54a482fd73 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionRedisIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionRedisIntegrationTest.java @@ -221,23 +221,21 @@ void denyFirstAndConcurrentRevocationHaveOnlyAtomicOriginalOutcomes() throws Exc var start = new CountDownLatch(1); try (var pool = Executors.newFixedThreadPool(2)) { var creation = - pool.submit( - () -> { - ready.countDown(); - await(start); - try { - return client.withInitialReceipt(f.binding, f.active, receipt -> true); - } catch (IllegalStateException refused) { - return false; - } - }); + pool.submit(() -> { + ready.countDown(); + await(start); + try { + return client.withInitialReceipt(f.binding, f.active, receipt -> true); + } catch (IllegalStateException refused) { + return false; + } + }); var revocation = - pool.submit( - () -> { - ready.countDown(); - await(start); - return revoke(f); - }); + pool.submit(() -> { + ready.countDown(); + await(start); + return revoke(f); + }); assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); start.countDown(); assertThat(revocation.get(10, TimeUnit.SECONDS)).isEqualTo(1L); @@ -329,10 +327,8 @@ void missingPendingMalformedAndChangedTokenOrPhysicalExpiryCannotCreateReceipt() bytes(wrongExpiry.tokenKey()), wrongExpiry.binding.tokenCleanupDeadlineEpochMillis() + 1L); } - assertThatThrownBy( - () -> - client.withInitialReceipt( - wrongExpiry.binding, wrongExpiry.active, receipt -> true)) + assertThatThrownBy(() -> + client.withInitialReceipt(wrongExpiry.binding, wrongExpiry.active, receipt -> true)) .isInstanceOf(IllegalStateException.class); assertThat(get(wrongExpiry.receiptKey())).isNull(); } @@ -427,11 +423,10 @@ void insufficientPhysicalAofAckAndDroppedSufficientReplyCannotReachCallback() { seed(f, f.active); var called = new AtomicBoolean(); try (var provider = provider(USER, PASSWORD)) { - assertThatThrownBy( - () -> - client(provider, 2, Clock.systemUTC()) - .withInitialReceipt( - f.binding, f.active, receipt -> called.compareAndSet(false, true))) + assertThatThrownBy(() -> + client(provider, 2, Clock.systemUTC()) + .withInitialReceipt( + f.binding, f.active, receipt -> called.compareAndSet(false, true))) .isInstanceOf(IllegalStateException.class); assertThat(called).isFalse(); assertReceipt(f); @@ -439,10 +434,9 @@ void insufficientPhysicalAofAckAndDroppedSufficientReplyCannotReachCallback() { var dropped = new AtomicBoolean(); AccountCoordinationPinnedConnectionProvider dropping = () -> dropAofReply(provider.openPinnedConnection(), dropped); - assertThatThrownBy( - () -> - client(dropping, 1, Clock.systemUTC()) - .withExistingReceipt(f.binding, receipt -> called.compareAndSet(false, true))) + assertThatThrownBy(() -> + client(dropping, 1, Clock.systemUTC()) + .withExistingReceipt(f.binding, receipt -> called.compareAndSet(false, true))) .isInstanceOf(IllegalStateException.class); assertThat(dropped).isTrue(); assertThat(called).isFalse(); @@ -459,10 +453,9 @@ void unavailableIndependentReadbackAndWrongPrincipalPreserveNonadmittingOriginal seed(f, f.active); try (var provider = provider(USER, PASSWORD); var wrong = provider(WRONG_USER, WRONG_PASSWORD)) { - assertThatThrownBy( - () -> - client(wrong, 1, Clock.systemUTC()) - .withInitialReceipt(f.binding, f.active, receipt -> true)) + assertThatThrownBy(() -> + client(wrong, 1, Clock.systemUTC()) + .withInitialReceipt(f.binding, f.active, receipt -> true)) .isInstanceOf(IllegalStateException.class); assertThat(get(f.receiptKey())).isNull(); var opened = new AtomicInteger(); @@ -473,11 +466,10 @@ void unavailableIndependentReadbackAndWrongPrincipalPreserveNonadmittingOriginal return provider.openPinnedConnection(); }; var called = new AtomicBoolean(); - assertThatThrownBy( - () -> - client(interrupted, 1, Clock.systemUTC()) - .withInitialReceipt( - f.binding, f.active, receipt -> called.compareAndSet(false, true))) + assertThatThrownBy(() -> + client(interrupted, 1, Clock.systemUTC()) + .withInitialReceipt( + f.binding, f.active, receipt -> called.compareAndSet(false, true))) .isInstanceOf(IllegalStateException.class); assertThat(opened).hasValue(2); assertThat(called).isFalse(); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java index 0def873ad4..980b0fb520 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionPostgresIntegrationTest.java @@ -253,11 +253,10 @@ void downstreamBootstrapRefusalRollsBackActualIdentityAndTenantGenerationTogethe when(dsl.fetchOne("SELECT clock_timestamp() AS observed_at")).thenReturn(ownerClock); var actors = mock(AccountControlUiActorService.class); when(actors.readAcceptedSignerKey("kid")) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return new AccountControlUiActorService.AcceptedSignerKey("kid", "fingerprint"); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new AccountControlUiActorService.AcceptedSignerKey("kid", "fingerprint"); + }); var captured = mock(AccountTenantCreationOwnerSourceCapture.Captured.class); when(captured.originalClaims()).thenReturn(issuance.claims); when(captured.originalSignerReceipt()).thenReturn(signer); @@ -272,17 +271,16 @@ void downstreamBootstrapRefusalRollsBackActualIdentityAndTenantGenerationTogethe when(dsl.fetchOne("SELECT txid_current()::text AS owner_transaction")).thenReturn(transaction); var bootstrap = mock(AccountTenantCreationBootstrapService.class); when(bootstrap.bootstrapForCompletion(any(), any())) - .thenAnswer( - invocation -> { - assertThat(actual.fetchCount(DSL.table("account_fresh_tenant_identity_associations"))) - .isEqualTo(1); - assertThat( - actual.fetchCount( - DSL.table("account_authority_generations"), - DSL.field("tenant_uuid").eq(tenant))) - .isEqualTo(1); - throw new IllegalStateException("Controlled downstream bootstrap refusal"); - }); + .thenAnswer(invocation -> { + assertThat(actual.fetchCount(DSL.table("account_fresh_tenant_identity_associations"))) + .isEqualTo(1); + assertThat( + actual.fetchCount( + DSL.table("account_authority_generations"), + DSL.field("tenant_uuid").eq(tenant))) + .isEqualTo(1); + throw new IllegalStateException("Controlled downstream bootstrap refusal"); + }); var owner = new AccountTenantCreationCompletionOwner( dsl, @@ -301,13 +299,12 @@ void downstreamBootstrapRefusalRollsBackActualIdentityAndTenantGenerationTogethe recentEvidence, mock(AccountAuditOutboxRepository.class), manager); - assertThatThrownBy( - () -> - owner.complete( - operation, - terminal, - mock(CapturedEnvironmentBoundary.class), - mock(AccountRecentReauthenticationEvidence.class))) + assertThatThrownBy(() -> + owner.complete( + operation, + terminal, + mock(CapturedEnvironmentBoundary.class), + mock(AccountRecentReauthenticationEvidence.class))) .isInstanceOf(IllegalStateException.class) .hasMessage("Controlled downstream bootstrap refusal"); assertThat(actual.fetchCount(DSL.table("account_fresh_tenant_identity_associations"))).isZero(); @@ -563,18 +560,15 @@ void capacityChangedAttemptConflictsWithoutUsageMutationAndIncompleteLedgerCanno f.request.capacityDelta(), null) .withDigest(); - assertThatThrownBy( - () -> - f.context.transaction.execute( - status -> f.repository.exact(changed, f.repository.find(changed.identity())))) + assertThatThrownBy(() -> + f.context.transaction.execute( + status -> f.repository.exact(changed, f.repository.find(changed.identity())))) .hasMessage("IDEMPOTENCY_CONFLICT"); - assertThatThrownBy( - () -> - f.context.transaction.executeWithoutResult( - status -> - f.context.dsl.execute( - "UPDATE account_tenant_capacity_usage SET held_units = held_units + 1, usage_revision = usage_revision + 1 WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", - f.request.identity().tenantId()))) + assertThatThrownBy(() -> + f.context.transaction.executeWithoutResult(status -> + f.context.dsl.execute( + "UPDATE account_tenant_capacity_usage SET held_units = held_units + 1, usage_revision = usage_revision + 1 WHERE tenant_uuid = ? AND owner_service = 'world-management-service'", + f.request.identity().tenantId()))) .isInstanceOf(RuntimeException.class); assertThat( Objects.requireNonNull( @@ -848,28 +842,25 @@ private static CapacityPersistenceFixture capacityPersistenceFixture(boolean exp var repository = new net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository(c.dsl); var initial = - c.transaction.execute( - status -> { - // Controlled fixture evidence deliberately bypasses the absent World producer. - // Production - // has no route to perform this insertion and World admission remains unavailable. - c.dsl.execute( - "INSERT INTO account_tenant_capacity_evaluations (evaluation_identity, snapshot_identity, tenant_uuid, caller_workload, owner_service, canonical_evidence, evaluated_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz)", - evidence.evaluationIdentity(), - evidence.snapshotIdentity(), - tenant, - evidence.callerWorkload(), - evidence.owner().service(), - evidence.canonicalBytes(), - net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository - .at(evidence.evaluatedAt()), - net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository - .at(evidence.expiresAt())); - return repository.create( - request, - evidence.expiresAt(), - Clock.fixed(evidence.evaluatedAt(), ZoneOffset.UTC)); - }); + c.transaction.execute(status -> { + // Controlled fixture evidence deliberately bypasses the absent World producer. + // Production + // has no route to perform this insertion and World admission remains unavailable. + c.dsl.execute( + "INSERT INTO account_tenant_capacity_evaluations (evaluation_identity, snapshot_identity, tenant_uuid, caller_workload, owner_service, canonical_evidence, evaluated_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?::timestamptz, ?::timestamptz)", + evidence.evaluationIdentity(), + evidence.snapshotIdentity(), + tenant, + evidence.callerWorkload(), + evidence.owner().service(), + evidence.canonicalBytes(), + net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.at( + evidence.evaluatedAt()), + net.firedevops.firemud.accountservice.repository.AccountTenantCapacityRepository.at( + evidence.expiresAt())); + return repository.create( + request, evidence.expiresAt(), Clock.fixed(evidence.evaluatedAt(), ZoneOffset.UTC)); + }); var owner = new net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner( c.dsl, @@ -950,13 +941,12 @@ void expiredCreatedSettlesSharedSourceHoldWithoutAnyAccountCreatorCompletion() { .issuedAt() .plusSeconds( assembled.recent.recentAgeSeconds() - assembled.recent.maxClockSkewSeconds()); - c.tx( - () -> { - c.dsl.execute("SET LOCAL statement_timeout = '20s'"); - return c.dsl.fetch( - "SELECT pg_sleep(GREATEST(0.0, EXTRACT(EPOCH FROM (?::timestamptz - clock_timestamp()))))", - OffsetDateTime.ofInstant(cutoff, ZoneOffset.UTC)); - }); + c.tx(() -> { + c.dsl.execute("SET LOCAL statement_timeout = '20s'"); + return c.dsl.fetch( + "SELECT pg_sleep(GREATEST(0.0, EXTRACT(EPOCH FROM (?::timestamptz - clock_timestamp()))))", + OffsetDateTime.ofInstant(cutoff, ZoneOffset.UTC)); + }); var historical = assembled.owner.complete( fixture.intent.creationOperationId(), @@ -990,11 +980,10 @@ void expiredCreatedSettlesSharedSourceHoldWithoutAnyAccountCreatorCompletion() { c.dsl.fetch( "SELECT *, xmin::text AS settled_xmin FROM account_tenant_creation_source_order_settlements")) .isEqualTo(settled); - originals.forEach( - (table, rows) -> - assertThat(c.dsl.fetch("SELECT *, xmin::text AS original_xmin FROM " + table)) - .as(table) - .isEqualTo(rows)); + originals.forEach((table, rows) -> + assertThat(c.dsl.fetch("SELECT *, xmin::text AS original_xmin FROM " + table)) + .as(table) + .isEqualTo(rows)); assertAtomicRows(c, 0); assertThat(c.dsl.fetchCount(DSL.table("account_recent_reauthentication_consumptions"))) .isZero(); @@ -1026,13 +1015,12 @@ void concurrentHistoricalSettlementBetweenSqlPhasesReturnsExactCommittedHistory( var executor = Executors.newSingleThreadExecutor(); try { var pending = - executor.submit( - () -> - assembled.owner.complete( - fixture.intent.creationOperationId(), - assembled.terminal, - assembled.environment, - assembled.recent)); + executor.submit(() -> + assembled.owner.complete( + fixture.intent.creationOperationId(), + assembled.terminal, + assembled.environment, + assembled.recent)); assertThat(initialPhaseCommitted.await(10, TimeUnit.SECONDS)).isTrue(); awaitOriginalCutoff(c, assembled.recent); var historical = @@ -1069,11 +1057,10 @@ void originalCutoffExpiringDuringSignerReadSettlesBeforeAnyFreshCreatorWrite() { StorageContext c = storageContext(15, 0); var fixture = storageFixture(c); var recent = - c.tx( - () -> - c.evidenceRepository - .findByCreationOperation(fixture.intent.creationOperationId()) - .orElseThrow()); + c.tx(() -> + c.evidenceRepository + .findByCreationOperation(fixture.intent.creationOperationId()) + .orElseThrow()); var crossedCutoffDuringSignerRead = new AtomicBoolean(); var assembled = assembleStoredOwner( @@ -1107,13 +1094,12 @@ private static void awaitOriginalCutoff( // Wait on the genuine database clock; immutable owner rows and clock functions stay intact. Instant cutoff = recent.issuedAt().plusSeconds(recent.recentAgeSeconds() - recent.maxClockSkewSeconds()); - c.tx( - () -> { - c.dsl.execute("SET LOCAL statement_timeout = '20s'"); - return c.dsl.fetch( - "SELECT pg_sleep(GREATEST(0.0, EXTRACT(EPOCH FROM (?::timestamptz - clock_timestamp()))))", - OffsetDateTime.ofInstant(cutoff, ZoneOffset.UTC)); - }); + c.tx(() -> { + c.dsl.execute("SET LOCAL statement_timeout = '20s'"); + return c.dsl.fetch( + "SELECT pg_sleep(GREATEST(0.0, EXTRACT(EPOCH FROM (?::timestamptz - clock_timestamp()))))", + OffsetDateTime.ofInstant(cutoff, ZoneOffset.UTC)); + }); } private static void assertNoAccountCompletion(StorageContext c, StoredOwner assembled) { @@ -1156,13 +1142,12 @@ void failureAfterActualOwnerReauthAndAuditWritesRollsBackEveryNewTenantConstitue org.mockito.ArgumentMatchers.eq("ACCOUNT_TENANT_CREATION_COMPLETED"), org.mockito.ArgumentMatchers.anyString()); var assembled = assembleStoredOwner(c, fixture, audits); - assertThatThrownBy( - () -> - assembled.owner.complete( - fixture.intent.creationOperationId(), - assembled.terminal, - assembled.environment, - assembled.recent)) + assertThatThrownBy(() -> + assembled.owner.complete( + fixture.intent.creationOperationId(), + assembled.terminal, + assembled.environment, + assembled.recent)) .isInstanceOf(IllegalStateException.class) .hasMessage("Controlled failure after actual final audit insertion"); assertAtomicRows(c, 0); @@ -1222,19 +1207,17 @@ void expiredDispatchCommitRollsBackWithoutConsumingItsOnlyInitialClaim() { StorageContext c = storageContext(); var fixture = storageFixture(c); var assembled = assembleStoredOwner(c, fixture, new AccountAuditOutboxRepository(c.dsl)); - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - "INSERT INTO account_tenant_creation_dispatch_intents" - + " (creation_operation_id, dispatch_call_id, authorization_binding_payload, authorization_digest, valid_before_epoch_millis)" - + " VALUES (?, ?, ?, ?, ?)", - fixture.intent.creationOperationId(), - UUID.randomUUID(), - assembled.prepared.sourceOrderBinding(), - assembled.prepared.authorizationDigest(), - System.currentTimeMillis() - 1))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + "INSERT INTO account_tenant_creation_dispatch_intents" + + " (creation_operation_id, dispatch_call_id, authorization_binding_payload, authorization_digest, valid_before_epoch_millis)" + + " VALUES (?, ?, ?, ?, ?)", + fixture.intent.creationOperationId(), + UUID.randomUUID(), + assembled.prepared.sourceOrderBinding(), + assembled.prepared.authorizationDigest(), + System.currentTimeMillis() - 1))) .isInstanceOf(RuntimeException.class); assertThat(c.dsl.fetchCount(DSL.table("account_tenant_creation_dispatch_intents"))).isZero(); assertThat( @@ -1278,11 +1261,10 @@ void liveClaimAndUnclaimedOriginalKeepPendingWithoutClosingOrChangingRetainedRow var outcomes = mock(GameDesignOriginalTenantCreationOutcomeClient.class); var completion = mock(AccountTenantCreationCompletionOwner.class); when(outcomes.readOriginal(original.binding())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - throw Status.NOT_FOUND.asRuntimeException(); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + throw Status.NOT_FOUND.asRuntimeException(); + }); var coordinator = new AccountTenantCreationCoordinator( admission, @@ -1299,15 +1281,14 @@ c.dsl, new DraftAuthorizationFenceRepository(c.dsl)), .isEqualTo(AccountTenantCreationCoordinator.State.PENDING); } org.mockito.Mockito.verifyNoInteractions(admission, creation, completion); - retained.forEach( - (table, rows) -> - assertThat( - c.dsl.fetch( - "SELECT *, xmin::text AS original_xmin FROM " - + table - + " ORDER BY creation_operation_id")) - .as(table) - .isEqualTo(rows)); + retained.forEach((table, rows) -> + assertThat( + c.dsl.fetch( + "SELECT *, xmin::text AS original_xmin FROM " + + table + + " ORDER BY creation_operation_id")) + .as(table) + .isEqualTo(rows)); assertThat(c.dsl.fetchCount(DSL.table("account_tenant_creation_dispatch_intents"))) .isEqualTo(claimed ? 1 : 0); assertThat(c.dsl.fetchCount(DSL.table("account_tenant_creation_completions"))).isZero(); @@ -1367,11 +1348,10 @@ private static StoredOwner assembleStoredOwner( var dsl = c.dsl; var intent = fixture.intent; var recent = - c.tx( - () -> - c.evidenceRepository - .findByCreationOperation(intent.creationOperationId()) - .orElseThrow()); + c.tx(() -> + c.evidenceRepository + .findByCreationOperation(intent.creationOperationId()) + .orElseThrow()); var party = new IndividualCreatorPartySource( intent.creatorPartyId(), @@ -1384,19 +1364,18 @@ private static StoredOwner assembleStoredOwner( 1L, 1L); byte[] partyPayload = CreatorPartyEncoding.party(party); - c.tx( - () -> - dsl.execute( - "INSERT INTO account_individual_creator_party_sources" - + " (creator_party_id, account_uuid, verification_status, identity_version, policy_reference, policy_version," - + " verification_evidence_reference, verification_evidence_version, source_version, source_payload, source_digest)" - + " VALUES (?, ?, 'VERIFIED', 1, ?, 1, ?, 1, 1, ?, ?)", - party.creatorPartyId(), - party.accountId(), - party.policyReference(), - party.verificationEvidenceReference(), - partyPayload, - CreatorPartyEncoding.digest(partyPayload))); + c.tx(() -> + dsl.execute( + "INSERT INTO account_individual_creator_party_sources" + + " (creator_party_id, account_uuid, verification_status, identity_version, policy_reference, policy_version," + + " verification_evidence_reference, verification_evidence_version, source_version, source_payload, source_digest)" + + " VALUES (?, ?, 'VERIFIED', 1, ?, 1, ?, 1, 1, ?, ?)", + party.creatorPartyId(), + party.accountId(), + party.policyReference(), + party.verificationEvidenceReference(), + partyPayload, + CreatorPartyEncoding.digest(partyPayload))); List sources = controlledSources(c, fixture); seedSerializationRows(c, sources); var orderRepository = @@ -1437,13 +1416,11 @@ private static StoredOwner assembleStoredOwner( var issuance = c.tx(() -> issuances.findToken(fixture.admitted.binding().tokenHash())); var accepted = mock(AccountControlUiActorService.class); when(accepted.readAcceptedSignerKey("test-key")) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - beforeSignerRead.run(); - return new AccountControlUiActorService.AcceptedSignerKey( - "test-key", "test-fingerprint"); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + beforeSignerRead.run(); + return new AccountControlUiActorService.AcceptedSignerKey("test-key", "test-fingerprint"); + }); var captured = mock(AccountTenantCreationOwnerSourceCapture.Captured.class); when(captured.originalClaims()).thenReturn(issuance.claims); when(captured.originalSignerReceipt()).thenReturn(issuance.signerReceipt); @@ -1553,26 +1530,24 @@ private record StoredOwner( AccountTenantCreationOwnerSourceCapture capture) {} private static void seedSerializationRows(StorageContext context, List sources) { - context.tx( - () -> { - for (SourceEvidence source : sources) { - context.dsl.execute( - "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?) " - + "ON CONFLICT DO NOTHING", - source.key()); - } - return null; - }); + context.tx(() -> { + for (SourceEvidence source : sources) { + context.dsl.execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?) " + + "ON CONFLICT DO NOTHING", + source.key()); + } + return null; + }); } private static List controlledSources( StorageContext context, StorageFixture fixture) { List policySources = - context.tx( - () -> - new AccountRecentReauthenticationPolicyRepository(context.dsl) - .resolveCurrentSourcesForGameCreation() - .sources()); + context.tx(() -> + new AccountRecentReauthenticationPolicyRepository(context.dsl) + .resolveCurrentSourcesForGameCreation() + .sources()); UUID actor = fixture.intent().initiatingAccountId(); UUID creatorParty = fixture.intent().creatorPartyId(); UUID hostedScope = UUID.randomUUID(); @@ -1629,24 +1604,23 @@ private static StorageFixture storageFixture( context.service.reauthenticate( context.request(account, UUID.randomUUID(), creationOperationId)); var intent = - context.tx( - () -> - new AccountTenantCreationIntentRepository(context.dsl, context.evidenceRepository) - .claim( - new AccountTenantCreationIntentRepository.Request( - UUID.randomUUID(), - creationOperationId, - UUID.randomUUID(), - account.getAccountUuid(), - "test-game", - "source-game", - "Game", - "controlled source-order test", - reauthentication.evidenceId(), - creatorPartyId, - UUID.randomUUID(), - 1, - true))); + context.tx(() -> + new AccountTenantCreationIntentRepository(context.dsl, context.evidenceRepository) + .claim( + new AccountTenantCreationIntentRepository.Request( + UUID.randomUUID(), + creationOperationId, + UUID.randomUUID(), + account.getAccountUuid(), + "test-game", + "source-game", + "Game", + "controlled source-order test", + reauthentication.evidenceId(), + creatorPartyId, + UUID.randomUUID(), + 1, + true))); UUID issuanceOperationId = UUID.randomUUID(); String tokenHash = @@ -1659,55 +1633,51 @@ private static StorageFixture storageFixture( long operationDeadline = tokenExpiry; long cleanupDeadline = tokenExpiry + 300_000; long receiptDeadline = operationDeadline + 86_400_000; - context.tx( - () -> - context.dsl.execute( - "INSERT INTO account_control_ui_issuance_operations " - + "(request_id, operation_id, token_jti, account_uuid, tenant_uuid, authorization_scope, caller_workload, " - + "caller_context_id, request_mac_key_id, request_digest, claims_payload, source_payload, bundle_payload, signer_receipt, " - + "issued_at_epoch_second, expires_at_epoch_second, registry_cleanup_deadline_epoch_millis, recovery_expires_at, status) " - + "VALUES (?, ?, ?, ?, NULL, 'ACCOUNT', 'spiffe://test-only/source-order', ?, 'test-mac', ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, 'PREPARED')", - UUID.randomUUID(), - issuanceOperationId, - UUID.randomUUID(), - account.getAccountUuid(), - UUID.randomUUID(), - "c".repeat(64), - activeRegistry, - activeRegistry, - activeRegistry, - AccountControlUiAuthority.canonical( - Map.of("kid", "test-key", "publicKeyFingerprint", "test-fingerprint")), - issuedAt, - issuedAt + 300, - cleanupDeadline, - OffsetDateTime.ofInstant(Instant.ofEpochSecond(issuedAt + 60), ZoneOffset.UTC))); - context.tx( - () -> - context.dsl.execute( - "UPDATE account_control_ui_issuance_operations SET status = 'CANDIDATE', token_hash = ?, " - + "pending_registry = ?, active_registry = ? WHERE operation_id = ?", - tokenHash, - activeRegistry, - activeRegistry, - issuanceOperationId)); - context.tx( - () -> - context.dsl.execute( - "INSERT INTO account_control_ui_response_envelopes " - + "(operation_id, encrypted_response, owner_binding, recovery_expires_at) " - + "SELECT operation_id, ?, ?, recovery_expires_at " - + "FROM account_control_ui_issuance_operations WHERE operation_id = ?", - activeRegistry, - activeRegistry, - issuanceOperationId)); - context.tx( - () -> - context.dsl.execute( - "UPDATE account_control_ui_issuance_operations SET status = 'COMMITTED', " - + "pending_receipt = ?, committed_at = CURRENT_TIMESTAMP WHERE operation_id = ?", - activeRegistry, - issuanceOperationId)); + context.tx(() -> + context.dsl.execute( + "INSERT INTO account_control_ui_issuance_operations " + + "(request_id, operation_id, token_jti, account_uuid, tenant_uuid, authorization_scope, caller_workload, " + + "caller_context_id, request_mac_key_id, request_digest, claims_payload, source_payload, bundle_payload, signer_receipt, " + + "issued_at_epoch_second, expires_at_epoch_second, registry_cleanup_deadline_epoch_millis, recovery_expires_at, status) " + + "VALUES (?, ?, ?, ?, NULL, 'ACCOUNT', 'spiffe://test-only/source-order', ?, 'test-mac', ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, 'PREPARED')", + UUID.randomUUID(), + issuanceOperationId, + UUID.randomUUID(), + account.getAccountUuid(), + UUID.randomUUID(), + "c".repeat(64), + activeRegistry, + activeRegistry, + activeRegistry, + AccountControlUiAuthority.canonical( + Map.of("kid", "test-key", "publicKeyFingerprint", "test-fingerprint")), + issuedAt, + issuedAt + 300, + cleanupDeadline, + OffsetDateTime.ofInstant(Instant.ofEpochSecond(issuedAt + 60), ZoneOffset.UTC))); + context.tx(() -> + context.dsl.execute( + "UPDATE account_control_ui_issuance_operations SET status = 'CANDIDATE', token_hash = ?, " + + "pending_registry = ?, active_registry = ? WHERE operation_id = ?", + tokenHash, + activeRegistry, + activeRegistry, + issuanceOperationId)); + context.tx(() -> + context.dsl.execute( + "INSERT INTO account_control_ui_response_envelopes " + + "(operation_id, encrypted_response, owner_binding, recovery_expires_at) " + + "SELECT operation_id, ?, ?, recovery_expires_at " + + "FROM account_control_ui_issuance_operations WHERE operation_id = ?", + activeRegistry, + activeRegistry, + issuanceOperationId)); + context.tx(() -> + context.dsl.execute( + "UPDATE account_control_ui_issuance_operations SET status = 'COMMITTED', " + + "pending_receipt = ?, committed_at = CURRENT_TIMESTAMP WHERE operation_id = ?", + activeRegistry, + issuanceOperationId)); var admissionBinding = new AccountTenantCreationAdmissionBinding( @@ -1727,52 +1697,47 @@ private static StorageFixture storageFixture( preparedAt, operationDeadline, receiptDeadline); - context.tx( - () -> - context.dsl.execute( - "INSERT INTO account_tenant_creation_admission_requests " - + "(creation_operation_id, intent_request_id, issuance_operation_id, actor_account_id, target_namespace, " - + "game_design_creation_request_id, game_design_request_digest, intent_digest, active_registry_digest, " - + "reauthentication_evidence_id, token_hash, token_cleanup_deadline_epoch_millis, token_expires_at_epoch_millis, " - + "prepared_at_epoch_millis, operation_deadline_epoch_millis, receipt_cleanup_deadline_epoch_millis, binding_payload, binding_digest) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - creationOperationId, - intent.requestId(), - issuanceOperationId, - account.getAccountUuid(), - admissionBinding.targetNamespace(), - admissionBinding.gameDesignCreationRequestId(), - admissionBinding.gameDesignRequestDigest(), - admissionBinding.intentDigest(), - admissionBinding.activeRegistryDigest(), - reauthentication.evidenceId(), - tokenHash, - cleanupDeadline, - tokenExpiry, - preparedAt, - operationDeadline, - receiptDeadline, - admissionBinding.canonicalReceipt(), - AccountControlUiCoordination.digest( - "SHA-256", admissionBinding.canonicalReceipt()))); + context.tx(() -> + context.dsl.execute( + "INSERT INTO account_tenant_creation_admission_requests " + + "(creation_operation_id, intent_request_id, issuance_operation_id, actor_account_id, target_namespace, " + + "game_design_creation_request_id, game_design_request_digest, intent_digest, active_registry_digest, " + + "reauthentication_evidence_id, token_hash, token_cleanup_deadline_epoch_millis, token_expires_at_epoch_millis, " + + "prepared_at_epoch_millis, operation_deadline_epoch_millis, receipt_cleanup_deadline_epoch_millis, binding_payload, binding_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + creationOperationId, + intent.requestId(), + issuanceOperationId, + account.getAccountUuid(), + admissionBinding.targetNamespace(), + admissionBinding.gameDesignCreationRequestId(), + admissionBinding.gameDesignRequestDigest(), + admissionBinding.intentDigest(), + admissionBinding.activeRegistryDigest(), + reauthentication.evidenceId(), + tokenHash, + cleanupDeadline, + tokenExpiry, + preparedAt, + operationDeadline, + receiptDeadline, + admissionBinding.canonicalReceipt(), + AccountControlUiCoordination.digest("SHA-256", admissionBinding.canonicalReceipt()))); // Physical AOF/replica/qualification values are controlled test facts. The private Admitted // value is still obtained only by reading the actual V1022 durable rows. - context.tx( - () -> - context.dsl.execute( - "INSERT INTO account_tenant_creation_admissions " - + "(creation_operation_id, receipt_payload, receipt_digest, local_aof_count, replica_aof_count, " - + "protected_binding_id, qualification_fence) VALUES (?, ?, ?, 1, 1, 'test-stipulated-physical-evidence', 7)", - creationOperationId, - admissionBinding.canonicalReceipt(), - AccountControlUiCoordination.digest( - "SHA-256", admissionBinding.canonicalReceipt()))); + context.tx(() -> + context.dsl.execute( + "INSERT INTO account_tenant_creation_admissions " + + "(creation_operation_id, receipt_payload, receipt_digest, local_aof_count, replica_aof_count, " + + "protected_binding_id, qualification_fence) VALUES (?, ?, ?, 1, 1, 'test-stipulated-physical-evidence', 7)", + creationOperationId, + admissionBinding.canonicalReceipt(), + AccountControlUiCoordination.digest("SHA-256", admissionBinding.canonicalReceipt()))); var admitted = - context.tx( - () -> - new AccountTenantCreationAdmissionRepository(context.dsl) - .readAdmitted(creationOperationId) - .orElseThrow()); + context.tx(() -> + new AccountTenantCreationAdmissionRepository(context.dsl) + .readAdmitted(creationOperationId) + .orElseThrow()); return new StorageFixture(account, intent, admitted); } @@ -1798,20 +1763,19 @@ private static StorageContext storageContext(int recentAgeSeconds, int maxClockS var manager = new DataSourceTransactionManager(source); var transaction = new TransactionTemplate(manager); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - transaction.executeWithoutResult( - ignored -> { - dsl.execute( - "INSERT INTO account_recent_reauthentication_policy_values " - + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " - + "VALUES ('PLATFORM', 1, ?, ?), ('DEPLOYMENT', 1, ?, ?)", - recentAgeSeconds, - maxClockSkewSeconds, - recentAgeSeconds, - maxClockSkewSeconds); - dsl.execute( - "INSERT INTO account_recent_reauthentication_policy_current " - + "(policy_scope, policy_version) VALUES ('PLATFORM', 1), ('DEPLOYMENT', 1)"); - }); + transaction.executeWithoutResult(ignored -> { + dsl.execute( + "INSERT INTO account_recent_reauthentication_policy_values " + + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " + + "VALUES ('PLATFORM', 1, ?, ?), ('DEPLOYMENT', 1, ?, ?)", + recentAgeSeconds, + maxClockSkewSeconds, + recentAgeSeconds, + maxClockSkewSeconds); + dsl.execute( + "INSERT INTO account_recent_reauthentication_policy_current " + + "(policy_scope, policy_version) VALUES ('PLATFORM', 1), ('DEPLOYMENT', 1)"); + }); var generations = new AccountAuthorityGenerationRepository(dsl); var outbox = new AccountAuthorityOutboxRepository(dsl); var sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java index d8c9ba3a53..da9a89224b 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationSourceOrderPostgresIntegrationTest.java @@ -119,17 +119,15 @@ void exactRetryPreservesOriginalBytesAndSharedGateBlocksEverySourceKey() { AccountTenantCreationSourceOrderBinding first; try { first = - c.tx( - () -> { - AccountTenantCreationSourceOrderBinding retained = - repository.acquireLocked(fixture.intent(), fixture.admitted(), sources); - for (SourceEvidence source : sources) { - CompletableFuture.runAsync( - () -> assertWriterGateDenied(c, source.key()), executor) - .join(); - } - return retained; - }); + c.tx(() -> { + AccountTenantCreationSourceOrderBinding retained = + repository.acquireLocked(fixture.intent(), fixture.admitted(), sources); + for (SourceEvidence source : sources) { + CompletableFuture.runAsync(() -> assertWriterGateDenied(c, source.key()), executor) + .join(); + } + return retained; + }); } finally { executor.shutdownNow(); } @@ -140,19 +138,17 @@ void exactRetryPreservesOriginalBytesAndSharedGateBlocksEverySourceKey() { assertThat(retry.authorizationDigest()).isEqualTo(first.authorizationDigest()); assertThat(xmin(c, fixture.intent().creationOperationId())).isEqualTo(originalXmin); assertThat( - c.tx( - () -> - repository - .readOriginal(fixture.intent().creationOperationId()) - .orElseThrow() - .canonicalBytes())) + c.tx(() -> + repository + .readOriginal(fixture.intent().creationOperationId()) + .orElseThrow() + .canonicalBytes())) .containsExactly(first.canonicalBytes()); assertThat( - c.tx( - () -> - repository.readPending(null, 10).stream() - .map(row -> row.binding().creationOperationId()) - .toList())) + c.tx(() -> + repository.readPending(null, 10).stream() + .map(row -> row.binding().creationOperationId()) + .toList())) .containsExactly(fixture.intent().creationOperationId()); for (SourceEvidence source : sources) { @@ -173,52 +169,45 @@ void distinctOriginalOrdersMayShareSourcesAndBothKeepSourceChangesWaiting() { var repository = repository(c); var first = - c.tx( - () -> - repository.acquireLocked(firstFixture.intent(), firstFixture.admitted(), sources)); + c.tx(() -> + repository.acquireLocked(firstFixture.intent(), firstFixture.admitted(), sources)); var second = - c.tx( - () -> - repository.acquireLocked( - secondFixture.intent(), secondFixture.admitted(), sources)); + c.tx(() -> + repository.acquireLocked(secondFixture.intent(), secondFixture.admitted(), sources)); assertThat(first.creationOperationId()).isNotEqualTo(second.creationOperationId()); assertThat(first.sources()).containsExactlyElementsOf(second.sources()); assertThat( - c.tx( - () -> - repository.readPending(null, 10).stream() - .map(row -> row.binding().creationOperationId()) - .toList())) + c.tx(() -> + repository.readPending(null, 10).stream() + .map(row -> row.binding().creationOperationId()) + .toList())) .containsExactlyInAnyOrder( firstFixture.intent().creationOperationId(), secondFixture.intent().creationOperationId()); assertThat( - c.tx( - () -> - repository - .readOriginal(firstFixture.intent().creationOperationId()) - .orElseThrow() - .canonicalBytes())) + c.tx(() -> + repository + .readOriginal(firstFixture.intent().creationOperationId()) + .orElseThrow() + .canonicalBytes())) .containsExactly(first.canonicalBytes()); assertThat( - c.tx( - () -> - repository - .readOriginal(secondFixture.intent().creationOperationId()) - .orElseThrow() - .canonicalBytes())) + c.tx(() -> + repository + .readOriginal(secondFixture.intent().creationOperationId()) + .orElseThrow() + .canonicalBytes())) .containsExactly(second.canonicalBytes()); assertThat( - c.tx( - () -> - Objects.requireNonNull( - c.dsl.fetchOne( - "SELECT count(*) AS count FROM account_tenant_creation_source_order_settlements " - + "WHERE creation_operation_id IN (?, ?)", - first.creationOperationId(), - second.creationOperationId())) - .get("count", Long.class))) + c.tx(() -> + Objects.requireNonNull( + c.dsl.fetchOne( + "SELECT count(*) AS count FROM account_tenant_creation_source_order_settlements " + + "WHERE creation_operation_id IN (?, ?)", + first.creationOperationId(), + second.creationOperationId())) + .get("count", Long.class))) .isZero(); var sourceChangeRepository = new DraftAuthorizationFenceRepository(c.dsl); @@ -233,18 +222,15 @@ void distinctOriginalOrdersMayShareSourcesAndBothKeepSourceChangesWaiting() { assertThat(c.tx(() -> sourceChangeRepository.sourceMutationPermitted(change))).isFalse(); String firstXmin = xmin(c, first.creationOperationId()); var recovered = - c.tx( - () -> - repository.acquireLocked(firstFixture.intent(), firstFixture.admitted(), sources)); + c.tx(() -> + repository.acquireLocked(firstFixture.intent(), firstFixture.admitted(), sources)); assertThat(recovered.canonicalBytes()).containsExactly(first.canonicalBytes()); assertThat(recovered.authorizationDigest()).isEqualTo(first.authorizationDigest()); assertThat(xmin(c, first.creationOperationId())).isEqualTo(firstXmin); - assertThatThrownBy( - () -> - c.tx( - () -> - repository.acquireLocked( - unacquiredFixture.intent(), unacquiredFixture.admitted(), sources))) + assertThatThrownBy(() -> + c.tx(() -> + repository.acquireLocked( + unacquiredFixture.intent(), unacquiredFixture.admitted(), sources))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Applicable authority source change is waiting"); assertThat( @@ -264,14 +250,11 @@ void verifiedTerminalSettlesEachSharedSourceHolderAndUnblocksOnlyAfterBoth() thr seedSerializationRows(c, sources); var repository = repository(c); var first = - c.tx( - () -> - repository.acquireLocked(firstFixture.intent(), firstFixture.admitted(), sources)); + c.tx(() -> + repository.acquireLocked(firstFixture.intent(), firstFixture.admitted(), sources)); var second = - c.tx( - () -> - repository.acquireLocked( - secondFixture.intent(), secondFixture.admitted(), sources)); + c.tx(() -> + repository.acquireLocked(secondFixture.intent(), secondFixture.admitted(), sources)); var sourceChangeRepository = new DraftAuthorizationFenceRepository(c.dsl); var waitingChange = @@ -292,12 +275,11 @@ void verifiedTerminalSettlesEachSharedSourceHolderAndUnblocksOnlyAfterBoth() thr assertThat(firstSettlement.canonicalBytes()).containsExactly(created.canonicalBytes()); assertThat(xmin(c, first.creationOperationId())).isEqualTo(originalXmin); assertThat( - c.tx( - () -> - repository - .readSettlement(first.creationOperationId()) - .orElseThrow() - .canonicalBytes())) + c.tx(() -> + repository + .readSettlement(first.creationOperationId()) + .orElseThrow() + .canonicalBytes())) .containsExactly(created.canonicalBytes()); assertWriterGateDenied(c, "ISSUER:firemud-account-service"); assertThat(c.tx(() -> repository.readSettlement(second.creationOperationId()))).isEmpty(); @@ -400,18 +382,17 @@ void failedOrMismatchedTerminalReadsCannotSettleAnOriginalHolder() throws Except } var created = terminalEvidence(expected, Outcome.CREATED); - assertThatThrownBy( - () -> - readTerminal( - created, - expected, - null, - response -> - response.toBuilder() - .setCreatedReceipt( - response.getCreatedReceipt().toBuilder() - .setEvidenceDigest("sha256:" + "f".repeat(64))) - .build())) + assertThatThrownBy(() -> + readTerminal( + created, + expected, + null, + response -> + response.toBuilder() + .setCreatedReceipt( + response.getCreatedReceipt().toBuilder() + .setEvidenceDigest("sha256:" + "f".repeat(64))) + .build())) .isInstanceOf(RuntimeException.class); assertThat(c.tx(() -> repository.readSettlement(original.creationOperationId()))).isEmpty(); @@ -428,12 +409,10 @@ void changedOrIncompleteSourceInputCannotReplacePendingOriginalAndSettlementRema var original = c.tx(() -> repository.acquireLocked(fixture.intent(), fixture.admitted(), sources)); - assertThatThrownBy( - () -> - c.tx( - () -> - repository.acquireLocked( - fixture.intent(), fixture.admitted(), sources.subList(0, 7)))) + assertThatThrownBy(() -> + c.tx(() -> + repository.acquireLocked( + fixture.intent(), fixture.admitted(), sources.subList(0, 7)))) .isInstanceOf(IllegalArgumentException.class); List changed = new ArrayList<>(sources); @@ -448,9 +427,8 @@ void changedOrIncompleteSourceInputCannotReplacePendingOriginalAndSettlementRema first.checkpointStream(), first.checkpointSequence(), "changed controlled owner bytes".getBytes(StandardCharsets.UTF_8))); - assertThatThrownBy( - () -> - c.tx(() -> repository.acquireLocked(fixture.intent(), fixture.admitted(), changed))) + assertThatThrownBy(() -> + c.tx(() -> repository.acquireLocked(fixture.intent(), fixture.admitted(), changed))) .isInstanceOf(IllegalStateException.class); AccountTenantCreationIntentRepository.OriginalIntent alteredActor = @@ -472,42 +450,36 @@ void changedOrIncompleteSourceInputCannotReplacePendingOriginalAndSettlementRema fixture.intent().requestPayload(), fixture.intent().requestDigest(), fixture.intent().createdAt()); - assertThatThrownBy( - () -> - AccountTenantCreationSourceOrderBinding.from( - alteredActor, fixture.admitted(), sources)) + assertThatThrownBy(() -> + AccountTenantCreationSourceOrderBinding.from(alteredActor, fixture.admitted(), sources)) .isInstanceOf(IllegalArgumentException.class); assertThat( - c.tx( - () -> - repository - .readOriginal(fixture.intent().creationOperationId()) - .orElseThrow() - .canonicalBytes())) + c.tx(() -> + repository + .readOriginal(fixture.intent().creationOperationId()) + .orElseThrow() + .canonicalBytes())) .containsExactly(original.canonicalBytes()); assertThat(c.tx(() -> consumptionCount(c, fixture.intent().recentReauthenticationEvidenceId()))) .isZero(); byte[] invalidTerminal = "unverified terminal input".getBytes(StandardCharsets.UTF_8); - assertThatThrownBy( - () -> - c.tx( - () -> - c.dsl.execute( - "INSERT INTO account_tenant_creation_source_order_settlements " - + "(creation_operation_id, target_namespace, game_design_creation_request_id, " - + "account_authorization_operation_id, initiating_account_id, creation_request_digest, " - + "account_authorization_digest, outcome_status, terminal_read_payload, terminal_read_digest) " - + "VALUES (?, 'test-game', ?, ?, ?, ?, ?, 'NOT_CREATED', ?, ?)", - fixture.intent().creationOperationId(), - fixture.intent().gameDesignCreationRequestId(), - fixture.intent().creationOperationId(), - fixture.intent().initiatingAccountId(), - fixture.intent().gameDesignRequestDigest(), - original.authorizationDigest(), - invalidTerminal, - "sha256:" - + AccountControlUiCoordination.digest("SHA-256", invalidTerminal)))) + assertThatThrownBy(() -> + c.tx(() -> + c.dsl.execute( + "INSERT INTO account_tenant_creation_source_order_settlements " + + "(creation_operation_id, target_namespace, game_design_creation_request_id, " + + "account_authorization_operation_id, initiating_account_id, creation_request_digest, " + + "account_authorization_digest, outcome_status, terminal_read_payload, terminal_read_digest) " + + "VALUES (?, 'test-game', ?, ?, ?, ?, ?, 'NOT_CREATED', ?, ?)", + fixture.intent().creationOperationId(), + fixture.intent().gameDesignCreationRequestId(), + fixture.intent().creationOperationId(), + fixture.intent().initiatingAccountId(), + fixture.intent().gameDesignRequestDigest(), + original.authorizationDigest(), + invalidTerminal, + "sha256:" + AccountControlUiCoordination.digest("SHA-256", invalidTerminal)))) .isInstanceOf(DataAccessException.class); for (String table : List.of( @@ -612,47 +584,41 @@ private static AccountTenantCreationSourceOrderRepository repository(Context con } private static void assertWriterGateDenied(Context context, String sourceKey) { - assertThatThrownBy( - () -> - context.tx( - () -> - context.dsl.fetch( - "SELECT account_control_ui_hold_required_sources(ARRAY[?]::TEXT[])", - sourceKey))) + assertThatThrownBy(() -> + context.tx(() -> + context.dsl.fetch( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::TEXT[])", + sourceKey))) .isInstanceOf(DataAccessException.class); } private static void assertWriterGateAllowed(Context context, String sourceKey) { - assertThatCode( - () -> - context.tx( - () -> - context.dsl.fetch( - "SELECT account_control_ui_hold_required_sources(ARRAY[?]::TEXT[])", - sourceKey))) + assertThatCode(() -> + context.tx(() -> + context.dsl.fetch( + "SELECT account_control_ui_hold_required_sources(ARRAY[?]::TEXT[])", + sourceKey))) .doesNotThrowAnyException(); } private static void seedSerializationRows(Context context, List sources) { - context.tx( - () -> { - for (SourceEvidence source : sources) { - context.dsl.execute( - "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?) " - + "ON CONFLICT DO NOTHING", - source.key()); - } - return null; - }); + context.tx(() -> { + for (SourceEvidence source : sources) { + context.dsl.execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?) " + + "ON CONFLICT DO NOTHING", + source.key()); + } + return null; + }); } private static List controlledSources(Context context, Fixture fixture) { List policySources = - context.tx( - () -> - new AccountRecentReauthenticationPolicyRepository(context.dsl) - .resolveCurrentSourcesForGameCreation() - .sources()); + context.tx(() -> + new AccountRecentReauthenticationPolicyRepository(context.dsl) + .resolveCurrentSourcesForGameCreation() + .sources()); UUID actor = fixture.intent().initiatingAccountId(); UUID creatorParty = fixture.intent().creatorPartyId(); UUID hostedScope = UUID.randomUUID(); @@ -726,24 +692,23 @@ private static Fixture fixture(Context context, Account account, UUID creatorPar context.service.reauthenticate( context.request(account, UUID.randomUUID(), creationOperationId)); var intent = - context.tx( - () -> - new AccountTenantCreationIntentRepository(context.dsl, context.evidenceRepository) - .claim( - new AccountTenantCreationIntentRepository.Request( - UUID.randomUUID(), - creationOperationId, - UUID.randomUUID(), - account.getAccountUuid(), - "test-game", - "source-game", - "Game", - "controlled source-order test", - reauthentication.evidenceId(), - creatorPartyId, - UUID.randomUUID(), - 1, - true))); + context.tx(() -> + new AccountTenantCreationIntentRepository(context.dsl, context.evidenceRepository) + .claim( + new AccountTenantCreationIntentRepository.Request( + UUID.randomUUID(), + creationOperationId, + UUID.randomUUID(), + account.getAccountUuid(), + "test-game", + "source-game", + "Game", + "controlled source-order test", + reauthentication.evidenceId(), + creatorPartyId, + UUID.randomUUID(), + 1, + true))); UUID issuanceOperationId = UUID.randomUUID(); String tokenHash = @@ -756,54 +721,50 @@ private static Fixture fixture(Context context, Account account, UUID creatorPar long operationDeadline = tokenExpiry; long cleanupDeadline = tokenExpiry + 300_000; long receiptDeadline = operationDeadline + 86_400_000; - context.tx( - () -> - context.dsl.execute( - "INSERT INTO account_control_ui_issuance_operations " - + "(request_id, operation_id, token_jti, account_uuid, tenant_uuid, authorization_scope, caller_workload, " - + "caller_context_id, request_mac_key_id, request_digest, claims_payload, source_payload, bundle_payload, signer_receipt, " - + "issued_at_epoch_second, expires_at_epoch_second, registry_cleanup_deadline_epoch_millis, recovery_expires_at, status) " - + "VALUES (?, ?, ?, ?, NULL, 'ACCOUNT', 'spiffe://test-only/source-order', ?, 'test-mac', ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, 'PREPARED')", - UUID.randomUUID(), - issuanceOperationId, - UUID.randomUUID(), - account.getAccountUuid(), - UUID.randomUUID(), - "c".repeat(64), - activeRegistry, - activeRegistry, - activeRegistry, - activeRegistry, - issuedAt, - issuedAt + 300, - cleanupDeadline, - OffsetDateTime.ofInstant(Instant.ofEpochSecond(issuedAt + 60), ZoneOffset.UTC))); - context.tx( - () -> - context.dsl.execute( - "UPDATE account_control_ui_issuance_operations SET status = 'CANDIDATE', token_hash = ?, " - + "pending_registry = ?, active_registry = ? WHERE operation_id = ?", - tokenHash, - activeRegistry, - activeRegistry, - issuanceOperationId)); - context.tx( - () -> - context.dsl.execute( - "INSERT INTO account_control_ui_response_envelopes " - + "(operation_id, encrypted_response, owner_binding, recovery_expires_at) " - + "SELECT operation_id, ?, ?, recovery_expires_at " - + "FROM account_control_ui_issuance_operations WHERE operation_id = ?", - activeRegistry, - activeRegistry, - issuanceOperationId)); - context.tx( - () -> - context.dsl.execute( - "UPDATE account_control_ui_issuance_operations SET status = 'COMMITTED', " - + "pending_receipt = ?, committed_at = CURRENT_TIMESTAMP WHERE operation_id = ?", - activeRegistry, - issuanceOperationId)); + context.tx(() -> + context.dsl.execute( + "INSERT INTO account_control_ui_issuance_operations " + + "(request_id, operation_id, token_jti, account_uuid, tenant_uuid, authorization_scope, caller_workload, " + + "caller_context_id, request_mac_key_id, request_digest, claims_payload, source_payload, bundle_payload, signer_receipt, " + + "issued_at_epoch_second, expires_at_epoch_second, registry_cleanup_deadline_epoch_millis, recovery_expires_at, status) " + + "VALUES (?, ?, ?, ?, NULL, 'ACCOUNT', 'spiffe://test-only/source-order', ?, 'test-mac', ?, ?, ?, ?, ?, ?, ?, ?, ?::timestamptz, 'PREPARED')", + UUID.randomUUID(), + issuanceOperationId, + UUID.randomUUID(), + account.getAccountUuid(), + UUID.randomUUID(), + "c".repeat(64), + activeRegistry, + activeRegistry, + activeRegistry, + activeRegistry, + issuedAt, + issuedAt + 300, + cleanupDeadline, + OffsetDateTime.ofInstant(Instant.ofEpochSecond(issuedAt + 60), ZoneOffset.UTC))); + context.tx(() -> + context.dsl.execute( + "UPDATE account_control_ui_issuance_operations SET status = 'CANDIDATE', token_hash = ?, " + + "pending_registry = ?, active_registry = ? WHERE operation_id = ?", + tokenHash, + activeRegistry, + activeRegistry, + issuanceOperationId)); + context.tx(() -> + context.dsl.execute( + "INSERT INTO account_control_ui_response_envelopes " + + "(operation_id, encrypted_response, owner_binding, recovery_expires_at) " + + "SELECT operation_id, ?, ?, recovery_expires_at " + + "FROM account_control_ui_issuance_operations WHERE operation_id = ?", + activeRegistry, + activeRegistry, + issuanceOperationId)); + context.tx(() -> + context.dsl.execute( + "UPDATE account_control_ui_issuance_operations SET status = 'COMMITTED', " + + "pending_receipt = ?, committed_at = CURRENT_TIMESTAMP WHERE operation_id = ?", + activeRegistry, + issuanceOperationId)); var admissionBinding = new AccountTenantCreationAdmissionBinding( @@ -823,52 +784,47 @@ private static Fixture fixture(Context context, Account account, UUID creatorPar preparedAt, operationDeadline, receiptDeadline); - context.tx( - () -> - context.dsl.execute( - "INSERT INTO account_tenant_creation_admission_requests " - + "(creation_operation_id, intent_request_id, issuance_operation_id, actor_account_id, target_namespace, " - + "game_design_creation_request_id, game_design_request_digest, intent_digest, active_registry_digest, " - + "reauthentication_evidence_id, token_hash, token_cleanup_deadline_epoch_millis, token_expires_at_epoch_millis, " - + "prepared_at_epoch_millis, operation_deadline_epoch_millis, receipt_cleanup_deadline_epoch_millis, binding_payload, binding_digest) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - creationOperationId, - intent.requestId(), - issuanceOperationId, - account.getAccountUuid(), - admissionBinding.targetNamespace(), - admissionBinding.gameDesignCreationRequestId(), - admissionBinding.gameDesignRequestDigest(), - admissionBinding.intentDigest(), - admissionBinding.activeRegistryDigest(), - reauthentication.evidenceId(), - tokenHash, - cleanupDeadline, - tokenExpiry, - preparedAt, - operationDeadline, - receiptDeadline, - admissionBinding.canonicalReceipt(), - AccountControlUiCoordination.digest( - "SHA-256", admissionBinding.canonicalReceipt()))); + context.tx(() -> + context.dsl.execute( + "INSERT INTO account_tenant_creation_admission_requests " + + "(creation_operation_id, intent_request_id, issuance_operation_id, actor_account_id, target_namespace, " + + "game_design_creation_request_id, game_design_request_digest, intent_digest, active_registry_digest, " + + "reauthentication_evidence_id, token_hash, token_cleanup_deadline_epoch_millis, token_expires_at_epoch_millis, " + + "prepared_at_epoch_millis, operation_deadline_epoch_millis, receipt_cleanup_deadline_epoch_millis, binding_payload, binding_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + creationOperationId, + intent.requestId(), + issuanceOperationId, + account.getAccountUuid(), + admissionBinding.targetNamespace(), + admissionBinding.gameDesignCreationRequestId(), + admissionBinding.gameDesignRequestDigest(), + admissionBinding.intentDigest(), + admissionBinding.activeRegistryDigest(), + reauthentication.evidenceId(), + tokenHash, + cleanupDeadline, + tokenExpiry, + preparedAt, + operationDeadline, + receiptDeadline, + admissionBinding.canonicalReceipt(), + AccountControlUiCoordination.digest("SHA-256", admissionBinding.canonicalReceipt()))); // Physical AOF/replica/qualification values are controlled test facts. The private Admitted // value is still obtained only by reading the actual V1022 durable rows. - context.tx( - () -> - context.dsl.execute( - "INSERT INTO account_tenant_creation_admissions " - + "(creation_operation_id, receipt_payload, receipt_digest, local_aof_count, replica_aof_count, " - + "protected_binding_id, qualification_fence) VALUES (?, ?, ?, 1, 1, 'test-stipulated-physical-evidence', 7)", - creationOperationId, - admissionBinding.canonicalReceipt(), - AccountControlUiCoordination.digest( - "SHA-256", admissionBinding.canonicalReceipt()))); + context.tx(() -> + context.dsl.execute( + "INSERT INTO account_tenant_creation_admissions " + + "(creation_operation_id, receipt_payload, receipt_digest, local_aof_count, replica_aof_count, " + + "protected_binding_id, qualification_fence) VALUES (?, ?, ?, 1, 1, 'test-stipulated-physical-evidence', 7)", + creationOperationId, + admissionBinding.canonicalReceipt(), + AccountControlUiCoordination.digest("SHA-256", admissionBinding.canonicalReceipt()))); var admitted = - context.tx( - () -> - new AccountTenantCreationAdmissionRepository(context.dsl) - .readAdmitted(creationOperationId) - .orElseThrow()); + context.tx(() -> + new AccountTenantCreationAdmissionRepository(context.dsl) + .readAdmitted(creationOperationId) + .orElseThrow()); return new Fixture(account, intent, admitted); } @@ -890,16 +846,15 @@ private static Context context() { var manager = new DataSourceTransactionManager(source); var transaction = new TransactionTemplate(manager); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - transaction.executeWithoutResult( - ignored -> { - dsl.execute( - "INSERT INTO account_recent_reauthentication_policy_values " - + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " - + "VALUES ('PLATFORM', 1, 300, 30), ('DEPLOYMENT', 1, 300, 30)"); - dsl.execute( - "INSERT INTO account_recent_reauthentication_policy_current " - + "(policy_scope, policy_version) VALUES ('PLATFORM', 1), ('DEPLOYMENT', 1)"); - }); + transaction.executeWithoutResult(ignored -> { + dsl.execute( + "INSERT INTO account_recent_reauthentication_policy_values " + + "(policy_scope, policy_version, recent_age_seconds, max_clock_skew_seconds) " + + "VALUES ('PLATFORM', 1, 300, 30), ('DEPLOYMENT', 1, 300, 30)"); + dsl.execute( + "INSERT INTO account_recent_reauthentication_policy_current " + + "(policy_scope, policy_version) VALUES ('PLATFORM', 1), ('DEPLOYMENT', 1)"); + }); var generations = new AccountAuthorityGenerationRepository(dsl); var outbox = new AccountAuthorityOutboxRepository(dsl); var sourceEvidence = new AccountAuthoritySourceEvidenceRepository(dsl, generations, outbox); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthorityTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthorityTest.java index 785de480b1..3e7e2b7940 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthorityTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountControlUiAuthorityTest.java @@ -369,12 +369,11 @@ AccountControlUiAuthority.Snapshot captureTenant() { current .account() .accountSecurityCutoff() - .map( - cutoff -> - new MembershipAuthorityEventV1Codec.AccountSecurityCutoff( - cutoff.accountAuthorityGeneration(), - cutoff.outboxStreamKey(), - cutoff.outboxSequence())), + .map(cutoff -> + new MembershipAuthorityEventV1Codec.AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence())), Optional.empty()); var fence = current.issuanceFence(); var member = @@ -565,10 +564,9 @@ void canonicalizationPreservesExactlyRepresentableNestedCounters() { @Test void canonicalizationRejectsArithmeticChangeInsteadOfIssuingRoundedAuthority() { for (long counter : new long[] {9007199254740993L, Long.MAX_VALUE}) { - assertThatThrownBy( - () -> - AccountControlUiAuthority.canonical( - Map.of("tuple", List.of(Map.of("counter", counter))))) + assertThatThrownBy(() -> + AccountControlUiAuthority.canonical( + Map.of("tuple", List.of(Map.of("counter", counter))))) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationServiceTest.java index c5c6195c2a..ba5e72a537 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/AccountDraftTerminalReconciliationServiceTest.java @@ -47,25 +47,23 @@ class AccountDraftTerminalReconciliationServiceTest { void unknownFromBothOwnersStaysPendingAndRemoteReadsRunOutsideTransactions() { Fixture f = fixture(Ordering.COMMIT_ORDER); when(f.gameDesignClient().read(any())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(f); - var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); - assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); - assertThat(request.originalAccountBinding()) - .containsExactly(f.binding().canonicalBytes()); - return new GameDesignDraftTerminalReadEvidence(request, Optional.empty()); - }); + .thenAnswer(invocation -> { + assertOutsideTransaction(f); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.originalAccountBinding()) + .containsExactly(f.binding().canonicalBytes()); + return new GameDesignDraftTerminalReadEvidence(request, Optional.empty()); + }); when(f.worldClient().read(any())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(f); - var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); - assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); - assertThat(request.originalAccountBinding()) - .containsExactly(f.binding().canonicalBytes()); - return new WorldDraftTerminalReadEvidence(request, Optional.empty()); - }); + .thenAnswer(invocation -> { + assertOutsideTransaction(f); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.originalAccountBinding()) + .containsExactly(f.binding().canonicalBytes()); + return new WorldDraftTerminalReadEvidence(request, Optional.empty()); + }); assertThat(f.service().reconcile(f.binding().operationId())).contains(Settlement.PENDING); assertThat(f.manager().commits).isEqualTo(2); @@ -80,19 +78,18 @@ void storedWorldOutcomeNeverSkipsMissingGameDesignAndRemainsImmutable() { readback(f.binding(), Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {7}); f.stored().put(Owner.WORLD, world); when(f.gameDesignClient().read(any())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(f); - var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); - return new GameDesignDraftTerminalReadEvidence( - request, - Optional.of( - readback( - f.binding(), - Owner.GAME_DESIGN, - Outcome.DEFINITIVELY_ABORTED, - new byte[] {8}))); - }); + .thenAnswer(invocation -> { + assertOutsideTransaction(f); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence( + request, + Optional.of( + readback( + f.binding(), + Owner.GAME_DESIGN, + Outcome.DEFINITIVELY_ABORTED, + new byte[] {8}))); + }); assertThat(f.service().reconcile(f.binding().operationId())) .contains(Settlement.FAILED_NONPUBLICATION); @@ -110,19 +107,15 @@ void storedGameDesignOutcomeReadsOnlyMissingWorldAndRevokeOrderNeedsBothAborts() readback(f.binding(), Owner.GAME_DESIGN, Outcome.DEFINITIVELY_ABORTED, new byte[] {9}); f.stored().put(Owner.GAME_DESIGN, gameDesign); when(f.worldClient().read(any())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(f); - var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); - return new WorldDraftTerminalReadEvidence( - request, - Optional.of( - readback( - f.binding(), - Owner.WORLD, - Outcome.DEFINITIVELY_ABORTED, - new byte[] {10}))); - }); + .thenAnswer(invocation -> { + assertOutsideTransaction(f); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new WorldDraftTerminalReadEvidence( + request, + Optional.of( + readback( + f.binding(), Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {10}))); + }); assertThat(f.service().reconcile(f.binding().operationId())) .contains(Settlement.FAILED_NONPUBLICATION); @@ -154,31 +147,29 @@ void changedRequestWrongOwnerAndWrongBindingAreRejected() { Fixture f = fixture(Ordering.COMMIT_ORDER); int selectedMismatch = mismatch; when(f.gameDesignClient().read(any())) - .thenAnswer( - invocation -> { - var expected = - (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); - var response = mock(GameDesignDraftTerminalReadEvidence.class); - var returnedRequest = - selectedMismatch == 0 - ? new GameDesignDraftTerminalReadEvidence.Request( - expected.schemaVersion(), - "other-namespace", - expected.readRequestId(), - expected.originalAccountBinding()) - : expected; - var wrongBinding = binding(); - var resultBinding = selectedMismatch == 2 ? wrongBinding : f.binding(); - OwnerReadback value = - readback( - resultBinding, - selectedMismatch == 1 ? Owner.WORLD : Owner.GAME_DESIGN, - Outcome.DEFINITIVELY_ABORTED, - new byte[] {11}); - when(response.request()).thenReturn(returnedRequest); - when(response.ownerReadback()).thenReturn(Optional.of(value)); - return response; - }); + .thenAnswer(invocation -> { + var expected = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + var response = mock(GameDesignDraftTerminalReadEvidence.class); + var returnedRequest = + selectedMismatch == 0 + ? new GameDesignDraftTerminalReadEvidence.Request( + expected.schemaVersion(), + "other-namespace", + expected.readRequestId(), + expected.originalAccountBinding()) + : expected; + var wrongBinding = binding(); + var resultBinding = selectedMismatch == 2 ? wrongBinding : f.binding(); + OwnerReadback value = + readback( + resultBinding, + selectedMismatch == 1 ? Owner.WORLD : Owner.GAME_DESIGN, + Outcome.DEFINITIVELY_ABORTED, + new byte[] {11}); + when(response.request()).thenReturn(returnedRequest); + when(response.ownerReadback()).thenReturn(Optional.of(value)); + return response; + }); assertThatThrownBy(() -> f.service().reconcile(f.binding().operationId())) .isInstanceOf(IllegalArgumentException.class); @@ -203,33 +194,28 @@ public DraftAuthorizationFenceRepository.FenceSnapshot answer( } }); when(f.gameDesignClient().read(any())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(f); - var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); - return new GameDesignDraftTerminalReadEvidence( - request, - Optional.of( - readback( - f.binding(), - Owner.GAME_DESIGN, - Outcome.DEFINITIVELY_ABORTED, - new byte[] {12}))); - }); + .thenAnswer(invocation -> { + assertOutsideTransaction(f); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence( + request, + Optional.of( + readback( + f.binding(), + Owner.GAME_DESIGN, + Outcome.DEFINITIVELY_ABORTED, + new byte[] {12}))); + }); when(f.worldClient().read(any())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(f); - var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); - return new WorldDraftTerminalReadEvidence( - request, - Optional.of( - readback( - f.binding(), - Owner.WORLD, - Outcome.DEFINITIVELY_ABORTED, - new byte[] {13}))); - }); + .thenAnswer(invocation -> { + assertOutsideTransaction(f); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new WorldDraftTerminalReadEvidence( + request, + Optional.of( + readback( + f.binding(), Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {13}))); + }); assertThatThrownBy(() -> f.service().reconcile(f.binding().operationId())) .isInstanceOf(IllegalStateException.class) @@ -260,31 +246,26 @@ void disappearedOrChangedOriginalDuringOwnerReadsIsDeniedAndRollsBack() { original.sources()); assertThat(changed.canonicalBytes()).isNotEqualTo(original.canonicalBytes()); when(f.gameDesignClient().read(any())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(f); - var request = - (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); - doAnswer( - originalRead -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()) - .isTrue(); - assertThat( - TransactionSynchronizationManager.isCurrentTransactionReadOnly()) - .isFalse(); - return absent ? Optional.empty() : Optional.of(changed); - }) - .when(f.repository()) - .readOriginalBinding(any()); - return new GameDesignDraftTerminalReadEvidence(request, Optional.empty()); - }); + .thenAnswer(invocation -> { + assertOutsideTransaction(f); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + doAnswer( + originalRead -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + return absent ? Optional.empty() : Optional.of(changed); + }) + .when(f.repository()) + .readOriginalBinding(any()); + return new GameDesignDraftTerminalReadEvidence(request, Optional.empty()); + }); when(f.worldClient().read(any())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(f); - return new WorldDraftTerminalReadEvidence( - invocation.getArgument(0), Optional.empty()); - }); + .thenAnswer(invocation -> { + assertOutsideTransaction(f); + return new WorldDraftTerminalReadEvidence(invocation.getArgument(0), Optional.empty()); + }); assertThatThrownBy(() -> f.service().reconcile(original.operationId())) .isInstanceOf(IllegalStateException.class); @@ -297,19 +278,18 @@ void disappearedOrChangedOriginalDuringOwnerReadsIsDeniedAndRollsBack() { void lostResponseDoesNotInventAbortAndExactRetrySettlesFromBothImmutableResults() { Fixture f = fixture(Ordering.COMMIT_ORDER); when(f.gameDesignClient().read(any())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(f); - var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); - return new GameDesignDraftTerminalReadEvidence( - request, - Optional.of( - readback( - f.binding(), - Owner.GAME_DESIGN, - Outcome.DEFINITIVELY_ABORTED, - new byte[] {14}))); - }); + .thenAnswer(invocation -> { + assertOutsideTransaction(f); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence( + request, + Optional.of( + readback( + f.binding(), + Owner.GAME_DESIGN, + Outcome.DEFINITIVELY_ABORTED, + new byte[] {14}))); + }); when(f.worldClient().read(any())) .thenThrow(new IllegalStateException("synthetic lost response")); assertThatThrownBy(() -> f.service().reconcile(f.binding().operationId())) @@ -346,21 +326,19 @@ void unknownOwnerResponsesObserveConcurrentGenuineSettlementWithoutInventingResu OwnerReadback worldAbort = readback(f.binding(), Owner.WORLD, Outcome.DEFINITIVELY_ABORTED, new byte[] {26}); when(f.gameDesignClient().read(any())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(f); - f.stored().put(Owner.GAME_DESIGN, gameDesignAbort); - f.stored().put(Owner.WORLD, worldAbort); - var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); - return new GameDesignDraftTerminalReadEvidence(request, Optional.empty()); - }); + .thenAnswer(invocation -> { + assertOutsideTransaction(f); + f.stored().put(Owner.GAME_DESIGN, gameDesignAbort); + f.stored().put(Owner.WORLD, worldAbort); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence(request, Optional.empty()); + }); when(f.worldClient().read(any())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(f); - var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); - return new WorldDraftTerminalReadEvidence(request, Optional.empty()); - }); + .thenAnswer(invocation -> { + assertOutsideTransaction(f); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new WorldDraftTerminalReadEvidence(request, Optional.empty()); + }); assertThat(f.service().reconcile(f.binding().operationId())) .contains(Settlement.FAILED_NONPUBLICATION); @@ -377,26 +355,24 @@ void mixedCommitOrderPreservesOriginalWorldCommitAndTerminalRetry() { OwnerReadback originalWorld = readback(f.binding(), Owner.WORLD, Outcome.COMMITTED, new byte[] {16}); when(f.gameDesignClient().read(any())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(f); - var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); - return new GameDesignDraftTerminalReadEvidence( - request, - Optional.of( - readback( - f.binding(), - Owner.GAME_DESIGN, - Outcome.DEFINITIVELY_ABORTED, - new byte[] {17}))); - }); + .thenAnswer(invocation -> { + assertOutsideTransaction(f); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence( + request, + Optional.of( + readback( + f.binding(), + Owner.GAME_DESIGN, + Outcome.DEFINITIVELY_ABORTED, + new byte[] {17}))); + }); when(f.worldClient().read(any())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(f); - var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); - return worldEvidence(request, originalWorld); - }); + .thenAnswer(invocation -> { + assertOutsideTransaction(f); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return worldEvidence(request, originalWorld); + }); assertThat(f.service().reconcile(f.binding().operationId())).contains(Settlement.PENDING); assertThat(f.stored().get(Owner.WORLD).canonicalBytes()) @@ -415,28 +391,23 @@ void mixedCommitOrderPreservesOriginalWorldCommitAndTerminalRetry() { void bothCommitOrderCommitsSettleAndRevokeOrderNeverAcceptsACommit() { Fixture committed = fixture(Ordering.COMMIT_ORDER); when(committed.gameDesignClient().read(any())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(committed); - var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); - return new GameDesignDraftTerminalReadEvidence( - request, - Optional.of( - readback( - committed.binding(), - Owner.GAME_DESIGN, - Outcome.COMMITTED, - new byte[] {20}))); - }); + .thenAnswer(invocation -> { + assertOutsideTransaction(committed); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence( + request, + Optional.of( + readback( + committed.binding(), Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {20}))); + }); when(committed.worldClient().read(any())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(committed); - var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); - return worldEvidence( - request, - readback(committed.binding(), Owner.WORLD, Outcome.COMMITTED, new byte[] {21})); - }); + .thenAnswer(invocation -> { + assertOutsideTransaction(committed); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return worldEvidence( + request, + readback(committed.binding(), Owner.WORLD, Outcome.COMMITTED, new byte[] {21})); + }); assertThat(committed.service().reconcile(committed.binding().operationId())) .contains(Settlement.COMMITTED); @@ -447,19 +418,18 @@ void bothCommitOrderCommitsSettleAndRevokeOrderNeverAcceptsACommit() { Owner.GAME_DESIGN, readback(revoked.binding(), Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {22})); when(revoked.worldClient().read(any())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(revoked); - var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); - return new WorldDraftTerminalReadEvidence( - request, - Optional.of( - readback( - revoked.binding(), - Owner.WORLD, - Outcome.DEFINITIVELY_ABORTED, - new byte[] {23}))); - }); + .thenAnswer(invocation -> { + assertOutsideTransaction(revoked); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new WorldDraftTerminalReadEvidence( + request, + Optional.of( + readback( + revoked.binding(), + Owner.WORLD, + Outcome.DEFINITIVELY_ABORTED, + new byte[] {23}))); + }); assertThat(revoked.service().reconcile(revoked.binding().operationId())) .contains(Settlement.PENDING); assertThat(revoked.stored().get(Owner.GAME_DESIGN).outcome()).isEqualTo(Outcome.COMMITTED); @@ -496,14 +466,12 @@ void absentReservedTerminalAndAmbientCasesNeverCallOwners() { var ambientTransaction = new TransactionTemplate(ambient.manager()); ambientTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); ambientTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - ambientTransaction.execute( - status -> { - assertThatThrownBy(() -> ambient.service().reconcile(ambient.binding().operationId())) - .isInstanceOf(IllegalStateException.class); - verifyNoInteractions( - ambient.repository(), ambient.gameDesignClient(), ambient.worldClient()); - return null; - }); + ambientTransaction.execute(status -> { + assertThatThrownBy(() -> ambient.service().reconcile(ambient.binding().operationId())) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(ambient.repository(), ambient.gameDesignClient(), ambient.worldClient()); + return null; + }); } @Test @@ -513,16 +481,14 @@ void v2WithoutWorldNeverReadsLooksUpOrRetainsWorldEvidence() { Ordering.COMMIT_ORDER, requiredBinding(List.of(DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE))); when(f.gameDesignClient().read(any())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(f); - var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); - return new GameDesignDraftTerminalReadEvidence( - request, - Optional.of( - readback( - f.binding(), Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {31}))); - }); + .thenAnswer(invocation -> { + assertOutsideTransaction(f); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence( + request, + Optional.of( + readback(f.binding(), Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {31}))); + }); assertThat(f.service().reconcile(f.binding().operationId())).contains(Settlement.COMMITTED); assertThat(f.service().reconcile(f.binding().operationId())).contains(Settlement.COMMITTED); @@ -543,24 +509,21 @@ void v2WorldAndGameDesignResultsCannotSettleMissingIndependentEntity() { DraftCommitBinding.Owner.WORLD_MANAGEMENT, DraftCommitBinding.Owner.ENTITY_MANAGEMENT))); when(f.gameDesignClient().read(any())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(f); - var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); - return new GameDesignDraftTerminalReadEvidence( - request, - Optional.of( - readback( - f.binding(), Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {32}))); - }); + .thenAnswer(invocation -> { + assertOutsideTransaction(f); + var request = (GameDesignDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return new GameDesignDraftTerminalReadEvidence( + request, + Optional.of( + readback(f.binding(), Owner.GAME_DESIGN, Outcome.COMMITTED, new byte[] {32}))); + }); when(f.worldClient().read(any())) - .thenAnswer( - invocation -> { - assertOutsideTransaction(f); - var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); - return worldEvidence( - request, readback(f.binding(), Owner.WORLD, Outcome.COMMITTED, new byte[] {33})); - }); + .thenAnswer(invocation -> { + assertOutsideTransaction(f); + var request = (WorldDraftTerminalReadEvidence.Request) invocation.getArgument(0); + return worldEvidence( + request, readback(f.binding(), Owner.WORLD, Outcome.COMMITTED, new byte[] {33})); + }); assertThat(f.service().reconcile(f.binding().operationId())).contains(Settlement.PENDING); byte[] originalWorld = f.stored().get(Owner.WORLD).canonicalBytes(); @@ -584,20 +547,18 @@ private static DraftAuthorizationFenceBinding requiredBinding( original.inputDigest()); var revisions = java.util.stream.IntStream.range(0, owners.size()) - .mapToObj( - index -> - new DraftCommitBinding.RevisionPayload( - Integer.toString(index), - UUID.randomUUID(), - owners.get(index), - "payload-" + index)) + .mapToObj(index -> + new DraftCommitBinding.RevisionPayload( + Integer.toString(index), + UUID.randomUUID(), + owners.get(index), + "payload-" + index)) .toList(); var affected = owners.stream() - .map( - owner -> - new DraftCommitBinding.AffectedUnit( - owner, "aggregate", owner.name(), "aggregate", owner.name(), "0")) + .map(owner -> + new DraftCommitBinding.AffectedUnit( + owner, "aggregate", owner.name(), "aggregate", owner.name(), "0")) .toList(); var complete = DraftCommitBinding.create( @@ -638,33 +599,30 @@ private static Fixture fixture(Ordering ordering, DraftAuthorizationFenceBinding when(repository.readOriginalBinding(any())).thenReturn(Optional.of(binding)); when(repository.read(any())).thenAnswer(invocation -> fenceSnapshot(binding, ordering)); when(repository.readOwnerResult(any(), any())) - .thenAnswer( - invocation -> { - Owner owner = invocation.getArgument(1); - OwnerReadback value = stored.get(owner); - return value == null - ? Optional.empty() - : Optional.of( - new DraftAuthorizationFenceRepository.OwnerResultSnapshot( - value.outcome(), value.canonicalBytes(), OffsetDateTime.now())); - }); + .thenAnswer(invocation -> { + Owner owner = invocation.getArgument(1); + OwnerReadback value = stored.get(owner); + return value == null + ? Optional.empty() + : Optional.of( + new DraftAuthorizationFenceRepository.OwnerResultSnapshot( + value.outcome(), value.canonicalBytes(), OffsetDateTime.now())); + }); when(repository.readSettlement(any())) - .thenAnswer( - invocation -> { - if (ordering == Ordering.RESERVED - || !stored.keySet().equals(java.util.Set.copyOf(binding.requiredOwners()))) { - return Settlement.PENDING; - } - if (ordering == Ordering.COMMIT_ORDER - && stored.values().stream() - .allMatch(value -> value.outcome() == Outcome.COMMITTED)) { - return Settlement.COMMITTED; - } - return stored.values().stream() - .allMatch(value -> value.outcome() == Outcome.DEFINITIVELY_ABORTED) - ? Settlement.FAILED_NONPUBLICATION - : Settlement.PENDING; - }); + .thenAnswer(invocation -> { + if (ordering == Ordering.RESERVED + || !stored.keySet().equals(java.util.Set.copyOf(binding.requiredOwners()))) { + return Settlement.PENDING; + } + if (ordering == Ordering.COMMIT_ORDER + && stored.values().stream().allMatch(value -> value.outcome() == Outcome.COMMITTED)) { + return Settlement.COMMITTED; + } + return stored.values().stream() + .allMatch(value -> value.outcome() == Outcome.DEFINITIVELY_ABORTED) + ? Settlement.FAILED_NONPUBLICATION + : Settlement.PENDING; + }); doAnswer( invocation -> { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceSelectedOwnerIntakeTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceSelectedOwnerIntakeTest.java index 38d6aacf84..2f2a8faf3d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceSelectedOwnerIntakeTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceSelectedOwnerIntakeTest.java @@ -75,10 +75,9 @@ void substitutedSelectedBindingCannotUseAnOriginalSettlement() throws Exception DraftCommitBinding changed = selected(fixture.selected.requestId(), fixture.selected.commitId(), "changed"); - assertThatThrownBy( - () -> - fixture.repository.requireSelectedOwnerIntakeAdmission( - List.of(fixture.currentSource), changed)) + assertThatThrownBy(() -> + fixture.repository.requireSelectedOwnerIntakeAdmission( + List.of(fixture.currentSource), changed)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("committed and settled"); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java index 53396c39fb..5e6b529d5a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java @@ -35,35 +35,31 @@ void clearTransaction() { void worldParticipationAdmissionRequiresWritableReadCommittedOwnerTransaction() throws Exception { Fixture fixture = new Fixture(false); - assertThatThrownBy( - () -> - fixture.repository.requireWorldParticipationDisclosureAdmission( - List.of(fixture.source))) + assertThatThrownBy(() -> + fixture.repository.requireWorldParticipationDisclosureAdmission( + List.of(fixture.source))) .isInstanceOf(IllegalStateException.class); TransactionSynchronizationManager.setActualTransactionActive(true); TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); - assertThatThrownBy( - () -> - fixture.repository.requireWorldParticipationDisclosureAdmission( - List.of(fixture.source))) + assertThatThrownBy(() -> + fixture.repository.requireWorldParticipationDisclosureAdmission( + List.of(fixture.source))) .isInstanceOf(IllegalStateException.class); TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); fixture.begin(); fixture.autoCommit = true; - assertThatThrownBy( - () -> - fixture.repository.requireWorldParticipationDisclosureAdmission( - List.of(fixture.source))) + assertThatThrownBy(() -> + fixture.repository.requireWorldParticipationDisclosureAdmission( + List.of(fixture.source))) .isInstanceOf(IllegalStateException.class); fixture.autoCommit = false; fixture.isolation = Connection.TRANSACTION_REPEATABLE_READ; - assertThatThrownBy( - () -> - fixture.repository.requireWorldParticipationDisclosureAdmission( - List.of(fixture.source))) + assertThatThrownBy(() -> + fixture.repository.requireWorldParticipationDisclosureAdmission( + List.of(fixture.source))) .isInstanceOf(IllegalStateException.class); assertThat(fixture.lockedKeys).isEmpty(); @@ -78,10 +74,8 @@ void pendingWorldParticipationBlocksDisclosureAdmissionAndChecksSortedExactKeys( SourceEvidence second = source("z-second"); fixture.pendingWorldKey = second.key(); - assertThatThrownBy( - () -> - fixture.repository.requireWorldParticipationDisclosureAdmission( - List.of(second, first))) + assertThatThrownBy(() -> + fixture.repository.requireWorldParticipationDisclosureAdmission(List.of(second, first))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("World participation remains pending"); @@ -117,11 +111,10 @@ void disclosurePreparationRejectsPendingWorldParticipationWithoutOwnerOperationR .anyMatch(statement -> statement.contains("account_selected_publication_sources")) .anyMatch(statement -> statement.contains("account_game_logic_intake_sources")); assertThat(fixture.fetchedSql) - .noneMatch( - statement -> - statement.contains("account_draft_authorization_fences") - || statement.contains( - "SELECT operation_id FROM account_draft_authorization_sources")); + .noneMatch(statement -> + statement.contains("account_draft_authorization_fences") + || statement.contains( + "SELECT operation_id FROM account_draft_authorization_sources")); assertThat(fixture.sql).noneMatch(statement -> statement.contains("UPDATE ")); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountOriginalNewFinalAdmissionReadClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountOriginalNewFinalAdmissionReadClientTest.java index b90eea8649..6bd2cfdda6 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountOriginalNewFinalAdmissionReadClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/AccountOriginalNewFinalAdmissionReadClientTest.java @@ -27,12 +27,11 @@ void acceptsTheContinuityCapAndPositiveShorterDurations() { @Test void rejectsContinuityDurationAboveTheCanonicalCap() { - assertThatThrownBy( - () -> - readback( - ADMISSION_AT_MILLIS, - MAX_CONTINUITY_DURATION_MILLIS + 1L, - ADMISSION_AT_MILLIS + MAX_CONTINUITY_DURATION_MILLIS + 1L)) + assertThatThrownBy(() -> + readback( + ADMISSION_AT_MILLIS, + MAX_CONTINUITY_DURATION_MILLIS + 1L, + ADMISSION_AT_MILLIS + MAX_CONTINUITY_DURATION_MILLIS + 1L)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Protected original final-admission readback is malformed"); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientMtlsTest.java index ec70086ff8..ee78806cbd 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientMtlsTest.java @@ -113,10 +113,9 @@ void wrongServerServiceOrNamespaceIsRejectedBeforeTheApplicationHandler() throws assertThatThrownBy( () -> client.listVisiblePublicProductionAdmissionTargets(UUID.randomUUID())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(service.calls()).hasValue(0); } } @@ -128,10 +127,9 @@ void staleCorrelationAndMalformedCompleteResponseRemainRefusals() throws Excepti try (var server = startServer("game-session", service); var client = newClient(server.port(), "account")) { client.init(); - service.respondWith( - request -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( - new DiscoveryRequest(UUID.randomUUID(), request.targetNamespace()), List.of())); + service.respondWith(request -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + new DiscoveryRequest(UUID.randomUUID(), request.targetNamespace()), List.of())); assertThatThrownBy( () -> client.listVisiblePublicProductionAdmissionTargets(UUID.randomUUID())) @@ -151,29 +149,27 @@ void staleCorrelationAndMalformedCompleteResponseRemainRefusals() throws Excepti @Test void oversizedAuthenticatedResponsePreservesResourceExhaustedFromInboundLimit() throws Exception { var service = new DiscoveryProbeService(); - service.respondWith( - request -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse(request, List.of()) - .toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField( - 100, - UnknownFieldSet.Field.newBuilder() - .addLengthDelimited(ByteString.copyFrom(new byte[4 * 1024 * 1024])) - .build()) - .build()) - .build()); + service.respondWith(request -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse(request, List.of()) + .toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 100, + UnknownFieldSet.Field.newBuilder() + .addLengthDelimited(ByteString.copyFrom(new byte[4 * 1024 * 1024])) + .build()) + .build()) + .build()); try (var server = startServer("game-session", service); var client = newClient(server.port(), "account")) { client.init(); assertThatThrownBy( () -> client.listVisiblePublicProductionAdmissionTargets(UUID.randomUUID())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.RESOURCE_EXHAUSTED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.RESOURCE_EXHAUSTED)); assertThat(service.calls()).hasValue(1); } } @@ -228,10 +224,9 @@ private static final class DiscoveryProbeService private final AtomicReference< Function> responseFactory = - new AtomicReference<>( - request -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( - request, List.of())); + new AtomicReference<>(request -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, List.of())); @Override public void listVisiblePublicProductionAdmissionTargets( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientTest.java index a9982c18b7..84618f51cf 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/CanonicalGameplayAdmissionDecisionReadClientTest.java @@ -131,9 +131,8 @@ void discoveryNeverConvertsTransportOrMalformedResponseIntoEmptySuccess() throws assertThatThrownBy( () -> f.client.listVisiblePublicProductionAdmissionTargets(UUID.randomUUID())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(status.getCode())); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(status.getCode())); } Fixture f = fixture(); when(f.stub.listVisiblePublicProductionAdmissionTargets(any())) @@ -184,16 +183,13 @@ void resolverUsesItsOwnFiniteDeadlineAndResponseBoundAndReturnsOnlyDecodedOwnerR when(f.stub.resolvePublishedRealmAdmissionTarget(request)).thenReturn(response); try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { codec - .when( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionRequest( - f.selector)) + .when(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionRequest(f.selector)) .thenReturn(request); codec - .when( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( - f.selector, response)) + .when(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( + f.selector, response)) .thenReturn(result); assertThat(f.client.resolvePublishedRealmAdmissionTarget(f.selector)).isSameAs(result); } @@ -216,21 +212,17 @@ void publishedReadRetainsItsFullPurposeBoundAndFiniteCompleteSourceDeadline() th when(f.stub.getPublishedRealmAdmissionOwnerRead(request)).thenReturn(response); try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { codec - .when( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmRequest(selector)) + .when(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmRequest(selector)) .thenReturn(request); codec - .when( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( - request)) + .when(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest(request)) .thenReturn(parsed); codec - .when( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( - parsed, response)) + .when(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsed, response)) .thenReturn(result); assertThat(f.client.readPublishedRealmAdmissionOwner(selector)).isSameAs(result); } @@ -249,9 +241,8 @@ void timeoutAndUnavailableAreNeverReinterpretedAsAbsence() throws Exception { .thenThrow(status.asRuntimeException()); assertThatThrownBy(() -> f.client.resolvePublishedRealmAdmissionTarget(f.selector)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(status.getCode())); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(status.getCode())); when(f.stub.getPublishedRealmAdmissionOwnerRead(any())) .thenThrow(status.asRuntimeException()); assertThatThrownBy(() -> f.client.readPublishedRealmAdmissionOwner(f.strictSelector())) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignAuthorizedTenantCreationClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignAuthorizedTenantCreationClientTest.java index 6c92e6706c..846424b92a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignAuthorizedTenantCreationClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignAuthorizedTenantCreationClientTest.java @@ -79,15 +79,14 @@ void sendsCompleteExactOriginalWithBoundedDeadlineAndExplicitDescriptionPresence for (String description : new String[] {null, ""}) { var f = new Fixture(description); when(f.stub.createAuthorizedTenant(any())) - .thenAnswer( - invocation -> { - var request = invocation.getArgument(0); - assertThat(request.getCreateRequestId()).isEqualTo(f.call.toString()); - assertThat(request.hasDescription()).isEqualTo(description != null); - assertThat(request.getCreationRequestDigest()) - .isEqualTo(f.binding.creationRequestDigest()); - return f.response(); - }); + .thenAnswer(invocation -> { + var request = invocation.getArgument(0); + assertThat(request.getCreateRequestId()).isEqualTo(f.call.toString()); + assertThat(request.hasDescription()).isEqualTo(description != null); + assertThat(request.getCreationRequestDigest()) + .isEqualTo(f.binding.creationRequestDigest()); + return f.response(); + }); assertThat(f.send()).isEqualTo(f.receipt); verify(f.stub).withDeadlineAfter(5000L, TimeUnit.MILLISECONDS); } @@ -157,10 +156,8 @@ void neverRetriesLostRepliesAndRefusesAmbientSqlOrExpiredDispatchBeforeNetwork() TransactionSynchronizationManager.setActualTransactionActive(true); assertThatThrownBy(untouched::send).isInstanceOf(IllegalStateException.class); TransactionSynchronizationManager.clear(); - assertThatThrownBy( - () -> - untouched.client.create( - untouched.call, untouched.binding, "fresh", "Game", null, 1L)) + assertThatThrownBy(() -> + untouched.client.create(untouched.call, untouched.binding, "fresh", "Game", null, 1L)) .isInstanceOf(IllegalStateException.class); verifyNoInteractions(untouched.stub); } @@ -170,10 +167,9 @@ void requiresFileMtlsAndPinsExactSameNamespaceGameDesignServer() throws Exceptio var tls = tls(); tls.setPlaintext(true); var channels = mock(GrpcChannelFactory.class); - assertThatThrownBy( - () -> - new GameDesignAuthorizedTenantCreationClient( - new ServiceEndpointsProperties(), tls, channels, "test")) + assertThatThrownBy(() -> + new GameDesignAuthorizedTenantCreationClient( + new ServiceEndpointsProperties(), tls, channels, "test")) .isInstanceOf(IllegalArgumentException.class); var f = new Fixture(null); Field field = GameDesignAuthorizedTenantCreationClient.class.getDeclaredField("peer"); @@ -187,10 +183,9 @@ void requiresFileMtlsAndPinsExactSameNamespaceGameDesignServer() throws Exceptio var missingFileTls = tls(); missingFileTls.setCertChain(tlsDirectory.resolve("missing-cert.pem").toString()); - assertThatThrownBy( - () -> - new GameDesignAuthorizedTenantCreationClient( - new ServiceEndpointsProperties(), missingFileTls, channels, "test")) + assertThatThrownBy(() -> + new GameDesignAuthorizedTenantCreationClient( + new ServiceEndpointsProperties(), missingFileTls, channels, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("existing readable file"); verifyNoInteractions(channels); @@ -245,10 +240,9 @@ void createAndCloseRequireInitializedClientAndCloseMakesItPermanentlyUnavailable .thenReturn(channel); var client = newClient(channelFactory); - assertThatThrownBy( - () -> - client.create( - f.call, f.binding, "fresh", "Game", null, System.currentTimeMillis() + 60_000)) + assertThatThrownBy(() -> + client.create( + f.call, f.binding, "fresh", "Game", null, System.currentTimeMillis() + 60_000)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not initialized"); assertThatThrownBy(() -> client.closeOriginal(f.binding)) @@ -262,10 +256,9 @@ void createAndCloseRequireInitializedClientAndCloseMakesItPermanentlyUnavailable .buildChannel(anyString(), eq(6565), any(CommonGrpcClientProperties.class), eq(true)); client.close(); - assertThatThrownBy( - () -> - client.create( - f.call, f.binding, "fresh", "Game", null, System.currentTimeMillis() + 60_000)) + assertThatThrownBy(() -> + client.create( + f.call, f.binding, "fresh", "Game", null, System.currentTimeMillis() + 60_000)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not initialized"); assertThatThrownBy(() -> client.closeOriginal(f.binding)) @@ -299,15 +292,9 @@ void createAndCloseRejectWrongServerPeerBeforeRequestReachesOwner() throws Excep assertThat(expectedPeer.get(baseStub.getCallOptions().getCredentials())) .isEqualTo("spiffe://firemud/ns/test/sa/game-design-service"); - assertThatThrownBy( - () -> - client.create( - f.call, - f.binding, - "fresh", - "Game", - null, - System.currentTimeMillis() + 60_000)) + assertThatThrownBy(() -> + client.create( + f.call, f.binding, "fresh", "Game", null, System.currentTimeMillis() + 60_000)) .isInstanceOf(StatusRuntimeException.class) .extracting(error -> ((StatusRuntimeException) error).getStatus().getCode()) .isEqualTo(Status.Code.UNAUTHENTICATED); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignFreshTenantIdentityClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignFreshTenantIdentityClientTest.java index 51294db75c..5d9944e726 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignFreshTenantIdentityClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignFreshTenantIdentityClientTest.java @@ -84,11 +84,10 @@ void exactResponseIsValidatedAndStableOnReplayWithoutCallingRetainedRpcs() throw verify(stub, times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); verify(stub, times(2)).resolveFreshTenantCreation(requestCaptor.capture()); assertThat(requestCaptor.getAllValues()) - .allSatisfy( - request -> { - assertThat(request.getCreationRequestId()).isEqualTo(REQUEST_ID.toString()); - assertThat(request.getExpectedRequestDigest()).isEqualTo(REQUEST_DIGEST); - }); + .allSatisfy(request -> { + assertThat(request.getCreationRequestId()).isEqualTo(REQUEST_ID.toString()); + assertThat(request.getExpectedRequestDigest()).isEqualTo(REQUEST_DIGEST); + }); verifyNoMoreInteractions(stub); } @@ -143,17 +142,15 @@ void rejectsPlaintextAndIncompleteAccountMtlsConfigurationBeforeChannelCreation( CommonGrpcClientProperties plaintext = mtlsProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new GameDesignFreshTenantIdentityClient( - new ServiceEndpointsProperties(), plaintext, channelFactory, "test")) + assertThatThrownBy(() -> + new GameDesignFreshTenantIdentityClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mTLS"); - assertThatThrownBy( - () -> - new GameDesignFreshTenantIdentityClient( - new ServiceEndpointsProperties(), null, channelFactory, "test")) + assertThatThrownBy(() -> + new GameDesignFreshTenantIdentityClient( + new ServiceEndpointsProperties(), null, channelFactory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("TLS configuration is required"); @@ -163,20 +160,18 @@ void rejectsPlaintextAndIncompleteAccountMtlsConfigurationBeforeChannelCreation( incompleteMtlsProperties("certs/account-client.crt", null, "certs/game-design-ca.crt"), incompleteMtlsProperties("certs/account-client.crt", "certs/account-client.key", null)); for (CommonGrpcClientProperties incomplete : incompleteConfigurations) { - assertThatThrownBy( - () -> - new GameDesignFreshTenantIdentityClient( - new ServiceEndpointsProperties(), incomplete, channelFactory, "test")) + assertThatThrownBy(() -> + new GameDesignFreshTenantIdentityClient( + new ServiceEndpointsProperties(), incomplete, channelFactory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("certificate, key, and CA"); } CommonGrpcClientProperties classpathMaterial = mtlsProperties(); classpathMaterial.setCertChain("classpath:certs/account-client.crt"); - assertThatThrownBy( - () -> - new GameDesignFreshTenantIdentityClient( - new ServiceEndpointsProperties(), classpathMaterial, channelFactory, "test")) + assertThatThrownBy(() -> + new GameDesignFreshTenantIdentityClient( + new ServiceEndpointsProperties(), classpathMaterial, channelFactory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("file-backed"); @@ -187,25 +182,20 @@ void rejectsPlaintextAndIncompleteAccountMtlsConfigurationBeforeChannelCreation( mtlsPropertiesWith( "certs/account-client.crt", "account-client.key", "classpath:ca.crt")); for (CommonGrpcClientProperties classpathConfiguration : classpathConfigurations) { - assertThatThrownBy( - () -> - new GameDesignFreshTenantIdentityClient( - new ServiceEndpointsProperties(), - classpathConfiguration, - channelFactory, - "test")) + assertThatThrownBy(() -> + new GameDesignFreshTenantIdentityClient( + new ServiceEndpointsProperties(), classpathConfiguration, channelFactory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("file-backed"); } for (String invalidNamespace : new String[] {null, "", "Upper", "not/a-label"}) { - assertThatThrownBy( - () -> - new GameDesignFreshTenantIdentityClient( - new ServiceEndpointsProperties(), - mtlsProperties(), - channelFactory, - invalidNamespace)) + assertThatThrownBy(() -> + new GameDesignFreshTenantIdentityClient( + new ServiceEndpointsProperties(), + mtlsProperties(), + channelFactory, + invalidNamespace)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("namespace"); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignOriginalTenantCreationOutcomeClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignOriginalTenantCreationOutcomeClientTest.java index 4f1b105e8b..6f8f778387 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignOriginalTenantCreationOutcomeClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameDesignOriginalTenantCreationOutcomeClientTest.java @@ -80,11 +80,10 @@ void copyDefaultTlsResources() throws Exception { void exactCreatedAndNotCreatedReadsReturnOnlyCodecValidatedEvidence() throws Exception { var stub = mockStub(); when(stub.resolveOriginalTenantCreationOutcome(any())) - .thenAnswer( - invocation -> - responseFor( - invocation.getArgument(0, ResolveOriginalTenantCreationOutcomeRequest.class), - Outcome.CREATED)); + .thenAnswer(invocation -> + responseFor( + invocation.getArgument(0, ResolveOriginalTenantCreationOutcomeRequest.class), + Outcome.CREATED)); var client = newClient(stub); var first = client.readOriginal(binding()); @@ -101,29 +100,27 @@ void exactCreatedAndNotCreatedReadsReturnOnlyCodecValidatedEvidence() throws Exc verify(stub, times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); verify(stub, times(2)).resolveOriginalTenantCreationOutcome(requests.capture()); assertThat(requests.getAllValues()) - .allSatisfy( - request -> { - assertThat(request.getSchemaVersion()).isEqualTo(1); - assertThat(request.getTargetNamespace()).isEqualTo("test"); - assertThat(request.getCreationRequestId()).isEqualTo(CREATION_ID.toString()); - assertThat(request.getAccountAuthorizationOperationId()) - .isEqualTo(AUTH_OPERATION_ID.toString()); - assertThat(request.getInitiatingAccountId()).isEqualTo(ACCOUNT_ID.toString()); - assertThat(request.getCreationRequestDigest()).isEqualTo(CREATION_DIGEST); - assertThat(request.getAccountAuthorizationDigest()).isEqualTo(AUTH_DIGEST); - assertThat(UUID.fromString(request.getReadRequestId())).isNotEqualTo(new UUID(0, 0)); - }); + .allSatisfy(request -> { + assertThat(request.getSchemaVersion()).isEqualTo(1); + assertThat(request.getTargetNamespace()).isEqualTo("test"); + assertThat(request.getCreationRequestId()).isEqualTo(CREATION_ID.toString()); + assertThat(request.getAccountAuthorizationOperationId()) + .isEqualTo(AUTH_OPERATION_ID.toString()); + assertThat(request.getInitiatingAccountId()).isEqualTo(ACCOUNT_ID.toString()); + assertThat(request.getCreationRequestDigest()).isEqualTo(CREATION_DIGEST); + assertThat(request.getAccountAuthorizationDigest()).isEqualTo(AUTH_DIGEST); + assertThat(UUID.fromString(request.getReadRequestId())).isNotEqualTo(new UUID(0, 0)); + }); assertThat(requests.getAllValues().get(0).getReadRequestId()) .isNotEqualTo(requests.getAllValues().get(1).getReadRequestId()); verifyNoMoreInteractions(stub); var notCreatedStub = mockStub(); when(notCreatedStub.resolveOriginalTenantCreationOutcome(any())) - .thenAnswer( - invocation -> - responseFor( - invocation.getArgument(0, ResolveOriginalTenantCreationOutcomeRequest.class), - Outcome.NOT_CREATED)); + .thenAnswer(invocation -> + responseFor( + invocation.getArgument(0, ResolveOriginalTenantCreationOutcomeRequest.class), + Outcome.NOT_CREATED)); var notCreated = newClient(notCreatedStub).readOriginal(binding()); assertThat(notCreated.evidence().outcome()).isEqualTo(Outcome.NOT_CREATED); assertThat(notCreated.evidence().receipt()).isEmpty(); @@ -132,60 +129,48 @@ void exactCreatedAndNotCreatedReadsReturnOnlyCodecValidatedEvidence() throws Exc @Test void refusesAnyChangedEchoOutcomeDigestOrNestedReceipt() throws Exception { assertRejected(response -> response.toBuilder().setTargetNamespace("other").build()); - assertRejected( - response -> - response.toBuilder().setCreationRequestId(UUID.randomUUID().toString()).build()); - assertRejected( - response -> - response.toBuilder() - .setAccountAuthorizationOperationId(UUID.randomUUID().toString()) - .build()); - assertRejected( - response -> - response.toBuilder().setInitiatingAccountId(UUID.randomUUID().toString()).build()); - assertRejected( - response -> - response.toBuilder().setCreationRequestDigest("sha256:" + "d".repeat(64)).build()); - assertRejected( - response -> - response.toBuilder().setAccountAuthorizationDigest("sha256:" + "e".repeat(64)).build()); + assertRejected(response -> + response.toBuilder().setCreationRequestId(UUID.randomUUID().toString()).build()); + assertRejected(response -> + response.toBuilder() + .setAccountAuthorizationOperationId(UUID.randomUUID().toString()) + .build()); + assertRejected(response -> + response.toBuilder().setInitiatingAccountId(UUID.randomUUID().toString()).build()); + assertRejected(response -> + response.toBuilder().setCreationRequestDigest("sha256:" + "d".repeat(64)).build()); + assertRejected(response -> + response.toBuilder().setAccountAuthorizationDigest("sha256:" + "e".repeat(64)).build()); assertRejected( response -> response.toBuilder().setReadRequestId(UUID.randomUUID().toString()).build()); assertRejected( response -> response.toBuilder().setEvidenceDigest("sha256:" + "f".repeat(64)).build()); assertRejected(response -> response.toBuilder().setSchemaVersion(2).build()); - assertRejected( - response -> - response.toBuilder() - .setOutcome( - OriginalTenantCreationOutcome.ORIGINAL_TENANT_CREATION_OUTCOME_UNSPECIFIED) - .build()); + assertRejected(response -> + response.toBuilder() + .setOutcome(OriginalTenantCreationOutcome.ORIGINAL_TENANT_CREATION_OUTCOME_UNSPECIFIED) + .build()); assertRejected(response -> response.toBuilder().setOutcomeValue(99).build()); - assertRejected( - response -> - response.toBuilder() - .setCreatedReceipt( - response.getCreatedReceipt().toBuilder() - .setCanonicalTenantId(UUID.randomUUID().toString())) - .build()); + assertRejected(response -> + response.toBuilder() + .setCreatedReceipt( + response.getCreatedReceipt().toBuilder() + .setCanonicalTenantId(UUID.randomUUID().toString())) + .build()); UnknownFieldSet unknown = UnknownFieldSet.newBuilder() .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) .build(); assertRejected(response -> response.toBuilder().setUnknownFields(unknown).build()); - assertRejected( - response -> - response.toBuilder() - .setCreatedReceipt( - response.getCreatedReceipt().toBuilder().setUnknownFields(unknown)) - .build()); - assertRejected( - response -> - response.toBuilder() - .setOutcome( - OriginalTenantCreationOutcome.ORIGINAL_TENANT_CREATION_OUTCOME_NOT_CREATED) - .setCreatedReceipt(ResolveFreshTenantCreationResponse.getDefaultInstance()) - .build()); + assertRejected(response -> + response.toBuilder() + .setCreatedReceipt(response.getCreatedReceipt().toBuilder().setUnknownFields(unknown)) + .build()); + assertRejected(response -> + response.toBuilder() + .setOutcome(OriginalTenantCreationOutcome.ORIGINAL_TENANT_CREATION_OUTCOME_NOT_CREATED) + .setCreatedReceipt(ResolveFreshTenantCreationResponse.getDefaultInstance()) + .build()); assertRejected(response -> response.toBuilder().clearCreatedReceipt().build()); } @@ -211,16 +196,15 @@ void absencePendingAndOutageArePropagatedWithoutInventingNoCreate() throws Excep void rejectsWrongLocalNamespaceAndInvalidBindingsBeforeRpc() throws Exception { var stub = mockStub(); var client = newClient(stub); - assertThatThrownBy( - () -> - client.readOriginal( - new Binding( - "other", - CREATION_ID, - AUTH_OPERATION_ID, - ACCOUNT_ID, - CREATION_DIGEST, - AUTH_DIGEST))) + assertThatThrownBy(() -> + client.readOriginal( + new Binding( + "other", + CREATION_ID, + AUTH_OPERATION_ID, + ACCOUNT_ID, + CREATION_DIGEST, + AUTH_DIGEST))) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> client.readOriginal(null)).isInstanceOf(NullPointerException.class); verifyNoInteractions(stub); @@ -231,16 +215,14 @@ void rejectsPlaintextAndIncompleteOrClasspathMtlsBeforeChannelCreation() { GrpcChannelFactory channels = mock(GrpcChannelFactory.class); CommonGrpcClientProperties plaintext = mtlsProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new GameDesignOriginalTenantCreationOutcomeClient( - new ServiceEndpointsProperties(), plaintext, channels, "test")) + assertThatThrownBy(() -> + new GameDesignOriginalTenantCreationOutcomeClient( + new ServiceEndpointsProperties(), plaintext, channels, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mTLS"); - assertThatThrownBy( - () -> - new GameDesignOriginalTenantCreationOutcomeClient( - new ServiceEndpointsProperties(), null, channels, "test")) + assertThatThrownBy(() -> + new GameDesignOriginalTenantCreationOutcomeClient( + new ServiceEndpointsProperties(), null, channels, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("workload mTLS"); for (CommonGrpcClientProperties incomplete : @@ -252,10 +234,9 @@ void rejectsPlaintextAndIncompleteOrClasspathMtlsBeforeChannelCreation() { mtlsPropertiesWith("cert", "classpath:key", "ca"), mtlsPropertiesWith("cert", "key", "classpath:ca") }) { - assertThatThrownBy( - () -> - new GameDesignOriginalTenantCreationOutcomeClient( - new ServiceEndpointsProperties(), incomplete, channels, "test")) + assertThatThrownBy(() -> + new GameDesignOriginalTenantCreationOutcomeClient( + new ServiceEndpointsProperties(), incomplete, channels, "test")) .isInstanceOf(IllegalArgumentException.class); } CommonGrpcClientProperties missingFile = @@ -263,17 +244,15 @@ void rejectsPlaintextAndIncompleteOrClasspathMtlsBeforeChannelCreation() { defaultTlsDirectory.resolve("missing-cert.pem").toString(), mtlsProperties().getPrivateKey(), mtlsProperties().getCaCert()); - assertThatThrownBy( - () -> - new GameDesignOriginalTenantCreationOutcomeClient( - new ServiceEndpointsProperties(), missingFile, channels, "test")) + assertThatThrownBy(() -> + new GameDesignOriginalTenantCreationOutcomeClient( + new ServiceEndpointsProperties(), missingFile, channels, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("readable file-backed TLS material"); for (String namespace : new String[] {null, "", "Upper", "not/a-label"}) { - assertThatThrownBy( - () -> - new GameDesignOriginalTenantCreationOutcomeClient( - new ServiceEndpointsProperties(), mtlsProperties(), channels, namespace)) + assertThatThrownBy(() -> + new GameDesignOriginalTenantCreationOutcomeClient( + new ServiceEndpointsProperties(), mtlsProperties(), channels, namespace)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("namespace"); } @@ -393,13 +372,11 @@ private void assertRejected(UnaryOperator - mutation.apply( - responseFor( - invocation.getArgument( - 0, ResolveOriginalTenantCreationOutcomeRequest.class), - Outcome.CREATED))); + .thenAnswer(invocation -> + mutation.apply( + responseFor( + invocation.getArgument(0, ResolveOriginalTenantCreationOutcomeRequest.class), + Outcome.CREATED))); assertThatThrownBy(() -> newClient(stub).readOriginal(binding())) .isInstanceOf(IllegalStateException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionCurrentPrivatePlaytestLifecycleReadClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionCurrentPrivatePlaytestLifecycleReadClientTest.java index a80494fb65..5dcd5bbb0e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionCurrentPrivatePlaytestLifecycleReadClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/GameSessionCurrentPrivatePlaytestLifecycleReadClientTest.java @@ -83,32 +83,29 @@ void trustedWrongWorkloadOrNamespaceCannotMintVerifiedEvidence() throws Exceptio @Test void changedCorrelationMalformedAndOverLimitResponsesFailClosed() throws Exception { try (var transport = new CurrentPrivatePlaytestReadTransportFixture(pki, directory, "gs")) { - transport.respond( - request -> - CurrentPrivatePlaytestLifecycleReadGrpcCodec.toResponse( - new CurrentPrivatePlaytestLifecycleReadGrpcCodec.Request( - UUID.randomUUID(), request.scope()), - Optional.empty())); + transport.respond(request -> + CurrentPrivatePlaytestLifecycleReadGrpcCodec.toResponse( + new CurrentPrivatePlaytestLifecycleReadGrpcCodec.Request( + UUID.randomUUID(), request.scope()), + Optional.empty())); assertThatThrownBy(() -> transport.client().read(scope())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("invalid"); - transport.respond( - request -> - ReadCurrentPrivatePlaytestLifecycleResponse.newBuilder() - .setCanonicalEvidence(ByteString.copyFromUtf8("{}")) - .build()); + transport.respond(request -> + ReadCurrentPrivatePlaytestLifecycleResponse.newBuilder() + .setCanonicalEvidence(ByteString.copyFromUtf8("{}")) + .build()); assertThatThrownBy(() -> transport.client().read(scope())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("invalid"); - transport.respond( - request -> - ReadCurrentPrivatePlaytestLifecycleResponse.newBuilder() - .setCanonicalEvidence( - ByteString.copyFrom( - new byte - [CurrentPrivatePlaytestLifecycleReadGrpcCodec.MAX_RESPONSE_WIRE_BYTES - + 1])) - .build()); + transport.respond(request -> + ReadCurrentPrivatePlaytestLifecycleResponse.newBuilder() + .setCanonicalEvidence( + ByteString.copyFrom( + new byte + [CurrentPrivatePlaytestLifecycleReadGrpcCodec.MAX_RESPONSE_WIRE_BYTES + + 1])) + .build()); assertThatThrownBy(() -> transport.client().read(scope())) .isInstanceOfSatisfying( io.grpc.StatusRuntimeException.class, @@ -134,11 +131,10 @@ void ambientSqlSynchronizationWrongNamespaceAndEndUserContextRefuseBeforeTranspo assertThatThrownBy(() -> transport.client().read(scope())) .isInstanceOf(IllegalStateException.class); SessionContext.clear(); - assertThatThrownBy( - () -> - transport - .client() - .read(new Scope("another-namespace", UUID.randomUUID(), "world", "realm"))) + assertThatThrownBy(() -> + transport + .client() + .read(new Scope("another-namespace", UUID.randomUUID(), "world", "realm"))) .isInstanceOf(IllegalArgumentException.class); assertThat(transport.calls()).isZero(); } @@ -148,13 +144,12 @@ void ambientSqlSynchronizationWrongNamespaceAndEndUserContextRefuseBeforeTranspo void plaintextCompositionIsUnavailable() { var plaintext = new CommonGrpcClientProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new GameSessionCurrentPrivatePlaytestLifecycleReadClient( - new ServiceEndpointsProperties(), - plaintext, - new GrpcChannelFactory(), - CurrentPrivatePlaytestReadTransportFixture.NAMESPACE)) + assertThatThrownBy(() -> + new GameSessionCurrentPrivatePlaytestLifecycleReadClient( + new ServiceEndpointsProperties(), + plaintext, + new GrpcChannelFactory(), + CurrentPrivatePlaytestReadTransportFixture.NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mTLS"); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/OwnerApprovedAccountTenantAssociationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/OwnerApprovedAccountTenantAssociationTest.java index 5c64e306da..12dc42cd98 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/OwnerApprovedAccountTenantAssociationTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/OwnerApprovedAccountTenantAssociationTest.java @@ -21,25 +21,24 @@ void rejectsNilCanonicalIdentityAndNoncanonicalSignature() { @Test void rejectsInvalidDigestAndSignedAt() { - assertThatThrownBy( - () -> - new OwnerApprovedAccountTenantAssociation( - 9, - UUID.randomUUID(), - "legacy-game-tenant", - 4, - "sha256:bad", - Instant.parse("2026-10-01T00:00:00Z"), - UUID.randomUUID(), - DIGEST, - Base64.getEncoder().encodeToString(new byte[64]), - "firemud", - "key-1", - "operator", - "ticket-1", - "not-an-instant", - 1, - 1)) + assertThatThrownBy(() -> + new OwnerApprovedAccountTenantAssociation( + 9, + UUID.randomUUID(), + "legacy-game-tenant", + 4, + "sha256:bad", + Instant.parse("2026-10-01T00:00:00Z"), + UUID.randomUUID(), + DIGEST, + Base64.getEncoder().encodeToString(new byte[64]), + "firemud", + "key-1", + "operator", + "ticket-1", + "not-an-instant", + 1, + 1)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java index e9f6ee1030..b19791dc47 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java @@ -89,12 +89,11 @@ void repeatedMtlsReadsBindTheExactTupleClaimPurposeAndDeadline() throws Exceptio StartSessionPreAuthorizationReservationTuple tuple = tuple(); List requests = new ArrayList<>(); try (MtlsFixture fixture = - mtlsFixture( - request -> { - requests.add(request); - assertThat(io.grpc.Context.current().getDeadline()).isNotNull(); - return validResponse(request, tuple.mutationDigest()); - })) { + mtlsFixture(request -> { + requests.add(request); + assertThat(io.grpc.Context.current().getDeadline()).isNotNull(); + return validResponse(request, tuple.mutationDigest()); + })) { StartSessionReservationEvidenceClient client = fixture.client(); ReadCurrentClaimEvidenceResponse issueFirst = @@ -134,15 +133,13 @@ void repeatedMtlsReadsBindTheExactTupleClaimPurposeAndDeadline() throws Exceptio assertThat(recoveryFirst).isEqualTo(recoveryRetry); assertThat(requests).hasSize(4); assertThat(requests) - .allSatisfy( - request -> { - assertThat(request.getControlPlaneRequestId()).isEqualTo(REQUEST_ID); - assertThat(request.getPreAuthorizationTupleJson().toByteArray()) - .containsExactly(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); - assertThat(request.getReservationOwnerId()) - .isEqualTo(RESERVATION_OWNER_ID.toString()); - assertThat(request.getReservationClaimFence()).isEqualTo(1L); - }); + .allSatisfy(request -> { + assertThat(request.getControlPlaneRequestId()).isEqualTo(REQUEST_ID); + assertThat(request.getPreAuthorizationTupleJson().toByteArray()) + .containsExactly(tuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + assertThat(request.getReservationOwnerId()).isEqualTo(RESERVATION_OWNER_ID.toString()); + assertThat(request.getReservationClaimFence()).isEqualTo(1L); + }); assertThat(requests.get(0).getPurpose()) .isEqualTo( StartSessionReservationEvidencePurpose @@ -198,15 +195,14 @@ void rejectsEveryResponseIdentityFieldUnknownFieldsAndStaleTimes() throws Except for (ReadCurrentClaimEvidenceResponse invalidResponse : invalid) { response.set(invalidResponse); - assertThatThrownBy( - () -> - client.readCurrentClaimEvidence( - tuple, - RESERVATION_OWNER_ID, - 1L, - RESERVATION_OWNER_ID, - 1L, - StartSessionReservationEvidenceClient.Purpose.ISSUE)) + assertThatThrownBy(() -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("stale or mismatched"); } @@ -247,52 +243,47 @@ void invalidInputIsRejectedBeforeAnyRpc() throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple(); AtomicInteger calls = new AtomicInteger(); try (MtlsFixture fixture = - mtlsFixture( - request -> { - calls.incrementAndGet(); - return validResponse(request, tuple.mutationDigest()); - })) { + mtlsFixture(request -> { + calls.incrementAndGet(); + return validResponse(request, tuple.mutationDigest()); + })) { StartSessionReservationEvidenceClient client = fixture.client(); - assertThatThrownBy( - () -> - client.readCurrentClaimEvidence( - null, - RESERVATION_OWNER_ID, - 1L, - RESERVATION_OWNER_ID, - 1L, - StartSessionReservationEvidenceClient.Purpose.ISSUE)) + assertThatThrownBy(() -> + client.readCurrentClaimEvidence( + null, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) .isInstanceOf(NullPointerException.class); - assertThatThrownBy( - () -> - client.readCurrentClaimEvidence( - tuple, - RESERVATION_OWNER_ID, - 0L, - RESERVATION_OWNER_ID, - 1L, - StartSessionReservationEvidenceClient.Purpose.ISSUE)) + assertThatThrownBy(() -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 0L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - client.readCurrentClaimEvidence( - tuple, - RESERVATION_OWNER_ID, - 1L, - RECOVERY_OWNER_ID, - 3L, - StartSessionReservationEvidenceClient.Purpose.ISSUE)) + assertThatThrownBy(() -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RECOVERY_OWNER_ID, + 3L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - client.readCurrentClaimEvidence( - tuple, - RESERVATION_OWNER_ID, - 1L, - RESERVATION_OWNER_ID, - 1L, - StartSessionReservationEvidenceClient.Purpose.RECOVER)) + assertThatThrownBy(() -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.RECOVER)) .isInstanceOf(IllegalArgumentException.class); assertThat(calls).hasValue(0); } @@ -304,35 +295,32 @@ void propagatesUnavailableAndStaleOwnerStatusesWithoutInterpretingThemAsEvidence StartSessionPreAuthorizationReservationTuple tuple = tuple(); AtomicReference status = new AtomicReference<>(Status.UNAVAILABLE); try (MtlsFixture fixture = - mtlsFixture( - request -> { - throw status.get().asRuntimeException(); - })) { + mtlsFixture(request -> { + throw status.get().asRuntimeException(); + })) { StartSessionReservationEvidenceClient client = fixture.client(); - assertThatThrownBy( - () -> - client.readCurrentClaimEvidence( - tuple, - RESERVATION_OWNER_ID, - 1L, - RESERVATION_OWNER_ID, - 1L, - StartSessionReservationEvidenceClient.Purpose.ISSUE)) + assertThatThrownBy(() -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) .isInstanceOf(StatusRuntimeException.class) .extracting(error -> ((StatusRuntimeException) error).getStatus().getCode()) .isEqualTo(Status.Code.UNAVAILABLE); status.set(Status.FAILED_PRECONDITION); - assertThatThrownBy( - () -> - client.readCurrentClaimEvidence( - tuple, - RESERVATION_OWNER_ID, - 1L, - RESERVATION_OWNER_ID, - 1L, - StartSessionReservationEvidenceClient.Purpose.ISSUE)) + assertThatThrownBy(() -> + client.readCurrentClaimEvidence( + tuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE)) .isInstanceOf(StatusRuntimeException.class) .extracting(error -> ((StatusRuntimeException) error).getStatus().getCode()) .isEqualTo(Status.Code.FAILED_PRECONDITION); @@ -393,10 +381,9 @@ void rejectsWrongAndMissingAuthenticatedServerIdentityBeforeRequestDelivery() th })) { assertThatThrownBy(() -> readIssue(fixture.client())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)) + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)) .hasMessageContaining("exact authenticated server workload identity"); } } @@ -407,11 +394,10 @@ void rejectsWrongAndMissingAuthenticatedServerIdentityBeforeRequestDelivery() th void rejectsAmbientTransactionAndSynchronizationBeforeAnyRpc() throws Exception { var calls = new AtomicInteger(); try (var fixture = - mtlsFixture( - request -> { - calls.incrementAndGet(); - return validResponse(request, tuple().mutationDigest()); - })) { + mtlsFixture(request -> { + calls.incrementAndGet(); + return validResponse(request, tuple().mutationDigest()); + })) { TransactionSynchronizationManager.setActualTransactionActive(true); assertThatThrownBy(() -> readIssue(fixture.client())) .isInstanceOf(IllegalStateException.class) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeBillingPrerequisiteObserverTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeBillingPrerequisiteObserverTest.java index 4e76953162..4c43599e87 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeBillingPrerequisiteObserverTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeBillingPrerequisiteObserverTest.java @@ -383,19 +383,19 @@ public Instant instant() { private static String customerResponse() { return """ - {"id":"cus_expected","object":"customer","deleted":false,"livemode":false, - "metadata":{"firemud_metadata_schema_version":"1", - "firemud_operation_type":"customer_provisioning", - "firemud_operation_id":"4e2af076-4a10-4aaf-93a0-e5df29271310", - "firemud_account_id":"79015b62-73ad-4dc0-a349-cc5b1a288a19"}} - """; + {"id":"cus_expected","object":"customer","deleted":false,"livemode":false, + "metadata":{"firemud_metadata_schema_version":"1", + "firemud_operation_type":"customer_provisioning", + "firemud_operation_id":"4e2af076-4a10-4aaf-93a0-e5df29271310", + "firemud_account_id":"79015b62-73ad-4dc0-a349-cc5b1a288a19"}} + """; } private static String customerResponseWithoutMetadata() { return """ - {"id":"cus_expected","object":"customer","deleted":false, - "livemode":false,"metadata":null} - """; + {"id":"cus_expected","object":"customer","deleted":false, + "livemode":false,"metadata":null} + """; } private static String customerResponseWithoutAccountMetadata() { @@ -406,10 +406,10 @@ private static String customerResponseWithoutAccountMetadata() { private static String paymentMethodResponse() { return """ - {"id":"pm_expected","object":"payment_method","type":"card","livemode":false, - "customer":"cus_expected","card":{"brand":"visa","last4":"4242", - "exp_month":12,"exp_year":2030}} - """; + {"id":"pm_expected","object":"payment_method","type":"card","livemode":false, + "customer":"cus_expected","card":{"brand":"visa","last4":"4242", + "exp_month":12,"exp_year":2030}} + """; } private static final class ControlledStripeTransport implements StripeResponseGetter { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java index 580cda3e13..12aac13eaa 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionObserverTest.java @@ -464,20 +464,20 @@ private static StripeHostingSubscriptionObserver.ExpectedBinding expected( private static String validResponse() { return """ - {"id":"sub_expected","object":"subscription","customer":"cus_expected", - "default_payment_method":"pm_expected","default_source":"src_ignored", - "livemode":false,"status":"active","cancel_at_period_end":false,"cancel_at":null, - "canceled_at":null,"ended_at":null, - "metadata":{"firemud_metadata_schema_version":"1", - "firemud_operation_type":"subscription_provisioning", - "firemud_operation_id":"4e2af076-4a10-4aaf-93a0-e5df29271310", - "firemud_subscription_id":"0c9ee07d-0e6d-4f66-9a87-54110acbc611", - "retained_marker":"evidence"}, - "items":{"object":"list","data":[{"id":"si_expected","object":"subscription_item", - "subscription":"sub_expected","quantity":1,"current_period_start":1778000000, - "current_period_end":1780592000,"price":{"id":"price_expected","object":"price"}}], - "has_more":false}} - """; + {"id":"sub_expected","object":"subscription","customer":"cus_expected", + "default_payment_method":"pm_expected","default_source":"src_ignored", + "livemode":false,"status":"active","cancel_at_period_end":false,"cancel_at":null, + "canceled_at":null,"ended_at":null, + "metadata":{"firemud_metadata_schema_version":"1", + "firemud_operation_type":"subscription_provisioning", + "firemud_operation_id":"4e2af076-4a10-4aaf-93a0-e5df29271310", + "firemud_subscription_id":"0c9ee07d-0e6d-4f66-9a87-54110acbc611", + "retained_marker":"evidence"}, + "items":{"object":"list","data":[{"id":"si_expected","object":"subscription_item", + "subscription":"sub_expected","quantity":1,"current_period_start":1778000000, + "current_period_end":1780592000,"price":{"id":"price_expected","object":"price"}}], + "has_more":false}} + """; } private static String singleItemData() { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java index 17e160a886..5e3fe348d6 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingSubscriptionProvisionerTest.java @@ -83,12 +83,11 @@ void initialCreateUsesExactDurableBindingsAndKeyThenIndependentlyReadsProvider() .extracting(RequestOptions::getIdempotencyKey) .containsExactly(null, null, null, OPERATION.toString(), null); assertThat(transport.options) - .allSatisfy( - options -> { - assertThat(options.getConnectTimeout()).isEqualTo(250); - assertThat(options.getReadTimeout()).isEqualTo(1000); - assertThat(options.getMaxNetworkRetries()).isZero(); - }); + .allSatisfy(options -> { + assertThat(options.getConnectTimeout()).isEqualTo(250); + assertThat(options.getReadTimeout()).isEqualTo(1000); + assertThat(options.getMaxNetworkRetries()).isZero(); + }); assertThat(transport.params.get(3)) .containsOnlyKeys( "customer", diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingWebhookVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingWebhookVerifierTest.java index 368df95ff1..2788d19c74 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingWebhookVerifierTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StripeHostingWebhookVerifierTest.java @@ -168,8 +168,8 @@ private static String signatureHeader(String secret, String payload, long timest private static String eventPayload() { return """ - {"id":"evt_local_signature_test","object":"event","api_version":"2025-02-24.acacia","created":__CREATED_TIMESTAMP__,"data":{"object":{"id":"sub_local_signature_test","object":"subscription","status":"active","metadata":{"description":"hébergement 🏠"}}},"livemode":false,"pending_webhooks":1,"request":null,"type":"customer.subscription.updated"} - """ + {"id":"evt_local_signature_test","object":"event","api_version":"2025-02-24.acacia","created":__CREATED_TIMESTAMP__,"data":{"object":{"id":"sub_local_signature_test","object":"subscription","status":"active","metadata":{"description":"hébergement 🏠"}}},"livemode":false,"pending_webhooks":1,"request":null,"type":"customer.subscription.updated"} + """ .replace("__CREATED_TIMESTAMP__", Long.toString(NOW.getEpochSecond())); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginProtectedSourcesConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginProtectedSourcesConfigurationTest.java index 9468d2277e..3fe30ea495 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginProtectedSourcesConfigurationTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginProtectedSourcesConfigurationTest.java @@ -59,9 +59,8 @@ void dedicatedUriRetainsExplicitTlsAclDatabaseAndCommandDeadline() { "not a URI containing secret" }) void refusesMissingAmbiguousOrWeakerUriWithoutRetainingCredentialCauses(String uri) { - assertThatThrownBy( - () -> - AccountGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri(uri, 500)) + assertThatThrownBy(() -> + AccountGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri(uri, 500)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Protected Account gameplay LOGIN configuration required") .hasNoCause(); @@ -70,11 +69,9 @@ void refusesMissingAmbiguousOrWeakerUriWithoutRetainingCredentialCauses(String u @ParameterizedTest @ValueSource(ints = {0, -1, 60_001}) void commandDeadlineMustBeExplicitAndBounded(int timeout) { - assertThatThrownBy( - () -> - AccountGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( - "rediss://account_coord_app:secret@coordination.example.invalid:6380/0", - timeout)) + assertThatThrownBy(() -> + AccountGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( + "rediss://account_coord_app:secret@coordination.example.invalid:6380/0", timeout)) .isInstanceOf(IllegalArgumentException.class) .hasNoCause(); } @@ -105,10 +102,9 @@ void protectedApiAndMaterializerMustMatchTheConfiguredNamespaceAndIncarnations() new AccountProtectedJwksSourceConfiguration() .accountPublicJwksApiBinding(trust, API_PATH, "test")) .isSameAs(construction.constructed().getFirst()); - assertThatThrownBy( - () -> - new AccountProtectedJwksSourceConfiguration() - .accountPublicJwksApiBinding(trust, API_PATH, "other")) + assertThatThrownBy(() -> + new AccountProtectedJwksSourceConfiguration() + .accountPublicJwksApiBinding(trust, API_PATH, "other")) .isInstanceOf(IllegalArgumentException.class) .hasNoCause(); } @@ -117,10 +113,9 @@ void protectedApiAndMaterializerMustMatchTheConfiguredNamespaceAndIncarnations() AccountJwtJwksApiBinding.class, (api, context) -> when(api.current()).thenReturn(apiBinding("test", "other-cluster")))) { - assertThatThrownBy( - () -> - new AccountProtectedJwksSourceConfiguration() - .accountPublicJwksApiBinding(trust, API_PATH, "test")) + assertThatThrownBy(() -> + new AccountProtectedJwksSourceConfiguration() + .accountPublicJwksApiBinding(trust, API_PATH, "test")) .isInstanceOf(IllegalArgumentException.class) .hasNoCause(); assertThat(construction.constructed()).hasSize(1); @@ -132,10 +127,9 @@ void missingWithdrawnOrAlternateProtectedSourcesNeverProduceAnApiBinding() { var trust = mock(AccountJwtSignerMaterializerTrustBinding.class); when(trust.current()).thenReturn(Optional.empty()); try (var construction = mockConstruction(AccountJwtJwksApiBinding.class)) { - assertThatThrownBy( - () -> - new AccountProtectedJwksSourceConfiguration() - .accountPublicJwksApiBinding(trust, API_PATH, "test")) + assertThatThrownBy(() -> + new AccountProtectedJwksSourceConfiguration() + .accountPublicJwksApiBinding(trust, API_PATH, "test")) .isInstanceOf(IllegalArgumentException.class) .hasNoCause(); assertThat(construction.constructed()).hasSize(1); @@ -147,23 +141,20 @@ void missingWithdrawnOrAlternateProtectedSourcesNeverProduceAnApiBinding() { (api, context) -> when(api.current()) .thenThrow(new AccountJwtJwksApiBinding.BindingRejectedException()))) { - assertThatThrownBy( - () -> - new AccountProtectedJwksSourceConfiguration() - .accountPublicJwksApiBinding(trust, API_PATH, "test")) + assertThatThrownBy(() -> + new AccountProtectedJwksSourceConfiguration() + .accountPublicJwksApiBinding(trust, API_PATH, "test")) .isInstanceOf(IllegalArgumentException.class) .hasNoCause(); assertThat(construction.constructed()).hasSize(1); } - assertThatThrownBy( - () -> - new AccountProtectedJwksSourceConfiguration() - .accountPublicJwksApiBinding(trust, "/alternate/binding", "test")) + assertThatThrownBy(() -> + new AccountProtectedJwksSourceConfiguration() + .accountPublicJwksApiBinding(trust, "/alternate/binding", "test")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountProtectedJwksSourceConfiguration() - .accountPublicJwksApiBinding(trust, API_PATH, "")) + assertThatThrownBy(() -> + new AccountProtectedJwksSourceConfiguration() + .accountPublicJwksApiBinding(trust, API_PATH, "")) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginSourceConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginSourceConfigurationTest.java index 29b075bd0c..989075b6b7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginSourceConfigurationTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountGameplayLoginSourceConfigurationTest.java @@ -66,22 +66,20 @@ class AccountGameplayLoginSourceConfigurationTest { void entireGraphIsAbsentByDefaultEvenWithoutOwnerInfrastructure() { new ApplicationContextRunner() .withUserConfiguration(CONFIGURATIONS) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(AccountGameplayAuthenticateReceiver.class); - assertThat(context).doesNotHaveBean(AccountGameplayDelegationSigner.class); - assertThat(context).doesNotHaveBean(AccountJwtJwksApiBinding.class); - assertThat(context).doesNotHaveBean(AccountGameplayDelegationRedisClient.class); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(AccountGameplayAuthenticateReceiver.class); + assertThat(context).doesNotHaveBean(AccountGameplayDelegationSigner.class); + assertThat(context).doesNotHaveBean(AccountJwtJwksApiBinding.class); + assertThat(context).doesNotHaveBean(AccountGameplayDelegationRedisClient.class); + }); new ApplicationContextRunner() .withUserConfiguration(CONFIGURATIONS) .withPropertyValues("firemud.account.gameplay-login.enabled=false") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(AccountGameplayAuthenticateReceiver.class); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(AccountGameplayAuthenticateReceiver.class); + }); } @Test @@ -107,76 +105,71 @@ void fullCompositionUsesGenuineIntermediateOwnersAndClosesItsDedicatedClient() { redisFactory.when(() -> RedisClient.create(any(RedisURI.class))).thenReturn(client); enabledContext() .withPropertyValues("firemud.account.public-jwks-read.enabled=true") - .run( - context -> { - assertThat(context).hasNotFailed(); - for (Class owner : - List.of( - AccountAuthEvidenceBundleRepository.class, - AccountGameplayDelegationIssuanceRepository.class, - AccountGameplayDelegationResponseEnvelopeRepository.class, - AccountGameplayDelegationResponseEnvelopeService.class, - AccountJwtJwksConfigMapClient.class, - AccountJwtJwksTrustedSource.class, - AccountGameplayDelegationSigner.class, - AccountGameplayDelegationRedisClient.class, - AccountGameplayDelegationAuthorityProjection.class, - AccountGameplayDelegationTokenRegistry.class, - AccountGameplayDelegationIssuanceCommitService.class, - AccountGameplayDelegationCommittedIssuanceOwner.class, - AccountGameplayDelegationResponseRecoveryOwner.class, - AccountGameplayAuthenticateReceiver.class)) { - assertThat(context).hasSingleBean(owner); - } + .run(context -> { + assertThat(context).hasNotFailed(); + for (Class owner : + List.of( + AccountAuthEvidenceBundleRepository.class, + AccountGameplayDelegationIssuanceRepository.class, + AccountGameplayDelegationResponseEnvelopeRepository.class, + AccountGameplayDelegationResponseEnvelopeService.class, + AccountJwtJwksConfigMapClient.class, + AccountJwtJwksTrustedSource.class, + AccountGameplayDelegationSigner.class, + AccountGameplayDelegationRedisClient.class, + AccountGameplayDelegationAuthorityProjection.class, + AccountGameplayDelegationTokenRegistry.class, + AccountGameplayDelegationIssuanceCommitService.class, + AccountGameplayDelegationCommittedIssuanceOwner.class, + AccountGameplayDelegationResponseRecoveryOwner.class, + AccountGameplayAuthenticateReceiver.class)) { + assertThat(context).hasSingleBean(owner); + } - var issuance = context.getBean(AccountGameplayDelegationIssuanceRepository.class); - var signer = context.getBean(AccountGameplayDelegationSigner.class); - var commits = context.getBean(AccountGameplayDelegationIssuanceCommitService.class); - var recovery = - context.getBean(AccountGameplayDelegationResponseRecoveryOwner.class); - var registry = context.getBean(AccountGameplayDelegationTokenRegistry.class); - var envelopes = - context.getBean(AccountGameplayDelegationResponseEnvelopeRepository.class); - assertThat(ReflectionTestUtils.getField(signer, "issuanceRepository")) - .isSameAs(issuance); - assertThat(ReflectionTestUtils.getField(commits, "signer")).isSameAs(signer); - assertThat(ReflectionTestUtils.getField(commits, "tokenRegistry")) - .isSameAs(registry); - assertThat(ReflectionTestUtils.getField(recovery, "responseEnvelopes")) - .isSameAs(envelopes); - assertThat(ReflectionTestUtils.getField(envelopes, "responseCryptography")) - .isSameAs(context.getBean("accountResponseEnvelopeCryptography")); - var receiver = context.getBean(AccountGameplayAuthenticateReceiver.class); - var login = ReflectionTestUtils.getField(receiver, "owner"); - assertThat(ReflectionTestUtils.getField(login, "commitOwner")).isSameAs(commits); - assertThat(ReflectionTestUtils.getField(login, "responseOwner")).isSameAs(recovery); - assertThat(ReflectionTestUtils.getField(receiver, "expectedWorkload")) - .isEqualTo("spiffe://firemud/ns/test/sa/game-session-service"); - assertThat(context.getBean(AcknowledgementRequirements.class)) - .isEqualTo(new AcknowledgementRequirements(1, 2, 900)); - var catalog = - (RedisScriptCatalog) - ReflectionTestUtils.getField( - context.getBean(AccountGameplayDelegationRedisClient.class), - "scriptCatalog"); - assertThat(catalog).isNotNull(); - assertThat(catalog.require(AccountGenerationProjectionRedisContract.SCRIPT_ID)) - .isEqualTo(AccountGenerationProjectionRedisContract.descriptor()); - assertThat( - catalog.require(AccountGameplayDelegationRedisClient.SCRIPT_ID).principal()) - .isEqualTo("account_coord_app"); - assertThat( - catalog - .require( - AccountGameplayDelegationRedisClient - .INITIAL_LOGIN_DISPOSAL_SCRIPT_ID) - .principal()) - .isEqualTo("account_coord_app"); - assertThat(apiConstruction.constructed()).hasSize(1); - verifyNoInteractions(context.getBean(DSLContext.class)); - verifyNoInteractions(context.getBean(AccountServiceImpl.class)); - verify(client, never()).connect(ByteArrayCodec.INSTANCE); - }); + var issuance = context.getBean(AccountGameplayDelegationIssuanceRepository.class); + var signer = context.getBean(AccountGameplayDelegationSigner.class); + var commits = context.getBean(AccountGameplayDelegationIssuanceCommitService.class); + var recovery = context.getBean(AccountGameplayDelegationResponseRecoveryOwner.class); + var registry = context.getBean(AccountGameplayDelegationTokenRegistry.class); + var envelopes = + context.getBean(AccountGameplayDelegationResponseEnvelopeRepository.class); + assertThat(ReflectionTestUtils.getField(signer, "issuanceRepository")) + .isSameAs(issuance); + assertThat(ReflectionTestUtils.getField(commits, "signer")).isSameAs(signer); + assertThat(ReflectionTestUtils.getField(commits, "tokenRegistry")).isSameAs(registry); + assertThat(ReflectionTestUtils.getField(recovery, "responseEnvelopes")) + .isSameAs(envelopes); + assertThat(ReflectionTestUtils.getField(envelopes, "responseCryptography")) + .isSameAs(context.getBean("accountResponseEnvelopeCryptography")); + var receiver = context.getBean(AccountGameplayAuthenticateReceiver.class); + var login = ReflectionTestUtils.getField(receiver, "owner"); + assertThat(ReflectionTestUtils.getField(login, "commitOwner")).isSameAs(commits); + assertThat(ReflectionTestUtils.getField(login, "responseOwner")).isSameAs(recovery); + assertThat(ReflectionTestUtils.getField(receiver, "expectedWorkload")) + .isEqualTo("spiffe://firemud/ns/test/sa/game-session-service"); + assertThat(context.getBean(AcknowledgementRequirements.class)) + .isEqualTo(new AcknowledgementRequirements(1, 2, 900)); + var catalog = + (RedisScriptCatalog) + ReflectionTestUtils.getField( + context.getBean(AccountGameplayDelegationRedisClient.class), + "scriptCatalog"); + assertThat(catalog).isNotNull(); + assertThat(catalog.require(AccountGenerationProjectionRedisContract.SCRIPT_ID)) + .isEqualTo(AccountGenerationProjectionRedisContract.descriptor()); + assertThat(catalog.require(AccountGameplayDelegationRedisClient.SCRIPT_ID).principal()) + .isEqualTo("account_coord_app"); + assertThat( + catalog + .require( + AccountGameplayDelegationRedisClient.INITIAL_LOGIN_DISPOSAL_SCRIPT_ID) + .principal()) + .isEqualTo("account_coord_app"); + assertThat(apiConstruction.constructed()).hasSize(1); + verifyNoInteractions(context.getBean(DSLContext.class)); + verifyNoInteractions(context.getBean(AccountServiceImpl.class)); + verify(client, never()).connect(ByteArrayCodec.INSTANCE); + }); var options = ArgumentCaptor.forClass(ClientOptions.class); verify(client).setOptions(options.capture()); assertThat(options.getValue().isAutoReconnect()).isFalse(); @@ -199,35 +192,32 @@ void absentMountSelectorsAndUnboundedRetentionFailWithoutOpeningConnections() { redisFactory.when(() -> RedisClient.create(any(RedisURI.class))).thenReturn(client); enabledContext() .withPropertyValues("firemud.account.gameplay-login.request-digest-keyring-path=") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasRootCauseInstanceOf(IllegalArgumentException.class) - .hasRootCauseMessage("Protected Account gameplay LOGIN configuration required"); - verify(client, never()).connect(ByteArrayCodec.INSTANCE); - }); + .run(context -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasRootCauseInstanceOf(IllegalArgumentException.class) + .hasRootCauseMessage("Protected Account gameplay LOGIN configuration required"); + verify(client, never()).connect(ByteArrayCodec.INSTANCE); + }); enabledContext() .withPropertyValues("firemud.account.response-envelope.keyring-path=") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasRootCauseInstanceOf(IllegalArgumentException.class) - .hasRootCauseMessage("Protected Account gameplay LOGIN configuration required"); - verify(client, never()).connect(ByteArrayCodec.INSTANCE); - }); + .run(context -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasRootCauseInstanceOf(IllegalArgumentException.class) + .hasRootCauseMessage("Protected Account gameplay LOGIN configuration required"); + verify(client, never()).connect(ByteArrayCodec.INSTANCE); + }); enabledContext() .withPropertyValues( "firemud.account.gameplay-login.registry-cleanup-margin-millis=300001") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasRootCauseInstanceOf(IllegalArgumentException.class) - .hasRootCauseMessage("Registry cleanup margin is outside its finite bound"); - verify(client, never()).connect(ByteArrayCodec.INSTANCE); - }); + .run(context -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasRootCauseInstanceOf(IllegalArgumentException.class) + .hasRootCauseMessage("Registry cleanup margin is outside its finite bound"); + verify(client, never()).connect(ByteArrayCodec.INSTANCE); + }); assertThat(apiConstruction.constructed()).isNotEmpty(); verify(client, never()).connect(ByteArrayCodec.INSTANCE); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiTransportTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiTransportTest.java index 65aa053af9..940c112faa 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiTransportTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtJwksApiTransportTest.java @@ -63,8 +63,9 @@ class AccountJwtJwksApiTransportTest { private static final Duration STALL_TIMEOUT = Duration.ofMillis(350); private static final byte[] SELF_REVIEW = (""" - {"apiVersion":"authentication.k8s.io/v1","kind":"SelfSubjectReview",%n\ - "status":{"userInfo":{"username":"%s"}}}%n""" + {"apiVersion":"authentication.k8s.io/v1","kind":"SelfSubjectReview",%n\ + "status":{"userInfo":{"username":"%s"}}}%n\ + """ .formatted(API_USERNAME)) .getBytes(StandardCharsets.UTF_8); private static final byte[] KUBE_SYSTEM_NAMESPACE = @@ -73,8 +74,9 @@ class AccountJwtJwksApiTransportTest { namespaceJson(NAMESPACE, NAMESPACE_UID).getBytes(StandardCharsets.UTF_8); private static final byte[] CONFIG_MAP = (""" - {"apiVersion":"v1","kind":"ConfigMap","metadata":{%n\ - "name":"jwt-jwks","namespace":"%s","uid":"%s","resourceVersion":"7"},"data":{}}%n""" + {"apiVersion":"v1","kind":"ConfigMap","metadata":{%n\ + "name":"jwt-jwks","namespace":"%s","uid":"%s","resourceVersion":"7"},"data":{}}%n\ + """ .formatted(NAMESPACE, CONFIG_MAP_UID)) .getBytes(StandardCharsets.UTF_8); @@ -741,8 +743,9 @@ private static void runOpenSsl(Path workingDirectory, String... arguments) throw private static String namespaceJson(String name, String uid) { return """ - {"apiVersion":"v1","kind":"Namespace","metadata":{"name":"%s","uid":"%s"},%n\ - "status":{"phase":"Active"}}%n""" + {"apiVersion":"v1","kind":"Namespace","metadata":{"name":"%s","uid":"%s"},%n\ + "status":{"phase":"Active"}}%n\ + """ .formatted(name, uid); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBindingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBindingTest.java index 9fb4d37984..b2718ec829 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBindingTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtReadinessTrustBindingTest.java @@ -55,36 +55,31 @@ void strictBindingPinsAccountRuntimeAndDedicatedHarnessIdentity() { @Test void missingExpiredDuplicateUnknownAndChangedIdentityBindingsAreRejected() { String valid = protectedConfig(NOW + 60); - assertThatThrownBy( - () -> - AccountJwtReadinessTrustBinding.parseProtectedBytes( - valid.getBytes(StandardCharsets.UTF_8), NOW + 60)) + assertThatThrownBy(() -> + AccountJwtReadinessTrustBinding.parseProtectedBytes( + valid.getBytes(StandardCharsets.UTF_8), NOW + 60)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountJwtReadinessTrustBinding.parseProtectedBytes( - (valid + "validatorInstanceId=other\n").getBytes(StandardCharsets.UTF_8), NOW)) + assertThatThrownBy(() -> + AccountJwtReadinessTrustBinding.parseProtectedBytes( + (valid + "validatorInstanceId=other\n").getBytes(StandardCharsets.UTF_8), NOW)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountJwtReadinessTrustBinding.parseProtectedBytes( - (valid + "untrusted=true\n").getBytes(StandardCharsets.UTF_8), NOW)) + assertThatThrownBy(() -> + AccountJwtReadinessTrustBinding.parseProtectedBytes( + (valid + "untrusted=true\n").getBytes(StandardCharsets.UTF_8), NOW)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountJwtReadinessTrustBinding.parseProtectedBytes( - valid - .replace( - "validatorInstanceId=account-validator-instance-7", - "validatorInstanceId=other") - .getBytes(StandardCharsets.UTF_8), - NOW)) + assertThatThrownBy(() -> + AccountJwtReadinessTrustBinding.parseProtectedBytes( + valid + .replace( + "validatorInstanceId=account-validator-instance-7", + "validatorInstanceId=other") + .getBytes(StandardCharsets.UTF_8), + NOW)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountJwtReadinessTrustBinding.parseProtectedBytes( - valid.replace("enabled=true", "enabled=false").getBytes(StandardCharsets.UTF_8), - NOW)) + assertThatThrownBy(() -> + AccountJwtReadinessTrustBinding.parseProtectedBytes( + valid.replace("enabled=true", "enabled=false").getBytes(StandardCharsets.UTF_8), + NOW)) .isInstanceOf(IllegalArgumentException.class); } @@ -191,30 +186,26 @@ void rejectsWritableAncestorEvenWhenTheImmediateDirectoryIsProtected() throws Ex try (MockedStatic mockedFiles = Mockito.mockStatic(Files.class, Mockito.CALLS_REAL_METHODS)) { mockedFiles - .when( - () -> - Files.getAttribute( - absoluteBinding, "unix:uid", java.nio.file.LinkOption.NOFOLLOW_LINKS)) + .when(() -> + Files.getAttribute( + absoluteBinding, "unix:uid", java.nio.file.LinkOption.NOFOLLOW_LINKS)) .thenReturn(0L); mockedFiles - .when( - () -> - Files.getPosixFilePermissions( - absoluteBinding, java.nio.file.LinkOption.NOFOLLOW_LINKS)) + .when(() -> + Files.getPosixFilePermissions( + absoluteBinding, java.nio.file.LinkOption.NOFOLLOW_LINKS)) .thenReturn(fileMode); for (Path ancestor : owners.keySet()) { Path resolvedAncestor = ancestor; mockedFiles - .when( - () -> - Files.getAttribute( - resolvedAncestor, "unix:uid", java.nio.file.LinkOption.NOFOLLOW_LINKS)) + .when(() -> + Files.getAttribute( + resolvedAncestor, "unix:uid", java.nio.file.LinkOption.NOFOLLOW_LINKS)) .thenAnswer(invocation -> owners.get(resolvedAncestor)); mockedFiles - .when( - () -> - Files.getPosixFilePermissions( - resolvedAncestor, java.nio.file.LinkOption.NOFOLLOW_LINKS)) + .when(() -> + Files.getPosixFilePermissions( + resolvedAncestor, java.nio.file.LinkOption.NOFOLLOW_LINKS)) .thenAnswer(invocation -> directoryModes.get(resolvedAncestor)); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBindingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBindingTest.java index 1e79326b38..a704a6746d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBindingTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtSignerMaterializerTrustBindingTest.java @@ -31,16 +31,14 @@ void strictProtectedFormatBindsClusterNamespaceUidsUriPinsAndRevision() { @Test void disabledOrIncompleteProtectedBindingCannotAuthorizeMaterializer() { - assertThatThrownBy( - () -> - AccountJwtSignerMaterializerTrustBinding.parseProtectedBytes( - "enabled=false\n".getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountJwtSignerMaterializerTrustBinding.parseProtectedBytes( + "enabled=false\n".getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountJwtSignerMaterializerTrustBinding.parseProtectedBytes( - protectedConfig("prod", "prod-cluster-1", "firemud-prod", "revision-7", "") - .getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountJwtSignerMaterializerTrustBinding.parseProtectedBytes( + protectedConfig("prod", "prod-cluster-1", "firemud-prod", "revision-7", "") + .getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); } @@ -48,25 +46,22 @@ void disabledOrIncompleteProtectedBindingCannotAuthorizeMaterializer() { void duplicateFieldsUnknownFieldsAndWrongNamespaceUriAreRejected() { String valid = protectedConfig("prod", "prod-cluster-1", "firemud-prod", "revision-7", "a".repeat(64)); - assertThatThrownBy( - () -> - AccountJwtSignerMaterializerTrustBinding.parseProtectedBytes( - (valid + "clusterId=prod-cluster-1\n").getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountJwtSignerMaterializerTrustBinding.parseProtectedBytes( + (valid + "clusterId=prod-cluster-1\n").getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountJwtSignerMaterializerTrustBinding.parseProtectedBytes( - (valid + "anotherField=not-accepted\n").getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountJwtSignerMaterializerTrustBinding.parseProtectedBytes( + (valid + "anotherField=not-accepted\n").getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); String wrongNamespaceUri = valid.replace( "spiffe://firemud/ns/firemud-prod/sa/jwt-signer-materializer", "spiffe://firemud/ns/other-namespace/sa/jwt-signer-materializer"); - assertThatThrownBy( - () -> - AccountJwtSignerMaterializerTrustBinding.parseProtectedBytes( - wrongNamespaceUri.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountJwtSignerMaterializerTrustBinding.parseProtectedBytes( + wrongNamespaceUri.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBindingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBindingTest.java index 98b4ba081a..cc1ce30fed 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBindingTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventoryBindingTest.java @@ -125,20 +125,18 @@ void parsesOnlyCompletePinnedRs256ApplicabilityAndProducesCanonicalRuntimeConfig @Test void rejectsDigestTamperingUnknownFieldsAndUnpinnedImage() throws Exception { byte[] valid = validBindingBytes(); - assertThatThrownBy( - () -> - AccountJwtValidatorInventoryBinding.parseProtectedBytes( - new String(valid, StandardCharsets.UTF_8) - .replace("cluster-test", "other-cluster") - .getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + new String(valid, StandardCharsets.UTF_8) + .replace("cluster-test", "other-cluster") + .getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalStateException.class); Map withUnknown = parseMap(valid); withUnknown.put("ambientTrust", true); - assertThatThrownBy( - () -> - AccountJwtValidatorInventoryBinding.parseProtectedBytes( - JSON.writeValueAsBytes(withUnknown))) + assertThatThrownBy(() -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(withUnknown))) .isInstanceOf(IllegalStateException.class); byte[] unpinnedImage = validBindingBytes("registry.example/firemud/player:latest"); @@ -162,10 +160,9 @@ void rejectsUnsortedDuplicateAndNoncanonicalPodIdentityPins() throws Exception { List pins = (List) validator.get("receiverPods"); validator.put("receiverPods", List.of(pins.get(1), pins.get(0))); rebindDigest(unsorted); - assertThatThrownBy( - () -> - AccountJwtValidatorInventoryBinding.parseProtectedBytes( - JSON.writeValueAsBytes(unsorted))) + assertThatThrownBy(() -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(unsorted))) .isInstanceOf(IllegalStateException.class); Map noncanonicalIp = parseMap(validBindingBytes()); @@ -177,10 +174,9 @@ void rejectsUnsortedDuplicateAndNoncanonicalPodIdentityPins() throws Exception { (Map) ((List) noncanonicalValidator.get("receiverPods")).get(0); firstPin.put("podIp", "010.0.0.10"); rebindDigest(noncanonicalIp); - assertThatThrownBy( - () -> - AccountJwtValidatorInventoryBinding.parseProtectedBytes( - JSON.writeValueAsBytes(noncanonicalIp))) + assertThatThrownBy(() -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(noncanonicalIp))) .isInstanceOf(IllegalStateException.class); Map uppercaseSpki = parseMap(validBindingBytes()); @@ -192,10 +188,9 @@ void rejectsUnsortedDuplicateAndNoncanonicalPodIdentityPins() throws Exception { (Map) ((List) uppercaseValidator.get("receiverPods")).get(1); secondPin.put("leafSpkiSha256", "D".repeat(64)); rebindDigest(uppercaseSpki); - assertThatThrownBy( - () -> - AccountJwtValidatorInventoryBinding.parseProtectedBytes( - JSON.writeValueAsBytes(uppercaseSpki))) + assertThatThrownBy(() -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(uppercaseSpki))) .isInstanceOf(IllegalStateException.class); Map sharedPodKey = parseMap(validBindingBytes()); @@ -207,10 +202,9 @@ void rejectsUnsortedDuplicateAndNoncanonicalPodIdentityPins() throws Exception { (List>) sharedKeyValidator.get("receiverPods"); sharedKeyPins.get(1).put("leafSpkiSha256", sharedKeyPins.get(0).get("leafSpkiSha256")); rebindDigest(sharedPodKey); - assertThatThrownBy( - () -> - AccountJwtValidatorInventoryBinding.parseProtectedBytes( - JSON.writeValueAsBytes(sharedPodKey))) + assertThatThrownBy(() -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(sharedPodKey))) .isInstanceOf(IllegalStateException.class); Map canonicalIpv6 = parseMap(validBindingBytes()); @@ -234,10 +228,9 @@ void rejectsUnsortedDuplicateAndNoncanonicalPodIdentityPins() throws Exception { ipv6Pin.put("podIp", "2001:0db8:0:0:0:0:0:1"); rebindDigest(canonicalIpv6); - assertThatThrownBy( - () -> - AccountJwtValidatorInventoryBinding.parseProtectedBytes( - JSON.writeValueAsBytes(canonicalIpv6))) + assertThatThrownBy(() -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(canonicalIpv6))) .isInstanceOf(IllegalStateException.class); } @@ -267,10 +260,9 @@ void rejectsOnePodLeafKeyPinnedToDifferentValidatorPods() throws Exception { sharedIdentity.put("validators", List.of(firstValidator, secondValidator)); rebindDigest(sharedIdentity); - assertThatThrownBy( - () -> - AccountJwtValidatorInventoryBinding.parseProtectedBytes( - JSON.writeValueAsBytes(sharedIdentity))) + assertThatThrownBy(() -> + AccountJwtValidatorInventoryBinding.parseProtectedBytes( + JSON.writeValueAsBytes(sharedIdentity))) .isInstanceOf(IllegalStateException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventorySourceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventorySourceTest.java index 534d36a8c1..bebd672629 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventorySourceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountJwtValidatorInventorySourceTest.java @@ -316,11 +316,10 @@ void returnsOnlyStableActualPodAndDeploymentIdentitiesAsNonAuthorizingEvidence() assertThat(snapshot.validators().get(0).pods().get(0).leafSpkiSha256()).isEqualTo(POD_SPKI); assertThat(snapshot.validators().get(0).replicaSets()) .singleElement() - .satisfies( - replicaSet -> { - assertThat(replicaSet.ownerDeploymentName()).isEqualTo("player-service"); - assertThat(replicaSet.ownerDeploymentUid()).isEqualTo(DEPLOYMENT_UID); - }); + .satisfies(replicaSet -> { + assertThat(replicaSet.ownerDeploymentName()).isEqualTo("player-service"); + assertThat(replicaSet.ownerDeploymentUid()).isEqualTo(DEPLOYMENT_UID); + }); assertThat(snapshot.digest()).matches("[0-9a-f]{64}"); assertThat(new String(snapshot.canonicalBytes(), StandardCharsets.UTF_8)) .contains("ownerDeploymentUid", DEPLOYMENT_UID, "podTemplateHash", POD_TEMPLATE_HASH) @@ -355,14 +354,13 @@ void initialOperationCanEnumerateExactRunningCandidatesBeforeKubernetesReadiness assertThat(snapshot.observationContext()).contains(context); assertThat(snapshot.validators()) .singleElement() - .satisfies( - validator -> { - assertThat(validator.pods()) - .extracting(AccountJwtValidatorInventorySource.PodObservation::uid) - .containsExactly(POD_UID); - assertThat(validator.image()).isEqualTo(IMAGE); - assertThat(validator.verifierConfigSha256()).isNotBlank(); - }); + .satisfies(validator -> { + assertThat(validator.pods()) + .extracting(AccountJwtValidatorInventorySource.PodObservation::uid) + .containsExactly(POD_UID); + assertThat(validator.image()).isEqualTo(IMAGE); + assertThat(validator.verifierConfigSha256()).isNotBlank(); + }); assertThat(new String(snapshot.canonicalBytes(), StandardCharsets.UTF_8)) .contains( "INITIAL_NO_ACTIVE_SIGNER_CANDIDATES", @@ -378,13 +376,12 @@ void nonReadyCandidatesRemainUnavailableForNormalRotationAndUnboundObservation() fixture.stubNotReadyCandidates(); assertUnavailable(fixture); - assertThatThrownBy( - () -> - fixture.source.observe( - new ObservationContext( - ObservationPurpose.STRICT_READY, - UUID.fromString("66666666-6666-4666-8666-666666666666"), - "9".repeat(64)))) + assertThatThrownBy(() -> + fixture.source.observe( + new ObservationContext( + ObservationPurpose.STRICT_READY, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + "9".repeat(64)))) .isInstanceOf(InventoryUnavailableException.class) .hasNoCause(); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountPublicJwksSourceConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountPublicJwksSourceConfigurationTest.java index 0dc0547011..7bc1859c85 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountPublicJwksSourceConfigurationTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountPublicJwksSourceConfigurationTest.java @@ -35,19 +35,18 @@ class AccountPublicJwksSourceConfigurationTest { @Test void noSourceOrReceiverIsRegisteredByDefault() { - context.run( - ctx -> { - assertThat(ctx).hasNotFailed(); - assertThat(ctx).doesNotHaveBean(AccountProtectedJwksSourceConfiguration.class); - assertThat(ctx).doesNotHaveBean(AccountJwtJwksApiBinding.class); - assertThat(ctx).doesNotHaveBean(AccountJwtJwksConfigMapClient.class); - assertThat(ctx).doesNotHaveBean(AccountJwtJwksTrustedSource.class); - assertThat( - AnnotationUtils.findAnnotation( - AccountProtectedJwksSourceConfiguration.class, Component.class)) - .isNull(); - assertThat(ctx).doesNotHaveBean(AccountPublicJwksReadGrpcService.class); - }); + context.run(ctx -> { + assertThat(ctx).hasNotFailed(); + assertThat(ctx).doesNotHaveBean(AccountProtectedJwksSourceConfiguration.class); + assertThat(ctx).doesNotHaveBean(AccountJwtJwksApiBinding.class); + assertThat(ctx).doesNotHaveBean(AccountJwtJwksConfigMapClient.class); + assertThat(ctx).doesNotHaveBean(AccountJwtJwksTrustedSource.class); + assertThat( + AnnotationUtils.findAnnotation( + AccountProtectedJwksSourceConfiguration.class, Component.class)) + .isNull(); + assertThat(ctx).doesNotHaveBean(AccountPublicJwksReadGrpcService.class); + }); } @Test @@ -93,24 +92,23 @@ void selectedConsumersImportExactlyOneProtectedGraphWithoutSelectingEachOther(St "transactionManager", PlatformTransactionManager.class, () -> mock(PlatformTransactionManager.class)) - .run( - ctx -> { - assertThat(ctx).hasNotFailed(); - assertThat(ctx).hasSingleBean(AccountProtectedJwksSourceConfiguration.class); - assertThat(ctx).hasSingleBean(AccountJwtJwksApiBinding.class); - assertThat(ctx).hasSingleBean(AccountJwtJwksConfigMapClient.class); - assertThat(ctx).hasSingleBean(AccountJwtJwksTrustedSource.class); - if (selection.equals("read") || selection.equals("all")) { - assertThat(ctx).hasSingleBean(AccountPublicJwksReadService.class); - assertThat(ctx).hasSingleBean(AccountPublicJwksReadGrpcService.class); - } else { - assertThat(ctx).doesNotHaveBean(AccountPublicJwksReadService.class); - assertThat(ctx).doesNotHaveBean(AccountPublicJwksReadGrpcService.class); - } - assertThat(ctx).doesNotHaveBean(AccountGameplayDelegationRedisClient.class); - assertThat(construction.constructed()).hasSize(1); - verifyNoInteractions(signers, publications); - }); + .run(ctx -> { + assertThat(ctx).hasNotFailed(); + assertThat(ctx).hasSingleBean(AccountProtectedJwksSourceConfiguration.class); + assertThat(ctx).hasSingleBean(AccountJwtJwksApiBinding.class); + assertThat(ctx).hasSingleBean(AccountJwtJwksConfigMapClient.class); + assertThat(ctx).hasSingleBean(AccountJwtJwksTrustedSource.class); + if (selection.equals("read") || selection.equals("all")) { + assertThat(ctx).hasSingleBean(AccountPublicJwksReadService.class); + assertThat(ctx).hasSingleBean(AccountPublicJwksReadGrpcService.class); + } else { + assertThat(ctx).doesNotHaveBean(AccountPublicJwksReadService.class); + assertThat(ctx).doesNotHaveBean(AccountPublicJwksReadGrpcService.class); + } + assertThat(ctx).doesNotHaveBean(AccountGameplayDelegationRedisClient.class); + assertThat(construction.constructed()).hasSize(1); + verifyNoInteractions(signers, publications); + }); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java index 1bbffbc433..0ed01a5462 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java @@ -56,29 +56,24 @@ class AccountStartSessionOperatorAuthorizationConfigurationTest { void ownerCompositionIsAbsentWhenTheOptInIsMissingOrFalse() { contextRunner() .withUserConfiguration(AccountStartSessionOperatorAuthorizationConfiguration.class) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context) - .doesNotHaveBean(AccountStartSessionOperatorAuthorizationService.class); - assertThat(context) - .doesNotHaveBean(AccountOperatorAuthorizationFingerprintKeyring.class); - assertThat(context).doesNotHaveBean(AccountResponseEnvelopeCryptography.class); - assertThat(context) - .doesNotHaveBean(AccountStartSessionAuthorityCaptureRepository.class); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .doesNotHaveBean(AccountStartSessionOperatorAuthorizationService.class); + assertThat(context).doesNotHaveBean(AccountOperatorAuthorizationFingerprintKeyring.class); + assertThat(context).doesNotHaveBean(AccountResponseEnvelopeCryptography.class); + assertThat(context).doesNotHaveBean(AccountStartSessionAuthorityCaptureRepository.class); + }); contextRunner() .withUserConfiguration(AccountStartSessionOperatorAuthorizationConfiguration.class) .withPropertyValues(OPT_IN + "=false") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context) - .doesNotHaveBean(AccountStartSessionOperatorAuthorizationService.class); - assertThat(context) - .doesNotHaveBean(AccountStartSessionAuthorityCaptureRepository.class); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .doesNotHaveBean(AccountStartSessionOperatorAuthorizationService.class); + assertThat(context).doesNotHaveBean(AccountStartSessionAuthorityCaptureRepository.class); + }); } @Test @@ -117,55 +112,48 @@ void explicitOptInFailsClosedWhenOwnerAndKeySourcesAreUnavailable() { "firemud.account.start-session-operator-authorization.fingerprint-post-expiry-retention=PT24H", OPERATOR_KEYRING_PATH + "=/run/test/operator-response", GENERAL_KEYRING_PATH + "=/run/test/general-response") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(rootCause(context.getStartupFailure())) - .hasMessageContaining(AccountControlUiActorService.class.getName()); - }); + .run(context -> { + assertThat(context).hasFailed(); + assertThat(rootCause(context.getStartupFailure())) + .hasMessageContaining(AccountControlUiActorService.class.getName()); + }); } @Test void explicitOptInUsesSuppliedCollaboratorsAndQualifiedOperatorCryptography() { enabledContext() - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context) - .hasSingleBean(AccountStartSessionOperatorAuthorizationService.class); - assertThat(context).hasSingleBean(DSLContext.class); - assertThat(context) - .hasSingleBean(AccountStartSessionAuthorityCaptureRepository.class); - assertThat(context) - .hasSingleBean(AccountOperatorAuthorizationFingerprintKeyring.class); - assertThat(context.getBeansOfType(AccountResponseEnvelopeCryptography.class)) - .hasSize(2) - .containsKeys( - "genericAccountResponseEnvelopeCryptography", - OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN); - assertThat( - ReflectionTestUtils.getField( - context.getBean(AccountStartSessionAuthorityCaptureRepository.class), - "dsl")) - .isSameAs(context.getBean(DSLContext.class)); - - AccountResponseEnvelopeCryptography genericCryptography = - context.getBean( - "genericAccountResponseEnvelopeCryptography", - AccountResponseEnvelopeCryptography.class); - AccountResponseEnvelopeCryptography operatorCryptography = - context.getBean( - OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN, - AccountResponseEnvelopeCryptography.class); - assertThat(operatorCryptography).isNotSameAs(genericCryptography); - assertThat(ReflectionTestUtils.getField(operatorCryptography, "keyring")) - .isNotSameAs(ReflectionTestUtils.getField(genericCryptography, "keyring")); - assertThat( - ReflectionTestUtils.getField( - context.getBean(AccountStartSessionOperatorAuthorizationService.class), - "responseCryptography")) - .isSameAs(operatorCryptography); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(AccountStartSessionOperatorAuthorizationService.class); + assertThat(context).hasSingleBean(DSLContext.class); + assertThat(context).hasSingleBean(AccountStartSessionAuthorityCaptureRepository.class); + assertThat(context).hasSingleBean(AccountOperatorAuthorizationFingerprintKeyring.class); + assertThat(context.getBeansOfType(AccountResponseEnvelopeCryptography.class)) + .hasSize(2) + .containsKeys( + "genericAccountResponseEnvelopeCryptography", + OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN); + assertThat( + ReflectionTestUtils.getField( + context.getBean(AccountStartSessionAuthorityCaptureRepository.class), "dsl")) + .isSameAs(context.getBean(DSLContext.class)); + + AccountResponseEnvelopeCryptography genericCryptography = + context.getBean( + "genericAccountResponseEnvelopeCryptography", + AccountResponseEnvelopeCryptography.class); + AccountResponseEnvelopeCryptography operatorCryptography = + context.getBean( + OPERATOR_RESPONSE_CRYPTOGRAPHY_BEAN, AccountResponseEnvelopeCryptography.class); + assertThat(operatorCryptography).isNotSameAs(genericCryptography); + assertThat(ReflectionTestUtils.getField(operatorCryptography, "keyring")) + .isNotSameAs(ReflectionTestUtils.getField(genericCryptography, "keyring")); + assertThat( + ReflectionTestUtils.getField( + context.getBean(AccountStartSessionOperatorAuthorizationService.class), + "responseCryptography")) + .isSameAs(operatorCryptography); + }); } @Test @@ -208,12 +196,11 @@ void missingOrReusedOperatorResponseMountPreventsOwnerComposition() { RESPONSE_RECOVERY_WINDOW + "=PT30S", "firemud.account.start-session-operator-authorization.fingerprint-post-expiry-retention=PT24H", GENERAL_KEYRING_PATH + "=/run/test/general-response") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(rootCause(context.getStartupFailure())) - .hasMessageContaining("Absolute operator response keyring mount is required"); - }); + .run(context -> { + assertThat(context).hasFailed(); + assertThat(rootCause(context.getStartupFailure())) + .hasMessageContaining("Absolute operator response keyring mount is required"); + }); assertStartupFailure( enabledContext( @@ -223,12 +210,10 @@ void missingOrReusedOperatorResponseMountPreventsOwnerComposition() { private static void assertStartupFailure( ApplicationContextRunner runner, String expectedRootCause) { - runner.run( - context -> { - assertThat(context).hasFailed(); - assertThat(rootCause(context.getStartupFailure())) - .hasMessageContaining(expectedRootCause); - }); + runner.run(context -> { + assertThat(context).hasFailed(); + assertThat(rootCause(context.getStartupFailure())).hasMessageContaining(expectedRootCause); + }); } private static Throwable rootCause(Throwable failure) { @@ -268,9 +253,8 @@ private static ApplicationContextRunner enabledContext( private static ApplicationContextRunner contextRunner() { return new ApplicationContextRunner() - .withInitializer( - context -> - context.getBeanFactory().setConversionService(new ApplicationConversionService())); + .withInitializer(context -> + context.getBeanFactory().setConversionService(new ApplicationConversionService())); } @TestConfiguration(proxyBeanMethods = false) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundleTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundleTest.java index 2ff5640e6b..1ec307a9b0 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundleTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountAuthEvidenceBundleTest.java @@ -50,72 +50,68 @@ void encodesAndReadsOnlyTheClosedCanonicalNonTenantProfile() { @Test void canonicalEvidenceCarrierHonorsItsProfileLimitWithinTheLargerEnvelopeBound() { - assertThatCode( - () -> - new Binding( - "game-session-account-delegation", - "request-1", - new byte[32], - WORKLOAD, - "operation-1", - Optional.empty(), - Optional.empty(), - Optional.empty(), - 1L, - new byte[] {'{', '}'}, - new byte[] {'{', '}'}, - new byte[AccountAuthEvidenceBundle.MAX_CANONICAL_BYTES])) + assertThatCode(() -> + new Binding( + "game-session-account-delegation", + "request-1", + new byte[32], + WORKLOAD, + "operation-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1L, + new byte[] {'{', '}'}, + new byte[] {'{', '}'}, + new byte[AccountAuthEvidenceBundle.MAX_CANONICAL_BYTES])) .doesNotThrowAnyException(); assertThatThrownBy(() -> AccountAuthEvidenceBundle.parseCanonical(new byte[8 * 1024 + 1])) .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class) .hasMessageContaining("byte bound"); - assertThatCode( - () -> - new Binding( - "game-session-account-delegation", - "request-1", - new byte[32], - WORKLOAD, - "operation-1", - Optional.empty(), - Optional.empty(), - Optional.empty(), - 1L, - new byte[] {'{', '}'}, - new byte[] {'{', '}'}, - new byte[8 * 1024 + 1])) + assertThatCode(() -> + new Binding( + "game-session-account-delegation", + "request-1", + new byte[32], + WORKLOAD, + "operation-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1L, + new byte[] {'{', '}'}, + new byte[] {'{', '}'}, + new byte[8 * 1024 + 1])) .doesNotThrowAnyException(); - assertThatCode( - () -> - new Binding( - "game-session-account-delegation", - "request-1", - new byte[32], - WORKLOAD, - "operation-1", - Optional.empty(), - Optional.empty(), - Optional.empty(), - 1L, - new byte[] {'{', '}'}, - new byte[] {'{', '}'}, - new byte[128 * 1024])) + assertThatCode(() -> + new Binding( + "game-session-account-delegation", + "request-1", + new byte[32], + WORKLOAD, + "operation-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1L, + new byte[] {'{', '}'}, + new byte[] {'{', '}'}, + new byte[128 * 1024])) .doesNotThrowAnyException(); - assertThatThrownBy( - () -> - new Binding( - "game-session-account-delegation", - "request-1", - new byte[32], - WORKLOAD, - "operation-1", - Optional.empty(), - Optional.empty(), - Optional.empty(), - 1L, - new byte[] {'{', '}'}, - new byte[] {'{', '}'}, - new byte[128 * 1024 + 1])) + assertThatThrownBy(() -> + new Binding( + "game-session-account-delegation", + "request-1", + new byte[32], + WORKLOAD, + "operation-1", + Optional.empty(), + Optional.empty(), + Optional.empty(), + 1L, + new byte[] {'{', '}'}, + new byte[] {'{', '}'}, + new byte[128 * 1024 + 1])) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("authority evidence bundle bytes"); } @@ -125,40 +121,32 @@ void strictParserRejectsDuplicateTrailingUnknownNullAndNonCanonicalInput() { byte[] valid = AccountAuthEvidenceBundle.fromOwnerEvaluation(evaluation()).canonicalBytes(); String text = new String(valid, StandardCharsets.UTF_8); - assertThatThrownBy( - () -> - AccountAuthEvidenceBundle.parseCanonical( - "{\"schema\":\"first\",\"schema\":\"second\"}" - .getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountAuthEvidenceBundle.parseCanonical( + "{\"schema\":\"first\",\"schema\":\"second\"}".getBytes(StandardCharsets.UTF_8))) .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); - assertThatThrownBy( - () -> - AccountAuthEvidenceBundle.parseCanonical( - (text + "{}\n").getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountAuthEvidenceBundle.parseCanonical( + (text + "{}\n").getBytes(StandardCharsets.UTF_8))) .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); - assertThatThrownBy( - () -> - AccountAuthEvidenceBundle.parseCanonical( - text.replace("\"schema\":", "\"unknown\":null,\"schema\":") - .getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountAuthEvidenceBundle.parseCanonical( + text.replace("\"schema\":", "\"unknown\":null,\"schema\":") + .getBytes(StandardCharsets.UTF_8))) .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); - assertThatThrownBy( - () -> - AccountAuthEvidenceBundle.parseCanonical( - text.replace( - "\"audience\":\"account-service\"", - "\"audience\":\"account-service\",\"privateKey\":\"fixture\"") - .getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountAuthEvidenceBundle.parseCanonical( + text.replace( + "\"audience\":\"account-service\"", + "\"audience\":\"account-service\",\"privateKey\":\"fixture\"") + .getBytes(StandardCharsets.UTF_8))) .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); - assertThatThrownBy( - () -> - AccountAuthEvidenceBundle.parseCanonical( - (" " + text).getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountAuthEvidenceBundle.parseCanonical((" " + text).getBytes(StandardCharsets.UTF_8))) .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); - assertThatThrownBy( - () -> - AccountAuthEvidenceBundle.parseCanonical( - text.replace(",\"sourceFence\":\"7\"", "").getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountAuthEvidenceBundle.parseCanonical( + text.replace(",\"sourceFence\":\"7\"", "").getBytes(StandardCharsets.UTF_8))) .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); } @@ -177,38 +165,31 @@ void profileRejectsTenantAuthorityAndNonCanonicalCounterRepresentations() { String numericIssuerGeneration = text.replace("\"issuerAuthGeneration\":\"1\"", "\"issuerAuthGeneration\":1"); - assertThatThrownBy( - () -> - AccountAuthEvidenceBundle.parseCanonical( - withTenantScope.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountAuthEvidenceBundle.parseCanonical( + withTenantScope.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); - assertThatThrownBy( - () -> - AccountAuthEvidenceBundle.parseCanonical( - numericSourceFence.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountAuthEvidenceBundle.parseCanonical( + numericSourceFence.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); - assertThatThrownBy( - () -> - AccountAuthEvidenceBundle.parseCanonical( - numericFence.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountAuthEvidenceBundle.parseCanonical(numericFence.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); - assertThatThrownBy( - () -> - AccountAuthEvidenceBundle.parseCanonical( - numericTokenGeneration.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountAuthEvidenceBundle.parseCanonical( + numericTokenGeneration.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); - assertThatThrownBy( - () -> - AccountAuthEvidenceBundle.parseCanonical( - numericIssuerGeneration.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountAuthEvidenceBundle.parseCanonical( + numericIssuerGeneration.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); } @Test void bundleReferenceUsesCanonicalCaptureTransactionAndFenceRanges() { - assertThatCode( - () -> - new BundleReference("1", "18446744073709551615", "9223372036854775807", "12345678")) + assertThatCode(() -> + new BundleReference("1", "18446744073709551615", "9223372036854775807", "12345678")) .doesNotThrowAnyException(); assertThatThrownBy(() -> new BundleReference("1", "18446744073709551616", "1", "12345678")) .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); @@ -237,13 +218,12 @@ void checkpointsMustBeExactAndSortedOwnerEvidenceShapes() { assertThatThrownBy(() -> AccountAuthEvidenceBundle.fromOwnerEvaluation(reversed)) .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); - assertThatThrownBy( - () -> - new OutboxCheckpoint( - "account:auth-authority:v1:account/" + value.accountId(), - 0L, - "event", - "sha256:" + "a".repeat(64))) + assertThatThrownBy(() -> + new OutboxCheckpoint( + "account:auth-authority:v1:account/" + value.accountId(), + 0L, + "event", + "sha256:" + "a".repeat(64))) .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); } @@ -287,10 +267,9 @@ void explicitZeroCheckpointIsEncodedWithoutEventIdentityButIsNotSourceProof() { + "\"sourceEventDigest\":\"sha256:" + "a".repeat(64) + "\""); - assertThatThrownBy( - () -> - AccountAuthEvidenceBundle.parseCanonical( - claimedEventAtZero.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountAuthEvidenceBundle.parseCanonical( + claimedEventAtZero.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigestTest.java index fc0fd83b27..4ac27b4919 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigestTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountLogoutRequestDigestTest.java @@ -23,8 +23,8 @@ void accountLogoutAllMatchesFixedRequestDigestV1PreimageAndDigestVector() { .isEqualTo( compactHex( """ - 31363a726571756573744469676573742f763131333a6f7065726174696f6e4b696e64363a737472696e673131383a4143434f554e545f4c4f474f55545f414c4c31363a7375626a6563744163636f756e744964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d31313131313131313131313131323a746f6b656e50726f66696c65363a737472696e673131303a636f6e74726f6c2d756931383a70726573656e746564546f6b656e48617368363a737472696e673136343a61616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161 - """)); + 31363a726571756573744469676573742f763131333a6f7065726174696f6e4b696e64363a737472696e673131383a4143434f554e545f4c4f474f55545f414c4c31363a7375626a6563744163636f756e744964363a737472696e673133363a31313131313131312d313131312d343131312d383131312d31313131313131313131313131323a746f6b656e50726f66696c65363a737472696e673131303a636f6e74726f6c2d756931383a70726573656e746564546f6b656e48617368363a737472696e673136343a61616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161 + """)); assertThat( AccountLogoutRequestDigest.accountLogoutAll( LOGOUT_ALL_ACCOUNT, "control-ui", tokenHash)) @@ -41,8 +41,8 @@ void tokenLogoutMatchesFixedRequestDigestV1PreimageAndDigestVector() { .isEqualTo( compactHex( """ - 31363a726571756573744469676573742f763131333a6f7065726174696f6e4b696e64363a737472696e673131323a544f4b454e5f4c4f474f555431363a7375626a6563744163636f756e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231323a746f6b656e50726f66696c65363a737472696e673131363a706c617965722d626f6f747374726170393a746f6b656e48617368363a737472696e673136343a62626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262 - """)); + 31363a726571756573744469676573742f763131333a6f7065726174696f6e4b696e64363a737472696e673131323a544f4b454e5f4c4f474f555431363a7375626a6563744163636f756e744964363a737472696e673133363a32323232323232322d323232322d343232322d383232322d32323232323232323232323231323a746f6b656e50726f66696c65363a737472696e673131363a706c617965722d626f6f747374726170393a746f6b656e48617368363a737472696e673136343a62626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262626262 + """)); assertThat( AccountLogoutRequestDigest.tokenLogout( TOKEN_LOGOUT_ACCOUNT, "player-bootstrap", tokenHash)) @@ -73,28 +73,24 @@ void eachClosedTupleFieldChangesTheDigest() { @Test void rejectsUnsupportedProfilesNoncanonicalAccountIdentityAndMalformedTokenHashes() { - assertThatThrownBy( - () -> - AccountLogoutRequestDigest.accountLogoutAll( - LOGOUT_ALL_ACCOUNT, "private-player-delegation", "a".repeat(64))) + assertThatThrownBy(() -> + AccountLogoutRequestDigest.accountLogoutAll( + LOGOUT_ALL_ACCOUNT, "private-player-delegation", "a".repeat(64))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("token profile"); - assertThatThrownBy( - () -> - AccountLogoutRequestDigest.accountLogoutAll( - new UUID(0L, 0L), "control-ui", "a".repeat(64))) + assertThatThrownBy(() -> + AccountLogoutRequestDigest.accountLogoutAll( + new UUID(0L, 0L), "control-ui", "a".repeat(64))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("non-nil Account UUID"); - assertThatThrownBy( - () -> - AccountLogoutRequestDigest.tokenLogout( - LOGOUT_ALL_ACCOUNT, "control-ui", "A".repeat(64))) + assertThatThrownBy(() -> + AccountLogoutRequestDigest.tokenLogout( + LOGOUT_ALL_ACCOUNT, "control-ui", "A".repeat(64))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("lowercase SHA-256 hex"); - assertThatThrownBy( - () -> - AccountLogoutRequestDigest.tokenLogout( - LOGOUT_ALL_ACCOUNT, "control-ui", "a".repeat(63))) + assertThatThrownBy(() -> + AccountLogoutRequestDigest.tokenLogout( + LOGOUT_ALL_ACCOUNT, "control-ui", "a".repeat(63))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("lowercase SHA-256 hex"); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequestTest.java index d1085cf5b3..7021a1f0f2 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequestTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountSecurityStateMutationRequestTest.java @@ -101,22 +101,20 @@ void closedCorrelationRejectsAssertionsCredentialsNullsAndUnknownFields() { assertThatThrownBy(() -> request(REQUEST, ACCOUNT, changed, 1L, 1L, KINDS, state(true))) .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - request( - REQUEST, - ACCOUNT, - "{}".getBytes(StandardCharsets.UTF_8), - 1L, - 1L, - KINDS, - state(true))) + assertThatThrownBy(() -> + request( + REQUEST, + ACCOUNT, + "{}".getBytes(StandardCharsets.UTF_8), + 1L, + 1L, + KINDS, + state(true))) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> request(REQUEST, ACCOUNT, original, 0L, 1L, KINDS, state(true))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - request(REQUEST, ACCOUNT, original, 1L, 1L, List.of("PASSWORD_RESET"), state(true))) + assertThatThrownBy(() -> + request(REQUEST, ACCOUNT, original, 1L, 1L, List.of("PASSWORD_RESET"), state(true))) .isInstanceOf(IllegalArgumentException.class); } @@ -130,16 +128,15 @@ void requestCopiesInputsAndStateHasOnlySharedCodecPolicyVocabulary() { assertThat(request.callerProofBinding()[0]).isEqualTo((byte) '{'); assertThatThrownBy(() -> request.mutationKinds().clear()) .isInstanceOf(UnsupportedOperationException.class); - assertThatThrownBy( - () -> - request( - REQUEST, - ACCOUNT, - request.callerProofBinding(), - 1L, - 1L, - KINDS, - new AccountState(true, List.of("PASSWORD"), List.of("admin"), "ACTIVE"))) + assertThatThrownBy(() -> + request( + REQUEST, + ACCOUNT, + request.callerProofBinding(), + 1L, + 1L, + KINDS, + new AccountState(true, List.of("PASSWORD"), List.of("admin"), "ACTIVE"))) .isInstanceOf(IllegalArgumentException.class); assertThat( AccountSecurityStateMutationRequest.parseCanonicalState( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementCodecTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementCodecTest.java index 2135a89085..9b8ce04731 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementCodecTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/DemoTenantEntitlementCodecTest.java @@ -102,15 +102,12 @@ void eventVerifierRejectsDuplicateKeysAndTrailingInput() throws Exception { "\"eventType\":\"TENANT_ENTITLEMENT_CHANGED\"", "\"eventType\":\"TENANT_ENTITLEMENT_CHANGED\",\"eventType\":\"TENANT_ENTITLEMENT_CHANGED\""); - assertThatThrownBy( - () -> - DemoTenantEntitlementEventV1Codec.verify( - duplicateKey.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + DemoTenantEntitlementEventV1Codec.verify(duplicateKey.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - DemoTenantEntitlementEventV1Codec.verify( - (canonical + " {}").getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + DemoTenantEntitlementEventV1Codec.verify( + (canonical + " {}").getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginDisposalResultTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginDisposalResultTest.java index 8a68d53a10..5206a07633 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginDisposalResultTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginDisposalResultTest.java @@ -28,18 +28,16 @@ void acceptsOnlyExactNonAuthorizingDispositionProofPairs() { .proofKind()) .isEqualTo(kind); } else { - assertThatThrownBy( - () -> - new InitialGameplayLoginDisposalResult( - request, context, operation, disposition, kind)) + assertThatThrownBy(() -> + new InitialGameplayLoginDisposalResult( + request, context, operation, disposition, kind)) .isInstanceOf(IllegalArgumentException.class); } } } - assertThatThrownBy( - () -> - new InitialGameplayLoginDisposalResult( - request, context, operation, Disposition.NO_TOKEN)) + assertThatThrownBy(() -> + new InitialGameplayLoginDisposalResult( + request, context, operation, Disposition.NO_TOKEN)) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResultTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResultTest.java index 0a23a662b5..cd8515cda6 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResultTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/InitialGameplayLoginResultTest.java @@ -93,31 +93,25 @@ void credentialAndEvidenceBytesAreDefensiveCopies() { @Test void rejectsRecoveredCredentialThatContradictsStoredEvidence() { AccountAuthEvidenceBundle bundle = evidenceBundle(); - assertThatThrownBy( - () -> - InitialGameplayLoginResult.fromRecoveredCredential( - credential( - bundle, UUID.randomUUID(), TOKEN_JTI, "a".repeat(64), expectedExpiry()))) + assertThatThrownBy(() -> + InitialGameplayLoginResult.fromRecoveredCredential( + credential(bundle, UUID.randomUUID(), TOKEN_JTI, "a".repeat(64), expectedExpiry()))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Recovered gameplay LOGIN metadata is inconsistent"); - assertThatThrownBy( - () -> - InitialGameplayLoginResult.fromRecoveredCredential( - credential( - bundle, ACCOUNT_ID, UUID.randomUUID(), "a".repeat(64), expectedExpiry()))) + assertThatThrownBy(() -> + InitialGameplayLoginResult.fromRecoveredCredential( + credential( + bundle, ACCOUNT_ID, UUID.randomUUID(), "a".repeat(64), expectedExpiry()))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Recovered gameplay LOGIN metadata is inconsistent"); - assertThatThrownBy( - () -> - InitialGameplayLoginResult.fromRecoveredCredential( - credential( - bundle, ACCOUNT_ID, TOKEN_JTI, "a".repeat(64), expectedExpiry() + 1L))) + assertThatThrownBy(() -> + InitialGameplayLoginResult.fromRecoveredCredential( + credential(bundle, ACCOUNT_ID, TOKEN_JTI, "a".repeat(64), expectedExpiry() + 1L))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Recovered gameplay LOGIN metadata is inconsistent"); - assertThatThrownBy( - () -> - InitialGameplayLoginResult.fromRecoveredCredential( - credential(bundle, ACCOUNT_ID, TOKEN_JTI, "not-a-hash", expectedExpiry()))) + assertThatThrownBy(() -> + InitialGameplayLoginResult.fromRecoveredCredential( + credential(bundle, ACCOUNT_ID, TOKEN_JTI, "not-a-hash", expectedExpiry()))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Recovered gameplay LOGIN metadata is inconsistent"); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProviderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProviderTest.java index 6483eb5542..6f4f22c9c5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProviderTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/AccountDeploymentEnvironmentBoundaryProviderTest.java @@ -49,30 +49,25 @@ void rejectsEveryExpectedFieldMismatch() { @Test void rejectsAbsentExpectedValuesAndEvidence() { - assertThatThrownBy( - () -> - new AccountDeploymentEnvironmentBoundaryProvider( - null, OWNER, EVENT, OWNER_EVIDENCE_DIGEST, evidence(OWNER_EVIDENCE))) + assertThatThrownBy(() -> + new AccountDeploymentEnvironmentBoundaryProvider( + null, OWNER, EVENT, OWNER_EVIDENCE_DIGEST, evidence(OWNER_EVIDENCE))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountDeploymentEnvironmentBoundaryProvider( - ENVIRONMENT, null, EVENT, OWNER_EVIDENCE_DIGEST, evidence(OWNER_EVIDENCE))) + assertThatThrownBy(() -> + new AccountDeploymentEnvironmentBoundaryProvider( + ENVIRONMENT, null, EVENT, OWNER_EVIDENCE_DIGEST, evidence(OWNER_EVIDENCE))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountDeploymentEnvironmentBoundaryProvider( - ENVIRONMENT, OWNER, null, OWNER_EVIDENCE_DIGEST, evidence(OWNER_EVIDENCE))) + assertThatThrownBy(() -> + new AccountDeploymentEnvironmentBoundaryProvider( + ENVIRONMENT, OWNER, null, OWNER_EVIDENCE_DIGEST, evidence(OWNER_EVIDENCE))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountDeploymentEnvironmentBoundaryProvider( - ENVIRONMENT, OWNER, EVENT, null, evidence(OWNER_EVIDENCE))) + assertThatThrownBy(() -> + new AccountDeploymentEnvironmentBoundaryProvider( + ENVIRONMENT, OWNER, EVENT, null, evidence(OWNER_EVIDENCE))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountDeploymentEnvironmentBoundaryProvider( - ENVIRONMENT, OWNER, EVENT, OWNER_EVIDENCE_DIGEST, null)) + assertThatThrownBy(() -> + new AccountDeploymentEnvironmentBoundaryProvider( + ENVIRONMENT, OWNER, EVENT, OWNER_EVIDENCE_DIGEST, null)) .isInstanceOf(NullPointerException.class); } @@ -91,14 +86,13 @@ void keepsAnIndependentImmutableCopyOfTheSuppliedEvidenceBytes() { @Test void existingBoundaryRecordRejectsBytesWithAConflictingDigest() { - assertThatThrownBy( - () -> - new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( - ENVIRONMENT, - OWNER, - EVENT, - "different-evidence".getBytes(StandardCharsets.UTF_8), - OWNER_EVIDENCE_DIGEST)) + assertThatThrownBy(() -> + new HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary( + ENVIRONMENT, + OWNER, + EVENT, + "different-evidence".getBytes(StandardCharsets.UTF_8), + OWNER_EVIDENCE_DIGEST)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Environment-owner evidence digest conflicts"); } @@ -120,10 +114,9 @@ private static void assertMismatch( String event, String digest, HostedTermsEnvironmentBinding.CurrentEnvironmentBoundary evidence) { - assertThatThrownBy( - () -> - new AccountDeploymentEnvironmentBoundaryProvider( - environment, owner, event, digest, evidence)) + assertThatThrownBy(() -> + new AccountDeploymentEnvironmentBoundaryProvider( + environment, owner, event, digest, evidence)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Deployment environment evidence differs from the fixed server boundary"); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffTest.java index 9cf194dec4..0a0b2d531c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffTest.java @@ -79,32 +79,30 @@ void exactDigestBindsEveryDisclosureFieldAndRejectsChangedOrMalformedInputs() { .isNotEqualTo(HostedTermsEncoding.digest(changed(original, "requestId").canonicalBytes())) .isNotEqualTo( HostedTermsEncoding.digest(changed(original, "authorityEvidence").canonicalBytes())); - assertThatThrownBy( - () -> - new HostedTermsDisclosureHandoff( - UUID.randomUUID(), - UUID.randomUUID(), - Kind.CATALOG, - source.key(), - original.predecessorDigest(), - original.candidateDigest(), - Instant.parse("2026-10-08T00:00:00.123456789Z"), - List.of(source), - new byte[] {1})) + assertThatThrownBy(() -> + new HostedTermsDisclosureHandoff( + UUID.randomUUID(), + UUID.randomUUID(), + Kind.CATALOG, + source.key(), + original.predecessorDigest(), + original.candidateDigest(), + Instant.parse("2026-10-08T00:00:00.123456789Z"), + List.of(source), + new byte[] {1})) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("microsecond"); - assertThatThrownBy( - () -> - new HostedTermsDisclosureHandoff( - original.handoffId(), - original.requestId(), - original.kind(), - original.sourceKey(), - original.predecessorDigest(), - original.candidateDigest(), - original.effectiveAt(), - List.of(source, source), - new byte[] {1})) + assertThatThrownBy(() -> + new HostedTermsDisclosureHandoff( + original.handoffId(), + original.requestId(), + original.kind(), + original.sourceKey(), + original.predecessorDigest(), + original.candidateDigest(), + original.effectiveAt(), + List.of(source, source), + new byte[] {1})) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Distinct complete sorted source evidence"); byte[] trailing = diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java index 8a318309d0..73116e080e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java @@ -37,10 +37,9 @@ class AccountAuditOutboxRepositoryTest { void exactCommittedOrMinimizedTerminalReceiptAfterLostCompareAndSetIsANoOp() { for (String status : new String[] {"COMMITTED", "MINIMIZED"}) { boolean minimized = "MINIMIZED".equals(status); - assertThatCode( - () -> - repositoryWithReadback(status, RECEIPT_ID, LOG_EVENT_ID, true) - .markDelivered(EVENT_ID, RECEIPT_ID, LOG_EVENT_ID, minimized)) + assertThatCode(() -> + repositoryWithReadback(status, RECEIPT_ID, LOG_EVENT_ID, true) + .markDelivered(EVENT_ID, RECEIPT_ID, LOG_EVENT_ID, minimized)) .doesNotThrowAnyException(); } } @@ -159,15 +158,11 @@ void canonicalTenantAuditEnvelopeRetainsTypedUuidIdentityAndExactPayloadDigest() @Test void canonicalTenantAuditIdentityRejectsNilAndNoncanonicalUuidForms() { - assertThatThrownBy( - () -> - AccountAuditTenantIdentity.canonicalTenantV2( - "00000000-0000-0000-0000-000000000000")) + assertThatThrownBy(() -> + AccountAuditTenantIdentity.canonicalTenantV2("00000000-0000-0000-0000-000000000000")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountAuditTenantIdentity.canonicalTenantV2( - "F4DF3B0A-5FC6-4F86-9EFC-0F053103B200")) + assertThatThrownBy(() -> + AccountAuditTenantIdentity.canonicalTenantV2("F4DF3B0A-5FC6-4F86-9EFC-0F053103B200")) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepositoryTest.java index a8e2d5ce02..7e84140feb 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthEvidenceBundleRepositoryTest.java @@ -113,11 +113,10 @@ void locksAccountAndAuthorityBeforeLockingAndRevalidatingOperation() { order .verify(dsl) .fetchOne( - argThat( - sql -> - sql.contains("SELECT operation_id, request_id, account_uuid") - && sql.contains("FROM account_gameplay_delegation_issuance_operations") - && !sql.contains("FOR UPDATE")), + argThat(sql -> + sql.contains("SELECT operation_id, request_id, account_uuid") + && sql.contains("FROM account_gameplay_delegation_issuance_operations") + && !sql.contains("FOR UPDATE")), any(Object[].class)); order .verify(dsl) @@ -134,10 +133,9 @@ void locksAccountAndAuthorityBeforeLockingAndRevalidatingOperation() { order .verify(dsl) .fetchOne( - argThat( - sql -> - sql.contains("FROM account_gameplay_delegation_issuance_operations") - && sql.contains("FOR UPDATE")), + argThat(sql -> + sql.contains("FROM account_gameplay_delegation_issuance_operations") + && sql.contains("FOR UPDATE")), any(Object[].class)); verifyNoInteractions(outbox); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java index d358dac487..9efe535a92 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java @@ -56,13 +56,9 @@ void malformedScopesAndNonPositiveStateFailBeforeStorageAccess() { .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> AuthorityScope.account(null)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new ScopeState( - AuthorityScope.account(accountId), - 0L, - 1L, - new IssuanceFence(accountId, 1L, 1L))) + assertThatThrownBy(() -> + new ScopeState( + AuthorityScope.account(accountId), 0L, 1L, new IssuanceFence(accountId, 1L, 1L))) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> new IssuanceFence(accountId, 0L, 1L)) .isInstanceOf(IllegalArgumentException.class); @@ -166,17 +162,15 @@ void tenantEnrollmentRejectsMissingCanonicalTenantIdentityBeforeStorageAccess() void snapshotRequiresEveryExplicitScopeWithoutFillingInMissingAuthority() { UUID accountId = UUID.fromString("11111111-1111-4111-8111-111111111111"); - assertThatThrownBy( - () -> - repository.readCompositeSnapshot("issuer-A", accountId, null, java.util.List.of())) + assertThatThrownBy(() -> + repository.readCompositeSnapshot("issuer-A", accountId, null, java.util.List.of())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - repository.readCompositeSnapshot( - "issuer-A", - accountId, - java.util.List.of(), - java.util.Arrays.asList(accountId, null))) + assertThatThrownBy(() -> + repository.readCompositeSnapshot( + "issuer-A", + accountId, + java.util.List.of(), + java.util.Arrays.asList(accountId, null))) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(dsl); @@ -197,10 +191,9 @@ void compositeSnapshotLocksExactAccountRowBeforeAnyAuthorityScope() { .when(dsl) .fetchOne(anyString(), eq(accountId)); - assertThatThrownBy( - () -> - repository.readCompositeSnapshot( - "firemud-account-service", accountId, java.util.List.of(), java.util.List.of())) + assertThatThrownBy(() -> + repository.readCompositeSnapshot( + "firemud-account-service", accountId, java.util.List.of(), java.util.List.of())) .isSameAs(stopAtFirstRead); assertThat(firstSql.get()).contains("FROM accounts").contains("FOR SHARE"); assertThat(firstBinding.get()).isEqualTo(accountId); @@ -264,10 +257,9 @@ void compositeSnapshotSharesIssuerOnlyAfterLockingTheAccountRowFirst() { .when(dsl) .fetchOne(anyString(), eq("ISSUER"), eq("firemud-account-service"), isNull(), isNull()); - assertThatThrownBy( - () -> - repository.readCompositeSnapshot( - "firemud-account-service", accountId, java.util.List.of(), java.util.List.of())) + assertThatThrownBy(() -> + repository.readCompositeSnapshot( + "firemud-account-service", accountId, java.util.List.of(), java.util.List.of())) .isSameAs(stopAtIssuerRead); assertThat(issuerSql.get()).contains("FOR SHARE").doesNotContain("FOR UPDATE"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepositoryTest.java index fbc00c6dcb..0714aa1bbc 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityOutboxRepositoryTest.java @@ -53,23 +53,21 @@ void malformedKeysAndZeroCheckpointsFailBeforeStorageAccess() { assertThatThrownBy( () -> new Checkpoint("account:auth-authority:v1:account/abc", 0L, null, null)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - repository.append( - "account:auth-authority:v1:account/abc", - "request-1", - "event-1", - "digest-1", - new byte[0])) + assertThatThrownBy(() -> + repository.append( + "account:auth-authority:v1:account/abc", + "request-1", + "event-1", + "digest-1", + new byte[0])) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - repository.append( - "account:auth-authority:v1:account/abc", - "r".repeat(513), - "event-1", - "digest-1", - new byte[] {1})) + assertThatThrownBy(() -> + repository.append( + "account:auth-authority:v1:account/abc", + "r".repeat(513), + "event-1", + "digest-1", + new byte[] {1})) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(dsl); @@ -160,16 +158,15 @@ void exactRetryWithChangedProducedEvidenceConflictsWithoutAdvancingHead() { "{\"eventDigest\":\"sha256:wire-digest-4\"}".getBytes(), "request-4")); - assertThatThrownBy( - () -> - repository.append( - "account:auth-authority:v1:membership/account-a/tenant-a", - "request-4", - sequence -> - new EventEvidence( - "event-4", - "sha256:changed", - "{\"eventDigest\":\"sha256:changed\"}".getBytes()))) + assertThatThrownBy(() -> + repository.append( + "account:auth-authority:v1:membership/account-a/tenant-a", + "request-4", + sequence -> + new EventEvidence( + "event-4", + "sha256:changed", + "{\"eventDigest\":\"sha256:changed\"}".getBytes()))) .isInstanceOf(AccountAuthorityOutboxRepository.IdempotencyConflictException.class); verify(dsl, never()) @@ -180,14 +177,13 @@ void exactRetryWithChangedProducedEvidenceConflictsWithoutAdvancingHead() { void factoryFailureCannotAdvanceHeadOrInsertEvent() { stubAppend(0L, null); - assertThatThrownBy( - () -> - repository.append( - "account:auth-authority:v1:membership/account-a/tenant-a", - "request-1", - sequence -> { - throw new IllegalStateException("producer failed"); - })) + assertThatThrownBy(() -> + repository.append( + "account:auth-authority:v1:membership/account-a/tenant-a", + "request-1", + sequence -> { + throw new IllegalStateException("producer failed"); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("producer failed"); @@ -251,11 +247,10 @@ void positiveCheckpointReadbackReturnsItsExactEventIdentityAndDigest() { when(event.get("payload", byte[].class)).thenReturn(new byte[] {2}); when(event.get("request_id", String.class)).thenReturn("request-2"); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> - invocation.getArgument(0).contains("account_authority_outbox_streams") - ? stream - : event); + .thenAnswer(invocation -> + invocation.getArgument(0).contains("account_authority_outbox_streams") + ? stream + : event); assertThat(repository.readCheckpoint(streamKey)) .contains(new Checkpoint(streamKey, 2L, "event-2", "canonical-digest-2")); @@ -266,11 +261,8 @@ void emptyZeroSequenceStreamHasNoPositiveCheckpoint() { String streamKey = "account:auth-authority:v1:membership/account-a/tenant-a"; Record stream = streamRecord(0L); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> - invocation.getArgument(0).startsWith("SELECT last_sequence") - ? stream - : null); + .thenAnswer(invocation -> + invocation.getArgument(0).startsWith("SELECT last_sequence") ? stream : null); assertThat(repository.readCheckpoint(streamKey)).isEmpty(); verify(dsl) @@ -285,11 +277,8 @@ void zeroSequenceStreamWithAnyEventEvidenceIsCorrupt() { Record stream = streamRecord(0L); Record event = mock(Record.class); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> - invocation.getArgument(0).startsWith("SELECT last_sequence") - ? stream - : event); + .thenAnswer(invocation -> + invocation.getArgument(0).startsWith("SELECT last_sequence") ? stream : event); assertThatThrownBy(() -> repository.readCheckpoint(streamKey)) .isInstanceOf(IllegalStateException.class) @@ -336,10 +325,9 @@ void requestReadbackFindsAnExactHistoricalEventInItsStream() { @Test void requestReadbackRejectsInvalidRequestIdentityBeforeStorageAccess() { - assertThatThrownBy( - () -> - repository.findEvent( - "account:auth-authority:v1:membership/account-a/tenant-a", "r".repeat(513))) + assertThatThrownBy(() -> + repository.findEvent( + "account:auth-authority:v1:membership/account-a/tenant-a", "r".repeat(513))) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(dsl); } @@ -371,23 +359,22 @@ private void stubAppend(long currentSequence, Record priorRequest) { Record advanced = streamRecord(currentSequence + 1L); when(dsl.execute(anyString(), any(Object[].class))).thenReturn(1); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String query = invocation.getArgument(0); - if (query.startsWith("SELECT last_sequence")) { - return stream; - } - if (query.startsWith("SELECT outbox_sequence")) { - return priorRequest; - } - if (query.startsWith("SELECT request_id")) { - return null; - } - if (query.startsWith("UPDATE account_authority_outbox_streams")) { - return advanced; - } - throw new AssertionError("Unexpected outbox query: " + query); - }); + .thenAnswer(invocation -> { + String query = invocation.getArgument(0); + if (query.startsWith("SELECT last_sequence")) { + return stream; + } + if (query.startsWith("SELECT outbox_sequence")) { + return priorRequest; + } + if (query.startsWith("SELECT request_id")) { + return null; + } + if (query.startsWith("UPDATE account_authority_outbox_streams")) { + return advanced; + } + throw new AssertionError("Unexpected outbox query: " + query); + }); } private Record streamRecord(long sequence) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepositoryTest.java index 51212ab6c7..fccaaa8373 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepositoryTest.java @@ -69,21 +69,19 @@ void sequenceZeroIsAnExplicitProvenanceBearingCheckpointWithoutSyntheticEventIde @Test void rejectsPartialOrFabricatedSequenceZeroCheckpoints() { - assertThatThrownBy( - () -> - new AccountAuthoritySourceEvidenceRepository.SourceCheckpoint( - "account:auth-authority:v1:issuer/firemud-account-service", - 0L, - Optional.of("synthetic-event"), - Optional.empty())) + assertThatThrownBy(() -> + new AccountAuthoritySourceEvidenceRepository.SourceCheckpoint( + "account:auth-authority:v1:issuer/firemud-account-service", + 0L, + Optional.of("synthetic-event"), + Optional.empty())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountAuthoritySourceEvidenceRepository.SourceCheckpoint( - "account:auth-authority:v1:issuer/firemud-account-service", - 1L, - Optional.empty(), - Optional.empty())) + assertThatThrownBy(() -> + new AccountAuthoritySourceEvidenceRepository.SourceCheckpoint( + "account:auth-authority:v1:issuer/firemud-account-service", + 1L, + Optional.empty(), + Optional.empty())) .isInstanceOf(IllegalArgumentException.class); } @@ -121,15 +119,13 @@ void accountSnapshotRequiresSameAccountFenceAndExactScopeKinds() { new AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot( issuer, account, fence)) .satisfies(snapshot -> assertThat(snapshot.account().issuanceFence()).isEqualTo(fence)); - assertThatThrownBy( - () -> - new AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot( - account, account, fence)) + assertThatThrownBy(() -> + new AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot( + account, account, fence)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot( - issuer, account, new IssuanceFence(UUID.randomUUID(), 1L, 1L))) + assertThatThrownBy(() -> + new AccountAuthoritySourceEvidenceRepository.IssuerAccountSourceSnapshot( + issuer, account, new IssuanceFence(UUID.randomUUID(), 1L, 1L))) .isInstanceOf(IllegalArgumentException.class); } @@ -169,11 +165,10 @@ void retainedReceiptEvidenceKeepsIndependentPositiveFenceCoordinates() { assertThat(evidence.issuanceFence()).isEqualTo(10L); assertThat(evidence.issuanceFenceSourceVersion()).isEqualTo(13L); - assertThatThrownBy( - () -> - new net.firedevops.firemud.accountservice.service - .AccountAuthoritySourceEventReadback.RetainedEventEvidence( - stream, 3L, 4L, 4L, 0L, 13L, new AccountSecurityCutoff("4", stream, "3"))) + assertThatThrownBy(() -> + new net.firedevops.firemud.accountservice.service.AccountAuthoritySourceEventReadback + .RetainedEventEvidence( + stream, 3L, 4L, 4L, 0L, 13L, new AccountSecurityCutoff("4", stream, "3"))) .isInstanceOf(IllegalArgumentException.class); } @@ -218,20 +213,19 @@ void currentAccountSourceReadRequiresAWritableMandatoryOwnerTransaction() void sourceEvidenceIsRestrictedToIssuerAndAccountScopes() { assertThat(ScopeKind.valueOf("ISSUER")).isEqualTo(ScopeKind.ISSUER); assertThat(ScopeKind.valueOf("ACCOUNT")).isEqualTo(ScopeKind.ACCOUNT); - assertThatThrownBy( - () -> - new AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence( - AuthorityScope.account(ACCOUNT_ID), - 0L, - 1L, - new IssuanceFence(ACCOUNT_ID, 1L, 1L), - zeroCheckpoint("account/" + ACCOUNT_ID), - Optional.empty(), - "ACCOUNT_REPOSITORY_INSERT", - 9L, - "ACCOUNT_REPOSITORY_INSERT", - 1L, - 1L)) + assertThatThrownBy(() -> + new AccountAuthoritySourceEvidenceRepository.CurrentSourceEvidence( + AuthorityScope.account(ACCOUNT_ID), + 0L, + 1L, + new IssuanceFence(ACCOUNT_ID, 1L, 1L), + zeroCheckpoint("account/" + ACCOUNT_ID), + Optional.empty(), + "ACCOUNT_REPOSITORY_INSERT", + 9L, + "ACCOUNT_REPOSITORY_INSERT", + 1L, + 1L)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerRepositoryTest.java index 9517a3f2fc..639b3a59ca 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountBillingCustomerRepositoryTest.java @@ -42,10 +42,9 @@ private void assertTransactionRefusal() { assertThatThrownBy(() -> customers.findByAccountForUpdate(ACCOUNT)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("active writable Account transaction"); - assertThatThrownBy( - () -> - customers.recordObservation( - ACCOUNT, OPERATION, 1, UUID.randomUUID(), Observation.AMBIGUOUS, null, DIGEST)) + assertThatThrownBy(() -> + customers.recordObservation( + ACCOUNT, OPERATION, 1, UUID.randomUUID(), Observation.AMBIGUOUS, null, DIGEST)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("active writable Account transaction"); } @@ -64,59 +63,53 @@ void rejectsNilOrConflatedOperationIdentitiesBeforeSql() { @Test void rejectsMissingEvidenceInvalidVersionAndInventedConfirmationBeforeSql() { TransactionSynchronizationManager.setActualTransactionActive(true); - assertThatThrownBy( - () -> - customers.recordObservation( - ACCOUNT, OPERATION, 0, UUID.randomUUID(), Observation.AMBIGUOUS, null, DIGEST)) + assertThatThrownBy(() -> + customers.recordObservation( + ACCOUNT, OPERATION, 0, UUID.randomUUID(), Observation.AMBIGUOUS, null, DIGEST)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - customers.recordObservation( - ACCOUNT, - OPERATION, - Long.MAX_VALUE, - UUID.randomUUID(), - Observation.AMBIGUOUS, - null, - DIGEST)) + assertThatThrownBy(() -> + customers.recordObservation( + ACCOUNT, + OPERATION, + Long.MAX_VALUE, + UUID.randomUUID(), + Observation.AMBIGUOUS, + null, + DIGEST)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - customers.recordObservation( - ACCOUNT, - OPERATION, - 1, - UUID.randomUUID(), - Observation.AMBIGUOUS, - "cus_unverified", - DIGEST)) + assertThatThrownBy(() -> + customers.recordObservation( + ACCOUNT, + OPERATION, + 1, + UUID.randomUUID(), + Observation.AMBIGUOUS, + "cus_unverified", + DIGEST)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - customers.recordObservation( - ACCOUNT, - OPERATION, - 1, - UUID.randomUUID(), - Observation.CONFIRMED, - "raw-customer-payload", - DIGEST)) + assertThatThrownBy(() -> + customers.recordObservation( + ACCOUNT, + OPERATION, + 1, + UUID.randomUUID(), + Observation.CONFIRMED, + "raw-customer-payload", + DIGEST)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - customers.recordObservation( - ACCOUNT, - OPERATION, - 1, - UUID.randomUUID(), - Observation.PROVIDER_ABSENT, - null, - "missing-digest")) + assertThatThrownBy(() -> + customers.recordObservation( + ACCOUNT, + OPERATION, + 1, + UUID.randomUUID(), + Observation.PROVIDER_ABSENT, + null, + "missing-digest")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - customers.recordObservation( - ACCOUNT, OPERATION, 1, UUID.randomUUID(), Observation.NONE, null, DIGEST)) + assertThatThrownBy(() -> + customers.recordObservation( + ACCOUNT, OPERATION, 1, UUID.randomUUID(), Observation.NONE, null, DIGEST)) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(dsl); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotRepositoryTest.java index eaf04f453a..00bd27fd6d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountCanonicalRuntimeMembershipSnapshotRepositoryTest.java @@ -40,14 +40,12 @@ void serviceOwnsOneWritableTransactionForTheExactSnapshotRead() { var transactionManager = new RecordingTransactionManager(); var expected = missingSnapshot(); when(repository.readCurrent(ACCOUNT_UUID, TENANT_UUID)) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) - .isFalse(); - transactionManager.events.add("owner-read"); - return expected; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + transactionManager.events.add("owner-read"); + return expected; + }); var service = new AccountCanonicalRuntimeMembershipSnapshotService(repository, transactionManager); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepositoryTest.java index d882831428..c4b85b02cd 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepositoryTest.java @@ -42,10 +42,9 @@ void remainsUnregisteredWithNoPublicMutationOrAuthorizationFacade() { assertThat( Arrays.stream(AccountGameplayAdmissionLeaseRepository.class.getDeclaredMethods()) .filter(method -> !method.isSynthetic()) - .anyMatch( - method -> - Modifier.isPublic(method.getModifiers()) - || Modifier.isProtected(method.getModifiers()))) + .anyMatch(method -> + Modifier.isPublic(method.getModifiers()) + || Modifier.isProtected(method.getModifiers()))) .isFalse(); } @@ -75,12 +74,11 @@ void requiresWritableSerializableAccountTransactionBeforeReadingOrWriting() { void rejectsNonV4AccountIdentityBeforeAnyStorageAccess() { DSLContext dsl = mock(DSLContext.class); var repository = new AccountGameplayAdmissionLeaseRepository(dsl); - assertThatThrownBy( - () -> - repository.allocate( - UUID.fromString("11111111-1111-1111-8111-111111111111"), - UUID.randomUUID(), - UUID.randomUUID())) + assertThatThrownBy(() -> + repository.allocate( + UUID.fromString("11111111-1111-1111-8111-111111111111"), + UUID.randomUUID(), + UUID.randomUUID())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("UUIDv4"); verifyNoInteractions(dsl); @@ -115,10 +113,9 @@ void insertedAllocationMustBeReadBackBeforeItCanBeReturned() { @Test void missingInsertedAllocationReadbackIsNotReturnedAsAnInMemoryIdentity() { DSLContext dsl = allocationDsl(null, 1); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionLeaseRepository(dsl) - .allocate(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())) + assertThatThrownBy(() -> + new AccountGameplayAdmissionLeaseRepository(dsl) + .allocate(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())) .hasMessage("Account admission lease allocation readback unavailable"); } @@ -126,10 +123,9 @@ void missingInsertedAllocationReadbackIsNotReturnedAsAnInMemoryIdentity() { @ValueSource(ints = {0, 2}) void allocationInsertRequiresExactlyOneStoredRow(int insertCount) { DSLContext dsl = allocationDsl(null, insertCount); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionLeaseRepository(dsl) - .allocate(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())) + assertThatThrownBy(() -> + new AccountGameplayAdmissionLeaseRepository(dsl) + .allocate(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())) .hasMessage("Account admission lease allocation insert unavailable"); } @@ -143,9 +139,8 @@ void changedInsertedAllocationIdentityFailsClosed(String field) { if (field.equals("lease_fence")) when(row.get(field, Long.class)).thenReturn(2L); else when(row.get(field, UUID.class)).thenReturn(UUID.randomUUID()); DSLContext dsl = allocationDsl(row, 1); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionLeaseRepository(dsl).allocate(account, request, lease)) + assertThatThrownBy(() -> + new AccountGameplayAdmissionLeaseRepository(dsl).allocate(account, request, lease)) .hasMessageContaining("identity conflict"); } @@ -199,13 +194,12 @@ void operationRecoveryRejectsMalformedStoredCarrierWithoutWrites() { Record row = mock(Record.class); when(row.get("evidence_json", String.class)).thenReturn("{}"); DSLContext dsl = recoveryDsl(row); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionLeaseRepository(dsl) - .findByRequest( - UUID.randomUUID(), - UUID.randomUUID(), - "spiffe://firemud/ns/test/sa/game-session-service")) + assertThatThrownBy(() -> + new AccountGameplayAdmissionLeaseRepository(dsl) + .findByRequest( + UUID.randomUUID(), + UUID.randomUUID(), + "spiffe://firemud/ns/test/sa/game-session-service")) .isInstanceOf(IllegalArgumentException.class); verify(dsl, never()).execute(anyString(), any(Object[].class)); } @@ -226,15 +220,13 @@ void abortedStorageShapeRetainsUnknownDecisionAndMandatoryPendingCleanup() { assertThatThrownBy( () -> new AccountGameplayAdmissionLeaseOperation(evidence, State.COMMITTED, null, null)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionLeaseOperation( - evidence, State.ABORTED, new UUID(0, 0), cleanup)) + assertThatThrownBy(() -> + new AccountGameplayAdmissionLeaseOperation( + evidence, State.ABORTED, new UUID(0, 0), cleanup)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionLeaseOperation( - evidence, State.ABORTED, null, new UUID(0, 0))) + assertThatThrownBy(() -> + new AccountGameplayAdmissionLeaseOperation( + evidence, State.ABORTED, null, new UUID(0, 0))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java index eb610aec02..71fa60963a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutorTest.java @@ -105,10 +105,9 @@ void historicalPendingReceiptConstructorRemainsPrivate() { void anotherDataSourceIsRejectedBeforeAnyConnection() throws Exception { var fixture = new Fixture(); var other = mock(DataSource.class); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(other) - .confirm(fixture.acknowledgement)) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(other) + .confirm(fixture.acknowledgement)) .hasMessageContaining("Fresh owned"); verifyNoInteractions(other); } @@ -537,29 +536,26 @@ private void prepareHistoricalRead(boolean afterCreate) throws SQLException { assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) .isEqualTo(Connection.TRANSACTION_SERIALIZABLE); when(repository.create(acknowledgement)) - .thenAnswer( - ignored -> { - if (creationFault == null) - return new AccountGameplayAdmissionOriginalAckReceiptRepository.Creation( - receipt, inserted); - AccountGameplayAdmissionOriginalAckReceipt value = - switch (creationFault) { - case "failure" -> - throw new IllegalStateException("creation unavailable"); - case "null" -> null; - case "decision" -> receipt(evidence, UUID.randomUUID()); - case "evidence" -> { - var carrier = new java.util.LinkedHashMap<>(evidence.carrier()); - carrier.put("requestId", UUID.randomUUID().toString()); - yield receipt( - AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier), - decision); - } - default -> throw new IllegalArgumentException(creationFault); - }; - return new AccountGameplayAdmissionOriginalAckReceiptRepository.Creation( - value, inserted); - }); + .thenAnswer(ignored -> { + if (creationFault == null) + return new AccountGameplayAdmissionOriginalAckReceiptRepository.Creation( + receipt, inserted); + AccountGameplayAdmissionOriginalAckReceipt value = + switch (creationFault) { + case "failure" -> throw new IllegalStateException("creation unavailable"); + case "null" -> null; + case "decision" -> receipt(evidence, UUID.randomUUID()); + case "evidence" -> { + var carrier = new java.util.LinkedHashMap<>(evidence.carrier()); + carrier.put("requestId", UUID.randomUUID().toString()); + yield receipt( + AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier), decision); + } + default -> throw new IllegalArgumentException(creationFault); + }; + return new AccountGameplayAdmissionOriginalAckReceiptRepository.Creation( + value, inserted); + }); when(repository.readExact(evidence, decision)).thenAnswer(ignored -> readResult()); when(repository.readDurably(evidence, decision)).thenAnswer(ignored -> readResult()); when(repository.captureHistorical(evidence, decision)).thenReturn(pending); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepositoryTest.java index 9b93ca4a42..de7b23f91a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepositoryTest.java @@ -144,10 +144,8 @@ void rejectsMissingChangedAndNonCommittedOriginalOperation() { .isInstanceOf(IllegalStateException.class); } var wrongDecision = committed(evidence, UUID.randomUUID()); - assertThatThrownBy( - () -> - repository(dsl(evidence, wrongDecision, null, receipt)) - .readExact(evidence, decision)) + assertThatThrownBy(() -> + repository(dsl(evidence, wrongDecision, null, receipt)).readExact(evidence, decision)) .isInstanceOf(IllegalStateException.class); var changedCarrier = new java.util.LinkedHashMap<>(evidence.carrier()); @@ -168,181 +166,170 @@ void validatesReceiptVersionFullBindingClockAndCanonicalDistinctUnsignedXids() { assertThat(valid.receiptXid()).isEqualTo("123457"); assertThat(valid.committedBeforeMs()).isLessThan(valid.expiresAtMs()); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalAckReceipt( - operation, - (short) 2, - valid.requestId(), - valid.accountId(), - valid.leaseId(), - valid.leaseFence(), - valid.evidenceSha256(), - decision, - valid.expiresAtMs(), - valid.finalizationXid(), - valid.committedBeforeMs(), - valid.receiptXid())) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 2, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalAckReceipt( - operation, - (short) 1, - UUID.randomUUID(), - valid.accountId(), - valid.leaseId(), - valid.leaseFence(), - valid.evidenceSha256(), - decision, - valid.expiresAtMs(), - valid.finalizationXid(), - valid.committedBeforeMs(), - valid.receiptXid())) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + UUID.randomUUID(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalAckReceipt( - operation, - (short) 1, - valid.requestId(), - UUID.randomUUID(), - valid.leaseId(), - valid.leaseFence(), - valid.evidenceSha256(), - decision, - valid.expiresAtMs(), - valid.finalizationXid(), - valid.committedBeforeMs(), - valid.receiptXid())) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + UUID.randomUUID(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalAckReceipt( - operation, - (short) 1, - valid.requestId(), - valid.accountId(), - UUID.randomUUID(), - valid.leaseFence(), - valid.evidenceSha256(), - decision, - valid.expiresAtMs(), - valid.finalizationXid(), - valid.committedBeforeMs(), - valid.receiptXid())) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + UUID.randomUUID(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalAckReceipt( - operation, - (short) 1, - valid.requestId(), - valid.accountId(), - valid.leaseId(), - valid.leaseFence() + 1, - valid.evidenceSha256(), - decision, - valid.expiresAtMs(), - valid.finalizationXid(), - valid.committedBeforeMs(), - valid.receiptXid())) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence() + 1, + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalAckReceipt( - operation, - (short) 1, - valid.requestId(), - valid.accountId(), - valid.leaseId(), - valid.leaseFence(), - "0".repeat(64), - decision, - valid.expiresAtMs(), - valid.finalizationXid(), - valid.committedBeforeMs(), - valid.receiptXid())) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + "0".repeat(64), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalAckReceipt( - operation, - (short) 1, - valid.requestId(), - valid.accountId(), - valid.leaseId(), - valid.leaseFence(), - valid.evidenceSha256(), - UUID.randomUUID(), - valid.expiresAtMs(), - valid.finalizationXid(), - valid.committedBeforeMs(), - valid.receiptXid())) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + UUID.randomUUID(), + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalAckReceipt( - operation, - (short) 1, - valid.requestId(), - valid.accountId(), - valid.leaseId(), - valid.leaseFence(), - valid.evidenceSha256(), - decision, - valid.expiresAtMs() + 1, - valid.finalizationXid(), - valid.committedBeforeMs(), - valid.receiptXid())) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs() + 1, + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.receiptXid())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalAckReceipt( - operation, - (short) 1, - valid.requestId(), - valid.accountId(), - valid.leaseId(), - valid.leaseFence(), - valid.evidenceSha256(), - decision, - valid.expiresAtMs(), - valid.finalizationXid(), - valid.expiresAtMs(), - valid.receiptXid())) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.expiresAtMs(), + valid.receiptXid())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalAckReceipt( - operation, - (short) 1, - valid.requestId(), - valid.accountId(), - valid.leaseId(), - valid.leaseFence(), - valid.evidenceSha256(), - decision, - valid.expiresAtMs(), - "18446744073709551616", - valid.committedBeforeMs(), - valid.receiptXid())) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + "18446744073709551616", + valid.committedBeforeMs(), + valid.receiptXid())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionOriginalAckReceipt( - operation, - (short) 1, - valid.requestId(), - valid.accountId(), - valid.leaseId(), - valid.leaseFence(), - valid.evidenceSha256(), - decision, - valid.expiresAtMs(), - valid.finalizationXid(), - valid.committedBeforeMs(), - valid.finalizationXid())) + assertThatThrownBy(() -> + new AccountGameplayAdmissionOriginalAckReceipt( + operation, + (short) 1, + valid.requestId(), + valid.accountId(), + valid.leaseId(), + valid.leaseFence(), + valid.evidenceSha256(), + decision, + valid.expiresAtMs(), + valid.finalizationXid(), + valid.committedBeforeMs(), + valid.finalizationXid())) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptTestFixtures.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptTestFixtures.java index 77ab4388fc..25d6fe4485 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptTestFixtures.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptTestFixtures.java @@ -77,13 +77,12 @@ static AccountGameplayAdmissionLeaseEvidence fixture() { "membership/" + account + "/" + tenant, "tenant/" + tenant) .stream() - .map( - suffix -> - Map.of( - "outboxStreamKey", - "account:auth-authority:v1:" + suffix, - "outboxSequence", - suffix.startsWith("account/") || suffix.startsWith("issuer/") ? "0" : "1")) + .map(suffix -> + Map.of( + "outboxStreamKey", + "account:auth-authority:v1:" + suffix, + "outboxSequence", + suffix.startsWith("account/") || suffix.startsWith("issuer/") ? "0" : "1")) .toList()); Map token = new LinkedHashMap<>(); token.put("accountId", account); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutorTest.java index 8f97cbddc3..1d849151ff 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutorTest.java @@ -276,14 +276,13 @@ void replacingEnlistedConnectionCannotCommitOriginalBinding() throws Exception { Connection different = mock(Connection.class); var calls = new AtomicInteger(); when(fixture.stampRow.next()) - .thenAnswer( - ignored -> { - if (calls.getAndIncrement() == 0) return true; - TransactionSynchronizationManager.unbindResource(fixture.source); - TransactionSynchronizationManager.bindResource( - fixture.source, new ConnectionHolder(different)); - return false; - }); + .thenAnswer(ignored -> { + if (calls.getAndIncrement() == 0) return true; + TransactionSynchronizationManager.unbindResource(fixture.source); + TransactionSynchronizationManager.bindResource( + fixture.source, new ConnectionHolder(different)); + return false; + }); try (var repositories = fixture.repositories(State.PENDING)) { assertThatThrownBy(() -> fixture.executor.execute(fixture.evidence, fixture.decision)) .hasMessageContaining("Fresh owned Account original COMMIT required"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepositoryTest.java index eb21d87e16..78c18e7bf5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepositoryTest.java @@ -78,14 +78,13 @@ void invalidAccountUuidDeniesBeforeOwnerReadOrPendingWrite() { UUID.fromString("4cae05e8-7a6b-3b14-9d44-665e3eec450b"), UUID.fromString("4cae05e8-7a6b-4b14-7d44-665e3eec450b") }) { - assertThatThrownBy( - () -> - repository.beginPendingForAccount( - UUID.randomUUID(), - accountId, - "spiffe://firemud/ns/test/sa/game-session-service", - UUID.randomUUID(), - AccountGameplayCredentialRequestBindingFixture.binding())) + assertThatThrownBy(() -> + repository.beginPendingForAccount( + UUID.randomUUID(), + accountId, + "spiffe://firemud/ns/test/sa/game-session-service", + UUID.randomUUID(), + AccountGameplayCredentialRequestBindingFixture.binding())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("A canonical version-4 Account UUID is required"); } @@ -189,14 +188,13 @@ void committedProjectionProofRequiresCanonicalAccountBytesNotRecipientFenceSchem .AccountGameplayDelegationAuthorityProjection.ProjectionObservation( issuerProjectionValue.digest(), canonicalAccount.digest(), 7L, 1L), source); - assertThatThrownBy( - () -> - method.invoke( - null, - new net.firedevops.firemud.accountservice.service.session - .AccountGameplayDelegationAuthorityProjection.ProjectionObservation( - issuerProjectionValue.digest(), "b".repeat(64), 7L, 1L), - source)) + assertThatThrownBy(() -> + method.invoke( + null, + new net.firedevops.firemud.accountservice.service.session + .AccountGameplayDelegationAuthorityProjection.ProjectionObservation( + issuerProjectionValue.digest(), "b".repeat(64), 7L, 1L), + source)) .hasCauseInstanceOf( AccountGameplayDelegationIssuanceRepository.StaleAuthorityException.class); } @@ -771,12 +769,11 @@ private static AccountAuthEvidenceBundle evidenceBundle( current .account() .accountSecurityCutoff() - .map( - cutoff -> - new GameSessionAccountDelegationProfile.AccountSecurityCutoff( - cutoff.accountAuthorityGeneration(), - cutoff.outboxStreamKey(), - cutoff.outboxSequence())); + .map(cutoff -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence())); return AccountAuthEvidenceBundle.fromOwnerEvaluation( new OwnerEvaluation( new BundleReference("1", "11", "9", "3"), @@ -873,12 +870,11 @@ private static void assertSigningBundleMatchesOwnerSnapshot( current .account() .accountSecurityCutoff() - .map( - cutoff -> - new GameSessionAccountDelegationProfile.AccountSecurityCutoff( - cutoff.accountAuthorityGeneration(), - cutoff.outboxStreamKey(), - cutoff.outboxSequence()))), + .map(cutoff -> + new GameSessionAccountDelegationProfile.AccountSecurityCutoff( + cutoff.accountAuthorityGeneration(), + cutoff.outboxStreamKey(), + cutoff.outboxSequence()))), "authority tuple and Account cutoff"); assertCanonicalBundleSubtree(fields.get("membershipVersion"), Map.of(), "membership version"); assertThat(fields.get("issuanceFence")) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepositoryTest.java index 17a001174d..9f6b4722f4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationResponseEnvelopeRepositoryTest.java @@ -122,23 +122,20 @@ void exactRetryReturnsExistingSealedMetadataWithoutResealingOrReturningJwt() thr // The owner bundle and encrypted response are mocked components. This proves only local // binding/CAS/readback orchestration; it is not a source, signer, or successful-issuance proof. when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0); - if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { - return fixture.operationRow(); - } - if (sql.contains("FROM accounts")) { - assertThat(sql).contains("FOR SHARE").doesNotContain("FOR UPDATE"); - return fixture.accountRow(); - } - if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { - return fixture.envelopeReads().getAndIncrement() == 0 - ? null - : fixture.envelopeRow(); - } - throw new AssertionError("Unexpected SQL in component fixture"); - }); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { + return fixture.operationRow(); + } + if (sql.contains("FROM accounts")) { + assertThat(sql).contains("FOR SHARE").doesNotContain("FOR UPDATE"); + return fixture.accountRow(); + } + if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { + return fixture.envelopeReads().getAndIncrement() == 0 ? null : fixture.envelopeRow(); + } + throw new AssertionError("Unexpected SQL in component fixture"); + }); when(fixture.dsl().execute(anyString(), any(Object[].class))).thenReturn(1); when(fixture.bundles().captureAndPersist(REQUEST_ID)).thenReturn(fixture.bundle()); when(fixture.bundles().readStoredNonAuthorizingValue(OPERATION_ID)) @@ -147,17 +144,15 @@ void exactRetryReturnsExistingSealedMetadataWithoutResealingOrReturningJwt() thr .thenReturn(fixture.sealed()); SealedCandidateObservation first = - inWritableOwnerTransaction( - () -> - fixture - .repository() - .sealPendingCandidate(REQUEST_ID, fixture.caller(), fixture.compactJwt())); + inWritableOwnerTransaction(() -> + fixture + .repository() + .sealPendingCandidate(REQUEST_ID, fixture.caller(), fixture.compactJwt())); SealedCandidateObservation retry = - inWritableOwnerTransaction( - () -> - fixture - .repository() - .sealPendingCandidate(REQUEST_ID, fixture.caller(), fixture.compactJwt())); + inWritableOwnerTransaction(() -> + fixture + .repository() + .sealPendingCandidate(REQUEST_ID, fixture.caller(), fixture.compactJwt())); assertThat(retry).isEqualTo(first); assertThat(first.operationId()).isEqualTo(OPERATION_ID); @@ -193,36 +188,30 @@ void changedCallerOrCompactCandidateDeniesBeforeSourceReadOrEncryption() throws .thenReturn(fixture.operationRow()); CallerIdentity wrongCaller = new CallerIdentity("spiffe://firemud/ns/other/sa/game-session-service", CALLER_CONTEXT_ID); - assertThatThrownBy( - () -> - inWritableOwnerTransaction( - () -> - fixture - .repository() - .sealPendingCandidate(REQUEST_ID, wrongCaller, fixture.compactJwt()))) + assertThatThrownBy(() -> + inWritableOwnerTransaction(() -> + fixture + .repository() + .sealPendingCandidate(REQUEST_ID, wrongCaller, fixture.compactJwt()))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class); CallerIdentity wrongContext = new CallerIdentity(WORKLOAD, UUID.fromString("c46b58cf-4204-468b-a499-2de0eb8ce5fc")); - assertThatThrownBy( - () -> - inWritableOwnerTransaction( - () -> - fixture - .repository() - .sealPendingCandidate(REQUEST_ID, wrongContext, fixture.compactJwt()))) + assertThatThrownBy(() -> + inWritableOwnerTransaction(() -> + fixture + .repository() + .sealPendingCandidate(REQUEST_ID, wrongContext, fixture.compactJwt()))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class); - assertThatThrownBy( - () -> - inWritableOwnerTransaction( - () -> - fixture - .repository() - .sealPendingCandidate( - REQUEST_ID, fixture.caller(), fixture.compactJwt() + "A"))) + assertThatThrownBy(() -> + inWritableOwnerTransaction(() -> + fixture + .repository() + .sealPendingCandidate( + REQUEST_ID, fixture.caller(), fixture.compactJwt() + "A"))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class); verifyNoInteractions(fixture.sourceEvidence(), fixture.bundles(), fixture.crypto()); @@ -238,18 +227,17 @@ void committedRecoveryReturnsOnlyExactHashMatchedJwtAfterActiveOwnerEvidence() t ActiveCommittedIssuanceObservation active = activeObservation(fixture); when(fixture.operationRow().get("status", String.class)).thenReturn("COMMITTED"); when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0); - if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { - return fixture.operationRow(); - } - if (sql.contains("FROM accounts")) return fixture.accountRow(); - if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { - return fixture.envelopeRow(); - } - throw new AssertionError("Unexpected recovery SQL in component fixture"); - }); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { + return fixture.operationRow(); + } + if (sql.contains("FROM accounts")) return fixture.accountRow(); + if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { + return fixture.envelopeRow(); + } + throw new AssertionError("Unexpected recovery SQL in component fixture"); + }); when(fixture .sourceEvidence() .readCurrentIssuerAccountSources( @@ -267,10 +255,8 @@ void committedRecoveryReturnsOnlyExactHashMatchedJwtAfterActiveOwnerEvidence() t fixture.dsl(), fixture.sourceEvidence(), fixture.bundles(), issuance, fixture.crypto()); var recovered = - inWritableOwnerTransaction( - () -> - repository.recoverCommittedResponse( - REQUEST_ID, ACCOUNT_ID, fixture.caller(), active)); + inWritableOwnerTransaction(() -> + repository.recoverCommittedResponse(REQUEST_ID, ACCOUNT_ID, fixture.caller(), active)); assertThat(recovered.compactJwtBytes()) .containsExactly(fixture.compactJwt().getBytes(StandardCharsets.US_ASCII)); @@ -297,51 +283,41 @@ void committedRecoveryPreflightRejectsEveryCallerBindingMismatchBeforeOwnerReads new AccountGameplayDelegationResponseEnvelopeRepository( fixture.dsl(), fixture.sourceEvidence(), fixture.bundles(), fixture.crypto()); - assertThatThrownBy( - () -> - inWritableOwnerTransaction( - () -> - repository.preflightCommittedRecovery( - UUID.fromString("58102ea4-9245-4ddc-a68c-3ff41dcf96af"), - ACCOUNT_ID, - fixture.caller()))) + assertThatThrownBy(() -> + inWritableOwnerTransaction(() -> + repository.preflightCommittedRecovery( + UUID.fromString("58102ea4-9245-4ddc-a68c-3ff41dcf96af"), + ACCOUNT_ID, + fixture.caller()))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.OperationUnavailableException.class) .hasNoCause(); - assertThatThrownBy( - () -> - inWritableOwnerTransaction( - () -> - repository.preflightCommittedRecovery( - REQUEST_ID, - UUID.fromString("674cb504-8f4c-4d06-86c6-7b72f79cae74"), - fixture.caller()))) + assertThatThrownBy(() -> + inWritableOwnerTransaction(() -> + repository.preflightCommittedRecovery( + REQUEST_ID, + UUID.fromString("674cb504-8f4c-4d06-86c6-7b72f79cae74"), + fixture.caller()))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class) .hasNoCause(); - assertThatThrownBy( - () -> - inWritableOwnerTransaction( - () -> - repository.preflightCommittedRecovery( - REQUEST_ID, - ACCOUNT_ID, - new CallerIdentity( - "spiffe://firemud/ns/other/sa/game-session-service", - CALLER_CONTEXT_ID)))) + assertThatThrownBy(() -> + inWritableOwnerTransaction(() -> + repository.preflightCommittedRecovery( + REQUEST_ID, + ACCOUNT_ID, + new CallerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", CALLER_CONTEXT_ID)))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class) .hasNoCause(); - assertThatThrownBy( - () -> - inWritableOwnerTransaction( - () -> - repository.preflightCommittedRecovery( - REQUEST_ID, - ACCOUNT_ID, - new CallerIdentity( - WORKLOAD, - UUID.fromString("e46c59e8-4dd8-49a7-9d26-2db49f0d0ecb"))))) + assertThatThrownBy(() -> + inWritableOwnerTransaction(() -> + repository.preflightCommittedRecovery( + REQUEST_ID, + ACCOUNT_ID, + new CallerIdentity( + WORKLOAD, UUID.fromString("e46c59e8-4dd8-49a7-9d26-2db49f0d0ecb"))))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.IdempotencyConflictException.class) .hasNoCause(); @@ -357,13 +333,11 @@ void committedRecoveryPreflightRejectsAnExpiredOriginalDeadlineBeforeOwnerReads( when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) .thenReturn(fixture.operationRow()); - assertThatThrownBy( - () -> - inWritableOwnerTransaction( - () -> - fixture - .repository() - .preflightCommittedRecovery(REQUEST_ID, ACCOUNT_ID, fixture.caller()))) + assertThatThrownBy(() -> + inWritableOwnerTransaction(() -> + fixture + .repository() + .preflightCommittedRecovery(REQUEST_ID, ACCOUNT_ID, fixture.caller()))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.ResponseRecoveryExpiredException .class) @@ -381,17 +355,12 @@ void committedRecoveryRejectsDecryptedDigestDriftAndMissingEnvelopeKey() throws .crypto() .decrypt(any(EncryptedResponseEnvelope.class), any(Binding.class), any(Instant.class))) .thenReturn(alteredJwt); - assertThatThrownBy( - () -> - inWritableOwnerTransaction( - () -> - digestHarness - .repository() - .recoverCommittedResponse( - REQUEST_ID, - ACCOUNT_ID, - digestFixture.caller(), - digestHarness.active()))) + assertThatThrownBy(() -> + inWritableOwnerTransaction(() -> + digestHarness + .repository() + .recoverCommittedResponse( + REQUEST_ID, ACCOUNT_ID, digestFixture.caller(), digestHarness.active()))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.StorageUnavailableException.class) .hasNoCause(); @@ -404,17 +373,15 @@ void committedRecoveryRejectsDecryptedDigestDriftAndMissingEnvelopeKey() throws .crypto() .decrypt(any(EncryptedResponseEnvelope.class), any(Binding.class), any(Instant.class))) .thenThrow(missingKey); - assertThatThrownBy( - () -> - inWritableOwnerTransaction( - () -> - missingKeyHarness - .repository() - .recoverCommittedResponse( - REQUEST_ID, - ACCOUNT_ID, - missingKeyFixture.caller(), - missingKeyHarness.active()))) + assertThatThrownBy(() -> + inWritableOwnerTransaction(() -> + missingKeyHarness + .repository() + .recoverCommittedResponse( + REQUEST_ID, + ACCOUNT_ID, + missingKeyFixture.caller(), + missingKeyHarness.active()))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.StorageUnavailableException.class) .hasNoCause(); @@ -426,14 +393,12 @@ void activeHashAndEnvelopeDigestDriftFailBeforeDecryption() throws Exception { RecoveryHarness harness = recoveryHarness(fixture); when(harness.active().tokenSha256()).thenReturn("f".repeat(64)); - assertThatThrownBy( - () -> - inWritableOwnerTransaction( - () -> - harness - .repository() - .recoverCommittedResponse( - REQUEST_ID, ACCOUNT_ID, fixture.caller(), harness.active()))) + assertThatThrownBy(() -> + inWritableOwnerTransaction(() -> + harness + .repository() + .recoverCommittedResponse( + REQUEST_ID, ACCOUNT_ID, fixture.caller(), harness.active()))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.OwnerEvidenceUnavailableException .class) @@ -445,17 +410,15 @@ void activeHashAndEnvelopeDigestDriftFailBeforeDecryption() throws Exception { RecoveryHarness envelopeHarness = recoveryHarness(envelopeFixture); when(envelopeFixture.envelopeRow().get("envelope_sha256", String.class)) .thenReturn("f".repeat(64)); - assertThatThrownBy( - () -> - inWritableOwnerTransaction( - () -> - envelopeHarness - .repository() - .recoverCommittedResponse( - REQUEST_ID, - ACCOUNT_ID, - envelopeFixture.caller(), - envelopeHarness.active()))) + assertThatThrownBy(() -> + inWritableOwnerTransaction(() -> + envelopeHarness + .repository() + .recoverCommittedResponse( + REQUEST_ID, + ACCOUNT_ID, + envelopeFixture.caller(), + envelopeHarness.active()))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.StorageUnavailableException.class) .hasNoCause(); @@ -468,14 +431,11 @@ void expiryAndMissingOwnerBundleDenyWithoutCreatingOrExposingEnvelope() throws E Fixture expired = fixture(NOW.minusSeconds(121L)); when(expired.dsl().fetchOne(anyString(), any(Object[].class))) .thenReturn(expired.operationRow()); - assertThatThrownBy( - () -> - inWritableOwnerTransaction( - () -> - expired - .repository() - .sealPendingCandidate( - REQUEST_ID, expired.caller(), expired.compactJwt()))) + assertThatThrownBy(() -> + inWritableOwnerTransaction(() -> + expired + .repository() + .sealPendingCandidate(REQUEST_ID, expired.caller(), expired.compactJwt()))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.ResponseRecoveryExpiredException .class); @@ -493,14 +453,11 @@ void expiryAndMissingOwnerBundleDenyWithoutCreatingOrExposingEnvelope() throws E when(missing.bundles().captureAndPersist(REQUEST_ID)) .thenThrow(new AccountAuthEvidenceBundleRepository.OwnerEvidenceUnavailableException()); - assertThatThrownBy( - () -> - inWritableOwnerTransaction( - () -> - missing - .repository() - .sealPendingCandidate( - REQUEST_ID, missing.caller(), missing.compactJwt()))) + assertThatThrownBy(() -> + inWritableOwnerTransaction(() -> + missing + .repository() + .sealPendingCandidate(REQUEST_ID, missing.caller(), missing.compactJwt()))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.OwnerEvidenceUnavailableException .class); @@ -513,27 +470,25 @@ void expiryAndMissingOwnerBundleDenyWithoutCreatingOrExposingEnvelope() throws E void pendingCandidateResumeRejectsAlteredEncryptedEnvelopeBeforeDecryption() throws Exception { Fixture fixture = fixture(NOW); when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0); - if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { - return fixture.operationRow(); - } - if (sql.contains("FROM accounts")) return fixture.accountRow(); - if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { - return fixture.envelopeRow(); - } - throw new AssertionError("Unexpected pending-resume SQL in component fixture"); - }); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { + return fixture.operationRow(); + } + if (sql.contains("FROM accounts")) return fixture.accountRow(); + if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { + return fixture.envelopeRow(); + } + throw new AssertionError("Unexpected pending-resume SQL in component fixture"); + }); when(fixture.bundles().readStoredNonAuthorizingValue(OPERATION_ID)) .thenReturn(fixture.bundle()); when(fixture.envelopeRow().get("envelope_bytes", byte[].class)) .thenReturn(new byte[] {9, 8, 7, 6, 5}); - assertThatThrownBy( - () -> - inWritableOwnerTransaction( - () -> fixture.repository().openPendingCandidate(REQUEST_ID, fixture.caller()))) + assertThatThrownBy(() -> + inWritableOwnerTransaction( + () -> fixture.repository().openPendingCandidate(REQUEST_ID, fixture.caller()))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.StorageUnavailableException.class) .hasNoCause(); @@ -548,18 +503,17 @@ private static RecoveryHarness recoveryHarness(Fixture fixture) throws Exception ActiveCommittedIssuanceObservation active = activeObservation(fixture); when(fixture.operationRow().get("status", String.class)).thenReturn("COMMITTED"); when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0); - if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { - return fixture.operationRow(); - } - if (sql.contains("FROM accounts")) return fixture.accountRow(); - if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { - return fixture.envelopeRow(); - } - throw new AssertionError("Unexpected recovery SQL in component fixture"); - }); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { + return fixture.operationRow(); + } + if (sql.contains("FROM accounts")) return fixture.accountRow(); + if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { + return fixture.envelopeRow(); + } + throw new AssertionError("Unexpected recovery SQL in component fixture"); + }); when(fixture .sourceEvidence() .readCurrentIssuerAccountSources( @@ -651,14 +605,11 @@ void sourceVersionOrFenceChangeDeniesBeforeBundleRead() throws Exception { GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) .thenReturn(changed); - assertThatThrownBy( - () -> - inWritableOwnerTransaction( - () -> - fixture - .repository() - .sealPendingCandidate( - REQUEST_ID, fixture.caller(), fixture.compactJwt()))) + assertThatThrownBy(() -> + inWritableOwnerTransaction(() -> + fixture + .repository() + .sealPendingCandidate(REQUEST_ID, fixture.caller(), fixture.compactJwt()))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.AuthorityChangedException.class); verifyNoInteractions(fixture.bundles(), fixture.crypto()); @@ -678,14 +629,11 @@ void bundleReadbackMustMatchTheSameOwnerEvaluationBytes() throws Exception { when(fixture.bundles().readStoredNonAuthorizingValue(OPERATION_ID)) .thenReturn(bundle(fixture.digest(), "3".repeat(64))); - assertThatThrownBy( - () -> - inWritableOwnerTransaction( - () -> - fixture - .repository() - .sealPendingCandidate( - REQUEST_ID, fixture.caller(), fixture.compactJwt()))) + assertThatThrownBy(() -> + inWritableOwnerTransaction(() -> + fixture + .repository() + .sealPendingCandidate(REQUEST_ID, fixture.caller(), fixture.compactJwt()))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.OwnerEvidenceUnavailableException .class); @@ -704,10 +652,9 @@ void tokenGenerationRequiresCanonicalOneStringAndRejectsOtherWireValues() throws assertThat(AccountAuthEvidenceBundle.parseCanonical(bundle.canonicalBytes())).isEqualTo(bundle); for (Object invalidTokenGeneration : List.of(1L, "01", "2")) { - assertThatThrownBy( - () -> - AccountAuthEvidenceBundle.parseCanonical( - bundleBytesWithTokenGeneration(bundle, invalidTokenGeneration))) + assertThatThrownBy(() -> + AccountAuthEvidenceBundle.parseCanonical( + bundleBytesWithTokenGeneration(bundle, invalidTokenGeneration))) .isInstanceOf(AccountAuthEvidenceBundle.InvalidBundleException.class); } } @@ -722,18 +669,17 @@ void mismatchedStoredEnvelopeExpiryIsNotReplayed() throws Exception { fixture.sealed().bytes(), NOW.getEpochSecond() + 119L); when(fixture.dsl().fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0); - if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { - return fixture.operationRow(); - } - if (sql.contains("FROM accounts")) return fixture.accountRow(); - if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { - return mismatchedExpiry; - } - throw new AssertionError("Unexpected SQL in component fixture"); - }); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM account_gameplay_delegation_issuance_operations")) { + return fixture.operationRow(); + } + if (sql.contains("FROM accounts")) return fixture.accountRow(); + if (sql.contains("FROM account_gameplay_delegation_response_envelopes")) { + return mismatchedExpiry; + } + throw new AssertionError("Unexpected SQL in component fixture"); + }); when(fixture .sourceEvidence() .readCurrentIssuerAccountSources( @@ -743,14 +689,11 @@ void mismatchedStoredEnvelopeExpiryIsNotReplayed() throws Exception { when(fixture.bundles().readStoredNonAuthorizingValue(OPERATION_ID)) .thenReturn(fixture.bundle()); - assertThatThrownBy( - () -> - inWritableOwnerTransaction( - () -> - fixture - .repository() - .sealPendingCandidate( - REQUEST_ID, fixture.caller(), fixture.compactJwt()))) + assertThatThrownBy(() -> + inWritableOwnerTransaction(() -> + fixture + .repository() + .sealPendingCandidate(REQUEST_ID, fixture.caller(), fixture.compactJwt()))) .isInstanceOf( AccountGameplayDelegationResponseEnvelopeRepository.StorageUnavailableException.class); verify(fixture.crypto(), never()) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java index 079de0a485..4904f2dbc7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountGameplayTokenIdentityFenceRepositoryTest.java @@ -121,10 +121,8 @@ void missingCommittedSourceCannotAuthorizeEvenWithActiveTokenRow() { Record token = tokenRow(State.ACTIVE); stubOwnerRows(dsl, account, token, null); transaction(); - assertThatThrownBy( - () -> - new AccountGameplayTokenIdentityFenceRepository(dsl) - .requireActiveForUpdate(IDENTITY)) + assertThatThrownBy(() -> + new AccountGameplayTokenIdentityFenceRepository(dsl).requireActiveForUpdate(IDENTITY)) .isInstanceOf(TokenFenceUnavailableException.class); } @@ -191,10 +189,8 @@ void exactIdentityMismatchCannotUseAnotherActiveFence() { IDENTITY.notBeforeEpochSecond() + 1L, IDENTITY.tokenGeneration(), IDENTITY.issuanceFence()); - assertThatThrownBy( - () -> - new AccountGameplayTokenIdentityFenceRepository(dsl) - .requireActiveForUpdate(changedNbf)) + assertThatThrownBy(() -> + new AccountGameplayTokenIdentityFenceRepository(dsl).requireActiveForUpdate(changedNbf)) .isInstanceOf(TokenFenceUnavailableException.class); } @@ -207,10 +203,8 @@ void pendingAndCommittedRevocationBothDenyAdmission() { Record source = mock(Record.class); stubOwnerRows(dsl, account, token, source); transaction(); - assertThatThrownBy( - () -> - new AccountGameplayTokenIdentityFenceRepository(dsl) - .requireActiveForUpdate(IDENTITY)) + assertThatThrownBy(() -> + new AccountGameplayTokenIdentityFenceRepository(dsl).requireActiveForUpdate(IDENTITY)) .isInstanceOf(TokenRevokedException.class); } } @@ -222,10 +216,8 @@ void actualOriginalDisposalGuardDeniesBeforeReadingAnActiveTokenFence() { when(dsl.fetchOne(DISPOSAL_GUARD_SELECT, IDENTITY.issuanceRequestId())) .thenReturn(mock(Record.class)); transaction(); - assertThatThrownBy( - () -> - new AccountGameplayTokenIdentityFenceRepository(dsl) - .requireActiveForUpdate(IDENTITY)) + assertThatThrownBy(() -> + new AccountGameplayTokenIdentityFenceRepository(dsl).requireActiveForUpdate(IDENTITY)) .isInstanceOf(TokenRevokedException.class); verify(dsl, never()).fetchOne(startsWith(TOKEN_SELECT_PREFIX), eq(IDENTITY.operationId())); verify(dsl, never()) @@ -273,10 +265,9 @@ void disposedStoredRevocationIntentStillRejectsAChangedRequest() { AccountGameplayTokenIdentityFenceRepository.revocationDigest(IDENTITY, changedRequest); transaction(); - assertThatThrownBy( - () -> - new AccountGameplayTokenIdentityFenceRepository(dsl) - .beginRevocationIntent(IDENTITY, changedRequest, digest)) + assertThatThrownBy(() -> + new AccountGameplayTokenIdentityFenceRepository(dsl) + .beginRevocationIntent(IDENTITY, changedRequest, digest)) .isInstanceOf( AccountGameplayTokenIdentityFenceRepository.RevocationConflictException.class); verify(dsl, never()) @@ -294,10 +285,9 @@ void disposalStillDeniesStartingANewRevocationIntentFromAnActiveFence() { AccountGameplayTokenIdentityFenceRepository.revocationDigest(IDENTITY, requestId); transaction(); - assertThatThrownBy( - () -> - new AccountGameplayTokenIdentityFenceRepository(dsl) - .beginRevocationIntent(IDENTITY, requestId, digest)) + assertThatThrownBy(() -> + new AccountGameplayTokenIdentityFenceRepository(dsl) + .beginRevocationIntent(IDENTITY, requestId, digest)) .isInstanceOf(TokenRevokedException.class); verify(dsl, never()) .execute(startsWith("UPDATE account_gameplay_token_identity_fences"), any(Object[].class)); @@ -412,10 +402,9 @@ void revocationDigestBindsEveryExactTokenIdentityAndRequestField() { void callerClaimedDigestCannotStartRevocationOrAcquireLocks() { DSLContext dsl = mock(DSLContext.class); transaction(); - assertThatThrownBy( - () -> - new AccountGameplayTokenIdentityFenceRepository(dsl) - .beginRevocationIntent(IDENTITY, UUID.randomUUID(), "b".repeat(64))) + assertThatThrownBy(() -> + new AccountGameplayTokenIdentityFenceRepository(dsl) + .beginRevocationIntent(IDENTITY, UUID.randomUUID(), "b".repeat(64))) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(dsl); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingBillingStreamReadTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingBillingStreamReadTest.java index eecfa54281..5a24cf4208 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingBillingStreamReadTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingBillingStreamReadTest.java @@ -106,10 +106,9 @@ void inverseRejectsUnknownNoncanonicalDuplicateOversizedAndContradictoryEnvelope fields -> fields.put("receipt", Map.of("hardCutoff", false)))) { Map fields = JSON.readValue(original, new TypeReference<>() {}); mutation.accept(fields); - assertThatThrownBy( - () -> - AccountHostingSubscriptionLifecycleEvidence.verifyBilling( - AccountHostingSubscriptionLifecycleEvidence.encode(fields))) + assertThatThrownBy(() -> + AccountHostingSubscriptionLifecycleEvidence.verifyBilling( + AccountHostingSubscriptionLifecycleEvidence.encode(fields))) .isInstanceOf(IllegalArgumentException.class); } String text = new String(original, StandardCharsets.UTF_8); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java index f8e58a0a74..5dc14d87a8 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingPlanCatalogTest.java @@ -49,10 +49,9 @@ void noDefaultPlanOrAmbiguousDuplicateCanBecomeAQuote() { assertThatThrownBy(() -> new AccountHostingPlanCatalog(List.of(entry, entry))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Ambiguous"); - assertThatThrownBy( - () -> - new AccountHostingPlanCatalog( - List.of(entry, configuration("basic-hosting", "price_other")))) + assertThatThrownBy(() -> + new AccountHostingPlanCatalog( + List.of(entry, configuration("basic-hosting", "price_other")))) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> new AccountHostingPlanCatalog(Arrays.asList(entry, null))) .isInstanceOf(IllegalArgumentException.class); @@ -72,12 +71,11 @@ void integralConfigurationRejectsIncompleteFractionalNegativeAndOverflowValuesWi .isInstanceOf(IllegalArgumentException.class); } } - assertThatThrownBy( - () -> - new AccountHostingPlanCatalog( - List.of( - new ConfiguredPlan( - "basic-hosting", "price_explicit", "0", "100", "2", "1048576")))) + assertThatThrownBy(() -> + new AccountHostingPlanCatalog( + List.of( + new ConfiguredPlan( + "basic-hosting", "price_explicit", "0", "100", "2", "1048576")))) .isInstanceOf(IllegalArgumentException.class); var maximum = new AccountHostingPlanCatalog( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java index d201170637..156223618e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepositoryTest.java @@ -286,14 +286,13 @@ void reconciliationRequiresExplicitFiniteNonzeroBudgetsAndRepresentableDurations assertThatThrownBy( () -> limits(1, 1, Duration.ofHours(2), Duration.ofSeconds(1), Duration.ofHours(1))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - limits( - 1, - 1, - Duration.ofSeconds(1), - Duration.ofSeconds(1), - Duration.ofSeconds(Long.MAX_VALUE))) + assertThatThrownBy(() -> + limits( + 1, + 1, + Duration.ofSeconds(1), + Duration.ofSeconds(1), + Duration.ofSeconds(Long.MAX_VALUE))) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(dsl); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java index 9b297e414a..aefbfc425e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryCanonicalTest.java @@ -52,10 +52,9 @@ void firstJoinRejectsNonFirstEventSequenceBeforeOwnerStorageReads() { AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); var repository = new AccountJoinOperationRepository(dsl, scopes); - assertThatThrownBy( - () -> - repository.commitCanonicalFirstJoin( - "request-v2", mock(CanonicalJoinScopeV2.class), "caller", proof(2L, 2L))) + assertThatThrownBy(() -> + repository.commitCanonicalFirstJoin( + "request-v2", mock(CanonicalJoinScopeV2.class), "caller", proof(2L, 2L))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Exact first-JOIN terminal proof required"); verifyNoInteractions(dsl, scopes); @@ -67,10 +66,9 @@ void firstJoinRejectsNonFirstMembershipRevisionBeforeOwnerStorageReads() { AccountConnectScopeRepository scopes = mock(AccountConnectScopeRepository.class); var repository = new AccountJoinOperationRepository(dsl, scopes); - assertThatThrownBy( - () -> - repository.commitCanonicalFirstJoin( - "request-v2", mock(CanonicalJoinScopeV2.class), "caller", proof(1L, 3L))) + assertThatThrownBy(() -> + repository.commitCanonicalFirstJoin( + "request-v2", mock(CanonicalJoinScopeV2.class), "caller", proof(1L, 3L))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Exact first-JOIN terminal proof required"); verifyNoInteractions(dsl, scopes); @@ -107,9 +105,8 @@ void boundPendingDiagnosticsRemainSeparateFromTheAvailablePolicy() { assertThat(unavailable.lastAttemptFailureCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); assertThatThrownBy(() -> evidence(true, "PENDING", null, "UNAVAILABLE", null, null, null)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - evidence(true, "PENDING", null, "AVAILABLE", "ENTITLEMENT_UNAVAILABLE", null, null)) + assertThatThrownBy(() -> + evidence(true, "PENDING", null, "AVAILABLE", "ENTITLEMENT_UNAVAILABLE", null, null)) .isInstanceOf(IllegalArgumentException.class); } @@ -126,21 +123,18 @@ void failedEvidenceMayRetainPolicyButCannotCarrySuccessProofOrRetryableOutcome() assertThatThrownBy( () -> evidence(true, "FAILED", "AUTH_UNAVAILABLE", "AVAILABLE", null, null, null)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - evidence( - true, "FAILED", "CONNECT_SCOPE_INVALID", "AVAILABLE", null, validProof(), 73L)) + assertThatThrownBy(() -> + evidence(true, "FAILED", "CONNECT_SCOPE_INVALID", "AVAILABLE", null, validProof(), 73L)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - evidence( - true, - "FAILED", - "CONNECT_SCOPE_INVALID", - "UNAVAILABLE", - "ENTITLEMENT_UNAVAILABLE", - null, - null)) + assertThatThrownBy(() -> + evidence( + true, + "FAILED", + "CONNECT_SCOPE_INVALID", + "UNAVAILABLE", + "ENTITLEMENT_UNAVAILABLE", + null, + null)) .isInstanceOf(IllegalArgumentException.class); } @@ -182,10 +176,9 @@ void nullCommitOutcomeIsClassifiedBeforeOwnerStorageReads() { TransactionSynchronizationManager.setActualTransactionActive(true); TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); try { - assertThatThrownBy( - () -> - repository.commitCanonicalJoin( - "request-v2", mock(CanonicalJoinScopeV2.class), "caller", null, validProof())) + assertThatThrownBy(() -> + repository.commitCanonicalJoin( + "request-v2", mock(CanonicalJoinScopeV2.class), "caller", null, validProof())) .isInstanceOf(CanonicalJoinOperationConflictException.class) .hasMessage("Canonical JOIN outcome/proof conflict"); verifyNoInteractions(dsl, scopes); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryTest.java index ccb5817d76..de24d64355 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepositoryTest.java @@ -40,10 +40,9 @@ void canonicalIntentAndPolicyMethodsRequireOwnerTransactionBeforeStorageAccess() .isInstanceOf(IllegalStateException.class) .hasMessage( "Canonical Account JOIN operation access requires an active owner transaction"); - assertThatThrownBy( - () -> - repository.recordCanonicalPolicyUnavailable( - "request-v2", scope, "caller", "ENTITLEMENT_UNAVAILABLE")) + assertThatThrownBy(() -> + repository.recordCanonicalPolicyUnavailable( + "request-v2", scope, "caller", "ENTITLEMENT_UNAVAILABLE")) .isInstanceOf(IllegalStateException.class) .hasMessage( "Canonical Account JOIN operation access requires an active owner transaction"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepositoryTest.java index de62ed19c3..57112e70b0 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtJwksPublicationRepositoryTest.java @@ -147,61 +147,59 @@ void immutableEvidenceDigestsBindIntentReceiptAndMountedCorrespondence() { void immutableEvidenceRejectsChangedDigestAndNonAdvancingRemoteReadback() { PrepublicationIntent intent = intent(); - assertThatThrownBy( - () -> - new PrepublicationIntent( - intent.operationId(), - intent.binding(), - intent.operationDigest(), - intent.generationRequestDigest(), - intent.generationReceiptDigest(), - intent.desiredStateVersion(), - intent.trustFence(), - intent.apiBindingDigest(), - intent.apiConfigRevision(), - intent.configMapName(), - intent.configMapUid(), - intent.expectedResourceVersion(), - intent.expectedSnapshotDigest(), - intent.targetGeneration(), - intent.targetKid(), - intent.publicKeyFingerprint(), - intent.expectedDurableActive(), - intent.expectedPublishedActive(), - intent.jwksJson(), - intent.generationMarkerJson(), - intent.publicDataDigest(), - intent.generationMarkerDigest(), - "f".repeat(64))) + assertThatThrownBy(() -> + new PrepublicationIntent( + intent.operationId(), + intent.binding(), + intent.operationDigest(), + intent.generationRequestDigest(), + intent.generationReceiptDigest(), + intent.desiredStateVersion(), + intent.trustFence(), + intent.apiBindingDigest(), + intent.apiConfigRevision(), + intent.configMapName(), + intent.configMapUid(), + intent.expectedResourceVersion(), + intent.expectedSnapshotDigest(), + intent.targetGeneration(), + intent.targetKid(), + intent.publicKeyFingerprint(), + intent.expectedDurableActive(), + intent.expectedPublishedActive(), + intent.jwksJson(), + intent.generationMarkerJson(), + intent.publicDataDigest(), + intent.generationMarkerDigest(), + "f".repeat(64))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("intent digest"); - assertThatThrownBy( - () -> - new PrepublicationIntent( - intent.operationId(), - intent.binding(), - intent.operationDigest(), - intent.generationRequestDigest(), - intent.generationReceiptDigest(), - intent.desiredStateVersion(), - intent.trustFence(), - intent.apiBindingDigest(), - intent.apiConfigRevision(), - intent.configMapName(), - intent.configMapUid(), - intent.expectedResourceVersion(), - intent.expectedSnapshotDigest(), - intent.targetGeneration(), - intent.targetKid(), - intent.publicKeyFingerprint(), - intent.expectedDurableActive(), - intent.expectedPublishedActive(), - intent.jwksJson(), - intent.generationMarkerJson(), - intent.publicDataDigest(), - intent.generationMarkerDigest(), - "0".repeat(64))) + assertThatThrownBy(() -> + new PrepublicationIntent( + intent.operationId(), + intent.binding(), + intent.operationDigest(), + intent.generationRequestDigest(), + intent.generationReceiptDigest(), + intent.desiredStateVersion(), + intent.trustFence(), + intent.apiBindingDigest(), + intent.apiConfigRevision(), + intent.configMapName(), + intent.configMapUid(), + intent.expectedResourceVersion(), + intent.expectedSnapshotDigest(), + intent.targetGeneration(), + intent.targetKid(), + intent.publicKeyFingerprint(), + intent.expectedDurableActive(), + intent.expectedPublishedActive(), + intent.jwksJson(), + intent.generationMarkerJson(), + intent.publicDataDigest(), + intent.generationMarkerDigest(), + "0".repeat(64))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("intent digest"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepositoryTest.java index 281daec872..3068b80a16 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepositoryTest.java @@ -93,12 +93,11 @@ void firstInstallFenceHasExactAbsentActiveAndPublishedPair() { assertThat(fence.durableActive()).isEmpty(); assertThat(fence.publishedActive()).isEmpty(); - assertThatThrownBy( - () -> - new AccountJwtReadinessProbeRepository.SignerFence( - Optional.empty(), - Optional.of( - new AccountJwtSignerDesiredStateRepository.ActiveSigner("1", "old-key")))) + assertThatThrownBy(() -> + new AccountJwtReadinessProbeRepository.SignerFence( + Optional.empty(), + Optional.of( + new AccountJwtSignerDesiredStateRepository.ActiveSigner("1", "old-key")))) .isInstanceOf(AccountJwtReadinessProbeRepository.QuarantinedStateException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java index f6e26dcfbe..56702f5d1e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepositoryTest.java @@ -168,15 +168,10 @@ void promotionCommitRequiresOwnerCreatedReadinessProofBeforeSql() { AccountJwtSignerDesiredStateRepository repository = new AccountJwtSignerDesiredStateRepository(dsl); - assertThatThrownBy( - () -> - inWritableTransaction( - () -> - repository.commitPreparedPromotion( - BINDING, - TRUST, - UUID.fromString("44444444-4444-4444-8444-444444444444"), - null))) + assertThatThrownBy(() -> + inWritableTransaction(() -> + repository.commitPreparedPromotion( + BINDING, TRUST, UUID.fromString("44444444-4444-4444-8444-444444444444"), null))) .isInstanceOf(NullPointerException.class) .hasMessageContaining("readiness proof"); verifyNoInteractions(dsl); @@ -214,28 +209,26 @@ void preparedPromotionDispatchReturnsReadbackAndRetryDoesNotRepeatCas() throws E Conversation conversation = new Conversation(); GenerationRequest request = inWritableTransaction(conversation::ensureRequest); GenerationRequest pending = - inWritableTransaction( - () -> - conversation.repository.recordSecretObservation( - BINDING, - TRUST, - request.operationId(), - request.operationDigest(), - SECRET_UID.toString(), - "12")); + inWritableTransaction(() -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + request.operationId(), + request.operationDigest(), + SECRET_UID.toString(), + "12")); PublicJwk jwk = publicJwk(request.targetKid()); GenerationResult result = - inWritableTransaction( - () -> - conversation.repository.recordGenerationResult( - BINDING, - TRUST, - request.operationId(), - pending.generationRequestDigest(), - SECRET_UID.toString(), - "12", - "13", - jwk.json())); + inWritableTransaction(() -> + conversation.repository.recordGenerationResult( + BINDING, + TRUST, + request.operationId(), + pending.generationRequestDigest(), + SECRET_UID.toString(), + "12", + "13", + jwk.json())); conversation.preparePromotionForDispatch(request, result); var first = @@ -257,45 +250,39 @@ void preparedPromotionDispatchRejectsExpiredReadinessBeforeDurableDispatch() thr Conversation conversation = new Conversation(); GenerationRequest request = inWritableTransaction(conversation::ensureRequest); GenerationRequest pending = - inWritableTransaction( - () -> - conversation.repository.recordSecretObservation( - BINDING, - TRUST, - request.operationId(), - request.operationDigest(), - SECRET_UID.toString(), - "12")); + inWritableTransaction(() -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + request.operationId(), + request.operationDigest(), + SECRET_UID.toString(), + "12")); PublicJwk jwk = publicJwk(request.targetKid()); GenerationResult result = - inWritableTransaction( - () -> - conversation.repository.recordGenerationResult( - BINDING, - TRUST, - request.operationId(), - pending.generationRequestDigest(), - SECRET_UID.toString(), - "12", - "13", - jwk.json())); + inWritableTransaction(() -> + conversation.repository.recordGenerationResult( + BINDING, + TRUST, + request.operationId(), + pending.generationRequestDigest(), + SECRET_UID.toString(), + "12", + "13", + jwk.json())); conversation.preparePromotionForDispatch(request, result); - assertThatThrownBy( - () -> - inWritableTransaction( - () -> conversation.repository.readCurrentGenerationRequest(BINDING, TRUST))) + assertThatThrownBy(() -> + inWritableTransaction( + () -> conversation.repository.readCurrentGenerationRequest(BINDING, TRUST))) .isInstanceOf( AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException.class) .hasMessageContaining( "Existing PREPARED signer state requires unavailable lifecycle evidence"); conversation.expireReadinessPlan(); - assertThatThrownBy( - () -> - inWritableTransaction( - () -> - conversation.repository.readAndMarkPreparedPromotionDispatched( - BINDING, TRUST))) + assertThatThrownBy(() -> + inWritableTransaction(() -> + conversation.repository.readAndMarkPreparedPromotionDispatched(BINDING, TRUST))) .isInstanceOf( AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException.class) .hasMessageContaining("expired before private dispatch"); @@ -309,48 +296,42 @@ void preparedPromotionDispatchCasRechecksReadinessDeadlineAtomically() throws Ex Conversation conversation = new Conversation(); GenerationRequest request = inWritableTransaction(conversation::ensureRequest); GenerationRequest pending = - inWritableTransaction( - () -> - conversation.repository.recordSecretObservation( - BINDING, - TRUST, - request.operationId(), - request.operationDigest(), - SECRET_UID.toString(), - "12")); + inWritableTransaction(() -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + request.operationId(), + request.operationDigest(), + SECRET_UID.toString(), + "12")); PublicJwk jwk = publicJwk(request.targetKid()); GenerationResult result = - inWritableTransaction( - () -> - conversation.repository.recordGenerationResult( - BINDING, - TRUST, - request.operationId(), - pending.generationRequestDigest(), - SECRET_UID.toString(), - "12", - "13", - jwk.json())); + inWritableTransaction(() -> + conversation.repository.recordGenerationResult( + BINDING, + TRUST, + request.operationId(), + pending.generationRequestDigest(), + SECRET_UID.toString(), + "12", + "13", + jwk.json())); conversation.preparePromotionForDispatch(request, result); conversation.expireReadinessAtDispatchCas(); - assertThatThrownBy( - () -> - inWritableTransaction( - () -> - conversation.repository.readAndMarkPreparedPromotionDispatched( - BINDING, TRUST))) + assertThatThrownBy(() -> + inWritableTransaction(() -> + conversation.repository.readAndMarkPreparedPromotionDispatched(BINDING, TRUST))) .isInstanceOf(AccountJwtSignerDesiredStateRepository.VersionConflictException.class); assertThat(conversation.promotionDispatchCasCount).isZero(); assertThat(conversation.executedStatements) - .anySatisfy( - sql -> { - assertThat(sql).contains("WITH readiness_clock AS MATERIALIZED"); - assertThat(sql).contains("clock_timestamp()"); - assertThat(sql).contains("plan.expires_at_epoch_seconds"); - assertThat(sql).contains("entry.expires_at_epoch_seconds"); - assertThat(sql).doesNotContain("CURRENT_TIMESTAMP"); - }); + .anySatisfy(sql -> { + assertThat(sql).contains("WITH readiness_clock AS MATERIALIZED"); + assertThat(sql).contains("clock_timestamp()"); + assertThat(sql).contains("plan.expires_at_epoch_seconds"); + assertThat(sql).contains("entry.expires_at_epoch_seconds"); + assertThat(sql).doesNotContain("CURRENT_TIMESTAMP"); + }); } @Test @@ -358,28 +339,26 @@ void exactDispatchedReadinessProofCanCommitAfterExpiryButChangedProofCannot() th Conversation conversation = new Conversation(); GenerationRequest request = inWritableTransaction(conversation::ensureRequest); GenerationRequest pending = - inWritableTransaction( - () -> - conversation.repository.recordSecretObservation( - BINDING, - TRUST, - request.operationId(), - request.operationDigest(), - SECRET_UID.toString(), - "12")); + inWritableTransaction(() -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + request.operationId(), + request.operationDigest(), + SECRET_UID.toString(), + "12")); PublicJwk jwk = publicJwk(request.targetKid()); GenerationResult result = - inWritableTransaction( - () -> - conversation.repository.recordGenerationResult( - BINDING, - TRUST, - request.operationId(), - pending.generationRequestDigest(), - SECRET_UID.toString(), - "12", - "13", - jwk.json())); + inWritableTransaction(() -> + conversation.repository.recordGenerationResult( + BINDING, + TRUST, + request.operationId(), + pending.generationRequestDigest(), + SECRET_UID.toString(), + "12", + "13", + jwk.json())); conversation.preparePromotionForDispatch(request, result); ReadinessPromotionProof exactProof = conversation.readinessProof( @@ -388,12 +367,10 @@ void exactDispatchedReadinessProofCanCommitAfterExpiryButChangedProofCannot() th conversation.expireReadinessPlan(); conversation.recordPromotionReceipts(result); int statementsBeforeUndeliveredRecovery = conversation.executedStatements.size(); - assertThatThrownBy( - () -> - inWritableTransaction( - () -> - conversation.repository.commitPreparedPromotion( - BINDING, TRUST, conversation.preparedPromotionId, exactProof))) + assertThatThrownBy(() -> + inWritableTransaction(() -> + conversation.repository.commitPreparedPromotion( + BINDING, TRUST, conversation.preparedPromotionId, exactProof))) .isInstanceOf(AccountJwtSignerDesiredStateRepository.QuarantinedStateException.class) .hasMessageContaining( "Promotion dispatch state is inconsistent with its receipts or terminal status"); @@ -407,12 +384,9 @@ void exactDispatchedReadinessProofCanCommitAfterExpiryButChangedProofCannot() th conversation.preparedPromotionValues.put("active_jwks_receipt_digest", null); conversation.preparedPromotionValues.put("active_jwks_public_data_digest", null); conversation.preparedPromotionValues.put("active_jwks_observed_resource_version", null); - assertThatThrownBy( - () -> - inWritableTransaction( - () -> - conversation.repository.readAndMarkPreparedPromotionDispatched( - BINDING, TRUST))) + assertThatThrownBy(() -> + inWritableTransaction(() -> + conversation.repository.readAndMarkPreparedPromotionDispatched(BINDING, TRUST))) .isInstanceOf( AccountJwtSignerDesiredStateRepository.PromotionPrerequisitesIncompleteException.class) .hasMessageContaining("expired before private dispatch"); @@ -434,12 +408,10 @@ void exactDispatchedReadinessProofCanCommitAfterExpiryButChangedProofCannot() th TRUST.bindingDigest(), "binding-r2"); int statementsBeforeChangedTrust = conversation.executedStatements.size(); - assertThatThrownBy( - () -> - inWritableTransaction( - () -> - conversation.repository.commitPreparedPromotion( - BINDING, changedTrust, conversation.preparedPromotionId, exactProof))) + assertThatThrownBy(() -> + inWritableTransaction(() -> + conversation.repository.commitPreparedPromotion( + BINDING, changedTrust, conversation.preparedPromotionId, exactProof))) .isInstanceOf(AccountJwtSignerDesiredStateRepository.BindingMismatchException.class) .hasMessageContaining("pinned enrollment"); assertThat( @@ -449,12 +421,10 @@ void exactDispatchedReadinessProofCanCommitAfterExpiryButChangedProofCannot() th conversation.changePreparedStateForCommit(); int statementsBeforeChangedState = conversation.executedStatements.size(); - assertThatThrownBy( - () -> - inWritableTransaction( - () -> - conversation.repository.commitPreparedPromotion( - BINDING, TRUST, conversation.preparedPromotionId, exactProof))) + assertThatThrownBy(() -> + inWritableTransaction(() -> + conversation.repository.commitPreparedPromotion( + BINDING, TRUST, conversation.preparedPromotionId, exactProof))) .isInstanceOf(AccountJwtSignerDesiredStateRepository.QuarantinedStateException.class) .hasMessageContaining("exact desired-state fence"); assertThat( @@ -467,12 +437,10 @@ void exactDispatchedReadinessProofCanCommitAfterExpiryButChangedProofCannot() th changedPreimage[0] ^= 1; ReadinessPromotionProof changedProof = conversation.readinessProof(result, changedPreimage); int statementsBeforeChangedProof = conversation.executedStatements.size(); - assertThatThrownBy( - () -> - inWritableTransaction( - () -> - conversation.repository.commitPreparedPromotion( - BINDING, TRUST, conversation.preparedPromotionId, changedProof))) + assertThatThrownBy(() -> + inWritableTransaction(() -> + conversation.repository.commitPreparedPromotion( + BINDING, TRUST, conversation.preparedPromotionId, changedProof))) .isInstanceOf(AccountJwtSignerDesiredStateRepository.IdempotencyConflictException.class) .hasMessageContaining("frozen PREPARED evidence"); assertThat( @@ -483,34 +451,28 @@ void exactDispatchedReadinessProofCanCommitAfterExpiryButChangedProofCannot() th String exactPrivateReceiptDigest = (String) conversation.preparedPromotionValues.get("private_promotion_receipt_digest"); var exactPrivateRecovery = - inWritableTransaction( - () -> - conversation.repository.readPreparedPrivatePromotionReceiptForRecovery( - BINDING, TRUST)); + inWritableTransaction(() -> + conversation.repository.readPreparedPrivatePromotionReceiptForRecovery(BINDING, TRUST)); assertThat(exactPrivateRecovery.promotionOperationId()) .isEqualTo(conversation.preparedPromotionId); assertThat(exactPrivateRecovery.generationOperationId()).isEqualTo(result.operationId()); assertThat(exactPrivateRecovery.receiptDigest()).isEqualTo(exactPrivateReceiptDigest); int statementsBeforeRecovery = conversation.executedStatements.size(); conversation.preparedPromotionValues.put("private_promotion_receipt_digest", "0".repeat(64)); - assertThatThrownBy( - () -> - inWritableTransaction( - () -> - conversation.repository.readPreparedPrivatePromotionReceiptForRecovery( - BINDING, TRUST))) + assertThatThrownBy(() -> + inWritableTransaction(() -> + conversation.repository.readPreparedPrivatePromotionReceiptForRecovery( + BINDING, TRUST))) .isExactlyInstanceOf(AccountJwtSignerDesiredStateRepository.QuarantinedStateException.class) .hasMessageContaining("private promotion receipt digest is invalid"); assertThat( conversation.executedStatements.subList( statementsBeforeRecovery, conversation.executedStatements.size())) .noneMatch(sql -> sql.contains("UPDATE ") || sql.contains("INSERT ")); - assertThatThrownBy( - () -> - inWritableTransaction( - () -> - conversation.repository.commitPreparedPromotion( - BINDING, TRUST, conversation.preparedPromotionId, exactProof))) + assertThatThrownBy(() -> + inWritableTransaction(() -> + conversation.repository.commitPreparedPromotion( + BINDING, TRUST, conversation.preparedPromotionId, exactProof))) .isInstanceOf(AccountJwtSignerDesiredStateRepository.QuarantinedStateException.class) .hasMessageContaining("private promotion receipt digest is invalid"); conversation.preparedPromotionValues.put("status", "PREPARED"); @@ -518,10 +480,9 @@ void exactDispatchedReadinessProofCanCommitAfterExpiryButChangedProofCannot() th "private_promotion_receipt_digest", exactPrivateReceiptDigest); var committed = - inWritableTransaction( - () -> - conversation.repository.commitPreparedPromotion( - BINDING, TRUST, conversation.preparedPromotionId, exactProof)); + inWritableTransaction(() -> + conversation.repository.commitPreparedPromotion( + BINDING, TRUST, conversation.preparedPromotionId, exactProof)); assertThat(committed.promotion().status()).isEqualTo("COMMITTED"); assertThat(committed.desiredState().recordVersion()).isEqualTo(4L); String terminalUpdate = @@ -550,12 +511,11 @@ void lockedEnrollmentRecoveryReadPinsOwnerRowWithoutChangingAnyEvidence() { ArgumentCaptor queries = ArgumentCaptor.forClass(String.class); verify(dsl, times(2)).fetchOne(queries.capture(), any(Object[].class)); assertThat(queries.getAllValues()) - .allSatisfy( - sql -> { - assertThat(sql) - .contains("FROM account_jwt_signer_desired_states") - .endsWith(" FOR UPDATE"); - }); + .allSatisfy(sql -> { + assertThat(sql) + .contains("FROM account_jwt_signer_desired_states") + .endsWith(" FOR UPDATE"); + }); verify(dsl, never()).execute(anyString(), any(Object[].class)); } @@ -600,10 +560,9 @@ void historicalAbortedGenerationHighWaterPreventsReuseWithoutActiveSigner() { .anyMatch(sql -> sql.contains("account_jwt_signer_generation_operations")); verify(conversation.dsl) .fetchOne( - org.mockito.ArgumentMatchers.argThat( - sql -> - sql.contains("COALESCE(MAX(target_generation), 0)") - && sql.contains("account_jwt_signer_generation_operations")), + org.mockito.ArgumentMatchers.argThat(sql -> + sql.contains("COALESCE(MAX(target_generation), 0)") + && sql.contains("account_jwt_signer_generation_operations")), any(Object[].class)); } @@ -681,10 +640,8 @@ void committedActiveSignerNeedsAnExplicitDurableRotationRequest() { Record activeState = record(values); when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(activeState); - assertThatThrownBy( - () -> - inWritableTransaction( - () -> repository.ensureCurrentGenerationRequest(BINDING, TRUST))) + assertThatThrownBy(() -> + inWritableTransaction(() -> repository.ensureCurrentGenerationRequest(BINDING, TRUST))) .isInstanceOf( AccountJwtSignerDesiredStateRepository.MissingGenerationOperationException.class) .hasMessageContaining("durable rotation request"); @@ -697,25 +654,23 @@ void secretObservationUnlocksOnlyTheExactGenerationFenceAndChangedReplayConflict GenerationRequest operation = inWritableTransaction(conversation::ensureRequest); GenerationRequest pending = - inWritableTransaction( - () -> - conversation.repository.recordSecretObservation( - BINDING, - TRUST, - operation.operationId(), - operation.operationDigest(), - SECRET_UID.toString(), - "12")); + inWritableTransaction(() -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "12")); GenerationRequest replay = - inWritableTransaction( - () -> - conversation.repository.recordSecretObservation( - BINDING, - TRUST, - operation.operationId(), - operation.operationDigest(), - SECRET_UID.toString(), - "12")); + inWritableTransaction(() -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "12")); assertThat(pending.phase()).isEqualTo(GenerationPhase.GENERATE_PENDING); assertThat(pending.generationRequestDigest()).hasSize(64); @@ -725,17 +680,15 @@ void secretObservationUnlocksOnlyTheExactGenerationFenceAndChangedReplayConflict assertThat(replay).isEqualTo(pending); int executedBeforeConflict = conversation.executedStatements.size(); - assertThatThrownBy( - () -> - inWritableTransaction( - () -> - conversation.repository.recordSecretObservation( - BINDING, - TRUST, - operation.operationId(), - operation.operationDigest(), - SECRET_UID.toString(), - "changed-rv"))) + assertThatThrownBy(() -> + inWritableTransaction(() -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "changed-rv"))) .isInstanceOf(AccountJwtSignerDesiredStateRepository.IdempotencyConflictException.class); assertThat(conversation.executedStatements).hasSize(executedBeforeConflict); } @@ -745,41 +698,38 @@ void generationReceiptDerivesCanonicalRsaFingerprintAndRemainsNonPromoting() thr Conversation conversation = new Conversation(); GenerationRequest operation = inWritableTransaction(conversation::ensureRequest); GenerationRequest pending = - inWritableTransaction( - () -> - conversation.repository.recordSecretObservation( - BINDING, - TRUST, - operation.operationId(), - operation.operationDigest(), - SECRET_UID.toString(), - "12")); + inWritableTransaction(() -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + operation.operationId(), + operation.operationDigest(), + SECRET_UID.toString(), + "12")); PublicJwk jwk = publicJwk(operation.targetKid()); GenerationResult result = - inWritableTransaction( - () -> - conversation.repository.recordGenerationResult( - BINDING, - TRUST, - operation.operationId(), - pending.generationRequestDigest(), - SECRET_UID.toString(), - "12", - "13", - jwk.json())); + inWritableTransaction(() -> + conversation.repository.recordGenerationResult( + BINDING, + TRUST, + operation.operationId(), + pending.generationRequestDigest(), + SECRET_UID.toString(), + "12", + "13", + jwk.json())); GenerationResult replay = - inWritableTransaction( - () -> - conversation.repository.recordGenerationResult( - BINDING, - TRUST, - operation.operationId(), - pending.generationRequestDigest(), - SECRET_UID.toString(), - "12", - "13", - jwk.json())); + inWritableTransaction(() -> + conversation.repository.recordGenerationResult( + BINDING, + TRUST, + operation.operationId(), + pending.generationRequestDigest(), + SECRET_UID.toString(), + "12", + "13", + jwk.json())); assertThat(result).isEqualTo(replay); assertThat(result.publicKeyFingerprint()).isEqualTo(jwk.fingerprint()); @@ -802,12 +752,10 @@ void generationReceiptDerivesCanonicalRsaFingerprintAndRemainsNonPromoting() thr "1".repeat(64), "2".repeat(64), "{\"keys\":[" + result.publicJwkJson() + "]}"); - assertThatThrownBy( - () -> - inWritableTransaction( - () -> - conversation.repository.prepareCurrentGeneration( - BINDING, TRUST, callerSuppliedPreparation, null))) + assertThatThrownBy(() -> + inWritableTransaction(() -> + conversation.repository.prepareCurrentGeneration( + BINDING, TRUST, callerSuppliedPreparation, null))) .isInstanceOf(NullPointerException.class) .hasMessageContaining("Account-verified readiness proof is required"); assertThat(conversation.executedStatements).hasSize(executedBeforePromotionAttempt); @@ -820,10 +768,9 @@ void absentOperationAndWrongCurrentOperationFailBeforeAnyMutation() { new AccountJwtSignerDesiredStateRepository(emptyDsl); Record emptyState = stateRow(BINDING, 1, null, null, null, null, null); when(emptyDsl.fetchOne(anyString(), any(Object[].class))).thenReturn(emptyState); - assertThatThrownBy( - () -> - inWritableTransaction( - () -> emptyRepository.readCurrentGenerationRequest(BINDING, TRUST))) + assertThatThrownBy(() -> + inWritableTransaction( + () -> emptyRepository.readCurrentGenerationRequest(BINDING, TRUST))) .isInstanceOf( AccountJwtSignerDesiredStateRepository.MissingGenerationOperationException.class); verify(emptyDsl, never()).execute(anyString(), any(Object[].class)); @@ -832,17 +779,15 @@ void absentOperationAndWrongCurrentOperationFailBeforeAnyMutation() { GenerationRequest operation = inWritableTransaction(conversation::ensureRequest); UUID wrongOperation = UUID.fromString("55555555-5555-4555-8555-555555555555"); int executedBeforeStaleCall = conversation.executedStatements.size(); - assertThatThrownBy( - () -> - inWritableTransaction( - () -> - conversation.repository.recordSecretObservation( - BINDING, - TRUST, - wrongOperation, - operation.operationDigest(), - SECRET_UID.toString(), - "12"))) + assertThatThrownBy(() -> + inWritableTransaction(() -> + conversation.repository.recordSecretObservation( + BINDING, + TRUST, + wrongOperation, + operation.operationDigest(), + SECRET_UID.toString(), + "12"))) .isInstanceOf( AccountJwtSignerDesiredStateRepository.StaleGenerationOperationException.class); assertThat(conversation.executedStatements).hasSize(executedBeforeStaleCall); @@ -854,19 +799,17 @@ void privateOrMalformedPublicJwkIsRejectedBeforeStorageAccess() { AccountJwtSignerDesiredStateRepository repository = new AccountJwtSignerDesiredStateRepository(dsl); - assertThatThrownBy( - () -> - inWritableTransaction( - () -> - repository.recordGenerationResult( - BINDING, - TRUST, - UUID.fromString("22222222-2222-4222-8222-222222222222"), - "a".repeat(64), - SECRET_UID.toString(), - "12", - "13", - "{\"d\":\"private\"}"))) + assertThatThrownBy(() -> + inWritableTransaction(() -> + repository.recordGenerationResult( + BINDING, + TRUST, + UUID.fromString("22222222-2222-4222-8222-222222222222"), + "a".repeat(64), + SECRET_UID.toString(), + "12", + "13", + "{\"d\":\"private\"}"))) .isInstanceOf(IllegalArgumentException.class); verify(dsl, never()).fetchOne(anyString(), any(Object[].class)); verify(dsl, never()).execute(anyString(), any(Object[].class)); @@ -1208,96 +1151,92 @@ private Conversation() { private Conversation(long historicalGenerationHighWater) { this.historicalGenerationHighWater = historicalGenerationHighWater; when(dsl.execute(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0); - Object[] arguments = invocation.getArguments(); - Object[] parameters = - arguments.length == 2 && arguments[1] instanceof Object[] bindings - ? bindings - : java.util.Arrays.copyOfRange(arguments, 1, arguments.length); - executedStatements.add(sql); - if (sql.contains("UPDATE account_jwt_signer_promotion_operations")) { - if (sql.contains( - "private_promotion_dispatched_at = readiness_clock.checked_at")) { - if (readinessExpiresAtDispatchCas) { - return 0; - } - promotionDispatchCasCount++; - preparedPromotionValues.put("private_promotion_dispatched", true); - } else if (sql.contains("SET status = 'COMMITTED'")) { - preparedPromotionValues.put("status", "COMMITTED"); - } + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0); + Object[] arguments = invocation.getArguments(); + Object[] parameters = + arguments.length == 2 && arguments[1] instanceof Object[] bindings + ? bindings + : java.util.Arrays.copyOfRange(arguments, 1, arguments.length); + executedStatements.add(sql); + if (sql.contains("UPDATE account_jwt_signer_promotion_operations")) { + if (sql.contains("private_promotion_dispatched_at = readiness_clock.checked_at")) { + if (readinessExpiresAtDispatchCas) { + return 0; } - if (sql.contains("account_jwt_signer_generation_operations")) { - operationInsert = parameters.clone(); - } else if (sql.contains("account_jwt_signer_secret_observations")) { - observationInsert = parameters.clone(); - } else if (sql.contains("account_jwt_signer_generation_results")) { - resultInsert = parameters.clone(); - } - return 1; - }); + promotionDispatchCasCount++; + preparedPromotionValues.put("private_promotion_dispatched", true); + } else if (sql.contains("SET status = 'COMMITTED'")) { + preparedPromotionValues.put("status", "COMMITTED"); + } + } + if (sql.contains("account_jwt_signer_generation_operations")) { + operationInsert = parameters.clone(); + } else if (sql.contains("account_jwt_signer_secret_observations")) { + observationInsert = parameters.clone(); + } else if (sql.contains("account_jwt_signer_generation_results")) { + resultInsert = parameters.clone(); + } + return 1; + }); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0); - if (sql.contains("account_jwt_signer_promotion_operations")) { - return preparedPromotionValues == null ? null : record(preparedPromotionValues); - } - if (sql.contains("account_jwt_readiness_probe_plans")) { - return preparedPromotionValues == null ? null : readinessPlanRow(); - } - if (sql.contains("account_jwt_readiness_probe_entries")) { - return record(Map.of("total", 1L, "verified", 1L)); - } - if (sql.contains("account_jwt_signer_desired_states")) { - stateReadCount++; - if (preparedPromotionId != null) { - if ("COMMITTED".equals(preparedPromotionValues.get("status"))) { - long activeGeneration = - ((Number) preparedPromotionValues.get("target_generation")).longValue(); - return stateRow( - BINDING, - 4, - activeGeneration, - (String) preparedPromotionValues.get("target_kid"), - activeGeneration, - (String) preparedPromotionValues.get("target_kid"), - null, - null); - } - if (preparedStateChangedForCommit) { - return stateRow( - BINDING, 4, null, null, null, null, null, preparedPromotionId); - } - return stateRow(BINDING, 3, null, null, null, null, null, preparedPromotionId); - } - return stateReadCount == 1 - ? stateRow(BINDING, 1, null, null, null, null, null) - : stateRow( - BINDING, - 2, - null, - null, - null, - null, - operationInsert == null ? null : (UUID) operationInsert[0]); - } - if (sql.contains("COALESCE(MAX(target_generation), 0)")) { - return scalarLongRecord(historicalGenerationHighWater); - } - if (sql.contains("account_jwt_signer_generation_operations")) { - return operationInsert == null ? null : generationOperationRow(operationInsert); - } - if (sql.contains("account_jwt_signer_generation_results")) { - return resultInsert == null ? null : generationResultRow(resultInsert); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("account_jwt_signer_promotion_operations")) { + return preparedPromotionValues == null ? null : record(preparedPromotionValues); + } + if (sql.contains("account_jwt_readiness_probe_plans")) { + return preparedPromotionValues == null ? null : readinessPlanRow(); + } + if (sql.contains("account_jwt_readiness_probe_entries")) { + return record(Map.of("total", 1L, "verified", 1L)); + } + if (sql.contains("account_jwt_signer_desired_states")) { + stateReadCount++; + if (preparedPromotionId != null) { + if ("COMMITTED".equals(preparedPromotionValues.get("status"))) { + long activeGeneration = + ((Number) preparedPromotionValues.get("target_generation")).longValue(); + return stateRow( + BINDING, + 4, + activeGeneration, + (String) preparedPromotionValues.get("target_kid"), + activeGeneration, + (String) preparedPromotionValues.get("target_kid"), + null, + null); } - if (sql.contains("account_jwt_signer_secret_observations")) { - return observationInsert == null ? null : secretObservationRow(observationInsert); + if (preparedStateChangedForCommit) { + return stateRow(BINDING, 4, null, null, null, null, null, preparedPromotionId); } - return null; - }); + return stateRow(BINDING, 3, null, null, null, null, null, preparedPromotionId); + } + return stateReadCount == 1 + ? stateRow(BINDING, 1, null, null, null, null, null) + : stateRow( + BINDING, + 2, + null, + null, + null, + null, + operationInsert == null ? null : (UUID) operationInsert[0]); + } + if (sql.contains("COALESCE(MAX(target_generation), 0)")) { + return scalarLongRecord(historicalGenerationHighWater); + } + if (sql.contains("account_jwt_signer_generation_operations")) { + return operationInsert == null ? null : generationOperationRow(operationInsert); + } + if (sql.contains("account_jwt_signer_generation_results")) { + return resultInsert == null ? null : generationResultRow(resultInsert); + } + if (sql.contains("account_jwt_signer_secret_observations")) { + return observationInsert == null ? null : secretObservationRow(observationInsert); + } + return null; + }); } private GenerationRequest ensureRequest() { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepositoryTest.java index 2f871c591b..774f3203f8 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountJwtValidatorInventoryRepositoryTest.java @@ -136,21 +136,20 @@ void rejectsSnapshotDigestMismatchAndReturnsDefensiveByteCopies() { returned[2] = 'x'; assertThat(snapshot.canonicalBytes()).isEqualTo(bytes); - assertThatThrownBy( - () -> - new AccountJwtValidatorInventoryRepository.StoredSnapshot( - "d".repeat(64), - "staging", - "cluster-a", - TRUST.expectedClusterIncarnationUid(), - "firemud", - TRUST.expectedNamespaceUid(), - "api-r1", - "b".repeat(64), - "inventory-r1", - "c".repeat(64), - Instant.parse("2026-10-05T00:00:00Z"), - bytes)) + assertThatThrownBy(() -> + new AccountJwtValidatorInventoryRepository.StoredSnapshot( + "d".repeat(64), + "staging", + "cluster-a", + TRUST.expectedClusterIncarnationUid(), + "firemud", + TRUST.expectedNamespaceUid(), + "api-r1", + "b".repeat(64), + "inventory-r1", + "c".repeat(64), + Instant.parse("2026-10-05T00:00:00Z"), + bytes)) .isInstanceOf( AccountJwtValidatorInventoryRepository.InventorySnapshotUnavailableException.class) .hasNoCause(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryTest.java index 33c03fd2ca..9b44f47e65 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountMembershipPairAuthorityRepositoryTest.java @@ -43,10 +43,9 @@ void freshProvenanceCannotCarryInventedNumericTenantIdentity() { null, TenantProvenanceKind.FRESH_GAME_DESIGN, OPERATION_ID, DIGEST); org.assertj.core.api.Assertions.assertThat(fresh.legacyTenantId()).isNull(); - assertThatThrownBy( - () -> - new VerifiedTenantProvenance( - 87L, TenantProvenanceKind.FRESH_GAME_DESIGN, OPERATION_ID, DIGEST)) + assertThatThrownBy(() -> + new VerifiedTenantProvenance( + 87L, TenantProvenanceKind.FRESH_GAME_DESIGN, OPERATION_ID, DIGEST)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("must not carry a legacy tenant ID"); } @@ -61,10 +60,9 @@ void pairAuthorityRepresentsSequenceZeroOnlyAsNonmembershipEvidence() { new PairAuthority(ACCOUNT_UUID, TENANT_UUID, fresh, false, 1L, 1L, 0L, null, null, false); assertThat(baseline.membershipExists()).isFalse(); assertThat(baseline.eventSequence()).isZero(); - assertThatThrownBy( - () -> - new PairAuthority( - ACCOUNT_UUID, TENANT_UUID, fresh, true, 1L, 1L, 0L, null, null, false)) + assertThatThrownBy(() -> + new PairAuthority( + ACCOUNT_UUID, TENANT_UUID, fresh, true, 1L, 1L, 0L, null, null, false)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("cannot claim membership or event evidence"); } @@ -241,11 +239,9 @@ void firstJoinPairCompareAndAdvanceRejectsStaleVersionBeforeWriting() { .fetchOne(anyString(), any(Object[].class)); TransactionSynchronizationManager.setActualTransactionActive(true); - assertThatThrownBy( - () -> - repository.commitTransition( - staleExpected, - new PairTransition(true, 1L, EVENT_ID_TEXT, EVENT_DIGEST, false))) + assertThatThrownBy(() -> + repository.commitTransition( + staleExpected, new PairTransition(true, 1L, EVENT_ID_TEXT, EVENT_DIGEST, false))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Stale or contradictory"); verify(dsl, org.mockito.Mockito.never()).execute(anyString(), any(Object[].class)); @@ -261,10 +257,9 @@ void firstJoinPairCompareAndAdvanceRejectsLaterSequenceBeforeWriting() { ACCOUNT_UUID, TENANT_UUID, freshProvenance(), false, 1L, 1L, 0L, null, null, false); TransactionSynchronizationManager.setActualTransactionActive(true); - assertThatThrownBy( - () -> - repository.commitTransition( - baseline, new PairTransition(true, 2L, EVENT_ID_TEXT, EVENT_DIGEST, false))) + assertThatThrownBy(() -> + repository.commitTransition( + baseline, new PairTransition(true, 2L, EVENT_ID_TEXT, EVENT_DIGEST, false))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("first positive JOIN transition"); verifyNoInteractions(dsl); @@ -279,10 +274,9 @@ void restoreCannotReuseAbsenceOrInventAnAuthorityInvalidation() { PairAuthority absence = new PairAuthority( ACCOUNT_UUID, TENANT_UUID, freshProvenance(), false, 1L, 1L, 0L, null, null, false); - assertThatThrownBy( - () -> - repository.commitRestore( - absence, new PairTransition(true, 1L, EVENT_ID_TEXT, EVENT_DIGEST, false))) + assertThatThrownBy(() -> + repository.commitRestore( + absence, new PairTransition(true, 1L, EVENT_ID_TEXT, EVENT_DIGEST, false))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("exact current positive pair"); PairAuthority positive = @@ -297,16 +291,14 @@ absence, new PairTransition(true, 1L, EVENT_ID_TEXT, EVENT_DIGEST, false))) "inactive-event", EVENT_DIGEST, true); - assertThatThrownBy( - () -> - repository.commitRestore( - positive, new PairTransition(true, 3L, EVENT_ID_TEXT, EVENT_DIGEST, true))) + assertThatThrownBy(() -> + repository.commitRestore( + positive, new PairTransition(true, 3L, EVENT_ID_TEXT, EVENT_DIGEST, true))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("exact current positive pair"); - assertThatThrownBy( - () -> - repository.commitRestore( - positive, new PairTransition(true, 4L, EVENT_ID_TEXT, EVENT_DIGEST, false))) + assertThatThrownBy(() -> + repository.commitRestore( + positive, new PairTransition(true, 4L, EVENT_ID_TEXT, EVENT_DIGEST, false))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("exact current positive pair"); verifyNoInteractions(dsl); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerTest.java index 516ee22eaf..cf39e4dd07 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerTest.java @@ -50,21 +50,18 @@ void bothIssueApisRefuseAmbientTransactionsBeforeCallerVerificationOrSourceReads TransactionSynchronizationManager.setActualTransactionActive(true); Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .run( - () -> { - assertThatThrownBy(() -> owner.issue("unlogged-test-token", null)) - .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); - assertThatThrownBy(() -> owner.issue(request)) - .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); - }); + .run(() -> { + assertThatThrownBy(() -> owner.issue("unlogged-test-token", null)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + assertThatThrownBy(() -> owner.issue(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + }); verifyNoInteractions(dataSource, callerVerifier, signer, tokenRegistry, responseCryptography); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java index d3425b1e45..5aa3968d2d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java @@ -45,26 +45,25 @@ void receiptEvidenceRejectsMalformedOrNonAccountBindingsBeforeStorageAccess() { .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> receipt("0".repeat(64), "0".repeat(64), "bad-verifier")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountPasswordResetOperationRepository.PasswordResetReceipt( - 9L, - ACCOUNT_UUID, - "0".repeat(64), - "PASSWORD_RESET", - "wrong-request-id", - 1, - "1".repeat(64), - LocalDateTime.of(2030, 1, 2, 3, 4, 5, 123456789), - "2".repeat(64), - streamKey(), - 1L, - "account-password-reset-event-v1:" + "0".repeat(64), - "sha256:" + "3".repeat(64), - 2L, - 2L, - 3L, - 3L)) + assertThatThrownBy(() -> + new AccountPasswordResetOperationRepository.PasswordResetReceipt( + 9L, + ACCOUNT_UUID, + "0".repeat(64), + "PASSWORD_RESET", + "wrong-request-id", + 1, + "1".repeat(64), + LocalDateTime.of(2030, 1, 2, 3, 4, 5, 123456789), + "2".repeat(64), + streamKey(), + 1L, + "account-password-reset-event-v1:" + "0".repeat(64), + "sha256:" + "3".repeat(64), + 2L, + 2L, + 3L, + 3L)) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(dsl); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPaymentInstrumentRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPaymentInstrumentRepositoryTest.java index f63d64ee74..bbcd76b146 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPaymentInstrumentRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPaymentInstrumentRepositoryTest.java @@ -46,17 +46,10 @@ private void assertTransactionRefusal() { assertThatThrownBy(() -> instruments.findByOwnerForUpdate(ACCOUNT, INSTRUMENT)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("active writable Account transaction"); - assertThatThrownBy( - () -> - instruments.recordAvailability( - new AvailabilityObservation( - UUID.randomUUID(), - INSTRUMENT, - ACCOUNT, - 1, - State.UNAVAILABLE, - DISPLAY, - DIGEST))) + assertThatThrownBy(() -> + instruments.recordAvailability( + new AvailabilityObservation( + UUID.randomUUID(), INSTRUMENT, ACCOUNT, 1, State.UNAVAILABLE, DISPLAY, DIGEST))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("active writable Account transaction"); } @@ -67,18 +60,17 @@ void attachmentRequiresProviderReferencesOpaqueIdentityAndEvidenceDigest() { .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> attachment("pm_safe", "raw-provider-response")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new Attachment( - UUID.randomUUID(), - new UUID(0L, 0L), - ACCOUNT, - UUID.randomUUID(), - "cus_safe", - "pm_safe", - State.ATTACHABLE, - DISPLAY, - DIGEST)) + assertThatThrownBy(() -> + new Attachment( + UUID.randomUUID(), + new UUID(0L, 0L), + ACCOUNT, + UUID.randomUUID(), + "cus_safe", + "pm_safe", + State.ATTACHABLE, + DISPLAY, + DIGEST)) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(dsl); } @@ -95,16 +87,15 @@ void onlyFixedDisplayFieldsAndAdvanceableExpectedVersionsAreAccepted() { assertThatThrownBy(() -> new DisplayMetadata("arbitrary provider payload", "4242", 12, 2030)) .isInstanceOf(IllegalArgumentException.class); for (long version : new long[] {0, -1, Long.MAX_VALUE}) { - assertThatThrownBy( - () -> - new AvailabilityObservation( - UUID.randomUUID(), - INSTRUMENT, - ACCOUNT, - version, - State.UNAVAILABLE, - DISPLAY, - DIGEST)) + assertThatThrownBy(() -> + new AvailabilityObservation( + UUID.randomUUID(), + INSTRUMENT, + ACCOUNT, + version, + State.UNAVAILABLE, + DISPLAY, + DIGEST)) .isInstanceOf(IllegalArgumentException.class); } assertThat(State.values()).containsExactly(State.ATTACHABLE, State.UNAVAILABLE); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java index fa6f550466..97eee7be67 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java @@ -38,22 +38,18 @@ void nonrestrictedProjectionAllowsPendingDeletionButRestrictedMismatchFailsClose when(account.get("lifecycle_state", String.class)).thenReturn("deactivated_pending_delete"); UUID accountUuid = UUID.fromString("68d408e1-ec07-4e0f-a59b-9bfc521365a0"); - assertThatCode( - () -> - requireLifecycleProjection( - dsl, - projection( - accountUuid, - Category.ACCOUNT_SECURITY_LOCK, - RestrictionState.NONRESTRICTED))) + assertThatCode(() -> + requireLifecycleProjection( + dsl, + projection( + accountUuid, Category.ACCOUNT_SECURITY_LOCK, RestrictionState.NONRESTRICTED))) .doesNotThrowAnyException(); - assertThatThrownBy( - () -> - requireLifecycleProjection( - dsl, - projection( - accountUuid, Category.ACCOUNT_SECURITY_LOCK, RestrictionState.RESTRICTED))) + assertThatThrownBy(() -> + requireLifecycleProjection( + dsl, + projection( + accountUuid, Category.ACCOUNT_SECURITY_LOCK, RestrictionState.RESTRICTED))) .isInstanceOf( AccountPlatformRestrictionOperationRepository.RestrictionProjectionUnavailableException .class); @@ -67,14 +63,11 @@ void missingAccountStillFailsClosedForRestrictionReadback() { "SELECT lifecycle_state FROM accounts WHERE account_uuid = ? FOR SHARE", accountUuid)) .thenReturn(null); - assertThatThrownBy( - () -> - requireLifecycleProjection( - dsl, - projection( - accountUuid, - Category.ACCOUNT_SECURITY_LOCK, - RestrictionState.NONRESTRICTED))) + assertThatThrownBy(() -> + requireLifecycleProjection( + dsl, + projection( + accountUuid, Category.ACCOUNT_SECURITY_LOCK, RestrictionState.NONRESTRICTED))) .isInstanceOf( AccountPlatformRestrictionOperationRepository.RestrictionProjectionUnavailableException .class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRealmAccessGrantRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRealmAccessGrantRepositoryTest.java index 313d83c2a8..0223970341 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRealmAccessGrantRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountRealmAccessGrantRepositoryTest.java @@ -54,9 +54,8 @@ void staleGenerationMakesTheUpdateCompareAndSwapMiss() { DSLContext dsl = DSL.using(new MockConnection(provider), SQLDialect.POSTGRES); UUID observedGeneration = UUID.fromString("f8a89f86-3319-4f1d-9a59-58ec18fb5f54"); - assertThatThrownBy( - () -> - new AccountRealmAccessGrantRepository(dsl).save(existingGrant(observedGeneration))) + assertThatThrownBy(() -> + new AccountRealmAccessGrantRepository(dsl).save(existingGrant(observedGeneration))) .isInstanceOf(IllegalStateException.class) .hasMessage("Failed to update account_realm_access_grant id=41"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java index 55cd33a991..88b6eb4495 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryTest.java @@ -66,18 +66,16 @@ void timestampWritesAndExpiryPredicateUseExplicitPostgresTypes() { assertThat(created.issuance().issuedAt()).isEqualTo(candidate.issuedAt()); assertThat(redeemed).isNotNull(); assertThat(store.queries) - .anySatisfy( - sql -> - assertThat(sql) - .contains( - "cast(? as timestamptz), cast(? as timestamptz), " - + "cast(? as timestamptz), 'issued'")) - .anySatisfy( - sql -> - assertThat(sql) - .contains( - "redeemed_at = cast(? as timestamptz)", - "reference_expires_at > cast(? as timestamptz)")); + .anySatisfy(sql -> + assertThat(sql) + .contains( + "cast(? as timestamptz), cast(? as timestamptz), " + + "cast(? as timestamptz), 'issued'")) + .anySatisfy(sql -> + assertThat(sql) + .contains( + "redeemed_at = cast(? as timestamptz)", + "reference_expires_at > cast(? as timestamptz)")); } @Test @@ -181,12 +179,9 @@ void preExpiryAndUnprovedMissingEnvelopeFailClosed() { IssuanceCandidate future = candidate(tuple()); inTransaction(() -> earlyRepository.createOrReadExact(future)); - assertThatThrownBy( - () -> - inTransaction( - () -> - earlyRepository.eraseExpiredResponseEnvelope( - future.controlPlaneRequestId()))) + assertThatThrownBy(() -> + inTransaction( + () -> earlyRepository.eraseExpiredResponseEnvelope(future.controlPlaneRequestId()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("evidence unavailable"); assertThat(earlyStore.row.envelope).containsExactly(future.encryptedResponseEnvelope()); @@ -198,12 +193,9 @@ void preExpiryAndUnprovedMissingEnvelopeFailClosed() { IssuanceCandidate expired = expiredCandidate(tuple()); inTransaction(() -> unprovedRepository.createOrReadExact(expired)); unprovedStore.row.envelope = null; - assertThatThrownBy( - () -> - inTransaction( - () -> - unprovedRepository.findByControlPlaneRequestId( - expired.controlPlaneRequestId()))) + assertThatThrownBy(() -> + inTransaction(() -> + unprovedRepository.findByControlPlaneRequestId(expired.controlPlaneRequestId()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("evidence unavailable"); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepositoryTest.java index ce8841ded4..6dc5d2949a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepositoryTest.java @@ -76,23 +76,21 @@ void closedCodecReadbackBindsCompleteTupleProjectionAndRejectsSubmicrosecondExpi byte[] roundedTimestampCandidate = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(subMicrosecond) .toByteArray(); - assertThatThrownBy( - () -> - AccountStartSessionWorldOriginalAttemptEvidenceRepository.validateResponse( - expected, roundedTimestampCandidate, fixture.parent())) + assertThatThrownBy(() -> + AccountStartSessionWorldOriginalAttemptEvidenceRepository.validateResponse( + expected, roundedTimestampCandidate, fixture.parent())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("conflicts"); byte[] changedProjection = "not the exact Account projection".getBytes(StandardCharsets.UTF_8); Result wrongProjection = new Result(expected, exact.originalLeaseExpiresAt(), changedProjection); - assertThatThrownBy( - () -> - AccountStartSessionWorldOriginalAttemptEvidenceRepository.validateResponse( - expected, - OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(wrongProjection) - .toByteArray(), - fixture.parent())) + assertThatThrownBy(() -> + AccountStartSessionWorldOriginalAttemptEvidenceRepository.validateResponse( + expected, + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(wrongProjection) + .toByteArray(), + fixture.parent())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("conflicts"); } @@ -103,10 +101,9 @@ void freshReadCorrelationIsNotDurableIdentityButEveryOwnerBindingFieldIs() { Request first = request(fixture, UUID.fromString("6a3922eb-96f5-4cc5-8e43-85c1bb3f49c0")); Request retry = request(fixture, UUID.fromString("21fa4d95-98f0-4c19-a5b6-864bd0467f94")); - assertThatCode( - () -> - AccountStartSessionWorldOriginalAttemptEvidenceRepository - .requireSameSemanticRequest(first, retry)) + assertThatCode(() -> + AccountStartSessionWorldOriginalAttemptEvidenceRepository.requireSameSemanticRequest( + first, retry)) .doesNotThrowAnyException(); assertMismatch( @@ -130,15 +127,14 @@ void freshReadCorrelationIsNotDurableIdentityButEveryOwnerBindingFieldIs() { OWNER_ATTEMPT_ID, UUID.fromString("1f2d6f4e-1202-4bdb-bcd4-f3c14e4cc764"), OWNER_FENCE); - assertThatThrownBy( - () -> - new Request( - UUID.randomUUID(), - "other-runtime", - fixture.parent().originalPostAuthorizationTuple(), - OWNER_ATTEMPT_ID, - OWNER_MUTATION_ID, - OWNER_FENCE)) + assertThatThrownBy(() -> + new Request( + UUID.randomUUID(), + "other-runtime", + fixture.parent().originalPostAuthorizationTuple(), + OWNER_ATTEMPT_ID, + OWNER_MUTATION_ID, + OWNER_FENCE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("target the exact requested namespace"); @@ -150,10 +146,9 @@ void freshReadCorrelationIsNotDurableIdentityButEveryOwnerBindingFieldIs() { OWNER_ATTEMPT_ID, OWNER_MUTATION_ID, OWNER_FENCE); - assertThatThrownBy( - () -> - AccountStartSessionWorldOriginalAttemptEvidenceRepository - .requireSameSemanticRequest(first, changedTuple)) + assertThatThrownBy(() -> + AccountStartSessionWorldOriginalAttemptEvidenceRepository.requireSameSemanticRequest( + first, changedTuple)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("conflicts"); } @@ -183,15 +178,14 @@ void storedResponseIsDefensiveAndItsDigestCoversTheCompleteResponseBytes() { assertThat(stored.toString()) .contains("projection=") .contains("responseBytes="); - assertThatThrownBy( - () -> - new StoredEvidence( - PARTICIPATION_ID, - OWNER_MUTATION_ID, - result.originalLeaseExpiresAt(), - new byte[] {1}, - digest, - result)) + assertThatThrownBy(() -> + new StoredEvidence( + PARTICIPATION_ID, + OWNER_MUTATION_ID, + result.originalLeaseExpiresAt(), + new byte[] {1}, + digest, + result)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("digest differs"); } @@ -199,10 +193,9 @@ void storedResponseIsDefensiveAndItsDigestCoversTheCompleteResponseBytes() { private static void assertMismatch( Request expected, String namespace, byte[] tuple, UUID attempt, UUID mutation, long fence) { Request changed = new Request(UUID.randomUUID(), namespace, tuple, attempt, mutation, fence); - assertThatThrownBy( - () -> - AccountStartSessionWorldOriginalAttemptEvidenceRepository - .requireSameSemanticRequest(expected, changed)) + assertThatThrownBy(() -> + AccountStartSessionWorldOriginalAttemptEvidenceRepository.requireSameSemanticRequest( + expected, changed)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("conflicts"); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepositoryTest.java index 816e265401..d1d3b3e020 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepositoryTest.java @@ -198,10 +198,9 @@ void typedReadbackRetainsTheExactCandidateAndRejectsChangedImmutableFields() { fixture.candidate().gameSessionOwnerFence(), "{\"changed\":true}", digest("{\"changed\":true}")); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationRepository.requireSameCandidate( - changedPreparation, stored)) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationRepository.requireSameCandidate( + changedPreparation, stored)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("conflicts"); } @@ -209,10 +208,9 @@ void typedReadbackRetainsTheExactCandidateAndRejectsChangedImmutableFields() { @Test void participationReadbackRejectsUnknownDatabaseColumns() { Fixture fixture = fixture(); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationRepository.decodeParticipation( - participationRow(fixture.candidate(), true), List.of(fixture.source()))) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationRepository.decodeParticipation( + participationRow(fixture.candidate(), true), List.of(fixture.source()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("unavailable"); } @@ -230,15 +228,13 @@ void sourceReadbackRejectsMissingAndSubstitutedChildren() { "1", bytes("substituted evidence")); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationRepository.requireExactSources( - List.of(fixture.source()), List.of())) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationRepository.requireExactSources( + List.of(fixture.source()), List.of())) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationRepository.requireExactSources( - List.of(fixture.source()), List.of(substituted))) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationRepository.requireExactSources( + List.of(fixture.source()), List.of(substituted))) .isInstanceOf(IllegalStateException.class); AccountStartSessionWorldParticipationRepository.requireExactSources( List.of(fixture.source()), List.of(fixture.source())); @@ -257,10 +253,9 @@ void terminalMustRepeatEveryStoredIdentityAndPreparationField() { WorldStartSessionExecutionTerminal changedAttempt = terminal(candidate, 41L, UUID.fromString("274c7a54-2f2a-409f-9eac-7b8a7733e590"), 8L); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationRepository.requireTerminalMatches( - stored, changedAttempt)) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationRepository.requireTerminalMatches( + stored, changedAttempt)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("conflicts"); } @@ -427,10 +422,9 @@ void findHistoricalForOriginalTupleRejectsMissingOrChangedSourceChildren() throw mockedRepository(fixture, reads, writes, null, false, children); beginWritableTransaction(); - assertThatThrownBy( - () -> - repository.findHistoricalForOriginalTuple( - fixture.candidate().originalPostAuthorizationTuple())) + assertThatThrownBy(() -> + repository.findHistoricalForOriginalTuple( + fixture.candidate().originalPostAuthorizationTuple())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("evidence unavailable"); assertThat(reads) @@ -464,9 +458,8 @@ void settleExactInsertsAndReadsBackTheSameTypedTerminalAfterHistoricalIdentityCh .anyMatch(sql -> sql.contains("account_start_session_authority_captures")) .anyMatch(sql -> sql.contains("account_start_session_world_participations")) .anyMatch(sql -> sql.contains("account_start_session_world_participation_sources")) - .anyMatch( - sql -> - sql.startsWith("INSERT INTO account_start_session_world_participation_settlements")) + .anyMatch(sql -> + sql.startsWith("INSERT INTO account_start_session_world_participation_settlements")) .anyMatch(sql -> sql.contains("account_start_session_world_participation_settlements")); assertThat(writes.get()).isNotNull().hasSize(5); assertThat(writes.get()[0]).isEqualTo(PARTICIPATION_ID); @@ -606,40 +599,36 @@ private static AccountStartSessionWorldParticipationRepository mockedRepository( .when(dsl) .connection(any(ConnectionRunnable.class)); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0); - sqlCalls.add(sql); - if (sql.contains("account_start_session_authority_captures")) { - return captureRow(fixture.candidate()); - } - if (sql.contains("account_start_session_world_participations")) { - return missingParticipation ? null : participationRow(fixture.candidate()); - } - if (sql.contains("account_start_session_world_participation_settlements")) { - return settlement == null ? null : settlementRow(settlement); - } - throw new AssertionError("Unexpected participation repository query: " + sql); - }); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0); + sqlCalls.add(sql); + if (sql.contains("account_start_session_authority_captures")) { + return captureRow(fixture.candidate()); + } + if (sql.contains("account_start_session_world_participations")) { + return missingParticipation ? null : participationRow(fixture.candidate()); + } + if (sql.contains("account_start_session_world_participation_settlements")) { + return settlement == null ? null : settlementRow(settlement); + } + throw new AssertionError("Unexpected participation repository query: " + sql); + }); when(dsl.fetch(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0); - sqlCalls.add(sql); - if (!sql.contains("account_start_session_world_participation_sources")) { - throw new AssertionError( - "Unexpected participation repository result query: " + sql); - } - return sourceRows(PARTICIPATION_ID, sourceChildren); - }); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0); + sqlCalls.add(sql); + if (!sql.contains("account_start_session_world_participation_sources")) { + throw new AssertionError("Unexpected participation repository result query: " + sql); + } + return sourceRows(PARTICIPATION_ID, sourceChildren); + }); when(dsl.execute(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0); - sqlCalls.add(sql); - writes.set((Object[]) invocation.getRawArguments()[1]); - return 1; - }); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0); + sqlCalls.add(sql); + writes.set((Object[]) invocation.getRawArguments()[1]); + return 1; + }); return new AccountStartSessionWorldParticipationRepository(dsl); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionCreateDigestTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionCreateDigestTest.java index ea5dd01038..177fc333bb 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionCreateDigestTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionCreateDigestTest.java @@ -62,19 +62,14 @@ void malformedOrUnnormalizedPlanCannotCollideThroughLossyEncoding() { @Test void missingCanonicalIdentityCannotBecomeRequestEvidence() { for (UUID identity : new UUID[] {null, new UUID(0, 0)}) { - assertThatThrownBy( - () -> - AccountSubscriptionCreateDigest.encode( - identity, OWNER, "basic-hosting", INSTRUMENT)) + assertThatThrownBy(() -> + AccountSubscriptionCreateDigest.encode(identity, OWNER, "basic-hosting", INSTRUMENT)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountSubscriptionCreateDigest.encode( - TENANT, identity, "basic-hosting", INSTRUMENT)) + assertThatThrownBy(() -> + AccountSubscriptionCreateDigest.encode(TENANT, identity, "basic-hosting", INSTRUMENT)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountSubscriptionCreateDigest.encode(TENANT, OWNER, "basic-hosting", identity)) + assertThatThrownBy(() -> + AccountSubscriptionCreateDigest.encode(TENANT, OWNER, "basic-hosting", identity)) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java index 7d79e6cc87..622bcd73cf 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountSubscriptionIntentRepositoryTest.java @@ -79,17 +79,9 @@ void exactNormalizedSavedInstrumentInputsAndAdvanceableVersionsAreRequired() { .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> new ProducerEvidence(ACCOUNT, UUID.randomUUID(), "unverified claim")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountSubscriptionCreateRequest( - new UUID(0L, 0L), - TENANT, - OWNER, - "basic-hosting", - INSTRUMENT, - 1, - PRODUCER, - null)) + assertThatThrownBy(() -> + new AccountSubscriptionCreateRequest( + new UUID(0L, 0L), TENANT, OWNER, "basic-hosting", INSTRUMENT, 1, PRODUCER, null)) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(dsl); } @@ -364,32 +356,29 @@ private BindingFixture() { OWNER.generation())); Record reservationRow = projection(reservation); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0, String.class); - reads.add(sql); - if (sql.startsWith("SELECT * FROM subscription_create_operations")) - return creationRow; - if (sql.contains("FROM accounts")) return ownerRow; - if (sql.contains("FROM billing_customer")) return customerRow; - if (sql.contains("FROM payment_instrument")) return instrumentRow; - if (sql.contains("FROM account_tenant_billing_owners")) return ownerRow; - if (sql.contains("FROM subscription s")) return currentRow; - if (sql.contains("FROM subscription_instrument_reservations")) - return missingReservation ? null : reservationRow; - throw new AssertionError("Unexpected original binding SQL: " + sql); - }); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0, String.class); + reads.add(sql); + if (sql.startsWith("SELECT * FROM subscription_create_operations")) return creationRow; + if (sql.contains("FROM accounts")) return ownerRow; + if (sql.contains("FROM billing_customer")) return customerRow; + if (sql.contains("FROM payment_instrument")) return instrumentRow; + if (sql.contains("FROM account_tenant_billing_owners")) return ownerRow; + if (sql.contains("FROM subscription s")) return currentRow; + if (sql.contains("FROM subscription_instrument_reservations")) + return missingReservation ? null : reservationRow; + throw new AssertionError("Unexpected original binding SQL: " + sql); + }); } } @SuppressWarnings("unchecked") private static Record projection(Map fields) { Record row = mock(Record.class); - doAnswer( - invocation -> - invocation - .getArgument(1, Class.class) - .cast(fields.get(invocation.getArgument(0, String.class)))) + doAnswer(invocation -> + invocation + .getArgument(1, Class.class) + .cast(fields.get(invocation.getArgument(0, String.class)))) .when(row) .get(anyString(), any(Class.class)); when(row.get(anyString())) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java index 3e3f844c13..645ebbe0ec 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java @@ -368,29 +368,27 @@ private SelectionFixture(boolean hosting) throws Exception { if (hosting) doReturn(authority).when(repository).readHostingCheckpoint(TENANT_ID, REQUEST_ID); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0, String.class); - if (sql.contains("FROM account_tenant_authority_source_records")) return head; - if (sql.contains("JOIN account_tenant_entitlement_outbox_streams")) return billing; - if (sql.contains("SELECT receipt_payload FROM subscription_lifecycle_receipts")) - return receipt; - if (sql.contains( - "SELECT canonical_tenant_id FROM account_fresh_tenant_identity_associations")) - return null; - throw new AssertionError("Unexpected source-selection SQL: " + sql); - }); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0, String.class); + if (sql.contains("FROM account_tenant_authority_source_records")) return head; + if (sql.contains("JOIN account_tenant_entitlement_outbox_streams")) return billing; + if (sql.contains("SELECT receipt_payload FROM subscription_lifecycle_receipts")) + return receipt; + if (sql.contains( + "SELECT canonical_tenant_id FROM account_fresh_tenant_identity_associations")) + return null; + throw new AssertionError("Unexpected source-selection SQL: " + sql); + }); } } @SuppressWarnings("unchecked") private static Record projection(Map fields) { Record row = mock(Record.class); - doAnswer( - invocation -> - invocation - .getArgument(1, Class.class) - .cast(fields.get(invocation.getArgument(0, String.class)))) + doAnswer(invocation -> + invocation + .getArgument(1, Class.class) + .cast(fields.get(invocation.getArgument(0, String.class)))) .when(row) .get(anyString(), any(Class.class)); return row; diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityHostingEventTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityHostingEventTest.java index 532278ce15..97f7d4208a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityHostingEventTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityHostingEventTest.java @@ -81,38 +81,36 @@ void lifecycleEmitsExactBillingIdentityConsumedByCanonicalTenantCodec() throws E Record version = mock(Record.class); when(version.get("next_version", Long.class)).thenReturn(8L); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0); - if (sql.contains("FROM subscription_lifecycle_operations")) { - return operation; - } - if (sql.contains("FROM subscription_lifecycle_attempts")) { - return attempt; - } - if (sql.contains("FROM subscription WHERE")) { - return links; - } - if (sql.contains("FROM account_tenant_authority_source_records")) { - return sourceHead; - } - if (sql.startsWith("SELECT greatest(")) { - return version; - } - throw new AssertionError("Unexpected producer read: " + sql); - }); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM subscription_lifecycle_operations")) { + return operation; + } + if (sql.contains("FROM subscription_lifecycle_attempts")) { + return attempt; + } + if (sql.contains("FROM subscription WHERE")) { + return links; + } + if (sql.contains("FROM account_tenant_authority_source_records")) { + return sourceHead; + } + if (sql.startsWith("SELECT greatest(")) { + return version; + } + throw new AssertionError("Unexpected producer read: " + sql); + }); var receiptBindings = new AtomicReference(); var reachedReceipt = new IllegalStateException("Stop after both actual event producers"); when(dsl.execute(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0); - if (sql.startsWith("INSERT INTO subscription_lifecycle_receipts")) { - receiptBindings.set((Object[]) invocation.getRawArguments()[1]); - throw reachedReceipt; - } - return 1; - }); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0); + if (sql.startsWith("INSERT INTO subscription_lifecycle_receipts")) { + receiptBindings.set((Object[]) invocation.getRawArguments()[1]); + throw reachedReceipt; + } + return 1; + }); UUID subscriptionId = UUID.fromString("55555555-5555-4555-8555-555555555555"); var owner = new OwnerFence(ATTEMPT_ID, 1L, ATTEMPT_ID); @@ -212,34 +210,32 @@ void lifecycleEmitsExactBillingIdentityConsumedByCanonicalTenantCodec() throws E AccountTenantEntitlementOutboxRepository.class, (repository, context) -> when(repository.appendHosting(any(), any(), any())) - .thenAnswer( - invocation -> { - LongFunction - factory = invocation.getArgument(2); - var event = factory.apply(7L); - emittedBilling.set(event); - return event; - })); + .thenAnswer(invocation -> { + LongFunction + factory = invocation.getArgument(2); + var event = factory.apply(7L); + emittedBilling.set(event); + return event; + })); var outboxMocks = mockConstruction( AccountAuthorityOutboxRepository.class, (repository, context) -> when(repository.append(anyString(), anyString(), any())) - .thenAnswer( - invocation -> { - LongFunction factory = - invocation.getArgument(2); - var evidence = factory.apply(4L); - emittedAuthority.set( - TenantAuthorityEventV1Codec.verify(evidence.payload())); - return new AccountAuthorityOutboxRepository.Event( - invocation.getArgument(0), - invocation.getArgument(1), - 4L, - evidence.eventId(), - evidence.eventDigest(), - evidence.payload()); - }))) { + .thenAnswer(invocation -> { + LongFunction factory = + invocation.getArgument(2); + var evidence = factory.apply(4L); + emittedAuthority.set( + TenantAuthorityEventV1Codec.verify(evidence.payload())); + return new AccountAuthorityOutboxRepository.Event( + invocation.getArgument(0), + invocation.getArgument(1), + 4L, + evidence.eventId(), + evidence.eventDigest(), + evidence.payload()); + }))) { var repository = new AccountHostingSubscriptionLifecycleRepository( dsl, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionTest.java index b31b507638..a09820fae6 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthoritySourceSelectionTest.java @@ -212,16 +212,15 @@ private Fixture(boolean paid) { billing.put("payload", payload); DSLContext dsl = mock(DSLContext.class); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0); - if (sql.contains("account_tenant_authority_source_records")) return row(head); - if (sql.contains("account_tenant_entitlement_outbox_events")) return row(billing); - if (sql.contains("subscription_lifecycle_receipts")) { - return row(Map.of("receipt_payload", hostingReceipt)); - } - throw new AssertionError(sql); - }); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("account_tenant_authority_source_records")) return row(head); + if (sql.contains("account_tenant_entitlement_outbox_events")) return row(billing); + if (sql.contains("subscription_lifecycle_receipts")) { + return row(Map.of("receipt_payload", hostingReceipt)); + } + throw new AssertionError(sql); + }); AccountAuthorityGenerationRepository generations = mock(AccountAuthorityGenerationRepository.class); when(generations.read(AccountAuthorityGenerationRepository.AuthorityScope.tenant(TENANT))) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepositoryTest.java index aa265736f8..4f7a94aefb 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRepositoryTest.java @@ -167,17 +167,16 @@ void firstFreshJoinPreparesMembershipWithoutAdvancingPairAuthority() { Record membershipReadback = freshMembershipRecord(73L, 17L, 2L, 1L); AtomicInteger membershipReads = new AtomicInteger(); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0); - if (sql.contains("FROM accounts WHERE id = ? FOR UPDATE")) { - return lockedAccount; - } - if (sql.contains("FROM account_tenant_membership")) { - return membershipReads.getAndIncrement() == 0 ? null : membershipReadback; - } - return null; - }); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0); + if (sql.contains("FROM accounts WHERE id = ? FOR UPDATE")) { + return lockedAccount; + } + if (sql.contains("FROM account_tenant_membership")) { + return membershipReads.getAndIncrement() == 0 ? null : membershipReadback; + } + return null; + }); ResultQuery insertQuery = mock(ResultQuery.class); doReturn(insertQuery).when(dsl).resultQuery(anyString(), any(Object[].class)); doReturn(73L).when(insertQuery).fetchOne(0, Long.class); @@ -255,13 +254,12 @@ void firstFreshJoinRejectsExistingMembershipWithoutReactivatingOrWritingPairStat when(lockedAccount.get("account_uuid_source_numeric_id", Long.class)).thenReturn(17L); Record existingMembership = freshMembershipRecord(73L, 17L, 2L, 1L); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0); - return sql.contains("FROM accounts WHERE id = ? FOR UPDATE") - ? lockedAccount - : existingMembership; - }); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0); + return sql.contains("FROM accounts WHERE id = ? FOR UPDATE") + ? lockedAccount + : existingMembership; + }); TransactionSynchronizationManager.setActualTransactionActive(true); AccountTenantMembershipRepository repository = @@ -289,12 +287,10 @@ void firstJoinPublicationReadCanSeePendingMembershipButLeavesItNonAuthoritative( Record lockedAccount = lockedAccountRecord(); Record pendingMembership = freshMembershipRecord(73L, 17L, 2L, 1L); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> - ((String) invocation.getArgument(0)) - .contains("FROM accounts WHERE id = ? FOR UPDATE") - ? lockedAccount - : pendingMembership); + .thenAnswer(invocation -> + ((String) invocation.getArgument(0)).contains("FROM accounts WHERE id = ? FOR UPDATE") + ? lockedAccount + : pendingMembership); PairAuthority baseline = new PairAuthority( ACCOUNT_UUID, TENANT_UUID, freshProvenance(), false, 1L, 1L, 0L, null, null, false); @@ -333,12 +329,10 @@ void firstJoinPublicationReadAllowsOnlyTheExactPositiveFirstEventForReplay() { Record lockedAccount = lockedAccountRecord(); Record positiveMembership = freshMembershipRecord(73L, 17L, 2L, 1L); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> - ((String) invocation.getArgument(0)) - .contains("FROM accounts WHERE id = ? FOR UPDATE") - ? lockedAccount - : positiveMembership); + .thenAnswer(invocation -> + ((String) invocation.getArgument(0)).contains("FROM accounts WHERE id = ? FOR UPDATE") + ? lockedAccount + : positiveMembership); PairAuthority positive = new PairAuthority( ACCOUNT_UUID, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepositoryTest.java index 43f8db49c1..320e198b42 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantMembershipRoleSnapshotRepositoryTest.java @@ -33,30 +33,23 @@ void canonicalizesRoleIdentifiersByUnsignedAsciiBytesAndPreservesCase() { @Test void rejectsMalformedDuplicateOrNonCanonicalRoleEvidence() { - assertThatThrownBy( - () -> - AccountTenantMembershipRoleSnapshotRepository.canonicalizeRoleSet( - List.of("player", "player"))) + assertThatThrownBy(() -> + AccountTenantMembershipRoleSnapshotRepository.canonicalizeRoleSet( + List.of("player", "player"))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountTenantMembershipRoleSnapshotRepository.canonicalizeRoleSet( - List.of("_player"))) + assertThatThrownBy(() -> + AccountTenantMembershipRoleSnapshotRepository.canonicalizeRoleSet(List.of("_player"))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountTenantMembershipRoleSnapshotRepository.canonicalizeRoleSet( - List.of("player admin"))) + assertThatThrownBy(() -> + AccountTenantMembershipRoleSnapshotRepository.canonicalizeRoleSet( + List.of("player admin"))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountTenantMembershipRoleSnapshotRepository.canonicalizeRoleSet( - List.of("pläyer"))) + assertThatThrownBy(() -> + AccountTenantMembershipRoleSnapshotRepository.canonicalizeRoleSet(List.of("pläyer"))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountTenantMembershipRoleSnapshotRepository.requireCanonicalRoleSet( - List.of("player_2", "player"))) + assertThatThrownBy(() -> + AccountTenantMembershipRoleSnapshotRepository.requireCanonicalRoleSet( + List.of("player_2", "player"))) .isInstanceOf(IllegalArgumentException.class); } @@ -68,10 +61,9 @@ void emptyRoleSetIsAnAuthoritativeSnapshotOnlyWhenVersionedAndPresent() { assertThat(snapshot.roles()).isEmpty(); assertThat(snapshot.snapshotVersion()).isEqualTo(3L); - assertThatThrownBy( - () -> - new AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot( - 11L, 7L, 701L, 0L, List.of())) + assertThatThrownBy(() -> + new AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot( + 11L, 7L, 701L, 0L, List.of())) .isInstanceOf(IllegalArgumentException.class); } @@ -124,10 +116,9 @@ void canonicalRoleSnapshotRetainsFreshUuidAndFullSourceWithoutNumericAlias() { assertThat(snapshot.tenantUuid()).isEqualTo(tenantUuid); assertThat(snapshot.tenantId()).isNull(); assertThat(snapshot.tenantProvenance()).isEqualTo(provenance); - assertThatThrownBy( - () -> - new AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot( - 11L, 7L, 701L, 1L, List.of("player"), accountUuid, tenantUuid, provenance)) + assertThatThrownBy(() -> + new AccountTenantMembershipRoleSnapshotRepository.RoleSnapshot( + 11L, 7L, 701L, 1L, List.of("player"), accountUuid, tenantUuid, provenance)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsInterceptorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsInterceptorTest.java index aadb56046c..be73f64fad 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsInterceptorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountJwtSignerMaterializerTlsInterceptorTest.java @@ -144,12 +144,11 @@ public void onMessage(String message) { } }; when(next.startCall(any(), any())) - .thenAnswer( - invocation -> { - assertThat(AccountJwtSignerMaterializerTlsInterceptor.authenticatedBinding()) - .isEqualTo(binding); - return listener; - }); + .thenAnswer(invocation -> { + assertThat(AccountJwtSignerMaterializerTlsInterceptor.authenticatedBinding()) + .isEqualTo(binding); + return listener; + }); ServerCall.Listener intercepted = interceptor.interceptCall(call, new Metadata(), next); assertThat(intercepted).isNotSameAs(listener); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuardTest.java index 6a57f07a05..ae617b3d7f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuardTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountPlayerAdmissionEntitlementWorkloadGuardTest.java @@ -65,12 +65,11 @@ void arbitraryPeerContextAndSessionClaimsNeverAuthenticate() throws Exception { GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri("spiffe://firemud/ns/firemud/sa/game-session-service") .orElseThrow()) - .run( - () -> { - assertThat(invoke(method, null).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); - assertThatThrownBy(guard::requireAuthenticatedGameSessionCaller) - .isInstanceOf(StatusRuntimeException.class); - }); + .run(() -> { + assertThat(invoke(method, null).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThatThrownBy(guard::requireAuthenticatedGameSessionCaller) + .isInstanceOf(StatusRuntimeException.class); + }); for (boolean internal : List.of(true, false)) { if (internal) SessionContext.setContext( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountRuntimeConsumerAuthWiringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountRuntimeConsumerAuthWiringTest.java index a20614e373..bc8121e447 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountRuntimeConsumerAuthWiringTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountRuntimeConsumerAuthWiringTest.java @@ -316,45 +316,42 @@ private static void withConfiguredInterceptor( AutoConfigurations.of( ConfigurationPropertiesAutoConfiguration.class, CommonSecurityAutoConfiguration.class)) - .withInitializer( - context -> { - try { - YamlPropertySourceLoader yamlLoader = new YamlPropertySourceLoader(); - PropertySource accountBase = - yamlLoader - .load( - "account-application", - new FileSystemResource("src/main/resources/application.yml")) - .get(0); - context.getEnvironment().getPropertySources().addLast(accountBase); - if (productionLayer) { - PropertySource accountProduction = - yamlLoader - .load( - "account-application-prod", - new FileSystemResource("src/main/resources/application-prod.yml")) - .get(0); - context.getEnvironment().getPropertySources().addFirst(accountProduction); - } - } catch (IOException exception) { - throw new IllegalStateException( - "Could not load Account application config", exception); - } - }) + .withInitializer(context -> { + try { + YamlPropertySourceLoader yamlLoader = new YamlPropertySourceLoader(); + PropertySource accountBase = + yamlLoader + .load( + "account-application", + new FileSystemResource("src/main/resources/application.yml")) + .get(0); + context.getEnvironment().getPropertySources().addLast(accountBase); + if (productionLayer) { + PropertySource accountProduction = + yamlLoader + .load( + "account-application-prod", + new FileSystemResource("src/main/resources/application-prod.yml")) + .get(0); + context.getEnvironment().getPropertySources().addFirst(accountProduction); + } + } catch (IOException exception) { + throw new IllegalStateException("Could not load Account application config", exception); + } + }) .withPropertyValues("firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234") - .run( - context -> { - assertThat(context).hasSingleBean(AuthTokenInterceptor.class); - assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) - .contains(IDENTITY_METHOD) - .contains(PRESENCE_METHOD) - .contains(REALM_GRANT_METHOD) - .doesNotContain(NONPUBLIC_METHOD); - assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) - .doesNotContain(UPDATE_PROFILE_METHOD); - action.accept( - context.getBean(AuthTokenInterceptor.class), context.getBean(JwtUtil.class)); - }); + .run(context -> { + assertThat(context).hasSingleBean(AuthTokenInterceptor.class); + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .contains(IDENTITY_METHOD) + .contains(PRESENCE_METHOD) + .contains(REALM_GRANT_METHOD) + .doesNotContain(NONPUBLIC_METHOD); + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .doesNotContain(UPDATE_PROFILE_METHOD); + action.accept( + context.getBean(AuthTokenInterceptor.class), context.getBean(JwtUtil.class)); + }); } private static < diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java index 6c8482d5ec..61a29963a4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantCapacityWorkloadGuardTest.java @@ -73,12 +73,11 @@ void arbitraryPeerContextAndSessionClaimsNeverAuthenticate() throws Exception { GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri("spiffe://firemud/ns/firemud/sa/game-session-service") .orElseThrow()) - .run( - () -> { - assertThat(invoke(method, null).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); - assertThatThrownBy(guard::requireAuthenticatedCaller) - .isInstanceOf(StatusRuntimeException.class); - }); + .run(() -> { + assertThat(invoke(method, null).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThatThrownBy(guard::requireAuthenticatedCaller) + .isInstanceOf(StatusRuntimeException.class); + }); for (boolean internal : List.of(true, false)) { if (internal) SessionContext.setContext( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuardTest.java index 491e712c7f..465642e890 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuardTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/AccountTenantOperationEntitlementWorkloadGuardTest.java @@ -67,12 +67,11 @@ void arbitraryPeerContextAndSessionClaimsNeverAuthenticate() throws Exception { GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri("spiffe://firemud/ns/firemud/sa/world-management-service") .orElseThrow()) - .run( - () -> { - assertThat(invoke(method, null).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); - assertThatThrownBy(guard::requireAuthenticatedWorldCaller) - .isInstanceOf(StatusRuntimeException.class); - }); + .run(() -> { + assertThat(invoke(method, null).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThatThrownBy(guard::requireAuthenticatedWorldCaller) + .isInstanceOf(StatusRuntimeException.class); + }); for (boolean internal : List.of(true, false)) { if (internal) SessionContext.setContext( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java index da8d99a809..e65ce321d1 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/EmailVerificationHttpAuthWiringTest.java @@ -45,32 +45,31 @@ void publicPostReachesMappedVerificationOwnerWithoutBearer(boolean productionLay assertOpenApiDeclaresPublicPost(); JwtUtil jwtUtil = mock(JwtUtil.class); configuredRunner(productionLayer, jwtUtil) - .run( - context -> { - assertThat(context).hasSingleBean(HttpJwtAuthInterceptor.class); - HttpAuthProperties properties = context.getBean(HttpAuthProperties.class); - assertThat(properties.isEnabled()).isTrue(); - assertThat(properties.getPublicRoutes()) - .filteredOn(route -> PATH.equals(route.getPathPattern())) - .extracting(HttpAuthProperties.HttpPublicRoute::getMethod) - .containsExactly("POST"); - AccountService owner = mock(AccountService.class); - var mvc = - MockMvcBuilders.standaloneSetup(new AuthController(owner)) - .addInterceptors(context.getBean(HttpJwtAuthInterceptor.class)) - .build(); + .run(context -> { + assertThat(context).hasSingleBean(HttpJwtAuthInterceptor.class); + HttpAuthProperties properties = context.getBean(HttpAuthProperties.class); + assertThat(properties.isEnabled()).isTrue(); + assertThat(properties.getPublicRoutes()) + .filteredOn(route -> PATH.equals(route.getPathPattern())) + .extracting(HttpAuthProperties.HttpPublicRoute::getMethod) + .containsExactly("POST"); + AccountService owner = mock(AccountService.class); + var mvc = + MockMvcBuilders.standaloneSetup(new AuthController(owner)) + .addInterceptors(context.getBean(HttpJwtAuthInterceptor.class)) + .build(); - mvc.perform( - post(PATH) - .contentType(MediaType.APPLICATION_JSON) - .content("{\"token\":\"exact-verification-token\"}")) - .andExpect(status().isOk()) - .andExpect(jsonPath("$.status").value("SUCCESS")); + mvc.perform( + post(PATH) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"token\":\"exact-verification-token\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.status").value("SUCCESS")); - verify(owner).verifyEmail(new VerifyEmailRequest("exact-verification-token")); - verifyNoMoreInteractions(owner); - verifyNoInteractions(jwtUtil); - }); + verify(owner).verifyEmail(new VerifyEmailRequest("exact-verification-token")); + verifyNoMoreInteractions(owner); + verifyNoInteractions(jwtUtil); + }); } @ParameterizedTest @@ -78,30 +77,27 @@ void publicPostReachesMappedVerificationOwnerWithoutBearer(boolean productionLay void publicPostPreservesVerificationOwnersInvalidTokenOutcome(boolean productionLayer) { JwtUtil jwtUtil = mock(JwtUtil.class); configuredRunner(productionLayer, jwtUtil) - .run( - context -> { - assertThat(context).hasSingleBean(HttpJwtAuthInterceptor.class); - AccountService owner = mock(AccountService.class); - VerifyEmailRequest invalid = new VerifyEmailRequest("invalid-token"); - doThrow(new IllegalArgumentException("Invalid token")) - .when(owner) - .verifyEmail(invalid); - var mvc = - MockMvcBuilders.standaloneSetup(new AuthController(owner)) - .setControllerAdvice(new GlobalExceptionHandler()) - .addInterceptors(context.getBean(HttpJwtAuthInterceptor.class)) - .build(); + .run(context -> { + assertThat(context).hasSingleBean(HttpJwtAuthInterceptor.class); + AccountService owner = mock(AccountService.class); + VerifyEmailRequest invalid = new VerifyEmailRequest("invalid-token"); + doThrow(new IllegalArgumentException("Invalid token")).when(owner).verifyEmail(invalid); + var mvc = + MockMvcBuilders.standaloneSetup(new AuthController(owner)) + .setControllerAdvice(new GlobalExceptionHandler()) + .addInterceptors(context.getBean(HttpJwtAuthInterceptor.class)) + .build(); - mvc.perform( - post(PATH) - .contentType(MediaType.APPLICATION_JSON) - .content("{\"token\":\"invalid-token\"}")) - .andExpect(status().isBadRequest()); + mvc.perform( + post(PATH) + .contentType(MediaType.APPLICATION_JSON) + .content("{\"token\":\"invalid-token\"}")) + .andExpect(status().isBadRequest()); - verify(owner).verifyEmail(invalid); - verifyNoMoreInteractions(owner); - verifyNoInteractions(jwtUtil); - }); + verify(owner).verifyEmail(invalid); + verifyNoMoreInteractions(owner); + verifyNoInteractions(jwtUtil); + }); } @ParameterizedTest @@ -109,17 +105,16 @@ void publicPostPreservesVerificationOwnersInvalidTokenOutcome(boolean production void getIsNotWhitelistedWithoutBearer(boolean productionLayer) { JwtUtil jwtUtil = mock(JwtUtil.class); configuredRunner(productionLayer, jwtUtil) - .run( - context -> { - assertThat(context).hasSingleBean(HttpJwtAuthInterceptor.class); - HttpJwtAuthInterceptor interceptor = context.getBean(HttpJwtAuthInterceptor.class); - MockHttpServletRequest request = new MockHttpServletRequest("GET", PATH); - MockHttpServletResponse response = new MockHttpServletResponse(); + .run(context -> { + assertThat(context).hasSingleBean(HttpJwtAuthInterceptor.class); + HttpJwtAuthInterceptor interceptor = context.getBean(HttpJwtAuthInterceptor.class); + MockHttpServletRequest request = new MockHttpServletRequest("GET", PATH); + MockHttpServletResponse response = new MockHttpServletResponse(); - assertThat(interceptor.preHandle(request, response, new Object())).isFalse(); - assertThat(response.getStatus()).isEqualTo(401); - verifyNoInteractions(jwtUtil); - }); + assertThat(interceptor.preHandle(request, response, new Object())).isFalse(); + assertThat(response.getStatus()).isEqualTo(401); + verifyNoInteractions(jwtUtil); + }); } private static WebApplicationContextRunner configuredRunner( @@ -131,29 +126,28 @@ private static WebApplicationContextRunner configuredRunner( CommonSecurityAutoConfiguration.class, CommonSecurityServletAutoConfiguration.class)) .withBean("jwtUtil", JwtUtil.class, () -> jwtUtil) - .withInitializer( - context -> { - try { - YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); - for (var source : - loader.load( - "account-application", - new FileSystemResource("src/main/resources/application.yml"))) { - context.getEnvironment().getPropertySources().addLast(source); - } - if (productionLayer) { - context.getEnvironment().setActiveProfiles("prod"); - for (var source : - loader.load( - "account-application-prod", - new FileSystemResource("src/main/resources/application-prod.yml"))) { - context.getEnvironment().getPropertySources().addFirst(source); - } - } - } catch (IOException exception) { - throw new IllegalStateException("Could not load Account HTTP auth YAML", exception); + .withInitializer(context -> { + try { + YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); + for (var source : + loader.load( + "account-application", + new FileSystemResource("src/main/resources/application.yml"))) { + context.getEnvironment().getPropertySources().addLast(source); + } + if (productionLayer) { + context.getEnvironment().setActiveProfiles("prod"); + for (var source : + loader.load( + "account-application-prod", + new FileSystemResource("src/main/resources/application-prod.yml"))) { + context.getEnvironment().getPropertySources().addFirst(source); } - }); + } + } catch (IOException exception) { + throw new IllegalStateException("Could not load Account HTTP auth YAML", exception); + } + }); } private static void assertOpenApiDeclaresPublicPost() { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java index 177df1b335..afd6c9f3ef 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/security/RuntimeAccountIdentityGrpcAuthWiringTest.java @@ -249,47 +249,44 @@ private static void withConfiguredInterceptor( AutoConfigurations.of( ConfigurationPropertiesAutoConfiguration.class, CommonSecurityAutoConfiguration.class)) - .withInitializer( - context -> { - try { - YamlPropertySourceLoader yamlLoader = new YamlPropertySourceLoader(); - PropertySource accountBase = - yamlLoader - .load( - "account-application", - new FileSystemResource("src/main/resources/application.yml")) - .get(0); - context.getEnvironment().getPropertySources().addLast(accountBase); - if (productionLayer) { - PropertySource accountProduction = - yamlLoader - .load( - "account-application-prod", - new FileSystemResource("src/main/resources/application-prod.yml")) - .get(0); - context.getEnvironment().getPropertySources().addFirst(accountProduction); - } - } catch (IOException exception) { - throw new IllegalStateException( - "Could not load Account application config", exception); - } - }) + .withInitializer(context -> { + try { + YamlPropertySourceLoader yamlLoader = new YamlPropertySourceLoader(); + PropertySource accountBase = + yamlLoader + .load( + "account-application", + new FileSystemResource("src/main/resources/application.yml")) + .get(0); + context.getEnvironment().getPropertySources().addLast(accountBase); + if (productionLayer) { + PropertySource accountProduction = + yamlLoader + .load( + "account-application-prod", + new FileSystemResource("src/main/resources/application-prod.yml")) + .get(0); + context.getEnvironment().getPropertySources().addFirst(accountProduction); + } + } catch (IOException exception) { + throw new IllegalStateException("Could not load Account application config", exception); + } + }) .withPropertyValues("firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234") - .run( - context -> { - assertThat(context).hasSingleBean(AuthTokenInterceptor.class); - assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) - .contains(IDENTITY_METHOD) - .contains( - START_SESSION_ISSUE_METHOD, - START_SESSION_RECOVER_METHOD, - START_SESSION_REDEEM_METHOD, - READ_REDEEMED_OPERATION_PROJECTION_METHOD) - .doesNotContain("account.v1.StartSessionOperatorAuthorizationService/*") - .doesNotContain(NONPUBLIC_METHOD); - action.accept( - context.getBean(AuthTokenInterceptor.class), context.getBean(JwtUtil.class)); - }); + .run(context -> { + assertThat(context).hasSingleBean(AuthTokenInterceptor.class); + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .contains(IDENTITY_METHOD) + .contains( + START_SESSION_ISSUE_METHOD, + START_SESSION_RECOVER_METHOD, + START_SESSION_REDEEM_METHOD, + READ_REDEEMED_OPERATION_PROJECTION_METHOD) + .doesNotContain("account.v1.StartSessionOperatorAuthorizationService/*") + .doesNotContain(NONPUBLIC_METHOD); + action.accept( + context.getBean(AuthTokenInterceptor.class), context.getBean(JwtUtil.class)); + }); } private static < diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java index 7706831a7d..c5657e4749 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java @@ -78,35 +78,32 @@ void currentButInactiveOrAdmissionBlockedSourcesProduceIneligibleStagingEvidence @Test void rejectsUnsupportedScopeAndPurposeBeforeReadingOwnerSources() { - assertThatThrownBy( - () -> - service.resolve( - 2, - NAMESPACE, - REQUEST_UUID, - ACCOUNT_UUID, - TENANT_UUID, - Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)) + assertThatThrownBy(() -> + service.resolve( + 2, + NAMESPACE, + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - service.resolve( - 1, - "other", - REQUEST_UUID, - ACCOUNT_UUID, - TENANT_UUID, - Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)) + assertThatThrownBy(() -> + service.resolve( + 1, + "other", + REQUEST_UUID, + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - service.resolve( - 1, - NAMESPACE, - new UUID(0L, 0L), - ACCOUNT_UUID, - TENANT_UUID, - Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)) + assertThatThrownBy(() -> + service.resolve( + 1, + NAMESPACE, + new UUID(0L, 0L), + ACCOUNT_UUID, + TENANT_UUID, + Purpose.PUBLIC_PRODUCTION_STAGING_ONLY)) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(repository); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java index 19bad6232f..3f177d3922 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java @@ -76,21 +76,20 @@ void unsupportedGenericAccountEventMapsToTypedUnavailableEvidence() { @Test void restrictionReceiptRequiresEventSequenceToTrailResultGenerationByOne() { - assertThatThrownBy( - () -> - new AccountPlatformRestrictionOperationRepository.Operation( - restrictionRequest(), - account().getId(), - AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT, - new AccountAuthorityGenerationRepository.IssuanceFence(ACCOUNT_UUID, 1L, 1L), - Optional.of( - new AccountPlatformRestrictionOperationRepository.Receipt( - restrictionEvent(2L, "2", "2"), - accountState(2L, 2L, 2L, 2L), - 2L, - 2L, - UUID.fromString("33333333-3333-4333-8333-333333333333"), - RestrictionState.RESTRICTED)))) + assertThatThrownBy(() -> + new AccountPlatformRestrictionOperationRepository.Operation( + restrictionRequest(), + account().getId(), + AccountIdentityProvenance.ACCOUNT_DATABASE_INSERT, + new AccountAuthorityGenerationRepository.IssuanceFence(ACCOUNT_UUID, 1L, 1L), + Optional.of( + new AccountPlatformRestrictionOperationRepository.Receipt( + restrictionEvent(2L, "2", "2"), + accountState(2L, 2L, 2L, 2L), + 2L, + 2L, + UUID.fromString("33333333-3333-4333-8333-333333333333"), + RestrictionState.RESTRICTED)))) .isInstanceOf( AccountPlatformRestrictionOperationRepository.RestrictionSourceUnavailableException .class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningServiceTest.java index bb1548a3e0..50dcb53571 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountBillingCustomerProvisioningServiceTest.java @@ -86,13 +86,12 @@ void newClaimCommitsAndReadsBackBeforeProviderAndExistingClaimReconcilesOnly() { prepare(inserted); int commitsBefore = transactions.commits; when(provider.reconcile(any(), eq(inserted))) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - assertThat(transactions.commits).isEqualTo(commitsBefore + 2); - return new StripeBillingCustomerProvisioner.Unresolved(null); - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(transactions.commits).isEqualTo(commitsBefore + 2); + return new StripeBillingCustomerProvisioner.Unresolved(null); + }); assertThat(service.provision(ACCOUNT, OPERATION)) .isInstanceOf(AccountBillingCustomerProvisioningService.PendingCustomer.class); } @@ -306,11 +305,10 @@ private ConfirmationFixture confirmationFixture(boolean simultaneous) throws Exc when(stripeCustomers.search(any(com.stripe.param.CustomerSearchParams.class))) .thenReturn(search); when(stripeCustomers.retrieve("cus_exact")) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return customer; - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return customer; + }); when(repository.recordObservation( eq(ACCOUNT), eq(OPERATION), @@ -319,34 +317,32 @@ private ConfirmationFixture confirmationFixture(boolean simultaneous) throws Exc eq(Observation.CONFIRMED), eq("cus_exact"), anyString())) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(transactions.commits).isEqualTo(2); - var saved = - new AccountBillingCustomerRecord( - ACCOUNT, - OPERATION, - KEY, - 2, - State.CONFIRMED, - "cus_exact", - call.getArgument(3), - Observation.CONFIRMED, - call.getArgument(6), - NOW, - NOW); - receipt.set(saved); - return saved; - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(transactions.commits).isEqualTo(2); + var saved = + new AccountBillingCustomerRecord( + ACCOUNT, + OPERATION, + KEY, + 2, + State.CONFIRMED, + "cus_exact", + call.getArgument(3), + Observation.CONFIRMED, + call.getArgument(6), + NOW, + NOW); + receipt.set(saved); + return saved; + }); when(repository.findObservationByRequestId(any())) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(transactions.commits).isEqualTo(3); - assertThat(call.getArgument(0)).isEqualTo(receipt.get().changeRequestId()); - return Optional.of(receipt.get()); - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(transactions.commits).isEqualTo(3); + assertThat(call.getArgument(0)).isEqualTo(receipt.get().changeRequestId()); + return Optional.of(receipt.get()); + }); var actual = new AccountBillingCustomerProvisioningService( repository, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java index 611243e7a8..3b53367c4d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalConnectScopeReaderTest.java @@ -106,10 +106,8 @@ void refusesMissingOrMalformedSignedProfileBeforeAccountRead() { () -> f.reader.read( ACCOUNT, - f.issue( - claims -> - claims.put( - "aud", List.of("bootstrap-connect-scope", "player-bootstrap"))))); + f.issue(claims -> + claims.put("aud", List.of("bootstrap-connect-scope", "player-bootstrap"))))); assertCode( "CONNECT_SCOPE_INVALID", () -> f.reader.read(ACCOUNT, f.issue(claims -> claims.put("targetClass", "PRIVATE")))); @@ -179,9 +177,8 @@ void rejectsFutureEvaluationExpiredScopeAndJwtExpiryContradiction() { () -> f.reader.read( ACCOUNT, - f.issue( - claims -> - claims.put("evaluatedAt", Instant.now().plusSeconds(30).toString())))); + f.issue(claims -> + claims.put("evaluatedAt", Instant.now().plusSeconds(30).toString())))); assertCode( "CONNECT_SCOPE_INVALID", () -> @@ -196,13 +193,12 @@ void rejectsFutureEvaluationExpiredScopeAndJwtExpiryContradiction() { () -> f.reader.read( ACCOUNT, - f.issue( - claims -> - claims.put( - "connectScopeExpiresAt", - Instant.parse((String) claims.get("connectScopeExpiresAt")) - .plusSeconds(1) - .toString())))); + f.issue(claims -> + claims.put( + "connectScopeExpiresAt", + Instant.parse((String) claims.get("connectScopeExpiresAt")) + .plusSeconds(1) + .toString())))); assertThat(f.transactions.started).isZero(); verifyNoInteractions(f.scopes); } @@ -276,12 +272,11 @@ void refusesAmbientTransactionWithoutChangingCallerSessionContext() { private static void assertCode(String expected, Runnable action) { assertThatThrownBy(action::run) .isInstanceOf(AuthenticationException.class) - .satisfies( - failure -> { - AuthenticationException authentication = (AuthenticationException) failure; - assertThat(authentication.getCode()).isEqualTo(expected); - assertThat(authentication.getMessage()).doesNotContain("eyJ"); - }); + .satisfies(failure -> { + AuthenticationException authentication = (AuthenticationException) failure; + assertThat(authentication.getCode()).isEqualTo(expected); + assertThat(authentication.getMessage()).doesNotContain("eyJ"); + }); } private static CanonicalJoinScopeV2 scope(String token, String evaluatedAt, String expiresAt) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java index edef33bdaf..cf782b73d7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java @@ -193,10 +193,9 @@ void existingJoinRejectsNullScopeBeforeAnyOwnerRead() { Fixture fixture = new Fixture(); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.coordinator.commitCanonicalJoin( - null, REQUEST_ID, CALLER_BINDING, null, null, null)) + assertThatThrownBy(() -> + fixture.coordinator.commitCanonicalJoin( + null, REQUEST_ID, CALLER_BINDING, null, null, null)) .isInstanceOf(NullPointerException.class) .hasMessage("canonical JOIN scope is required"); verifyNoInteractions( @@ -216,18 +215,16 @@ void existingJoinRejectsUnboundedSelectorsBeforeAnyOwnerRead() { fixture.startWritableTransaction(); for (String requestId : new String[] {null, "", " ", "x".repeat(129)}) { - assertThatThrownBy( - () -> - fixture.coordinator.commitCanonicalJoin( - fixture.scope, requestId, CALLER_BINDING, null, null, null)) + assertThatThrownBy(() -> + fixture.coordinator.commitCanonicalJoin( + fixture.scope, requestId, CALLER_BINDING, null, null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical JOIN request ID"); } for (String callerBinding : new String[] {null, "", " ", "x".repeat(129)}) { - assertThatThrownBy( - () -> - fixture.coordinator.commitCanonicalJoin( - fixture.scope, REQUEST_ID, callerBinding, null, null, null)) + assertThatThrownBy(() -> + fixture.coordinator.commitCanonicalJoin( + fixture.scope, REQUEST_ID, callerBinding, null, null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("verified caller binding"); } @@ -333,10 +330,9 @@ void committedJoinStillRejectsChangedRequestOrCallerBinding(boolean changedReque .thenReturn(Optional.of(Fixture.committed(fixture.operation, fixture.expectedProof))); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.coordinator.commitCanonicalJoin( - fixture.scope, requestId, callerBinding, null, null, null)) + assertThatThrownBy(() -> + fixture.coordinator.commitCanonicalJoin( + fixture.scope, requestId, callerBinding, null, null, null)) .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class) .hasMessage("Canonical JOIN intent conflicts"); verifyNoInteractions( @@ -354,16 +350,14 @@ void changedCallerUnderGlobalRequestIdConflictsBeforeReturningAnyReceipt() { fixture.arrangePending(); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.coordinator.commitCanonicalFirstJoin( - fixture.scope, REQUEST_ID, "different-caller-binding")) + assertThatThrownBy(() -> + fixture.coordinator.commitCanonicalFirstJoin( + fixture.scope, REQUEST_ID, "different-caller-binding")) .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class) .hasMessage("Canonical JOIN intent conflicts") - .satisfies( - exception -> - assertThat(exception.getMessage()) - .doesNotContain(CALLER_BINDING, ACCOUNT_ID.toString())); + .satisfies(exception -> + assertThat(exception.getMessage()) + .doesNotContain(CALLER_BINDING, ACCOUNT_ID.toString())); verify(fixture.memberships, never()).createFreshMembershipForJoin(any(), any()); verify(fixture.eventProducer, never()) .publishCanonicalFirstJoinMembershipChange(any(), anyString(), anyString()); @@ -381,16 +375,13 @@ void changedAccountUnderGlobalRequestIdConflictsBeforeReturningAnyReceipt() { .thenReturn(Optional.of(otherAccount)); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.coordinator.commitCanonicalFirstJoin( - otherScope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.coordinator.commitCanonicalFirstJoin(otherScope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(AccountJoinOperationRepository.CanonicalJoinOperationConflictException.class) .hasMessage("Canonical JOIN intent conflicts") - .satisfies( - exception -> - assertThat(exception.getMessage()) - .doesNotContain(ACCOUNT_ID.toString(), OTHER_ACCOUNT_ID.toString())); + .satisfies(exception -> + assertThat(exception.getMessage()) + .doesNotContain(ACCOUNT_ID.toString(), OTHER_ACCOUNT_ID.toString())); verify(fixture.memberships, never()).createFreshMembershipForJoin(any(), any()); verify(fixture.eventProducer, never()) .publishCanonicalFirstJoinMembershipChange(any(), anyString(), anyString()); @@ -406,10 +397,8 @@ void pendingOperationCannotTurnAnAlreadyPositiveMembershipIntoTerminalSuccess() .thenThrow(new IllegalStateException("fresh membership already exists")); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.coordinator.commitCanonicalFirstJoin( - fixture.scope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.coordinator.commitCanonicalFirstJoin(fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(IllegalStateException.class) .hasMessage("fresh membership already exists"); verify(fixture.eventProducer, never()) @@ -428,10 +417,8 @@ void mismatchedEventReadbackCannotProduceAnAuditOrTerminalReceipt() { when(fixture.outbox.findEvent(EVENT_STREAM, 1L)).thenReturn(Optional.of(changed)); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.coordinator.commitCanonicalFirstJoin( - fixture.scope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.coordinator.commitCanonicalFirstJoin(fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(IllegalStateException.class) .hasMessage("Canonical first-JOIN event differs from checkpoint"); verify(fixture.audit, never()) @@ -449,10 +436,8 @@ void mismatchedPairReadbackCannotProduceAnAuditOrTerminalReceipt() { Optional.of(fixture.positivePair(fixture.event.eventId(), "sha256:" + "f".repeat(64)))); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.coordinator.commitCanonicalFirstJoin( - fixture.scope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.coordinator.commitCanonicalFirstJoin(fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(IllegalStateException.class) .hasMessage("Canonical first-JOIN pair differs from its event"); verify(fixture.audit, never()) @@ -471,10 +456,8 @@ void mismatchedAuditReadbackCannotCommitTheGlobalOperation() { .thenReturn(Optional.of(wrongTenant)); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.coordinator.commitCanonicalFirstJoin( - fixture.scope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.coordinator.commitCanonicalFirstJoin(fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(IllegalStateException.class) .hasMessage("Canonical JOIN audit envelope differs from its receipt"); verify(fixture.operations, never()) @@ -487,10 +470,8 @@ void readOnlyTransactionIsRejectedBeforeOwnerRepositoriesAreTouched() { TransactionSynchronizationManager.setActualTransactionActive(true); TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); - assertThatThrownBy( - () -> - fixture.coordinator.commitCanonicalFirstJoin( - fixture.scope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.coordinator.commitCanonicalFirstJoin(fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("writable Account owner transaction"); verifyNoInteractions( @@ -508,10 +489,8 @@ void readOnlyTransactionIsRejectedBeforeOwnerRepositoriesAreTouched() { void inactiveTransactionIsRejectedBeforeOwnerRepositoriesAreTouched() { Fixture fixture = new Fixture(); - assertThatThrownBy( - () -> - fixture.coordinator.commitCanonicalFirstJoin( - fixture.scope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.coordinator.commitCanonicalFirstJoin(fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("writable Account owner transaction"); verifyNoInteractions( @@ -548,16 +527,15 @@ void auditPreimageRejectsAnEventNotBoundToTheCheckpoint() { Fixture fixture = new Fixture(); Event changed = fixture.event("other-global-request"); - assertThatThrownBy( - () -> - AccountCanonicalFirstJoinTerminalCoordinator.canonicalAuditPayload( - fixture.scope, - REQUEST_ID, - fixture.operation.intentDigest(), - fixture.operation.requestDigest(), - 5L, - fixture.checkpoint, - changed)) + assertThatThrownBy(() -> + AccountCanonicalFirstJoinTerminalCoordinator.canonicalAuditPayload( + fixture.scope, + REQUEST_ID, + fixture.operation.intentDigest(), + fixture.operation.requestDigest(), + 5L, + fixture.checkpoint, + changed)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact event checkpoint"); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java index 7765522719..bd960d17b8 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalPublicRealmScopeOwnerTest.java @@ -116,17 +116,15 @@ void directProducerUsesExactGameSessionPeerAndCurrentOwnersWithoutBootstrapRegis void directProducerAcceptsPositiveSessionBytesWithinTheJoinBoundary(String sessionId) { Fixture f = new Fixture(300000L); directPeer(NAMESPACE, "game-session-service") - .run( - () -> { - var scope = - f.owner - .issueDirectTextScope( - directCaller(f.target, sessionId), directTarget(f.target)) - .scope(); - assertThat(scope.accountId()).isEqualTo(ACCOUNT); - assertThat(f.retained.get()).isEqualTo(scope); - verify(f.scopes).insertCanonical(PRIVATE_ACCOUNT, scope, f.provenance()); - }); + .run(() -> { + var scope = + f.owner + .issueDirectTextScope(directCaller(f.target, sessionId), directTarget(f.target)) + .scope(); + assertThat(scope.accountId()).isEqualTo(ACCOUNT); + assertThat(f.retained.get()).isEqualTo(scope); + verify(f.scopes).insertCanonical(PRIVATE_ACCOUNT, scope, f.provenance()); + }); } @ParameterizedTest @@ -135,13 +133,12 @@ void directProducerRefusesSessionBytesBeyondTheJoinBoundaryBeforeOwnerReads(int Fixture f = new Fixture(300000L); String sessionId = "0".repeat(length - 1) + "1"; directPeer(NAMESPACE, "game-session-service") - .run( - () -> - assertCode( - "CONNECT_CONTEXT_INVALID", - () -> - f.owner.issueDirectTextScope( - directCaller(f.target, sessionId), directTarget(f.target)))); + .run(() -> + assertCode( + "CONNECT_CONTEXT_INVALID", + () -> + f.owner.issueDirectTextScope( + directCaller(f.target, sessionId), directTarget(f.target)))); verifyNoInteractions( f.accounts, f.memberships, @@ -172,16 +169,14 @@ void directProducerRefusesNonPositiveAsciiLongsAndRetainsParseCauseBeforeOwnerRe String sessionId) { Fixture f = new Fixture(300000L); directPeer(NAMESPACE, "game-session-service") - .run( - () -> - assertThatThrownBy( - () -> - f.owner.issueDirectTextScope( - directCaller(f.target, sessionId), directTarget(f.target))) - .isInstanceOf(AuthenticationException.class) - .hasCauseInstanceOf(NumberFormatException.class) - .extracting(failure -> ((AuthenticationException) failure).getCode()) - .isEqualTo("CONNECT_CONTEXT_INVALID")); + .run(() -> + assertThatThrownBy(() -> + f.owner.issueDirectTextScope( + directCaller(f.target, sessionId), directTarget(f.target))) + .isInstanceOf(AuthenticationException.class) + .hasCauseInstanceOf(NumberFormatException.class) + .extracting(failure -> ((AuthenticationException) failure).getCode()) + .isEqualTo("CONNECT_CONTEXT_INVALID")); verifyNoInteractions( f.accounts, f.memberships, @@ -201,12 +196,10 @@ void directProducerRefusesWrongPeerBeforeReadingAccountOrSources(String mismatch directPeer( mismatch.equals("other-namespace") ? "other" : NAMESPACE, mismatch.equals("wrong-service") ? "world-management-service" : "game-session-service"); - peer.run( - () -> - assertCode( - "AUTH_UNAVAILABLE", - () -> - f.owner.issueDirectTextScope(directCaller(f.target), directTarget(f.target)))); + peer.run(() -> + assertCode( + "AUTH_UNAVAILABLE", + () -> f.owner.issueDirectTextScope(directCaller(f.target), directTarget(f.target)))); verifyNoInteractions( f.accounts, f.memberships, @@ -224,13 +217,11 @@ void directProducerRejectsUnknownAccountWithoutReadingTargetsOrPersistingScope() doReturn(Optional.empty()).when(f.accounts).findByAccountUuidForUpdate(ACCOUNT); directPeer(NAMESPACE, "game-session-service") - .run( - () -> - assertCode( - "CONNECT_CONTEXT_INVALID", - () -> - f.owner.issueDirectTextScope( - directCaller(f.target), directTarget(f.target)))); + .run(() -> + assertCode( + "CONNECT_CONTEXT_INVALID", + () -> + f.owner.issueDirectTextScope(directCaller(f.target), directTarget(f.target)))); verify(f.accounts).findByAccountUuidForUpdate(ACCOUNT); verifyNoInteractions( @@ -245,13 +236,11 @@ void directProducerKeepsAccountRepositoryFailureRetryableWithoutReadingTargets() .findByAccountUuidForUpdate(ACCOUNT); directPeer(NAMESPACE, "game-session-service") - .run( - () -> - assertCode( - "AUTH_UNAVAILABLE", - () -> - f.owner.issueDirectTextScope( - directCaller(f.target), directTarget(f.target)))); + .run(() -> + assertCode( + "AUTH_UNAVAILABLE", + () -> + f.owner.issueDirectTextScope(directCaller(f.target), directTarget(f.target)))); verify(f.accounts).findByAccountUuidForUpdate(ACCOUNT); verifyNoInteractions( @@ -264,13 +253,11 @@ void directProducerReportsUnavailableEntitlementWithoutMisclassifyingThePointer( when(f.entitlements.evaluate(TENANT)).thenReturn(f.evaluation(false)); directPeer(NAMESPACE, "game-session-service") - .run( - () -> - assertCode( - "ENTITLEMENT_UNAVAILABLE", - () -> - f.owner.issueDirectTextScope( - directCaller(f.target), directTarget(f.target)))); + .run(() -> + assertCode( + "ENTITLEMENT_UNAVAILABLE", + () -> + f.owner.issueDirectTextScope(directCaller(f.target), directTarget(f.target)))); assertThat(f.targetReads.get()).isEqualTo(2); verifyNoInteractions(f.scopes, f.sessions, f.memberships); @@ -282,13 +269,11 @@ void directProducerRechecksCurrentAccountAndTargetBeforePersistingScope() { f.onSecondTargetRead = () -> f.account.setLifecycleState(AccountLifecycleState.DEACTIVATED_PENDING_DELETE); directPeer(NAMESPACE, "game-session-service") - .run( - () -> - assertCode( - "AUTH_UNAVAILABLE", - () -> - f.owner.issueDirectTextScope( - directCaller(f.target), directTarget(f.target)))); + .run(() -> + assertCode( + "AUTH_UNAVAILABLE", + () -> + f.owner.issueDirectTextScope(directCaller(f.target), directTarget(f.target)))); verifyNoInteractions(f.scopes, f.sessions); } @@ -422,12 +407,11 @@ void invalidJwtFromScopeOwnerParsingIsMappedWithoutCause() { assertThatThrownBy(() -> f.owner.listRealmScopes(f.token, "tenant", "world")) .isInstanceOf(AuthenticationException.class) - .satisfies( - failure -> { - assertThat(((AuthenticationException) failure).getCode()) - .isEqualTo("CONNECT_CONTEXT_INVALID"); - assertThat(failure.getCause()).isNull(); - }); + .satisfies(failure -> { + assertThat(((AuthenticationException) failure).getCode()) + .isEqualTo("CONNECT_CONTEXT_INVALID"); + assertThat(failure.getCause()).isNull(); + }); } @Test @@ -438,12 +422,10 @@ void operationalBootstrapCallerFailureIsRetainedAsUnavailableCause() { assertThatThrownBy(() -> f.owner.listRealmScopes(f.token, "tenant", "world")) .isInstanceOf(AuthenticationException.class) - .satisfies( - wrapped -> { - assertThat(((AuthenticationException) wrapped).getCode()) - .isEqualTo("AUTH_UNAVAILABLE"); - assertThat(wrapped.getCause()).isSameAs(failure); - }); + .satisfies(wrapped -> { + assertThat(((AuthenticationException) wrapped).getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(wrapped.getCause()).isSameAs(failure); + }); } @Test @@ -454,12 +436,10 @@ void absoluteExpirySigningFailureIsRetainedAsUnavailableCause() { assertThatThrownBy(() -> f.owner.listRealmScopes(f.token, "tenant", "world")) .isInstanceOf(AuthenticationException.class) - .satisfies( - wrapped -> { - assertThat(((AuthenticationException) wrapped).getCode()) - .isEqualTo("AUTH_UNAVAILABLE"); - assertThat(wrapped.getCause()).isSameAs(failure); - }); + .satisfies(wrapped -> { + assertThat(((AuthenticationException) wrapped).getCode()).isEqualTo("AUTH_UNAVAILABLE"); + assertThat(wrapped.getCause()).isSameAs(failure); + }); } @Test @@ -809,65 +789,56 @@ private Fixture(long bootstrapLifetime) { "jti", UUID.randomUUID().toString())); when(accounts.findByAccountUuid(ACCOUNT)) - .thenAnswer( - invocation -> { - assertOutsideSql(); - return Optional.of(account); - }); + .thenAnswer(invocation -> { + assertOutsideSql(); + return Optional.of(account); + }); when(accounts.findByAccountUuidForUpdate(ACCOUNT)) - .thenAnswer( - invocation -> { - assertInsideSql(); - return Optional.of(account); - }); + .thenAnswer(invocation -> { + assertInsideSql(); + return Optional.of(account); + }); when(sessions.isAccountSessionActive(PRIVATE_ACCOUNT, token)) - .thenAnswer( - invocation -> { - assertOutsideSql(); - registryChecks.incrementAndGet(); - return active.get(); - }); + .thenAnswer(invocation -> { + assertOutsideSql(); + registryChecks.incrementAndGet(); + return active.get(); + }); when(tenants.read(TENANT)) - .thenAnswer( - invocation -> { - assertInsideSql(); - return Optional.of(source); - }); + .thenAnswer(invocation -> { + assertInsideSql(); + return Optional.of(source); + }); when(heads.readCurrentSourceSelection(TENANT)) - .thenAnswer( - invocation -> { - assertInsideSql(); - return head; - }); + .thenAnswer(invocation -> { + assertInsideSql(); + return head; + }); when(memberships.findFreshMembershipForUpdate(ACCOUNT, TENANT)) - .thenAnswer( - invocation -> { - assertInsideSql(); - return member.get(); - }); + .thenAnswer(invocation -> { + assertInsideSql(); + return member.get(); + }); when(entitlements.evaluate(TENANT)) - .thenAnswer( - invocation -> { - assertOutsideSql(); - return evaluation; - }); + .thenAnswer(invocation -> { + assertOutsideSql(); + return evaluation; + }); when(targets.listVisiblePublicProductionAdmissionTargets(any())) - .thenAnswer( - invocation -> { - assertOutsideSql(); - int count = targetReads.incrementAndGet(); - if (count == 2) onSecondTargetRead.run(); - var request = - new DiscoveryRequest(invocation.getArgument(0, UUID.class), NAMESPACE); - List values = - count == 1 - ? (firstCollection == null ? List.of(target) : firstCollection) - : (secondCollection == null ? List.of(secondTarget) : secondCollection); - return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( - request, - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( - request, values)); - }); + .thenAnswer(invocation -> { + assertOutsideSql(); + int count = targetReads.incrementAndGet(); + if (count == 2) onSecondTargetRead.run(); + var request = new DiscoveryRequest(invocation.getArgument(0, UUID.class), NAMESPACE); + List values = + count == 1 + ? (firstCollection == null ? List.of(target) : firstCollection) + : (secondCollection == null ? List.of(secondTarget) : secondCollection); + return CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, values)); + }); doAnswer( invocation -> { assertInsideSql(); @@ -879,58 +850,56 @@ private Fixture(long bootstrapLifetime) { .when(scopes) .insertCanonical(anyLong(), any(), any()); when(scopes.findCanonical(any())) - .thenAnswer( - invocation -> { - assertInsideSql(); - CanonicalJoinScopeV2 original = retained.get(); - if (corruptReadback) - return Optional.of( - new CanonicalJoinScopeV2( - original.connectScopeId(), - original.accountId(), - original.tenantId(), - UUID.randomUUID(), - original.tenantSlug(), - original.worldSlug(), - original.realmSlug(), - original.playableStateNamespaceId(), - original.playableStateScope(), - original.gameInstanceId(), - original.catalogRevision(), - original.pointerVersion(), - original.evaluatedAt(), - original.connectScopeExpiresAt())); - return Optional.of(original); - }); + .thenAnswer(invocation -> { + assertInsideSql(); + CanonicalJoinScopeV2 original = retained.get(); + if (corruptReadback) + return Optional.of( + new CanonicalJoinScopeV2( + original.connectScopeId(), + original.accountId(), + original.tenantId(), + UUID.randomUUID(), + original.tenantSlug(), + original.worldSlug(), + original.realmSlug(), + original.playableStateNamespaceId(), + original.playableStateScope(), + original.gameInstanceId(), + original.catalogRevision(), + original.pointerVersion(), + original.evaluatedAt(), + original.connectScopeExpiresAt())); + return Optional.of(original); + }); when(scopes.findCanonicalEvidenceByTokenHash(any())) - .thenAnswer( - invocation -> { - assertInsideSql(); - CanonicalConnectScopeEvidence original = retainedEvidence.get(); - if (corruptDigest) - return Optional.of( - new CanonicalConnectScopeEvidence( - original.scopeTokenHash(), - original.privateAccountId(), - original.targetClass(), - original.accountUuid(), - original.tenantUuid(), - original.realmId(), - original.tenantSlug(), - original.worldSlug(), - original.realmSlug(), - original.playableStateNamespaceUuid(), - original.playableStateScope(), - original.gameInstanceUuid(), - original.catalogRevision(), - original.pointerVersion(), - original.evaluatedAt(), - original.connectScopeExpiresAt(), - 2, - "sha256:" + "b".repeat(64), - original.tenantProvenance())); - return Optional.of(original); - }); + .thenAnswer(invocation -> { + assertInsideSql(); + CanonicalConnectScopeEvidence original = retainedEvidence.get(); + if (corruptDigest) + return Optional.of( + new CanonicalConnectScopeEvidence( + original.scopeTokenHash(), + original.privateAccountId(), + original.targetClass(), + original.accountUuid(), + original.tenantUuid(), + original.realmId(), + original.tenantSlug(), + original.worldSlug(), + original.realmSlug(), + original.playableStateNamespaceUuid(), + original.playableStateScope(), + original.gameInstanceUuid(), + original.catalogRevision(), + original.pointerVersion(), + original.evaluatedAt(), + original.connectScopeExpiresAt(), + 2, + "sha256:" + "b".repeat(64), + original.tenantProvenance())); + return Optional.of(original); + }); var properties = new AccountTokenProperties(); properties.setConnectScopeExpirationMs(120000L); var caller = new AccountPlayerBootstrapCallerVerifier(jwt, accounts, sessions); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReaderTest.java index 018de0893d..73d26cc71c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReaderTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCreatorMembershipSourceReaderTest.java @@ -53,9 +53,8 @@ void clearTransactionState() { @Test void requiresWritableOwnerTransactionBeforeReadingOrEnrollingAnything() { - assertThatThrownBy( - () -> - reader.readFreshNeverJoinedMembershipSnapshot(UUID.randomUUID(), UUID.randomUUID())) + assertThatThrownBy(() -> + reader.readFreshNeverJoinedMembershipSnapshot(UUID.randomUUID(), UUID.randomUUID())) .isInstanceOf(IllegalStateException.class); verifyNoInteractions( accounts, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContractTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContractTest.java index bccc9a219f..085c076a10 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContractTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRedisContractTest.java @@ -103,23 +103,20 @@ void onlyCanonicalAccountKeysAndExactModeSpecificArgumentsAreAccepted() { key, "PRESENT", "expected", "candidate"); AccountGenerationProjectionRedisContract.validateInvocation(key, "VERIFY", "expected", ""); - assertThatThrownBy( - () -> - AccountGenerationProjectionRedisContract.validateInvocation( - "session:auth:generation:issuer:c980fa44-619e-4ca4-8ad6-75b0538a66a3", - "ABSENT", - "", - "candidate")) + assertThatThrownBy(() -> + AccountGenerationProjectionRedisContract.validateInvocation( + "session:auth:generation:issuer:c980fa44-619e-4ca4-8ad6-75b0538a66a3", + "ABSENT", + "", + "candidate")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGenerationProjectionRedisContract.validateInvocation( - key, "VERIFY", "expected", "candidate")) + assertThatThrownBy(() -> + AccountGenerationProjectionRedisContract.validateInvocation( + key, "VERIFY", "expected", "candidate")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGenerationProjectionRedisContract.validateInvocation( - key, "ABSENT", "not-empty", "candidate")) + assertThatThrownBy(() -> + AccountGenerationProjectionRedisContract.validateInvocation( + key, "ABSENT", "not-empty", "candidate")) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java index da86c5f95e..5db4db5c16 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionLifecycleServiceTest.java @@ -47,10 +47,9 @@ private void assertRefusal() { assertThatThrownBy(() -> service.claimProvisioning(UUID.randomUUID(), 1, UUID.randomUUID())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("ambient SQL transaction"); - assertThatThrownBy( - () -> - service.reconcile( - UUID.randomUUID(), UUID.randomUUID(), 2, "sub_controlled", UUID.randomUUID())) + assertThatThrownBy(() -> + service.reconcile( + UUID.randomUUID(), UUID.randomUUID(), 2, "sub_controlled", UUID.randomUUID())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("ambient SQL transaction"); assertThatThrownBy(() -> service.readCurrent(UUID.randomUUID())) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java index 32590851fa..67211fd1e7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountHostingSubscriptionProvisioningServiceTest.java @@ -51,32 +51,28 @@ void claimCommitAndIndependentReadbackPrecedeProviderAndUnknownOutcomeDefersWith ProviderDispatch readback = mock(ProviderDispatch.class); when(readback.claim()).thenReturn(claim); when(repository.prepareProviderDispatch(any(), any())) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - return prepared; - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return prepared; + }); when(repository.readProviderDispatch(prepared)) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(transactions.commits).isEqualTo(1); - return readback; - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(transactions.commits).isEqualTo(1); + return readback; + }); when(provider.provision(readback)) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - assertThat(transactions.commits).isEqualTo(2); - return new StripeHostingSubscriptionProvisioner.Pending("UNKNOWN", null); - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(transactions.commits).isEqualTo(2); + return new StripeHostingSubscriptionProvisioner.Pending("UNKNOWN", null); + }); when(repository.deferUnresolved(claim)) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - return Disposition.WAITING; - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return Disposition.WAITING; + }); var result = (AccountHostingSubscriptionProvisioningService.Pending) service.provision(claim, UUID.randomUUID(), UUID.randomUUID()); @@ -96,11 +92,10 @@ void expiredAttemptReturnsTypedPendingWithoutStartingLifecycle(String providerRe var providerResult = new StripeHostingSubscriptionProvisioner.Pending(providerReason, null); when(provider.provision(readback)).thenReturn(providerResult); when(repository.deferUnresolved(claim)) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - return Disposition.ATTEMPT_EXPIRED; - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return Disposition.ATTEMPT_EXPIRED; + }); assertThat(service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) .isEqualTo( @@ -123,11 +118,10 @@ void refusedDispatchCommitsLocalDeferralWithoutCallingProvider(boolean readbackR .thenThrow(new FenceRejectedException("wallet observation advanced")); } when(repository.deferUnresolved(claim)) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - return Disposition.TERMINAL_FAILURE; - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return Disposition.TERMINAL_FAILURE; + }); assertThat(service.provision(claim, UUID.randomUUID(), UUID.randomUUID())) .isEqualTo( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java index 06bc3dd11e..cabe8f4c96 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountLogoutAllAuthorityEventProducerTest.java @@ -54,64 +54,41 @@ void rejectsMalformedRequestEvidenceBeforeDatabaseOrTransactionInteraction() { 1L, new AccountAuthorityGenerationRepository.IssuanceFence(ACCOUNT_UUID, 1L, 1L)); - assertThatThrownBy( - () -> - producer.commit( - new UUID(0L, 0L), - 1, - REQUEST_DIGEST, - TOKEN_PROFILE, - TOKEN_HASH, - account, - expected)) + assertThatThrownBy(() -> + producer.commit( + new UUID(0L, 0L), 1, REQUEST_DIGEST, TOKEN_PROFILE, TOKEN_HASH, account, expected)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("non-nil"); - assertThatThrownBy( - () -> - producer.commit( - UUID.randomUUID(), - 0, - REQUEST_DIGEST, - TOKEN_PROFILE, - TOKEN_HASH, - account, - expected)) + assertThatThrownBy(() -> + producer.commit( + UUID.randomUUID(), 0, REQUEST_DIGEST, TOKEN_PROFILE, TOKEN_HASH, account, expected)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("positive"); - assertThatThrownBy( - () -> - producer.commit( - UUID.randomUUID(), - 1, - "A".repeat(64), - TOKEN_PROFILE, - TOKEN_HASH, - account, - expected)) + assertThatThrownBy(() -> + producer.commit( + UUID.randomUUID(), 1, "A".repeat(64), TOKEN_PROFILE, TOKEN_HASH, account, expected)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("lowercase SHA-256"); - assertThatThrownBy( - () -> - producer.commit( - UUID.randomUUID(), - 1, - REQUEST_DIGEST, - TOKEN_PROFILE, - "b".repeat(63), - account, - expected)) + assertThatThrownBy(() -> + producer.commit( + UUID.randomUUID(), + 1, + REQUEST_DIGEST, + TOKEN_PROFILE, + "b".repeat(63), + account, + expected)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("token hash"); - assertThatThrownBy( - () -> - producer.commit( - UUID.randomUUID(), - 1, - REQUEST_DIGEST, - "private-player-delegation", - TOKEN_HASH, - account, - expected)) + assertThatThrownBy(() -> + producer.commit( + UUID.randomUUID(), + 1, + REQUEST_DIGEST, + "private-player-delegation", + TOKEN_HASH, + account, + expected)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("token profile"); @@ -133,16 +110,15 @@ void rejectsAmbientTransactionAndDoesNotUseExpectedStateAsCallerAuthorization() TransactionSynchronizationManager.setActualTransactionActive(true); try { - assertThatThrownBy( - () -> - producer.commit( - UUID.randomUUID(), - 1, - REQUEST_DIGEST, - TOKEN_PROFILE, - TOKEN_HASH, - account, - expected)) + assertThatThrownBy(() -> + producer.commit( + UUID.randomUUID(), + 1, + REQUEST_DIGEST, + TOKEN_PROFILE, + TOKEN_HASH, + account, + expected)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("without an ambient transaction"); collaborators.verifyUnused(); @@ -163,16 +139,15 @@ void rejectsMismatchedExpectedSourceScopeBeforeDatabaseInteraction() { 1L, new AccountAuthorityGenerationRepository.IssuanceFence(ACCOUNT_UUID, 1L, 1L)); - assertThatThrownBy( - () -> - producer.commit( - UUID.randomUUID(), - 1, - REQUEST_DIGEST, - TOKEN_PROFILE, - TOKEN_HASH, - account, - wrongScope)) + assertThatThrownBy(() -> + producer.commit( + UUID.randomUUID(), + 1, + REQUEST_DIGEST, + TOKEN_PROFILE, + TOKEN_HASH, + account, + wrongScope)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Expected Account authority scope"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java index 895c108fda..2e2f26d2dd 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java @@ -161,10 +161,9 @@ void restoreRequiresCanonicalScopeBeforeReadingOwnerState() { Fixture fixture = new Fixture(); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.producer.publishCanonicalRestoredMembershipChange( - null, REQUEST_ID, CALLER_BINDING, fixture.absenceBaseline, null, null, null)) + assertThatThrownBy(() -> + fixture.producer.publishCanonicalRestoredMembershipChange( + null, REQUEST_ID, CALLER_BINDING, fixture.absenceBaseline, null, null, null)) .isInstanceOf(NullPointerException.class) .hasMessage("canonical JOIN scope is required"); @@ -188,16 +187,15 @@ void restoreRejectsContradictoryAccountIdentityBeforeLocking(String malformed) { when(fixture.accounts.findByAccountUuid(ACCOUNT_UUID)) .thenReturn("absent".equals(malformed) ? Optional.empty() : Optional.of(fixture.account)); - assertThatThrownBy( - () -> - fixture.producer.publishCanonicalRestoredMembershipChange( - fixture.scope, - REQUEST_ID, - CALLER_BINDING, - fixture.absenceBaseline, - null, - null, - null)) + assertThatThrownBy(() -> + fixture.producer.publishCanonicalRestoredMembershipChange( + fixture.scope, + REQUEST_ID, + CALLER_BINDING, + fixture.absenceBaseline, + null, + null, + null)) .isInstanceOf(IllegalStateException.class) .hasMessage( "absent".equals(malformed) @@ -276,10 +274,9 @@ void restoreRejectsUnboundOrNoncanonicalRoleSnapshotBeforeAuthorityReads(String ACCOUNT_UUID, TENANT_UUID, fixture.provenance, 73L, 4L)) .thenReturn(Optional.of(roles)); - assertThatThrownBy( - () -> - fixture.producer.publishCanonicalRestoredMembershipChange( - fixture.scope, REQUEST_ID, CALLER_BINDING, previous, null, null, null)) + assertThatThrownBy(() -> + fixture.producer.publishCanonicalRestoredMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING, previous, null, null, null)) .isInstanceOf(IllegalStateException.class) .hasMessage( List.of("unsorted", "duplicate").contains(malformed) @@ -318,16 +315,15 @@ void restoreRequiresBoundedRequestSelectorsBeforeReadingOwnerState( default -> throw new AssertionError(malformed); }; - assertThatThrownBy( - () -> - fixture.producer.publishCanonicalRestoredMembershipChange( - fixture.scope, - "request".equals(selector) ? invalid : REQUEST_ID, - "caller".equals(selector) ? invalid : CALLER_BINDING, - fixture.absenceBaseline, - null, - null, - null)) + assertThatThrownBy(() -> + fixture.producer.publishCanonicalRestoredMembershipChange( + fixture.scope, + "request".equals(selector) ? invalid : REQUEST_ID, + "caller".equals(selector) ? invalid : CALLER_BINDING, + fixture.absenceBaseline, + null, + null, + null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage( ("request".equals(selector) @@ -349,16 +345,15 @@ void paidRestoreRequiresOriginalFenceAndSealedResultBeforeReadingOwnerState( var observed = missingFence ? mock(StripeHostingSubscriptionObserver.ObservedSubscription.class) : null; - assertThatThrownBy( - () -> - fixture.producer.publishCanonicalRestoredMembershipChange( - fixture.scope, - REQUEST_ID, - CALLER_BINDING, - fixture.absenceBaseline, - hosting, - fence, - observed)) + assertThatThrownBy(() -> + fixture.producer.publishCanonicalRestoredMembershipChange( + fixture.scope, + REQUEST_ID, + CALLER_BINDING, + fixture.absenceBaseline, + hosting, + fence, + observed)) .isInstanceOf(NullPointerException.class) .hasMessage( missingFence @@ -383,43 +378,40 @@ void appendsCanonicalEventReadbackAndFirstPairCasFromLockedOwnerEvidence(boolean AtomicReference committedEvent = new AtomicReference<>(); AtomicInteger membershipCheckpointReads = new AtomicInteger(); when(fixture.outbox.readCheckpoint(any(String.class))) - .thenAnswer( - invocation -> { - String stream = invocation.getArgument(0); - if (!MEMBERSHIP_STREAM.equals(stream)) { - return Optional.empty(); - } - return membershipCheckpointReads.getAndIncrement() == 0 - ? Optional.empty() - : Optional.of(fixture.checkpoint(committedEvent.get())); - }); + .thenAnswer(invocation -> { + String stream = invocation.getArgument(0); + if (!MEMBERSHIP_STREAM.equals(stream)) { + return Optional.empty(); + } + return membershipCheckpointReads.getAndIncrement() == 0 + ? Optional.empty() + : Optional.of(fixture.checkpoint(committedEvent.get())); + }); when(fixture.outbox.append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class))) - .thenAnswer( - invocation -> { - LongFunction factory = invocation.getArgument(2); - EventEvidence evidence = factory.apply(1L); - Event event = - new Event( - MEMBERSHIP_STREAM, - REQUEST_ID, - 1L, - evidence.eventId(), - evidence.eventDigest(), - evidence.payload()); - committedEvent.set(event); - return event; - }); + .thenAnswer(invocation -> { + LongFunction factory = invocation.getArgument(2); + EventEvidence evidence = factory.apply(1L); + Event event = + new Event( + MEMBERSHIP_STREAM, + REQUEST_ID, + 1L, + evidence.eventId(), + evidence.eventDigest(), + evidence.payload()); + committedEvent.set(event); + return event; + }); when(fixture.outbox.findEvent(MEMBERSHIP_STREAM, REQUEST_ID)) .thenAnswer(invocation -> Optional.of(committedEvent.get())); when(fixture.outbox.findEvent(MEMBERSHIP_STREAM, 1L)) .thenAnswer(invocation -> Optional.of(committedEvent.get())); // The pair event ID and digest are supplied by the event candidate, as in the real CAS. when(fixture.pairs.commitTransition(eq(fixture.absenceBaseline), any(PairTransition.class))) - .thenAnswer( - invocation -> { - PairTransition transition = invocation.getArgument(1); - return fixture.positivePair(transition.eventId(), transition.eventDigest()); - }); + .thenAnswer(invocation -> { + PairTransition transition = invocation.getArgument(1); + return fixture.positivePair(transition.eventId(), transition.eventDigest()); + }); fixture.startWritableTransaction(); var hosting = mock(AccountHostingSubscriptionLifecycleRepository.class); @@ -491,11 +483,10 @@ void exactPositiveReplayReturnsTheExistingCheckpointWithoutAnotherAppendOrCas(bo when(fixture.pairs.readForUpdate(ACCOUNT_UUID, TENANT_UUID)) .thenReturn(Optional.of(fixture.positivePair(event.eventId(), event.eventDigest()))); when(fixture.outbox.readCheckpoint(any(String.class))) - .thenAnswer( - invocation -> - MEMBERSHIP_STREAM.equals(invocation.getArgument(0)) - ? Optional.of(checkpoint) - : Optional.empty()); + .thenAnswer(invocation -> + MEMBERSHIP_STREAM.equals(invocation.getArgument(0)) + ? Optional.of(checkpoint) + : Optional.empty()); when(fixture.outbox.findEvent(MEMBERSHIP_STREAM, REQUEST_ID)).thenReturn(Optional.of(event)); when(fixture.outbox.findEvent(MEMBERSHIP_STREAM, 1L)).thenReturn(Optional.of(event)); when(fixture.entitlements.readCurrent(TENANT_UUID)) @@ -542,42 +533,39 @@ void firstJoinUsesCurrentAccountAndIssuerAuthorityAfterPriorSourceMutation() { AtomicReference committedEvent = new AtomicReference<>(); AtomicInteger membershipCheckpointReads = new AtomicInteger(); when(fixture.outbox.readCheckpoint(any(String.class))) - .thenAnswer( - invocation -> { - String stream = invocation.getArgument(0); - if (!MEMBERSHIP_STREAM.equals(stream)) { - return Optional.of(new Checkpoint(stream, 1L, "tenant-event-1", DIGEST)); - } - return membershipCheckpointReads.getAndIncrement() == 0 - ? Optional.empty() - : Optional.of(fixture.checkpoint(committedEvent.get())); - }); + .thenAnswer(invocation -> { + String stream = invocation.getArgument(0); + if (!MEMBERSHIP_STREAM.equals(stream)) { + return Optional.of(new Checkpoint(stream, 1L, "tenant-event-1", DIGEST)); + } + return membershipCheckpointReads.getAndIncrement() == 0 + ? Optional.empty() + : Optional.of(fixture.checkpoint(committedEvent.get())); + }); when(fixture.outbox.append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class))) - .thenAnswer( - invocation -> { - LongFunction factory = invocation.getArgument(2); - EventEvidence evidence = factory.apply(1L); - Event event = - new Event( - MEMBERSHIP_STREAM, - REQUEST_ID, - 1L, - evidence.eventId(), - evidence.eventDigest(), - evidence.payload()); - committedEvent.set(event); - return event; - }); + .thenAnswer(invocation -> { + LongFunction factory = invocation.getArgument(2); + EventEvidence evidence = factory.apply(1L); + Event event = + new Event( + MEMBERSHIP_STREAM, + REQUEST_ID, + 1L, + evidence.eventId(), + evidence.eventDigest(), + evidence.payload()); + committedEvent.set(event); + return event; + }); when(fixture.outbox.findEvent(MEMBERSHIP_STREAM, REQUEST_ID)) .thenAnswer(invocation -> Optional.of(committedEvent.get())); when(fixture.outbox.findEvent(MEMBERSHIP_STREAM, 1L)) .thenAnswer(invocation -> Optional.of(committedEvent.get())); when(fixture.pairs.commitTransition(eq(fixture.absenceBaseline), any(PairTransition.class))) - .thenAnswer( - invocation -> { - PairTransition transition = invocation.getArgument(1); - return fixture.positivePair(transition.eventId(), transition.eventDigest()); - }); + .thenAnswer(invocation -> { + PairTransition transition = invocation.getArgument(1); + return fixture.positivePair(transition.eventId(), transition.eventDigest()); + }); fixture.producer.publishCanonicalFirstJoinMembershipChange( fixture.scope, REQUEST_ID, CALLER_BINDING); @@ -621,37 +609,34 @@ void firstJoinAcceptsLaterTenantAuthorityOnlyWithExactCurrentTenantSourceAndBill AtomicReference committedEvent = new AtomicReference<>(); AtomicInteger membershipCheckpointReads = new AtomicInteger(); when(fixture.outbox.readCheckpoint(any(String.class))) - .thenAnswer( - invocation -> - membershipCheckpointReads.getAndIncrement() == 0 - ? Optional.empty() - : Optional.of(fixture.checkpoint(committedEvent.get()))); + .thenAnswer(invocation -> + membershipCheckpointReads.getAndIncrement() == 0 + ? Optional.empty() + : Optional.of(fixture.checkpoint(committedEvent.get()))); when(fixture.outbox.append(eq(MEMBERSHIP_STREAM), eq(REQUEST_ID), any(LongFunction.class))) - .thenAnswer( - invocation -> { - LongFunction factory = invocation.getArgument(2); - EventEvidence evidence = factory.apply(1L); - Event event = - new Event( - MEMBERSHIP_STREAM, - REQUEST_ID, - 1L, - evidence.eventId(), - evidence.eventDigest(), - evidence.payload()); - committedEvent.set(event); - return event; - }); + .thenAnswer(invocation -> { + LongFunction factory = invocation.getArgument(2); + EventEvidence evidence = factory.apply(1L); + Event event = + new Event( + MEMBERSHIP_STREAM, + REQUEST_ID, + 1L, + evidence.eventId(), + evidence.eventDigest(), + evidence.payload()); + committedEvent.set(event); + return event; + }); when(fixture.outbox.findEvent(MEMBERSHIP_STREAM, REQUEST_ID)) .thenAnswer(invocation -> Optional.of(committedEvent.get())); when(fixture.outbox.findEvent(MEMBERSHIP_STREAM, 1L)) .thenAnswer(invocation -> Optional.of(committedEvent.get())); when(fixture.pairs.commitTransition(eq(fixture.absenceBaseline), any(PairTransition.class))) - .thenAnswer( - invocation -> { - PairTransition transition = invocation.getArgument(1); - return fixture.positivePair(transition.eventId(), transition.eventDigest()); - }); + .thenAnswer(invocation -> { + PairTransition transition = invocation.getArgument(1); + return fixture.positivePair(transition.eventId(), transition.eventDigest()); + }); fixture.producer.publishCanonicalFirstJoinMembershipChange( fixture.scope, REQUEST_ID, CALLER_BINDING); @@ -679,10 +664,9 @@ void firstJoinDeniesBareGenerationOneTenantBaselineBeforeEntitlementLookupOrMuta .thenReturn(fixture.authoritySnapshot(1L, 1L, 1L, 1L)); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.producer.publishCanonicalFirstJoinMembershipChange( - fixture.scope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(IllegalStateException.class) .hasMessage( "Canonical first JOIN requires exact current public-JOIN entitlement and tenant authority evidence"); @@ -705,10 +689,9 @@ void firstJoinDeniesAStalePendingEntitlementVersionWithoutMutation() { .thenReturn(fixture.entitlementSnapshot(currentEvent, 6L, true, true)); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.producer.publishCanonicalFirstJoinMembershipChange( - fixture.scope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("exact current public-join entitlement evidence"); @@ -728,10 +711,9 @@ void firstJoinDeniesCurrentEntitlementWhenPublicJoinIsNoLongerAllowed() { .thenReturn(fixture.entitlementSnapshot(currentEvent, 5L, true, false)); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.producer.publishCanonicalFirstJoinMembershipChange( - fixture.scope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("exact current public-join entitlement evidence"); @@ -751,10 +733,9 @@ void firstJoinDeniesCurrentEntitlementWhenGameplayIsUnavailable() { .thenReturn(fixture.entitlementSnapshot(currentEvent, 5L, false, true)); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.producer.publishCanonicalFirstJoinMembershipChange( - fixture.scope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("exact current public-join entitlement evidence"); @@ -771,10 +752,9 @@ void firstJoinFailsClosedWhenCurrentEntitlementReadIsUnavailable() { .thenThrow(new IllegalStateException("current entitlement unavailable")); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.producer.publishCanonicalFirstJoinMembershipChange( - fixture.scope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(IllegalStateException.class) .hasMessage("current entitlement unavailable"); @@ -793,10 +773,9 @@ void firstJoinDeniesEntitlementSnapshotWithDifferentCurrentAuthorityEventBinding .thenReturn(fixture.entitlementSnapshot(differentCurrentEvent)); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.producer.publishCanonicalFirstJoinMembershipChange( - fixture.scope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("exact current public-join entitlement evidence"); @@ -818,10 +797,9 @@ void firstJoinDeniesAdvancedTenantAuthorityWithoutTenantSourceEventReadback() { when(fixture.tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(null); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.producer.publishCanonicalFirstJoinMembershipChange( - fixture.scope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("exact current Account, source, and tenant authority evidence"); @@ -873,10 +851,9 @@ void firstJoinDeniesWhenTenantSourceRepositoryRejectsMissingOrMismatchedBillingE new IllegalStateException("Current tenant billing event is absent or mismatched")); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.producer.publishCanonicalFirstJoinMembershipChange( - fixture.scope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("billing event is absent or mismatched"); @@ -894,10 +871,9 @@ void firstJoinDeniesWhenCurrentAccountSourceIdentityDoesNotMatchLockedAccount() .thenReturn(fixture.sourceSnapshot(1L, 1L, 18L)); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.producer.publishCanonicalFirstJoinMembershipChange( - fixture.scope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("exact current Account, source, and tenant authority evidence"); @@ -913,10 +889,9 @@ void firstJoinDeniesWhenLockedMembershipTenantProvenanceDiffersFromItsOperation( fixture.membership.setTenantProvenanceDigest("sha256:" + "b".repeat(64)); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.producer.publishCanonicalFirstJoinMembershipChange( - fixture.scope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("locked Account or tenant provenance"); @@ -933,10 +908,9 @@ void conflictingCallerIsDeniedBeforeMembershipOrEventSourcesAreRead() { .thenReturn(Optional.of(fixture.operation("different-caller"))); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.producer.publishCanonicalFirstJoinMembershipChange( - fixture.scope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("request, caller, scope, or available policy"); verify(fixture.memberships, never()) @@ -951,10 +925,9 @@ void eventPublicationRequiresWritableAccountTransactionBeforeAnyLookup() { Fixture fixture = new Fixture(); TransactionSynchronizationManager.setActualTransactionActive(false); - assertThatThrownBy( - () -> - fixture.producer.publishCanonicalFirstJoinMembershipChange( - fixture.scope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(IllegalStateException.class) .hasMessage("Canonical Account JOIN requires an active owner transaction"); verifyNoInteractions( @@ -1012,10 +985,9 @@ void paidMismatchOrUnavailableSourceNeverPublishesOrFallsBack(String failure) { .thenThrow(new IllegalStateException("controlled paid source unavailable")); else when(hosting.readCurrent(fence, observed)).thenReturn(receipt); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.producer.publishPaidCanonicalFirstJoinMembershipChange( - fixture.scope, REQUEST_ID, CALLER_BINDING, hosting, fence, observed)) + assertThatThrownBy(() -> + fixture.producer.publishPaidCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING, hosting, fence, observed)) .isInstanceOf(IllegalStateException.class) .hasMessage( "unavailable".equals(failure) @@ -1065,10 +1037,9 @@ private void denyLaterTenantSource(TenantAuthorityEventV1Codec.Event event) { when(fixture.tenantAuthorityEvents.readCurrentByTenant(TENANT_UUID)).thenReturn(event); fixture.startWritableTransaction(); - assertThatThrownBy( - () -> - fixture.producer.publishCanonicalFirstJoinMembershipChange( - fixture.scope, REQUEST_ID, CALLER_BINDING)) + assertThatThrownBy(() -> + fixture.producer.publishCanonicalFirstJoinMembershipChange( + fixture.scope, REQUEST_ID, CALLER_BINDING)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("exact current Account, source, and tenant authority evidence"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentServiceTest.java index fcc522b4ba..e72c45c631 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPaymentInstrumentAttachmentServiceTest.java @@ -103,29 +103,28 @@ private void source() { when(instruments.findAttachmentByRequestId(request.requestId())) .thenAnswer(call -> Optional.ofNullable(retained)); when(instruments.retainAttachment(any())) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(transactions.commits).isEqualTo(1); - Attachment a = call.getArgument(0); - retained = - new AccountPaymentInstrumentRecord( - a.instrumentUuid(), - a.accountUuid(), - a.customerProvisioningRequestId(), - a.providerCustomerId(), - a.providerPaymentMethodId(), - a.requestId(), - 1, - a.state(), - a.display(), - a.requestId(), - a.evidenceDigest(), - NOW, - NOW); - current = retained; - return retained; - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(transactions.commits).isEqualTo(1); + Attachment a = call.getArgument(0); + retained = + new AccountPaymentInstrumentRecord( + a.instrumentUuid(), + a.accountUuid(), + a.customerProvisioningRequestId(), + a.providerCustomerId(), + a.providerPaymentMethodId(), + a.requestId(), + 1, + a.state(), + a.display(), + a.requestId(), + a.evidenceDigest(), + NOW, + NOW); + current = retained; + return retained; + }); } private AccountPaymentInstrumentRecord occupiedInstrument() { @@ -251,17 +250,16 @@ void receiptCommittedDuringSdkReadReturnsHistoricalOriginalAndLaterAvailability( transport.paths.clear(); transport.lastFour = "4444"; when(customers.findByAccountForUpdate(ACCOUNT)) - .thenAnswer( - call -> { - if (transport.paths.size() == 2) { - // Another invocation committed its original receipt and a later availability - // version - // after this invocation's preparation but before final owner-lock acquisition. - retained = original; - current = later; - } - return Optional.of(customer); - }); + .thenAnswer(call -> { + if (transport.paths.size() == 2) { + // Another invocation committed its original receipt and a later availability + // version + // after this invocation's preparation but before final owner-lock acquisition. + retained = original; + current = later; + } + return Optional.of(customer); + }); var replay = (HistoricalAttachment) service().retainSavedMethod(request); assertThat(replay.receipt()).isEqualTo(original); assertThat(replay.receipt().display().lastFour()).isEqualTo("4242"); @@ -312,13 +310,12 @@ void slowObservationAndPostObservationLockDelayFailFreshnessBeforeRetention() { void lockWaitAfterSdkObservationAlsoCountsAgainstFreshness() { source(); when(customers.findByAccountForUpdate(ACCOUNT)) - .thenAnswer( - call -> { - if (!transport.paths.isEmpty()) { - clock.now = NOW.plusSeconds(11); - } - return Optional.of(customer); - }); + .thenAnswer(call -> { + if (!transport.paths.isEmpty()) { + clock.now = NOW.plusSeconds(11); + } + return Optional.of(customer); + }); assertThatThrownBy(() -> service().retainSavedMethod(request)).hasMessageContaining("stale"); verify(instruments, never()).retainAttachment(any()); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java index 703e8bf61e..e07e7e4e22 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwnerTest.java @@ -201,11 +201,10 @@ void existingMembershipCarriesItsIndependentVersionAndPositiveCheckpoint() throw .containsExactlyEntriesOf(Map.of(TENANT.toString(), "1")); assertThat(value.membershipSource().gameplayAdmissionAllowed()).isTrue(); assertThat(value.membershipSource().sourceEvidence()) - .anySatisfy( - source -> { - assertThat(source.eventId()).isEqualTo("membership-event-1"); - assertThat(source.eventDigest()).startsWith("sha256:"); - }); + .anySatisfy(source -> { + assertThat(source.eventId()).isEqualTo("membership-event-1"); + assertThat(source.eventDigest()).startsWith("sha256:"); + }); var order = inOrder(f.accounts, f.issuances, f.memberships, f.scopes, f.demos); order.verify(f.accounts).findByAccountUuidForUpdate(ACCOUNT); order.verify(f.issuances).readCurrentCommittedCandidateByJti(f.identity.tokenJti()); @@ -227,23 +226,20 @@ void paidReadRunsProviderOutsideSqlThenCapturesCurrentReceiptAndPlayerInFinalTra var fence = mock(ReadFence.class); var observed = mock(StripeHostingSubscriptionObserver.ObservedSubscription.class); when(f.hosting.prepareCurrentRead(TENANT)) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - return fence; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return fence; + }); when(f.observer.observe(fence.binding())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return observed; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return observed; + }); when(f.hosting.readCurrent(fence, observed)) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - return f.receipt(status); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return f.receipt(status); + }); var value = f.owner.evaluate(f.request, "controlled-token"); assertThat(value.fields()) .containsEntry("sourceKind", "PAID_HOSTING") @@ -332,11 +328,10 @@ void sourceTimeoutReachesJdbcLockingStatementAndRollsBackWithoutReturningEvidenc when(connection.getTransactionIsolation()) .thenReturn(Connection.TRANSACTION_READ_COMMITTED, Connection.TRANSACTION_SERIALIZABLE); when(connection.prepareStatement(anyString())) - .thenAnswer( - invocation -> { - assertThat(invocation.getArgument(0, String.class)).endsWith("for update"); - return statement; - }); + .thenAnswer(invocation -> { + assertThat(invocation.getArgument(0, String.class)).endsWith("for update"); + return statement; + }); when(statement.execute()).thenThrow(new SQLTimeoutException("Controlled timeout", "57014")); // The real Spring proxy transfers the remaining transaction budget to jOOQ's JDBC statement. // The driver is controlled here; physical PostgreSQL cancellation is separate proof. @@ -406,10 +401,9 @@ void callerAccountMismatchFailsBeforeAnySourceRead() throws Exception { original.gameInstanceId(), original.catalogRevision(), original.pointerVersion()); - assertThatThrownBy( - () -> - f.owner.evaluate( - new Request(other, f.scope.connectScopeId(), PEER), "controlled-token")) + assertThatThrownBy(() -> + f.owner.evaluate( + new Request(other, f.scope.connectScopeId(), PEER), "controlled-token")) .hasMessageContaining("ENTITLEMENT_UNAVAILABLE"); verifyNoInteractions( f.accounts, @@ -644,48 +638,47 @@ private static void assertReceiverRefusal(Fixture f, io.grpc.Status.Code expecte private static Stream protectedTargetFailures() { return Stream.of("resolve", "strict") - .flatMap( - stage -> { - Stream outages = - Stream.of( - new CanonicalGameplayAdmissionDecisionReadClient.ClientUnavailableException( - new IllegalStateException("private target detail")), - io.grpc.Status.UNAVAILABLE - .withDescription("private target detail") - .asRuntimeException(), - io.grpc.Status.DEADLINE_EXCEEDED - .withDescription("private target detail") - .asRuntimeException(), - io.grpc.Status.CANCELLED - .withDescription("private target detail") - .asRuntimeException(), - io.grpc.Status.ABORTED - .withDescription("private target detail") - .asRuntimeException()); - Stream unexpected = + .flatMap(stage -> { + Stream outages = + Stream.of( + new CanonicalGameplayAdmissionDecisionReadClient.ClientUnavailableException( + new IllegalStateException("private target detail")), + io.grpc.Status.UNAVAILABLE + .withDescription("private target detail") + .asRuntimeException(), + io.grpc.Status.DEADLINE_EXCEEDED + .withDescription("private target detail") + .asRuntimeException(), + io.grpc.Status.CANCELLED + .withDescription("private target detail") + .asRuntimeException(), + io.grpc.Status.ABORTED + .withDescription("private target detail") + .asRuntimeException()); + Stream unexpected = + Stream.of( + io.grpc.Status.INVALID_ARGUMENT + .withDescription("private target detail") + .asRuntimeException(), + new IllegalArgumentException("private target detail"), + new IllegalStateException( + "Game Session returned invalid current target evidence", + new IllegalArgumentException("private target detail")), + new NullPointerException("private target detail")); + return Stream.concat( + Stream.concat( + outages.map( + failure -> Arguments.of(stage, failure, io.grpc.Status.Code.UNAVAILABLE)), Stream.of( - io.grpc.Status.INVALID_ARGUMENT - .withDescription("private target detail") - .asRuntimeException(), - new IllegalArgumentException("private target detail"), - new IllegalStateException( - "Game Session returned invalid current target evidence", - new IllegalArgumentException("private target detail")), - new NullPointerException("private target detail")); - return Stream.concat( - Stream.concat( - outages.map( - failure -> Arguments.of(stage, failure, io.grpc.Status.Code.UNAVAILABLE)), - Stream.of( - Arguments.of( - stage, - io.grpc.Status.FAILED_PRECONDITION - .withDescription("private target detail") - .asRuntimeException(), - io.grpc.Status.Code.FAILED_PRECONDITION))), - unexpected.map( - failure -> Arguments.of(stage, failure, io.grpc.Status.Code.INTERNAL))); - }); + Arguments.of( + stage, + io.grpc.Status.FAILED_PRECONDITION + .withDescription("private target detail") + .asRuntimeException(), + io.grpc.Status.Code.FAILED_PRECONDITION))), + unexpected.map( + failure -> Arguments.of(stage, failure, io.grpc.Status.Code.INTERNAL))); + }); } @Test @@ -801,11 +794,10 @@ void protectedReadCannotReplaceSupportedPolicyBeforeEvidenceCapture() throws Exc var original = f.targets.readPublishedRealmAdmissionOwner(resolved.strictSelector()); doReturn(resolved).when(f.targets).resolvePublishedRealmAdmissionTarget(f.request.target()); when(f.targets.readPublishedRealmAdmissionOwner(resolved.strictSelector())) - .thenAnswer( - invocation -> { - when(original.currentTarget().characterCreationPolicy()).thenReturn("PLAYER_CREATED"); - return original; - }); + .thenAnswer(invocation -> { + when(original.currentTarget().characterCreationPolicy()).thenReturn("PLAYER_CREATED"); + return original; + }); assertThatThrownBy(() -> f.owner.evaluate(f.request, "controlled-token")) .isExactlyInstanceOf( @@ -862,91 +854,83 @@ void strictProtectedReadFailureNeverProducesCanonicalPlayerEvidence() throws Exc /** Controlled protected-client double: no physical GS/World source provenance is claimed. */ private static void controlledTarget(CanonicalGameplayAdmissionDecisionReadClient targets) { when(targets.resolvePublishedRealmAdmissionTarget(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - var selector = - invocation.getArgument( - 0, - CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); - var target = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); - when(target.targetNamespace()).thenReturn(selector.targetNamespace()); - when(target.canonicalTenantId()).thenReturn(selector.tenantId()); - when(target.tenantSlug()).thenReturn(selector.tenantSlug()); - when(target.worldSlug()).thenReturn(selector.worldSlug()); - when(target.realmId()).thenReturn(selector.realmId()); - when(target.realmSlug()).thenReturn(selector.realmSlug()); - when(target.playableStateNamespaceId()) - .thenReturn(selector.playableStateNamespaceId()); - when(target.playableStateScope()).thenReturn(selector.playableStateScope()); - when(target.canonicalGameInstanceId()).thenReturn(selector.gameInstanceId()); - when(target.catalogRevision()).thenReturn(selector.catalogRevision()); - when(target.pointerVersion()).thenReturn(selector.pointerVersion()); - when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); - when(target.ownerProofOutcome()) - .thenReturn( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED); - UUID version = UUID.fromString("33333333-3333-4333-8333-333333333333"); - when(target.canonicalVersionId()).thenReturn(version); - when(target.activeWorldEpoch()).thenReturn(5L); - var strict = - new CanonicalGameplayRosterOwnerReadEvidence.Request( - selector.readRequestId(), - selector.accountId(), - selector.targetNamespace(), - selector.tenantId(), - selector.worldSlug(), - selector.realmId(), - selector.realmSlug(), - selector.playableStateNamespaceId(), - selector.playableStateScope(), - selector.gameInstanceId(), - version, - selector.catalogRevision(), - selector.pointerVersion(), - 5L); - var resolved = - mock( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget - .class); - when(resolved.selector()).thenReturn(selector); - when(resolved.currentTarget()).thenReturn(target); - when(resolved.strictSelector()).thenReturn(strict); - var read = - mock( - CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); - when(read.selector()).thenReturn(strict); - when(read.currentTarget()).thenReturn(target); - var source = mock(CanonicalGameplayRosterOwnerReadEvidence.class); - when(source.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); - var policies = mock(PublishedRealmEntryPolicySetEvidence.class); - when(policies.policySetDigest()).thenReturn("sha256:" + "b".repeat(64)); - when(source.publishedPolicySetEvidence()).thenReturn(policies); - var ownerProof = - mock( - net.firedevops.firemud.common.world - .GameSessionCanonicalInitialAdmissionOwnerProof.class); - when(ownerProof.proofDigest()).thenReturn("sha256:" + "c".repeat(64)); - when(source.gameSessionOwnerProof()).thenReturn(ownerProof); - when(read.sourceEvidence()).thenReturn(source); - var world = mock(WorldCanonicalInstanceLifecycleEvidence.class); - when(world.canonicalBytes()) - .thenReturn( - "controlled-complete-world-source" - .getBytes(java.nio.charset.StandardCharsets.UTF_8)); - when(world.captureId()) - .thenReturn(UUID.fromString("44444444-4444-4444-8444-444444444444")); - when(world.rowVersion()).thenReturn(2L); - when(read.worldLifecycleEvidence()).thenReturn(world); - when(targets.readPublishedRealmAdmissionOwner(strict)) - .thenAnswer( - readCall -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()) - .isFalse(); - return read; - }); - return resolved; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var selector = + invocation.getArgument( + 0, CanonicalGameplayAdmissionDecisionReadGrpcCodec.RetainedTargetSelector.class); + var target = mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); + when(target.targetNamespace()).thenReturn(selector.targetNamespace()); + when(target.canonicalTenantId()).thenReturn(selector.tenantId()); + when(target.tenantSlug()).thenReturn(selector.tenantSlug()); + when(target.worldSlug()).thenReturn(selector.worldSlug()); + when(target.realmId()).thenReturn(selector.realmId()); + when(target.realmSlug()).thenReturn(selector.realmSlug()); + when(target.playableStateNamespaceId()).thenReturn(selector.playableStateNamespaceId()); + when(target.playableStateScope()).thenReturn(selector.playableStateScope()); + when(target.canonicalGameInstanceId()).thenReturn(selector.gameInstanceId()); + when(target.catalogRevision()).thenReturn(selector.catalogRevision()); + when(target.pointerVersion()).thenReturn(selector.pointerVersion()); + when(target.characterCreationPolicy()).thenReturn("PRESEEDED_ONLY"); + when(target.ownerProofOutcome()) + .thenReturn( + CanonicalGameplayAdmissionDecisionReadGrpcCodec.OwnerProofOutcome.COMMITTED); + UUID version = UUID.fromString("33333333-3333-4333-8333-333333333333"); + when(target.canonicalVersionId()).thenReturn(version); + when(target.activeWorldEpoch()).thenReturn(5L); + var strict = + new CanonicalGameplayRosterOwnerReadEvidence.Request( + selector.readRequestId(), + selector.accountId(), + selector.targetNamespace(), + selector.tenantId(), + selector.worldSlug(), + selector.realmId(), + selector.realmSlug(), + selector.playableStateNamespaceId(), + selector.playableStateScope(), + selector.gameInstanceId(), + version, + selector.catalogRevision(), + selector.pointerVersion(), + 5L); + var resolved = + mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.ResolvedPublishedTarget.class); + when(resolved.selector()).thenReturn(selector); + when(resolved.currentTarget()).thenReturn(target); + when(resolved.strictSelector()).thenReturn(strict); + var read = + mock(CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class); + when(read.selector()).thenReturn(strict); + when(read.currentTarget()).thenReturn(target); + var source = mock(CanonicalGameplayRosterOwnerReadEvidence.class); + when(source.admissionPointerSnapshotDigest()).thenReturn("a".repeat(64)); + var policies = mock(PublishedRealmEntryPolicySetEvidence.class); + when(policies.policySetDigest()).thenReturn("sha256:" + "b".repeat(64)); + when(source.publishedPolicySetEvidence()).thenReturn(policies); + var ownerProof = + mock( + net.firedevops.firemud.common.world.GameSessionCanonicalInitialAdmissionOwnerProof + .class); + when(ownerProof.proofDigest()).thenReturn("sha256:" + "c".repeat(64)); + when(source.gameSessionOwnerProof()).thenReturn(ownerProof); + when(read.sourceEvidence()).thenReturn(source); + var world = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(world.canonicalBytes()) + .thenReturn( + "controlled-complete-world-source" + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + when(world.captureId()) + .thenReturn(UUID.fromString("44444444-4444-4444-8444-444444444444")); + when(world.rowVersion()).thenReturn(2L); + when(read.worldLifecycleEvidence()).thenReturn(world); + when(targets.readPublishedRealmAdmissionOwner(strict)) + .thenAnswer(readCall -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return read; + }); + return resolved; + }); } private static final class Fixture { @@ -1061,42 +1045,40 @@ private Fixture(boolean exists, String stateScope) throws Exception { var dsl = mock(DSLContext.class); // Controlled retention content, not physical atomicity or Account source authentication. when(dsl.execute(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0, String.class); - if (!sql.startsWith("INSERT INTO account_tenant_capacity_evaluations ")) - throw new AssertionError(sql); - if (refuseCapacityRetention) - throw new DataAccessException("Controlled capacity retention refusal"); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - if (missingCapacityRetentionReadback) return 0; - Object[] values = (Object[]) invocation.getRawArguments()[1]; - String id = (String) values[0]; - if (retainedCapacity.containsKey(id)) return 0; - var row = mock(org.jooq.Record.class); - when(row.get("evaluation_identity", String.class)).thenReturn(id); - when(row.get("snapshot_identity", String.class)).thenReturn((String) values[1]); - when(row.get("tenant_uuid", UUID.class)).thenReturn((UUID) values[2]); - when(row.get("caller_workload", String.class)).thenReturn((String) values[3]); - when(row.get("owner_service", String.class)).thenReturn((String) values[4]); - when(row.get("canonical_evidence", byte[].class)) - .thenReturn(((byte[]) values[5]).clone()); - when(row.get("evaluated_at", java.time.OffsetDateTime.class)) - .thenReturn((java.time.OffsetDateTime) values[6]); - when(row.get("expires_at", java.time.OffsetDateTime.class)) - .thenReturn((java.time.OffsetDateTime) values[7]); - retainedCapacity.put(id, row); - return 1; - }); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0, String.class); + if (!sql.startsWith("INSERT INTO account_tenant_capacity_evaluations ")) + throw new AssertionError(sql); + if (refuseCapacityRetention) + throw new DataAccessException("Controlled capacity retention refusal"); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + if (missingCapacityRetentionReadback) return 0; + Object[] values = (Object[]) invocation.getRawArguments()[1]; + String id = (String) values[0]; + if (retainedCapacity.containsKey(id)) return 0; + var row = mock(org.jooq.Record.class); + when(row.get("evaluation_identity", String.class)).thenReturn(id); + when(row.get("snapshot_identity", String.class)).thenReturn((String) values[1]); + when(row.get("tenant_uuid", UUID.class)).thenReturn((UUID) values[2]); + when(row.get("caller_workload", String.class)).thenReturn((String) values[3]); + when(row.get("owner_service", String.class)).thenReturn((String) values[4]); + when(row.get("canonical_evidence", byte[].class)) + .thenReturn(((byte[]) values[5]).clone()); + when(row.get("evaluated_at", java.time.OffsetDateTime.class)) + .thenReturn((java.time.OffsetDateTime) values[6]); + when(row.get("expires_at", java.time.OffsetDateTime.class)) + .thenReturn((java.time.OffsetDateTime) values[7]); + retainedCapacity.put(id, row); + return 1; + }); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0, String.class); - if (!sql.startsWith("SELECT * FROM account_tenant_capacity_evaluations ")) - throw new AssertionError(sql); - Object[] values = (Object[]) invocation.getRawArguments()[1]; - return retainedCapacity.get((String) values[0]); - }); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0, String.class); + if (!sql.startsWith("SELECT * FROM account_tenant_capacity_evaluations ")) + throw new AssertionError(sql); + Object[] values = (Object[]) invocation.getRawArguments()[1]; + return retainedCapacity.get((String) values[0]); + }); var connection = mock(Connection.class); when(connection.getTransactionIsolation()).thenReturn(Connection.TRANSACTION_SERIALIZABLE); doAnswer( @@ -1124,11 +1106,10 @@ private Fixture(boolean exists, String stateScope) throws Exception { when(caller.identity()).thenReturn(identity); when(caller.currentCandidate()).thenReturn(candidate); when(callers.verifyPresentedCompactToken("controlled-token")) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return caller; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return caller; + }); Account account = new Account(); account.setId(10L); account.setAccountUuid(ACCOUNT); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwnerTest.java index 436c96b67f..bc71e34b8f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwnerTest.java @@ -77,11 +77,10 @@ void paidFactsKeepTheirActualObservationAndDeadlineWithoutReadingDemo() { void demoRevalidationCannotRenewTheOriginalObservationDeadline() { Fixture f = new Fixture(SourceKind.NON_PAID_DEMO); when(f.demos.revalidate(f.demo)) - .thenAnswer( - invocation -> { - f.time.set(NOW.plusSeconds(7)); - return f.demo; - }); + .thenAnswer(invocation -> { + f.time.set(NOW.plusSeconds(7)); + return f.demo; + }); var value = f.owner.evaluate(TENANT); assertThat(value.sourceKind()).isEqualTo(SourceKind.NON_PAID_DEMO); assertThat(value.evaluatedAt()).isEqualTo(NOW); @@ -121,11 +120,10 @@ void paidFailureNeverFallsBackToRetainedDemo() { void expiredDemoObservationAndFinalCommitFailureExposeNoValue() { Fixture f = new Fixture(SourceKind.NON_PAID_DEMO); when(f.demos.revalidate(f.demo)) - .thenAnswer( - invocation -> { - f.time.set(NOW.plusSeconds(15)); - return f.demo; - }); + .thenAnswer(invocation -> { + f.time.set(NOW.plusSeconds(15)); + return f.demo; + }); assertThatThrownBy(() -> f.owner.evaluate(TENANT)) .isInstanceOf(AccountPublicBootstrapEntitlementOwner.UnavailableException.class); Fixture failedCommit = new Fixture(SourceKind.NON_PAID_DEMO); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java index e718012026..e9f746caf1 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapWorldsOwnerTest.java @@ -161,13 +161,12 @@ void expiredEntitlementDuringFinalCollectionReadRefusesTheWholeList() { Fixture f = new Fixture(); Target target = target(TENANT_A, "tenant-a", "world", "World", 1); when(f.targets.listVisiblePublicProductionAdmissionTargets(any())) - .thenAnswer( - invocation -> { - f.readCount++; - if (f.readCount == 1) return f.evidence(List.of(target)); - f.time.set(NOW.plusSeconds(15)); - return f.evidence(List.of(target)); - }); + .thenAnswer(invocation -> { + f.readCount++; + if (f.readCount == 1) return f.evidence(List.of(target)); + f.time.set(NOW.plusSeconds(15)); + return f.evidence(List.of(target)); + }); when(f.entitlements.evaluate(TENANT_A)) .thenReturn(evaluation(TENANT_A, true, NOW.plusSeconds(15))); @@ -280,14 +279,9 @@ void independentTenantEvaluationsOverlapWithEightWorkerBoundAndNoAmbientContexts var tenants = IntStream.range(0, 24).mapToObj(index -> UUID.randomUUID()).toList(); var targets = IntStream.range(0, tenants.size()) - .mapToObj( - index -> - target( - tenants.get(index), - "tenant-" + index, - "world-" + index, - "World " + index, - 1)) + .mapToObj(index -> + target( + tenants.get(index), "tenant-" + index, "world-" + index, "World " + index, 1)) .toList(); f.stubTargetReads(targets, targets.reversed()); var firstWave = new CountDownLatch(8); @@ -295,23 +289,22 @@ void independentTenantEvaluationsOverlapWithEightWorkerBoundAndNoAmbientContexts var active = new AtomicInteger(); var peak = new AtomicInteger(); when(f.entitlements.evaluate(any())) - .thenAnswer( - invocation -> { - int current = active.incrementAndGet(); - peak.accumulateAndGet(current, Math::max); - try { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); - if (entered.incrementAndGet() <= 8) { - firstWave.countDown(); - assertThat(firstWave.await(5, TimeUnit.SECONDS)).isTrue(); - } - return evaluation(invocation.getArgument(0), true, NOW.plusSeconds(15)); - } finally { - active.decrementAndGet(); - } - }); + .thenAnswer(invocation -> { + int current = active.incrementAndGet(); + peak.accumulateAndGet(current, Math::max); + try { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + if (entered.incrementAndGet() <= 8) { + firstWave.countDown(); + assertThat(firstWave.await(5, TimeUnit.SECONDS)).isTrue(); + } + return evaluation(invocation.getArgument(0), true, NOW.plusSeconds(15)); + } finally { + active.decrementAndGet(); + } + }); assertThat(f.owner.listWorlds(TOKEN)).hasSize(24); assertThat(peak.get()).isEqualTo(8); assertThat(entered.get()).isEqualTo(24); @@ -342,14 +335,9 @@ void simultaneousDiscoveryCallsAcrossOwnerInstancesShareTheEightEvaluationLimit( var tenants = IntStream.range(0, 16).mapToObj(index -> UUID.randomUUID()).toList(); var targets = IntStream.range(0, tenants.size()) - .mapToObj( - index -> - target( - tenants.get(index), - "tenant-" + index, - "world-" + index, - "World " + index, - 1)) + .mapToObj(index -> + target( + tenants.get(index), "tenant-" + index, "world-" + index, "World " + index, 1)) .toList(); first.stubTargetReads(targets, targets); second.stubTargetReads(targets, targets); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java index 0b811bf47e..3fb9605d9d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantCapacityOwnerTest.java @@ -80,13 +80,12 @@ void sharedRejectedUsageVectorsReachAccountReservationGuardWithoutWrites() throw request.requireCommittable(); TransactionSynchronizationManager.setActualTransactionActive(true); try { - assertThatThrownBy( - () -> - new AccountTenantCapacityRepository(dsl) - .create( - request, - request.evidence().expiresAt(), - Clock.fixed(request.evidence().evaluatedAt(), ZoneOffset.UTC))) + assertThatThrownBy(() -> + new AccountTenantCapacityRepository(dsl) + .create( + request, + request.evidence().expiresAt(), + Clock.fixed(request.evidence().evaluatedAt(), ZoneOffset.UTC))) .as(vector.path("name").asText()) .hasMessage(vector.path("expected").asText()); verify(dsl, never()).execute(anyString(), any(Object[].class)); @@ -104,17 +103,15 @@ void expiryWhileWaitingForUsageDoesNotReserveCapacity() { Clock clock = mock(Clock.class); when(clock.instant()).thenThrow(new AssertionError("read before acquiring usage row")); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - org.mockito.Mockito.doReturn(request.evidence().expiresAt()).when(clock).instant(); - return mock(Record.class); - }); + .thenAnswer(invocation -> { + org.mockito.Mockito.doReturn(request.evidence().expiresAt()).when(clock).instant(); + return mock(Record.class); + }); TransactionSynchronizationManager.setActualTransactionActive(true); - assertThatThrownBy( - () -> - new AccountTenantCapacityRepository(dsl) - .create(request, request.evidence().expiresAt(), clock)) + assertThatThrownBy(() -> + new AccountTenantCapacityRepository(dsl) + .create(request, request.evidence().expiresAt(), clock)) .isInstanceOfSatisfying( AccountTenantCapacityRepository.CapacityException.class, failure -> assertThat(failure.code()).isEqualTo(Failure.CAPACITY_ADMISSION_STALE)); @@ -139,11 +136,10 @@ void repeatedSerializationFailuresRetryAndReplayInAFreshTransaction() throws Exc var aborted = serializationFailure(); var abortedAttempts = new AtomicInteger(); when(f.accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) - .thenAnswer( - invocation -> { - if (abortedAttempts.incrementAndGet() == 2) f.existing = true; - throw aborted; - }); + .thenAnswer(invocation -> { + if (abortedAttempts.incrementAndGet() == 2) f.existing = true; + throw aborted; + }); assertThat(f.owner.commit(f.request, f.request.evidence().callerWorkload()).reservationId()) .isEqualTo(f.reservation); @@ -176,17 +172,14 @@ void cancelledCallDoesNotRetryAnAbortedTransaction() throws Exception { var aborted = serializationFailure(); try (var caller = Context.current().withCancellation()) { when(f.accounts.findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT)) - .thenAnswer( - invocation -> { - caller.cancel(null); - throw aborted; - }); - - caller.run( - () -> - assertThatThrownBy( - () -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) - .isSameAs(aborted)); + .thenAnswer(invocation -> { + caller.cancel(null); + throw aborted; + }); + + caller.run(() -> + assertThatThrownBy(() -> f.owner.commit(f.request, f.request.evidence().callerWorkload())) + .isSameAs(aborted)); } verify(f.accounts).findByAccountUuidForUpdate(CapacityAdmissionTestFixture.ACCOUNT); verify(f.dsl, never()).execute(anyString(), any(Object[].class)); @@ -427,12 +420,11 @@ void nonCreatingEvidenceCannotStartRecoveryOrRearmWork() throws Exception { .withDigest(); assertThatThrownBy(() -> recovery.rearm(f.request, next)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - recovery.reconcile( - denied, - net.firedevops.firemud.accountservice.service - .AccountTenantCapacityRecoveryWorker.NoCommitAction.RETAIN_FOR_REARM)) + assertThatThrownBy(() -> + recovery.reconcile( + denied, + net.firedevops.firemud.accountservice.service.AccountTenantCapacityRecoveryWorker + .NoCommitAction.RETAIN_FOR_REARM)) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(f.accounts, f.dsl, f.memberships, f.issuances, f.scopes, source); } @@ -504,18 +496,17 @@ private Fixture(boolean expired, Request request, String namespace) throws Excep when(evaluation.get("expires_at", java.time.OffsetDateTime.class)) .thenReturn(AccountTenantCapacityRepository.at(evidence.expiresAt())); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0, String.class); - if (sql.startsWith("SELECT * FROM account_tenant_capacity_reservations ")) - return existing ? row : null; - if (sql.startsWith( - "SELECT snapshot_identity FROM account_tenant_capacity_evaluations ")) - return evaluation; - if (sql.startsWith("SELECT * FROM account_tenant_capacity_evaluations ")) - return retained ? evaluation : null; - throw new AssertionError(sql); - }); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0, String.class); + if (sql.startsWith("SELECT * FROM account_tenant_capacity_reservations ")) + return existing ? row : null; + if (sql.startsWith( + "SELECT snapshot_identity FROM account_tenant_capacity_evaluations ")) + return evaluation; + if (sql.startsWith("SELECT * FROM account_tenant_capacity_evaluations ")) + return retained ? evaluation : null; + throw new AssertionError(sql); + }); owner = new AccountTenantCapacityOwner( dsl, diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerTest.java index c2c35caf09..96cf1f4c97 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountTenantOperationEntitlementOwnerTest.java @@ -53,18 +53,15 @@ void demoUsesIndependentWritableSerializableTransactionAndPropagatesFiveSecondJd // This driver is controlled; the PostgreSQL suite proves physical connection isolation. var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); when(demos.readCurrent(tenantId)) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) - .isFalse(); - dsl.connection( - current -> - assertThat(current.getTransactionIsolation()) - .isEqualTo(Connection.TRANSACTION_SERIALIZABLE)); - dsl.execute("SELECT 1"); - throw new AssertionError("The controlled source statement must time out"); - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + dsl.connection(current -> + assertThat(current.getTransactionIsolation()) + .isEqualTo(Connection.TRANSACTION_SERIALIZABLE)); + dsl.execute("SELECT 1"); + throw new AssertionError("The controlled source statement must time out"); + }); var owner = new AccountTenantOperationEntitlementOwner( hosting, demos, transactions, Clock.systemUTC(), "prod"); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredCredentialCleanupJobTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredCredentialCleanupJobTest.java index 622251012d..e0f64ada35 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredCredentialCleanupJobTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredCredentialCleanupJobTest.java @@ -118,9 +118,8 @@ void cleanupPublishesOldestExpiredRowLagWithoutCredentialMaterial() { when(emailVerification.deleteExpired(any(), eq(5))).thenReturn(0); when(emailLoginChallenge.deleteExpired(any(), eq(5))).thenReturn(0); when(passwordReset.findOldestExpiredAt(any())) - .thenAnswer( - invocation -> - Optional.of(invocation.getArgument(0, LocalDateTime.class).minusSeconds(7))); + .thenAnswer(invocation -> + Optional.of(invocation.getArgument(0, LocalDateTime.class).minusSeconds(7))); when(emailVerification.findOldestExpiredAt(any())).thenReturn(Optional.empty()); when(emailLoginChallenge.findOldestExpiredAt(any())).thenReturn(Optional.empty()); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); @@ -266,21 +265,14 @@ void cleanupConfigurationMustBePositive() { mock(AccountEmailLoginChallengeRepository.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - assertThatThrownBy( - () -> - new ExpiredCredentialCleanupJob( - passwordReset, - emailVerification, - emailLoginChallenge, - meterRegistry, - 0, - 60_000)) + assertThatThrownBy(() -> + new ExpiredCredentialCleanupJob( + passwordReset, emailVerification, emailLoginChallenge, meterRegistry, 0, 60_000)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("batch-size"); - assertThatThrownBy( - () -> - new ExpiredCredentialCleanupJob( - passwordReset, emailVerification, emailLoginChallenge, meterRegistry, 1, 0)) + assertThatThrownBy(() -> + new ExpiredCredentialCleanupJob( + passwordReset, emailVerification, emailLoginChallenge, meterRegistry, 1, 0)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("interval-ms"); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentServiceTest.java index cc3908be00..96d712586e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentServiceTest.java @@ -106,39 +106,34 @@ void exactOwnerEvidenceIsImportedReadBackAndGenerationInitializedInsideOneTransa new java.util.concurrent.atomic.AtomicBoolean(); when(client.resolveCreation(REQUEST_ID, REQUEST_DIGEST)).thenReturn(evidence); when(associations.importVerified(evidence)) - .thenAnswer( - invocation -> { - assertThat(transactionActive.get()).isTrue(); - return evidence; - }); + .thenAnswer(invocation -> { + assertThat(transactionActive.get()).isTrue(); + return evidence; + }); when(associations.read(evidence.canonicalTenantId())) - .thenAnswer( - invocation -> { - assertThat(transactionActive.get()).isTrue(); - return java.util.Optional.of(evidence); - }); + .thenAnswer(invocation -> { + assertThat(transactionActive.get()).isTrue(); + return java.util.Optional.of(evidence); + }); when(generations.initializeTenantIfAbsent(evidence.canonicalTenantId())) - .thenAnswer( - invocation -> { - assertThat(transactionActive.get()).isTrue(); - return new ScopeState( - AuthorityScope.tenant(evidence.canonicalTenantId()), 1L, 1L, null); - }); + .thenAnswer(invocation -> { + assertThat(transactionActive.get()).isTrue(); + return new ScopeState(AuthorityScope.tenant(evidence.canonicalTenantId()), 1L, 1L, null); + }); when(transaction.execute( ArgumentMatchers .> any())) - .thenAnswer( - invocation -> { - transactionActive.set(true); - try { - return ((TransactionCallback) invocation.getArgument(0)) - .doInTransaction(mock(TransactionStatus.class)); - } finally { - transactionActive.set(false); - } - }); + .thenAnswer(invocation -> { + transactionActive.set(true); + try { + return ((TransactionCallback) invocation.getArgument(0)) + .doInTransaction(mock(TransactionStatus.class)); + } finally { + transactionActive.set(false); + } + }); FreshTenantIdentityEnrollmentService service = new FreshTenantIdentityEnrollmentService(client, associations, generations, transaction); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java index 3aae3e801b..bb6055e89e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java @@ -1937,16 +1937,13 @@ void listPresenceVisibilityPoliciesResolvesAndReturnsCanonicalUuidKeysForSocialP .collect(java.util.stream.Collectors.toSet())); assertTrue( observer.response().getPoliciesList().stream() - .anyMatch( - entry -> - entry.getAccountId().equals(ACCOUNT_UUID) - && entry.getPolicy().equals("PRIVATE"))); + .anyMatch(entry -> + entry.getAccountId().equals(ACCOUNT_UUID) && entry.getPolicy().equals("PRIVATE"))); assertTrue( observer.response().getPoliciesList().stream() - .anyMatch( - entry -> - entry.getAccountId().equals(OTHER_ACCOUNT_UUID) - && entry.getPolicy().equals("HIDDEN_STAFF"))); + .anyMatch(entry -> + entry.getAccountId().equals(OTHER_ACCOUNT_UUID) + && entry.getPolicy().equals("HIDDEN_STAFF"))); assertTrue(observer.completed()); assertFalse(observer.receivedTransportError()); Mockito.verify(accountService) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java index aff5196fda..e1f542b6ac 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java @@ -117,11 +117,10 @@ void rejectsRetainedPreparedRecoveryBeforeDispatchWhenCoordinatorIsAbsent() { Observer observer = new Observer<>(); authenticate(TRUST) - .run( - () -> - service.getCurrentPromotionRequest( - GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build(), - observer)); + .run(() -> + service.getCurrentPromotionRequest( + GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build(), + observer)); assertFailedPrecondition(observer.failure); verify(repository, never()).readPreparedGenerationForRecovery(any(), any()); @@ -215,9 +214,8 @@ void recordsPrivatePromotionResultAndReconcilesWhenCoordinatorIsConfigured() { assertThat(observer.value.getPublicReceiptDigest()).isEqualTo(receipt.receiptDigest()); verify(coordinator) .reconcilePreparedPromotionOnce( - org.mockito.ArgumentMatchers.argThat( - (PrivatePromotionObservation observation) -> - observation.promotionOperationId().equals(promotionOperationId)), + org.mockito.ArgumentMatchers.argThat((PrivatePromotionObservation observation) -> + observation.promotionOperationId().equals(promotionOperationId)), org.mockito.ArgumentMatchers.eq(receipt)); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java index ee0851233d..42eff5f790 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java @@ -330,11 +330,10 @@ void bootstrapRealmsKeepsPlayerContextForTheComposedOwnersWorkloadGuard() { service.setCanonicalPublicRealmScopeOwner(owner); SessionContext.setContext("e9e3aa54-9712-4e01-8767-f23f3c662e64", List.of(), Map.of()); when(owner.listRealmScopes("bootstrap", "source-tenant", "demo")) - .thenAnswer( - invocation -> { - assertTrue(SessionContext.hasAuthenticatedCallerContext()); - throw new IllegalStateException("Canonical source requires workload-only context"); - }); + .thenAnswer(invocation -> { + assertTrue(SessionContext.hasAuthenticatedCallerContext()); + throw new IllegalStateException("Canonical source requires workload-only context"); + }); try { assertThrows( IllegalStateException.class, @@ -452,10 +451,9 @@ private enum IdentityFailure { private static java.util.stream.Stream ordinaryIssuanceIdentityFailures() { return java.util.Arrays.stream(OrdinaryIssuance.values()) - .flatMap( - mode -> - java.util.Arrays.stream(IdentityFailure.values()) - .map(failure -> org.junit.jupiter.params.provider.Arguments.of(mode, failure))); + .flatMap(mode -> + java.util.Arrays.stream(IdentityFailure.values()) + .map(failure -> org.junit.jupiter.params.provider.Arguments.of(mode, failure))); } @ParameterizedTest @@ -780,15 +778,14 @@ void createAccountPersistsOnlyGlobalIdentity() { new CreateAccountRequest("demo", " DEMO@example.com ", "password"); UUID accountUuid = UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b"); when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) - .thenAnswer( - invocation -> { - Account saved = invocation.getArgument(0); - saved.setId(1L); - saved.setAccountUuid(accountUuid); - saved.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); - saved.setAccountUuidSourceNumericId(1L); - return saved; - }); + .thenAnswer(invocation -> { + Account saved = invocation.getArgument(0); + saved.setId(1L); + saved.setAccountUuid(accountUuid); + saved.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + saved.setAccountUuidSourceNumericId(1L); + return saved; + }); AccountDto dto = service.createAccount(request); @@ -812,15 +809,14 @@ void createAccountPersistsOnlyGlobalIdentity() { @Test void createAccountRejectsPublicIdentityWithoutExactPersistedSourceRow() { when(accountRepository.save(org.mockito.ArgumentMatchers.any(Account.class))) - .thenAnswer( - invocation -> { - Account saved = invocation.getArgument(0); - saved.setId(1L); - saved.setAccountUuid(UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b")); - saved.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); - saved.setAccountUuidSourceNumericId(2L); - return saved; - }); + .thenAnswer(invocation -> { + Account saved = invocation.getArgument(0); + saved.setId(1L); + saved.setAccountUuid(UUID.fromString("4cae05e8-7a6b-4b14-9d44-665e3eec450b")); + saved.setAccountUuidProvenance(AccountIdentityProvenance.ACCOUNT_REPOSITORY_INSERT); + saved.setAccountUuidSourceNumericId(2L); + return saved; + }); assertThrows( IllegalStateException.class, @@ -1232,18 +1228,16 @@ void canonicalJoinOutageKeepsTheIntentRetryableAndRecoversTheSameRequest(String when(f.demos.revalidate(f.demo)).thenThrow(unavailable).thenReturn(f.demo); case "member" -> org.mockito.Mockito.doThrow(unavailable) - .doAnswer( - invocation -> - f.joined.get() ? Optional.of(f.currentMembership) : Optional.empty()) + .doAnswer(invocation -> + f.joined.get() ? Optional.of(f.currentMembership) : Optional.empty()) .when(accountTenantMembershipRepository) .findFreshMembershipForUpdate(f.scope.accountId(), f.scope.tenantId()); case "terminal" -> org.mockito.Mockito.doThrow(unavailable) - .doAnswer( - invocation -> { - f.joined.set(true); - return f.committed; - }) + .doAnswer(invocation -> { + f.joined.set(true); + return f.committed; + }) .when(f.terminal) .commitCanonicalJoin(f.scope, f.requestId, f.binding, null, null, null); default -> throw new AssertionError(stage); @@ -1311,10 +1305,8 @@ void canonicalJoinChangedTargetBetweenStrictReadsIsTerminalWithoutMembershipEffe org.mockito.Mockito.mock(Target.class, org.mockito.AdditionalAnswers.delegatesTo(f.target)); when(changed.activeWorldEpoch()).thenReturn(2L); var reads = new java.util.concurrent.atomic.AtomicInteger(); - org.mockito.Mockito.doAnswer( - invocation -> - f.resolve( - invocation.getArgument(0), reads.incrementAndGet() == 1 ? f.target : changed)) + org.mockito.Mockito.doAnswer(invocation -> + f.resolve(invocation.getArgument(0), reads.incrementAndGet() == 1 ? f.target : changed)) .when(f.targets) .resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any()); assertEquals( @@ -1472,10 +1464,9 @@ void canonicalJoinExpiryAtCommitGatesDoesNotRewritePendingIntent(boolean afterCo var f = canonicalJoinFixture(); var clock = org.mockito.Mockito.mock(Clock.class); when(clock.instant()) - .thenAnswer( - invocation -> - Instant.parse(f.scope.evaluatedAt()) - .plusSeconds(!afterCoordinator || f.joined.get() ? 120 : 1)); + .thenAnswer(invocation -> + Instant.parse(f.scope.evaluatedAt()) + .plusSeconds(!afterCoordinator || f.joined.get() ? 120 : 1)); f.compose(clock); assertEquals( @@ -1512,9 +1503,8 @@ void canonicalJoinReturnsCommittedReceiptWhenScopeExpiresAfterCommit() { var committed = new AtomicBoolean(); var clock = org.mockito.Mockito.mock(Clock.class); when(clock.instant()) - .thenAnswer( - invocation -> - Instant.parse(f.scope.evaluatedAt()).plusSeconds(committed.get() ? 120 : 1)); + .thenAnswer(invocation -> + Instant.parse(f.scope.evaluatedAt()).plusSeconds(committed.get() ? 120 : 1)); f.compose(clock); org.mockito.Mockito.doAnswer( invocation -> { @@ -1676,11 +1666,10 @@ void canonicalDirectJoinUsesTheSameTerminalOwnerAndUuidTargetWithoutBootstrapSes org.mockito.Mockito.clearInvocations(sessionService); var result = canonicalGameSessionPeer() - .call( - () -> - service.joinPublicProductionFromGameSession( - caller, - new JoinPublicProductionRequest(f.scope.connectScopeId(), f.requestId))); + .call(() -> + service.joinPublicProductionFromGameSession( + caller, + new JoinPublicProductionRequest(f.scope.connectScopeId(), f.requestId))); assertTrue(result.success()); assertEquals(f.scope.tenantId(), result.tenantId()); assertFalse(result.replayed()); @@ -1708,15 +1697,14 @@ void canonicalDirectJoinRejectsWrongWorkloadBeforeReadingScope(String mismatch) } assertEquals( "AUTH_UNAVAILABLE", - peer.call( - () -> - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProductionFromGameSession( - f.directCaller(f.requestId), - new JoinPublicProductionRequest( - f.scope.connectScopeId(), f.requestId)))) + peer.call(() -> + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProductionFromGameSession( + f.directCaller(f.requestId), + new JoinPublicProductionRequest( + f.scope.connectScopeId(), f.requestId)))) .getCode()); verifyNoInteractions(f.reader, accountJoinOperationRepository, f.terminal); } @@ -1739,15 +1727,14 @@ void canonicalDirectJoinRejectsAnyCallerTargetMismatchBeforeIntent(String field) assertEquals( "CONNECT_SCOPE_MISMATCH", canonicalGameSessionPeer() - .call( - () -> - assertThrows( - AuthenticationException.class, - () -> - service.joinPublicProductionFromGameSession( - caller, - new JoinPublicProductionRequest( - f.scope.connectScopeId(), f.requestId)))) + .call(() -> + assertThrows( + AuthenticationException.class, + () -> + service.joinPublicProductionFromGameSession( + caller, + new JoinPublicProductionRequest( + f.scope.connectScopeId(), f.requestId)))) .getCode()); verifyNoInteractions(accountJoinOperationRepository, f.terminal); } @@ -1893,43 +1880,42 @@ private CanonicalJoinFixture(String requestId) { when(targets.resolvePublishedRealmAdmissionTarget(org.mockito.ArgumentMatchers.any())) .thenAnswer(invocation -> resolve(invocation.getArgument(0), target)); when(targets.readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - var strict = - invocation.getArgument( - 0, - net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence - .Request.class); - Target currentTarget = resolvedTarget; - long activeWorldEpoch = currentTarget.activeWorldEpoch(); - var published = - org.mockito.Mockito.mock( - net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence - .class); - when(published.selector()).thenReturn(strict); - when(published.currentTarget()).thenReturn(currentTarget); - var sourceEvidence = - org.mockito.Mockito.mock( - net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence - .class); - when(sourceEvidence.request()).thenReturn(strict); - var policies = - org.mockito.Mockito.mock( - net.firedevops.firemud.common.publication - .PublishedRealmEntryPolicySetEvidence.class); - when(policies.canonicalBytes()).thenReturn(policyBytes); - when(sourceEvidence.publishedPolicySetEvidence()).thenReturn(policies); - when(published.sourceEvidence()).thenReturn(sourceEvidence); - var world = - org.mockito.Mockito.mock( - net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence - .class); - when(world.lifecycleStatus()).thenReturn("ACTIVE"); - when(world.lifecycleEpoch()).thenReturn(activeWorldEpoch); - when(published.worldLifecycleEvidence()).thenReturn(world); - return published; - }); + .thenAnswer(invocation -> { + var strict = + invocation.getArgument( + 0, + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence + .Request.class); + Target currentTarget = resolvedTarget; + long activeWorldEpoch = currentTarget.activeWorldEpoch(); + var published = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence + .class); + when(published.selector()).thenReturn(strict); + when(published.currentTarget()).thenReturn(currentTarget); + var sourceEvidence = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence + .class); + when(sourceEvidence.request()).thenReturn(strict); + var policies = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence + .class); + when(policies.canonicalBytes()).thenReturn(policyBytes); + when(sourceEvidence.publishedPolicySetEvidence()).thenReturn(policies); + when(published.sourceEvidence()).thenReturn(sourceEvidence); + var world = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence + .class); + when(world.lifecycleStatus()).thenReturn("ACTIVE"); + when(world.lifecycleEpoch()).thenReturn(activeWorldEpoch); + when(published.worldLifecycleEvidence()).thenReturn(world); + return published; + }); when(pending.status()).thenReturn("PENDING"); when(accountJoinOperationRepository.findCanonicalEvidenceForUpdateByRequestId(requestId)) .thenReturn(Optional.of(pending)); @@ -1963,11 +1949,10 @@ private CanonicalJoinFixture(String requestId) { org.mockito.ArgumentMatchers.isNull(), org.mockito.ArgumentMatchers.isNull(), org.mockito.ArgumentMatchers.isNull())) - .thenAnswer( - invocation -> { - joined.set(true); - return committed; - }); + .thenAnswer(invocation -> { + joined.set(true); + return committed; + }); service.setAccountBootstrapRosterReadClient(roster); compose(Clock.fixed(now.plusSeconds(1), java.time.ZoneOffset.UTC)); } @@ -2086,10 +2071,9 @@ private DirectTextCallerContext directCaller(String id) { assertEquals(List.of(12, 37), actors.stream().map(value -> value.level()).toList()); assertTrue( actors.stream() - .allMatch( - value -> - "SHARED".equals(value.stateScope()) - && "PRESEEDED_ONLY".equals(value.characterCreationPolicy()))); + .allMatch(value -> + "SHARED".equals(value.stateScope()) + && "PRESEEDED_ONLY".equals(value.characterCreationPolicy()))); var target = org.mockito.ArgumentCaptor.forClass( net.firedevops.firemud.common.gamesession @@ -2268,13 +2252,12 @@ void canonicalBootstrapCharactersRejectsTargetDriftDuringEntityReadInsteadOfRetu org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - drift.set(true); - return List.of( - new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient - .Actor(UUID.randomUUID(), "Ada", 12)); - }); + .thenAnswer(invocation -> { + drift.set(true); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Ada", 12)); + }); assertEquals( "CONNECT_SCOPE_MISMATCH", assertThrows(AuthenticationException.class, f::characters).getCode()); @@ -2289,14 +2272,13 @@ void canonicalBootstrapCharactersRechecksMembershipAfterEntityRead() { org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - f.currentMembership.setLifecycleState("INACTIVE"); - f.currentMembership.setGameplayAdmissionAllowed(false); - return List.of( - new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient - .Actor(UUID.randomUUID(), "Ada", 12)); - }); + .thenAnswer(invocation -> { + f.currentMembership.setLifecycleState("INACTIVE"); + f.currentMembership.setGameplayAdmissionAllowed(false); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Ada", 12)); + }); var failure = assertThrows(AuthenticationException.class, f::characters); assertEquals("AUTH_UNAVAILABLE", failure.getCode()); assertEquals("Bootstrap membership changed during discovery", failure.getMessage()); @@ -2317,22 +2299,21 @@ void canonicalBootstrapCharactersRejectsChangedMembershipSnapshotAfterEntityRead org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - switch (changed) { - case "version" -> - f.currentMembership.setMembershipVersion( - f.currentMembership.getMembershipVersion() + 1L); - case "generation" -> - f.currentMembership.setMembershipAuthorityGeneration( - f.currentMembership.getMembershipAuthorityGeneration() + 1L); - case "membership-id" -> f.currentMembership.setId(702L); - default -> throw new AssertionError(changed); - } - return List.of( - new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient - .Actor(UUID.randomUUID(), "Withheld", 12)); - }); + .thenAnswer(invocation -> { + switch (changed) { + case "version" -> + f.currentMembership.setMembershipVersion( + f.currentMembership.getMembershipVersion() + 1L); + case "generation" -> + f.currentMembership.setMembershipAuthorityGeneration( + f.currentMembership.getMembershipAuthorityGeneration() + 1L); + case "membership-id" -> f.currentMembership.setId(702L); + default -> throw new AssertionError(changed); + } + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Withheld", 12)); + }); assertEquals( "AUTH_UNAVAILABLE", assertThrows(AuthenticationException.class, f::characters).getCode()); verifyNoInteractions(accountJoinOperationRepository, accountAuditOutboxRepository); @@ -2346,14 +2327,13 @@ void canonicalBootstrapCharactersRejectsChangedPublishedPolicyCaptureAfterEntity org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - f.policyBytes = - "changed-controlled-policy-set".getBytes(java.nio.charset.StandardCharsets.UTF_8); - return List.of( - new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient - .Actor(UUID.randomUUID(), "Withheld", 12)); - }); + .thenAnswer(invocation -> { + f.policyBytes = + "changed-controlled-policy-set".getBytes(java.nio.charset.StandardCharsets.UTF_8); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Withheld", 12)); + }); assertEquals( "CONNECT_SCOPE_MISMATCH", assertThrows(AuthenticationException.class, f::characters).getCode()); @@ -2368,18 +2348,15 @@ void canonicalBootstrapCharactersRechecksCurrentEntitlementAfterEntityRead() { org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - when(f.demos.readCurrent(f.scope.tenantId())) - .thenThrow( - new DataAccessResourceFailureException("controlled late billing outage")); - when(f.demos.revalidate(f.demo)) - .thenThrow( - new DataAccessResourceFailureException("controlled late billing outage")); - return List.of( - new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient - .Actor(UUID.randomUUID(), "Ada", 12)); - }); + .thenAnswer(invocation -> { + when(f.demos.readCurrent(f.scope.tenantId())) + .thenThrow(new DataAccessResourceFailureException("controlled late billing outage")); + when(f.demos.revalidate(f.demo)) + .thenThrow(new DataAccessResourceFailureException("controlled late billing outage")); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Ada", 12)); + }); assertEquals( "ENTITLEMENT_UNAVAILABLE", assertThrows(AuthenticationException.class, f::characters).getCode()); @@ -2428,13 +2405,12 @@ public Instant instant() { org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - time.set(Instant.parse(f.scope.connectScopeExpiresAt())); - return List.of( - new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient - .Actor(UUID.randomUUID(), "Ada", 12)); - }); + .thenAnswer(invocation -> { + time.set(Instant.parse(f.scope.connectScopeExpiresAt())); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Ada", 12)); + }); assertEquals( "CONNECT_SCOPE_INVALID", assertThrows(AuthenticationException.class, f::characters).getCode()); @@ -2484,14 +2460,13 @@ void canonicalBootstrapCharactersRechecksTheBrowserRegistryAfterEntityRead() { org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - when(sessionService.isAccountSessionActive(f.account.getId(), f.bootstrap)) - .thenReturn(false); - return List.of( - new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient - .Actor(UUID.randomUUID(), "Withheld", 12)); - }); + .thenAnswer(invocation -> { + when(sessionService.isAccountSessionActive(f.account.getId(), f.bootstrap)) + .thenReturn(false); + return List.of( + new net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient + .Actor(UUID.randomUUID(), "Withheld", 12)); + }); assertEquals( "CONNECT_CONTEXT_INVALID", assertThrows(AuthenticationException.class, f::characters).getCode()); @@ -2555,18 +2530,17 @@ void canonicalBootstrapCharactersRejectsUnsupportedPolicyFromLateControlledOwner // Retained resolution admits PRESEEDED_ONLY only. Change this controlled owner response // after that check to exercise the facade's own unsupported-policy refusal, not the codec. when(f.targets.readPublishedRealmAdmissionOwner(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - when(f.target.characterCreationPolicy()).thenReturn(policy); - var published = - org.mockito.Mockito.mock( - net.firedevops.firemud.common.gamesession - .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence - .class); - when(published.selector()).thenReturn(invocation.getArgument(0)); - when(published.currentTarget()).thenReturn(f.target); - return published; - }); + .thenAnswer(invocation -> { + when(f.target.characterCreationPolicy()).thenReturn(policy); + var published = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamesession + .CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence + .class); + when(published.selector()).thenReturn(invocation.getArgument(0)); + when(published.currentTarget()).thenReturn(f.target); + return published; + }); var failure = assertThrows(AuthenticationException.class, f::characters); assertEquals("REALM_UNAVAILABLE", failure.getCode()); assertEquals( @@ -2613,13 +2587,12 @@ void emailLoginOtpRequestPersistsOnlyHashedChallengeAndSendsSixDigitCode() { when(accountRepository.findByEmail("verified@example.com")).thenReturn(Optional.of(account)); when(accountEmailLoginChallengeRepository.findByAccountId(9L)).thenReturn(Optional.empty()); when(accountEmailLoginChallengeRepository.save(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> { - net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = - invocation.getArgument(0); - challenge.setId(3L); - return challenge; - }); + .thenAnswer(invocation -> { + net.firedevops.firemud.accountservice.entity.AccountEmailLoginChallenge challenge = + invocation.getArgument(0); + challenge.setId(3L); + return challenge; + }); service.requestEmailLoginOtp("verified@example.com"); @@ -4349,11 +4322,10 @@ void candidatePasswordVerifierIsPreparedBeforeWritableOwnerTransactionBegins() { org.mockito.ArgumentMatchers.eq(65536), org.mockito.ArgumentMatchers.eq(1), org.mockito.ArgumentMatchers.any(char[].class))) - .thenAnswer( - invocation -> { - candidateVerifierPrepared.set(true); - return "prepared-candidate-verifier"; - }); + .thenAnswer(invocation -> { + candidateVerifierPrepared.set(true); + return "prepared-candidate-verifier"; + }); org.mockito.Mockito.doAnswer( invocation -> { assertTrue( @@ -4438,17 +4410,16 @@ void passwordResetIssuanceFenceOverflowStopsBeforeTokenPasswordOrEventMutation() org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> - sourceChanges.participate( - invocation.getArgument(0), - invocation.getArgument(1), - invocation.getArgument(2), - invocation.getArgument(3), - invocation.getArgument(4), - invocation.getArgument(5), - invocation.getArgument(6), - invocation.getArgument(7))); + .thenAnswer(invocation -> + sourceChanges.participate( + invocation.getArgument(0), + invocation.getArgument(1), + invocation.getArgument(2), + invocation.getArgument(3), + invocation.getArgument(4), + invocation.getArgument(5), + invocation.getArgument(6), + invocation.getArgument(7))); org.springframework.transaction.support.TransactionSynchronizationManager .setActualTransactionActive(true); @@ -4640,10 +4611,9 @@ void sendUsernameReminderContainsDeliveryFailure() { "demo@example.com")); assertTrue( appender.list.stream() - .anyMatch( - event -> - "Recovery email delivery failed; cause=RuntimeException" - .equals(event.getFormattedMessage()))); + .anyMatch(event -> + "Recovery email delivery failed; cause=RuntimeException" + .equals(event.getFormattedMessage()))); assertFalse( appender.list.stream() .anyMatch(event -> event.getFormattedMessage().contains("SMTP failure"))); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/LegacySubscriptionContainmentTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/LegacySubscriptionContainmentTest.java index 51af089c77..2ca984f7b0 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/LegacySubscriptionContainmentTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/LegacySubscriptionContainmentTest.java @@ -100,14 +100,13 @@ public void onCompleted() {} Context.ROOT.withValue( GrpcPeerIdentity.CONTEXT_KEY, new GrpcPeerIdentity("spiffe://firemud/ns/test/sa/" + workload, "test", workload)); - context.run( - () -> - rpc.getTenantEntitlementsForRuntime( - GetTenantEntitlementsForRuntimeRequest.newBuilder() - .setTenantId("7") - .setRequestId("retained-is-not-authority") - .build(), - observer)); + context.run(() -> + rpc.getTenantEntitlementsForRuntime( + GetTenantEntitlementsForRuntimeRequest.newBuilder() + .setTenantId("7") + .setRequestId("retained-is-not-authority") + .build(), + observer)); assertThat(response.get()).isNotNull(); assertThat(response.get().getError().getCode()).isEqualTo("ENTITLEMENT_UNAVAILABLE"); assertThat(response.get().getGameplayAvailable()).isFalse(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java index ae2986a85d..d8ec340230 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java @@ -38,12 +38,11 @@ void createPaymentIntentSetsTenantId() throws Exception { when(membershipRepository.existsByAccountIdAndTenantId(1L, 2L)).thenReturn(true); when(accountRepository.findById(1L)).thenReturn(Optional.of(account)); when(txRepo.save(any())) - .thenAnswer( - invocation -> { - PaymentTransaction tx = invocation.getArgument(0); - tx.setId(10L); - return tx; - }); + .thenAnswer(invocation -> { + PaymentTransaction tx = invocation.getArgument(0); + tx.setId(10L); + return tx; + }); when(stripeClient.calculatePlatformFee(500L)).thenReturn(25L); when(stripeClient.createPaymentIntent(500L, "usd")) .thenReturn(new StripeClient.IntentResult("pi", "secret", "pending")); @@ -92,12 +91,11 @@ void createDonationSetsFlag() throws Exception { when(membershipRepository.existsByAccountIdAndTenantId(1L, 2L)).thenReturn(true); when(accountRepository.findById(1L)).thenReturn(Optional.of(account)); when(txRepo.save(any())) - .thenAnswer( - invocation -> { - PaymentTransaction tx = invocation.getArgument(0); - tx.setId(11L); - return tx; - }); + .thenAnswer(invocation -> { + PaymentTransaction tx = invocation.getArgument(0); + tx.setId(11L); + return tx; + }); when(stripeClient.calculatePlatformFee(100L)).thenReturn(5L); when(stripeClient.createPaymentIntent(100L, "usd")) .thenReturn(new StripeClient.IntentResult("pi2", "donate", "pending")); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java index ffe6eb6ae7..e7632721f3 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java @@ -92,10 +92,9 @@ void leavesRuntimeReadInactiveWhenWorkloadNamespaceIsNotConfigured() { Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .run( - () -> - inactiveService.resolveRuntimeAccountIdentity( - request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), observer)); + .run(() -> + inactiveService.resolveRuntimeAccountIdentity( + request(ACCOUNT_ID.toString(), REQUEST_ID.toString()), observer)); assertThat(status(observer)).isEqualTo(Status.Code.PERMISSION_DENIED); verifyNoInteractions(repository); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/realm/AccountCurrentLifecycleRealmGrantReadOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/realm/AccountCurrentLifecycleRealmGrantReadOwnerTest.java index 6c51ddbe99..6ba27660f8 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/realm/AccountCurrentLifecycleRealmGrantReadOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/realm/AccountCurrentLifecycleRealmGrantReadOwnerTest.java @@ -63,14 +63,12 @@ void obtainsActualSourceOutsideSqlThenUsesBoundedReadOnlyAccountTransaction() th when(grant.receipt()).thenReturn(receipt); when(grant.active()).thenReturn(true); when(repository.readCurrent(expected, expiry)) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) - .isTrue(); - assertThat(transport.calls()).isEqualTo(1); - return Optional.of(grant); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); + assertThat(transport.calls()).isEqualTo(1); + return Optional.of(grant); + }); var result = new AccountCurrentLifecycleRealmGrantReadOwner( transport.client(), diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordinationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordinationTest.java index 7b3aa4f2c2..c4deccc015 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordinationTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCoordinationTest.java @@ -282,9 +282,8 @@ private static final class Fixture { when(commands.aclWhoami()).thenReturn("account_coord_app"); when(catalog.require(AccountControlUiRegistryContract.SCRIPT_ID)).thenReturn(descriptor); when(commands.scriptLoad(any(byte[].class))) - .thenAnswer( - invocation -> - AccountControlUiCoordination.digest("SHA-1", invocation.getArgument(0))); + .thenAnswer(invocation -> + AccountControlUiCoordination.digest("SHA-1", invocation.getArgument(0))); doReturn(1L) .when(commands) .evalsha( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java index 46b1f625da..a2512f171c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiCurrentActorVerifierTest.java @@ -177,11 +177,10 @@ void bothActorScopesRejectSubstitutedAccountCutoffAndNumericCutoffCounters() thr Map changedCheckpoint = new LinkedHashMap<>(accountCutoff(3L)); changedCheckpoint.put("outboxSequence", "1"); Fixture substituted = advancedAccountFixture(accountOnly, changedCheckpoint); - assertDenied( - () -> { - if (accountOnly) substituted.verifier.verifyAccount(substituted.compactJwt); - else substituted.verifier.verify(substituted.compactJwt, TENANT_ID); - }); + assertDenied(() -> { + if (accountOnly) substituted.verifier.verifyAccount(substituted.compactJwt); + else substituted.verifier.verify(substituted.compactJwt, TENANT_ID); + }); for (String field : List.of("accountAuthorityGeneration", "outboxSequence")) { Map numericCutoff = new LinkedHashMap<>(accountCutoff(3L)); numericCutoff.put(field, Long.parseLong((String) numericCutoff.get(field))); @@ -715,11 +714,10 @@ private Fixture( PublicJwksSnapshot jwksSnapshot = new PublicJwksSnapshot(sourceIdentity, jwksBytes); when(publicJwks.sourceIdentity()).thenReturn(sourceIdentity); when(publicJwks.load()) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return jwksSnapshot; - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return jwksSnapshot; + }); String trustBindingDigest = AccountJwtSignerMaterializerTrustBinding.computeBindingDigest( @@ -1010,14 +1008,12 @@ private Fixture( when(accountSnapshot.sources()) .thenReturn(accountSources(globalRoles, currentAccountGeneration)); when(authority.captureAccount(issuanceAccountId)) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()) - .isTrue(); - assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) - .isFalse(); - return accountSnapshot; - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + return accountSnapshot; + }); } else { configureCurrentSources( currentTenantGeneration, @@ -1029,16 +1025,15 @@ private Fixture( PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); when(transactionManager.getTransaction(any(TransactionDefinition.class))) - .thenAnswer( - invocation -> { - TransactionDefinition definition = invocation.getArgument(0); - assertThat(definition.getIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); - TransactionSynchronizationManager.setActualTransactionActive(true); - TransactionSynchronizationManager.setCurrentTransactionReadOnly( - definition.isReadOnly()); - return new SimpleTransactionStatus(); - }); + .thenAnswer(invocation -> { + TransactionDefinition definition = invocation.getArgument(0); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly( + definition.isReadOnly()); + return new SimpleTransactionStatus(); + }); doAnswer( ignored -> { TransactionSynchronizationManager.clear(); @@ -1125,11 +1120,10 @@ private void configureRegistry(byte[] activeRegistry) { when(connection.sync()).thenReturn(commands); when(commands.aclWhoami()).thenReturn(AccountControlUiRegistryReader.REQUIRED_ACL_IDENTITY); when(commands.get(any(byte[].class))) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return activeRegistry; - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return activeRegistry; + }); when(commands.pexpiretime(any(byte[].class))).thenReturn(CLEANUP_DEADLINE_MILLIS); registry = new AccountControlUiRegistryReader(() -> connection); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepositoryTest.java index 4f4a6d1170..b19e6e1b2b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceRepositoryTest.java @@ -102,20 +102,19 @@ void prepareReusesOwnerLinearizationAndAllocatesItsFenceExactlyOnce() throws Exc Instant.class, long.class); prepare.setAccessible(true); - assertThatThrownBy( - () -> - prepare.invoke( - repository, - requestId, - "spiffe://firemud/ns/test/sa/logging-admin-service", - callerContextId, - "test-mac-key", - "a".repeat(64), - authenticated, - source, - signer, - Instant.parse("2026-10-08T11:00:00Z"), - 300_000L)) + assertThatThrownBy(() -> + prepare.invoke( + repository, + requestId, + "spiffe://firemud/ns/test/sa/logging-admin-service", + callerContextId, + "test-mac-key", + "a".repeat(64), + authenticated, + source, + signer, + Instant.parse("2026-10-08T11:00:00Z"), + 300_000L)) .isInstanceOf(InvocationTargetException.class) .hasCauseInstanceOf(IllegalStateException.class); @@ -140,16 +139,15 @@ void cleanupDeadlineUsesCheckedPerIssuanceMarginAndAllowsExplicitZero() throws E void retainedLegacyIssuanceWithoutCleanupDeadlineCannotBeReinterpreted() throws Exception { Record row = mock(Record.class); when(row.get(anyString(), any(Class.class))) - .thenAnswer( - call -> - switch (call.getArgument(0, String.class)) { - case "authorization_scope" -> "TENANT"; - case "tenant_uuid" -> TENANT_ID; - case "issued_at_epoch_second" -> 1_800_000_000L; - case "expires_at_epoch_second" -> 1_800_000_300L; - case "recovery_expires_at" -> OffsetDateTime.parse("2027-01-15T08:01:00Z"); - default -> null; - }); + .thenAnswer(call -> + switch (call.getArgument(0, String.class)) { + case "authorization_scope" -> "TENANT"; + case "tenant_uuid" -> TENANT_ID; + case "issued_at_epoch_second" -> 1_800_000_000L; + case "expires_at_epoch_second" -> 1_800_000_300L; + case "recovery_expires_at" -> OffsetDateTime.parse("2027-01-15T08:01:00Z"); + default -> null; + }); var retained = stored(row); assertThatThrownBy(() -> storedExpiryMillis(retained)) @@ -190,9 +188,8 @@ void committedCurrentSourceReadDeniesMissingLegacyCleanupDeadline() { when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(row); TransactionSynchronizationManager.setActualTransactionActive(true); - assertThatThrownBy( - () -> - new AccountControlUiCommittedIssuanceRepository(dsl).readCommitted("b".repeat(64))) + assertThatThrownBy(() -> + new AccountControlUiCommittedIssuanceRepository(dsl).readCommitted("b".repeat(64))) .isInstanceOf(IllegalStateException.class); } @@ -209,30 +206,29 @@ void accountPreparationPersistsClosedAccountScopeAndGlobalRoleEvidence() throws .thenAnswer(call -> storedValues.get(call.getArgument(0, String.class))); when(dsl.execute( startsWith("INSERT INTO account_control_ui_issuance_operations"), any(Object[].class))) - .thenAnswer( - call -> { - Object[] args = (Object[]) call.getRawArguments()[1]; - storedValues.put("request_id", args[0]); - storedValues.put("operation_id", args[1]); - storedValues.put("token_jti", args[2]); - storedValues.put("account_uuid", args[3]); - storedValues.put("tenant_uuid", args[4]); - storedValues.put("authorization_scope", args[5]); - storedValues.put("caller_workload", args[6]); - storedValues.put("caller_context_id", args[7]); - storedValues.put("request_mac_key_id", args[8]); - storedValues.put("request_digest", args[9]); - storedValues.put("claims_payload", args[10]); - storedValues.put("source_payload", args[11]); - storedValues.put("bundle_payload", args[12]); - storedValues.put("signer_receipt", args[13]); - storedValues.put("issued_at_epoch_second", args[14]); - storedValues.put("expires_at_epoch_second", args[15]); - storedValues.put("registry_cleanup_deadline_epoch_millis", args[16]); - storedValues.put("recovery_expires_at", args[17]); - storedValues.put("status", "PREPARED"); - return 1; - }); + .thenAnswer(call -> { + Object[] args = (Object[]) call.getRawArguments()[1]; + storedValues.put("request_id", args[0]); + storedValues.put("operation_id", args[1]); + storedValues.put("token_jti", args[2]); + storedValues.put("account_uuid", args[3]); + storedValues.put("tenant_uuid", args[4]); + storedValues.put("authorization_scope", args[5]); + storedValues.put("caller_workload", args[6]); + storedValues.put("caller_context_id", args[7]); + storedValues.put("request_mac_key_id", args[8]); + storedValues.put("request_digest", args[9]); + storedValues.put("claims_payload", args[10]); + storedValues.put("source_payload", args[11]); + storedValues.put("bundle_payload", args[12]); + storedValues.put("signer_receipt", args[13]); + storedValues.put("issued_at_epoch_second", args[14]); + storedValues.put("expires_at_epoch_second", args[15]); + storedValues.put("registry_cleanup_deadline_epoch_millis", args[16]); + storedValues.put("recovery_expires_at", args[17]); + storedValues.put("status", "PREPARED"); + return 1; + }); when(dsl.fetchOne( startsWith("SELECT * FROM account_control_ui_issuance_operations WHERE request_id = ?"), any(Object[].class))) @@ -498,9 +494,8 @@ private static void assertCommittedMapperRejects(String scopeKind, UUID tenantId DSLContext dsl = mock(DSLContext.class); Record row = committedRow(scopeKind, tenantId, 1_800_000_300_000L); when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(row); - assertThatThrownBy( - () -> - new AccountControlUiCommittedIssuanceRepository(dsl).readCommitted("b".repeat(64))) + assertThatThrownBy(() -> + new AccountControlUiCommittedIssuanceRepository(dsl).readCommitted("b".repeat(64))) .isInstanceOf(IllegalStateException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java index aa7cb8600b..3698353037 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceWorkflowTest.java @@ -67,19 +67,16 @@ void primaryDenialCommitsAccountingBeforeThrowingAndNeverStartsIssuancePreparati "creator@example.test", "test-only-secret")) .thenThrow(denial); try (var ignored = fixture.withPeer(ISSUER)) { - assertThatThrownBy( - () -> - fixture - .service() - .issue( - fixture.request(fixture.tenant, fixture.context, "test-only-secret"), - fixture.environment)) + assertThatThrownBy(() -> + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "test-only-secret"), + fixture.environment)) .isInstanceOf(AuthenticationException.class) .hasMessage(denial.getMessage()) - .satisfies( - error -> - assertThat(((AuthenticationException) error).getCode()) - .isEqualTo(denial.getCode())); + .satisfies(error -> + assertThat(((AuthenticationException) error).getCode()).isEqualTo(denial.getCode())); } var order = inOrder(fixture.primary, fixture.transactions); order @@ -159,13 +156,12 @@ void currentSourceUnavailabilityDeniesWithoutMarkingOriginalTerminal() { .thenThrow(new IllegalStateException("test-only source unavailable")); try (var ignored = fixture.withPeer(ISSUER)) { - assertThatThrownBy( - () -> - fixture - .service() - .issue( - fixture.request(fixture.tenant, fixture.context, "test-only-secret"), - fixture.environment)) + assertThatThrownBy(() -> + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "test-only-secret"), + fixture.environment)) .isInstanceOf(IllegalStateException.class); } @@ -250,11 +246,10 @@ void accountGlobalIssuanceUsesAccountSourcesAndReturnsItsSingleOriginalCredentia when(fixture.signers.requireOriginal(any(byte[].class))).thenReturn(signer); when(fixture.cryptography.currentKeyId()).thenReturn("test-only-mac-key"); when(fixture.cryptography.requestDigest(anyString(), any(byte[].class))) - .thenAnswer( - call -> { - requestBytes.set(call.getArgument(1, byte[].class).clone()); - return "account-request-digest"; - }); + .thenAnswer(call -> { + requestBytes.set(call.getArgument(1, byte[].class).clone()); + return "account-request-digest"; + }); when(fixture.cryptography.seal(any(byte[].class), any(byte[].class), any(Instant.class))) .thenReturn(new byte[] {8}); when(fixture.cryptography.open(any(byte[].class), any(byte[].class), any(Instant.class))) @@ -392,14 +387,12 @@ void accountGlobalReplayReturnsOriginalCredentialAndCrossScopeRetriesConflict() } try (var ignored = conflict.withPeer(ISSUER)) { if (originalWasAccount) { - assertThatThrownBy( - () -> - conflict - .service() - .issue( - conflict.request( - conflict.tenant, conflict.context, "test-only-secret"), - conflict.environment)) + assertThatThrownBy(() -> + conflict + .service() + .issue( + conflict.request(conflict.tenant, conflict.context, "test-only-secret"), + conflict.environment)) .isInstanceOf(IllegalArgumentException.class); } else { assertThatThrownBy(() -> conflict.service().issueAccount(conflict.accountRequest())) @@ -429,13 +422,12 @@ void unavailableActiveRegistryReadbackDeniesWithoutTerminalizingCommittedOrigina .thenThrow(new IllegalStateException("test-only active registry unavailable")); try (var ignored = fixture.withPeer(ISSUER)) { - assertThatThrownBy( - () -> - fixture - .service() - .issue( - fixture.request(fixture.tenant, fixture.context, "test-only-secret"), - fixture.environment)) + assertThatThrownBy(() -> + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "test-only-secret"), + fixture.environment)) .isInstanceOf(IllegalStateException.class); } @@ -458,13 +450,12 @@ void missingOriginalEnvelopeCreatesRevokingIntentAndDoesNotClaimRevocationOnRegi .thenThrow(new IllegalStateException("test-only Coordination unavailable")); try (var ignored = fixture.withPeer(ISSUER)) { - assertThatThrownBy( - () -> - fixture - .service() - .issue( - fixture.request(fixture.tenant, fixture.context, "test-only-secret"), - fixture.environment)) + assertThatThrownBy(() -> + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "test-only-secret"), + fixture.environment)) .isInstanceOf(IllegalStateException.class); } @@ -474,11 +465,10 @@ void missingOriginalEnvelopeCreatesRevokingIntentAndDoesNotClaimRevocationOnRegi assertThat(sameOriginalRecord(original, originalCaptor.getValue())).isTrue(); verify(fixture.registry) .revoke( - argThat( - actual -> - "REVOKING".equals(actual.status) - && original.tokenHash.equals(actual.tokenHash) - && original.operationId.equals(actual.operationId))); + argThat(actual -> + "REVOKING".equals(actual.status) + && original.tokenHash.equals(actual.tokenHash) + && original.operationId.equals(actual.operationId))); verify(fixture.operations, never()).finishRecoveryFailure(any(), any()); } @@ -492,13 +482,12 @@ void expiredOriginalPersistsRevokingIntentBeforeUnavailableRegistryAndNeverRetur .thenThrow(new IllegalStateException("test-only Coordination unavailable")); try (var ignored = fixture.withPeer(ISSUER)) { - assertThatThrownBy( - () -> - fixture - .service() - .issue( - fixture.request(fixture.tenant, fixture.context, "test-only-secret"), - fixture.environment)) + assertThatThrownBy(() -> + fixture + .service() + .issue( + fixture.request(fixture.tenant, fixture.context, "test-only-secret"), + fixture.environment)) .isInstanceOf(IllegalStateException.class); } @@ -585,11 +574,10 @@ private static final class Fixture { Fixture(Instant recoveryExpiry) { when(transactions.getTransaction(any(TransactionDefinition.class))) - .thenAnswer( - call -> { - TransactionSynchronizationManager.setActualTransactionActive(true); - return new SimpleTransactionStatus(); - }); + .thenAnswer(call -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + }); doAnswer( call -> { TransactionSynchronizationManager.clear(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationTest.java index 315d034ec4..b9fefb9d34 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiPrimaryAuthenticationTest.java @@ -89,10 +89,9 @@ void actualPasswordProducesCanonicalActorOnlyForEligibleAccount() { () -> primary.authenticateControlUiPrimaryIdentity(account.getEmail(), "wrong-secret")) .isInstanceOf(RuntimeException.class); account.setLifecycleState(AccountLifecycleState.SECURITY_LOCKED); - assertThatThrownBy( - () -> - primary.authenticateControlUiPrimaryIdentity( - account.getEmail(), "test-only-primary-secret")) + assertThatThrownBy(() -> + primary.authenticateControlUiPrimaryIdentity( + account.getEmail(), "test-only-primary-secret")) .isInstanceOf(RuntimeException.class); } @@ -139,10 +138,9 @@ void passwordIsCheckedAgainstTheLockedCurrentRowAfterAConcurrentReset() { "USER", false)); - assertThatThrownBy( - () -> - primary.authenticateControlUiPrimaryIdentity( - account.getEmail(), "test-only-primary-secret")) + assertThatThrownBy(() -> + primary.authenticateControlUiPrimaryIdentity( + account.getEmail(), "test-only-primary-secret")) .isExactlyInstanceOf(AuthenticationException.class); assertThat( primary @@ -159,10 +157,9 @@ void changedEmailSelectorIsRejectedAfterTheAccountRowIsLocked() { current.setEmail("reassigned@example.test"); select(account, current); - assertThatThrownBy( - () -> - primary.authenticateControlUiPrimaryIdentity( - account.getEmail(), "test-only-primary-secret")) + assertThatThrownBy(() -> + primary.authenticateControlUiPrimaryIdentity( + account.getEmail(), "test-only-primary-secret")) .isExactlyInstanceOf(AuthenticationException.class); verify(mapper, never()).toDto(current); } @@ -216,10 +213,8 @@ void changedUsernameSelectedRowIsRejectedBeforeCredentialVerificationOrMapping() when(accounts.findByUsername(account.getUsername())).thenReturn(Optional.of(account)); when(accounts.findByIdForUpdate(account.getId())).thenReturn(Optional.of(current)); - assertThatThrownBy( - () -> - primary.authenticateControlUiPrimaryIdentity( - account.getUsername(), "test-only-otp")) + assertThatThrownBy(() -> + primary.authenticateControlUiPrimaryIdentity(account.getUsername(), "test-only-otp")) .isExactlyInstanceOf(AuthenticationException.class); verifyPrimaryAuthenticationDidNotStart(); } @@ -250,17 +245,15 @@ void existingUsernameFallbackStillResolvesAndLocksTheSelectedAccount() { @Test void missingAndReadOnlyTransactionDenyBeforeCredentialAccess() { TransactionSynchronizationManager.clear(); - assertThatThrownBy( - () -> - primary.authenticateControlUiPrimaryIdentity( - account.getEmail(), "test-only-primary-secret")) + assertThatThrownBy(() -> + primary.authenticateControlUiPrimaryIdentity( + account.getEmail(), "test-only-primary-secret")) .isInstanceOf(IllegalStateException.class); TransactionSynchronizationManager.setActualTransactionActive(true); TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); - assertThatThrownBy( - () -> - primary.authenticateControlUiPrimaryIdentity( - account.getEmail(), "test-only-primary-secret")) + assertThatThrownBy(() -> + primary.authenticateControlUiPrimaryIdentity( + account.getEmail(), "test-only-primary-secret")) .isInstanceOf(IllegalStateException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java index bbc6417ef8..23aa02e00c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiRegistryReaderTest.java @@ -44,10 +44,9 @@ void rejectsUnknownFieldsAndNonCanonicalBytes() throws Exception { Map missingDeadline = new LinkedHashMap<>(record()); missingDeadline.remove("registryCleanupDeadlineEpochMillis"); - assertThatThrownBy( - () -> - AccountControlUiRegistryReader.parseActiveRecord( - canonicalBytes(missingDeadline), TOKEN_HASH)) + assertThatThrownBy(() -> + AccountControlUiRegistryReader.parseActiveRecord( + canonicalBytes(missingDeadline), TOKEN_HASH)) .isInstanceOf(IllegalStateException.class); String canonical = new String(canonicalRecord(), StandardCharsets.UTF_8); @@ -110,15 +109,13 @@ void acceptsExactCleanupDeadlineAndRejectsMissingOrOutOfRangeEvidence() { assertThatThrownBy( () -> AccountControlUiRegistryReader.checkedCleanupDeadlineMillis(1_800_000_000L, null)) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - AccountControlUiRegistryReader.checkedCleanupDeadlineMillis( - 1_800_000_000L, 1_799_999_999_999L)) + assertThatThrownBy(() -> + AccountControlUiRegistryReader.checkedCleanupDeadlineMillis( + 1_800_000_000L, 1_799_999_999_999L)) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - AccountControlUiRegistryReader.checkedCleanupDeadlineMillis( - Long.MAX_VALUE, 9_007_199_254_740_991L)) + assertThatThrownBy(() -> + AccountControlUiRegistryReader.checkedCleanupDeadlineMillis( + Long.MAX_VALUE, 9_007_199_254_740_991L)) .isInstanceOf(IllegalStateException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java index c25b99cd96..fd32ed4de5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java @@ -204,10 +204,9 @@ void committedCurrentnessByJtiRejectsChangedAccountSourceBeforeReturningActor() when(changed.evidence()).thenReturn(new byte[] {99}); when(f.authority.capture(f.actor, f.tenant, f.environment)).thenReturn(changed); - assertThatThrownBy( - () -> - f.actors.withCurrentCommitted( - f.actor, f.tenant, f.jti, f.environment, current -> current.source().actor())) + assertThatThrownBy(() -> + f.actors.withCurrentCommitted( + f.actor, f.tenant, f.jti, f.environment, current -> current.source().actor())) .isInstanceOf(IllegalStateException.class); } @@ -222,14 +221,13 @@ void committedCurrentnessByJtiRejectsRevokedOrMismatchedRegistryBeforeSourceRead doThrow(new IllegalStateException("test-only revoked token")) .when(revoked.registry) .readActive(revokedHash); - assertThatThrownBy( - () -> - revoked.actors.withCurrentCommitted( - revoked.actor, - revoked.tenant, - revoked.jti, - revoked.environment, - current -> current.source().actor())) + assertThatThrownBy(() -> + revoked.actors.withCurrentCommitted( + revoked.actor, + revoked.tenant, + revoked.jti, + revoked.environment, + current -> current.source().actor())) .isInstanceOf(IllegalStateException.class); verify(revoked.authority, never()).capture(revoked.actor, revoked.tenant, revoked.environment); @@ -240,14 +238,13 @@ void committedCurrentnessByJtiRejectsRevokedOrMismatchedRegistryBeforeSourceRead AccountControlUiIssuanceRepository.hash( mismatchedCompact.getBytes(StandardCharsets.US_ASCII)); doReturn(new byte[] {99}).when(mismatched.registry).readActive(mismatchedHash); - assertThatThrownBy( - () -> - mismatched.actors.withCurrentCommitted( - mismatched.actor, - mismatched.tenant, - mismatched.jti, - mismatched.environment, - current -> current.source().actor())) + assertThatThrownBy(() -> + mismatched.actors.withCurrentCommitted( + mismatched.actor, + mismatched.tenant, + mismatched.jti, + mismatched.environment, + current -> current.source().actor())) .isInstanceOf(IllegalStateException.class); verify(mismatched.authority, never()) .capture(mismatched.actor, mismatched.tenant, mismatched.environment); @@ -334,10 +331,9 @@ void accountActorConsumesExactCurrentSourcesAndProducerFenceInsideOwnerTransacti verify(f.authority, never()).capture(any(), any(), any()); assertThatThrownBy(() -> f.actors.authenticate(compact, f.tenant, f.environment)) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - f.actors.withCurrentCommitted( - f.actor, f.tenant, f.jti, f.environment, current -> current)) + assertThatThrownBy(() -> + f.actors.withCurrentCommitted( + f.actor, f.tenant, f.jti, f.environment, current -> current)) .isInstanceOf(IllegalStateException.class); } @@ -377,13 +373,12 @@ void accountActorRejectsChangedSourceOrRoleAndNeverInvokesMutation() throws Exce String compact = f.sign(f.claims); f.owner(compact); when(f.snapshot.evidence()).thenReturn(new byte[] {99}); - assertThatThrownBy( - () -> - f.actors.withCurrentAccount( - compact, - current -> { - throw new AssertionError("mutation must not run"); - })) + assertThatThrownBy(() -> + f.actors.withCurrentAccount( + compact, + current -> { + throw new AssertionError("mutation must not run"); + })) .isInstanceOf(IllegalStateException.class); assertThatThrownBy(() -> f.actors.authenticateAccount(compact)) .isInstanceOf(IllegalStateException.class); @@ -409,13 +404,12 @@ void accountActorRejectsTenantTokenAndLostProducerFence() throws Exception { doThrow(new IllegalStateException("test-only concurrent source writer")) .when(account.fences) .lockProducerSourcesNowait(any()); - assertThatThrownBy( - () -> - account.actors.withCurrentAccount( - compact, - current -> { - throw new AssertionError("mutation must not run"); - })) + assertThatThrownBy(() -> + account.actors.withCurrentAccount( + compact, + current -> { + throw new AssertionError("mutation must not run"); + })) .isInstanceOf(IllegalStateException.class); } @@ -431,13 +425,12 @@ void accountActorStillRequiresExactRegistryAndOriginalSigner() throws Exception when(f.registry.readActive(anyString())).thenReturn(new byte[] {12}); when(f.signers.requireOriginal(any(byte[].class))) .thenThrow(new IllegalStateException("test-only missing original signer")); - assertThatThrownBy( - () -> - f.actors.withCurrentAccount( - compact, - current -> { - throw new AssertionError("mutation must not run"); - })) + assertThatThrownBy(() -> + f.actors.withCurrentAccount( + compact, + current -> { + throw new AssertionError("mutation must not run"); + })) .isInstanceOf(IllegalStateException.class); verify(f.authority, never()).captureAccount(any()); verify(f.fences, never()).lockProducerSourcesNowait(any()); @@ -494,40 +487,37 @@ void accountSourceCallbacksUseExactOriginalInsideTransactionAndProducerLocks() t void accountOriginalRecoveryRejectsTenantChangedAccountAndExpiredOriginal() throws Exception { Fixture tenant = new Fixture(); tenant.owner(tenant.sign(tenant.claims)); - assertThatThrownBy( - () -> - tenant.actors.withCurrentAccountCommitted( - tenant.actor, - tenant.jti, - current -> { - throw new AssertionError("callback must not run"); - })) + assertThatThrownBy(() -> + tenant.actors.withCurrentAccountCommitted( + tenant.actor, + tenant.jti, + current -> { + throw new AssertionError("callback must not run"); + })) .isInstanceOf(IllegalStateException.class); verify(tenant.authority, never()).captureAccount(any()); Fixture account = new Fixture(true); account.owner(account.sign(account.claims)); - assertThatThrownBy( - () -> - account.actors.withCurrentAccountCommitted( - UUID.randomUUID(), - account.jti, - current -> { - throw new AssertionError("callback must not run"); - })) + assertThatThrownBy(() -> + account.actors.withCurrentAccountCommitted( + UUID.randomUUID(), + account.jti, + current -> { + throw new AssertionError("callback must not run"); + })) .isInstanceOf(IllegalStateException.class); verify(account.authority, never()).captureAccount(any()); Fixture expired = new Fixture(true, NOW.plusSeconds(300)); expired.owner(expired.sign(expired.claims)); - assertThatThrownBy( - () -> - expired.actors.withCurrentAccountCommitted( - expired.actor, - expired.jti, - current -> { - throw new AssertionError("callback must not run"); - })) + assertThatThrownBy(() -> + expired.actors.withCurrentAccountCommitted( + expired.actor, + expired.jti, + current -> { + throw new AssertionError("callback must not run"); + })) .isInstanceOf(IllegalStateException.class); verify(expired.authority, never()).captureAccount(any()); } @@ -563,14 +553,13 @@ void accountOriginalRecoveryRejectsChangedSourcesRegistrySignerAndProducerFence( Fixture f = new Fixture(true); f.owner(f.sign(f.claims)); change.accept(f); - assertThatThrownBy( - () -> - f.actors.withCurrentAccountCommitted( - f.actor, - f.jti, - current -> { - throw new AssertionError("callback must not run"); - })) + assertThatThrownBy(() -> + f.actors.withCurrentAccountCommitted( + f.actor, + f.jti, + current -> { + throw new AssertionError("callback must not run"); + })) .isInstanceOf(IllegalStateException.class); } } @@ -721,11 +710,10 @@ private static final class Fixture { when(source.sourceIdentity()).thenReturn(pin); when(source.load()).thenReturn(new AccountPublicJwksCache.PublicJwksSnapshot(pin, jwks)); when(transactions.getTransaction(any())) - .thenAnswer( - ignored -> { - TransactionSynchronizationManager.setActualTransactionActive(true); - return new SimpleTransactionStatus(); - }); + .thenAnswer(ignored -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + return new SimpleTransactionStatus(); + }); doAnswer( ignored -> { TransactionSynchronizationManager.clear(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcServiceTest.java index d105b4e257..0c604ade2b 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationGrpcServiceTest.java @@ -68,25 +68,23 @@ void authenticatesExactPeerAndCredentialBeforeDecodingOrOwnerCapture() { .code()) .isEqualTo(Status.Code.UNAUTHENTICATED); assertThat( - authorized( - () -> - invokeAuthorize( - GameLogicIntakeAuthorizationRequest.newBuilder() - .setUnknownFields( - com.google.protobuf.UnknownFieldSet.newBuilder() - .addField( - 99, - com.google.protobuf.UnknownFieldSet.Field.newBuilder() - .addVarint(1) - .build()) - .build()) - .build())) + authorized(() -> + invokeAuthorize( + GameLogicIntakeAuthorizationRequest.newBuilder() + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, + com.google.protobuf.UnknownFieldSet.Field.newBuilder() + .addVarint(1) + .build()) + .build()) + .build())) .code()) .isEqualTo(Status.Code.INVALID_ARGUMENT); assertThat( - authorized( - () -> - invokeAuthorize(request().toBuilder().setTargetNamespace("other").build())) + authorized(() -> + invokeAuthorize(request().toBuilder().setTargetNamespace("other").build())) .code()) .isEqualTo(Status.Code.PERMISSION_DENIED); verifyNoInteractions(owner, terms); @@ -120,21 +118,19 @@ void capturesEnvironmentOnlyThroughSupplierAndEchoesExactSelectionWithoutCredent var binding = authorization(decoded); var captures = new AtomicInteger(); when(terms.captureCurrentEnvironmentBoundary()) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - captures.incrementAndGet(); - return captured; - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + captures.incrementAndGet(); + return captured; + }); when(owner.authorizeWithEnvironmentCapture( eq(CREDENTIAL), eq(decoded.intakeRequestId()), eq(decoded.selected()), any())) - .thenAnswer( - call -> { - Supplier capture = call.getArgument(3); - assertThat(capture.get()).isSameAs(captured); - return binding; - }); + .thenAnswer(call -> { + Supplier capture = call.getArgument(3); + assertThat(capture.get()).isSameAs(captured); + return binding; + }); var result = authorized(() -> invokeAuthorize(safeRequest)); assertThat(result.error()).isNull(); @@ -282,16 +278,15 @@ private Status.Code boundCode(io.grpc.Metadata headers) { (io.grpc.ServerMethodDefinition< GameLogicIntakeAuthorizationRequest, GameLogicIntakeAuthorizationResponse>) receiver.bindService().getMethods().stream() - .filter( - candidate -> - candidate - .getMethodDescriptor() - .getFullMethodName() - .equals( - net.firedevops.firemud.account.v1 - .AccountGameLogicIntakeAuthorizationServiceGrpc - .getAuthorizeIntakeMethod() - .getFullMethodName())) + .filter(candidate -> + candidate + .getMethodDescriptor() + .getFullMethodName() + .equals( + net.firedevops.firemud.account.v1 + .AccountGameLogicIntakeAuthorizationServiceGrpc + .getAuthorizeIntakeMethod() + .getFullMethodName())) .findFirst() .orElseThrow(); io.grpc.ServerCall diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRecoveryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRecoveryTest.java index 27d2bcd053..51a8d1d5a8 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRecoveryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeAuthorizationRecoveryTest.java @@ -152,12 +152,10 @@ void requiresFreshAuthorityAfterRemoteSourceReadBeforeFinalization() { new AccountGameLogicIntakeSourceReadRecovery( scope, AccountGameLogicIntakeSourceReadRecovery.State.RESERVED, Optional.empty())); when(sourceClient.read(any(GameplayRuleSourceReadEvidence.Request.class))) - .thenAnswer( - call -> { - events.add("source-read"); - return new GameplayRuleSourceReadEvidence( - call.getArgument(0), authorization.source()); - }); + .thenAnswer(call -> { + events.add("source-read"); + return new GameplayRuleSourceReadEvidence(call.getArgument(0), authorization.source()); + }); var actorCalls = new AtomicInteger(); doAnswer( call -> { @@ -183,20 +181,19 @@ void requiresFreshAuthorityAfterRemoteSourceReadBeforeFinalization() { .orElseThrow()); var prior = context.attach(); try { - assertThatThrownBy( - () -> - service.authorizeWithEnvironmentCapture( - CREDENTIAL, - intakeRequestId, - selected, - () -> { - if (environmentCaptures.incrementAndGet() == 1) { - events.add("capture-reservation"); - return initialEnvironment; - } - events.add("capture-finalization"); - throw currentnessUnavailable; - })) + assertThatThrownBy(() -> + service.authorizeWithEnvironmentCapture( + CREDENTIAL, + intakeRequestId, + selected, + () -> { + if (environmentCaptures.incrementAndGet() == 1) { + events.add("capture-reservation"); + return initialEnvironment; + } + events.add("capture-finalization"); + throw currentnessUnavailable; + })) .isSameAs(currentnessUnavailable); } finally { context.detach(prior); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java index 6617d688f5..8b6acb6ae5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSettlementGrpcServiceTest.java @@ -91,9 +91,8 @@ void returnsExactRetainedAndAbortedReceiptForNewCorrelationRetryWithoutChangingB var receipt = new AccountGameLogicIntakeSettlement(evidence.receipt().terminal()); when(owner.settle(any())).thenReturn(receipt); var first = - authorized( - () -> - invoke(AccountGameLogicIntakeSettlementProtoCodec.toRequest(evidence.request()))); + authorized(() -> + invoke(AccountGameLogicIntakeSettlementProtoCodec.toRequest(evidence.request()))); assertThat(first.error()).isNull(); assertThat( AccountGameLogicIntakeSettlementProtoCodec.fromResponse( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcServiceTest.java index fc3a5bb34e..8c51471a8c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameLogicIntakeSourceReadGrpcServiceTest.java @@ -64,11 +64,10 @@ void dispatchesOnlyMatchingProofMethodAndEchoesExactConfirmedRequest() { var wrongFirst = new Collector(); var wrongLast = new Collector(); peer("test", "game-design-service") - .run( - () -> { - service.readSourceScope(finalized, wrongFirst); - service.readFinalizedIntake(prelim, wrongLast); - }); + .run(() -> { + service.readSourceScope(finalized, wrongFirst); + service.readFinalizedIntake(prelim, wrongLast); + }); assertThat(wrongFirst.error).isEqualTo(Status.Code.INVALID_ARGUMENT); assertThat(wrongLast.error).isEqualTo(Status.Code.INVALID_ARGUMENT); verifyNoInteractions(owner); @@ -79,11 +78,10 @@ void dispatchesOnlyMatchingProofMethodAndEchoesExactConfirmedRequest() { var first = new Collector(); var last = new Collector(); peer("test", "game-design-service") - .run( - () -> { - service.readSourceScope(prelim, first); - service.readFinalizedIntake(finalized, last); - }); + .run(() -> { + service.readSourceScope(prelim, first); + service.readFinalizedIntake(finalized, last); + }); assertThat(first.response.getRequest()).isEqualTo(prelim); assertThat(last.response.getRequest()).isEqualTo(finalized); assertThat(first.response.getPermitted()).isTrue(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifierTest.java index 9283b0e399..2bbec89af0 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifierTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionCallerVerifierTest.java @@ -206,10 +206,9 @@ void replacesJwksCacheWhenTrustedSourceIdentityChanges() throws Exception { AccountJwtJwksTrustedSource source = mock(AccountJwtJwksTrustedSource.class); when(source.sourceIdentity()).thenAnswer(invocation -> activeIdentity.get()); when(source.load()) - .thenAnswer( - invocation -> - new PublicJwksSnapshot( - activeIdentity.get(), activeJwks.get().getBytes(StandardCharsets.UTF_8))); + .thenAnswer(invocation -> + new PublicJwksSnapshot( + activeIdentity.get(), activeJwks.get().getBytes(StandardCharsets.UTF_8))); String oldToken = fixture.signedToken(signingPair, fixture.initialClaims()); CommittedCandidateVerificationData oldCandidate = fixture.candidate(oldToken, ACCOUNT_ID, false, false); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcServiceTest.java index 4a304b6f4d..99646eae0e 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAdmissionLeaseGrpcServiceTest.java @@ -442,11 +442,10 @@ public void onCompleted() { throw new AssertionError("completion must not follow failed onNext"); } }; - assertThatThrownBy( - () -> - withPeer( - peer(NAMESPACE, "game-session-service"), - () -> service.acquireGameplayAdmissionLease(request, observer))) + assertThatThrownBy(() -> + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> service.acquireGameplayAdmissionLease(request, observer))) .isSameAs(callbackFailure); } @@ -519,10 +518,9 @@ private List callsWithDefaultRequests() { } private List confirmationCallsWithDefaultRequests() { - return List.of( - observer -> - service.confirmOriginalNewGameplayAdmission( - ConfirmOriginalNewGameplayAdmissionRequest.getDefaultInstance(), observer)); + return List.of(observer -> + service.confirmOriginalNewGameplayAdmission( + ConfirmOriginalNewGameplayAdmissionRequest.getDefaultInstance(), observer)); } private void assertConfirmationCode( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java index 77943bc790..bad1a2149d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayAuthenticateReceiverTest.java @@ -400,17 +400,16 @@ void disposalRejectsIncompleteWitnessAndRedactsOwnerFailure() { var peer = GrpcPeerIdentity.parseUri(WORKLOAD).orElseThrow(); Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .run( - () -> - adapter.retireInitialGameplayLogin( - request - .clone() - .setTokenWitness( - net.firedevops.firemud.account.v1.InitialGameplayLoginTokenWitness - .newBuilder() - .setTokenJti(TOKEN_JTI.toString())) - .build(), - incomplete)); + .run(() -> + adapter.retireInitialGameplayLogin( + request + .clone() + .setTokenWitness( + net.firedevops.firemud.account.v1.InitialGameplayLoginTokenWitness + .newBuilder() + .setTokenJti(TOKEN_JTI.toString())) + .build(), + incomplete)); assertThat(Status.fromThrowable(incomplete.failure).getCode()) .isEqualTo(Status.Code.INVALID_ARGUMENT); verifyNoInteractions(disposal); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java index d72612c038..1c9da11a3c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java @@ -100,10 +100,9 @@ void absentAccountRunsDecoyVerificationButNeverIssuesOrActivates() { assertThatThrownBy(() -> fixture.owner.authenticate(request("secret"), WORKLOAD, verifier)) .isInstanceOf(AuthenticationException.class) - .satisfies( - failure -> - assertThat(((AuthenticationException) failure).getCode()) - .isEqualTo(AuthenticationErrorCodes.INVALID_CREDENTIALS)); + .satisfies(failure -> + assertThat(((AuthenticationException) failure).getCode()) + .isEqualTo(AuthenticationErrorCodes.INVALID_CREDENTIALS)); verify(verifier).verifyAbsentAccountCredential("secret"); verify(verifier, never()).verify(any(), anyString()); @@ -160,12 +159,11 @@ void exactRetryReturnsOriginalCredentialAndConsumesOtpOnlyInItsPendingTransactio .thenReturn(Optional.empty(), Optional.empty(), Optional.of(exactRetry)); when(fixture.issuance.beginPendingForAccount( eq(REQUEST_ID), eq(ACCOUNT_ID), eq(WORKLOAD), eq(CONTEXT_ID), eq(binding))) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - fixture.transactions.events.add("pending-operation"); - return newlyPending; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + fixture.transactions.events.add("pending-operation"); + return newlyPending; + }); AccountGameplayCanonicalLoginOwner.CredentialVerifier verifier = new AccountGameplayCanonicalLoginOwner.CredentialVerifier() { @@ -207,12 +205,11 @@ public void consumeOneTimeCredential( .commitPendingCandidate(REQUEST_ID); when(fixture.responseOwner.recoverInitialLoginResponse( eq(REQUEST_ID), eq(ACCOUNT_ID), any(CallerIdentity.class))) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - fixture.transactions.events.add("activate-recover-response"); - return response; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + fixture.transactions.events.add("activate-recover-response"); + return response; + }); InitialGameplayLoginResult first = fixture.owner.authenticate(request, WORKLOAD, verifier); InitialGameplayLoginResult retry = fixture.owner.authenticate(request, WORKLOAD, verifier); @@ -358,10 +355,9 @@ void commitOrRecoveryFailureNeverReturnsTheCredential() { doThrow(new IllegalStateException("private signer or registry detail")) .when(commitFailure.commitOwner) .commitPendingCandidate(REQUEST_ID); - assertThatThrownBy( - () -> - commitFailure.owner.authenticate( - request("original-secret"), WORKLOAD, unusedVerifier())) + assertThatThrownBy(() -> + commitFailure.owner.authenticate( + request("original-secret"), WORKLOAD, unusedVerifier())) .isInstanceOf(IllegalStateException.class) .hasMessage("private signer or registry detail"); verify(commitFailure.responseOwner, never()).recoverInitialLoginResponse(any(), any(), any()); @@ -370,10 +366,9 @@ void commitOrRecoveryFailureNeverReturnsTheCredential() { doThrow(new IllegalStateException("private recovery detail")) .when(recoveryFailure.responseOwner) .recoverInitialLoginResponse(any(), any(), any()); - assertThatThrownBy( - () -> - recoveryFailure.owner.authenticate( - request("original-secret"), WORKLOAD, unusedVerifier())) + assertThatThrownBy(() -> + recoveryFailure.owner.authenticate( + request("original-secret"), WORKLOAD, unusedVerifier())) .isInstanceOf(IllegalStateException.class) .hasMessage("private recovery detail"); verify(recoveryFailure.commitOwner).commitPendingCandidate(REQUEST_ID); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigesterTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigesterTest.java index 1ee19275d8..2f99b9f9a4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigesterTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCredentialRequestDigesterTest.java @@ -144,14 +144,13 @@ void bindingChangesForEveryCredentialCallerAndSourceContextDimension() { void rejectsUnverifiedOrNonGameSessionCallerIdentity() { assertThatThrownBy(() -> bind(KEY, REQUEST, "player@example.com", null, ACCOUNT_ID)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - bind( - KEY, - REQUEST, - "player@example.com", - "spiffe://firemud/ns/test/sa/tcp-proxy-service", - ACCOUNT_ID)) + assertThatThrownBy(() -> + bind( + KEY, + REQUEST, + "player@example.com", + "spiffe://firemud/ns/test/sa/tcp-proxy-service", + ACCOUNT_ID)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java index 5f8c1bbbac..e3cdc5fd50 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationAuthorityProjectionTest.java @@ -80,10 +80,9 @@ void canonicalProjectionPairRejectsMissingAccountProjection() { null, valid.canonicalIssuerProjection()); - assertThatThrownBy( - () -> - AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair( - missingAccountProjection)) + assertThatThrownBy(() -> + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair( + missingAccountProjection)) .isInstanceOf( AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); } @@ -169,11 +168,10 @@ void selectedIndependentVersionMismatchDeniesBeforeRedisEvenWhenGenerationMatche void selectedSourceChangedAfterExactRedisReadbackNeverReturnsObservation() { SelectedOwnerFixture fixture = new SelectedOwnerFixture(); when(fixture.redis.readSelectedAuthorityProjections(ACCOUNT_ID, fixture.tenant)) - .thenAnswer( - invocation -> { - when(fixture.member.getMembershipVersion()).thenReturn(3L); - return fixture.values; - }); + .thenAnswer(invocation -> { + when(fixture.member.getMembershipVersion()).thenReturn(3L); + return fixture.values; + }); assertThatThrownBy( () -> fixture.projection.observeSelectedCurrent(ACCOUNT_ID, fixture.tenant)) .isInstanceOf( @@ -619,16 +617,15 @@ void selectedPublicationRereadsOwnerCurrentnessAfterCasReplay() { org.mockito.ArgumentMatchers.anyBoolean(), org.mockito.ArgumentMatchers.nullable(byte[].class), any(List.class))) - .thenAnswer( - invocation -> { - @SuppressWarnings("unchecked") - List candidates = invocation.getArgument(4); - String candidate = new String(candidates.getLast(), StandardCharsets.UTF_8); - if (candidate.contains("\"accountId\"")) { - when(fixture.member.getMembershipVersion()).thenReturn(3L); - } - return AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED; - }); + .thenAnswer(invocation -> { + @SuppressWarnings("unchecked") + List candidates = invocation.getArgument(4); + String candidate = new String(candidates.getLast(), StandardCharsets.UTF_8); + if (candidate.contains("\"accountId\"")) { + when(fixture.member.getMembershipVersion()).thenReturn(3L); + } + return AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED; + }); assertThatThrownBy( () -> fixture.projection.publishSelectedCurrent(ACCOUNT_ID, fixture.tenant)) @@ -720,9 +717,8 @@ void currentContradictoryCompositeOrUnsupportedClosedAccountSourceStillDenies() GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) .thenReturn( snapshot(1L, 2L)); // The actual composite still proves 1, not this claimed head. - assertThatThrownBy( - () -> - contradictory.projection.observeSelectedCurrent(ACCOUNT_ID, contradictory.tenant)) + assertThatThrownBy(() -> + contradictory.projection.observeSelectedCurrent(ACCOUNT_ID, contradictory.tenant)) .isInstanceOf( AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); org.mockito.Mockito.verifyNoInteractions(contradictory.redis); @@ -969,18 +965,15 @@ void canonicalIssuerBaselineRejectsGenericAliasesAndAdvancedLocalSource() throws .doesNotContainKeys("schema", "scope", "digest", "checkpoint"); Map altered = new LinkedHashMap<>(decodeFields(issuer)); altered.put("schema", "account-auth-authority-projection/v1"); - assertThatThrownBy( - () -> - AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( - JSON.writeValueAsBytes(altered), - "issuer", - GameSessionAccountDelegationProfile.ISSUER)) + assertThatThrownBy(() -> + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + JSON.writeValueAsBytes(altered), + "issuer", + GameSessionAccountDelegationProfile.ISSUER)) .isInstanceOf( AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); - assertThatThrownBy( - () -> - AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair( - snapshot(2, 1))) + assertThatThrownBy(() -> + AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot(2, 1))) .isInstanceOf( AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); } @@ -1021,31 +1014,28 @@ void rejectsLegacyAccountSchemaUnknownFieldsWrongIdentityAndMissingEvent() throw for (String field : List.of("issuanceFence", "digest", "generation")) { Map altered = new LinkedHashMap<>(decodeFields(account)); altered.put(field, "1"); - assertThatThrownBy( - () -> - AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( - JSON.writeValueAsString(altered) - .getBytes(java.nio.charset.StandardCharsets.UTF_8), - "account", - ACCOUNT_ID.toString())) + assertThatThrownBy(() -> + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + JSON.writeValueAsString(altered) + .getBytes(java.nio.charset.StandardCharsets.UTF_8), + "account", + ACCOUNT_ID.toString())) .isInstanceOf( AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); } Map missing = new LinkedHashMap<>(decodeFields(account)); missing.remove("sourceEvent"); - assertThatThrownBy( - () -> - AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( - JSON.writeValueAsString(missing) - .getBytes(java.nio.charset.StandardCharsets.UTF_8), - "account", - ACCOUNT_ID.toString())) + assertThatThrownBy(() -> + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + JSON.writeValueAsString(missing) + .getBytes(java.nio.charset.StandardCharsets.UTF_8), + "account", + ACCOUNT_ID.toString())) .isInstanceOf( AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); - assertThatThrownBy( - () -> - AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( - account, "account", UUID.randomUUID().toString())) + assertThatThrownBy(() -> + AccountGameplayDelegationAuthorityProjection.ProjectionValue.decode( + account, "account", UUID.randomUUID().toString())) .isInstanceOf( AccountGameplayDelegationAuthorityProjection.ProjectionUnavailableException.class); } @@ -1150,11 +1140,10 @@ void publishesOnlyAfterOwnerSnapshotTransactionHasCompleted() { GameSessionAccountDelegationProfile.ISSUER, ACCOUNT_ID)) .thenReturn(snapshot(1L, 11L)); when(redis.publishAuthorityProjections(any(UUID.class), any(byte[].class), any(byte[].class))) - .thenAnswer( - invocation -> { - assertThat(transactionActive.get()).isFalse(); - return AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED; - }); + .thenAnswer(invocation -> { + assertThat(transactionActive.get()).isFalse(); + return AccountGameplayDelegationRedisClient.ProjectionPublicationOutcome.PUBLISHED; + }); AccountGameplayDelegationAuthorityProjection projection = new AccountGameplayDelegationAuthorityProjection( sourceEvidence, transactionManager, redis); @@ -1304,11 +1293,10 @@ private static PlatformTransactionManager transactionManager(AtomicBoolean activ PlatformTransactionManager manager = mock(PlatformTransactionManager.class); TransactionStatus status = mock(TransactionStatus.class); when(manager.getTransaction(any(TransactionDefinition.class))) - .thenAnswer( - invocation -> { - if (active != null) active.set(true); - return status; - }); + .thenAnswer(invocation -> { + if (active != null) active.set(true); + return status; + }); doAnswer( invocation -> { if (active != null) active.set(false); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwnerTest.java index 2c5fd85671..c64b96cf2f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationCommittedIssuanceOwnerTest.java @@ -50,10 +50,9 @@ void malformedRequestIsDeniedBeforeStartingOwnerReads() { AccountGameplayDelegationCommittedIssuanceOwner owner = owner(repository, signer, registry, mock(PlatformTransactionManager.class)); - assertThatThrownBy( - () -> - owner.inspectCurrentCommittedIssuance( - UUID.fromString("00000000-0000-0000-0000-000000000000"))) + assertThatThrownBy(() -> + owner.inspectCurrentCommittedIssuance( + UUID.fromString("00000000-0000-0000-0000-000000000000"))) .isInstanceOf(OwnerUnavailableException.class) .hasNoCause(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitServiceTest.java index ec357308ee..aa82ac36dc 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationIssuanceCommitServiceTest.java @@ -121,18 +121,16 @@ void genuineRsaSignerCompositionCannotCommitWithoutOwnerRegistrationReceipt() th when(repository.readCommittedProof(signerFixture.requestId())).thenReturn(Optional.empty()); when(registry.registerPending(signerFixture.requestId())).thenReturn(null); when(projection.publishCurrent(signerFixture.accountId())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return new PublicationObservation( - "d".repeat(64), "e".repeat(64), 11L, 12L, ProjectionPublicationOutcome.PUBLISHED); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new PublicationObservation( + "d".repeat(64), "e".repeat(64), 11L, 12L, ProjectionPublicationOutcome.PUBLISHED); + }); when(projection.observeCurrent(signerFixture.accountId())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return new ProjectionObservation("d".repeat(64), "e".repeat(64), 11L, 12L); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new ProjectionObservation("d".repeat(64), "e".repeat(64), 11L, 12L); + }); AccountGameplayDelegationIssuanceCommitService service = new AccountGameplayDelegationIssuanceCommitService( @@ -218,22 +216,16 @@ void projectionObservationMustMatchPublishedDigestAndGeneration() throws Excepti when(repository.readCommittedProof(signerFixture.requestId())).thenReturn(Optional.empty()); when(registry.registerPending(signerFixture.requestId())).thenReturn(receipt); when(projection.publishCurrent(signerFixture.accountId())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return new PublicationObservation( - "d".repeat(64), - "e".repeat(64), - 11L, - 12L, - ProjectionPublicationOutcome.PUBLISHED); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new PublicationObservation( + "d".repeat(64), "e".repeat(64), 11L, 12L, ProjectionPublicationOutcome.PUBLISHED); + }); when(projection.observeCurrent(signerFixture.accountId())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return mismatch; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return mismatch; + }); AccountGameplayDelegationIssuanceCommitService service = new AccountGameplayDelegationIssuanceCommitService( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java index 2d53209ccc..2b8bc43762 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationRedisClientTest.java @@ -112,37 +112,34 @@ void selectedEventPageUsesOnePinnedConnectionAndOneDurabilityAckFor128OrderedCas .thenAnswer(invocation -> sha1(invocation.getArgument(0))); when(commands.evalsha( anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) - .thenAnswer( - invocation -> { - byte[][] keys = invocation.getArgument(2); - Object[] rawArguments = invocation.getRawArguments(); - if (rawArguments.length != 4 - || !(rawArguments[3] instanceof byte[][] arguments) - || arguments.length != 3) return -1L; - String key = new String(keys[0], StandardCharsets.UTF_8); - String mode = new String(arguments[0], StandardCharsets.US_ASCII); - byte[] current = stored.get(key); - if (current != null && Arrays.equals(current, arguments[2])) return 0L; - if (("ABSENT".equals(mode) && current != null) - || ("PRESENT".equals(mode) && !Arrays.equals(current, arguments[1]))) { - return -1L; - } - stored.put(key, arguments[2].clone()); - return 1L; - }); + .thenAnswer(invocation -> { + byte[][] keys = invocation.getArgument(2); + Object[] rawArguments = invocation.getRawArguments(); + if (rawArguments.length != 4 + || !(rawArguments[3] instanceof byte[][] arguments) + || arguments.length != 3) return -1L; + String key = new String(keys[0], StandardCharsets.UTF_8); + String mode = new String(arguments[0], StandardCharsets.US_ASCII); + byte[] current = stored.get(key); + if (current != null && Arrays.equals(current, arguments[2])) return 0L; + if (("ABSENT".equals(mode) && current != null) + || ("PRESENT".equals(mode) && !Arrays.equals(current, arguments[1]))) { + return -1L; + } + stored.put(key, arguments[2].clone()); + return 1L; + }); doReturn(List.of(1L, 1L)) .when(commands) .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); when(commands.get(any(byte[].class))) - .thenAnswer( - invocation -> - stored.get(new String(invocation.getArgument(0), StandardCharsets.UTF_8))); + .thenAnswer(invocation -> + stored.get(new String(invocation.getArgument(0), StandardCharsets.UTF_8))); AccountGameplayDelegationRedisClient client = - client( - () -> { - openedConnections.incrementAndGet(); - return connection; - }); + client(() -> { + openedConnections.incrementAndGet(); + return connection; + }); assertThat( client.publishSelectedAuthorityEventPage(ACCOUNT_ID, tenant, false, null, candidates)) @@ -159,11 +156,10 @@ void selectedEventPageUsesOnePinnedConnectionAndOneDurabilityAckFor128OrderedCas .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); verify(commands) .get( - argThat( - key -> - Arrays.equals( - key, - ascii("session:auth:generation:membership:" + ACCOUNT_ID + ":" + tenant)))); + argThat(key -> + Arrays.equals( + key, + ascii("session:auth:generation:membership:" + ACCOUNT_ID + ":" + tenant)))); verify(connection).close(); assertThat(args.getAllValues()).hasSize(128); for (int index = 0; index < candidates.size(); index++) { @@ -192,21 +188,19 @@ void selectedEventPageDeniesPartialCasAndRecoversFromActualContiguousRedisHead() .thenAnswer(invocation -> sha1(invocation.getArgument(0))); when(failedCommands.evalsha( anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) - .thenAnswer( - invocation -> { - int attempt = attempts.incrementAndGet(); - if (attempt == 3) return -1L; - Object[] rawArguments = invocation.getRawArguments(); - if (rawArguments.length != 4 - || !(rawArguments[3] instanceof byte[][] arguments) - || arguments.length != 3) return -1L; - stored.put(key, arguments[2].clone()); - return 1L; - }); - assertThatThrownBy( - () -> - client(failedConnection) - .publishSelectedAuthorityEventPage(ACCOUNT_ID, tenant, false, null, candidates)) + .thenAnswer(invocation -> { + int attempt = attempts.incrementAndGet(); + if (attempt == 3) return -1L; + Object[] rawArguments = invocation.getRawArguments(); + if (rawArguments.length != 4 + || !(rawArguments[3] instanceof byte[][] arguments) + || arguments.length != 3) return -1L; + stored.put(key, arguments[2].clone()); + return 1L; + }); + assertThatThrownBy(() -> + client(failedConnection) + .publishSelectedAuthorityEventPage(ACCOUNT_ID, tenant, false, null, candidates)) .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat(stored.get(key)).containsExactly(candidates.get(1)); verify(failedCommands, org.mockito.Mockito.never()) @@ -220,22 +214,20 @@ void selectedEventPageDeniesPartialCasAndRecoversFromActualContiguousRedisHead() .thenAnswer(invocation -> sha1(invocation.getArgument(0))); when(recoveryCommands.evalsha( anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) - .thenAnswer( - invocation -> { - Object[] rawArguments = invocation.getRawArguments(); - if (rawArguments.length != 4 - || !(rawArguments[3] instanceof byte[][] arguments) - || arguments.length != 3) return -1L; - stored.put(key, arguments[2].clone()); - return 1L; - }); + .thenAnswer(invocation -> { + Object[] rawArguments = invocation.getRawArguments(); + if (rawArguments.length != 4 + || !(rawArguments[3] instanceof byte[][] arguments) + || arguments.length != 3) return -1L; + stored.put(key, arguments[2].clone()); + return 1L; + }); doReturn(List.of(1L, 1L)) .when(recoveryCommands) .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); when(recoveryCommands.get(any(byte[].class))) - .thenAnswer( - invocation -> - stored.get(new String(invocation.getArgument(0), StandardCharsets.UTF_8))); + .thenAnswer(invocation -> + stored.get(new String(invocation.getArgument(0), StandardCharsets.UTF_8))); assertThat( client(recoveryConnection) @@ -270,11 +262,9 @@ void selectedEventPageDeniesUnacknowledgedDurabilityAndIncorrectFinalReadback() .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); if (badReadback) when(commands.get(any(byte[].class))).thenReturn(ascii("wrong head")); - assertThatThrownBy( - () -> - client(connection) - .publishSelectedAuthorityEventPage( - ACCOUNT_ID, tenant, false, null, candidates)) + assertThatThrownBy(() -> + client(connection) + .publishSelectedAuthorityEventPage(ACCOUNT_ID, tenant, false, null, candidates)) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); verify(connection).close(); @@ -302,25 +292,23 @@ void selectedPublicationUsesFourCasCallsOnePinnedAckAndExactNoTtlReadback() thro when(commands.scriptLoad(any(byte[].class))) .thenAnswer(invocation -> sha1(invocation.getArgument(0))); when(commands.get(any(byte[].class))) - .thenAnswer( - invocation -> - stored.get(new String(invocation.getArgument(0), StandardCharsets.UTF_8))); + .thenAnswer(invocation -> + stored.get(new String(invocation.getArgument(0), StandardCharsets.UTF_8))); when(commands.evalsha( anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) - .thenAnswer( - invocation -> { - byte[][] keys = invocation.getArgument(2); - String key = new String(keys[0], StandardCharsets.UTF_8); - if (key.startsWith("session:auth:generation:tenant:")) { - stored.put(key, values[2]); - return 1L; - } - if (key.startsWith("session:auth:generation:membership:")) { - stored.put(key, values[3]); - return 1L; - } - return 0L; - }); + .thenAnswer(invocation -> { + byte[][] keys = invocation.getArgument(2); + String key = new String(keys[0], StandardCharsets.UTF_8); + if (key.startsWith("session:auth:generation:tenant:")) { + stored.put(key, values[2]); + return 1L; + } + if (key.startsWith("session:auth:generation:membership:")) { + stored.put(key, values[3]); + return 1L; + } + return 0L; + }); doReturn(List.of(1L, 1L)) .when(commands) .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); @@ -351,22 +339,20 @@ void selectedObservationRejectsMissingMembershipAndAnySelectedTtl() throws Excep var connection = connection(); var commands = connection.sync(); when(commands.get(any(byte[].class))) - .thenAnswer( - invocation -> { - String key = new String(invocation.getArgument(0), StandardCharsets.UTF_8); - if (key.contains(":issuer:")) return values[0]; - if (key.contains(":account:")) return values[1]; - if (key.contains(":tenant:")) return values[2]; - return missing ? null : values[3]; - }); + .thenAnswer(invocation -> { + String key = new String(invocation.getArgument(0), StandardCharsets.UTF_8); + if (key.contains(":issuer:")) return values[0]; + if (key.contains(":account:")) return values[1]; + if (key.contains(":tenant:")) return values[2]; + return missing ? null : values[3]; + }); if (!missing) when(commands.pttl(any(byte[].class))) - .thenAnswer( - invocation -> - new String(invocation.getArgument(0), StandardCharsets.UTF_8) - .contains(":membership:") - ? 500L - : -1L); + .thenAnswer(invocation -> + new String(invocation.getArgument(0), StandardCharsets.UTF_8) + .contains(":membership:") + ? 500L + : -1L); assertThatThrownBy( () -> client(connection).readSelectedAuthorityProjections(ACCOUNT_ID, tenant)) .isInstanceOf( @@ -391,18 +377,16 @@ void authorityProjectionUsesTwoExactOneKeyCasCallsOneAofAckAndSameConnectionRead .when(commands) .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); when(commands.get(any(byte[].class))) - .thenAnswer( - invocation -> { - byte[] key = invocation.getArgument(0); - if (Arrays.equals( - key, ascii("session:auth:generation:issuer:firemud-account-service"))) { - return values[0].clone(); - } - if (Arrays.equals(key, ascii("session:auth:generation:account:" + ACCOUNT_ID))) { - return values[1].clone(); - } - return null; - }); + .thenAnswer(invocation -> { + byte[] key = invocation.getArgument(0); + if (Arrays.equals(key, ascii("session:auth:generation:issuer:firemud-account-service"))) { + return values[0].clone(); + } + if (Arrays.equals(key, ascii("session:auth:generation:account:" + ACCOUNT_ID))) { + return values[1].clone(); + } + return null; + }); AccountGameplayDelegationRedisClient client = client(connection); assertThat(client.publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) @@ -433,10 +417,9 @@ key, ascii("session:auth:generation:issuer:firemud-account-service"))) { .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); verify(commands) .get( - argThat( - key -> - Arrays.equals( - key, ascii("session:auth:generation:issuer:firemud-account-service")))); + argThat(key -> + Arrays.equals( + key, ascii("session:auth:generation:issuer:firemud-account-service")))); verify(commands, times(2)) .get( argThat( @@ -470,13 +453,12 @@ void accountObservationRejectsProjectionWithAnyTtl() throws Exception { var connection = connection(); var commands = connection.sync(); when(commands.get(any(byte[].class))) - .thenAnswer( - invocation -> { - byte[] key = invocation.getArgument(0); - return Arrays.equals(key, ascii("session:auth:generation:account:" + ACCOUNT_ID)) - ? pair[1] - : pair[0]; - }); + .thenAnswer(invocation -> { + byte[] key = invocation.getArgument(0); + return Arrays.equals(key, ascii("session:auth:generation:account:" + ACCOUNT_ID)) + ? pair[1] + : pair[0]; + }); when(commands.pttl(any(byte[].class))).thenReturn(1000L); assertThatThrownBy(() -> client(connection).readAuthorityProjections(ACCOUNT_ID)) .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); @@ -490,15 +472,13 @@ void authorityProjectionObservationRejectsIssuerOnlyTtl() throws Exception { var connection = connection(); var commands = connection.sync(); when(commands.get(any(byte[].class))) - .thenAnswer( - invocation -> { - byte[] key = invocation.getArgument(0); - return Arrays.equals(key, issuerProjectionKey()) ? pair[0] : pair[1]; - }); + .thenAnswer(invocation -> { + byte[] key = invocation.getArgument(0); + return Arrays.equals(key, issuerProjectionKey()) ? pair[0] : pair[1]; + }); when(commands.pttl(any(byte[].class))) - .thenAnswer( - invocation -> - Arrays.equals(invocation.getArgument(0), issuerProjectionKey()) ? 1L : -1L); + .thenAnswer(invocation -> + Arrays.equals(invocation.getArgument(0), issuerProjectionKey()) ? 1L : -1L); assertThatThrownBy(() -> client(connection).readAuthorityProjections(ACCOUNT_ID)) .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); @@ -522,17 +502,15 @@ void authorityProjectionPublicationReadbackRejectsIssuerOnlyTtl() throws Excepti .when(commands) .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); when(commands.get(any(byte[].class))) - .thenAnswer( - invocation -> { - byte[] key = invocation.getArgument(0); - if (Arrays.equals(key, issuerProjectionKey())) return values[0].clone(); - if (Arrays.equals(key, accountProjectionKey())) return values[1].clone(); - return null; - }); + .thenAnswer(invocation -> { + byte[] key = invocation.getArgument(0); + if (Arrays.equals(key, issuerProjectionKey())) return values[0].clone(); + if (Arrays.equals(key, accountProjectionKey())) return values[1].clone(); + return null; + }); when(commands.pttl(any(byte[].class))) - .thenAnswer( - invocation -> - Arrays.equals(invocation.getArgument(0), issuerProjectionKey()) ? 1L : -1L); + .thenAnswer(invocation -> + Arrays.equals(invocation.getArgument(0), issuerProjectionKey()) ? 1L : -1L); assertThatThrownBy( () -> client(connection).publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) @@ -557,10 +535,8 @@ void acknowledgementOrReadbackUncertaintyNeverReturnsProjectionSuccess() throws .when(noAckCommands) .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); - assertThatThrownBy( - () -> - client(noAckConnection) - .publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) + assertThatThrownBy(() -> + client(noAckConnection).publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); verify(noAckCommands, times(1)).get(any(byte[].class)); @@ -576,10 +552,9 @@ void acknowledgementOrReadbackUncertaintyNeverReturnsProjectionSuccess() throws .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); when(readbackCommands.get(any(byte[].class))).thenReturn(null, ascii("wrong projection")); - assertThatThrownBy( - () -> - client(readbackConnection) - .publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) + assertThatThrownBy(() -> + client(readbackConnection) + .publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); } @@ -596,9 +571,8 @@ void staleOrConflictingIssuerProjectionStopsBeforeAccountWriteOrDurabilityAck() anyString(), eq(ScriptOutputType.INTEGER), any(byte[][].class), any(byte[][].class))) .thenReturn(result); - assertThatThrownBy( - () -> - client(connection).publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) + assertThatThrownBy(() -> + client(connection).publishAuthorityProjections(ACCOUNT_ID, values[0], values[1])) .isInstanceOf( AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); @@ -622,11 +596,10 @@ void projectionDescriptorsPinExactRoleKeyArgumentAndLuaDigest() throws Exception assertThat(descriptors).hasSize(1); RedisScriptDescriptor issuer = descriptors.stream() - .filter( - descriptor -> - descriptor - .scriptId() - .equals(AccountGameplayDelegationRedisClient.ISSUER_PROJECTION_SCRIPT_ID)) + .filter(descriptor -> + descriptor + .scriptId() + .equals(AccountGameplayDelegationRedisClient.ISSUER_PROJECTION_SCRIPT_ID)) .findFirst() .orElseThrow(); RedisScriptDescriptor account = @@ -720,11 +693,9 @@ void committedActivationDescriptorAndLuaPinOnlyExactLifecycleByteChange() throws RedisScriptDescriptor descriptor = new AccountGameplayDelegationRedisScriptContribution() .descriptors().stream() - .filter( - item -> - item.scriptId() - .equals( - AccountGameplayDelegationRedisClient.ACTIVE_TRANSITION_SCRIPT_ID)) + .filter(item -> + item.scriptId() + .equals(AccountGameplayDelegationRedisClient.ACTIVE_TRANSITION_SCRIPT_ID)) .findFirst() .orElseThrow(); assertThat(descriptor.owner()).isEqualTo("account-service"); @@ -832,10 +803,9 @@ void pendingRecordExpiryUsesInjectedClockAndRejectsExactExpiryBoundary() throws client( () -> fixture.connection(), Clock.fixed(Instant.ofEpochSecond(expirySecond), ZoneOffset.UTC)); - assertThatThrownBy( - () -> - atExpiry.requirePendingRecord( - fixture.pendingRecord().tokenHash(), pendingBytes, expiryMillis)) + assertThatThrownBy(() -> + atExpiry.requirePendingRecord( + fixture.pendingRecord().tokenHash(), pendingBytes, expiryMillis)) .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); } @@ -847,12 +817,11 @@ void pendingRecordAbsoluteExpiryRejectsExactMillisecondBoundary() throws Excepti () -> fixture.connection(), Clock.fixed(Instant.ofEpochMilli(fixture.absoluteExpiryMillis()), ZoneOffset.UTC)); - assertThatThrownBy( - () -> - atDeadline.requirePendingRecord( - fixture.pendingRecord().tokenHash(), - fixture.registryValue().get(), - fixture.absoluteExpiryMillis())) + assertThatThrownBy(() -> + atDeadline.requirePendingRecord( + fixture.pendingRecord().tokenHash(), + fixture.registryValue().get(), + fixture.absoluteExpiryMillis())) .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); } @@ -861,11 +830,8 @@ void committedActivationRejectsOwnerExpiryAtExactSecondBoundary() throws Excepti ActivationFixture fixture = activationFixture(Clock.fixed(Instant.ofEpochSecond(1_800_000_180L), ZoneOffset.UTC)); - assertThatThrownBy( - () -> - fixture - .client() - .activateCommittedPending(fixture.pendingReceipt(), fixture.owner())) + assertThatThrownBy(() -> + fixture.client().activateCommittedPending(fixture.pendingReceipt(), fixture.owner())) .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); verify(fixture.commands(), times(1)) .evalsha( @@ -877,12 +843,10 @@ void committedActivationRejectsChangedOwnerRecordAndMissingOrStaleRegistryValues throws Exception { ActivationFixture ownerMismatch = activationFixture(); doReturn("f".repeat(64)).when(ownerMismatch.owner()).tokenSha256(); - assertThatThrownBy( - () -> - ownerMismatch - .client() - .activateCommittedPending( - ownerMismatch.pendingReceipt(), ownerMismatch.owner())) + assertThatThrownBy(() -> + ownerMismatch + .client() + .activateCommittedPending(ownerMismatch.pendingReceipt(), ownerMismatch.owner())) .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); verify(ownerMismatch.commands(), times(1)) .evalsha( @@ -890,11 +854,8 @@ void committedActivationRejectsChangedOwnerRecordAndMissingOrStaleRegistryValues ActivationFixture missing = activationFixture(); missing.registryValue().set(null); - assertThatThrownBy( - () -> - missing - .client() - .activateCommittedPending(missing.pendingReceipt(), missing.owner())) + assertThatThrownBy(() -> + missing.client().activateCommittedPending(missing.pendingReceipt(), missing.owner())) .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); verify(missing.commands(), times(1)) .evalsha( @@ -916,11 +877,10 @@ void committedActivationRejectsChangedOwnerRecordAndMissingOrStaleRegistryValues void committedActivationRejectsWrongRoleExpiryReadbackAndInsufficientAof() throws Exception { ActivationFixture wrongRole = activationFixture(); doReturn("account_coord_admin").when(wrongRole.commands()).aclWhoami(); - assertThatThrownBy( - () -> - wrongRole - .client() - .activateCommittedPending(wrongRole.pendingReceipt(), wrongRole.owner())) + assertThatThrownBy(() -> + wrongRole + .client() + .activateCommittedPending(wrongRole.pendingReceipt(), wrongRole.owner())) .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); verify(wrongRole.commands(), times(1)) .evalsha( @@ -930,11 +890,10 @@ void committedActivationRejectsWrongRoleExpiryReadbackAndInsufficientAof() throw doReturn(wrongExpiry.absoluteExpiryMillis() + 1L) .when(wrongExpiry.commands()) .pexpiretime(any(byte[].class)); - assertThatThrownBy( - () -> - wrongExpiry - .client() - .activateCommittedPending(wrongExpiry.pendingReceipt(), wrongExpiry.owner())) + assertThatThrownBy(() -> + wrongExpiry + .client() + .activateCommittedPending(wrongExpiry.pendingReceipt(), wrongExpiry.owner())) .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); verify(wrongExpiry.commands(), times(1)) .evalsha( @@ -942,19 +901,16 @@ void committedActivationRejectsWrongRoleExpiryReadbackAndInsufficientAof() throw ActivationFixture wrongReadback = activationFixture(); AtomicInteger reads = new AtomicInteger(); - doAnswer( - invocation -> - reads.incrementAndGet() == 2 - ? ascii("unexpected-active-readback") - : wrongReadback.registryValue().get().clone()) + doAnswer(invocation -> + reads.incrementAndGet() == 2 + ? ascii("unexpected-active-readback") + : wrongReadback.registryValue().get().clone()) .when(wrongReadback.commands()) .get(any(byte[].class)); - assertThatThrownBy( - () -> - wrongReadback - .client() - .activateCommittedPending( - wrongReadback.pendingReceipt(), wrongReadback.owner())) + assertThatThrownBy(() -> + wrongReadback + .client() + .activateCommittedPending(wrongReadback.pendingReceipt(), wrongReadback.owner())) .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat(wrongReadback.absoluteExpiry().get()) .isEqualTo(wrongReadback.absoluteExpiryMillis()); @@ -963,12 +919,11 @@ void committedActivationRejectsWrongRoleExpiryReadbackAndInsufficientAof() throw doReturn(List.of(1L, 0L)) .when(insufficientAof.commands()) .dispatch(any(ProtocolKeyword.class), any(CommandOutput.class), any(CommandArgs.class)); - assertThatThrownBy( - () -> - insufficientAof - .client() - .activateCommittedPending( - insufficientAof.pendingReceipt(), insufficientAof.owner())) + assertThatThrownBy(() -> + insufficientAof + .client() + .activateCommittedPending( + insufficientAof.pendingReceipt(), insufficientAof.owner())) .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); assertThat( GameSessionAccountDelegationRegistryRecord.decode( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java index 44674f3587..3fa7f1e357 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationSignerTest.java @@ -148,11 +148,10 @@ private static synchronized void ensureEphemeralRsaPairs() throws Exception { private static Map castClaims(Map claims) { Map copy = new LinkedHashMap<>(); - claims.forEach( - (key, value) -> { - if (!(key instanceof String text)) throw new AssertionError("JWT claim key is not text"); - copy.put(text, value); - }); + claims.forEach((key, value) -> { + if (!(key instanceof String text)) throw new AssertionError("JWT claim key is not text"); + copy.put(text, value); + }); return copy; } @@ -415,11 +414,10 @@ void revalidatesPrivateProofOnlyInsideWritableTransactionAgainstCurrentOwner() t TransactionTemplate writable = new TransactionTemplate(fixture.transactionManager); int loadsBeforeOwnerCheck = fixture.publicSourceLoadCount.get(); - writable.execute( - status -> { - fixture.signer.requireCurrentCommittedSigner(proof); - return null; - }); + writable.execute(status -> { + fixture.signer.requireCurrentCommittedSigner(proof); + return null; + }); assertEquals(loadsBeforeOwnerCheck, fixture.publicSourceLoadCount.get()); TransactionTemplate readOnly = new TransactionTemplate(fixture.transactionManager); @@ -427,11 +425,10 @@ void revalidatesPrivateProofOnlyInsideWritableTransactionAgainstCurrentOwner() t assertThrows( AccountGameplayDelegationSigner.SigningUnavailableException.class, () -> - readOnly.execute( - status -> { - fixture.signer.requireCurrentCommittedSigner(proof); - return null; - })); + readOnly.execute(status -> { + fixture.signer.requireCurrentCommittedSigner(proof); + return null; + })); } @Test @@ -447,11 +444,10 @@ void revalidatesRepositoryIssuedCommittedSnapshotOnlyInsideWritableTransaction() int loadsBeforeOwnerCheck = fixture.publicSourceLoadCount.get(); new TransactionTemplate(fixture.transactionManager) - .execute( - status -> { - fixture.signer.requireCurrentCommittedSigner(committed); - return null; - }); + .execute(status -> { + fixture.signer.requireCurrentCommittedSigner(committed); + return null; + }); assertEquals(loadsBeforeOwnerCheck, fixture.publicSourceLoadCount.get()); TransactionTemplate readOnly = new TransactionTemplate(fixture.transactionManager); @@ -459,11 +455,10 @@ void revalidatesRepositoryIssuedCommittedSnapshotOnlyInsideWritableTransaction() assertThrows( AccountGameplayDelegationSigner.SigningUnavailableException.class, () -> - readOnly.execute( - status -> { - fixture.signer.requireCurrentCommittedSigner(committed); - return null; - })); + readOnly.execute(status -> { + fixture.signer.requireCurrentCommittedSigner(committed); + return null; + })); } @Test @@ -476,11 +471,10 @@ void committedSnapshotRecheckDeniesChangedSignerOrWithdrawnProtectedTrust() thro AccountGameplayDelegationSigner.SigningUnavailableException.class, () -> new TransactionTemplate(changedOwner.transactionManager) - .execute( - status -> { - changedOwner.signer.requireCurrentCommittedSigner(changedSnapshot); - return null; - })); + .execute(status -> { + changedOwner.signer.requireCurrentCommittedSigner(changedSnapshot); + return null; + })); Fixture withdrawnTrust = new Fixture(temporaryDirectory, false); var trustProof = withdrawnTrust.signer.signPendingCandidate(REQUEST_ID).verificationProof(); @@ -490,11 +484,10 @@ void committedSnapshotRecheckDeniesChangedSignerOrWithdrawnProtectedTrust() thro AccountGameplayDelegationSigner.SigningUnavailableException.class, () -> new TransactionTemplate(withdrawnTrust.transactionManager) - .execute( - status -> { - withdrawnTrust.signer.requireCurrentCommittedSigner(trustSnapshot); - return null; - })); + .execute(status -> { + withdrawnTrust.signer.requireCurrentCommittedSigner(trustSnapshot); + return null; + })); } private static CommittedCandidateVerificationData committedData( @@ -542,11 +535,10 @@ void refusesVerificationProofAfterCurrentCommittedSignerChangesOrTrustIsWithdraw assertThrows( AccountGameplayDelegationSigner.SigningUnavailableException.class, () -> - writable.execute( - status -> { - changedOwner.signer.requireCurrentCommittedSigner(proof); - return null; - })); + writable.execute(status -> { + changedOwner.signer.requireCurrentCommittedSigner(proof); + return null; + })); Fixture withdrawnTrust = new Fixture(temporaryDirectory, false); var trustProof = withdrawnTrust.signer.signPendingCandidate(REQUEST_ID).verificationProof(); @@ -556,11 +548,10 @@ void refusesVerificationProofAfterCurrentCommittedSignerChangesOrTrustIsWithdraw assertThrows( AccountGameplayDelegationSigner.SigningUnavailableException.class, () -> - trustTransaction.execute( - status -> { - withdrawnTrust.signer.requireCurrentCommittedSigner(trustProof); - return null; - })); + trustTransaction.execute(status -> { + withdrawnTrust.signer.requireCurrentCommittedSigner(trustProof); + return null; + })); } @Test @@ -576,11 +567,10 @@ void responseRecoveryAcceptsACommittedSignerAfterRotationOnlyWhileItsExactKeyIsR Files.writeString(fixture.privateRoot.resolve("current.key"), "unavailable private material"); new TransactionTemplate(fixture.transactionManager) - .execute( - status -> { - fixture.signer.requireCurrentCommittedRecoverySigner(committed); - return null; - }); + .execute(status -> { + fixture.signer.requireCurrentCommittedRecoverySigner(committed); + return null; + }); fixture.signer.requireRetainedCommittedPublicKey(committed); assertTrue(fixture.sourceLoadsWereOutsideTransactions.get()); @@ -589,11 +579,10 @@ void responseRecoveryAcceptsACommittedSignerAfterRotationOnlyWhileItsExactKeyIsR AccountGameplayDelegationSigner.SigningUnavailableException.class, () -> new TransactionTemplate(fixture.transactionManager) - .execute( - status -> { - fixture.signer.requireCurrentCommittedSigner(committed); - return null; - })); + .execute(status -> { + fixture.signer.requireCurrentCommittedSigner(committed); + return null; + })); } @Test @@ -605,11 +594,10 @@ void responseRecoveryRejectsMissingSubstitutedExpiredOrUntrustedHistoricalKey() missingKey.sourceJwks.set( jwksJson(mismatchedPair, "account-key-43").getBytes(StandardCharsets.UTF_8)); new TransactionTemplate(missingKey.transactionManager) - .execute( - status -> { - missingKey.signer.requireCurrentCommittedRecoverySigner(missingCommitted); - return null; - }); + .execute(status -> { + missingKey.signer.requireCurrentCommittedRecoverySigner(missingCommitted); + return null; + }); assertThrows( AccountGameplayDelegationSigner.SigningUnavailableException.class, () -> missingKey.signer.requireRetainedCommittedPublicKey(missingCommitted)); @@ -623,11 +611,10 @@ void responseRecoveryRejectsMissingSubstitutedExpiredOrUntrustedHistoricalKey() jwksJson(mismatchedPair, KID, mismatchedPair, "account-key-43") .getBytes(StandardCharsets.UTF_8)); new TransactionTemplate(substitutedKey.transactionManager) - .execute( - status -> { - substitutedKey.signer.requireCurrentCommittedRecoverySigner(substitutedCommitted); - return null; - }); + .execute(status -> { + substitutedKey.signer.requireCurrentCommittedRecoverySigner(substitutedCommitted); + return null; + }); assertThrows( AccountGameplayDelegationSigner.SigningUnavailableException.class, () -> substitutedKey.signer.requireRetainedCommittedPublicKey(substitutedCommitted)); @@ -654,11 +641,10 @@ void responseRecoveryRejectsMissingSubstitutedExpiredOrUntrustedHistoricalKey() AccountGameplayDelegationSigner.SigningUnavailableException.class, () -> new TransactionTemplate(expired.transactionManager) - .execute( - status -> { - expired.signer.requireCurrentCommittedRecoverySigner(expiredCommitted); - return null; - })); + .execute(status -> { + expired.signer.requireCurrentCommittedRecoverySigner(expiredCommitted); + return null; + })); Fixture withdrawnTrust = new Fixture(temporaryDirectory, false); var trustProof = withdrawnTrust.signer.signPendingCandidate(REQUEST_ID).verificationProof(); @@ -668,11 +654,10 @@ void responseRecoveryRejectsMissingSubstitutedExpiredOrUntrustedHistoricalKey() AccountGameplayDelegationSigner.SigningUnavailableException.class, () -> new TransactionTemplate(withdrawnTrust.transactionManager) - .execute( - status -> { - withdrawnTrust.signer.requireCurrentCommittedRecoverySigner(trustCommitted); - return null; - })); + .execute(status -> { + withdrawnTrust.signer.requireCurrentCommittedRecoverySigner(trustCommitted); + return null; + })); } @Test @@ -685,11 +670,10 @@ void refusesVerificationProofWhenPromotionReceiptFenceNoLongerMatches() throws E assertThrows( AccountGameplayDelegationSigner.SigningUnavailableException.class, () -> - writable.execute( - status -> { - fixture.signer.requireCurrentCommittedSigner(proof); - return null; - })); + writable.execute(status -> { + fixture.signer.requireCurrentCommittedSigner(proof); + return null; + })); } @Test @@ -1100,28 +1084,26 @@ private void configureProtectedBindings() { private void configureTrustedJwksSource() { when(trustedJwksSource.sourceIdentity()) - .thenAnswer( - invocation -> { - if (TransactionSynchronizationManager.isActualTransactionActive()) { - sourceLoadsWereOutsideTransactions.set(false); - } - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - return sourceIdentity; - }); + .thenAnswer(invocation -> { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + sourceLoadsWereOutsideTransactions.set(false); + } + assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + return sourceIdentity; + }); when(trustedJwksSource.load()) - .thenAnswer( - invocation -> { - if (TransactionSynchronizationManager.isActualTransactionActive()) { - sourceLoadsWereOutsideTransactions.set(false); - } - assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); - int load = publicSourceLoadCount.incrementAndGet(); - byte[] bytes = - load >= mutateSourceOnLoad && changedSourceBytes != null - ? changedSourceBytes - : sourceJwks.get(); - return new PublicJwksSnapshot(sourceIdentity, bytes); - }); + .thenAnswer(invocation -> { + if (TransactionSynchronizationManager.isActualTransactionActive()) { + sourceLoadsWereOutsideTransactions.set(false); + } + assertFalse(TransactionSynchronizationManager.isActualTransactionActive()); + int load = publicSourceLoadCount.incrementAndGet(); + byte[] bytes = + load >= mutateSourceOnLoad && changedSourceBytes != null + ? changedSourceBytes + : sourceJwks.get(); + return new PublicJwksSnapshot(sourceIdentity, bytes); + }); } private void configureCommittedSigner(CommittedSignerEvidence evidence) { @@ -1157,63 +1139,60 @@ private void configureIssuanceRepository() { when(issuance.readPendingSigningIdentity(REQUEST_ID)) .thenReturn(pendingSigningIdentity, pendingSigningIdentity); when(issuance.bindSignedCandidate(eq(REQUEST_ID), anyString(), eq(GENERATION))) - .thenAnswer( - invocation -> { - String jwt = invocation.getArgument(1); - transientJwt.set(jwt); - GameSessionAccountDelegationRegistryRecord record = - GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( - jwt, - GENERATION, - new IssuanceBinding( - ISSUANCE_OPERATION_ID.toString(), - REQUEST_ID.toString(), - REQUEST_DIGEST, - ACCOUNT_ID.toString()), - authoritySnapshot, - evidenceReference, - NOW.getEpochSecond(), - GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); - boundRecord.set(record); - return new BoundTokenCandidate( - REQUEST_ID, record.tokenHash(), record.kid(), record.signerGeneration()); - }); - when(issuance.readPendingRegistryCandidate(REQUEST_ID)) - .thenAnswer( - invocation -> { - GameSessionAccountDelegationRegistryRecord record = boundRecord.get(); - assertNotNull(record); - return new PendingRegistryCandidate( - pendingIdentity, - record.tokenHash(), - record.kid(), - record.signerGeneration(), - record.expiresAtEpochSecond(), - record.toCanonicalJsonBytes( - GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES), + .thenAnswer(invocation -> { + String jwt = invocation.getArgument(1); + transientJwt.set(jwt); + GameSessionAccountDelegationRegistryRecord record = + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + jwt, + GENERATION, + new IssuanceBinding( + ISSUANCE_OPERATION_ID.toString(), + REQUEST_ID.toString(), + REQUEST_DIGEST, + ACCOUNT_ID.toString()), authoritySnapshot, - evidenceReference); - }); + evidenceReference, + NOW.getEpochSecond(), + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES); + boundRecord.set(record); + return new BoundTokenCandidate( + REQUEST_ID, record.tokenHash(), record.kid(), record.signerGeneration()); + }); + when(issuance.readPendingRegistryCandidate(REQUEST_ID)) + .thenAnswer(invocation -> { + GameSessionAccountDelegationRegistryRecord record = boundRecord.get(); + assertNotNull(record); + return new PendingRegistryCandidate( + pendingIdentity, + record.tokenHash(), + record.kid(), + record.signerGeneration(), + record.expiresAtEpochSecond(), + record.toCanonicalJsonBytes( + GameSessionAccountDelegationProfile.MAX_REGISTRY_RECORD_BYTES), + authoritySnapshot, + evidenceReference); + }); } private void configureEnvelopeService() { when(envelopeService.sealPendingCandidate( eq(REQUEST_ID), any(CallerIdentity.class), anyString())) - .thenAnswer( - invocation -> { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - CallerIdentity caller = invocation.getArgument(1); - String jwt = invocation.getArgument(2); - assertEquals(WORKLOAD, caller.workload()); - assertEquals(CALLER_CONTEXT_ID, caller.contextId()); - assertEquals(transientJwt.get(), jwt); - return sealedObservation( - ISSUANCE_OPERATION_ID, - REQUEST_ID, - evidenceBundle, - Math.multiplyExact(pendingIdentity.expiresAtEpochSecond(), 1_000L) - + sealedExpiryDeltaMillis); - }); + .thenAnswer(invocation -> { + assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + CallerIdentity caller = invocation.getArgument(1); + String jwt = invocation.getArgument(2); + assertEquals(WORKLOAD, caller.workload()); + assertEquals(CALLER_CONTEXT_ID, caller.contextId()); + assertEquals(transientJwt.get(), jwt); + return sealedObservation( + ISSUANCE_OPERATION_ID, + REQUEST_ID, + evidenceBundle, + Math.multiplyExact(pendingIdentity.expiresAtEpochSecond(), 1_000L) + + sealedExpiryDeltaMillis); + }); } private void returnMissingCommittedEvidence() { @@ -1266,26 +1245,24 @@ private void changePendingIdentityAfterFirstRead() { private void returnMismatchedBoundCandidate() { when(issuance.bindSignedCandidate(eq(REQUEST_ID), anyString(), eq(GENERATION))) - .thenAnswer( - invocation -> { - transientJwt.set(invocation.getArgument(1)); - return new BoundTokenCandidate(REQUEST_ID, "f".repeat(64), KID, GENERATION); - }); + .thenAnswer(invocation -> { + transientJwt.set(invocation.getArgument(1)); + return new BoundTokenCandidate(REQUEST_ID, "f".repeat(64), KID, GENERATION); + }); } private void returnMismatchedEnvelopeReadback() { when(envelopeService.sealPendingCandidate( eq(REQUEST_ID), any(CallerIdentity.class), anyString())) - .thenAnswer( - invocation -> { - assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); - transientJwt.set(invocation.getArgument(2)); - return sealedObservation( - UUID.fromString("3a7c3d0c-ab15-4f86-b5af-9e29bc7d3543"), - REQUEST_ID, - evidenceBundle, - Math.multiplyExact(pendingIdentity.expiresAtEpochSecond(), 1_000L)); - }); + .thenAnswer(invocation -> { + assertTrue(TransactionSynchronizationManager.isActualTransactionActive()); + transientJwt.set(invocation.getArgument(2)); + return sealedObservation( + UUID.fromString("3a7c3d0c-ab15-4f86-b5af-9e29bc7d3543"), + REQUEST_ID, + evidenceBundle, + Math.multiplyExact(pendingIdentity.expiresAtEpochSecond(), 1_000L)); + }); } private void returnMismatchedSealedExpiry() { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistryTest.java index a3336bb2d7..d2ff7bb283 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayDelegationTokenRegistryTest.java @@ -122,11 +122,10 @@ void setUp() throws Exception { snapshot(), evidenceBundleReference()); when(repository.readPendingRegistryCandidate(UUID.fromString(REQUEST_ID))) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - return candidate; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return candidate; + }); when(commands.aclWhoami()) .thenReturn(AccountGameplayDelegationRedisClient.REQUIRED_ACL_IDENTITY); when(commands.scriptLoad(any(byte[].class))) @@ -161,10 +160,9 @@ void setUp() throws Exception { void rejectsAmbientAccountTransactionBeforeReadingCandidateOrOpeningRedis() { TransactionTemplate ambientTransaction = new TransactionTemplate(transactionManager); - assertThatThrownBy( - () -> - ambientTransaction.execute( - status -> registry.registerPending(UUID.fromString(REQUEST_ID)))) + assertThatThrownBy(() -> + ambientTransaction.execute( + status -> registry.registerPending(UUID.fromString(REQUEST_ID)))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("ambient Account transaction"); @@ -372,9 +370,8 @@ void rejectsScriptBytesThatDoNotMatchTheImmutableOwnerDescriptorDigest() { 16_384, getClass().getClassLoader()); - assertThatThrownBy( - () -> - alteredClient.registerPending(candidate.tokenHash(), encodedRecord, EXPIRY_MILLIS)) + assertThatThrownBy(() -> + alteredClient.registerPending(candidate.tokenHash(), encodedRecord, EXPIRY_MILLIS)) .isInstanceOf(AccountGameplayDelegationRedisClient.AccountCoordinationRedisException.class); verifyNoMoreInteractions(connection); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java index 86c606f8ee..c731ca583f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayPrimaryCredentialVerifierTest.java @@ -238,13 +238,12 @@ void canonicalModesAndDenialsPerformExactlyTwoKdfVerifications( when(crypto.hash(eq(2), eq(65536), eq(1), any(char[].class))) .thenReturn("process-local-decoy"); when(crypto.verify(anyString(), any(char[].class))) - .thenAnswer( - call -> { - String storedHash = call.getArgument(0); - String presented = new String((char[]) call.getArgument(1)); - return (storedHash.equals(PASSWORD_HASH) && presented.equals("password")) - || (storedHash.equals(OTP_HASH) && presented.equals("246810")); - }); + .thenAnswer(call -> { + String storedHash = call.getArgument(0); + String presented = new String((char[]) call.getArgument(1)); + return (storedHash.equals(PASSWORD_HASH) && presented.equals("password")) + || (storedHash.equals(OTP_HASH) && presented.equals("246810")); + }); if (denied) assertDenial( () -> verifier.verify(account, secret), AuthenticationErrorCodes.INVALID_CREDENTIALS); @@ -283,13 +282,12 @@ void lockedIdentityDenialStillCompletesTwoKdfVerifications(String secret) { when(crypto.hash(eq(2), eq(65536), eq(1), any(char[].class))) .thenReturn("process-local-decoy"); when(crypto.verify(anyString(), any(char[].class))) - .thenAnswer( - call -> { - String storedHash = call.getArgument(0); - return secret.equals("246810") - ? storedHash.equals(OTP_HASH) - : storedHash.equals(PASSWORD_HASH); - }); + .thenAnswer(call -> { + String storedHash = call.getArgument(0); + return secret.equals("246810") + ? storedHash.equals(OTP_HASH) + : storedHash.equals(PASSWORD_HASH); + }); assertDenial(() -> verifier.verify(account, secret), AuthenticationErrorCodes.ACCOUNT_LOCKED); verify(crypto, times(2)).verify(anyString(), any(char[].class)); } @@ -387,20 +385,17 @@ void verificationAndConsumptionRequireActualWritableTransaction(boolean readOnly TransactionSynchronizationManager.setCurrentTransactionReadOnly(readOnly); assertThatThrownBy(() -> verifier.verify(account, "password")) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - verifier.consumeOneTimeCredential( - account, new CredentialVerification(ACCOUNT_ID, 15L))) + assertThatThrownBy(() -> + verifier.consumeOneTimeCredential(account, new CredentialVerification(ACCOUNT_ID, 15L))) .isInstanceOf(IllegalStateException.class); verifyNoInteractions(challenges); } @Test void consumptionRejectsMismatchedAccountIdentityBeforeReadingChallenge() { - assertThatThrownBy( - () -> - verifier.consumeOneTimeCredential( - account, new CredentialVerification(UUID.randomUUID(), 15L))) + assertThatThrownBy(() -> + verifier.consumeOneTimeCredential( + account, new CredentialVerification(UUID.randomUUID(), 15L))) .isInstanceOf(IllegalStateException.class); verifyNoInteractions(challenges); } @@ -410,10 +405,8 @@ account, new CredentialVerification(UUID.randomUUID(), 15L))) void consumptionRequiresExactChallengeIdentityAndOwnership(boolean wrongOwner) { if (wrongOwner) challenge.setAccountId(43L); else challenge.setId(16L); - assertThatThrownBy( - () -> - verifier.consumeOneTimeCredential( - account, new CredentialVerification(ACCOUNT_ID, 15L))) + assertThatThrownBy(() -> + verifier.consumeOneTimeCredential(account, new CredentialVerification(ACCOUNT_ID, 15L))) .isInstanceOf(IllegalStateException.class); verify(challenges, never()).delete(any()); } @@ -421,10 +414,8 @@ account, new CredentialVerification(ACCOUNT_ID, 15L))) @Test void consumptionRequiresChallengeStillPresent() { when(challenges.findByAccountId(42L)).thenReturn(Optional.empty()); - assertThatThrownBy( - () -> - verifier.consumeOneTimeCredential( - account, new CredentialVerification(ACCOUNT_ID, 15L))) + assertThatThrownBy(() -> + verifier.consumeOneTimeCredential(account, new CredentialVerification(ACCOUNT_ID, 15L))) .isInstanceOf(IllegalStateException.class); verify(challenges, never()).delete(any()); } @@ -512,13 +503,12 @@ void realCanonicalOwnerConsumesOnlyAfterNewPendingAndExactRetrySkipsConsumedOtp( when(fixture.issuance.readCurrentGameplayLoginReplay(REQUEST_ID)) .thenReturn(Optional.empty(), Optional.empty(), Optional.of(replay)); when(fixture.issuance.beginPendingForAccount(any(), any(), any(), any(), any())) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - verify(challenges, never()).delete(any()); - transactions.events.add("pending"); - return pending; - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + verify(challenges, never()).delete(any()); + transactions.events.add("pending"); + return pending; + }); doAnswer( call -> { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionServiceTest.java index 21d89cd499..2d63613cf2 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountHostingSubscriptionTerminalResolutionServiceTest.java @@ -327,12 +327,11 @@ private void currentActors(AccountAuthenticatedActor... currentActors) { events.add("current-actor-" + ordinal); @SuppressWarnings("unchecked") Function action = invocation.getArgument(1); - return inOwnerTransaction( - () -> { - Object result = action.apply(currentActors[index]); - events.add("current-account-return-" + ordinal); - return result; - }); + return inOwnerTransaction(() -> { + Object result = action.apply(currentActors[index]); + events.add("current-account-return-" + ordinal); + return result; + }); }) .when(actors) .withCurrentAccount(eq(CONTROL_UI_JWT), any()); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java index 95bfbca50d..7f77facedf 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksConfigMapClientTest.java @@ -57,15 +57,14 @@ void observesOnlyFixedConfigMapAfterPrincipalAndNamespaceChecks() { ApiCall.READ_TARGET_NAMESPACE, ApiCall.READ_JWKS_CONFIG_MAP); assertThat(api.calls) - .allMatch( - call -> - Set.of( - ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, - ApiCall.READ_KUBE_SYSTEM_NAMESPACE, - ApiCall.READ_TARGET_NAMESPACE, - ApiCall.READ_JWKS_CONFIG_MAP, - ApiCall.PATCH_JWKS_CONFIG_MAP) - .contains(call)); + .allMatch(call -> + Set.of( + ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL, + ApiCall.READ_KUBE_SYSTEM_NAMESPACE, + ApiCall.READ_TARGET_NAMESPACE, + ApiCall.READ_JWKS_CONFIG_MAP, + ApiCall.PATCH_JWKS_CONFIG_MAP) + .contains(call)); } @org.junit.jupiter.api.Test @@ -259,10 +258,8 @@ void rejectsPrivateJwkMaterialBeforeAnyApiCall() { AccountJwtJwksConfigMapClient.GENERATION_DATA_KEY, marker("op-private")); - assertThatThrownBy( - () -> - client(api) - .publish(new ConfigMapSnapshot(CONFIG_MAP_UID, "41", Map.of()), privateJwks)) + assertThatThrownBy(() -> + client(api).publish(new ConfigMapSnapshot(CONFIG_MAP_UID, "41", Map.of()), privateJwks)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Account public JWKS contains private material"); @@ -399,11 +396,10 @@ void activeMarkerDoesNotTreatExactDataAtUnchangedPriorVersionAsSuccessfulCas() { @org.junit.jupiter.api.Test void jwksConfigMapAccessHasNoSecretListCreateOrDeleteCapability() { assertThat(ApiCall.values()) - .noneMatch( - call -> - call.name().contains("SECRET") - || call.name().contains("CREATE") - || call.name().contains("DELETE")); + .noneMatch(call -> + call.name().contains("SECRET") + || call.name().contains("CREATE") + || call.name().contains("DELETE")); assertThat(ApiCall.values()) .filteredOn(call -> call.name().contains("JWKS_CONFIG_MAP")) .containsExactly(ApiCall.READ_JWKS_CONFIG_MAP, ApiCall.PATCH_JWKS_CONFIG_MAP); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationServiceTest.java index 29cfc32868..b9622548b4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksPrepublicationServiceTest.java @@ -70,14 +70,12 @@ void currentGenerationIsPrepublishedWithRetainedKeysAndExactAccountReadbackOnly( .thenReturn(Optional.empty()); when(fixture.client.observe()).thenReturn(fixture.snapshot); when(fixture.client.publish(eq(fixture.snapshot), anyMap())) - .thenAnswer( - invocation -> { - Map desired = invocation.getArgument(1); - Map readback = new LinkedHashMap<>(desired); - readback.put("unrelated.txt", "preserved"); - return new CasObservation( - CONFIG_MAP_UID, "41", "42", desired, readback, Outcome.APPLIED); - }); + .thenAnswer(invocation -> { + Map desired = invocation.getArgument(1); + Map readback = new LinkedHashMap<>(desired); + readback.put("unrelated.txt", "preserved"); + return new CasObservation(CONFIG_MAP_UID, "41", "42", desired, readback, Outcome.APPLIED); + }); when(fixture.publicationRepository.recordPrepublicationIntent( eq(accountBinding()), eq(trustFence(fixture.binding)), @@ -90,14 +88,13 @@ void currentGenerationIsPrepublishedWithRetainedKeysAndExactAccountReadbackOnly( any(String.class), any(String.class), any(String.class))) - .thenAnswer( - invocation -> - intent( - fixture, - invocation.getArgument(9), - invocation.getArgument(10), - invocation.getArgument(7), - invocation.getArgument(8))); + .thenAnswer(invocation -> + intent( + fixture, + invocation.getArgument(9), + invocation.getArgument(10), + invocation.getArgument(7), + invocation.getArgument(8))); when(fixture.publicationRepository.recordPublicationReceipt( eq(accountBinding()), eq(trustFence(fixture.binding)), @@ -108,17 +105,15 @@ void currentGenerationIsPrepublishedWithRetainedKeysAndExactAccountReadbackOnly( eq("42"), any(String.class), any(String.class))) - .thenAnswer( - invocation -> - PublicationReceipt.create( - intent( - fixture, - invocation.getArgument(7), - invocation.getArgument(8), - "41", - AccountJwtJwksPublicationRepository.snapshotDigest( - fixture.snapshot.data())), - invocation.getArgument(6))); + .thenAnswer(invocation -> + PublicationReceipt.create( + intent( + fixture, + invocation.getArgument(7), + invocation.getArgument(8), + "41", + AccountJwtJwksPublicationRepository.snapshotDigest(fixture.snapshot.data())), + invocation.getArgument(6))); PublicationReceipt receipt = fixture.service.prepublishCurrentGeneration(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java index b1e7cb41eb..59f9c0aac4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java @@ -404,63 +404,58 @@ void realPrincipalReviewOutageRemainsRetryableThroughCurrentReadGrpc() throws Ex var reviewStatus = new AtomicInteger(503); var json = JsonMapper.builder().build(); when(operation.send(any(), any())) - .thenAnswer( - invocation -> { - ApiCall call = invocation.getArgument(0); - int status = - call == ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL ? reviewStatus.get() : 200; - Map body = - switch (call) { - case REVIEW_AUTHENTICATED_PRINCIPAL -> - status == 201 - ? Map.of( - "apiVersion", "authentication.k8s.io/v1", - "kind", "SelfSubjectReview", - "status", - Map.of( - "userInfo", - Map.of("username", parsed.expectedApiUsername()))) - : Map.of(); - case READ_KUBE_SYSTEM_NAMESPACE, READ_TARGET_NAMESPACE -> - Map.of( - "apiVersion", - "v1", - "kind", - "Namespace", - "metadata", - Map.of( - "name", - call == ApiCall.READ_KUBE_SYSTEM_NAMESPACE - ? "kube-system" - : NAMESPACE, - "uid", - call == ApiCall.READ_KUBE_SYSTEM_NAMESPACE - ? CLUSTER_UID - : NAMESPACE_UID), + .thenAnswer(invocation -> { + ApiCall call = invocation.getArgument(0); + int status = call == ApiCall.REVIEW_AUTHENTICATED_PRINCIPAL ? reviewStatus.get() : 200; + Map body = + switch (call) { + case REVIEW_AUTHENTICATED_PRINCIPAL -> + status == 201 + ? Map.of( + "apiVersion", "authentication.k8s.io/v1", + "kind", "SelfSubjectReview", "status", - Map.of("phase", "Active")); - case READ_JWKS_CONFIG_MAP -> + Map.of( + "userInfo", Map.of("username", parsed.expectedApiUsername()))) + : Map.of(); + case READ_KUBE_SYSTEM_NAMESPACE, READ_TARGET_NAMESPACE -> + Map.of( + "apiVersion", + "v1", + "kind", + "Namespace", + "metadata", + Map.of( + "name", + call == ApiCall.READ_KUBE_SYSTEM_NAMESPACE ? "kube-system" : NAMESPACE, + "uid", + call == ApiCall.READ_KUBE_SYSTEM_NAMESPACE + ? CLUSTER_UID + : NAMESPACE_UID), + "status", + Map.of("phase", "Active")); + case READ_JWKS_CONFIG_MAP -> + Map.of( + "apiVersion", + "v1", + "kind", + "ConfigMap", + "metadata", Map.of( - "apiVersion", - "v1", - "kind", - "ConfigMap", - "metadata", - Map.of( - "name", - AccountJwtJwksConfigMapClient.CONFIG_MAP_NAME, - "namespace", - NAMESPACE, - "uid", - CONFIG_MAP_UID, - "resourceVersion", - fixture.snapshot.resourceVersion()), - "data", - fixture.snapshot.data()); - default -> throw new AssertionError("Unexpected public-read API call"); - }; - return new ApiResponse(status, json.writeValueAsBytes(body)); - }); + "name", + AccountJwtJwksConfigMapClient.CONFIG_MAP_NAME, + "namespace", + NAMESPACE, + "uid", + CONFIG_MAP_UID, + "resourceVersion", + fixture.snapshot.resourceVersion()), + "data", + fixture.snapshot.data()); + default -> throw new AssertionError("Unexpected public-read API call"); + }; + return new ApiResponse(status, json.writeValueAsBytes(body)); + }); var source = new AccountJwtJwksTrustedSource( new AccountJwtJwksConfigMapClient(api), @@ -704,20 +699,19 @@ void movingOwnerNeverLaundersUidTrustMarkerOrOwnedByteTamper() { fixture.accountBinding, fixture.trustFence)) .thenReturn(Optional.of(fixture.publication), Optional.of(after)); when(fixture.configMapClient.observe()) - .thenAnswer( - invocation -> { - if (tamper.equals("trust")) - when(fixture.materializerTrust.current()) - .thenReturn(Optional.of(binding(CLUSTER_UID, NAMESPACE_UID, "other-trust"))); - Map data = new LinkedHashMap<>(fixture.snapshot.data()); - if (tamper.equals("marker")) - data.put("jwt-generation.json", fixture.initialMarker + " "); - if (tamper.equals("jwks")) data.put("jwks.json", "{\"keys\":[]}"); - return new ConfigMapSnapshot( - tamper.equals("uid") ? "44444444-4444-4444-8444-444444444444" : CONFIG_MAP_UID, - "42", - data); - }); + .thenAnswer(invocation -> { + if (tamper.equals("trust")) + when(fixture.materializerTrust.current()) + .thenReturn(Optional.of(binding(CLUSTER_UID, NAMESPACE_UID, "other-trust"))); + Map data = new LinkedHashMap<>(fixture.snapshot.data()); + if (tamper.equals("marker")) + data.put("jwt-generation.json", fixture.initialMarker + " "); + if (tamper.equals("jwks")) data.put("jwks.json", "{\"keys\":[]}"); + return new ConfigMapSnapshot( + tamper.equals("uid") ? "44444444-4444-4444-8444-444444444444" : CONFIG_MAP_UID, + "42", + data); + }); assertRejectedPublicRead(fixture); verify(fixture.configMapClient).observe(); } @@ -728,26 +722,22 @@ void movedOwnerCannotChangeTheAnchoredUidEvenWhenPriorLiveBytesStillQualify() { Fixture fixture = new Fixture(); AtomicInteger reads = new AtomicInteger(); when(fixture.desiredStateRepository.readLockedEnrollmentState(fixture.accountBinding)) - .thenAnswer( - invocation -> { - if (reads.incrementAndGet() == 2) { - fixture.useStableCommittedState(); - var committed = - fixture - .desiredStateRepository - .readCurrentCommittedSigner( - fixture.accountBinding, - fixture.trustFence, - API_BINDING_DIGEST, - "api-r1") - .orElseThrow(); - when(committed.promotion().publicConfigMapUid()) - .thenReturn("44444444-4444-4444-8444-444444444444"); - when(committed.publicReceipt().configMapUid()) - .thenReturn("44444444-4444-4444-8444-444444444444"); - } - return fixture.desiredStateRepository.readEnrollmentState(fixture.accountBinding); - }); + .thenAnswer(invocation -> { + if (reads.incrementAndGet() == 2) { + fixture.useStableCommittedState(); + var committed = + fixture + .desiredStateRepository + .readCurrentCommittedSigner( + fixture.accountBinding, fixture.trustFence, API_BINDING_DIGEST, "api-r1") + .orElseThrow(); + when(committed.promotion().publicConfigMapUid()) + .thenReturn("44444444-4444-4444-8444-444444444444"); + when(committed.publicReceipt().configMapUid()) + .thenReturn("44444444-4444-4444-8444-444444444444"); + } + return fixture.desiredStateRepository.readEnrollmentState(fixture.accountBinding); + }); assertRejectedPublicRead(fixture); verify(fixture.configMapClient).observe(); assertThat(reads.get()).isEqualTo(2); @@ -775,11 +765,10 @@ void movementRequalificationKeepsInitialPinAndCapturedCancellation() throws Exce Fixture cancelled = new Fixture(); try (var context = Context.current().withCancellation()) { when(cancelled.configMapClient.observe()) - .thenAnswer( - invocation -> { - context.cancel(null); - return cancelled.snapshot; - }); + .thenAnswer(invocation -> { + context.cancel(null); + return cancelled.snapshot; + }); assertThatThrownBy(() -> context.call(cancelled.source::currentPublicRead)) .isInstanceOf(SourceUnavailableException.class); verify(cancelled.configMapClient).observe(); @@ -849,13 +838,12 @@ void movementWithVersionOnlyReadbackRequiresAFreshCoherentTrial() { .thenReturn(Optional.of(fixture.publication), Optional.of(later)); when(fixture.configMapClient.observe()) .thenReturn(new ConfigMapSnapshot(CONFIG_MAP_UID, "43", fixture.snapshot.data())) - .thenAnswer( - invocation -> { - assertThatThrownBy(fixture.source::load) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Account trusted public JWKS source was rejected"); - return new ConfigMapSnapshot(CONFIG_MAP_UID, "44", fixture.snapshot.data()); - }); + .thenAnswer(invocation -> { + assertThatThrownBy(fixture.source::load) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + return new ConfigMapSnapshot(CONFIG_MAP_UID, "44", fixture.snapshot.data()); + }); var result = fixture.source.currentPublicRead(); assertThat(result.sourceIdentity().configMapUid()).isEqualTo(CONFIG_MAP_UID); @@ -944,25 +932,23 @@ public long nanoTime() { try (var incoming = Context.current().withDeadline(deadline, scheduler)) { AtomicInteger trustReads = new AtomicInteger(); when(fixture.materializerTrust.current()) - .thenAnswer( - invocation -> { - assertThat(Context.current().getDeadline()).isSameAs(deadline); - if (trustReads.incrementAndGet() == (afterMovement ? 3 : 1)) { - if (failure.equals("cancel")) incoming.cancel(null); - else ticks.set(TimeUnit.SECONDS.toNanos(2)); - } - return Optional.of(fixture.binding); - }); - incoming.run( - () -> { - if (afterMovement) assertRejectedPublicRead(fixture); - else - assertThatThrownBy(fixture.source::currentPublicRead) - .isExactlyInstanceOf(SourceUnavailableException.class); - assertThatThrownBy(fixture.source::load) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Account trusted public JWKS source was rejected"); + .thenAnswer(invocation -> { + assertThat(Context.current().getDeadline()).isSameAs(deadline); + if (trustReads.incrementAndGet() == (afterMovement ? 3 : 1)) { + if (failure.equals("cancel")) incoming.cancel(null); + else ticks.set(TimeUnit.SECONDS.toNanos(2)); + } + return Optional.of(fixture.binding); }); + incoming.run(() -> { + if (afterMovement) assertRejectedPublicRead(fixture); + else + assertThatThrownBy(fixture.source::currentPublicRead) + .isExactlyInstanceOf(SourceUnavailableException.class); + assertThatThrownBy(fixture.source::load) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + }); assertThat(trustReads.get()).isEqualTo(afterMovement ? 3 : 1); verify(fixture.configMapClient, times(afterMovement ? 1 : 0)).observe(); } @@ -1000,14 +986,13 @@ void establishedPinReadProgressesWhileAnotherRemoteObservationIsBlocked() throws CountDownLatch release = new CountDownLatch(1); AtomicInteger observations = new AtomicInteger(); when(fixture.configMapClient.observe()) - .thenAnswer( - invocation -> { - if (observations.incrementAndGet() == 1) { - blocked.countDown(); - assertThat(release.await(5, TimeUnit.SECONDS)).isTrue(); - } - return fixture.snapshot; - }); + .thenAnswer(invocation -> { + if (observations.incrementAndGet() == 1) { + blocked.countDown(); + assertThat(release.await(5, TimeUnit.SECONDS)).isTrue(); + } + return fixture.snapshot; + }); var pool = Executors.newFixedThreadPool(2); try { var first = pool.submit(fixture.source::currentPublicRead); @@ -1039,19 +1024,18 @@ void initiallyQueuedReadersReleaseInitializationMonitorOnceThePinIsInstalled() t new java.util.concurrent.ConcurrentLinkedQueue<>(); AtomicInteger observations = new AtomicInteger(); when(fixture.configMapClient.observe()) - .thenAnswer( - invocation -> { - int current = observations.incrementAndGet(); - if (current == 1) { - firstWorker.set(Thread.currentThread()); - firstRemote.countDown(); - assertThat(releaseFirst.await(5, TimeUnit.SECONDS)).isTrue(); - } else if (current == 2) { - secondRemote.countDown(); - assertThat(releaseSecond.await(5, TimeUnit.SECONDS)).isTrue(); - } - return fixture.snapshot; - }); + .thenAnswer(invocation -> { + int current = observations.incrementAndGet(); + if (current == 1) { + firstWorker.set(Thread.currentThread()); + firstRemote.countDown(); + assertThat(releaseFirst.await(5, TimeUnit.SECONDS)).isTrue(); + } else if (current == 2) { + secondRemote.countDown(); + assertThat(releaseSecond.await(5, TimeUnit.SECONDS)).isTrue(); + } + return fixture.snapshot; + }); var pool = Executors.newFixedThreadPool(3); var completed = new java.util.concurrent.ExecutorCompletionService< @@ -1060,28 +1044,26 @@ void initiallyQueuedReadersReleaseInitializationMonitorOnceThePinIsInstalled() t var first = completed.submit(fixture.source::currentPublicRead); assertThat(firstRemote.await(5, TimeUnit.SECONDS)).isTrue(); for (int i = 0; i < 2; i++) { - completed.submit( - () -> { - queuedWorkers.add(Thread.currentThread()); - queued.countDown(); - return fixture.source.currentPublicRead(); - }); + completed.submit(() -> { + queuedWorkers.add(Thread.currentThread()); + queued.countDown(); + return fixture.source.currentPublicRead(); + }); } assertThat(queued.await(5, TimeUnit.SECONDS)).isTrue(); org.awaitility.Awaitility.await() .atMost(2, TimeUnit.SECONDS) - .untilAsserted( - () -> { - assertThat(queuedWorkers).hasSize(2); - for (Thread worker : queuedWorkers) { - var info = - java.lang.management.ManagementFactory.getThreadMXBean() - .getThreadInfo(worker.threadId()); - assertThat(info).isNotNull(); - assertThat(info.getThreadState()).isEqualTo(Thread.State.BLOCKED); - assertThat(info.getLockOwnerId()).isEqualTo(firstWorker.get().threadId()); - } - }); + .untilAsserted(() -> { + assertThat(queuedWorkers).hasSize(2); + for (Thread worker : queuedWorkers) { + var info = + java.lang.management.ManagementFactory.getThreadMXBean() + .getThreadInfo(worker.threadId()); + assertThat(info).isNotNull(); + assertThat(info.getThreadState()).isEqualTo(Thread.State.BLOCKED); + assertThat(info.getLockOwnerId()).isEqualTo(firstWorker.get().threadId()); + } + }); releaseFirst.countDown(); assertThat(first.get(5, TimeUnit.SECONDS).jwksBytes()) .containsExactly(JWKS_1.getBytes(StandardCharsets.UTF_8)); @@ -1118,40 +1100,37 @@ void competingFirstReadersCannotInstallConflictingSourcePins() throws Exception AtomicReference firstWorker = new AtomicReference<>(); AtomicReference secondWorker = new AtomicReference<>(); when(fixture.configMapClient.observe()) - .thenAnswer( - invocation -> { - if (observations.incrementAndGet() == 1) { - firstWorker.set(Thread.currentThread()); - blocked.countDown(); - assertThat(release.await(5, TimeUnit.SECONDS)).isTrue(); - return fixture.snapshot; - } - return new ConfigMapSnapshot( - "44444444-4444-4444-8444-444444444444", "42", fixture.snapshot.data()); - }); + .thenAnswer(invocation -> { + if (observations.incrementAndGet() == 1) { + firstWorker.set(Thread.currentThread()); + blocked.countDown(); + assertThat(release.await(5, TimeUnit.SECONDS)).isTrue(); + return fixture.snapshot; + } + return new ConfigMapSnapshot( + "44444444-4444-4444-8444-444444444444", "42", fixture.snapshot.data()); + }); var pool = Executors.newFixedThreadPool(2); try { var first = pool.submit(fixture.source::currentPublicRead); assertThat(blocked.await(5, TimeUnit.SECONDS)).isTrue(); var second = - pool.submit( - () -> { - secondWorker.set(Thread.currentThread()); - secondStarted.countDown(); - return fixture.source.currentPublicRead(); - }); + pool.submit(() -> { + secondWorker.set(Thread.currentThread()); + secondStarted.countDown(); + return fixture.source.currentPublicRead(); + }); assertThat(secondStarted.await(5, TimeUnit.SECONDS)).isTrue(); org.awaitility.Awaitility.await() .atMost(2, TimeUnit.SECONDS) - .untilAsserted( - () -> { - var info = - java.lang.management.ManagementFactory.getThreadMXBean() - .getThreadInfo(secondWorker.get().threadId()); - assertThat(info).isNotNull(); - assertThat(info.getThreadState()).isEqualTo(Thread.State.BLOCKED); - assertThat(info.getLockOwnerId()).isEqualTo(firstWorker.get().threadId()); - }); + .untilAsserted(() -> { + var info = + java.lang.management.ManagementFactory.getThreadMXBean() + .getThreadInfo(secondWorker.get().threadId()); + assertThat(info).isNotNull(); + assertThat(info.getThreadState()).isEqualTo(Thread.State.BLOCKED); + assertThat(info.getLockOwnerId()).isEqualTo(firstWorker.get().threadId()); + }); release.countDown(); assertThat(first.get(5, TimeUnit.SECONDS).sourceIdentity().configMapUid()) .isEqualTo(CONFIG_MAP_UID); @@ -1837,10 +1816,9 @@ private static void assertRejectedPublicRead(Fixture fixture) { var guard = mock(AccountPublicJwksReadWorkloadGuard.class); when(guard.requireCaller()) .thenReturn(mock(AccountPublicJwksReadWorkloadGuard.ProtectedCaller.class)); - assertThatThrownBy( - () -> - new AccountPublicJwksReadService(fixture.source, guard) - .read(AccountPublicJwksReadCodec.request())) + assertThatThrownBy(() -> + new AccountPublicJwksReadService(fixture.source, guard) + .read(AccountPublicJwksReadCodec.request())) .isExactlyInstanceOf( net.firedevops.firemud.common.security.AccountPublicJwksCache.InvalidJwksException .class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapperTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapperTest.java index a4971bb393..dc271262e0 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapperTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerProtoMapperTest.java @@ -107,40 +107,35 @@ void receiverMetadataRequestIsClosedAndContainsOnlyCanonicalLocalSelectors() { assertThat(parsed.projectedPodUid()).isEqualTo("66666666-6666-4666-8666-666666666666"); assertThat(parsed.serverLeafSpkiSha256()).isEqualTo("a".repeat(64)); - assertThatThrownBy( - () -> - mapper.parseReceiverMetadataRequest( - GetCurrentReadinessReceiverMetadataRequest.getDefaultInstance())) + assertThatThrownBy(() -> + mapper.parseReceiverMetadataRequest( + GetCurrentReadinessReceiverMetadataRequest.getDefaultInstance())) .isInstanceOf( AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException.class); - assertThatThrownBy( - () -> - mapper.parseReceiverMetadataRequest( - request.toBuilder() - .setProjectedPodUid("66666666-6666-4666-8666-66666666666A") - .build())) + assertThatThrownBy(() -> + mapper.parseReceiverMetadataRequest( + request.toBuilder() + .setProjectedPodUid("66666666-6666-4666-8666-66666666666A") + .build())) .isInstanceOf( AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException.class); - assertThatThrownBy( - () -> - mapper.parseReceiverMetadataRequest( - request.toBuilder().setServerLeafSpkiSha256("A".repeat(64)).build())) + assertThatThrownBy(() -> + mapper.parseReceiverMetadataRequest( + request.toBuilder().setServerLeafSpkiSha256("A".repeat(64)).build())) .isInstanceOf( AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException.class); - assertThatThrownBy( - () -> - mapper.parseReceiverMetadataRequest( - request.toBuilder().setProjectedPodUid("6".repeat(4096)).build())) + assertThatThrownBy(() -> + mapper.parseReceiverMetadataRequest( + request.toBuilder().setProjectedPodUid("6".repeat(4096)).build())) .isInstanceOf( AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException.class); UnknownFieldSet unknown = UnknownFieldSet.newBuilder() .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) .build(); - assertThatThrownBy( - () -> - mapper.parseReceiverMetadataRequest( - request.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + mapper.parseReceiverMetadataRequest( + request.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf( AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerServiceTest.java index 650134593e..fb985e0cdc 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessProbeOwnerServiceTest.java @@ -69,29 +69,26 @@ void selectsOwnerContextThenObservesInventoryBeforeOpeningTheOwnerReadTransactio ObservationPurpose.STRICT_READY, selector.rotationOperationId(), "9".repeat(64)); when(repository.readCurrentInventoryObservationContext( eq(BINDING), eq(TRUST), eq(selector.rotationOperationId()))) - .thenAnswer( - ignored -> { - order.add("context"); - return context; - }); + .thenAnswer(ignored -> { + order.add("context"); + return context; + }); when(inventorySource.observe(context)) - .thenAnswer( - ignored -> { - assertThat(order).containsExactly("transaction", "context", "commit"); - order.add("inventory"); - return snapshot; - }); + .thenAnswer(ignored -> { + assertThat(order).containsExactly("transaction", "context", "commit"); + order.add("inventory"); + return snapshot; + }); OwnerProbeEvidence evidence = mock(OwnerProbeEvidence.class); when(repository.readCurrentProbeOwner( eq(BINDING), eq(TRUST), eq(selector), eq(snapshot), eq(BINDING.namespace()))) - .thenAnswer( - ignored -> { - order.add("repository"); - assertThat(order) - .containsExactly( - "transaction", "context", "commit", "inventory", "transaction", "repository"); - return evidence; - }); + .thenAnswer(ignored -> { + order.add("repository"); + assertThat(order) + .containsExactly( + "transaction", "context", "commit", "inventory", "transaction", "repository"); + return evidence; + }); TransactionTemplate transaction = new TransactionTemplate(new RecordingTransactionManager(order)); AccountJwtReadinessProbeService service = diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverMetadataServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverMetadataServiceTest.java index 8f6a75954e..92a7c95d35 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverMetadataServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessReceiverMetadataServiceTest.java @@ -139,23 +139,20 @@ void clearTransactionState() { @Test void selectsCurrentProtectedOperationAndReturnsOnlyRecheckedMetadataWithoutCreatingPlan() { when(inventorySource.observe(context)) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return inventory; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return inventory; + }); when(trustedJwksSource.sourceIdentity()) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return sourceIdentity; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return sourceIdentity; + }); when(trustedJwksSource.load()) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return new PublicJwksSnapshot(sourceIdentity, PUBLIC_JWKS_BYTES); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new PublicJwksSnapshot(sourceIdentity, PUBLIC_JWKS_BYTES); + }); var response = service.getCurrentReadinessReceiverMetadata(request().build()); @@ -220,17 +217,15 @@ public void rollback(TransactionStatus status) { .thenReturn(context); when(repository.readCurrentPlan(accountBinding, trustFence, OPERATION_ID)).thenReturn(plan); when(inventorySource.observe(context)) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return inventory; - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return inventory; + }); when(trustedJwksSource.load()) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return new PublicJwksSnapshot(sourceIdentity, PUBLIC_JWKS_BYTES); - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new PublicJwksSnapshot(sourceIdentity, PUBLIC_JWKS_BYTES); + }); var clock = Clock.fixed(Instant.ofEpochSecond(NOW), ZoneOffset.UTC); var realProbeService = new AccountJwtReadinessProbeService( @@ -272,10 +267,9 @@ void deniesMissingProtectedJwksWithoutLeakingSourceFailureDetails() { @Test void rejectsMalformedRequestBeforeReadingPlanInventoryOrPublicJwks() { - assertThatThrownBy( - () -> - service.getCurrentReadinessReceiverMetadata( - GetCurrentReadinessReceiverMetadataRequest.getDefaultInstance())) + assertThatThrownBy(() -> + service.getCurrentReadinessReceiverMetadata( + GetCurrentReadinessReceiverMetadataRequest.getDefaultInstance())) .isInstanceOf( AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException.class); @@ -283,10 +277,9 @@ void rejectsMalformedRequestBeforeReadingPlanInventoryOrPublicJwks() { UnknownFieldSet.newBuilder() .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) .build(); - assertThatThrownBy( - () -> - service.getCurrentReadinessReceiverMetadata( - request().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + service.getCurrentReadinessReceiverMetadata( + request().setUnknownFields(unknown).build())) .isInstanceOf( AccountJwtReadinessProbeOwnerProtoMapper.InvalidOwnerReadRequestException.class); @@ -378,11 +371,10 @@ void rejectsMismatchedJwksSourceOrPublicBytes() { when(trustedJwksSource.sourceIdentity()) .thenReturn(sourceIdentity("33333333-3333-4333-8333-333333333333", "account-api-r1")); when(trustedJwksSource.load()) - .thenAnswer( - ignored -> - new PublicJwksSnapshot( - sourceIdentity("88888888-8888-4888-8888-888888888888", "account-api-r1"), - PUBLIC_JWKS_BYTES)); + .thenAnswer(ignored -> + new PublicJwksSnapshot( + sourceIdentity("88888888-8888-4888-8888-888888888888", "account-api-r1"), + PUBLIC_JWKS_BYTES)); assertUnavailable(request().build()); setUp(); @@ -448,13 +440,12 @@ void rejectsOperationThatAdvancesDuringSecondInventoryAndJwksRead() { AtomicInteger inventoryReads = new AtomicInteger(); AtomicBoolean secondNetworkPhaseComplete = new AtomicBoolean(); when(inventorySource.observe(context)) - .thenAnswer( - ignored -> { - if (inventoryReads.incrementAndGet() == 2) { - secondNetworkPhaseComplete.set(true); - } - return inventory; - }); + .thenAnswer(ignored -> { + if (inventoryReads.incrementAndGet() == 2) { + secondNetworkPhaseComplete.set(true); + } + return inventory; + }); when(probeService.readCurrentInventoryObservationContext(accountBinding, trustFence)) .thenAnswer(ignored -> secondNetworkPhaseComplete.get() ? rotatedContext : context); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyringTest.java index 4e515e2997..5903d25f30 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyringTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationFingerprintKeyringTest.java @@ -98,14 +98,13 @@ void missingWithdrawnExpiredOrInsufficientlyRetainedOriginalKeyFailsClosed() { for (Snapshot snapshot : unavailableSnapshots) { AccountOperatorAuthorizationFingerprintKeyring keyring = keyring(snapshot); - assertThatThrownBy( - () -> - keyring.matchesOriginal( - ReferenceKind.HUMAN_OPERATOR, - REFERENCE, - original, - REFERENCE_EXPIRY, - RESPONSE_EXPIRY)) + assertThatThrownBy(() -> + keyring.matchesOriginal( + ReferenceKind.HUMAN_OPERATOR, + REFERENCE, + original, + REFERENCE_EXPIRY, + RESPONSE_EXPIRY)) .isInstanceOf(KeyUnavailableException.class); } } @@ -122,32 +121,28 @@ void rejectsMalformedFingerprintBeforeReadingTheOwnerKeySource() { CLOCK, RETENTION_WINDOW); - assertThatThrownBy( - () -> - keyring.matchesOriginal( - ReferenceKind.HUMAN_OPERATOR, - REFERENCE, - "arfp/v1/invalid/not-a-digest", - REFERENCE_EXPIRY, - RESPONSE_EXPIRY)) + assertThatThrownBy(() -> + keyring.matchesOriginal( + ReferenceKind.HUMAN_OPERATOR, + REFERENCE, + "arfp/v1/invalid/not-a-digest", + REFERENCE_EXPIRY, + RESPONSE_EXPIRY)) .isInstanceOf(IllegalArgumentException.class); assertThat(reads).hasValue(0); } @Test void rejectsAmbiguousKeySnapshotsAndMissingRetentionPolicy() { - assertThatThrownBy( - () -> - new Snapshot( - new KeyMaterial("duplicate", key("active-secret")), - List.of( - new KeyMaterial( - "duplicate", key("retained-secret"), NOW.plusSeconds(600))))) + assertThatThrownBy(() -> + new Snapshot( + new KeyMaterial("duplicate", key("active-secret")), + List.of( + new KeyMaterial("duplicate", key("retained-secret"), NOW.plusSeconds(600))))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountOperatorAuthorizationFingerprintKeyring( - () -> snapshot("active", "active-secret", List.of()), CLOCK, Duration.ZERO)) + assertThatThrownBy(() -> + new AccountOperatorAuthorizationFingerprintKeyring( + () -> snapshot("active", "active-secret", List.of()), CLOCK, Duration.ZERO)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprintTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprintTest.java index 7fb008b2d5..98fb7f38f4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprintTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOperatorAuthorizationReferenceFingerprintTest.java @@ -67,10 +67,9 @@ void fingerprintsOpaqueBytesWithoutDecodingThemAsText() { void rejectsMissingOrUnsupportedKeyMaterialAndInvalidKeyIds() { assertThatThrownBy(() -> new AccountOperatorAuthorizationReferenceFingerprint(KEY_ID, null)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountOperatorAuthorizationReferenceFingerprint( - KEY_ID, new SecretKeySpec(KEY_BYTES, "AES"))) + assertThatThrownBy(() -> + new AccountOperatorAuthorizationReferenceFingerprint( + KEY_ID, new SecretKeySpec(KEY_BYTES, "AES"))) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> calculator("")).isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> calculator("bad/key")).isInstanceOf(IllegalArgumentException.class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderGrpcServiceTest.java index f3083e15a0..25d9c6eeda 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderGrpcServiceTest.java @@ -102,17 +102,15 @@ void deniesAmbientSqlNamespaceAndUnknownFieldsBeforeCapture() { .code()) .isEqualTo(Status.Code.PERMISSION_DENIED); assertThat( - authorized( - () -> - invoke( - request.toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField( - 99, - UnknownFieldSet.Field.newBuilder().addVarint(1).build()) - .build()) - .build())) + authorized(() -> + invoke( + request.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) .code()) .isEqualTo(Status.Code.INVALID_ARGUMENT); verifyNoInteractions(owner, terms); @@ -124,11 +122,10 @@ void capturesEnvironmentInternallyAndPreservesOriginalCredentialAndCompleteBindi var decoded = AccountOriginalDraftOrderGrpcCodec.fromRequest(wire, CREDENTIAL); var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); when(terms.captureCurrentEnvironmentBoundary()) - .thenAnswer( - call -> { - outsideSql(); - return captured; - }); + .thenAnswer(call -> { + outsideSql(); + return captured; + }); org.mockito.Mockito.doAnswer( call -> { outsideSql(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderServiceTest.java index 1e65799b0d..d63ef7f375 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderServiceTest.java @@ -72,10 +72,8 @@ void heldReplaySkipsCreatorAndEnvironmentAndUnavailableReadCannotFallThrough() { org.mockito.ArgumentMatchers.any()); when(actors.readHeldOriginalDraft(original)) .thenThrow(new IllegalStateException("ambiguous")); - assertThatThrownBy( - () -> - service.claimWithEnvironmentCapture( - "expired.original.credential", original, capture)) + assertThatThrownBy(() -> + service.claimWithEnvironmentCapture("expired.original.credential", original, capture)) .isInstanceOf(IllegalStateException.class); verifyNoInteractions(capture); } finally { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPolicyTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPolicyTest.java index 6b08d7d71c..95877277d2 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPolicyTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationPolicyTest.java @@ -29,25 +29,21 @@ void explicitPlatformAndDeploymentValuesResolveToExactVersionedEffectivePolicy() @Test void deploymentCannotLoosenPlatformOrExceedHardAgeAndSkewLimits() { var platform = new PlatformValue(1L, 300L, 30L); - assertThatThrownBy( - () -> - AccountRecentReauthenticationPolicy.resolve( - platform, new DeploymentValue(2L, 301L, 30L))) + assertThatThrownBy(() -> + AccountRecentReauthenticationPolicy.resolve( + platform, new DeploymentValue(2L, 301L, 30L))) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - AccountRecentReauthenticationPolicy.resolve( - platform, new DeploymentValue(2L, 300L, 31L))) + assertThatThrownBy(() -> + AccountRecentReauthenticationPolicy.resolve( + platform, new DeploymentValue(2L, 300L, 31L))) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - AccountRecentReauthenticationPolicy.resolve( - platform, new DeploymentValue(2L, 300L, 300L))) + assertThatThrownBy(() -> + AccountRecentReauthenticationPolicy.resolve( + platform, new DeploymentValue(2L, 300L, 300L))) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - AccountRecentReauthenticationPolicy.resolve( - new PlatformValue(1L, 90L, 30L), new DeploymentValue(1L, 300L, 30L))) + assertThatThrownBy(() -> + AccountRecentReauthenticationPolicy.resolve( + new PlatformValue(1L, 90L, 30L), new DeploymentValue(1L, 300L, 30L))) .isInstanceOf(IllegalStateException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java index 4b7a017dd8..d7a24d12be 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountRecentReauthenticationReplayTest.java @@ -31,11 +31,10 @@ void exactReplayUsesRetainedKeyWithoutPrimaryAuthenticationAndClearsTransientByt var f = new Fixture(); AtomicReference transientRequest = new AtomicReference<>(); when(f.crypto.recentReauthenticationRequestMac(eq("prior-key"), any())) - .thenAnswer( - invocation -> { - transientRequest.set(invocation.getArgument(1)); - return "a".repeat(64); - }); + .thenAnswer(invocation -> { + transientRequest.set(invocation.getArgument(1)); + return "a".repeat(64); + }); assertThat(f.service.reauthenticate(f.request(f.operation))).isSameAs(f.evidence); verify(f.crypto, times(2)).recentReauthenticationRequestMac(eq("prior-key"), any()); verify(f.crypto, never()).currentKeyId(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java index 07b5a9c8f5..f1dc6410f7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeCryptographyTest.java @@ -68,10 +68,9 @@ void authenticatesMaximumAuthorityBundleAndResponseWithoutChangingRawBindingByte byte[] changedAuthorityBundle = authorityBundle.clone(); changedAuthorityBundle[changedAuthorityBundle.length / 2] ^= 0x01; - assertThatThrownBy( - () -> - cryptography.decrypt( - envelope, bindingWithAuthorityBundle(changedAuthorityBundle), RECOVERY_EXPIRY)) + assertThatThrownBy(() -> + cryptography.decrypt( + envelope, bindingWithAuthorityBundle(changedAuthorityBundle), RECOVERY_EXPIRY)) .isInstanceOf(AccountResponseEnvelopeCryptography.IntegrityException.class); } @@ -82,27 +81,23 @@ void rejectsAuthorityResponseAndCiphertextBoundsPlusOne() throws IOException { cryptography(Clock.fixed(NOW, ZoneOffset.UTC)); var binding = binding(); - assertThatThrownBy( - () -> - bindingWithAuthorityBundle( - new byte - [AccountResponseEnvelopeCryptography.MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES - + 1])) + assertThatThrownBy(() -> + bindingWithAuthorityBundle( + new byte + [AccountResponseEnvelopeCryptography.MAX_AUTHORITY_EVIDENCE_BUNDLE_BYTES + 1])) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - cryptography.encrypt( - binding, - new byte[AccountResponseEnvelopeCryptography.MAX_RESPONSE_BYTES + 1], - RECOVERY_EXPIRY)) + assertThatThrownBy(() -> + cryptography.encrypt( + binding, + new byte[AccountResponseEnvelopeCryptography.MAX_RESPONSE_BYTES + 1], + RECOVERY_EXPIRY)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - cryptography.decrypt( - new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope( - new byte[AccountResponseEnvelopeCryptography.MAX_ENVELOPE_BYTES + 1]), - binding, - RECOVERY_EXPIRY)) + assertThatThrownBy(() -> + cryptography.decrypt( + new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope( + new byte[AccountResponseEnvelopeCryptography.MAX_ENVELOPE_BYTES + 1]), + binding, + RECOVERY_EXPIRY)) .isInstanceOf(AccountResponseEnvelopeCryptography.IntegrityException.class); } @@ -176,13 +171,11 @@ void rejectsDecryptionAtTheImmutableRecoveryExpiry() throws IOException { assertThatThrownBy(() -> expiredCryptography.decrypt(envelope, binding(), RECOVERY_EXPIRY)) .isInstanceOf(AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException.class) - .satisfies( - failure -> - assertThat( - ((AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException) - failure) - .errorCode()) - .isEqualTo("RESPONSE_RECOVERY_EXPIRED")); + .satisfies(failure -> + assertThat( + ((AccountResponseEnvelopeCryptography.ResponseRecoveryExpiredException) failure) + .errorCode()) + .isEqualTo("RESPONSE_RECOVERY_EXPIRED")); } private AccountResponseEnvelopeCryptography cryptography(Clock clock) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.java index 25704ccad1..7e4d2542fe 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountResponseEnvelopeKeyringTest.java @@ -90,10 +90,9 @@ void acceptsProjectedSecretSymlinksInsideMountAndRejectsTargetsOutsideIt() throw void failsClosedForMissingAndMalformedMounts() throws IOException { assertThatThrownBy(() -> new AccountResponseEnvelopeKeyring("").readCurrent()) .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); - assertThatThrownBy( - () -> - new AccountResponseEnvelopeKeyring(temporaryDirectory.resolve("missing").toString()) - .readCurrent()) + assertThatThrownBy(() -> + new AccountResponseEnvelopeKeyring(temporaryDirectory.resolve("missing").toString()) + .readCurrent()) .isInstanceOf(AccountResponseEnvelopeKeyring.KeyUnavailableException.class); Path malformedMount = Files.createDirectory(temporaryDirectory.resolve("malformed")); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java index 937b78fad5..6e6088bfc6 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java @@ -88,10 +88,9 @@ void authenticatedGameDesignClientReachesEnvironmentCaptureThenUnresolvedOwner() assertThatThrownBy(() -> client.authorize(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); assertThat(server.handlerCalls()).hasValue(1); var calls = inOrder(terms, owner); @@ -116,10 +115,9 @@ void maximumCreatorCredentialMetadataReachesAuthenticatedOwnerUnchanged() throws assertThatThrownBy(() -> client.authorize(request(credential))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); assertThat(server.handlerCalls()).hasValue(1); var calls = inOrder(terms, owner); @@ -139,11 +137,10 @@ void trustedWrongServiceAndNamespaceGameDesignCallersAreDeniedBeforeCapture() th assertThatThrownBy(() -> client.authorize(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .as(identity.alias()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .as(identity.alias()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); assertThat(server.handlerCalls()).as(identity.alias()).hasValue(1); verifyNoInteractions(terms, owner); @@ -161,13 +158,10 @@ void missingClientCertificateFailsTlsBeforeReceiverOrOwner() throws Exception { assertThatThrownBy(() -> client.authorize(wire)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) - .as( - "missing client certificate must fail during TLS negotiation: %s", - failure) - .isTrue()); + .satisfies(failure -> + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as("missing client certificate must fail during TLS negotiation: %s", failure) + .isTrue()); assertThat(server.handlerCalls()).hasValue(0); verifyNoInteractions(terms, owner); @@ -183,10 +177,9 @@ void creatorCredentialMetadataIsRequiredBeforeEnvironmentCapture() throws Except assertThatThrownBy( () -> client.authorize(AccountSelectedPublicationOrderGrpcCodec.toRequest(request()))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(server.handlerCalls()).hasValue(1); verifyNoInteractions(terms, owner); @@ -204,11 +197,10 @@ void clientRejectsTrustedWrongServiceAndNamespaceAccountServerIdentities() throw assertThatThrownBy(() -> client.authorize(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .as(identity.alias()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .as(identity.alias()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(server.handlerCalls()).as(identity.alias()).hasValue(0); verifyNoInteractions(terms, owner); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java index 7e8aba8be6..f591da43f0 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java @@ -135,17 +135,15 @@ void deniesAmbientSqlNamespaceAndUnknownFieldsBeforeCapture() { .code()) .isEqualTo(Status.Code.PERMISSION_DENIED); assertThat( - authorized( - () -> - invoke( - request.toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField( - 99, - UnknownFieldSet.Field.newBuilder().addVarint(1).build()) - .build()) - .build())) + authorized(() -> + invoke( + request.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) .code()) .isEqualTo(Status.Code.INVALID_ARGUMENT); verifyNoInteractions(owner, terms); @@ -174,21 +172,18 @@ void deniesAmbientSqlNamespaceAndUnknownFieldsBeforeCapture() { null, new byte[] {1}))); when(terms.captureCurrentEnvironmentBoundary()) - .thenAnswer( - call -> { - outsideSql(); - return captured; - }); + .thenAnswer(call -> { + outsideSql(); + return captured; + }); when(owner.authorize(eq(CREDENTIAL), any(), same(captured))) - .thenAnswer( - call -> { - outsideSql(); - assertThat( - call.getArgument(1, AuthoredDraftPublishSelectionBinding.class) - .canonicalBytes()) - .isEqualTo(decoded.originalSelection()); - return binding; - }); + .thenAnswer(call -> { + outsideSql(); + assertThat( + call.getArgument(1, AuthoredDraftPublishSelectionBinding.class).canonicalBytes()) + .isEqualTo(decoded.originalSelection()); + return binding; + }); var result = authorized(() -> invoke(request)); assertThat(result.error()).isNull(); assertThat( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderServiceTest.java index 375ee54ec9..d067e732d4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderServiceTest.java @@ -90,25 +90,22 @@ void exactReadCompletesBeforeOwnerReceivesUnchangedCreatorJwtEnvironmentAndSelec var lookup = selection(); var result = mock(AccountPublicationAuthorizationBinding.class); when(client.read(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - var request = - invocation.getArgument( - 0, AuthoredDraftPublishSelectionReadEvidence.Request.class); - assertThat(request.targetNamespace()).isEqualTo("test"); - assertThat(request.originalSelection()).containsExactly(lookup.canonicalBytes()); - assertThat(request.selectionDigest()).isEqualTo(lookup.digest()); - return fixtureEvidence(request); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + var request = + invocation.getArgument(0, AuthoredDraftPublishSelectionReadEvidence.Request.class); + assertThat(request.targetNamespace()).isEqualTo("test"); + assertThat(request.originalSelection()).containsExactly(lookup.canonicalBytes()); + assertThat(request.selectionDigest()).isEqualTo(lookup.digest()); + return fixtureEvidence(request); + }); when(owner.authorize(eq(COMPACT_JWT), eq(lookup), same(environment))) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - return result; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return result; + }); assertThat(authorized(() -> service.authorize(COMPACT_JWT, lookup, environment))) .isSameAs(result); var request = ArgumentCaptor.forClass(AuthoredDraftPublishSelectionReadEvidence.Request.class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjectionTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjectionTest.java index c758b848dc..43a1b6f4c5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjectionTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedGameplayAuthorityProjectionTest.java @@ -34,15 +34,13 @@ void independentMembershipVersionAndGenerationSurviveExactEventRoundTrip() { value.canonicalBytes(), ACCOUNT, TENANT) .canonicalBytes()) .containsExactly(value.canonicalBytes()); - assertThatThrownBy( - () -> - AccountSelectedGameplayAuthorityProjection.decode( - value.canonicalBytes(), UUID.randomUUID(), TENANT)) + assertThatThrownBy(() -> + AccountSelectedGameplayAuthorityProjection.decode( + value.canonicalBytes(), UUID.randomUUID(), TENANT)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountSelectedGameplayAuthorityProjection.membership( - member(ACCOUNT, TENANT, "1", "7", "2"), 9L)) + assertThatThrownBy(() -> + AccountSelectedGameplayAuthorityProjection.membership( + member(ACCOUNT, TENANT, "1", "7", "2"), 9L)) .isInstanceOf(IllegalArgumentException.class); } @@ -86,10 +84,9 @@ void duplicateExtraAliasAndMissingEventFailClosed() { json.replace("\"sourceVersion\":\"2\"", "\"generation\":\"2\""), json.replace("\"sourceVersion\":\"2\"", "\"sourceVersion\":\"2\",\"extra\":true"), json.replace("\"sourceVersion\":\"2\"", "\"sourceVersion\":2"))) { - assertThatThrownBy( - () -> - AccountSelectedGameplayAuthorityProjection.decode( - malformed.getBytes(StandardCharsets.UTF_8), ACCOUNT, TENANT)) + assertThatThrownBy(() -> + AccountSelectedGameplayAuthorityProjection.decode( + malformed.getBytes(StandardCharsets.UTF_8), ACCOUNT, TENANT)) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcServiceTest.java index 4666b4da76..e346a471d4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationProducerGrpcServiceTest.java @@ -130,12 +130,11 @@ void delegatesExactRequestAndEnvironmentCaptureAndPassesThroughOwnerBindingOnRet eq(decoded.owner()), eq(decoded.selected()), any())) - .thenAnswer( - call -> { - Supplier capture = call.getArgument(4); - assertThat(capture.get()).isSameAs(captured); - return binding; - }); + .thenAnswer(call -> { + Supplier capture = call.getArgument(4); + assertThat(capture.get()).isSameAs(captured); + return binding; + }); var first = authorized(() -> invokeAuthorize(wire)); var retry = authorized(() -> invokeAuthorize(wire)); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest.java index 15b3c5c4e7..90120a2ff7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadGrpcServiceTest.java @@ -74,9 +74,8 @@ void authenticatesOwnerAndRejectsEndUserBeforeParsingOrOwnerAccess() { var allowedPeerMalformed = new Collector(); peer("test", "entity-management-service") - .run( - () -> - service.readHeldSelectedOwnerIntakeAuthorization(malformed, allowedPeerMalformed)); + .run(() -> + service.readHeldSelectedOwnerIntakeAuthorization(malformed, allowedPeerMalformed)); assertThat(allowedPeerMalformed.error).isEqualTo(Status.Code.INVALID_ARGUMENT); verifyNoInteractions(owner); } @@ -160,10 +159,9 @@ void rejectsWrongNamespaceClosedFieldsDigestUnknownFieldsAndMalformedSizes() { var wrongNamespace = new Collector(); peer("test", "entity-management-service") - .run( - () -> - service.readHeldSelectedOwnerIntakeAuthorization( - valid.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); + .run(() -> + service.readHeldSelectedOwnerIntakeAuthorization( + valid.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); assertThat(wrongNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); var changedReader = diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java index 4fece0788e..d80cb02544 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationReadServiceTest.java @@ -65,14 +65,13 @@ void readsExactEntityAndAutomationBindingsInIndependentReadCommittedTransactions var definitions = ArgumentCaptor.forClass(TransactionDefinition.class); verify(transactions, times(2)).getTransaction(definitions.capture()); assertThat(definitions.getAllValues()) - .allSatisfy( - definition -> { - assertThat(definition.getPropagationBehavior()) - .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertThat(definition.getIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); - assertThat(definition.isReadOnly()).isFalse(); - }); + .allSatisfy(definition -> { + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + }); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java index 3a50adb47e..65f3985bf4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationServiceTest.java @@ -102,11 +102,10 @@ void freshAuthorizationReadsOutsideSqlThenRevalidatesAndReadsBackExactOriginalId eq(current), eq("test"), any(Runnable.class))) - .thenAnswer( - invocation -> { - invocation.getArgument(5).run(); - return scope; - }); + .thenAnswer(invocation -> { + invocation.getArgument(5).run(); + return scope; + }); when(repository.recoverSourceRead(scope)) .thenReturn( recovery(scope, AccountSelectedOwnerIntakeSourceReservationRepository.State.RESERVED)); @@ -115,11 +114,10 @@ void freshAuthorizationReadsOutsideSqlThenRevalidatesAndReadsBackExactOriginalId argThat(candidate -> sameContent(candidate, content)), eq(current), any(Runnable.class))) - .thenAnswer( - invocation -> { - invocation.getArgument(3).run(); - return binding; - }); + .thenAnswer(invocation -> { + invocation.getArgument(3).run(); + return binding; + }); doAnswer( invocation -> { Function action = invocation.getArgument(3); @@ -244,26 +242,24 @@ void substitutedSelectedContentDeniesWithoutReleasingThePreliminaryReservation() when(sources.read(any(SelectedOwnerIntakeSourceReadEvidence.Request.class))) .thenReturn(content(substitutedScope, "substituted")); - assertThatThrownBy( - () -> - asPeerResult( - "test", - "game-design-service", - () -> - service.authorizeWithEnvironmentCapture( - TOKEN, - selected.requestId(), - Owner.ENTITY_MANAGEMENT, - selected, - () -> { - captures.incrementAndGet(); - return environment; - }))) + assertThatThrownBy(() -> + asPeerResult( + "test", + "game-design-service", + () -> + service.authorizeWithEnvironmentCapture( + TOKEN, + selected.requestId(), + Owner.ENTITY_MANAGEMENT, + selected, + () -> { + captures.incrementAndGet(); + return environment; + }))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); assertThat(captures.get()).isEqualTo(1); verify(repository) @@ -304,23 +300,21 @@ void changedCurrentCreatorDuringPostReadCaptureCannotFinalize() { .withCurrent( eq(TOKEN), eq(TENANT), any(CapturedEnvironmentBoundary.class), any(Function.class)); - assertThatThrownBy( - () -> - asPeerResult( - "test", - "game-design-service", - () -> - service.authorizeWithEnvironmentCapture( - TOKEN, - selected.requestId(), - Owner.ENTITY_MANAGEMENT, - selected, - () -> environment))) + assertThatThrownBy(() -> + asPeerResult( + "test", + "game-design-service", + () -> + service.authorizeWithEnvironmentCapture( + TOKEN, + selected.requestId(), + Owner.ENTITY_MANAGEMENT, + selected, + () -> environment))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); assertThat(actorCalls.get()).isEqualTo(2); verify(sources).read(any(SelectedOwnerIntakeSourceReadEvidence.Request.class)); @@ -344,11 +338,10 @@ void lostFinalizationAcknowledgementRecoversOnlyTheCommittedSameBinding() { argThat(candidate -> sameContent(candidate, content)), eq(current), any(Runnable.class))) - .thenAnswer( - invocation -> { - invocation.getArgument(3).run(); - throw new IllegalStateException("final commit acknowledgement lost"); - }); + .thenAnswer(invocation -> { + invocation.getArgument(3).run(); + throw new IllegalStateException("final commit acknowledgement lost"); + }); when(repository.findFinalAuthorization(scope)).thenReturn(Optional.of(binding)); var result = @@ -390,23 +383,20 @@ void unavailableRemoteResponseLeavesTheOriginalPreliminaryReservationHeld() { .thenThrow( Status.UNAVAILABLE.withDescription("source read outcome unknown").asRuntimeException()); - assertThatThrownBy( - () -> - asPeerResult( - "test", - "game-design-service", - () -> - service.authorizeWithEnvironmentCapture( - TOKEN, - selected.requestId(), - Owner.ENTITY_MANAGEMENT, - selected, - () -> environment))) + assertThatThrownBy(() -> + asPeerResult( + "test", + "game-design-service", + () -> + service.authorizeWithEnvironmentCapture( + TOKEN, + selected.requestId(), + Owner.ENTITY_MANAGEMENT, + selected, + () -> environment))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAVAILABLE)); verify(repository) .reserveSourceRead( @@ -451,28 +441,26 @@ void downstreamSourceStatusesAreSanitizedAndKeepThePreliminaryReservationHeld() downstreamCode == Status.Code.FAILED_PRECONDITION ? Status.Code.FAILED_PRECONDITION : Status.Code.UNAVAILABLE; - assertThatThrownBy( - () -> - asPeerResult( - "test", - "game-design-service", - () -> - service.authorizeWithEnvironmentCapture( - TOKEN, - selected.requestId(), - Owner.ENTITY_MANAGEMENT, - selected, - () -> environment))) + assertThatThrownBy(() -> + asPeerResult( + "test", + "game-design-service", + () -> + service.authorizeWithEnvironmentCapture( + TOKEN, + selected.requestId(), + Owner.ENTITY_MANAGEMENT, + selected, + () -> environment))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - StatusRuntimeException statusFailure = (StatusRuntimeException) failure; - assertThat(statusFailure.getStatus().getCode()).isEqualTo(expectedCode); - assertThat(statusFailure.getStatus().getDescription()) - .isEqualTo("Game Design selected-owner source content is unavailable"); - assertThat(statusFailure.getCause()).isNull(); - assertThat(statusFailure.getTrailers()).isNull(); - }); + .satisfies(failure -> { + StatusRuntimeException statusFailure = (StatusRuntimeException) failure; + assertThat(statusFailure.getStatus().getCode()).isEqualTo(expectedCode); + assertThat(statusFailure.getStatus().getDescription()) + .isEqualTo("Game Design selected-owner source content is unavailable"); + assertThat(statusFailure.getCause()).isNull(); + assertThat(statusFailure.getTrailers()).isNull(); + }); verify(repository) .reserveSourceRead( @@ -539,11 +527,10 @@ private void stubFreshReservation( eq(current), eq("test"), any(Runnable.class))) - .thenAnswer( - invocation -> { - invocation.getArgument(5).run(); - return scope; - }); + .thenAnswer(invocation -> { + invocation.getArgument(5).run(); + return scope; + }); when(repository.recoverSourceRead(scope)) .thenReturn( recovery(scope, AccountSelectedOwnerIntakeSourceReservationRepository.State.RESERVED)); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcServiceTest.java index 8325c8a06d..3ed0e4edcd 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementGrpcServiceTest.java @@ -142,9 +142,8 @@ void returnsFullStoredReceiptAndExactEchoForNewCorrelationRetry() { var bindings = ArgumentCaptor.forClass(SelectedOwnerIntakeAuthorizationBinding.class); verify(owner, times(2)).settle(bindings.capture()); assertThat(bindings.getAllValues()) - .allSatisfy( - retained -> - assertThat(retained.canonicalBytes()).containsExactly(binding.canonicalBytes())); + .allSatisfy(retained -> + assertThat(retained.canonicalBytes()).containsExactly(binding.canonicalBytes())); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java index 82d8cdab2b..073994b503 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java @@ -71,40 +71,35 @@ void readsAutomationOutsideSqlThenCommitsAndReadsBackInIndependentTransactions() .when(harness.repository) .readFinalAuthorization(ORIGINAL); when(harness.repository.findSettlement(ORIGINAL)) - .thenAnswer( - ignored -> { - assertWritableReadCommittedTransaction(); - int read = settlementReads.incrementAndGet(); - harness.steps.add(read == 1 ? "prior-settlement-lookup" : "post-commit-readback"); - return read == 1 ? Optional.empty() : Optional.of(stored.get()); - }); + .thenAnswer(ignored -> { + assertWritableReadCommittedTransaction(); + int read = settlementReads.incrementAndGet(); + harness.steps.add(read == 1 ? "prior-settlement-lookup" : "post-commit-readback"); + return read == 1 ? Optional.empty() : Optional.of(stored.get()); + }); when(harness.automationClient.read(any())) - .thenAnswer( - invocation -> { - assertNoSql(); - harness.steps.add("remote-automation-terminal-read"); - AutomationSelectedSourceIntakeTerminalReadEvidence.Request request = - invocation.getArgument(0); - assertThat(request.binding().canonicalBytes()) - .containsExactly(ORIGINAL.canonicalBytes()); - assertThat(request.readRequestId()) - .isNotIn(ORIGINAL.operationId(), ORIGINAL.fenceId(), ORIGINAL.intakeRequestId()); - return new AutomationSelectedSourceIntakeTerminalReadEvidence(request, ownerReceipt); - }); + .thenAnswer(invocation -> { + assertNoSql(); + harness.steps.add("remote-automation-terminal-read"); + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request = + invocation.getArgument(0); + assertThat(request.binding().canonicalBytes()).containsExactly(ORIGINAL.canonicalBytes()); + assertThat(request.readRequestId()) + .isNotIn(ORIGINAL.operationId(), ORIGINAL.fenceId(), ORIGINAL.intakeRequestId()); + return new AutomationSelectedSourceIntakeTerminalReadEvidence(request, ownerReceipt); + }); when(harness.repository.settleCommittedEmpty(any())) - .thenAnswer( - invocation -> { - assertWritableReadCommittedTransaction(); - harness.steps.add("commit-exact-terminal-settlement"); - AutomationSelectedSourceIntakeTerminalReadEvidence evidence = - invocation.getArgument(0); - assertThat(evidence.request().binding().canonicalBytes()) - .containsExactly(ORIGINAL.canonicalBytes()); - AccountSelectedOwnerIntakeSettlementReceipt receipt = - AccountSelectedOwnerIntakeSettlementReceipt.create(evidence); - stored.set(receipt); - return receipt; - }); + .thenAnswer(invocation -> { + assertWritableReadCommittedTransaction(); + harness.steps.add("commit-exact-terminal-settlement"); + AutomationSelectedSourceIntakeTerminalReadEvidence evidence = invocation.getArgument(0); + assertThat(evidence.request().binding().canonicalBytes()) + .containsExactly(ORIGINAL.canonicalBytes()); + AccountSelectedOwnerIntakeSettlementReceipt receipt = + AccountSelectedOwnerIntakeSettlementReceipt.create(evidence); + stored.set(receipt); + return receipt; + }); AccountSelectedOwnerIntakeSettlementReceipt actual = asGameDesign(() -> harness.service.settle(ORIGINAL)); @@ -164,28 +159,24 @@ void freshReadCorrelationKeepsAnAlreadyCommittedImmutableOwnerReceiptWinner() { AccountSelectedOwnerIntakeSettlementReceipt.create( new AutomationSelectedSourceIntakeTerminalReadEvidence(winnerRequest, ownerReceipt)); when(harness.repository.findSettlement(ORIGINAL)) - .thenAnswer( - ignored -> - settlementReads.incrementAndGet() == 1 ? Optional.empty() : Optional.of(winner)); + .thenAnswer(ignored -> + settlementReads.incrementAndGet() == 1 ? Optional.empty() : Optional.of(winner)); when(harness.automationClient.read(any())) - .thenAnswer( - invocation -> { - assertNoSql(); - AutomationSelectedSourceIntakeTerminalReadEvidence.Request request = - invocation.getArgument(0); - remoteRequest.set(request); - return new AutomationSelectedSourceIntakeTerminalReadEvidence(request, ownerReceipt); - }); + .thenAnswer(invocation -> { + assertNoSql(); + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request = + invocation.getArgument(0); + remoteRequest.set(request); + return new AutomationSelectedSourceIntakeTerminalReadEvidence(request, ownerReceipt); + }); when(harness.repository.settleCommittedEmpty(any())) - .thenAnswer( - invocation -> { - assertWritableReadCommittedTransaction(); - AutomationSelectedSourceIntakeTerminalReadEvidence evidence = - invocation.getArgument(0); - assertThat(evidence.request().readRequestId()) - .isEqualTo(remoteRequest.get().readRequestId()); - return winner; - }); + .thenAnswer(invocation -> { + assertWritableReadCommittedTransaction(); + AutomationSelectedSourceIntakeTerminalReadEvidence evidence = invocation.getArgument(0); + assertThat(evidence.request().readRequestId()) + .isEqualTo(remoteRequest.get().readRequestId()); + return winner; + }); AccountSelectedOwnerIntakeSettlementReceipt recovered = asGameDesign(() -> harness.service.settle(ORIGINAL)); @@ -219,19 +210,18 @@ void unavailableNullAndChangedOwnerTerminalEvidenceNeverReachesAccountSettlement AutomationEmptySelectedSourceIntakeReceipt ownerReceipt = ownerReceipt(ORIGINAL, "changed-echo"); when(changedEcho.automationClient.read(any())) - .thenAnswer( - invocation -> { - var request = - (AutomationSelectedSourceIntakeTerminalReadEvidence.Request) - invocation.getArgument(0); - var changed = - new AutomationSelectedSourceIntakeTerminalReadEvidence.Request( - request.schemaVersion(), - request.targetNamespace(), - UUID.randomUUID(), - request.binding()); - return new AutomationSelectedSourceIntakeTerminalReadEvidence(changed, ownerReceipt); - }); + .thenAnswer(invocation -> { + var request = + (AutomationSelectedSourceIntakeTerminalReadEvidence.Request) + invocation.getArgument(0); + var changed = + new AutomationSelectedSourceIntakeTerminalReadEvidence.Request( + request.schemaVersion(), + request.targetNamespace(), + UUID.randomUUID(), + request.binding()); + return new AutomationSelectedSourceIntakeTerminalReadEvidence(changed, ownerReceipt); + }); assertStatus( Status.Code.FAILED_PRECONDITION, () -> asGameDesign(() -> changedEcho.service.settle(ORIGINAL))); @@ -242,10 +232,9 @@ void unavailableNullAndChangedOwnerTerminalEvidenceNeverReachesAccountSettlement ownerReceipt(ORIGINAL, "corrupt-digest"); when(badReceipt.receiptDigest()).thenReturn("sha256:" + "f".repeat(64)); when(corruptReceipt.automationClient.read(any())) - .thenAnswer( - invocation -> - new AutomationSelectedSourceIntakeTerminalReadEvidence( - invocation.getArgument(0), badReceipt)); + .thenAnswer(invocation -> + new AutomationSelectedSourceIntakeTerminalReadEvidence( + invocation.getArgument(0), badReceipt)); assertStatus( Status.Code.FAILED_PRECONDITION, () -> asGameDesign(() -> corruptReceipt.service.settle(ORIGINAL))); @@ -263,16 +252,13 @@ void failedSettlementCommitDoesNotPretendToHaveReadBackTheUnknownOutcome() { AutomationEmptySelectedSourceIntakeReceipt ownerReceipt = ownerReceipt(ORIGINAL, "commit-failure"); when(harness.automationClient.read(any())) - .thenAnswer( - invocation -> - new AutomationSelectedSourceIntakeTerminalReadEvidence( - invocation.getArgument(0), ownerReceipt)); + .thenAnswer(invocation -> + new AutomationSelectedSourceIntakeTerminalReadEvidence( + invocation.getArgument(0), ownerReceipt)); when(harness.repository.settleCommittedEmpty(any())) - .thenAnswer( - invocation -> - AccountSelectedOwnerIntakeSettlementReceipt.create( - (AutomationSelectedSourceIntakeTerminalReadEvidence) - invocation.getArgument(0))); + .thenAnswer(invocation -> + AccountSelectedOwnerIntakeSettlementReceipt.create( + (AutomationSelectedSourceIntakeTerminalReadEvidence) invocation.getArgument(0))); harness.transactions.failCommitAt = 2; assertThatThrownBy(() -> asGameDesign(() -> harness.service.settle(ORIGINAL))) @@ -297,10 +283,9 @@ void missingOrDifferentLookupOnlyReadbackRemainsUnresolved() { NAMESPACE, ORIGINAL), ownerReceipt)); when(missing.automationClient.read(any())) - .thenAnswer( - invocation -> - new AutomationSelectedSourceIntakeTerminalReadEvidence( - invocation.getArgument(0), ownerReceipt)); + .thenAnswer(invocation -> + new AutomationSelectedSourceIntakeTerminalReadEvidence( + invocation.getArgument(0), ownerReceipt)); when(missing.repository.settleCommittedEmpty(any())).thenReturn(committed); when(missing.repository.findSettlement(ORIGINAL)) .thenReturn(Optional.empty(), Optional.empty()); @@ -321,10 +306,9 @@ void missingOrDifferentLookupOnlyReadbackRemainsUnresolved() { AccountSelectedOwnerIntakeSettlementReceipt.create( new AutomationSelectedSourceIntakeTerminalReadEvidence(otherRequest, ownerReceipt)); when(changed.automationClient.read(any())) - .thenAnswer( - invocation -> - new AutomationSelectedSourceIntakeTerminalReadEvidence( - invocation.getArgument(0), ownerReceipt)); + .thenAnswer(invocation -> + new AutomationSelectedSourceIntakeTerminalReadEvidence( + invocation.getArgument(0), ownerReceipt)); when(changed.repository.settleCommittedEmpty(any())).thenReturn(exactCommit); when(changed.repository.findSettlement(ORIGINAL)) .thenReturn(Optional.empty(), Optional.of(substitutedReadback)); @@ -352,22 +336,18 @@ void wrongPeerEndUserAmbientSqlAndNonAutomationScopeAreRejectedBeforeRepositoryA SessionContext.clear(); TransactionSynchronizationManager.setActualTransactionActive(true); - asGameDesign( - () -> - assertStatus(Status.Code.FAILED_PRECONDITION, () -> harness.service.settle(ORIGINAL))); + asGameDesign(() -> + assertStatus(Status.Code.FAILED_PRECONDITION, () -> harness.service.settle(ORIGINAL))); TransactionSynchronizationManager.setActualTransactionActive(false); TransactionSynchronizationManager.initSynchronization(); - asGameDesign( - () -> - assertStatus(Status.Code.FAILED_PRECONDITION, () -> harness.service.settle(ORIGINAL))); + asGameDesign(() -> + assertStatus(Status.Code.FAILED_PRECONDITION, () -> harness.service.settle(ORIGINAL))); TransactionSynchronizationManager.clear(); SelectedOwnerIntakeAuthorizationBinding entityBinding = AccountSelectedOwnerIntakeAuthorizationReadServiceTest.binding(Owner.ENTITY_MANAGEMENT); - asGameDesign( - () -> - assertStatus( - Status.Code.FAILED_PRECONDITION, () -> harness.service.settle(entityBinding))); + asGameDesign(() -> + assertStatus(Status.Code.FAILED_PRECONDITION, () -> harness.service.settle(entityBinding))); Harness wrongBindingNamespace = new Harness("other-runtime"); asPeer( @@ -394,30 +374,27 @@ void entityLostLookupOnlyReadbackRecoversExactPriorWithoutAnotherRemoteReadOrWri when(harness.repository.findSettlement(binding)) .thenAnswer(ignored -> Optional.ofNullable(stored.get())); when(harness.entityClient.read(any())) - .thenAnswer( - invocation -> { - assertNoSql(); - EntitySelectedSourceIntakeTerminalReadEvidence.Request request = - invocation.getArgument(0); - return new EntitySelectedSourceIntakeTerminalReadEvidence(request, owner); - }); + .thenAnswer(invocation -> { + assertNoSql(); + EntitySelectedSourceIntakeTerminalReadEvidence.Request request = + invocation.getArgument(0); + return new EntitySelectedSourceIntakeTerminalReadEvidence(request, owner); + }); when(harness.repository.settleEntityCommittedEmpty(any())) - .thenAnswer( - invocation -> { - assertWritableReadCommittedTransaction(); - EntitySelectedSourceIntakeTerminalReadEvidence evidence = invocation.getArgument(0); - var receipt = AccountSelectedOwnerIntakeSettlementReceipt.create(evidence); - stored.set(receipt); - return receipt; - }); + .thenAnswer(invocation -> { + assertWritableReadCommittedTransaction(); + EntitySelectedSourceIntakeTerminalReadEvidence evidence = invocation.getArgument(0); + var receipt = AccountSelectedOwnerIntakeSettlementReceipt.create(evidence); + stored.set(receipt); + return receipt; + }); // The first post-commit lookup is absent even though the immutable writer committed. AtomicInteger reads = new AtomicInteger(); when(harness.repository.findSettlement(binding)) - .thenAnswer( - ignored -> { - assertWritableReadCommittedTransaction(); - return reads.incrementAndGet() <= 2 ? Optional.empty() : Optional.of(stored.get()); - }); + .thenAnswer(ignored -> { + assertWritableReadCommittedTransaction(); + return reads.incrementAndGet() <= 2 ? Optional.empty() : Optional.of(stored.get()); + }); try (var decoder = Mockito.mockStatic(EntityEmptySelectedSourceIntakeReceipt.class)) { decoder .when(() -> EntityEmptySelectedSourceIntakeReceipt.fromStored(owner.canonicalBytes())) @@ -476,12 +453,10 @@ void unavailableOrChangedEntityReadNeverCreatesAccountSettlement() { Harness changed = new Harness(NAMESPACE, true); when(changed.repository.findSettlement(binding)).thenReturn(Optional.empty()); when(changed.entityClient.read(any())) - .thenAnswer( - invocation -> - new EntitySelectedSourceIntakeTerminalReadEvidence( - EntitySelectedSourceIntakeTerminalReadEvidence.Request.create( - NAMESPACE, binding), - entityReceipt(binding))); + .thenAnswer(invocation -> + new EntitySelectedSourceIntakeTerminalReadEvidence( + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create(NAMESPACE, binding), + entityReceipt(binding))); assertStatus( Status.Code.FAILED_PRECONDITION, () -> asGameDesign(() -> changed.service.settle(binding))); verify(changed.repository, never()).settleEntityCommittedEmpty(any()); @@ -532,14 +507,13 @@ void downstreamStatusFailuresPreserveTerminalStatusesAndSanitizeOthersForBothOwn || downstreamCode == Status.Code.DATA_LOSS) { assertThatThrownBy(() -> asGameDesign(() -> harness.service.settle(binding))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - StatusRuntimeException statusFailure = (StatusRuntimeException) failure; - assertThat(statusFailure.getStatus().getCode()).isEqualTo(downstreamCode); - assertThat(statusFailure.getStatus().getDescription()).isNull(); - assertThat(statusFailure.getCause()).isNull(); - assertThat(statusFailure.getTrailers()).isNull(); - }); + .satisfies(failure -> { + StatusRuntimeException statusFailure = (StatusRuntimeException) failure; + assertThat(statusFailure.getStatus().getCode()).isEqualTo(downstreamCode); + assertThat(statusFailure.getStatus().getDescription()).isNull(); + assertThat(statusFailure.getCause()).isNull(); + assertThat(statusFailure.getTrailers()).isNull(); + }); } else { Status.Code expectedCode = downstreamCode == Status.Code.FAILED_PRECONDITION @@ -555,15 +529,14 @@ void downstreamStatusFailuresPreserveTerminalStatusesAndSanitizeOthersForBothOwn : "Entity terminal evidence is unavailable"; assertThatThrownBy(() -> asGameDesign(() -> harness.service.settle(binding))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - StatusRuntimeException statusFailure = (StatusRuntimeException) failure; - assertThat(statusFailure.getStatus().getCode()).isEqualTo(expectedCode); - assertThat(statusFailure.getStatus().getDescription()) - .isEqualTo(expectedDescription); - assertThat(statusFailure.getCause()).isNull(); - assertThat(statusFailure.getTrailers()).isNull(); - }); + .satisfies(failure -> { + StatusRuntimeException statusFailure = (StatusRuntimeException) failure; + assertThat(statusFailure.getStatus().getCode()).isEqualTo(expectedCode); + assertThat(statusFailure.getStatus().getDescription()) + .isEqualTo(expectedDescription); + assertThat(statusFailure.getCause()).isNull(); + assertThat(statusFailure.getTrailers()).isNull(); + }); } verify(harness.repository, never()).settleCommittedEmpty(any()); verify(harness.repository, never()).settleEntityCommittedEmpty(any()); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcServiceTest.java index 7b9350cff7..122d9b77ab 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadGrpcServiceTest.java @@ -104,10 +104,9 @@ void rejectsWrongNamespaceBeforeOwnerAndRejectsWrongReaderPurposeOrDomain() { var wrongNamespace = new Collector(); peer("test", "game-design-service") - .run( - () -> - service.readSourceScope( - original.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); + .run(() -> + service.readSourceScope( + original.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); assertThat(wrongNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); var wrongReader = diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadServiceTest.java index 1bbcf2842f..56284d55d7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReadServiceTest.java @@ -79,14 +79,13 @@ void exactCreatorRegistryReadOccursBetweenIndependentSqlReadbacks() { var definition = ArgumentCaptor.forClass(TransactionDefinition.class); verify(transactions, times(2)).getTransaction(definition.capture()); assertThat(definition.getAllValues()) - .allSatisfy( - value -> { - assertThat(value.getPropagationBehavior()) - .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertThat(value.getIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); - assertThat(value.isReadOnly()).isFalse(); - }); + .allSatisfy(value -> { + assertThat(value.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(value.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(value.isReadOnly()).isFalse(); + }); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java index 9e5e1b4967..cf92641a47 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationServiceTest.java @@ -333,14 +333,13 @@ void expiredPreliminaryRecoveryBoundsWorkAndUsesOneOwnerTransactionPerCandidate( var definitions = org.mockito.ArgumentCaptor.forClass(TransactionDefinition.class); verify(transactions, org.mockito.Mockito.times(3)).getTransaction(definitions.capture()); assertThat(definitions.getAllValues()) - .allSatisfy( - definition -> { - assertThat(definition.getPropagationBehavior()) - .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertThat(definition.getIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); - assertThat(definition.isReadOnly()).isFalse(); - }); + .allSatisfy(definition -> { + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + }); verify(repository).findExpiredPreliminarySourceReadScopes(128, "test", null); verify(repository).abortExpiredPreliminarySourceRead(first, "test"); verify(repository).abortExpiredPreliminarySourceRead(second, "test"); @@ -388,14 +387,13 @@ void expiredPreliminaryRecoveryCarriesCursorAcrossSkippedAndSuccessfulPages() { var definitions = org.mockito.ArgumentCaptor.forClass(TransactionDefinition.class); verify(transactions, times(3)).getTransaction(definitions.capture()); assertThat(definitions.getAllValues()) - .allSatisfy( - definition -> { - assertThat(definition.getPropagationBehavior()) - .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertThat(definition.getIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); - assertThat(definition.isReadOnly()).isFalse(); - }); + .allSatisfy(definition -> { + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + }); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest.java index 85ebabb83d..d1c21a33e7 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadGrpcServiceTest.java @@ -61,9 +61,8 @@ void authenticatesWorldAndRejectsEndUserBeforeParsingOrOwnerAccess() { } var otherNamespace = new Collector(); peer("other", "world-management-service") - .run( - () -> - service.readHeldSelectedOwnerWorldClosureAuthorization(malformed, otherNamespace)); + .run(() -> + service.readHeldSelectedOwnerWorldClosureAuthorization(malformed, otherNamespace)); assertThat(otherNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); SessionContext.setContext("44", List.of(), java.util.Map.of()); @@ -78,10 +77,9 @@ void authenticatesWorldAndRejectsEndUserBeforeParsingOrOwnerAccess() { var allowedPeerMalformed = new Collector(); peer("test", "world-management-service") - .run( - () -> - service.readHeldSelectedOwnerWorldClosureAuthorization( - malformed, allowedPeerMalformed)); + .run(() -> + service.readHeldSelectedOwnerWorldClosureAuthorization( + malformed, allowedPeerMalformed)); assertThat(allowedPeerMalformed.error).isEqualTo(Status.Code.INVALID_ARGUMENT); verifyNoInteractions(owner); } @@ -155,10 +153,9 @@ void rejectsWrongNamespaceClosedFieldsDigestUnknownFieldsAndMalformedSizes() { var wrongNamespace = new Collector(); peer("test", "world-management-service") - .run( - () -> - service.readHeldSelectedOwnerWorldClosureAuthorization( - valid.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); + .run(() -> + service.readHeldSelectedOwnerWorldClosureAuthorization( + valid.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); assertThat(wrongNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); var changedDigest = diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceTest.java index ee268a7717..53fb2b21f9 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadServiceTest.java @@ -55,14 +55,13 @@ void readsExactEntityAndAutomationBindingsInIndependentReadCommittedTransactions var definitions = ArgumentCaptor.forClass(TransactionDefinition.class); verify(transactions, times(2)).getTransaction(definitions.capture()); assertThat(definitions.getAllValues()) - .allSatisfy( - definition -> { - assertThat(definition.getPropagationBehavior()) - .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertThat(definition.getIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); - assertThat(definition.isReadOnly()).isFalse(); - }); + .allSatisfy(definition -> { + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + }); } @Test diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.java index 4255b44274..8ba853325d 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.java @@ -30,10 +30,9 @@ class AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest { void keytoolTimeoutTerminatesAndReapsTheStalledChild() throws Exception { Process process = keytoolAwaitingPassword(); try { - assertThatThrownBy( - () -> - ActivationProtectionGrpcMtlsTestSupport.TestPki.awaitKeytoolExit( - process, 1, TimeUnit.SECONDS)) + assertThatThrownBy(() -> + ActivationProtectionGrpcMtlsTestSupport.TestPki.awaitKeytoolExit( + process, 1, TimeUnit.SECONDS)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("execution deadline"); assertThat(process.isAlive()).isFalse(); @@ -49,10 +48,9 @@ void keytoolInterruptionReapsTheChildAndPreservesTheInterruptFlag() throws Excep Process process = keytoolAwaitingPassword(); try { Thread.currentThread().interrupt(); - assertThatThrownBy( - () -> - ActivationProtectionGrpcMtlsTestSupport.TestPki.awaitKeytoolExit( - process, 30, TimeUnit.SECONDS)) + assertThatThrownBy(() -> + ActivationProtectionGrpcMtlsTestSupport.TestPki.awaitKeytoolExit( + process, 30, TimeUnit.SECONDS)) .isInstanceOf(InterruptedException.class); assertThat(Thread.currentThread().isInterrupted()).isTrue(); Thread.interrupted(); @@ -141,11 +139,10 @@ void missingClientCertificateFailsAtTlsHandshake() throws Exception { var client = ActivationProtectionGrpcMtlsTestSupport.clientWithoutIdentity( pki, temporaryDirectory, server.getPort())) { - assertThatThrownBy( - () -> - acquire( - client.channel(), - AcquireOriginalStartSessionActivationProtectionRequest.getDefaultInstance())) + assertThatThrownBy(() -> + acquire( + client.channel(), + AcquireOriginalStartSessionActivationProtectionRequest.getDefaultInstance())) .isInstanceOf(StatusRuntimeException.class) .satisfies( failure -> assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue()); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionServiceTest.java index 7a309aea3d..83e3b78d7c 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionServiceTest.java @@ -101,17 +101,16 @@ void rejectsAmbientAccountTransactionBeforeParsingOrRemoteOwnerRead() { @Test void rejectsInvalidAccountNamespaceAtConstruction() { var h = new Harness(); - assertThatThrownBy( - () -> - new AccountStartSessionActivationProtectionAcquisitionService( - h.issuer, - h.participation, - h.attempts, - h.protections, - h.launchReader, - h.currentAttemptReader, - h.transactions, - "World_Runtime")) + assertThatThrownBy(() -> + new AccountStartSessionActivationProtectionAcquisitionService( + h.issuer, + h.participation, + h.attempts, + h.protections, + h.launchReader, + h.currentAttemptReader, + h.transactions, + "World_Runtime")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Canonical Account workload namespace"); } @@ -401,27 +400,25 @@ AccountStartSessionActivationProtectionAcquisitionInput committedInput() throws "sha256:" + "c".repeat(64), OffsetDateTime.parse("2030-01-01T00:00:01Z")))); when(currentAttemptReader.read(any())) - .thenAnswer( - invocation -> - new OriginalStartSessionCurrentAttemptEvidence.Result( - invocation.getArgument(0), lease, tuple.canonicalBytes())); + .thenAnswer(invocation -> + new OriginalStartSessionCurrentAttemptEvidence.Result( + invocation.getArgument(0), lease, tuple.canonicalBytes())); // Explicit controlled GS realm/catalog inputs; these mocks establish no owner provenance. when(launchReader.read(any())) - .thenAnswer( - invocation -> - new CanonicalGameInstanceLaunchAssociationReadEvidence.Result( - invocation.getArgument(0), - world.playableStateNamespaceId(), - RealmEntryPolicy.StateScope.SHARED, - true, - CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus - .STARTING, - 0L, - attempt, - fence, - UUID.fromString("e8e8e8e8-e8e8-48e8-88e8-e8e8e8e8e8e8"), - 17L, - preparing.launchBinding())); + .thenAnswer(invocation -> + new CanonicalGameInstanceLaunchAssociationReadEvidence.Result( + invocation.getArgument(0), + world.playableStateNamespaceId(), + RealmEntryPolicy.StateScope.SHARED, + true, + CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus + .STARTING, + 0L, + attempt, + fence, + UUID.fromString("e8e8e8e8-e8e8-48e8-88e8-e8e8e8e8e8e8"), + 17L, + preparing.launchBinding())); when(attempts.findHistoricalExact(any(), any())) .thenAnswer(invocation -> Optional.of(witness(invocation.getArgument(1), lease))); doAnswer( diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementGrpcMtlsTest.java index 59a48974cc..64ace252ec 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementGrpcMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementGrpcMtlsTest.java @@ -70,11 +70,10 @@ void missingClientCertificateFailsAtTlsHandshakeBeforeHandler() throws Exception var client = ActivationProtectionGrpcMtlsTestSupport.clientWithoutIdentity( pki, temporaryDirectory, server.getPort())) { - assertThatThrownBy( - () -> - settle( - client.channel(), - SettleOriginalStartSessionActivationProtectionRequest.getDefaultInstance())) + assertThatThrownBy(() -> + settle( + client.channel(), + SettleOriginalStartSessionActivationProtectionRequest.getDefaultInstance())) .isInstanceOf(StatusRuntimeException.class) .satisfies( failure -> assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue()); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementServiceTest.java index 9f96510b89..82f0c8d03f 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionSettlementServiceTest.java @@ -82,13 +82,11 @@ void deniesUnavailableHistoricalProtectionBeforeRemoteWorldRead() { 7L); when(repository.findHistoricalExact( input.accountProtectionId(), input.accountProtectionFence())) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) - .isFalse(); - return Optional.empty(); - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + return Optional.empty(); + }); withWorldPeer(() -> assertCode(Status.Code.FAILED_PRECONDITION, () -> service.settle(input))); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java index eae2e931fa..62064e08f8 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java @@ -56,26 +56,24 @@ void rejectsWrongPeerNamespaceAndEndUserBeforeRequestDecodeOrOwnerInvocation() { void rejectsWrongCanonicalNamespaceAndMalformedEnvelopeBeforeOwner() { Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer(NAMESPACE, "game-session-service")) - .run( - () -> { - var wrongNamespace = - AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest( - AccountStartSessionAdmissionProtectionGrpcTestFixture.request("another")); - var wrongNamespaceObserver = new Capture(); - service.acquireStartSessionAdmissionProtection( - wrongNamespace, wrongNamespaceObserver); - assertThat(wrongNamespaceObserver.code()).isEqualTo(Status.Code.PERMISSION_DENIED); - - var malformed = - AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest( - AccountStartSessionAdmissionProtectionGrpcTestFixture.request(NAMESPACE)) - .toBuilder() - .addSchemaVersion(1) - .build(); - var malformedObserver = new Capture(); - service.acquireStartSessionAdmissionProtection(malformed, malformedObserver); - assertThat(malformedObserver.code()).isEqualTo(Status.Code.INVALID_ARGUMENT); - }); + .run(() -> { + var wrongNamespace = + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest( + AccountStartSessionAdmissionProtectionGrpcTestFixture.request("another")); + var wrongNamespaceObserver = new Capture(); + service.acquireStartSessionAdmissionProtection(wrongNamespace, wrongNamespaceObserver); + assertThat(wrongNamespaceObserver.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + + var malformed = + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest( + AccountStartSessionAdmissionProtectionGrpcTestFixture.request(NAMESPACE)) + .toBuilder() + .addSchemaVersion(1) + .build(); + var malformedObserver = new Capture(); + service.acquireStartSessionAdmissionProtection(malformed, malformedObserver); + assertThat(malformedObserver.code()).isEqualTo(Status.Code.INVALID_ARGUMENT); + }); verifyNoInteractions(owner); } @@ -92,11 +90,10 @@ void sanitizesOwnerFailureAfterTheExactCanonicalRequestPassesTheGuard() { Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer(NAMESPACE, "game-session-service")) - .run( - () -> - service.acquireStartSessionAdmissionProtection( - AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest(request), - response)); + .run(() -> + service.acquireStartSessionAdmissionProtection( + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest(request), + response)); assertThat(response.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); assertThat(response.errorDescription) @@ -145,11 +142,10 @@ void sanitizesUnexpectedOwnerIllegalStateAsInternal() { Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer(NAMESPACE, "game-session-service")) - .run( - () -> - service.acquireStartSessionAdmissionProtection( - AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest(request), - response)); + .run(() -> + service.acquireStartSessionAdmissionProtection( + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest(request), + response)); assertThat(response.code()).isEqualTo(Status.Code.INTERNAL); assertThat(response.errorDescription) @@ -185,11 +181,10 @@ private void assertExpectedOwnerFailureMapsToFailedPrecondition(RuntimeException Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer(NAMESPACE, "game-session-service")) - .run( - () -> - service.acquireStartSessionAdmissionProtection( - AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest(request), - response)); + .run(() -> + service.acquireStartSessionAdmissionProtection( + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest(request), + response)); assertThat(response.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); assertThat(response.errorDescription) @@ -209,11 +204,10 @@ private void assertSqlFailureMapsTo(RuntimeException failure, Status.Code expect Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer(NAMESPACE, "game-session-service")) - .run( - () -> - service.acquireStartSessionAdmissionProtection( - AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest(request), - response)); + .run(() -> + service.acquireStartSessionAdmissionProtection( + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest(request), + response)); assertThat(response.code()).isEqualTo(expected); assertThat(response.errorDescription) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionManualFactoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionManualFactoryTest.java index 85c404eff9..937842b131 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionManualFactoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionManualFactoryTest.java @@ -69,16 +69,14 @@ void boundedTlsReceiverRejectsOversizeBeforeOwner() throws Exception { .MAX_REQUEST_WIRE_BYTES])) .build(); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionServiceGrpc.newBlockingStub(channel) - .withDeadlineAfter(10, TimeUnit.SECONDS) - .acquireStartSessionAdmissionProtection(oversized)) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(10, TimeUnit.SECONDS) + .acquireStartSessionAdmissionProtection(oversized)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.RESOURCE_EXHAUSTED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.RESOURCE_EXHAUSTED)); verifyNoInteractions(owner); } @@ -94,31 +92,27 @@ void exactSameNamespaceCertificatePassesGuardAndWrongPeerIsRejected() throws Exc AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.toRequest( AccountStartSessionAdmissionProtectionGrpcTestFixture.request(NAMESPACE)); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionServiceGrpc.newBlockingStub( - channel("game-session")) - .withDeadlineAfter(10, TimeUnit.SECONDS) - .acquireStartSessionAdmissionProtection(request)) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionServiceGrpc.newBlockingStub( + channel("game-session")) + .withDeadlineAfter(10, TimeUnit.SECONDS) + .acquireStartSessionAdmissionProtection(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)) + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)) .hasMessageNotContaining("controlled owner outcome"); verify(owner).acquire(any()); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionServiceGrpc.newBlockingStub( - channel("wrong-workload")) - .withDeadlineAfter(10, TimeUnit.SECONDS) - .acquireStartSessionAdmissionProtection(request)) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionServiceGrpc.newBlockingStub( + channel("wrong-workload")) + .withDeadlineAfter(10, TimeUnit.SECONDS) + .acquireStartSessionAdmissionProtection(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); verify(owner).acquire(any()); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java index 60027ab521..efc6e35662 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java @@ -114,14 +114,12 @@ void acquisitionReadsGameSessionOutsideSqlThenUsesAccountCurrentnessAndExactRead any(byte[].class))) .thenReturn(Optional.of(storedProtection)); when(h.currentAttemptReader.read(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - var read = - (OriginalStartSessionCurrentAttemptEvidence.Request) invocation.getArgument(0); - return new OriginalStartSessionCurrentAttemptEvidence.Result( - read, EXPIRY, fixture.request().accountRedemptionProjectionBytes()); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var read = (OriginalStartSessionCurrentAttemptEvidence.Request) invocation.getArgument(0); + return new OriginalStartSessionCurrentAttemptEvidence.Result( + read, EXPIRY, fixture.request().accountRedemptionProjectionBytes()); + }); doAnswer( invocation -> { @SuppressWarnings("unchecked") @@ -219,23 +217,21 @@ void settlementReadsExactTerminalOutsideSqlAndCommitsImmutableReadback() { fixture.protection().accountProtectionFence())) .thenReturn(Optional.empty(), Optional.of(expected)); when(h.client.read(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - var read = (AccountInitialAdmissionSettlementReadInput) invocation.getArgument(0); - assertThat(read.protection().canonicalBytes()) - .containsExactly(fixture.protection().canonicalBytes()); - return new AccountInitialAdmissionSettlementReadEvidence( - read.readRequestId(), read.protection(), fixture.committedTerminal()); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var read = (AccountInitialAdmissionSettlementReadInput) invocation.getArgument(0); + assertThat(read.protection().canonicalBytes()) + .containsExactly(fixture.protection().canonicalBytes()); + return new AccountInitialAdmissionSettlementReadEvidence( + read.readRequestId(), read.protection(), fixture.committedTerminal()); + }); when(h.repository.settleExact(any())).thenReturn(expected); var actual = - withGameSessionPeerResult( - () -> - h.service.settle( - fixture.protection().accountProtectionId(), - fixture.protection().accountProtectionFence())); + withGameSessionPeerResult(() -> + h.service.settle( + fixture.protection().accountProtectionId(), + fixture.protection().accountProtectionFence())); assertThat(actual.canonicalBytes()).containsExactly(canonicalSettlement.canonicalBytes()); assertThat(h.transactions.begins).isEqualTo(3); @@ -272,11 +268,10 @@ void exactHistoricalSettlementReplayDoesNotRequeryOrRenewProtection() { .thenReturn(Optional.of(receipt)); var actual = - withGameSessionPeerResult( - () -> - h.service.settle( - fixture.protection().accountProtectionId(), - fixture.protection().accountProtectionFence())); + withGameSessionPeerResult(() -> + h.service.settle( + fixture.protection().accountProtectionId(), + fixture.protection().accountProtectionFence())); assertThat(actual.canonicalBytes()).containsExactly(receipt.canonicalBytes()); verifyNoInteractions(h.client); @@ -303,21 +298,19 @@ void settlementAcceptsOnlyTheExactDefinitiveFencedAbortOutcome() { fixture.protection().accountProtectionFence())) .thenReturn(Optional.empty(), Optional.of(expected)); when(h.client.read(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - var read = (AccountInitialAdmissionSettlementReadInput) invocation.getArgument(0); - return new AccountInitialAdmissionSettlementReadEvidence( - read.readRequestId(), read.protection(), aborted); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var read = (AccountInitialAdmissionSettlementReadInput) invocation.getArgument(0); + return new AccountInitialAdmissionSettlementReadEvidence( + read.readRequestId(), read.protection(), aborted); + }); when(h.repository.settleExact(any())).thenReturn(expected); var actual = - withGameSessionPeerResult( - () -> - h.service.settle( - fixture.protection().accountProtectionId(), - fixture.protection().accountProtectionFence())); + withGameSessionPeerResult(() -> + h.service.settle( + fixture.protection().accountProtectionId(), + fixture.protection().accountProtectionFence())); assertThat(actual.outcome()) .isEqualTo(GameSessionCanonicalInitialAdmissionOwnerProof.Outcome.ABORTED); @@ -338,21 +331,19 @@ void settlementRejectsChangedOwnerReadBeforeMutationAndClassifiesDependencyFailu fixture.protection().accountProtectionFence())) .thenReturn(Optional.empty()); when(h.client.read(any())) - .thenAnswer( - invocation -> { - var read = (AccountInitialAdmissionSettlementReadInput) invocation.getArgument(0); - return new AccountInitialAdmissionSettlementReadEvidence( - UUID.randomUUID(), read.protection(), fixture.committedTerminal()); - }); - - withGameSessionPeer( - () -> - assertCode( - Status.Code.FAILED_PRECONDITION, - () -> - h.service.settle( - fixture.protection().accountProtectionId(), - fixture.protection().accountProtectionFence()))); + .thenAnswer(invocation -> { + var read = (AccountInitialAdmissionSettlementReadInput) invocation.getArgument(0); + return new AccountInitialAdmissionSettlementReadEvidence( + UUID.randomUUID(), read.protection(), fixture.committedTerminal()); + }); + + withGameSessionPeer(() -> + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + h.service.settle( + fixture.protection().accountProtectionId(), + fixture.protection().accountProtectionFence()))); verify(h.repository, never()).settleExact(any()); for (RuntimeException malformed : @@ -372,13 +363,11 @@ void settlementRejectsChangedOwnerReadBeforeMutationAndClassifiesDependencyFailu .thenReturn(Optional.empty()); doThrow(malformed).when(invalid.client).read(any()); var failure = - statusFailure( - () -> - withGameSessionPeer( - () -> - invalid.service.settle( - fixture.protection().accountProtectionId(), - fixture.protection().accountProtectionFence()))); + statusFailure(() -> + withGameSessionPeer(() -> + invalid.service.settle( + fixture.protection().accountProtectionId(), + fixture.protection().accountProtectionFence()))); assertThat(Status.fromThrowable(failure).getCode()) .isEqualTo(Status.Code.FAILED_PRECONDITION); assertThat(failure.getCause()).isSameAs(malformed); @@ -397,13 +386,11 @@ void settlementRejectsChangedOwnerReadBeforeMutationAndClassifiesDependencyFailu var localFailure = new IllegalStateException("closed local dependency reader"); doThrow(localFailure).when(unavailable.client).read(any()); var localStatusFailure = - statusFailure( - () -> - withGameSessionPeer( - () -> - unavailable.service.settle( - fixture.protection().accountProtectionId(), - fixture.protection().accountProtectionFence()))); + statusFailure(() -> + withGameSessionPeer(() -> + unavailable.service.settle( + fixture.protection().accountProtectionId(), + fixture.protection().accountProtectionFence()))); assertThat(Status.fromThrowable(localStatusFailure).getCode()) .isEqualTo(Status.Code.UNAVAILABLE); assertThat(Status.fromThrowable(localStatusFailure).getDescription()) @@ -425,13 +412,11 @@ void settlementRejectsChangedOwnerReadBeforeMutationAndClassifiesDependencyFailu Status.fromCode(code).withDescription("trusted upstream detail").asRuntimeException(); doThrow(upstream).when(dependency.client).read(any()); var failure = - statusFailure( - () -> - withGameSessionPeer( - () -> - dependency.service.settle( - fixture.protection().accountProtectionId(), - fixture.protection().accountProtectionFence()))); + statusFailure(() -> + withGameSessionPeer(() -> + dependency.service.settle( + fixture.protection().accountProtectionId(), + fixture.protection().accountProtectionFence()))); assertThat(Status.fromThrowable(failure).getCode()) .isEqualTo(infrastructureCodes().contains(code) ? code : Status.Code.FAILED_PRECONDITION); assertThat(failure.getCause()).isSameAs(upstream); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionWorkloadGuardTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionWorkloadGuardTest.java index 863959d9f1..2f1d06ec33 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionWorkloadGuardTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionWorkloadGuardTest.java @@ -54,11 +54,10 @@ private static void assertDenied( Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); assertThatThrownBy(() -> context.run(invocation)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - org.assertj.core.api.Assertions.assertThat( - ((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(expected)); + .satisfies(failure -> + org.assertj.core.api.Assertions.assertThat( + ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(expected)); } private static GrpcPeerIdentity peer(String namespace, String service) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java index 018f7f2691..ade3982492 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepositoryTest.java @@ -181,17 +181,16 @@ void worldReceivingLookupAcceptsWorldPeerAndRetainedLoggingIssuer() { AccountStartSessionAuthorityCapture observed = withPeer(WORLD_PEER_URI, NAMESPACE, "world-management-service") - .call( - () -> - fixture - .repository() - .lockReadExactCurrentFromWorldReceiving( - fixture.current(), - fixture.tuple(), - LOGGING_PEER_URI, - RESERVATION_OWNER_ID, - 7L, - WORLD_PEER_URI)); + .call(() -> + fixture + .repository() + .lockReadExactCurrentFromWorldReceiving( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L, + WORLD_PEER_URI)); assertThat(observed.sameStoredValue(fixture.capture())).isTrue(); verify(fixture.dsl(), times(1)) @@ -204,37 +203,33 @@ void worldReceivingLookupRejectsWrongPeerAndNamespaceBeforeStorage() { WorldLookupFixture fixture = worldLookupFixture(true); beginOwnerTransaction(); - assertUnavailable( - () -> - withPeer(LOGGING_PEER_URI, NAMESPACE, "logging-admin-service") - .call( - () -> - fixture - .repository() - .lockReadExactCurrentFromWorldReceiving( - fixture.current(), - fixture.tuple(), - LOGGING_PEER_URI, - RESERVATION_OWNER_ID, - 7L, - WORLD_PEER_URI))); - assertUnavailable( - () -> - withPeer( - "spiffe://firemud/ns/other/sa/world-management-service", - "other", - "world-management-service") - .call( - () -> - fixture - .repository() - .lockReadExactCurrentFromWorldReceiving( - fixture.current(), - fixture.tuple(), - LOGGING_PEER_URI, - RESERVATION_OWNER_ID, - 7L, - WORLD_PEER_URI))); + assertUnavailable(() -> + withPeer(LOGGING_PEER_URI, NAMESPACE, "logging-admin-service") + .call(() -> + fixture + .repository() + .lockReadExactCurrentFromWorldReceiving( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L, + WORLD_PEER_URI))); + assertUnavailable(() -> + withPeer( + "spiffe://firemud/ns/other/sa/world-management-service", + "other", + "world-management-service") + .call(() -> + fixture + .repository() + .lockReadExactCurrentFromWorldReceiving( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L, + WORLD_PEER_URI))); verifyNoInteractions(fixture.dsl()); } @@ -245,20 +240,18 @@ void worldReceivingLookupRejectsAmbientEndUserContextBeforeStorage() { beginOwnerTransaction(); SessionContext.setContext("account-user", List.of("tenantAdmin"), Map.of()); - assertUnavailable( - () -> - withPeer(WORLD_PEER_URI, NAMESPACE, "world-management-service") - .call( - () -> - fixture - .repository() - .lockReadExactCurrentFromWorldReceiving( - fixture.current(), - fixture.tuple(), - LOGGING_PEER_URI, - RESERVATION_OWNER_ID, - 7L, - WORLD_PEER_URI))); + assertUnavailable(() -> + withPeer(WORLD_PEER_URI, NAMESPACE, "world-management-service") + .call(() -> + fixture + .repository() + .lockReadExactCurrentFromWorldReceiving( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L, + WORLD_PEER_URI))); verifyNoInteractions(fixture.dsl()); } @@ -268,20 +261,18 @@ void worldReceivingLookupDoesNotCreateMissingOriginalCapture() { WorldLookupFixture fixture = worldLookupFixture(false); beginOwnerTransaction(); - assertUnavailable( - () -> - withPeer(WORLD_PEER_URI, NAMESPACE, "world-management-service") - .call( - () -> - fixture - .repository() - .lockReadExactCurrentFromWorldReceiving( - fixture.current(), - fixture.tuple(), - LOGGING_PEER_URI, - RESERVATION_OWNER_ID, - 7L, - WORLD_PEER_URI))); + assertUnavailable(() -> + withPeer(WORLD_PEER_URI, NAMESPACE, "world-management-service") + .call(() -> + fixture + .repository() + .lockReadExactCurrentFromWorldReceiving( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L, + WORLD_PEER_URI))); verify(fixture.dsl(), times(1)) .fetchOne(startsWith("SELECT control_plane_request_id"), any(Object[].class)); @@ -293,31 +284,28 @@ void existingExactCurrentReadStillRequiresLoggingPeer() { WorldLookupFixture fixture = worldLookupFixture(true); beginOwnerTransaction(); - assertUnavailable( - () -> - withPeer(WORLD_PEER_URI, NAMESPACE, "world-management-service") - .call( - () -> - fixture - .repository() - .lockReadExactCurrent( - fixture.current(), - fixture.tuple(), - LOGGING_PEER_URI, - RESERVATION_OWNER_ID, - 7L))); + assertUnavailable(() -> + withPeer(WORLD_PEER_URI, NAMESPACE, "world-management-service") + .call(() -> + fixture + .repository() + .lockReadExactCurrent( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L))); assertThat( withPeer(LOGGING_PEER_URI, NAMESPACE, "logging-admin-service") - .call( - () -> - fixture - .repository() - .lockReadExactCurrent( - fixture.current(), - fixture.tuple(), - LOGGING_PEER_URI, - RESERVATION_OWNER_ID, - 7L)) + .call(() -> + fixture + .repository() + .lockReadExactCurrent( + fixture.current(), + fixture.tuple(), + LOGGING_PEER_URI, + RESERVATION_OWNER_ID, + 7L)) .sameStoredValue(fixture.capture())) .isTrue(); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureTest.java index 4ad82f5835..75415340d0 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureTest.java @@ -117,23 +117,21 @@ void rejectsMismatchedRetainedCaptureDigestAndNonPositiveCaptureAllocations() { AccountStartSessionAuthorityCapture.create( "control-plane-request-3", 1L, 2L, "3", "2026-10-10T12:34:56.789Z", snapshot); - assertThatThrownBy( - () -> - AccountStartSessionAuthorityCapture.fromStorage( - capture.controlPlaneRequestId(), - 1L, - 2L, - "3", - capture.capturedAt(), - snapshot, - "0".repeat(64), - capture.canonicalBytes(), - capture.canonicalSha256())) + assertThatThrownBy(() -> + AccountStartSessionAuthorityCapture.fromStorage( + capture.controlPlaneRequestId(), + 1L, + 2L, + "3", + capture.capturedAt(), + snapshot, + "0".repeat(64), + capture.canonicalBytes(), + capture.canonicalSha256())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountStartSessionAuthorityCapture.create( - "control-plane-request-3", 0L, 2L, "3", "2026-10-10T12:34:56.789Z", snapshot)) + assertThatThrownBy(() -> + AccountStartSessionAuthorityCapture.create( + "control-plane-request-3", 0L, 2L, "3", "2026-10-10T12:34:56.789Z", snapshot)) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java index 8ac647e4f1..03a799aff5 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java @@ -120,10 +120,9 @@ void strictDecoderRejectsTenantAssuranceAndGlobalBranchEvidence() { new LinkedHashMap<>(object(withAssurance.get("issuanceEvidence"))); assuranceArm.put("assurance", Map.of("level", "step-up")); withAssurance.put("issuanceEvidence", assuranceArm); - assertThatThrownBy( - () -> - AccountStartSessionOperatorAuthorityBundle.decode( - AccountControlUiAuthority.canonical(withAssurance))) + assertThatThrownBy(() -> + AccountStartSessionOperatorAuthorityBundle.decode( + AccountControlUiAuthority.canonical(withAssurance))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("missing or unsupported fields"); @@ -132,10 +131,9 @@ void strictDecoderRejectsTenantAssuranceAndGlobalBranchEvidence() { new LinkedHashMap<>(object(globalArm.get("issuanceEvidence"))); substituted.put("role", "platformAdmin"); globalArm.put("issuanceEvidence", substituted); - assertThatThrownBy( - () -> - AccountStartSessionOperatorAuthorityBundle.decode( - AccountControlUiAuthority.canonical(globalArm))) + assertThatThrownBy(() -> + AccountStartSessionOperatorAuthorityBundle.decode( + AccountControlUiAuthority.canonical(globalArm))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("tenantAdmin"); } @@ -155,14 +153,13 @@ void currentSourceMustRetainExactActorGenerationAndSelectedTenant() { var substitutedSource = fixture.source(fixture.actorId, fixture.tenantId, 8L, new byte[] {8}, 2L); - assertThatThrownBy( - () -> - bundle.requireCurrent( - substitutedSource, - fixture.issuance, - fixture.tuple, - bundle.referenceForCapture(capture), - ISSUED_AT.plusSeconds(1))) + assertThatThrownBy(() -> + bundle.requireCurrent( + substitutedSource, + fixture.issuance, + fixture.tuple, + bundle.referenceForCapture(capture), + ISSUED_AT.plusSeconds(1))) .isInstanceOf(IllegalStateException.class); } @@ -180,27 +177,25 @@ void expiredOrChangedCurrentAuthorityIsPreconditionFailureButMalformedBundleIsIn ISSUED_AT.plusSeconds(60)); var reference = bundle.referenceForCapture(capture); - assertThatThrownBy( - () -> - bundle.requireCurrent( - fixture.source, - fixture.issuance, - fixture.tuple, - reference, - ISSUED_AT.plusSeconds(60))) + assertThatThrownBy(() -> + bundle.requireCurrent( + fixture.source, + fixture.issuance, + fixture.tuple, + reference, + ISSUED_AT.plusSeconds(60))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("expired"); var changedTenantAuthority = fixture.source(fixture.actorId, fixture.tenantId, 8L, new byte[] {8}, 2L); - assertThatThrownBy( - () -> - bundle.requireCurrent( - changedTenantAuthority, - fixture.issuance, - fixture.tuple, - reference, - ISSUED_AT.plusSeconds(1))) + assertThatThrownBy(() -> + bundle.requireCurrent( + changedTenantAuthority, + fixture.issuance, + fixture.tuple, + reference, + ISSUED_AT.plusSeconds(1))) .isInstanceOf(IllegalStateException.class); assertThatThrownBy(() -> AccountStartSessionOperatorAuthorityBundle.decode(new byte[] {0x01})) @@ -230,18 +225,16 @@ void sameAttemptReplayAfterEnvelopeHorizonRetainsOriginalSourceLinearization() { originalReference.sourceVersion(), originalReference.sourceFence(), "123457"); - assertThatThrownBy( - () -> - bundle.requireCurrentSnapshotForExactReplay( - fixture.source, fixture.issuance, fixture.tuple, substitutedTransaction)) + assertThatThrownBy(() -> + bundle.requireCurrentSnapshotForExactReplay( + fixture.source, fixture.issuance, fixture.tuple, substitutedTransaction)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("source differs"); var changedSource = fixture.source(fixture.actorId, fixture.tenantId, 8L, new byte[] {8}, 2L); - assertThatThrownBy( - () -> - bundle.requireCurrentSnapshotForExactReplay( - changedSource, fixture.issuance, fixture.tuple, originalReference)) + assertThatThrownBy(() -> + bundle.requireCurrentSnapshotForExactReplay( + changedSource, fixture.issuance, fixture.tuple, originalReference)) .isInstanceOf(IllegalStateException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java index 518b5e42c8..e722607720 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java @@ -125,22 +125,20 @@ void issuePerformsCryptoOutsideSqlAndRejectsSourceChangeBeforeDurableInsert() { when(captureRepository.prepareOrReadExact(any(), any(), anyString(), any(), anyLong())) .thenReturn(capture); when(captureRepository.lockExactCurrent(any(), any(), any(), anyString(), any(), anyLong())) - .thenAnswer( - invocation -> { - Current current = invocation.getArgument(1); - if (current.source() != originalSource) { - throw new IllegalArgumentException("Current Account source changed"); - } - return capture; - }); + .thenAnswer(invocation -> { + Current current = invocation.getArgument(1); + if (current.source() != originalSource) { + throw new IllegalArgumentException("Current Account source changed"); + } + return capture; + }); when(claims.readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), any())) - .thenAnswer( - ignored -> { - org.assertj.core.api.Assertions.assertThat( - TransactionSynchronizationManager.isActualTransactionActive()) - .isFalse(); - return claimEvidence(tuple, requestOwnerId); - }); + .thenAnswer(ignored -> { + org.assertj.core.api.Assertions.assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + return claimEvidence(tuple, requestOwnerId); + }); doAnswer( invocation -> { org.assertj.core.api.Assertions.assertThat( @@ -151,14 +149,13 @@ void issuePerformsCryptoOutsideSqlAndRejectsSourceChangeBeforeDurableInsert() { .when(fingerprintKeys) .fingerprintForIssue(any(), any()); when(responseCrypto.encrypt(any(), any(), any())) - .thenAnswer( - invocation -> { - org.assertj.core.api.Assertions.assertThat( - TransactionSynchronizationManager.isActualTransactionActive()) - .isFalse(); - return new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope( - new byte[] {3, 4, 5}); - }); + .thenAnswer(invocation -> { + org.assertj.core.api.Assertions.assertThat( + TransactionSynchronizationManager.isActualTransactionActive()) + .isFalse(); + return new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope( + new byte[] {3, 4, 5}); + }); AtomicInteger ownerPass = new AtomicInteger(); doAnswer( @@ -219,11 +216,10 @@ void issuePerformsCryptoOutsideSqlAndRejectsSourceChangeBeforeDurableInsert() { Context.current() .withValue( GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(LOGGING_PEER).orElseThrow()) - .run( - () -> - assertThatThrownBy(() -> service.issue(request)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("source changed")); + .run(() -> + assertThatThrownBy(() -> service.issue(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source changed")); verify(repository, never()).createOrReadExact(any()); } @@ -277,55 +273,48 @@ void ownerIssuesRecoversAndReplaysSameAttemptAcrossReferenceExpiry() throws Exce .thenAnswer(ignored -> new SimpleTransactionStatus()); when(hostedTerms.captureCurrentEnvironmentBoundary()).thenReturn(environment); when(captureRepository.prepareOrReadExact(any(), any(), anyString(), any(), anyLong())) - .thenAnswer( - invocation -> { - Current requestedCurrent = invocation.getArgument(0); - StartSessionPreAuthorizationReservationTuple requestedTuple = - invocation.getArgument(1); - UUID requestedOwner = invocation.getArgument(3); - long requestedFence = invocation.getArgument(4); - return captures.computeIfAbsent( - requestedTuple.controlPlaneRequestId(), - ignored -> - capture( - requestedTuple, - requestedCurrent.source(), - requestedCurrent.stored(), - requestedOwner, - requestedFence)); - }); + .thenAnswer(invocation -> { + Current requestedCurrent = invocation.getArgument(0); + StartSessionPreAuthorizationReservationTuple requestedTuple = invocation.getArgument(1); + UUID requestedOwner = invocation.getArgument(3); + long requestedFence = invocation.getArgument(4); + return captures.computeIfAbsent( + requestedTuple.controlPlaneRequestId(), + ignored -> + capture( + requestedTuple, + requestedCurrent.source(), + requestedCurrent.stored(), + requestedOwner, + requestedFence)); + }); when(captureRepository.lockExactCurrent(any(), any(), any(), anyString(), any(), anyLong())) - .thenAnswer( - invocation -> { - StartSessionPreAuthorizationReservationTuple requestedTuple = - invocation.getArgument(2); - AccountStartSessionAuthorityCapture requestedCapture = - captures.get(requestedTuple.controlPlaneRequestId()); - assertThat(requestedCapture).isNotNull(); - return requestedCapture; - }); + .thenAnswer(invocation -> { + StartSessionPreAuthorizationReservationTuple requestedTuple = invocation.getArgument(2); + AccountStartSessionAuthorityCapture requestedCapture = + captures.get(requestedTuple.controlPlaneRequestId()); + assertThat(requestedCapture).isNotNull(); + return requestedCapture; + }); when(captureRepository.lockReadExactCurrent(any(), any(), anyString(), any(), anyLong())) - .thenAnswer( - invocation -> { - StartSessionPreAuthorizationReservationTuple requestedTuple = - invocation.getArgument(1); - AccountStartSessionAuthorityCapture requestedCapture = - captures.get(requestedTuple.controlPlaneRequestId()); - assertThat(requestedCapture).isNotNull(); - return requestedCapture; - }); + .thenAnswer(invocation -> { + StartSessionPreAuthorizationReservationTuple requestedTuple = invocation.getArgument(1); + AccountStartSessionAuthorityCapture requestedCapture = + captures.get(requestedTuple.controlPlaneRequestId()); + assertThat(requestedCapture).isNotNull(); + return requestedCapture; + }); AtomicInteger claimReadCount = new AtomicInteger(); when(claims.readCurrentClaimEvidence(any(), any(), anyLong(), any(), anyLong(), any())) - .thenAnswer( - invocation -> { - Instant localNow = operationClock.instant(); - Instant observedAt = - claimReadCount.getAndIncrement() == 0 ? localNow.plusSeconds(2) : localNow; - return claimEvidence( - invocation.getArgument(0), - invocation.getArgument(1), - observedAt); - }); + .thenAnswer(invocation -> { + Instant localNow = operationClock.instant(); + Instant observedAt = + claimReadCount.getAndIncrement() == 0 ? localNow.plusSeconds(2) : localNow; + return claimEvidence( + invocation.getArgument(0), + invocation.getArgument(1), + observedAt); + }); Path responseKeyringDirectory = temporaryDirectory.resolve("operator-response"); Files.createDirectories(responseKeyringDirectory); @@ -347,63 +336,60 @@ void ownerIssuesRecoversAndReplaysSameAttemptAcrossReferenceExpiry() throws Exce Map durableRecords = new ConcurrentHashMap<>(); Map originalRedemptions = new ConcurrentHashMap<>(); when(repository.findByControlPlaneRequestId(anyString())) - .thenAnswer( - invocation -> - Optional.ofNullable(durableRecords.get(invocation.getArgument(0)))); + .thenAnswer(invocation -> + Optional.ofNullable(durableRecords.get(invocation.getArgument(0)))); when(repository.createOrReadExact(any())) - .thenAnswer( - invocation -> { - var candidate = - invocation - . - getArgument(0); - IssuanceRecord issuance = issuedRecord(candidate); - IssuanceRecord existing = - durableRecords.putIfAbsent(candidate.controlPlaneRequestId(), issuance); - return new AccountStartSessionOperatorAuthorizationRepository.CreateOrReadResult( - existing == null, existing == null ? issuance : existing); - }); + .thenAnswer(invocation -> { + var candidate = + invocation + . + getArgument(0); + IssuanceRecord issuance = issuedRecord(candidate); + IssuanceRecord existing = + durableRecords.putIfAbsent(candidate.controlPlaneRequestId(), issuance); + return new AccountStartSessionOperatorAuthorizationRepository.CreateOrReadResult( + existing == null, existing == null ? issuance : existing); + }); when(repository.redeemExact(any())) - .thenAnswer( - invocation -> { - RedemptionRequest redemption = invocation.getArgument(0); - IssuanceRecord issuance = durableRecords.get(redemption.controlPlaneRequestId()); - assertThat(issuance).isNotNull(); - assertThat(redemption.controlPlaneRequestId()) - .isEqualTo(issuance.controlPlaneRequestId()); - assertThat(redemption.preAuthorizationTuple()) - .containsExactly(issuance.preAuthorizationTuple()); - assertThat(redemption.authorizationReferenceFingerprint()) - .isEqualTo(issuance.authorizationReferenceFingerprint()); - assertThat(redemption.reservationOwnerId()).isEqualTo(issuance.reservationOwnerId()); - assertThat(redemption.reservationClaimFence()) - .isEqualTo(issuance.reservationClaimFence()); - assertThat(redemption.redeemerWorkloadUri()).isEqualTo(GAME_SESSION_PEER); - assertThat(redemption.authorityEvidenceBundle()) - .containsExactly(issuance.authorityEvidenceBundle()); - assertThat(redemption.now()).isEqualTo(operationClock.instant()); - - boolean replay = issuance.status() == Status.REDEEMED; - if (replay) { - RedemptionRequest original = - originalRedemptions.get(redemption.controlPlaneRequestId()); - assertThat(original).isNotNull(); - assertThat(redemption.ownerAttemptId()).isEqualTo(original.ownerAttemptId()); - assertThat(redemption.ownerFence()).isEqualTo(original.ownerFence()); - } else { - assertThat(issuance.status()).isEqualTo(Status.ISSUED); - assertThat(redemption.now()).isBefore(issuance.referenceExpiresAt()); - originalRedemptions.put(redemption.controlPlaneRequestId(), redemption); - durableRecords.put( - redemption.controlPlaneRequestId(), withRedemption(issuance, redemption)); - } - return new AccountStartSessionOperatorAuthorizationRepository.RedemptionResult( - issuance.authorizationReferenceFingerprint(), - issuance.authorityEvidenceBundle(), - issuance.issuanceOperationId(), - issuance.issuanceFence(), - replay); - }); + .thenAnswer(invocation -> { + RedemptionRequest redemption = invocation.getArgument(0); + IssuanceRecord issuance = durableRecords.get(redemption.controlPlaneRequestId()); + assertThat(issuance).isNotNull(); + assertThat(redemption.controlPlaneRequestId()) + .isEqualTo(issuance.controlPlaneRequestId()); + assertThat(redemption.preAuthorizationTuple()) + .containsExactly(issuance.preAuthorizationTuple()); + assertThat(redemption.authorizationReferenceFingerprint()) + .isEqualTo(issuance.authorizationReferenceFingerprint()); + assertThat(redemption.reservationOwnerId()).isEqualTo(issuance.reservationOwnerId()); + assertThat(redemption.reservationClaimFence()) + .isEqualTo(issuance.reservationClaimFence()); + assertThat(redemption.redeemerWorkloadUri()).isEqualTo(GAME_SESSION_PEER); + assertThat(redemption.authorityEvidenceBundle()) + .containsExactly(issuance.authorityEvidenceBundle()); + assertThat(redemption.now()).isEqualTo(operationClock.instant()); + + boolean replay = issuance.status() == Status.REDEEMED; + if (replay) { + RedemptionRequest original = + originalRedemptions.get(redemption.controlPlaneRequestId()); + assertThat(original).isNotNull(); + assertThat(redemption.ownerAttemptId()).isEqualTo(original.ownerAttemptId()); + assertThat(redemption.ownerFence()).isEqualTo(original.ownerFence()); + } else { + assertThat(issuance.status()).isEqualTo(Status.ISSUED); + assertThat(redemption.now()).isBefore(issuance.referenceExpiresAt()); + originalRedemptions.put(redemption.controlPlaneRequestId(), redemption); + durableRecords.put( + redemption.controlPlaneRequestId(), withRedemption(issuance, redemption)); + } + return new AccountStartSessionOperatorAuthorizationRepository.RedemptionResult( + issuance.authorizationReferenceFingerprint(), + issuance.authorityEvidenceBundle(), + issuance.issuanceOperationId(), + issuance.issuanceFence(), + replay); + }); AtomicReference currentForCalls = new AtomicReference<>(current); doAnswer( invocation -> { @@ -613,22 +599,20 @@ void ownerIssuesRecoversAndReplaysSameAttemptAcrossReferenceExpiry() throws Exce ownerFence + 1); for (var changedRequest : List.of(changedAttempt, changedFence)) { gameSessionContext() - .run( - () -> - assertThatThrownBy(() -> service.redeem(changedRequest)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("cannot authorize another owner attempt")); + .run(() -> + assertThatThrownBy(() -> service.redeem(changedRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("cannot authorize another owner attempt")); } AccountControlUiAuthority.Snapshot changedSource = source(actorId, tenantId, 8L, new byte[] {2}); currentForCalls.set(new Current(stored, changedSource)); gameSessionContext() - .run( - () -> - assertThatThrownBy(() -> service.redeem(redeemRequest)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Current Account source differs")); + .run(() -> + assertThatThrownBy(() -> service.redeem(redeemRequest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Current Account source differs")); verify(repository, times(3)).redeemExact(any()); currentForCalls.set(current); @@ -660,11 +644,10 @@ void ownerIssuesRecoversAndReplaysSameAttemptAcrossReferenceExpiry() throws Exce 19L); operationClock.setInstant(expiredRecord.referenceExpiresAt()); gameSessionContext() - .run( - () -> - assertThatThrownBy(() -> service.redeem(firstRedemptionAfterExpiry)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Original Account authority evidence is expired")); + .run(() -> + assertThatThrownBy(() -> service.redeem(firstRedemptionAfterExpiry)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Original Account authority evidence is expired")); verify(repository, times(3)).redeemExact(any()); operationClock.setInstant(record.responseEnvelopeExpiresAt().minusMillis(1)); @@ -689,13 +672,12 @@ void ownerIssuesRecoversAndReplaysSameAttemptAcrossReferenceExpiry() throws Exce AccountControlUiAuthority.canonical(bundle.authorityTuple()), AccountControlUiAuthority.canonical(bundle.membershipVersion()), bundle.canonicalBytes()); - assertThatThrownBy( - () -> - responseCrypto.decrypt( - new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope( - record.encryptedResponseEnvelope()), - distinctBinding, - record.responseEnvelopeExpiresAt())) + assertThatThrownBy(() -> + responseCrypto.decrypt( + new AccountResponseEnvelopeCryptography.EncryptedResponseEnvelope( + record.encryptedResponseEnvelope()), + distinctBinding, + record.responseEnvelopeExpiresAt())) .isInstanceOf(AccountResponseEnvelopeCryptography.IntegrityException.class); } @@ -709,11 +691,10 @@ void exactRepeatedReadReturnsOriginalRedeemedProjectionAfterCurrentnessRevalidat Context.current() .withValue( GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(GAME_DESIGN_PEER).orElseThrow()) - .run( - () -> { - first.set(harness.service().readRedeemedOperationProjection(harness.request())); - retry.set(harness.service().readRedeemedOperationProjection(harness.request())); - }); + .run(() -> { + first.set(harness.service().readRedeemedOperationProjection(harness.request())); + retry.set(harness.service().readRedeemedOperationProjection(harness.request())); + }); RedeemedOperationProjection original = first.get(); RedeemedOperationProjection exactRetry = retry.get(); @@ -806,13 +787,11 @@ void exactOriginalGameSessionRedeemerCanReadItsImmutableProjection() { Context.current() .withValue( GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(wrongPeerUri).orElseThrow()) - .run( - () -> - assertThatThrownBy( - () -> harness.service().readRedeemedOperationProjection(malformed)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining( - "Exact authenticated Game Design or original Game Session identity")); + .run(() -> + assertThatThrownBy(() -> harness.service().readRedeemedOperationProjection(malformed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining( + "Exact authenticated Game Design or original Game Session identity")); } verify(harness.repository(), never()).findByControlPlaneRequestId(anyString()); @@ -829,15 +808,10 @@ void projectionRejectsMissingUnredeemedAndWrongRedeemerRecords() { .repository() .findByControlPlaneRequestId(missingHarness.tuple().controlPlaneRequestId())) .thenReturn(Optional.empty()); - gameDesignContext.run( - () -> - assertThatThrownBy( - () -> - missingHarness - .service() - .readRedeemedOperationProjection(missingHarness.request())) - .isInstanceOf( - AccountStartSessionOperatorAuthorizationService.NotFoundException.class)); + gameDesignContext.run(() -> + assertThatThrownBy(() -> + missingHarness.service().readRedeemedOperationProjection(missingHarness.request())) + .isInstanceOf(AccountStartSessionOperatorAuthorizationService.NotFoundException.class)); verify(missingHarness.actors(), never()) .withCurrentCommitted(any(), any(), any(), any(), any()); @@ -847,15 +821,11 @@ void projectionRejectsMissingUnredeemedAndWrongRedeemerRecords() { .repository() .findByControlPlaneRequestId(issuedHarness.tuple().controlPlaneRequestId())) .thenReturn(Optional.of(issued)); - gameDesignContext.run( - () -> - assertThatThrownBy( - () -> - issuedHarness - .service() - .readRedeemedOperationProjection(issuedHarness.request())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Stored redeemed operation")); + gameDesignContext.run(() -> + assertThatThrownBy(() -> + issuedHarness.service().readRedeemedOperationProjection(issuedHarness.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Stored redeemed operation")); verify(issuedHarness.actors(), never()).withCurrentCommitted(any(), any(), any(), any(), any()); ReadHarness wrongRedeemerHarness = readHarness(NOW.plusSeconds(30)); @@ -866,15 +836,13 @@ void projectionRejectsMissingUnredeemedAndWrongRedeemerRecords() { .repository() .findByControlPlaneRequestId(wrongRedeemerHarness.tuple().controlPlaneRequestId())) .thenReturn(Optional.of(wrongRedeemer)); - gameDesignContext.run( - () -> - assertThatThrownBy( - () -> - wrongRedeemerHarness - .service() - .readRedeemedOperationProjection(wrongRedeemerHarness.request())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Stored redeemed operation")); + gameDesignContext.run(() -> + assertThatThrownBy(() -> + wrongRedeemerHarness + .service() + .readRedeemedOperationProjection(wrongRedeemerHarness.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Stored redeemed operation")); verify(wrongRedeemerHarness.actors(), never()) .withCurrentCommitted(any(), any(), any(), any(), any()); } @@ -947,24 +915,19 @@ void projectionRejectsTupleOwnerAttemptFenceAndFingerprintSubstitutionBeforeCurr Context gameDesignContext = gameDesignContext(); for (ReadRedeemedOperationProjectionRequest request : requests) { - gameDesignContext.run( - () -> - assertThatThrownBy(() -> harness.service().readRedeemedOperationProjection(request)) - .isInstanceOf(IllegalStateException.class)); + gameDesignContext.run(() -> + assertThatThrownBy(() -> harness.service().readRedeemedOperationProjection(request)) + .isInstanceOf(IllegalStateException.class)); } verify(harness.actors(), never()).withCurrentCommitted(any(), any(), any(), any(), any()); ReadHarness expiredHarness = readHarness(NOW.minusSeconds(10)); - gameDesignContext.run( - () -> - assertThatThrownBy( - () -> - expiredHarness - .service() - .readRedeemedOperationProjection(expiredHarness.request())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Stored redeemed operation")); + gameDesignContext.run(() -> + assertThatThrownBy(() -> + expiredHarness.service().readRedeemedOperationProjection(expiredHarness.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Stored redeemed operation")); verify(expiredHarness.actors(), never()) .withCurrentCommitted(any(), any(), any(), any(), any()); } @@ -979,12 +942,11 @@ void projectionRejectsRevokedOrChangedCurrentAccountSource() { Context.current() .withValue( GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(GAME_DESIGN_PEER).orElseThrow()) - .run( - () -> - assertThatThrownBy( - () -> harness.service().readRedeemedOperationProjection(harness.request())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Current Account source")); + .run(() -> + assertThatThrownBy( + () -> harness.service().readRedeemedOperationProjection(harness.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Current Account source")); verify(harness.actors()) .withCurrentCommitted( @@ -1019,12 +981,11 @@ void recoveryDoesNotDecryptOrRecreateAnErasedOriginalResponse() { Context.current() .withValue( GrpcPeerIdentity.CONTEXT_KEY, GrpcPeerIdentity.parseUri(LOGGING_PEER).orElseThrow()) - .run( - () -> - assertThatThrownBy(() -> harness.service().recover(request)) - .isInstanceOf( - AccountStartSessionOperatorAuthorizationService - .ResponseEnvelopeErasedException.class)); + .run(() -> + assertThatThrownBy(() -> harness.service().recover(request)) + .isInstanceOf( + AccountStartSessionOperatorAuthorizationService.ResponseEnvelopeErasedException + .class)); verify(harness.responseCrypto(), never()).decrypt(any(), any(), any()); verify(harness.repository(), never()).createOrReadExact(any()); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionServiceTest.java index b83f479ef7..52681f1078 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionServiceTest.java @@ -166,17 +166,15 @@ void rejectsUnavailableOrSubstitutedGameSessionRequestEchoBeforeIssuerCallbackOr for (Function substituteEcho : substitutedEchoes) { Harness harness = new Harness(); when(harness.gameSessionClient.read(any(Request.class))) - .thenAnswer( - invocation -> { - assertNoSql(); - harness.steps.add("remote-read"); - Request expected = invocation.getArgument(0); - Request echoed = substituteEcho.apply(expected); - return echoed == null - ? null - : new Result( - echoed, ORIGINAL_LEASE_EXPIRY, projection(harness.tuple, Map.of())); - }); + .thenAnswer(invocation -> { + assertNoSql(); + harness.steps.add("remote-read"); + Request expected = invocation.getArgument(0); + Request echoed = substituteEcho.apply(expected); + return echoed == null + ? null + : new Result(echoed, ORIGINAL_LEASE_EXPIRY, projection(harness.tuple, Map.of())); + }); assertCode( Status.Code.FAILED_PRECONDITION, @@ -350,20 +348,19 @@ void discoversCommittedCoordinatesByExactTupleAfterPostCommitReadbackRefusalAndE assertThat(harness.readbackTransactions.rollbacks).isEqualTo(1); when(harness.participationRepository.findHistoricalForOriginalTuple(any(byte[].class))) - .thenAnswer( - invocation -> { - assertWritableReadCommittedTransaction(); - byte[] lookupTuple = invocation.getArgument(0); - assertThat(lookupTuple).containsExactly(harness.tuple.canonicalBytes()); - assertThat(harness.committedParticipation.originalPostAuthorizationTuple()) - .containsExactly(lookupTuple); - assertThat(harness.committedParticipation.sources()).hasSize(1); - assertThat(harness.committedParticipation.sources().get(0).canonicalBytes()) - .containsExactly( - participationSource(sourceEvidence("current source")).canonicalBytes()); - harness.steps.add("historical-tuple-readback"); - return Optional.of(harness.committedParticipation); - }); + .thenAnswer(invocation -> { + assertWritableReadCommittedTransaction(); + byte[] lookupTuple = invocation.getArgument(0); + assertThat(lookupTuple).containsExactly(harness.tuple.canonicalBytes()); + assertThat(harness.committedParticipation.originalPostAuthorizationTuple()) + .containsExactly(lookupTuple); + assertThat(harness.committedParticipation.sources()).hasSize(1); + assertThat(harness.committedParticipation.sources().get(0).canonicalBytes()) + .containsExactly( + participationSource(sourceEvidence("current source")).canonicalBytes()); + harness.steps.add("historical-tuple-readback"); + return Optional.of(harness.committedParticipation); + }); var historicalService = new AccountStartSessionWorldParticipationHistoricalReadService( harness.participationRepository, harness.readbackTransactions, NAMESPACE); @@ -705,54 +702,49 @@ void configureSuccess() { .withCurrentWorldReceivingParticipationCurrentness( any(byte[].class), eq(GAME_SESSION_ATTEMPT_ID), eq(GAME_SESSION_FENCE), any()); when(participationRepository.createOrReadExact(any(Candidate.class))) - .thenAnswer( - invocation -> { - assertWritableReadCommittedTransaction(); - steps.add("participation-write"); - return committedParticipation; - }); + .thenAnswer(invocation -> { + assertWritableReadCommittedTransaction(); + steps.add("participation-write"); + return committedParticipation; + }); when(attemptEvidenceRepository.retainCurrentExact( any(StoredParticipation.class), any(Result.class))) - .thenAnswer( - invocation -> { - assertWritableReadCommittedTransaction(); - steps.add("proof-write"); - StoredParticipation exactParticipation = invocation.getArgument(0); - Result observation = invocation.getArgument(1); - StoredEvidence existing = retainedProof.get(); - if (existing != null) return existing; - StoredEvidence created = storedEvidence(exactParticipation, observation); - retainedProof.set(created); - return created; - }); + .thenAnswer(invocation -> { + assertWritableReadCommittedTransaction(); + steps.add("proof-write"); + StoredParticipation exactParticipation = invocation.getArgument(0); + Result observation = invocation.getArgument(1); + StoredEvidence existing = retainedProof.get(); + if (existing != null) return existing; + StoredEvidence created = storedEvidence(exactParticipation, observation); + retainedProof.set(created); + return created; + }); when(participationRepository.findCurrentExact(any(Candidate.class))) - .thenAnswer( - invocation -> { - assertWritableReadCommittedTransaction(); - steps.add("participation-readback"); - return participationMissingOnReadback - ? Optional.empty() - : Optional.of(participationReadback.get()); - }); + .thenAnswer(invocation -> { + assertWritableReadCommittedTransaction(); + steps.add("participation-readback"); + return participationMissingOnReadback + ? Optional.empty() + : Optional.of(participationReadback.get()); + }); when(attemptEvidenceRepository.findCurrentExact( any(StoredParticipation.class), any(Request.class))) - .thenAnswer( - invocation -> { - assertWritableReadCommittedTransaction(); - steps.add("proof-readback"); - return Optional.ofNullable(retainedProof.get()); - }); + .thenAnswer(invocation -> { + assertWritableReadCommittedTransaction(); + steps.add("proof-readback"); + return Optional.ofNullable(retainedProof.get()); + }); } void configureClientResult(byte[] projectionBytes) { when(gameSessionClient.read(any(Request.class))) - .thenAnswer( - invocation -> { - assertNoSql(); - steps.add("remote-read"); - Request read = invocation.getArgument(0); - return new Result(read, ORIGINAL_LEASE_EXPIRY, projectionBytes); - }); + .thenAnswer(invocation -> { + assertNoSql(); + steps.add("remote-read"); + Request read = invocation.getArgument(0); + return new Result(read, ORIGINAL_LEASE_EXPIRY, projectionBytes); + }); } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadServiceTest.java index 2859dea367..07cbea73d6 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadServiceTest.java @@ -97,11 +97,10 @@ void readsExactHistoryAfterIngressExpiryAndPriorSettlementWithoutCurrentnessOrMu throws Exception { StoredParticipation expired = participation(true); when(repository.findHistoricalForOriginalTuple(request(true).originalPostAuthorizationTuple())) - .thenAnswer( - call -> { - assertWritableReadCommittedTransaction(); - return Optional.of(expired); - }); + .thenAnswer(call -> { + assertWritableReadCommittedTransaction(); + return Optional.of(expired); + }); // A prior terminal receipt is deliberately present; historical participation reads do not // require it, rewrite it, or treat its outcome as fresh execution permission. when(repository.findSettlementExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) @@ -151,13 +150,12 @@ void absentMismatchedNamespaceAndMismatchedRetainedIdentityFailClosed() { assertCode( Status.Code.PERMISSION_DENIED, () -> - authorized( - () -> - service.read( - new AccountStartSessionWorldParticipationHistoricalReadRequest( - READ_ID, - "other-runtime", - originalTuple("other-runtime", false).canonicalBytes())))); + authorized(() -> + service.read( + new AccountStartSessionWorldParticipationHistoricalReadRequest( + READ_ID, + "other-runtime", + originalTuple("other-runtime", false).canonicalBytes())))); verify(repository, org.mockito.Mockito.times(2)) .findHistoricalForOriginalTuple(request(false).originalPostAuthorizationTuple()); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java index f721291564..35c26667bf 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java @@ -87,10 +87,9 @@ void exactWorldClientReachesReceiverAndPassesOnlyTheRetainedLookupToOwner() thro assertThatThrownBy(() -> client.settle(input())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); assertThat(server.handlerCalls()).hasValue(1); verify(owner).settle(PARTICIPATION_ID, PARTICIPATION_FENCE); @@ -108,11 +107,10 @@ void trustedWrongServiceAndNamespaceCertificatesAreDeniedBeforeOwnerInteraction( assertThatThrownBy(() -> client.settle(input())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .as(identity.alias()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .as(identity.alias()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); assertThat(server.handlerCalls()).as(identity.alias()).hasValue(1); verifyNoInteractions(owner); @@ -131,13 +129,10 @@ void missingClientCertificateFailsDuringTlsBeforeHandlerOrOwner() throws Excepti assertThatThrownBy(() -> client.settle(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) - .as( - "missing client certificate must fail during TLS negotiation: %s", - failure) - .isTrue()); + .satisfies(failure -> + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as("missing client certificate must fail during TLS negotiation: %s", failure) + .isTrue()); assertThat(server.handlerCalls()).hasValue(0); verifyNoInteractions(owner); @@ -153,10 +148,9 @@ void authenticatedEndUserContextIsDeniedAtReceiverBeforeOwnerInteraction() throw assertThatThrownBy(() -> client.settle(input())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); assertThat(server.handlerCalls()).hasValue(1); verifyNoInteractions(owner); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementServiceTest.java index 731003e29a..f86b0a03bd 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementServiceTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementServiceTest.java @@ -114,31 +114,29 @@ void derivesExactReadFromRetainedParticipationAndCommitsThenReadsBackBothOutcome when(repository.findSettlementExact(PARTICIPATION_ID, PARTICIPATION_FENCE)) .thenReturn(Optional.empty(), Optional.of(expected)); when(world.read(any())) - .thenAnswer( - call -> { - assertNoSql(); - WorldStartSessionExecutionTerminalReadRequest request = call.getArgument(0); - assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); - assertThat(request.originalPostAuthorizationTuple()) - .containsExactly(fixture.participation.originalPostAuthorizationTuple()); - assertThat(request.accountWorldParticipationId()).isEqualTo(PARTICIPATION_ID); - assertThat(request.accountWorldParticipationFence()).isEqualTo(PARTICIPATION_FENCE); - assertThat(request.gameSessionOwnerAttemptId()).isEqualTo(GAME_SESSION_ATTEMPT_ID); - assertThat(request.gameSessionOwnerFence()).isEqualTo(GAME_SESSION_FENCE); - assertThat(request.canonicalGameInstanceId()).isEqualTo(GAME_INSTANCE_ID); - assertThat(request.preparationInputJson()).isEqualTo(PREPARATION_INPUT); - assertThat(request.preparationInputDigest()) - .isEqualTo(fixture.participation.preparationInputDigest()); - return terminal; - }); + .thenAnswer(call -> { + assertNoSql(); + WorldStartSessionExecutionTerminalReadRequest request = call.getArgument(0); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.originalPostAuthorizationTuple()) + .containsExactly(fixture.participation.originalPostAuthorizationTuple()); + assertThat(request.accountWorldParticipationId()).isEqualTo(PARTICIPATION_ID); + assertThat(request.accountWorldParticipationFence()).isEqualTo(PARTICIPATION_FENCE); + assertThat(request.gameSessionOwnerAttemptId()).isEqualTo(GAME_SESSION_ATTEMPT_ID); + assertThat(request.gameSessionOwnerFence()).isEqualTo(GAME_SESSION_FENCE); + assertThat(request.canonicalGameInstanceId()).isEqualTo(GAME_INSTANCE_ID); + assertThat(request.preparationInputJson()).isEqualTo(PREPARATION_INPUT); + assertThat(request.preparationInputDigest()) + .isEqualTo(fixture.participation.preparationInputDigest()); + return terminal; + }); when(repository.settleExact(any())) - .thenAnswer( - call -> { - assertWritableTransaction(); - assertThat(call.getArgument(0, WorldStartSessionExecutionTerminal.class).outcome()) - .isEqualTo(outcome); - return expected; - }); + .thenAnswer(call -> { + assertWritableTransaction(); + assertThat(call.getArgument(0, WorldStartSessionExecutionTerminal.class).outcome()) + .isEqualTo(outcome); + return expected; + }); int priorCommits = transactions.commits; StoredSettlement actual = @@ -222,11 +220,10 @@ void exactCodecRejectsSubstitutedWorldTerminalAndNoSqlOccursAcrossNetwork() { 41L, WorldStartSessionExecutionTerminal.Outcome.COMMITTED); when(world.read(any())) - .thenAnswer( - call -> { - assertNoSql(); - return substituted; - }); + .thenAnswer(call -> { + assertNoSql(); + return substituted; + }); assertThatThrownBy( () -> authorized(() -> service.settle(PARTICIPATION_ID, PARTICIPATION_FENCE))) .isInstanceOf(IllegalArgumentException.class) diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionBindingTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionBindingTest.java index 9fa10e5679..a9e614d5cc 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionBindingTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionBindingTest.java @@ -64,12 +64,11 @@ void boundedPolicyRejectsExtendedLogicalWindowRetentionAndUnsafeIntegers() { .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> deadlines(binding, NOW, NOW + 86_400_000L)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - deadlines( - binding, - binding.operationDeadlineEpochMillis(), - binding.receiptCleanupDeadlineEpochMillis() + 1L)) + assertThatThrownBy(() -> + deadlines( + binding, + binding.operationDeadlineEpochMillis(), + binding.receiptCleanupDeadlineEpochMillis() + 1L)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> deadlines(binding, Long.MAX_VALUE, Long.MAX_VALUE)) .isInstanceOf(IllegalArgumentException.class); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionOwnerTest.java index e057d0a388..58509c9899 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionOwnerTest.java @@ -217,12 +217,11 @@ void changedTokenCannotRebindAnExistingPreparedAdmissionOrReachRedis() { new AccountControlUiIssuanceRepository.Stored(Fixture.row(changedIssuanceRow)); when(fixture.issuances.findToken(changedTokenHash)).thenReturn(changedIssuance); when(fixture.actors.withCurrentAccount(eq(changedJwt), any())) - .thenAnswer( - invocation -> { - Function action = invocation.getArgument(1); - return new TransactionTemplate(fixture.transactionManager) - .execute(ignored -> action.apply(changedActor)); - }); + .thenAnswer(invocation -> { + Function action = invocation.getArgument(1); + return new TransactionTemplate(fixture.transactionManager) + .execute(ignored -> action.apply(changedActor)); + }); assertThatThrownBy(() -> fixture.start(changedJwt, fixture.request)) .isInstanceOf(IllegalStateException.class); @@ -481,20 +480,19 @@ private static final class Fixture { when(captured.sources()).thenReturn(sources); when(transactionManager.getTransaction(any())) - .thenAnswer( - invocation -> { - TransactionDefinition definition = invocation.getArgument(0); - if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) { - assertThat(definition.getIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); - } - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - TransactionSynchronizationManager.setActualTransactionActive(true); - TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); - currentTransactionId = ++begins; - events.add("begin:" + currentTransactionId); - return mock(TransactionStatus.class); - }); + .thenAnswer(invocation -> { + TransactionDefinition definition = invocation.getArgument(0); + if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) { + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + } + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + TransactionSynchronizationManager.setActualTransactionActive(true); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + currentTransactionId = ++begins; + events.add("begin:" + currentTransactionId); + return mock(TransactionStatus.class); + }); doAnswer( ignored -> { events.add("commit:" + currentTransactionId); @@ -518,13 +516,12 @@ private static final class Fixture { .rollback(any()); when(actors.withCurrentAccount(eq(JWT), any())) - .thenAnswer( - invocation -> { - events.add("account-actor"); - Function action = invocation.getArgument(1); - return new TransactionTemplate(transactionManager) - .execute(ignored -> action.apply(actor)); - }); + .thenAnswer(invocation -> { + events.add("account-actor"); + Function action = invocation.getArgument(1); + return new TransactionTemplate(transactionManager) + .execute(ignored -> action.apply(actor)); + }); when(actor.accountId()).thenReturn(accountId); when(actor.issuanceOperationId()).thenReturn(issuanceId); when(actor.tokenHash()).thenReturn(tokenHash); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionRedisClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionRedisClientTest.java index 794df9c3c6..323590c2e4 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionRedisClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAdmissionRedisClientTest.java @@ -137,9 +137,8 @@ void missingQualificationWrongBindingAndUnavailablePrincipalDenyBeforeMutation() var wrongPrincipal = new Fixture(); when(wrongPrincipal.writer.aclWhoami()).thenReturn("another_owner"); - assertThatThrownBy( - () -> - wrongPrincipal.client.withExistingReceipt(wrongPrincipal.binding, receipt -> true)) + assertThatThrownBy(() -> + wrongPrincipal.client.withExistingReceipt(wrongPrincipal.binding, receipt -> true)) .isInstanceOf(IllegalStateException.class); verify(wrongPrincipal.writer, never()).scriptLoad(any(byte[].class)); @@ -159,12 +158,11 @@ void insufficientLostOrMalformedAcknowledgementNeverCallsReadbackOrCallback() th var f = new Fixture(); doReturn(counts).when(f.writer).dispatch(any(), any(), any()); var called = new AtomicBoolean(); - assertThatThrownBy( - () -> - f.client.withInitialReceipt( - f.binding, - AccountTenantCreationAdmissionBindingTest.active(), - receipt -> called.compareAndSet(false, true))) + assertThatThrownBy(() -> + f.client.withInitialReceipt( + f.binding, + AccountTenantCreationAdmissionBindingTest.active(), + receipt -> called.compareAndSet(false, true))) .isInstanceOf(IllegalStateException.class); assertThat(called).isFalse(); verifyNoInteractions(f.reader); @@ -195,18 +193,16 @@ void changedExpiryInterruptedReadbackOrDeadlineCrossingCannotPublishEvidence() t var late = new Fixture(); when(late.reader.get(any(byte[].class))) - .thenAnswer( - ignored -> { - when(late.clock.millis()).thenReturn(late.binding.operationDeadlineEpochMillis()); - return late.binding.canonicalReceipt(); - }); + .thenAnswer(ignored -> { + when(late.clock.millis()).thenReturn(late.binding.operationDeadlineEpochMillis()); + return late.binding.canonicalReceipt(); + }); var called = new AtomicBoolean(); - assertThatThrownBy( - () -> - late.client.withInitialReceipt( - late.binding, - AccountTenantCreationAdmissionBindingTest.active(), - receipt -> called.compareAndSet(false, true))) + assertThatThrownBy(() -> + late.client.withInitialReceipt( + late.binding, + AccountTenantCreationAdmissionBindingTest.active(), + receipt -> called.compareAndSet(false, true))) .isInstanceOf(IllegalStateException.class); assertThat(called).isFalse(); } @@ -229,18 +225,15 @@ void unknownOutcomeOrMissingRecoveryCannotObtainDurabilityReceipt() throws Excep void lostExternalExclusionAfterPhysicalReadbackDoesNotEnterCallback() throws Exception { var f = new Fixture(); when(f.reader.get(any(byte[].class))) - .thenAnswer( - ignored -> { - doThrow(new IllegalStateException("Controlled external exclusion loss")) - .when(f.lease) - .requireCurrent(); - return f.binding.canonicalReceipt(); - }); + .thenAnswer(ignored -> { + doThrow(new IllegalStateException("Controlled external exclusion loss")) + .when(f.lease) + .requireCurrent(); + return f.binding.canonicalReceipt(); + }); var called = new AtomicBoolean(); - assertThatThrownBy( - () -> - f.client.withExistingReceipt( - f.binding, receipt -> called.compareAndSet(false, true))) + assertThatThrownBy(() -> + f.client.withExistingReceipt(f.binding, receipt -> called.compareAndSet(false, true))) .isInstanceOf(IllegalStateException.class); assertThat(called).isFalse(); verify(f.lease).close(); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAuthorizationPreparationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAuthorizationPreparationTest.java index 2238a3fb36..b9c22ea9d9 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAuthorizationPreparationTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationAuthorizationPreparationTest.java @@ -197,16 +197,15 @@ private static final class Fixture { Fixture() throws Exception { when(manager.getTransaction(any())) - .thenAnswer( - invocation -> { - TransactionDefinition definition = invocation.getArgument(0); - assertThat(definition.getIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - TransactionSynchronizationManager.setActualTransactionActive(true); - begins++; - return mock(TransactionStatus.class); - }); + .thenAnswer(invocation -> { + TransactionDefinition definition = invocation.getArgument(0); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + TransactionSynchronizationManager.setActualTransactionActive(true); + begins++; + return mock(TransactionStatus.class); + }); doAnswer( invocation -> { commits++; @@ -287,12 +286,11 @@ private static final class Fixture { .thenReturn(row); when(issuances.decodeStored(row)).thenReturn(issuance); when(actors.readAcceptedSignerKey("kid")) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(commits).isEqualTo(1); - return new AcceptedSignerKey("kid", "fingerprint"); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(commits).isEqualTo(1); + return new AcceptedSignerKey("kid", "fingerprint"); + }); when(captured.originalSignerReceipt()).thenReturn(receipt); when(captured.originalClaims()).thenReturn(issuance.claims); when(captured.issuanceOperationId()).thenReturn(issuanceId); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionOwnerTest.java index 9d1c692998..e40fef0960 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCompletionOwnerTest.java @@ -83,12 +83,11 @@ void exactCompletionUsesActualRetainedConsentAndReplaysWithoutNewWritesOrConsump order .verify(f.owners) .establishInitial( - Mockito.argThat( - request -> - request.requestId().equals(f.request) - && request.consentOperationId().equals(f.consent) - && request.consentStatementVersion() == 7 - && request.affirmativeConsent())); + Mockito.argThat(request -> + request.requestId().equals(f.request) + && request.consentOperationId().equals(f.consent) + && request.consentStatementVersion() == 7 + && request.affirmativeConsent())); order .verify(f.reauth) .validateAndConsumeLocked( @@ -521,11 +520,10 @@ private static final class Fixture { Fixture() throws Exception { when(manager.getTransaction(any())) - .thenAnswer( - invocation -> { - TransactionSynchronizationManager.setActualTransactionActive(true); - return mock(TransactionStatus.class); - }); + .thenAnswer(invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + return mock(TransactionStatus.class); + }); doAnswer( invocation -> { TransactionSynchronizationManager.setActualTransactionActive(false); @@ -625,11 +623,10 @@ private static final class Fixture { when(clock.get("observed_at", java.time.OffsetDateTime.class)) .thenAnswer(invocation -> databaseNow.atOffset(ZoneOffset.UTC)); when(dsl.fetchOne("SELECT clock_timestamp() AS observed_at")) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - return clock; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return clock; + }); when(holder.intentPayload()).thenReturn(new byte[] {1}); when(holder.intentDigest()).thenReturn("sha256:" + "b".repeat(64)); when(holder.admissionPayload()).thenReturn(admissionPayload); @@ -643,11 +640,10 @@ private static final class Fixture { when(orders.readSettlement(operation)) .thenAnswer(invocation -> settled ? Optional.of(evidence) : Optional.empty()); when(orders.settleLocked(holder, terminal)) - .thenAnswer( - invocation -> { - settled = true; - return evidence; - }); + .thenAnswer(invocation -> { + settled = true; + return evidence; + }); Record row = mock(Record.class); when(row.get("authorization_scope", String.class)).thenReturn("ACCOUNT"); when(row.get("operation_id", UUID.class)).thenReturn(issuanceId); @@ -670,12 +666,11 @@ private static final class Fixture { issuanceId)) .thenReturn(row); when(actors.readAcceptedSignerKey("kid")) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - beforeSignerRead.run(); - return new AccountControlUiActorService.AcceptedSignerKey("kid", "fingerprint"); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + beforeSignerRead.run(); + return new AccountControlUiActorService.AcceptedSignerKey("kid", "fingerprint"); + }); var captured = mock(AccountTenantCreationOwnerSourceCapture.Captured.class); when(captured.originalClaims()).thenReturn(issuance.claims); when(captured.originalSignerReceipt()).thenReturn(signer); @@ -702,17 +697,15 @@ private static final class Fixture { var bootstrap = mock(AccountTenantCreationBootstrapResult.class); when(bootstrap.resultDigest()).thenReturn("bootstrap"); when(bootstraps.bootstrapForCompletion(any(), any())) - .thenAnswer( - invocation -> { - var creator = - invocation - . - getArgument(0); - var source = - invocation.getArgument(1); - return source.withCurrentAuthorizationAndSourceParticipation( - creator, () -> bootstrap); - }); + .thenAnswer(invocation -> { + var creator = + invocation + .getArgument( + 0); + var source = + invocation.getArgument(1); + return source.withCurrentAuthorizationAndSourceParticipation(creator, () -> bootstrap); + }); var transaction = mock(Record.class); when(transaction.get("owner_transaction", String.class)).thenReturn("transaction"); when(dsl.fetchOne("SELECT txid_current()::text AS owner_transaction")) @@ -732,37 +725,35 @@ private static final class Fixture { when(reauth.validateAndConsumeLocked(any(), any(), anyString(), any())) .thenReturn(consumption); when(audits.appendCanonicalTenant(any(), anyString(), anyString(), anyString())) - .thenAnswer( - invocation -> { - var audit = mock(AccountAuditEnvelope.class); - String payload = invocation.getArgument(3); - String digest = - "sha256:" - + AccountControlUiIssuanceRepository.hash( - payload.getBytes(java.nio.charset.StandardCharsets.UTF_8)); - when(audit.payloadDigest()).thenReturn(digest); - return audit; - }); + .thenAnswer(invocation -> { + var audit = mock(AccountAuditEnvelope.class); + String payload = invocation.getArgument(3); + String digest = + "sha256:" + + AccountControlUiIssuanceRepository.hash( + payload.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + when(audit.payloadDigest()).thenReturn(digest); + return audit; + }); when(dsl.fetchOne( "SELECT * FROM account_tenant_creation_completions WHERE creation_operation_id = ?", operation)) .thenAnswer(invocation -> resultRow); when(dsl.execute(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - Object[] values = (Object[]) invocation.getRawArguments()[1]; - Map stored = new HashMap<>(); - stored.put("intent_request_id", values[1]); - stored.put("tenant_uuid", values[2]); - stored.put("terminal_payload", values[3]); - stored.put("terminal_digest", values[4]); - stored.put("result_payload", values[5]); - stored.put("result_digest", values[6]); - resultRow = mock(Record.class); - when(resultRow.get(anyString(), any(Class.class))) - .thenAnswer(read -> stored.get(read.getArgument(0))); - return 1; - }); + .thenAnswer(invocation -> { + Object[] values = (Object[]) invocation.getRawArguments()[1]; + Map stored = new HashMap<>(); + stored.put("intent_request_id", values[1]); + stored.put("tenant_uuid", values[2]); + stored.put("terminal_payload", values[3]); + stored.put("terminal_digest", values[4]); + stored.put("result_payload", values[5]); + stored.put("result_digest", values[6]); + resultRow = mock(Record.class); + when(resultRow.get(anyString(), any(Class.class))) + .thenAnswer(read -> stored.get(read.getArgument(0))); + return 1; + }); } AccountTenantCreationCompletionOwner.Result complete() { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCurrentAuthorizationOwnerTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCurrentAuthorizationOwnerTest.java index 33f54849cc..fc96ce334a 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCurrentAuthorizationOwnerTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationCurrentAuthorizationOwnerTest.java @@ -216,15 +216,14 @@ private static final class Fixture { Fixture() throws Exception { when(manager.getTransaction(any())) - .thenAnswer( - call -> { - TransactionDefinition definition = call.getArgument(0); - assertThat(definition.getIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); - assertThat(definition.getTimeout()).isEqualTo(5); - TransactionSynchronizationManager.setActualTransactionActive(true); - return mock(TransactionStatus.class); - }); + .thenAnswer(call -> { + TransactionDefinition definition = call.getArgument(0); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getTimeout()).isEqualTo(5); + TransactionSynchronizationManager.setActualTransactionActive(true); + return mock(TransactionStatus.class); + }); doAnswer( call -> { commits++; @@ -318,18 +317,16 @@ private static final class Fixture { .thenReturn(row); when(issuances.decodeStored(row)).thenReturn(issuance); when(actors.readAcceptedSignerKey("kid")) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(commits).isEqualTo(1); - return new AccountControlUiActorService.AcceptedSignerKey("kid", "fingerprint"); - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(commits).isEqualTo(1); + return new AccountControlUiActorService.AcceptedSignerKey("kid", "fingerprint"); + }); when(terms.captureCurrentEnvironmentBoundary()) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return environment; - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return environment; + }); when(capture.captureLocked(any(), any(), any(), any())).thenReturn(captured); when(captured.originalClaims()).thenReturn(new byte[] {3}); when(captured.originalSignerReceipt()).thenReturn(signer); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationDispatchRepositoryTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationDispatchRepositoryTest.java index 89e59014cf..ff69026ac0 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationDispatchRepositoryTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationDispatchRepositoryTest.java @@ -192,11 +192,10 @@ private static final class Fixture { Fixture() { var manager = mock(PlatformTransactionManager.class); when(manager.getTransaction(any())) - .thenAnswer( - invocation -> { - TransactionSynchronizationManager.setActualTransactionActive(true); - return mock(TransactionStatus.class); - }); + .thenAnswer(invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + return mock(TransactionStatus.class); + }); doAnswer( invocation -> { commits++; @@ -273,11 +272,10 @@ private static final class Fixture { issuance)) .thenReturn(original); when(actors.readAcceptedSignerKey("kid")) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return new AccountControlUiActorService.AcceptedSignerKey("kid", "fingerprint"); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new AccountControlUiActorService.AcceptedSignerKey("kid", "fingerprint"); + }); var observed = mock(AccountTenantCreationOwnerSourceCapture.Captured.class); when(observed.originalClaims()).thenReturn(stored.claims); when(observed.originalSignerReceipt()).thenReturn(signer); @@ -301,26 +299,24 @@ private static final class Fixture { .thenAnswer(invocation -> hideClaim ? null : row); observe(Instant.ofEpochMilli(1899999900000L)); when(dsl.fetchOne("SELECT clock_timestamp() AS observed_at")) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - return clock; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + return clock; + }); when(dsl.execute(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - Object[] values = (Object[]) invocation.getRawArguments()[1]; - claimFields.put("creation_operation_id", values[0]); - claimFields.put("dispatch_call_id", values[1]); - claimFields.put("authorization_binding_payload", values[2]); - claimFields.put("authorization_digest", values[3]); - claimFields.put("valid_before_epoch_millis", values[4]); - row = mock(Record.class); - when(row.get(anyString(), any(Class.class))) - .thenAnswer(read -> claimFields.get(read.getArgument(0))); - return 1; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + Object[] values = (Object[]) invocation.getRawArguments()[1]; + claimFields.put("creation_operation_id", values[0]); + claimFields.put("dispatch_call_id", values[1]); + claimFields.put("authorization_binding_payload", values[2]); + claimFields.put("authorization_digest", values[3]); + claimFields.put("valid_before_epoch_millis", values[4]); + row = mock(Record.class); + when(row.get(anyString(), any(Class.class))) + .thenAnswer(read -> claimFields.get(read.getArgument(0))); + return 1; + }); repository = new AccountTenantCreationDispatchRepository( dsl, intents, admissions, orders, issuances, actors, capture, manager); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationOwnerSourceCaptureTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationOwnerSourceCaptureTest.java index 2df6692324..415b7f8829 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationOwnerSourceCaptureTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountTenantCreationOwnerSourceCaptureTest.java @@ -228,10 +228,8 @@ void stalePolicyAndReauthenticationBindingAreDeniedWithoutConsumption() throws E f = new Fixture(); var wrong = f.evidence(UUID.randomUUID(), f.operation); var denied = f; - assertThatThrownBy( - () -> - denied.capture.captureLocked( - denied.intent, denied.admitted, denied.environment, wrong)) + assertThatThrownBy(() -> + denied.capture.captureLocked(denied.intent, denied.admitted, denied.environment, wrong)) .isInstanceOf(IllegalStateException.class); org.mockito.Mockito.verifyNoInteractions(f.reauth); f = new Fixture(); @@ -289,10 +287,9 @@ void ownerReauthenticationDenialAndIncompleteSourceVectorPropagate() throws Exce var current = f.currentness(f.party, f.owner.id); var sources = new ArrayList<>(current.sourceEvidence()); sources.add(sources.getFirst()); - assertThatThrownBy( - () -> - new EnvironmentBoundCurrentness( - current.environment(), current.binding(), current.terms(), sources)) + assertThatThrownBy(() -> + new EnvironmentBoundCurrentness( + current.environment(), current.binding(), current.terms(), sources)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProviderTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProviderTest.java index 8bcd6c5d1f..525f9b1475 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProviderTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/LettuceAccountCoordinationPinnedConnectionProviderTest.java @@ -81,14 +81,13 @@ void disposesConnectionThatFinishesAfterConcurrentProviderClose() throws Excepti CountDownLatch connectStarted = new CountDownLatch(1); CountDownLatch finishConnect = new CountDownLatch(1); when(client.connect(ByteArrayCodec.INSTANCE)) - .thenAnswer( - ignored -> { - connectStarted.countDown(); - if (!finishConnect.await(5, TimeUnit.SECONDS)) { - throw new AssertionError("test connection was not released"); - } - return connection; - }); + .thenAnswer(ignored -> { + connectStarted.countDown(); + if (!finishConnect.await(5, TimeUnit.SECONDS)) { + throw new AssertionError("test connection was not released"); + } + return connection; + }); ExecutorService executor = Executors.newSingleThreadExecutor(); try (MockedStatic redisClientFactory = mockStatic(RedisClient.class)) { redisClientFactory.when(() -> RedisClient.create(uri)).thenReturn(client); diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPkiTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPkiTest.java index e738bd42f4..1621be8912 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPkiTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPkiTest.java @@ -18,10 +18,8 @@ class AccountStartSessionReservationProofPkiTest { void timeoutTerminatesAndReapsTheStalledChild() throws Exception { Process process = awaitingPassword(); try { - assertThatThrownBy( - () -> - AccountStartSessionReservationProofPki.awaitKeytoolExit( - process, 1, TimeUnit.SECONDS)) + assertThatThrownBy(() -> + AccountStartSessionReservationProofPki.awaitKeytoolExit(process, 1, TimeUnit.SECONDS)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("execution deadline"); assertThat(process.isAlive()).isFalse(); @@ -37,10 +35,9 @@ void interruptionTerminatesAndReapsTheChildAndRestoresTheInterruptFlag() throws Process process = awaitingPassword(); try { Thread.currentThread().interrupt(); - assertThatThrownBy( - () -> - AccountStartSessionReservationProofPki.awaitKeytoolExit( - process, 30, TimeUnit.SECONDS)) + assertThatThrownBy(() -> + AccountStartSessionReservationProofPki.awaitKeytoolExit( + process, 30, TimeUnit.SECONDS)) .isInstanceOf(InterruptedException.class); assertThat(Thread.currentThread().isInterrupted()).isTrue(); Thread.interrupted(); diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index c08602aa0a..4b9e8d27dd 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -550,12 +550,11 @@ public void assertOriginalDraftSettlement( } public byte[] originalDraftOwnerReadback(DraftAuthorizationFenceBinding original, Owner owner) { - return f.tx( - () -> - f.fences - .readOwnerResult(original, owner) - .orElseThrow(() -> new AssertionError("Original Draft owner readback absent")) - .readback()) + return f.tx(() -> + f.fences + .readOwnerResult(original, owner) + .orElseThrow(() -> new AssertionError("Original Draft owner readback absent")) + .readback()) .clone(); } diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java index f3124dfc74..6e7824b219 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -227,25 +227,23 @@ final class AccountControlUiOwnerSourcesFixture { new AccountPlatformRestrictionOperationRepository( dsl, generations, outbox, sourceEvidence, restrictionBirths); account = - tx( - () -> { - Account candidate = new Account(); - String suffix = UUID.randomUUID().toString(); - candidate.setUsername("owner-" + suffix); - candidate.setEmail(suffix + "@example.test"); - candidate.setPasswordHash(hash("test-only-disabled-password")); - candidate.setLoginAuthModes("EMAIL_OTP"); - return accounts.save(candidate); - }); + tx(() -> { + Account candidate = new Account(); + String suffix = UUID.randomUUID().toString(); + candidate.setUsername("owner-" + suffix); + candidate.setEmail(suffix + "@example.test"); + candidate.setPasswordHash(hash("test-only-disabled-password")); + candidate.setLoginAuthModes("EMAIL_OTP"); + return accounts.save(candidate); + }); var creator = testCreation(account.getAccountUuid(), creationEvidence); var fresh = new FreshTenantIdentityAssociationRepository(dsl, creationEvidence.targetNamespace()); - tx( - () -> { - fresh.importVerified(creator.creationEvidence()); - generations.initializeTenantIfAbsent(tenant); - return null; - }); + tx(() -> { + fresh.importVerified(creator.creationEvidence()); + generations.initializeTenantIfAbsent(tenant); + return null; + }); var pairs = new AccountMembershipPairAuthorityRepository(dsl); var memberships = new AccountTenantMembershipRepository(dsl, accounts, fresh, pairs); var roles = new AccountTenantMembershipRoleSnapshotRepository(dsl); @@ -376,18 +374,17 @@ final class AccountControlUiOwnerSourcesFixture { restrictionOperations, dsl); challenges = new AccountEmailLoginChallengeRepository(dsl); - tx( - () -> { - var challenge = new AccountEmailLoginChallenge(); - var now = LocalDateTime.now().withNano(0); - challenge.setAccountId(account.getId()); - challenge.setCodeHash(hash(OTP)); - challenge.setExpiresAt(now.plusMinutes(5)); - challenge.setResendAvailableAt(now.plusMinutes(1)); - challenge.setCreatedAt(now); - challenge.setUpdatedAt(now); - return challenges.save(challenge); - }); + tx(() -> { + var challenge = new AccountEmailLoginChallenge(); + var now = LocalDateTime.now().withNano(0); + challenge.setAccountId(account.getId()); + challenge.setCodeHash(hash(OTP)); + challenge.setExpiresAt(now.plusMinutes(5)); + challenge.setResendAvailableAt(now.plusMinutes(1)); + challenge.setCreatedAt(now); + challenge.setUpdatedAt(now); + return challenges.save(challenge); + }); var primaryTarget = new AccountServiceImpl( accounts, @@ -501,17 +498,16 @@ AccountControlUiIssuanceService.Request request(String secret) { /** Fresh real Account/auth sources only; no tenant membership or current restriction is added. */ Account createGlobalAccount(String password) { - return tx( - () -> { - Account candidate = new Account(); - String suffix = UUID.randomUUID().toString(); - candidate.setUsername("global-owner-" + suffix); - candidate.setEmail(suffix + "@example.test"); - candidate.setPasswordHash(hash(password)); - candidate.setEmailVerified(true); - candidate.setLoginAuthModes(AccountLoginAuthModes.DEFAULT_SERIALIZED); - return accounts.save(candidate); - }); + return tx(() -> { + Account candidate = new Account(); + String suffix = UUID.randomUUID().toString(); + candidate.setUsername("global-owner-" + suffix); + candidate.setEmail(suffix + "@example.test"); + candidate.setPasswordHash(hash(password)); + candidate.setEmailVerified(true); + candidate.setLoginAuthModes(AccountLoginAuthModes.DEFAULT_SERIALIZED); + return accounts.save(candidate); + }); } /** @@ -520,30 +516,29 @@ Account createGlobalAccount(String password) { * The ordinary createGlobalAccount helper deliberately remains uncertified for negative proofs. */ Account createCertifiedGlobalAccount(String password) { - return tx( - () -> { - for (Category category : Category.values()) { - ensureControlledFreshEnrollmentPolicy(category); - } - String suffix = UUID.randomUUID().toString(); - var result = - new AccountFreshEnrollmentRepository( - dsl, - accounts, - new AccountFreshEnrollmentPolicyRepository(dsl), - restrictionOperations) - .enroll( - new AccountFreshEnrollmentRequest( - UUID.randomUUID(), - "global-" + suffix, - suffix + "@example.test", - hash(password), - true, - AccountLoginAuthModes.DEFAULT_SERIALIZED)); - assertThat(result.accountSecurityLock().receipt()).isPresent(); - assertThat(result.platformAccessBan().receipt()).isPresent(); - return accounts.findById(result.accountId()).orElseThrow(); - }); + return tx(() -> { + for (Category category : Category.values()) { + ensureControlledFreshEnrollmentPolicy(category); + } + String suffix = UUID.randomUUID().toString(); + var result = + new AccountFreshEnrollmentRepository( + dsl, + accounts, + new AccountFreshEnrollmentPolicyRepository(dsl), + restrictionOperations) + .enroll( + new AccountFreshEnrollmentRequest( + UUID.randomUUID(), + "global-" + suffix, + suffix + "@example.test", + hash(password), + true, + AccountLoginAuthModes.DEFAULT_SERIALIZED)); + assertThat(result.accountSecurityLock().receipt()).isPresent(); + assertThat(result.platformAccessBan().receipt()).isPresent(); + return accounts.findById(result.accountId()).orElseThrow(); + }); } private void ensureControlledFreshEnrollmentPolicy(Category category) { @@ -665,22 +660,21 @@ private static byte[] canonicalPolicyPublicationBytes( /** Stores an actual hashed email-OTP challenge for the separate Account's real primary path. */ AccountEmailLoginChallenge installGlobalOtp(Account globalAccount, String otp) { - return tx( - () -> { - challenges.lockAccountChallenge(globalAccount.getId()); - if (challenges.findByAccountId(globalAccount.getId()).isPresent()) { - throw new IllegalStateException("Global Account already has an email challenge"); - } - var now = LocalDateTime.now().withNano(0); - var challenge = new AccountEmailLoginChallenge(); - challenge.setAccountId(globalAccount.getId()); - challenge.setCodeHash(hash(otp)); - challenge.setExpiresAt(now.plusMinutes(5)); - challenge.setResendAvailableAt(now.plusMinutes(1)); - challenge.setCreatedAt(now); - challenge.setUpdatedAt(now); - return challenges.save(challenge); - }); + return tx(() -> { + challenges.lockAccountChallenge(globalAccount.getId()); + if (challenges.findByAccountId(globalAccount.getId()).isPresent()) { + throw new IllegalStateException("Global Account already has an email challenge"); + } + var now = LocalDateTime.now().withNano(0); + var challenge = new AccountEmailLoginChallenge(); + challenge.setAccountId(globalAccount.getId()); + challenge.setCodeHash(hash(otp)); + challenge.setExpiresAt(now.plusMinutes(5)); + challenge.setResendAvailableAt(now.plusMinutes(1)); + challenge.setCreatedAt(now); + challenge.setUpdatedAt(now); + return challenges.save(challenge); + }); } T tx(Supplier action) { diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java index a7b4c0613d..92ba004182 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java @@ -227,12 +227,9 @@ AccountJwtJwksConfigMapClient.CasObservation publish( */ void prepareInitialPrepublication() throws Exception { prepareInitialGeneration(); - assertThatThrownBy( - () -> - f.tx( - () -> - desired.readCurrentCommittedSigner( - BINDING, trust(), API_DIGEST, API_REVISION))) + assertThatThrownBy(() -> + f.tx(() -> + desired.readCurrentCommittedSigner(BINDING, trust(), API_DIGEST, API_REVISION))) .isInstanceOf(AccountJwtSignerDesiredStateRepository.QuarantinedStateException.class) .hasMessage("Account durable and published active signer fences disagree"); } @@ -243,45 +240,41 @@ private PreparedGeneration prepareInitialGeneration() throws Exception { authenticated .when(AccountJwtSignerMaterializerTlsInterceptor::authenticatedBinding) .thenReturn(materializerBinding()); - AccountControlUiSignerFixture.rpc( - out -> - materializer.enrollBootstrap( - EnrollBootstrapRequest.newBuilder().setSchemaVersion(1).build(), out)); + AccountControlUiSignerFixture.rpc(out -> + materializer.enrollBootstrap( + EnrollBootstrapRequest.newBuilder().setSchemaVersion(1).build(), out)); GetCurrentGenerationRequestResponse initial = - rpc( - out -> - materializer.getCurrentGenerationRequest( - GetCurrentGenerationRequestRequest.newBuilder().setSchemaVersion(1).build(), - out)); + rpc(out -> + materializer.getCurrentGenerationRequest( + GetCurrentGenerationRequestRequest.newBuilder().setSchemaVersion(1).build(), + out)); var request = f.tx(() -> desired.readCurrentGenerationRequest(BINDING, trust())); GetCurrentGenerationRequestResponse observed = - rpc( - out -> - materializer.recordSecretObservation( - RecordSecretObservationRequest.newBuilder() - .setSchemaVersion(1) - .setOperationId(initial.getOperationId()) - .setOperationDigest(initial.getOperationDigest()) - .setSecretUid(SECRET_UID) - .setObservedResourceVersion("12") - .build(), - out)); + rpc(out -> + materializer.recordSecretObservation( + RecordSecretObservationRequest.newBuilder() + .setSchemaVersion(1) + .setOperationId(initial.getOperationId()) + .setOperationDigest(initial.getOperationDigest()) + .setSecretUid(SECRET_UID) + .setObservedResourceVersion("12") + .build(), + out)); var pair = generateRsa3072(); var publicKey = publicJwk(request.targetKid(), (RSAPublicKey) pair.getPublic()); RecordGenerationResultResponse recorded = - rpc( - out -> - materializer.recordGenerationResult( - RecordGenerationResultRequest.newBuilder() - .setSchemaVersion(1) - .setOperationId(initial.getOperationId()) - .setGenerationRequestDigest(observed.getGenerationRequestDigest()) - .setSecretUid(SECRET_UID) - .setExpectedPriorResourceVersion("12") - .setObservedResourceVersion("13") - .setPublicJwkJson(publicKey.json()) - .build(), - out)); + rpc(out -> + materializer.recordGenerationResult( + RecordGenerationResultRequest.newBuilder() + .setSchemaVersion(1) + .setOperationId(initial.getOperationId()) + .setGenerationRequestDigest(observed.getGenerationRequestDigest()) + .setSecretUid(SECRET_UID) + .setExpectedPriorResourceVersion("12") + .setObservedResourceVersion("13") + .setPublicJwkJson(publicKey.json()) + .build(), + out)); var result = f.tx(() -> desired.readCurrentGenerationResult(BINDING, trust())); assertThat(recorded.getOperationId()).isEqualTo(result.operationId().toString()); assertThat(recorded.getOperationDigest()).isEqualTo(result.operationDigest()); @@ -379,18 +372,16 @@ void commit() throws Exception { () -> readiness.readCurrentExpectedPods(BINDING, trust(), issued, current)); for (var pod : pods) { var acceptance = testAuthenticatedAcceptance(issued, pod, now().getEpochSecond()); - f.tx( - () -> - readiness.recordPodAcceptance( - BINDING, trust(), issued, pod, acceptance, current)); + f.tx(() -> + readiness.recordPodAcceptance( + BINDING, trust(), issued, pod, acceptance, current)); } }); assertThat(delivered) .hasSize(8) - .allSatisfy( - entry -> - assertThat(entry.state()) - .isEqualTo(AccountJwtReadinessProbeRepository.ProbeState.VERIFIED)); + .allSatisfy(entry -> + assertThat(entry.state()) + .isEqualTo(AccountJwtReadinessProbeRepository.ProbeState.VERIFIED)); assertThat(f.dsl.fetchCount(DSL.table("account_jwt_readiness_pod_receipts"))).isEqualTo(12); assertThat( f.dsl.fetchCount( @@ -399,11 +390,9 @@ void commit() throws Exception { .isEqualTo(2); var prepared = coordinator.prepareCurrentPromotionOnce().orElseThrow(); GetCurrentPromotionRequestResponse dispatched = - rpc( - out -> - materializer.getCurrentPromotionRequest( - GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build(), - out)); + rpc(out -> + materializer.getCurrentPromotionRequest( + GetCurrentPromotionRequestRequest.newBuilder().setSchemaVersion(1).build(), out)); var promotion = f.tx(() -> desired.readPreparedGenerationForRecovery(BINDING, trust())).promotion(); assertThat(prepared.operationId()).isEqualTo(promotion.operationId()); @@ -419,27 +408,25 @@ void commit() throws Exception { Files.writeString( privateRoot.resolve("current.key"), privateBundleJson(request, result, pair)); RecordPrivatePromotionResultResponse committed = - rpc( - out -> - materializer.recordPrivatePromotionResult( - RecordPrivatePromotionResultRequest.newBuilder() - .setSchemaVersion(1) - .setPromotionOperationId(promotion.operationId().toString()) - .setPromotionRequestDigest(promotion.requestDigest()) - .setGenerationOperationId(result.operationId().toString()) - .setGenerationOperationDigest(result.operationDigest()) - .setSecretUid(SECRET_UID) - .setExpectedPriorResourceVersion( - promotion.expectedPrivateResourceVersion()) - .setObservedResourceVersion("14") - .setCurrent( - PromotionPublicKeyIdentity.newBuilder() - .setGeneration(result.targetGeneration()) - .setKid(result.targetKid()) - .setPublicKeyFingerprint(result.publicKeyFingerprint())) - .addResultingSlots("current") - .build(), - out)); + rpc(out -> + materializer.recordPrivatePromotionResult( + RecordPrivatePromotionResultRequest.newBuilder() + .setSchemaVersion(1) + .setPromotionOperationId(promotion.operationId().toString()) + .setPromotionRequestDigest(promotion.requestDigest()) + .setGenerationOperationId(result.operationId().toString()) + .setGenerationOperationDigest(result.operationDigest()) + .setSecretUid(SECRET_UID) + .setExpectedPriorResourceVersion(promotion.expectedPrivateResourceVersion()) + .setObservedResourceVersion("14") + .setCurrent( + PromotionPublicKeyIdentity.newBuilder() + .setGeneration(result.targetGeneration()) + .setKid(result.targetKid()) + .setPublicKeyFingerprint(result.publicKeyFingerprint())) + .addResultingSlots("current") + .build(), + out)); var durableCommit = f.tx(() -> desired.readCurrentCommittedSigner(BINDING, trust(), API_DIGEST, API_REVISION)) .orElseThrow(); @@ -764,28 +751,26 @@ private static Map inventoryValidatorMap( result.put( "profiles", validator.profiles().stream() - .map( - profile -> - Map.of("tokenProfile", profile.tokenProfile(), "audience", profile.audience())) + .map(profile -> + Map.of("tokenProfile", profile.tokenProfile(), "audience", profile.audience())) .toList()); result.put( "pods", validator.pods().stream() - .map( - pod -> - Map.ofEntries( - Map.entry("name", pod.name()), - Map.entry("uid", pod.uid()), - Map.entry("resourceVersion", pod.resourceVersion()), - Map.entry("ownerReplicaSetName", pod.ownerName()), - Map.entry("ownerReplicaSetUid", pod.ownerUid()), - Map.entry("podTemplateHash", pod.podTemplateHash()), - Map.entry("image", pod.image()), - Map.entry("verifierConfigSha256", pod.verifierConfigSha256()), - Map.entry("podIp", pod.podIp()), - Map.entry("exactPodEndpoint", pod.endpoint().toString()), - Map.entry("canonicalServiceUri", pod.receiverServiceUri()), - Map.entry("leafSpkiSha256", pod.leafSpkiSha256()))) + .map(pod -> + Map.ofEntries( + Map.entry("name", pod.name()), + Map.entry("uid", pod.uid()), + Map.entry("resourceVersion", pod.resourceVersion()), + Map.entry("ownerReplicaSetName", pod.ownerName()), + Map.entry("ownerReplicaSetUid", pod.ownerUid()), + Map.entry("podTemplateHash", pod.podTemplateHash()), + Map.entry("image", pod.image()), + Map.entry("verifierConfigSha256", pod.verifierConfigSha256()), + Map.entry("podIp", pod.podIp()), + Map.entry("exactPodEndpoint", pod.endpoint().toString()), + Map.entry("canonicalServiceUri", pod.receiverServiceUri()), + Map.entry("leafSpkiSha256", pod.leafSpkiSha256()))) .toList()); result.put("receiverServiceUri", serviceUri); result.put("receiverPort", receiverPort); diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountJwtPreparedPublicationPostgresFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountJwtPreparedPublicationPostgresFixture.java index b6d333caa3..ef43e86e20 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountJwtPreparedPublicationPostgresFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountJwtPreparedPublicationPostgresFixture.java @@ -432,28 +432,26 @@ private Map inventoryValidatorMap( result.put( "profiles", validator.profiles().stream() - .map( - profile -> - Map.of("tokenProfile", profile.tokenProfile(), "audience", profile.audience())) + .map(profile -> + Map.of("tokenProfile", profile.tokenProfile(), "audience", profile.audience())) .toList()); result.put( "pods", validator.pods().stream() - .map( - pod -> - Map.ofEntries( - Map.entry("name", pod.name()), - Map.entry("uid", pod.uid()), - Map.entry("resourceVersion", pod.resourceVersion()), - Map.entry("ownerReplicaSetName", pod.ownerName()), - Map.entry("ownerReplicaSetUid", pod.ownerUid()), - Map.entry("podTemplateHash", pod.podTemplateHash()), - Map.entry("image", pod.image()), - Map.entry("verifierConfigSha256", pod.verifierConfigSha256()), - Map.entry("podIp", pod.podIp()), - Map.entry("exactPodEndpoint", pod.endpoint().toString()), - Map.entry("canonicalServiceUri", pod.receiverServiceUri()), - Map.entry("leafSpkiSha256", pod.leafSpkiSha256()))) + .map(pod -> + Map.ofEntries( + Map.entry("name", pod.name()), + Map.entry("uid", pod.uid()), + Map.entry("resourceVersion", pod.resourceVersion()), + Map.entry("ownerReplicaSetName", pod.ownerName()), + Map.entry("ownerReplicaSetUid", pod.ownerUid()), + Map.entry("podTemplateHash", pod.podTemplateHash()), + Map.entry("image", pod.image()), + Map.entry("verifierConfigSha256", pod.verifierConfigSha256()), + Map.entry("podIp", pod.podIp()), + Map.entry("exactPodEndpoint", pod.endpoint().toString()), + Map.entry("canonicalServiceUri", pod.receiverServiceUri()), + Map.entry("leafSpkiSha256", pod.leafSpkiSha256()))) .toList()); result.put("receiverServiceUri", serviceUri); result.put("receiverPort", receiverPort); diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java index 7c64d3dc52..8bf06f599c 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountOriginalStartSessionAuthorizationProofFixture.java @@ -502,21 +502,18 @@ private static StartSessionReservationEvidenceClient stipulatedLoggingClaimClien any(UUID.class), anyLong(), eq(StartSessionReservationEvidenceClient.Purpose.ISSUE))) - .thenAnswer( - invocation -> { - var tuple = - invocation.getArgument(0, StartSessionPreAuthorizationReservationTuple.class); - UUID reservationOwnerId = invocation.getArgument(1, UUID.class); - long reservationClaimFence = invocation.getArgument(2, Long.class); - UUID claimOwnerId = invocation.getArgument(3, UUID.class); - long claimFence = invocation.getArgument(4, Long.class); - if (!reservationOwnerId.equals(claimOwnerId) || reservationClaimFence != claimFence) { - throw new IllegalArgumentException( - "Stipulated ISSUE claim must retain the original owner and fence"); - } - return stipulatedClaim( - tuple, reservationOwnerId, reservationClaimFence, Instant.now()); - }); + .thenAnswer(invocation -> { + var tuple = invocation.getArgument(0, StartSessionPreAuthorizationReservationTuple.class); + UUID reservationOwnerId = invocation.getArgument(1, UUID.class); + long reservationClaimFence = invocation.getArgument(2, Long.class); + UUID claimOwnerId = invocation.getArgument(3, UUID.class); + long claimFence = invocation.getArgument(4, Long.class); + if (!reservationOwnerId.equals(claimOwnerId) || reservationClaimFence != claimFence) { + throw new IllegalArgumentException( + "Stipulated ISSUE claim must retain the original owner and fence"); + } + return stipulatedClaim(tuple, reservationOwnerId, reservationClaimFence, Instant.now()); + }); return client; } diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedEntitlementFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedEntitlementFixture.java index 64c6e0907d..ce42543ee3 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedEntitlementFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedEntitlementFixture.java @@ -162,13 +162,12 @@ public AccountPlayerAdmissionSharedEntitlementFixture( outbox); // Missing rows alone are not evidence. Enroll the exact account-fenced absence baseline. demo = - sources.tx( - () -> { - sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); - generations.initialize(AuthorityScope.membership(login.accountId(), sources.tenant)); - members.prepareFreshCreatorAbsence(login.accountId(), sources.tenant); - return demos.provision(demoRequest, creation); - }); + sources.tx(() -> { + sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); + generations.initialize(AuthorityScope.membership(login.accountId(), sources.tenant)); + members.prepareFreshCreatorAbsence(login.accountId(), sources.tenant); + return demos.provision(demoRequest, creation); + }); var retainedScopes = new AccountConnectScopeRepository( @@ -316,55 +315,50 @@ public CanonicalJoinTerminalProof commitFirstJoin( assertThat(scope.tenantId()).isEqualTo(sources.tenant); requireCurrentTarget(issued, scope); var before = - joinTransaction.execute( - status -> { - sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); - operations.insertCanonicalIntent(requestId, scope, controlledCallerBinding); - return authority.readCurrentIssuerAccountSources( - GameSessionAccountDelegationProfile.ISSUER, login.accountId()); - }); + joinTransaction.execute(status -> { + sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); + operations.insertCanonicalIntent(requestId, scope, controlledCallerBinding); + return authority.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, login.accountId()); + }); // The second actual target read detects pre-commit drift, but is intentionally not a hold. requireCurrentTarget(issued, scope); CanonicalJoinTerminalProof proof = - joinTransaction.execute( - status -> { - sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); - requireLiveScope(scope); - var currentDemo = demos.revalidate(demo); - operations.bindCanonicalPolicyEvidence( - requestId, - scope, - controlledCallerBinding, - currentDemo.allowPublicJoin(), - currentDemo.entitlementVersion()); - var committed = - firstJoin.commitCanonicalFirstJoin(scope, requestId, controlledCallerBinding); - assertFirstJoinReceipt(scope, requestId, controlledCallerBinding, committed); - requireLiveScope(scope); - return committed; - }); + joinTransaction.execute(status -> { + sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); + requireLiveScope(scope); + var currentDemo = demos.revalidate(demo); + operations.bindCanonicalPolicyEvidence( + requestId, + scope, + controlledCallerBinding, + currentDemo.allowPublicJoin(), + currentDemo.entitlementVersion()); + var committed = + firstJoin.commitCanonicalFirstJoin(scope, requestId, controlledCallerBinding); + assertFirstJoinReceipt(scope, requestId, controlledCallerBinding, committed); + requireLiveScope(scope); + return committed; + }); Objects.requireNonNull(proof, "Committed first-JOIN receipt is required"); // Independent transaction proves durable terminal replay, not merely same-transaction reads. var replay = - joinTransaction.execute( - status -> { - sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); - requireLiveScope(scope); - assertThat( - operations.insertCanonicalIntent(requestId, scope, controlledCallerBinding)) - .isFalse(); - var repeated = - firstJoin.commitCanonicalFirstJoin(scope, requestId, controlledCallerBinding); - assertFirstJoinReceipt(scope, requestId, controlledCallerBinding, repeated); - return repeated; - }); + joinTransaction.execute(status -> { + sources.accounts.findByAccountUuidForUpdate(login.accountId()).orElseThrow(); + requireLiveScope(scope); + assertThat(operations.insertCanonicalIntent(requestId, scope, controlledCallerBinding)) + .isFalse(); + var repeated = + firstJoin.commitCanonicalFirstJoin(scope, requestId, controlledCallerBinding); + assertFirstJoinReceipt(scope, requestId, controlledCallerBinding, repeated); + return repeated; + }); assertThat(replay).isEqualTo(proof); assertThat(scopeReader.read(login.accountId(), scope.connectScopeId())).isEqualTo(scope); var after = - sources.tx( - () -> - authority.readCurrentIssuerAccountSources( - GameSessionAccountDelegationProfile.ISSUER, login.accountId())); + sources.tx(() -> + authority.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, login.accountId())); Objects.requireNonNull(before, "Original LOGIN authority sources are required"); assertThat(after.issuer()).isEqualTo(before.issuer()); assertThat(after.account()).isEqualTo(before.account()); @@ -508,20 +502,19 @@ public void assertNonAdmittingEvidence(RuntimePlayerAdmissionEntitlementEvidence /** Confirms actual absence enrollment and current tenant DEMO source without editing history. */ public void assertAbsentMembership() { - sources.tx( - () -> { - var current = snapshots.readCurrent(login.accountId(), sources.tenant); - assertThat(current.accountId()).isEqualTo(login.accountId().toString()); - assertThat(current.tenantId()).isEqualTo(sources.tenant.toString()); - assertThat(current.membershipExists()).isFalse(); - assertThat(current.membershipLifecycleState()).isEqualTo("MISSING"); - assertThat(current.gameplayAdmissionAllowed()).isFalse(); - assertThat(current.roles()).isEmpty(); - assertThat(current.membershipVersion()).containsEntry(sources.tenant.toString(), "1"); - assertThat(current.membershipAuthorityGeneration()).isEqualTo("1"); - assertThat(demos.revalidate(demo)).isEqualTo(demo); - return null; - }); + sources.tx(() -> { + var current = snapshots.readCurrent(login.accountId(), sources.tenant); + assertThat(current.accountId()).isEqualTo(login.accountId().toString()); + assertThat(current.tenantId()).isEqualTo(sources.tenant.toString()); + assertThat(current.membershipExists()).isFalse(); + assertThat(current.membershipLifecycleState()).isEqualTo("MISSING"); + assertThat(current.gameplayAdmissionAllowed()).isFalse(); + assertThat(current.roles()).isEmpty(); + assertThat(current.membershipVersion()).containsEntry(sources.tenant.toString(), "1"); + assertThat(current.membershipAuthorityGeneration()).isEqualTo("1"); + assertThat(demos.revalidate(demo)).isEqualTo(demo); + return null; + }); login.assertCreatorRemainsNonAdmitting(); verifyNoInteractions(unusedPaidRepository, unusedProvider, unusedBrowserSessions); } diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java index ad28fb69a8..d44c7f707f 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountPlayerAdmissionSharedOwnerFixture.java @@ -119,11 +119,10 @@ private AccountPlayerAdmissionSharedOwnerFixture( var outbox = new AccountAuthorityOutboxRepository(sources.dsl); authoritySources = new AccountAuthoritySourceEvidenceRepository(sources.dsl, generations, outbox); - sources.tx( - () -> { - authoritySources.initializeIssuerIfAbsent(GameSessionAccountDelegationProfile.ISSUER); - return null; - }); + sources.tx(() -> { + authoritySources.initializeIssuerIfAbsent(GameSessionAccountDelegationProfile.ISSUER); + return null; + }); var bundles = new AccountAuthEvidenceBundleRepository(sources.dsl, generations, outbox); var issuanceTarget = new AccountGameplayDelegationIssuanceRepository(sources.dsl, authoritySources, bundles); @@ -354,10 +353,9 @@ public void assertCommittedNonAdmittingLogin( Math.addExact( Math.multiplyExact(expiresAtEpochSecond, 1_000L), REGISTRY_CLEANUP_MILLIS)); var snapshot = - sources.tx( - () -> - authoritySources.readCurrentIssuerAccountSources( - GameSessionAccountDelegationProfile.ISSUER, accountId())); + sources.tx(() -> + authoritySources.readCurrentIssuerAccountSources( + GameSessionAccountDelegationProfile.ISSUER, accountId())); byte[][] expected = AccountGameplayDelegationAuthorityProjection.canonicalProjectionPair(snapshot); var observation = projection.observeCurrent(accountId()); @@ -390,52 +388,50 @@ public void assertCommittedNonAdmittingLogin( } assertCreatorRemainsNonAdmitting(); if (!accountId().equals(sources.account.getAccountUuid())) { - sources.tx( - () -> { - var fresh = - new FreshTenantIdentityAssociationRepository( - sources.dsl, creationEvidence().targetNamespace()); - var memberships = - new AccountTenantMembershipRepository( - sources.dsl, - sources.accounts, - fresh, - new AccountMembershipPairAuthorityRepository(sources.dsl)); - assertThat(memberships.findFreshMembership(accountId(), sources.tenant)).isEmpty(); - return null; - }); + sources.tx(() -> { + var fresh = + new FreshTenantIdentityAssociationRepository( + sources.dsl, creationEvidence().targetNamespace()); + var memberships = + new AccountTenantMembershipRepository( + sources.dsl, + sources.accounts, + fresh, + new AccountMembershipPairAuthorityRepository(sources.dsl)); + assertThat(memberships.findFreshMembership(accountId(), sources.tenant)).isEmpty(); + return null; + }); } } /** Real canonical membership and role readback, with the original source tuple unchanged. */ public void assertCreatorRemainsNonAdmitting() { UUID creatorId = sources.account.getAccountUuid(); - sources.tx( - () -> { - var fresh = - new FreshTenantIdentityAssociationRepository( - sources.dsl, creationEvidence().targetNamespace()); - assertThat(fresh.read(sources.tenant)).contains(creationEvidence()); - var pairs = new AccountMembershipPairAuthorityRepository(sources.dsl); - var memberships = - new AccountTenantMembershipRepository(sources.dsl, sources.accounts, fresh, pairs); - var membership = memberships.findFreshMembership(creatorId, sources.tenant).orElseThrow(); - assertThat(membership.getLifecycleState()).isEqualTo("ACTIVE"); - assertThat(membership.getAuthorityProvenance()).isEqualTo("TENANT_CREATION"); - assertThat(membership.isGameplayAdmissionAllowed()).isFalse(); - var pair = pairs.readPositive(creatorId, sources.tenant).orElseThrow(); - var roles = - new AccountTenantMembershipRoleSnapshotRepository(sources.dsl) - .findForCanonicalUpdate( - creatorId, - sources.tenant, - pair.provenance(), - membership.getId(), - membership.getMembershipVersion()) - .orElseThrow(); - assertThat(roles.roles()).containsExactly("tenantAdmin"); - return null; - }); + sources.tx(() -> { + var fresh = + new FreshTenantIdentityAssociationRepository( + sources.dsl, creationEvidence().targetNamespace()); + assertThat(fresh.read(sources.tenant)).contains(creationEvidence()); + var pairs = new AccountMembershipPairAuthorityRepository(sources.dsl); + var memberships = + new AccountTenantMembershipRepository(sources.dsl, sources.accounts, fresh, pairs); + var membership = memberships.findFreshMembership(creatorId, sources.tenant).orElseThrow(); + assertThat(membership.getLifecycleState()).isEqualTo("ACTIVE"); + assertThat(membership.getAuthorityProvenance()).isEqualTo("TENANT_CREATION"); + assertThat(membership.isGameplayAdmissionAllowed()).isFalse(); + var pair = pairs.readPositive(creatorId, sources.tenant).orElseThrow(); + var roles = + new AccountTenantMembershipRoleSnapshotRepository(sources.dsl) + .findForCanonicalUpdate( + creatorId, + sources.tenant, + pair.provenance(), + membership.getId(), + membership.getMembershipVersion()) + .orElseThrow(); + assertThat(roles.roles()).containsExactly("tenantAdmin"); + return null; + }); } private static Path writeResponseKeyring(Path temporary) throws IOException { diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/CurrentPrivatePlaytestReadTransportFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/CurrentPrivatePlaytestReadTransportFixture.java index 365226677f..6258594b62 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/CurrentPrivatePlaytestReadTransportFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/CurrentPrivatePlaytestReadTransportFixture.java @@ -49,10 +49,8 @@ public final class CurrentPrivatePlaytestReadTransportFixture implements AutoClo private final AtomicBoolean finiteDeadline = new AtomicBoolean(); private final AtomicReference> responder = - new AtomicReference<>( - request -> - CurrentPrivatePlaytestLifecycleReadGrpcCodec.toResponse( - request, Optional.empty())); + new AtomicReference<>(request -> + CurrentPrivatePlaytestLifecycleReadGrpcCodec.toResponse(request, Optional.empty())); public static LoopbackMtlsTestPki.Pki createPki(Path directory) throws Exception { return LoopbackMtlsTestPki.create( diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/PluginRuntimeRequestHistoryRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/PluginRuntimeRequestHistoryRepository.java index c4611dccee..bec76f3ec4 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/PluginRuntimeRequestHistoryRepository.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/PluginRuntimeRequestHistoryRepository.java @@ -52,14 +52,13 @@ public PluginRuntimeRequestHistory insertOrGet(PluginRuntimeRequestHistory entit .doNothing() .returningResult(PLUGIN_RUNTIME_REQUEST_HISTORY.fields()) .fetchOptional(this::toEntity) - .orElseGet( - () -> - find( - entity.getTenantId(), - entity.getGameInstanceId(), - entity.getPluginId(), - entity.getControlPlaneRequestId()) - .orElseThrow()); + .orElseGet(() -> + find( + entity.getTenantId(), + entity.getGameInstanceId(), + entity.getPluginId(), + entity.getControlPlaneRequestId()) + .orElseThrow()); if (!normalize(entity.getOperation()).equals(normalize(winner.getOperation())) || !normalize(entity.getRequestFingerprint()) .equals(normalize(winner.getRequestFingerprint()))) { diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptDefinitionRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptDefinitionRepository.java index 2682fcde36..af61a20cc4 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptDefinitionRepository.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptDefinitionRepository.java @@ -220,16 +220,14 @@ private SaveResult insertOrGetByIdentity(ScriptDefinition entity) { .otherwise(SCRIPTS.ROW_VERSION)) .where(SCRIPTS.BASE_VERSION_ID.isNotDistinctFrom(DSL.excluded(SCRIPTS.BASE_VERSION_ID))) .returningResult(returningFields) - .fetchOptional( - returned -> { - ScriptDefinition definition = toEntity(returned); - if (!sameIdentity(definition, entity)) { - throw new IllegalStateException( - "script definition identity upsert returned an unexpected row"); - } - return new SaveResult( - definition, Boolean.TRUE.equals(returned.get(INSERTED_ROW))); - }); + .fetchOptional(returned -> { + ScriptDefinition definition = toEntity(returned); + if (!sameIdentity(definition, entity)) { + throw new IllegalStateException( + "script definition identity upsert returned an unexpected row"); + } + return new SaveResult(definition, Boolean.TRUE.equals(returned.get(INSERTED_ROW))); + }); if (saved.isPresent()) { return saved.get(); } diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptEventAuditRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptEventAuditRepository.java index 53d5f74b82..ab0c72c610 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptEventAuditRepository.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptEventAuditRepository.java @@ -277,10 +277,9 @@ private Optional insertHandlerIdentity(ScriptEventA .doUpdate() .set(SCRIPT_EVENT_AUDIT.ID, SCRIPT_EVENT_AUDIT.ID) .returningResult(returningFields) - .fetchOptional( - returned -> - new HandlerIdentityInsertResult( - toEntity(returned), Boolean.TRUE.equals(returned.get(INSERTED_ROW)))); + .fetchOptional(returned -> + new HandlerIdentityInsertResult( + toEntity(returned), Boolean.TRUE.equals(returned.get(INSERTED_ROW)))); } private record HandlerIdentityInsertResult(ScriptEventAudit audit, boolean inserted) {} @@ -412,10 +411,9 @@ public ScriptEventAudit save(ScriptEventAudit entity) { requireCoherentPluginFence(entity); ScriptEventAudit persisted = findById(entity.getId()) - .orElseThrow( - () -> - AutomationScriptingJooqRepositorySupport.staleWrite( - "script_event_audit", entity.getId())); + .orElseThrow(() -> + AutomationScriptingJooqRepositorySupport.staleWrite( + "script_event_audit", entity.getId())); requireMatchingImmutableIdentity(entity, persisted); int nextRowVersion = entity.getRowVersion() + 1; int updated = diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptEventIngressAuditRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptEventIngressAuditRepository.java index 3a90a62af5..4de1070067 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptEventIngressAuditRepository.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptEventIngressAuditRepository.java @@ -291,17 +291,16 @@ private Optional insertEventIdentity( .doUpdate() .set(SCRIPT_EVENT_INGRESS_AUDIT.ID, SCRIPT_EVENT_INGRESS_AUDIT.ID) .returningResult(returningFields); - return insert.fetchOptional( - returned -> { - ScriptEventIngressAudit audit = toEntity(returned); - boolean inserted = Boolean.TRUE.equals(returned.get(INSERTED_ROW)); - if (!inserted) { - requireMatchingPinOwnerEvidence( - normalizedRequestId, audit.getScriptPinControlPlaneRequestId()); - requireMatchingClaimPluginFence(entity, audit); - } - return new IdempotentInsertResult(audit, inserted); - }); + return insert.fetchOptional(returned -> { + ScriptEventIngressAudit audit = toEntity(returned); + boolean inserted = Boolean.TRUE.equals(returned.get(INSERTED_ROW)); + if (!inserted) { + requireMatchingPinOwnerEvidence( + normalizedRequestId, audit.getScriptPinControlPlaneRequestId()); + requireMatchingClaimPluginFence(entity, audit); + } + return new IdempotentInsertResult(audit, inserted); + }); } @SuppressFBWarnings( diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepository.java index 47739b7410..f393b22f5f 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepository.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepository.java @@ -63,12 +63,11 @@ public long deleteExpiredRetentionEvidence(Instant safeWatermark, Instant now) { .where(candidateEligibility) .orderBy(candidates.EVENT_ID.asc()) .limit(RETENTION_DELETE_BATCH_SIZE) - .fetch( - record -> - new RetentionCandidate( - record.get(candidates.ID), - record.get(candidates.TENANT_ID), - record.get(candidates.WORK_ITEM_ID))); + .fetch(record -> + new RetentionCandidate( + record.get(candidates.ID), + record.get(candidates.TENANT_ID), + record.get(candidates.WORK_ITEM_ID))); if (selected.isEmpty()) { return 0L; } @@ -82,10 +81,9 @@ record -> .where(selectedParentBundleCondition(selected)) .orderBy(SCRIPT_WORK_ITEMS.TENANT_ID.asc(), SCRIPT_WORK_ITEMS.ID.asc()) .forUpdate() - .fetch( - record -> - new RetentionBundle( - record.get(SCRIPT_WORK_ITEMS.TENANT_ID), record.get(SCRIPT_WORK_ITEMS.ID))); + .fetch(record -> + new RetentionBundle( + record.get(SCRIPT_WORK_ITEMS.TENANT_ID), record.get(SCRIPT_WORK_ITEMS.ID))); if (existingParents.isEmpty()) { return 0L; } @@ -116,12 +114,11 @@ record -> .and( retentionEligibility( recheckCandidates, recheckSiblings, cutoff, current, true))) - .fetch( - record -> - new RetentionCandidate( - record.get(recheckCandidates.ID), - record.get(recheckCandidates.TENANT_ID), - record.get(recheckCandidates.WORK_ITEM_ID))); + .fetch(record -> + new RetentionCandidate( + record.get(recheckCandidates.ID), + record.get(recheckCandidates.TENANT_ID), + record.get(recheckCandidates.WORK_ITEM_ID))); if (eligible.isEmpty()) { return 0L; } @@ -435,10 +432,9 @@ public ScriptHandoffEvent save(ScriptHandoffEvent entity) { } ScriptHandoffEvent existing = findByEventId(entity.getEventId()) - .orElseThrow( - () -> - new IllegalStateException( - "handoff event conflict did not yield a persisted row")); + .orElseThrow(() -> + new IllegalStateException( + "handoff event conflict did not yield a persisted row")); if (!immutableIdentityMatches(existing, entity)) { throw identityConflict(existing, entity); } diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepository.java index b911abddfe..1bab6bb58e 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepository.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepository.java @@ -334,11 +334,10 @@ public List findDistinctInstancePatchPairs( SCRIPT_WORK_ITEMS.GAME_INSTANCE_ID, SCRIPT_WORK_ITEMS.SCRIPT_PATCH_VERSION) .from(SCRIPT_WORK_ITEMS) .where(condition) - .fetch( - record -> - new ScriptPatchInstanceProjectionView( - record.get(SCRIPT_WORK_ITEMS.GAME_INSTANCE_ID), - record.get(SCRIPT_WORK_ITEMS.SCRIPT_PATCH_VERSION))); + .fetch(record -> + new ScriptPatchInstanceProjectionView( + record.get(SCRIPT_WORK_ITEMS.GAME_INSTANCE_ID), + record.get(SCRIPT_WORK_ITEMS.SCRIPT_PATCH_VERSION))); } public List findByStatusOrderByCreatedAtAscIdAsc( @@ -744,10 +743,8 @@ public ScriptWorkItem save(ScriptWorkItem entity) { } entity.setRowVersion(nextRowVersion); return findById(entity.getId()) - .orElseThrow( - () -> - new IllegalStateException( - "Saved script_work_item missing for id=" + entity.getId())); + .orElseThrow(() -> + new IllegalStateException("Saved script_work_item missing for id=" + entity.getId())); } public ScriptWorkItem saveAndFlush(ScriptWorkItem entity) { @@ -827,10 +824,9 @@ private Optional insertTriggerIdentity(ScriptWorkIt .doUpdate() .set(SCRIPT_WORK_ITEMS.ID, SCRIPT_WORK_ITEMS.ID) .returningResult(returningFields) - .fetchOptional( - returned -> - new TriggerIdentityInsertResult( - toEntity(returned), Boolean.TRUE.equals(returned.get(INSERTED_ROW)))); + .fetchOptional(returned -> + new TriggerIdentityInsertResult( + toEntity(returned), Boolean.TRUE.equals(returned.get(INSERTED_ROW)))); } private record TriggerIdentityInsertResult(ScriptWorkItem workItem, boolean inserted) {} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogRepository.java index d0617e40a7..68669ded25 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogRepository.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/runtimecatalog/AutomationRuntimeFamilyCatalogRepository.java @@ -46,29 +46,28 @@ public AutomationRuntimeFamilyCatalogRepository( public Evidence read(Request request) { requireIndependent(request); byte[] committed = - capture.execute( - status -> { - AutomationRuntimeFamilyCatalog catalog = currentCatalog(); - byte[] requestBytes = AutomationRuntimeFamilyCatalogCodec.requestBytes(request); - var proposed = new Evidence(request, UUID.randomUUID(), catalog); - byte[] evidenceBytes = AutomationRuntimeFamilyCatalogCodec.evidenceBytes(proposed); - dsl.execute( - "INSERT INTO " - + table("automation_runtime_family_catalog_snapshot") - + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," - + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)" - + " ON CONFLICT (read_request_id) DO NOTHING", - request.readRequestId(), - request.targetNamespace(), - requestBytes, - AutomationRuntimeFamilyCatalog.sha256(requestBytes), - proposed.snapshotId(), - catalog.catalogEpoch(), - catalog.digest(), - evidenceBytes, - proposed.digest()); - return retained(request, catalog); - }); + capture.execute(status -> { + AutomationRuntimeFamilyCatalog catalog = currentCatalog(); + byte[] requestBytes = AutomationRuntimeFamilyCatalogCodec.requestBytes(request); + var proposed = new Evidence(request, UUID.randomUUID(), catalog); + byte[] evidenceBytes = AutomationRuntimeFamilyCatalogCodec.evidenceBytes(proposed); + dsl.execute( + "INSERT INTO " + + table("automation_runtime_family_catalog_snapshot") + + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," + + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)" + + " ON CONFLICT (read_request_id) DO NOTHING", + request.readRequestId(), + request.targetNamespace(), + requestBytes, + AutomationRuntimeFamilyCatalog.sha256(requestBytes), + proposed.snapshotId(), + catalog.catalogEpoch(), + catalog.digest(), + evidenceBytes, + proposed.digest()); + return retained(request, catalog); + }); Evidence result = readExact(request); if (!Arrays.equals(committed, AutomationRuntimeFamilyCatalogCodec.evidenceBytes(result))) { throw new CatalogConflictException("Committed Automation catalog readback changed"); @@ -79,10 +78,9 @@ public Evidence read(Request request) { /** Missing, stale, contradictory or corrupt evidence refuses; none is an empty-owner result. */ public Evidence readExact(Request request) { requireIndependent(request); - return readback.execute( - status -> - AutomationRuntimeFamilyCatalogCodec.evidenceFromStored( - retained(request, currentCatalog()))); + return readback.execute(status -> + AutomationRuntimeFamilyCatalogCodec.evidenceFromStored( + retained(request, currentCatalog()))); } private AutomationRuntimeFamilyCatalog currentCatalog() { diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationAdmissionStateServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationAdmissionStateServiceImpl.java index c0086957e8..fc7d866150 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationAdmissionStateServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationAdmissionStateServiceImpl.java @@ -139,16 +139,15 @@ private AutomationAdmissionState findOrCreate( String normalizedRegionId = normalize(regionId); return repository .findByTenantIdAndGameInstanceIdAndRegionId(tenantId, gameInstanceId, normalizedRegionId) - .orElseGet( - () -> { - AutomationAdmissionState state = new AutomationAdmissionState(); - state.setTenantId(tenantId); - state.setGameInstanceId(gameInstanceId); - state.setRegionId(normalizedRegionId); - state.setMode(MODE_NORMAL); - state.setAdmissionEpoch(1L); - return repository.save(state); - }); + .orElseGet(() -> { + AutomationAdmissionState state = new AutomationAdmissionState(); + state.setTenantId(tenantId); + state.setGameInstanceId(gameInstanceId); + state.setRegionId(normalizedRegionId); + state.setMode(MODE_NORMAL); + state.setAdmissionEpoch(1L); + return repository.save(state); + }); } private static AdmissionStateSummary toSummary(AutomationAdmissionState state) { diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationEventControlPlaneService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationEventControlPlaneService.java index dc5a809e7f..ffa027fa05 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationEventControlPlaneService.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationEventControlPlaneService.java @@ -38,10 +38,9 @@ ListScriptEventDefinitionsResponse listScriptEventDefinitions( ListScriptEventDefinitionsResponse.Builder response = ListScriptEventDefinitionsResponse.newBuilder(); eventRegistryService.listDefinitions().stream() - .filter( - definition -> - request.getOwnerService().isBlank() - || definition.ownerService().equals(request.getOwnerService())) + .filter(definition -> + request.getOwnerService().isBlank() + || definition.ownerService().equals(request.getOwnerService())) .map(AutomationEventControlPlaneService::toProto) .forEach(response::addDefinitions); return response.build(); diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java index ca7a9412d6..3666d91711 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java @@ -122,12 +122,11 @@ ListScriptPatchStatusesResponse listScriptPatchStatuses(ListScriptPatchStatusesR request.getChangedAfterMs(), request.getChangedBeforeMs()) .stream() - .map( - summary -> - toProto( - summary, - workflowMetadataResolver.resolve( - request.getTenantId(), summary.scriptPatchVersion()))) + .map(summary -> + toProto( + summary, + workflowMetadataResolver.resolve( + request.getTenantId(), summary.scriptPatchVersion()))) .forEach(response::addPatches); return response.build(); } @@ -400,12 +399,11 @@ ListScriptHandoffEventsResponse listScriptHandoffEvents(ListScriptHandoffEventsR loadGameplayCommandStatuses(request.getTenantId(), summaries); ListScriptHandoffEventsResponse.Builder response = ListScriptHandoffEventsResponse.newBuilder(); summaries.stream() - .map( - summary -> - toProto( - summary, - currentScopes.get(summary.targetGameInstanceId()), - commandStatuses.get(summary.gameSessionCommandId()))) + .map(summary -> + toProto( + summary, + currentScopes.get(summary.targetGameInstanceId()), + commandStatuses.get(summary.gameSessionCommandId()))) .forEach(response::addEvents); return response.build(); } @@ -452,15 +450,14 @@ ReplayDeadLetteredWorkItemsResponse replayDeadLetteredWorkItems( .setRejectedCount(result.rejectedCount()) .setRequestFingerprint(result.requestFingerprint()); result.results().stream() - .map( - item -> - ReplayDeadLetteredWorkItemResult.newBuilder() - .setWorkItemId(item.workItemId()) - .setOutcome(item.outcome()) - .setRejectionReason(item.rejectionReason()) - .setFailureReason(item.failureReason()) - .setFailureGeneration(item.failureGeneration()) - .build()) + .map(item -> + ReplayDeadLetteredWorkItemResult.newBuilder() + .setWorkItemId(item.workItemId()) + .setOutcome(item.outcome()) + .setRejectionReason(item.rejectionReason()) + .setFailureReason(item.failureReason()) + .setFailureGeneration(item.failureGeneration()) + .build()) .forEach(response::addResults); return response.build(); } diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcService.java index 081120f25d..e12728443b 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcService.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcService.java @@ -324,17 +324,16 @@ public void updateScript( request.getBaseVersionId(), request.getDefinition(), request.getEventBindingsList().stream() - .map( - binding -> - new ScriptDefinitionDto.EventBindingDto( - binding.getEventType(), - binding.getEventSchemaVersion(), - binding.getTargetScopeType(), - binding.getTargetScopeId(), - binding.getPriority(), - binding.getPriorityTag(), - binding.getRequiresExclusiveEvent(), - binding.getBindingId())) + .map(binding -> + new ScriptDefinitionDto.EventBindingDto( + binding.getEventType(), + binding.getEventSchemaVersion(), + binding.getTargetScopeType(), + binding.getTargetScopeId(), + binding.getPriority(), + binding.getPriorityTag(), + binding.getRequiresExclusiveEvent(), + binding.getBindingId())) .toList()); scriptService.updateScript(dto); UpdateScriptResponse resp = UpdateScriptResponse.newBuilder().setSuccess(true).build(); diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/BuiltInScriptEventRegistryService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/BuiltInScriptEventRegistryService.java index 5ee0d0ea95..a2827d9fdd 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/BuiltInScriptEventRegistryService.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/BuiltInScriptEventRegistryService.java @@ -140,14 +140,13 @@ private static List stringListField(Map raw, String key) { throw new IllegalStateException("Built-in event registry field '" + key + "' is required"); } return listValue.stream() - .map( - element -> { - if (!(element instanceof String stringValue) || stringValue.isBlank()) { - throw new IllegalStateException( - "Built-in event registry field '" + key + "' must contain strings"); - } - return stringValue; - }) + .map(element -> { + if (!(element instanceof String stringValue) || stringValue.isBlank()) { + throw new IllegalStateException( + "Built-in event registry field '" + key + "' must contain strings"); + } + return stringValue; + }) .toList(); } } diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/FactionServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/FactionServiceImpl.java index 04d13ee628..12fc3ed93f 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/FactionServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/FactionServiceImpl.java @@ -38,15 +38,14 @@ public int adjustReputation( standingRepository .findByTenantIdAndCharacterIdAndPlayableStateKeyAndFaction_Id( tenantId, characterId, playableStateKey, factionId) - .orElseGet( - () -> { - FactionStanding fs = new FactionStanding(); - fs.setTenantId(tenantId); - fs.setCharacterId(characterId); - fs.setPlayableStateKey(playableStateKey); - fs.setFaction(faction); - return fs; - }); + .orElseGet(() -> { + FactionStanding fs = new FactionStanding(); + fs.setTenantId(tenantId); + fs.setCharacterId(characterId); + fs.setPlayableStateKey(playableStateKey); + fs.setFaction(faction); + return fs; + }); standing.setReputation(standing.getReputation() + delta); standingRepository.save(standing); return standing.getReputation(); diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/NpcAggressionServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/NpcAggressionServiceImpl.java index cfe97939d6..61d0274815 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/NpcAggressionServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/NpcAggressionServiceImpl.java @@ -23,14 +23,13 @@ public void setAggressionState(Long tenantId, Long npcId, AggressionState state) NpcMemory mem = memoryRepository .findByNpcIdAndKeyAndTenantId(npcId, AGGRESSION_KEY, tenantId) - .orElseGet( - () -> { - NpcMemory newMem = new NpcMemory(); - newMem.setNpcId(npcId); - newMem.setKey(AGGRESSION_KEY); - newMem.setTenantId(tenantId); - return newMem; - }); + .orElseGet(() -> { + NpcMemory newMem = new NpcMemory(); + newMem.setNpcId(npcId); + newMem.setKey(AGGRESSION_KEY); + newMem.setTenantId(tenantId); + return newMem; + }); mem.setValue(state.name()); memoryRepository.save(mem); } diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImpl.java index 7d415205aa..ec4e2a7696 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImpl.java @@ -85,9 +85,8 @@ public void validateActivation( List targetBindings = allBindings.stream() - .filter( - binding -> - binding.pluginOwner().matches(pluginId, pluginVersionId) && binding.enabled()) + .filter(binding -> + binding.pluginOwner().matches(pluginId, pluginVersionId) && binding.enabled()) .toList(); if (targetBindings.isEmpty()) { return; @@ -105,11 +104,10 @@ public void validateActivation( List existingBindings = allBindings.stream() .filter(ResolvedBinding::enabled) - .filter( - binding -> - !binding.pluginOwner().matches(pluginId, pluginVersionId) - && participatesInResolvedHandlerSet( - binding.pluginOwner(), activePluginVersions)) + .filter(binding -> + !binding.pluginOwner().matches(pluginId, pluginVersionId) + && participatesInResolvedHandlerSet( + binding.pluginOwner(), activePluginVersions)) .toList(); validateCommandAliases(targetBindings); diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImpl.java index e0255ffd99..7bb037e63c 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImpl.java @@ -171,30 +171,29 @@ public Optional getLocalLifecycleStatus( requireText(pluginId, "plugin_id"); return repository .findByTenantIdAndGameInstanceIdAndPluginId(tenantId, gameInstanceId, pluginId) - .map( - state -> { - try { - return toStatus(state, Map.of()); - } catch (IllegalArgumentException ex) { - return new PluginRuntimeStatus( - normalize(state.getActivePluginVersionId()), - normalize(state.getPendingPluginVersionId()), - normalize(state.getRuntimeRegionId()), - zeroIfNull(state.getRuntimeRegionEpoch()), - PluginState.PLUGIN_STATE_UNSPECIFIED, - ScriptHandoffOutcomeSupport.REASON_AUTHORITY_UNAVAILABLE, - state.getLastChangedAt() == null ? 0L : state.getLastChangedAt().toEpochMilli(), - normalize(state.getControlPlaneRequestId()), - normalize(state.getActorPrincipal()), - state.getLastPolicyCheckedAt() == null - ? 0L - : state.getLastPolicyCheckedAt().toEpochMilli(), - null, - null, - state.getPluginActivationEpoch(), - state.getLifecycleRevision()); - } - }); + .map(state -> { + try { + return toStatus(state, Map.of()); + } catch (IllegalArgumentException ex) { + return new PluginRuntimeStatus( + normalize(state.getActivePluginVersionId()), + normalize(state.getPendingPluginVersionId()), + normalize(state.getRuntimeRegionId()), + zeroIfNull(state.getRuntimeRegionEpoch()), + PluginState.PLUGIN_STATE_UNSPECIFIED, + ScriptHandoffOutcomeSupport.REASON_AUTHORITY_UNAVAILABLE, + state.getLastChangedAt() == null ? 0L : state.getLastChangedAt().toEpochMilli(), + normalize(state.getControlPlaneRequestId()), + normalize(state.getActorPrincipal()), + state.getLastPolicyCheckedAt() == null + ? 0L + : state.getLastPolicyCheckedAt().toEpochMilli(), + null, + null, + state.getPluginActivationEpoch(), + state.getLifecycleRevision()); + } + }); } @Override @@ -416,10 +415,9 @@ private void requireAbilitySchemaMatch( .filter( digest -> PARTICIPANT_KEY_AUTOMATION_SCRIPTING.equals(digest.getParticipantKey())) .findFirst() - .orElseThrow( - () -> - new IllegalArgumentException( - "PLUGIN_ABILITY_SCHEMA_MISMATCH: runtime ability schema digest is unavailable")); + .orElseThrow(() -> + new IllegalArgumentException( + "PLUGIN_ABILITY_SCHEMA_MISMATCH: runtime ability schema digest is unavailable")); if (!automationDigest.getContentDigest().equals(pluginAbilitySchemaDigest)) { throw new IllegalArgumentException( "PLUGIN_ABILITY_SCHEMA_MISMATCH: plugin ability schema digest does not match runtime version"); @@ -446,29 +444,27 @@ public PolicyReconciliationResult reconcileActivePluginPolicy(int maxItems) { PluginState.PLUGIN_STATE_ENABLED.name(), "", PageRequest.of(0, limit)); List policyDecisions = activeStates.stream() - .map( - state -> - new PolicyDecision( - state, - disableReasonForCurrentPolicy( - gameDesignControlPlaneClient.getPublishedPluginVersion( - state.getTenantId(), - state.getPluginId(), - normalize(state.getActivePluginVersionId()))))) + .map(state -> + new PolicyDecision( + state, + disableReasonForCurrentPolicy( + gameDesignControlPlaneClient.getPublishedPluginVersion( + state.getTenantId(), + state.getPluginId(), + normalize(state.getActivePluginVersionId()))))) .toList(); List decisions = policyDecisions.stream() - .map( - decision -> { - GetGameInstanceRuntimeStateResponse runtime = - decision.disableReason().isEmpty() - ? null - : gameSessionControlPlaneClient.getGameInstanceRuntimeState( - decision.snapshot().getTenantId(), - decision.snapshot().getGameInstanceId(), - normalize(decision.snapshot().getRuntimeRegionId())); - return new PolicyDecision(decision.snapshot(), decision.disableReason(), runtime); - }) + .map(decision -> { + GetGameInstanceRuntimeStateResponse runtime = + decision.disableReason().isEmpty() + ? null + : gameSessionControlPlaneClient.getGameInstanceRuntimeState( + decision.snapshot().getTenantId(), + decision.snapshot().getGameInstanceId(), + normalize(decision.snapshot().getRuntimeRegionId())); + return new PolicyDecision(decision.snapshot(), decision.disableReason(), runtime); + }) .toList(); Instant now = Instant.now(); int disabledCount = 0; @@ -555,17 +551,16 @@ private Optional violationForCurrentPolicy(PluginRuntimeS state.getTenantId(), state.getPluginId(), activePluginVersionId); PluginPublicationLink publicationLink = toPublicationLink(activePluginVersionId, publication); return disableReasonForCurrentPolicy(publication) - .map( - reason -> - new PluginPolicyViolation( - state.getGameInstanceId(), - normalize(state.getRuntimeRegionId()), - zeroIfNull(state.getRuntimeRegionEpoch()), - state.getPluginId(), - activePluginVersionId, - reason, - state.getLastChangedAt().toEpochMilli(), - publicationLink)); + .map(reason -> + new PluginPolicyViolation( + state.getGameInstanceId(), + normalize(state.getRuntimeRegionId()), + zeroIfNull(state.getRuntimeRegionEpoch()), + state.getPluginId(), + activePluginVersionId, + reason, + state.getLastChangedAt().toEpochMilli(), + publicationLink)); } private Optional disableReasonForCurrentPolicy( @@ -714,10 +709,8 @@ private boolean transition( repository .findByTenantIdAndGameInstanceIdAndPluginId( command.tenantId(), command.gameInstanceId(), command.pluginId()) - .orElseGet( - () -> - newState( - command.tenantId(), command.gameInstanceId(), command.pluginId(), now)); + .orElseGet(() -> + newState(command.tenantId(), command.gameInstanceId(), command.pluginId(), now)); String previous = normalize(state.getActivePluginVersionId()); if (requestId.equals(normalize(state.getControlPlaneRequestId()))) { throw new IllegalArgumentException( diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptDesignDigestServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptDesignDigestServiceImpl.java index 6dacdd4cc4..eda12bba10 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptDesignDigestServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptDesignDigestServiceImpl.java @@ -57,15 +57,13 @@ public ScriptDraftDesignDigest getDraftDesignDigestForVersion(String tenantId, S long tenantKey = RequestIdValidation.requirePositiveLong(tenantId, "tenantId"); List> scripts = repository.findByTenantIdOrderByNameAscScriptVersionAsc(tenantKey).stream() - .map( - script -> - canonicalMap( - Map.of( - "name", normalize(script.getName()), - "version", normalize(script.getScriptVersion()), - "baseVersionId", - Objects.requireNonNullElse(script.getBaseVersionId(), 0L), - "definition", normalize(script.getDefinition())))) + .map(script -> + canonicalMap( + Map.of( + "name", normalize(script.getName()), + "version", normalize(script.getScriptVersion()), + "baseVersionId", Objects.requireNonNullElse(script.getBaseVersionId(), 0L), + "definition", normalize(script.getDefinition())))) .toList(); List> bindings = bindingRepository diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java index af99f44bb5..7cd90cd4ec 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImpl.java @@ -761,11 +761,10 @@ private boolean hasUsablePluginFence( return true; } return resolvePluginStatus(authority, request, handler.pluginOwner().pluginId()) - .filter( - status -> - status.pluginState() == PluginState.PLUGIN_STATE_ENABLED - && normalize(handler.pluginOwner().pluginVersionId()) - .equals(normalize(status.activePluginVersionId()))) + .filter(status -> + status.pluginState() == PluginState.PLUGIN_STATE_ENABLED + && normalize(handler.pluginOwner().pluginVersionId()) + .equals(normalize(status.activePluginVersionId()))) .filter(status -> status.pluginActivationEpoch() > 0 && status.lifecycleRevision() > 0) .isPresent(); } @@ -848,10 +847,9 @@ private TriggerAdmission admissionWithHandlers( request.getEventType(), schemaVersion) .stream() - .filter( - binding -> - request.getScriptId().isBlank() - || binding.getScriptId().equals(request.getScriptId())) + .filter(binding -> + request.getScriptId().isBlank() + || binding.getScriptId().equals(request.getScriptId())) .filter(binding -> matchesScope(binding, request, payload)) .toList(); PluginOwnerResolution ownerResolution = @@ -880,22 +878,18 @@ private TriggerAdmission admissionWithHandlers( request.getRegionEpoch()); List handlers = scopedBindings.stream() - .map( - binding -> - new ResolvedHandler(binding, ownersByScriptId.get(binding.getScriptId()))) - .filter( - handler -> - participatesInResolvedHandlerSet(handler.pluginOwner(), activePluginVersions)) - .filter( - handler -> - !filterByRequestPluginOwnership - || hasMatchingPluginOwner(handler.pluginOwner(), request)) + .map(binding -> + new ResolvedHandler(binding, ownersByScriptId.get(binding.getScriptId()))) + .filter(handler -> + participatesInResolvedHandlerSet(handler.pluginOwner(), activePluginVersions)) + .filter(handler -> + !filterByRequestPluginOwnership + || hasMatchingPluginOwner(handler.pluginOwner(), request)) .toList(); if (handlers.stream() - .anyMatch( - handler -> - handler.pluginOwner() != null - && normalize(handler.binding().getBindingId()).isBlank())) { + .anyMatch(handler -> + handler.pluginOwner() != null + && normalize(handler.binding().getBindingId()).isBlank())) { return new TriggerAdmission( false, OUTCOME_VERSION_UNAVAILABLE, "plugin_binding_unresolved", 0); } @@ -910,18 +904,17 @@ && normalize(handler.binding().getBindingId()).isBlank())) { return new TriggerAdmission( false, OUTCOME_VERSION_UNAVAILABLE, "plugin_binding_unresolved", 0); } - handlers.forEach( - handler -> - admitHandler( - request, - schemaVersion, - definition, - handler, - sourceService, - admissionState, - scriptPinEpoch, - claim, - authority)); + handlers.forEach(handler -> + admitHandler( + request, + schemaVersion, + definition, + handler, + sourceService, + admissionState, + scriptPinEpoch, + claim, + authority)); String reason = handlers.isEmpty() ? "admitted_no_handlers" : "admitted_handlers_resolved"; return new TriggerAdmission(true, OUTCOME_ADMITTED, reason, handlers.size()); } diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java index 33f68f24b3..f64b14c311 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImpl.java @@ -310,15 +310,14 @@ public HandoffResult handoff(ScriptWorkItem workItem, EmittedCommand command) { if (isReconciliationRequired(downstreamResult)) { if (!normalize(downstreamResult.commandId()).isBlank()) { try { - return executeResponseTransaction( - () -> - persistReconciliationRequiredCommandId( - workItem, - command, - dispatchId, - downstreamResult, - preparation.intentId(), - preparation.intentRowVersion())); + return executeResponseTransaction(() -> + persistReconciliationRequiredCommandId( + workItem, + command, + dispatchId, + downstreamResult, + preparation.intentId(), + preparation.intentRowVersion())); } catch (RuntimeException ex) { LOGGER.warn( "Unable to persist retained Game Session command identity for workItemId={} commandOrdinal={}; retaining in-flight evidence", @@ -330,15 +329,14 @@ public HandoffResult handoff(ScriptWorkItem workItem, EmittedCommand command) { return downstreamResult; } try { - return executeResponseTransaction( - () -> - persistDownstreamResponse( - workItem, - command, - dispatchId, - downstreamResult, - preparation.intentId(), - preparation.intentRowVersion())); + return executeResponseTransaction(() -> + persistDownstreamResponse( + workItem, + command, + dispatchId, + downstreamResult, + preparation.intentId(), + preparation.intentRowVersion())); } catch (RuntimeException ex) { LOGGER.warn( "Unable to persist script handoff response for workItemId={} commandOrdinal={}; retaining in-flight evidence", @@ -391,11 +389,10 @@ private void executeIntentBoundary(Runnable action) { action.run(); return; } - handoffTransactionTemplate.execute( - status -> { - action.run(); - return null; - }); + handoffTransactionTemplate.execute(status -> { + action.run(); + return null; + }); } private HandoffResult executeRpcWithoutLocalTransaction(RpcCall rpcCall) { @@ -1225,40 +1222,37 @@ private HandoffResult reconcileFailedIntentPreparation( String dispatchId, WorkItemIntentState intentState) { try { - return executeRpcWithoutLocalTransaction( - () -> { - Optional persistedWorkItem = - workItemRepository.findById(workItem.getId()); - Optional persistedIntent = - handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal( - workItem.getTenantId(), workItem.getId(), command.ordinal()); - if (persistedIntent.isPresent()) { - ScriptHandoffEvent intent = persistedIntent.orElseThrow(); - ScriptWorkItem identitySource = persistedWorkItem.orElse(workItem); - if (!handoffIdentityMatches(intent, identitySource, command, dispatchId)) { - return reconciliationRequiredResult( - "persisted handoff intent identity does not match request; reconciliation is required"); - } - if (!isAcceptedHandoff(intent) && isHandoffInFlightIntent(intent)) { - return retainedInFlightHandoffResult(intent); - } - if (!isDefinitiveNonAcceptedHandoff(intent)) { - return reconciliationRequiredResult( - "handoff intent may have committed; reconciliation is required"); - } - } - if (persistedWorkItem.isEmpty()) { - return reconciliationRequiredResult( - "handoff preparation outcome could not be confirmed"); - } - ScriptWorkItem persisted = persistedWorkItem.orElseThrow(); - if (!Objects.equals(persisted.getStatus(), intentState.status()) - || persisted.getRowVersion() != intentState.rowVersion()) { - return reconciliationRequiredResult( - "work item state changed while handoff preparation outcome was uncertain"); - } - return retryablePreparationResult(); - }); + return executeRpcWithoutLocalTransaction(() -> { + Optional persistedWorkItem = workItemRepository.findById(workItem.getId()); + Optional persistedIntent = + handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal( + workItem.getTenantId(), workItem.getId(), command.ordinal()); + if (persistedIntent.isPresent()) { + ScriptHandoffEvent intent = persistedIntent.orElseThrow(); + ScriptWorkItem identitySource = persistedWorkItem.orElse(workItem); + if (!handoffIdentityMatches(intent, identitySource, command, dispatchId)) { + return reconciliationRequiredResult( + "persisted handoff intent identity does not match request; reconciliation is required"); + } + if (!isAcceptedHandoff(intent) && isHandoffInFlightIntent(intent)) { + return retainedInFlightHandoffResult(intent); + } + if (!isDefinitiveNonAcceptedHandoff(intent)) { + return reconciliationRequiredResult( + "handoff intent may have committed; reconciliation is required"); + } + } + if (persistedWorkItem.isEmpty()) { + return reconciliationRequiredResult("handoff preparation outcome could not be confirmed"); + } + ScriptWorkItem persisted = persistedWorkItem.orElseThrow(); + if (!Objects.equals(persisted.getStatus(), intentState.status()) + || persisted.getRowVersion() != intentState.rowVersion()) { + return reconciliationRequiredResult( + "work item state changed while handoff preparation outcome was uncertain"); + } + return retryablePreparationResult(); + }); } catch (RuntimeException readbackFailure) { LOGGER.warn( "Unable to read back failed script handoff preparation for workItemId={} commandOrdinal={}; retaining in-flight evidence", @@ -1572,14 +1566,13 @@ private void updateAudit( ScriptWorkItem workItem, String stage, String outcome, String reason, Instant now) { auditRepository .findByWorkItemId(workItem.getId()) - .ifPresent( - audit -> { - audit.setFinalStage(stage); - audit.setFinalOutcome(outcome); - audit.setFinalReason(reason); - audit.setUpdatedAt(now); - auditRepository.save(audit); - }); + .ifPresent(audit -> { + audit.setFinalStage(stage); + audit.setFinalOutcome(outcome); + audit.setFinalReason(reason); + audit.setUpdatedAt(now); + auditRepository.save(audit); + }); } private static String dispatchId(ScriptWorkItem workItem, int ordinal) { @@ -1677,11 +1670,10 @@ private ScriptHandoffEvent appendHandoffEvent( handoffEventRepository .findByTenantIdAndWorkItemIdAndCommandOrdinal( workItem.getTenantId(), workItem.getId(), command.ordinal()) - .ifPresent( - existing -> { - event.setId(existing.getId()); - event.setRowVersion(existing.getRowVersion()); - }); + .ifPresent(existing -> { + event.setId(existing.getId()); + event.setRowVersion(existing.getRowVersion()); + }); } ScriptHandoffEvent saved = handoffEventRepository.save(event); return saved == null ? event : saved; diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchInstanceRolloutProjectionServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchInstanceRolloutProjectionServiceImpl.java index be04a5f708..1f9e6dac5d 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchInstanceRolloutProjectionServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchInstanceRolloutProjectionServiceImpl.java @@ -70,11 +70,10 @@ public Optional getProjection : repository.findByTenantIdAndGameInstanceIdAndScriptPatchVersion( tenantId, gameInstanceId, scriptPatchVersion); return projection - .filter( - value -> - scriptPinEpoch <= 0 - || normalize(lastObservedControlPlaneRequestId) - .equals(normalize(value.getLastObservedControlPlaneRequestId()))) + .filter(value -> + scriptPinEpoch <= 0 + || normalize(lastObservedControlPlaneRequestId) + .equals(normalize(value.getLastObservedControlPlaneRequestId()))) .map(this::toSummary); } @@ -104,25 +103,22 @@ public List listProjections( .findByTenantIdAndGameInstanceIdOrderByLastChangedAtDescScriptPatchVersionAsc( tenantId, gameInstanceId); return projections.stream() - .filter( - projection -> - scriptPatchVersion == null - || scriptPatchVersion.isBlank() - || projection.getScriptPatchVersion().equals(scriptPatchVersion)) + .filter(projection -> + scriptPatchVersion == null + || scriptPatchVersion.isBlank() + || projection.getScriptPatchVersion().equals(scriptPatchVersion)) .filter( projection -> scriptPinEpoch <= 0 || projection.getScriptPinEpoch() == scriptPinEpoch) - .filter( - projection -> - scriptPinEpoch <= 0 - || normalize(lastObservedControlPlaneRequestId) - .equals(normalize(projection.getLastObservedControlPlaneRequestId()))) + .filter(projection -> + scriptPinEpoch <= 0 + || normalize(lastObservedControlPlaneRequestId) + .equals(normalize(projection.getLastObservedControlPlaneRequestId()))) .map(this::toSummary) - .filter( - summary -> - rolloutStatus - == ScriptPatchInstanceRolloutStatus - .SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED - || summary.rolloutStatus() == rolloutStatus) + .filter(summary -> + rolloutStatus + == ScriptPatchInstanceRolloutStatus + .SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED + || summary.rolloutStatus() == rolloutStatus) .filter(summary -> changedAfterMs <= 0 || summary.lastChangedAtMs() > changedAfterMs) .filter(summary -> changedBeforeMs <= 0 || summary.lastChangedAtMs() < changedBeforeMs) .sorted( @@ -194,12 +190,11 @@ public void refreshForInstance(String tenantId, String gameInstanceId) { pinProjectionService .getPinConvergence(tenantId, gameInstanceId) .summary() - .ifPresent( - pin -> { - if (!pin.observedPinnedScriptPatchVersion().isBlank()) { - patchVersions.add(pin.observedPinnedScriptPatchVersion()); - } - }); + .ifPresent(pin -> { + if (!pin.observedPinnedScriptPatchVersion().isBlank()) { + patchVersions.add(pin.observedPinnedScriptPatchVersion()); + } + }); patchVersions.forEach( patchVersion -> refreshProjection(tenantId, gameInstanceId, patchVersion)); } @@ -413,15 +408,13 @@ private static void requireCompleteTuple(long scriptPinEpoch, String requestId) private static boolean priorRollbackObserved(Optional existingRolloutStatus) { return existingRolloutStatus - .map( - status -> - ScriptPatchInstanceRolloutStatus.SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_ROLLED_BACK - .name() - .equals(status) - || ScriptPatchInstanceRolloutStatus - .SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_REPINNED - .name() - .equals(status)) + .map(status -> + ScriptPatchInstanceRolloutStatus.SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_ROLLED_BACK + .name() + .equals(status) + || ScriptPatchInstanceRolloutStatus.SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_REPINNED + .name() + .equals(status)) .orElse(false); } diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImpl.java index 536315824d..350fb7e1ed 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImpl.java @@ -74,12 +74,11 @@ public PinConvergenceLookup getPinConvergence(String tenantId, String gameInstan if (!acceptObservation(current.orElse(null), runtimeState)) { return current .map(value -> new PinConvergenceLookup(Optional.of(toSummary(value, now)), "", "")) - .orElseGet( - () -> - new PinConvergenceLookup( - Optional.empty(), - "INVALID_RUNTIME_PIN_TUPLE", - "GetAutomationPinConvergence failed: invalid_runtime_pin_tuple")); + .orElseGet(() -> + new PinConvergenceLookup( + Optional.empty(), + "INVALID_RUNTIME_PIN_TUPLE", + "GetAutomationPinConvergence failed: invalid_runtime_pin_tuple")); } if (!hasPositiveScriptPinEpoch(runtimeState)) { if (hasLegacyPositivePinProjection(current.orElse(null))) { diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchReadinessProjectionServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchReadinessProjectionServiceImpl.java index 789a2ce924..5acca73e13 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchReadinessProjectionServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchReadinessProjectionServiceImpl.java @@ -264,11 +264,10 @@ private Optional findCurrentProjection( } return repository .findLatestGenerationByTenantId(tenantId) - .filter( - latest -> - generation.equals(latest.getReadinessGeneration()) - && projection.getId() != null - && projection.getId().equals(latest.getId())) + .filter(latest -> + generation.equals(latest.getReadinessGeneration()) + && projection.getId() != null + && projection.getId().equals(latest.getId())) .map(latest -> projection); } @@ -338,12 +337,11 @@ private void cancelPendingOnLoadWork(String tenantId, String scriptPatchVersion, if (cancelable.isEmpty()) { return; } - cancelable.forEach( - item -> { - item.setStatus("CANCELED"); - item.setCancelReason("superseded_by_newer_patch"); - item.setUpdatedAt(now); - }); + cancelable.forEach(item -> { + item.setStatus("CANCELED"); + item.setCancelReason("superseded_by_newer_patch"); + item.setUpdatedAt(now); + }); workItemRepository.saveAll(cancelable); } @@ -366,10 +364,9 @@ private static boolean hasInvalidOnLoadBaseVersion( && (expectedBaseVersionId == null || expectedBaseVersionId <= 0L || workItems.stream() - .anyMatch( - item -> - item.getScriptPatchBaseVersionId() == null - || !expectedBaseVersionId.equals(item.getScriptPatchBaseVersionId()))); + .anyMatch(item -> + item.getScriptPatchBaseVersionId() == null + || !expectedBaseVersionId.equals(item.getScriptPatchBaseVersionId()))); } private static String onLoadBaseVersionFailureReason( diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchVersionCommandService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchVersionCommandService.java index 0e3ec88f63..c9c0f13fea 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchVersionCommandService.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchVersionCommandService.java @@ -86,11 +86,10 @@ public boolean notifyUpdate( "affectedScripts must resolve exactly one definition per unique requested name"); } if (defs.stream() - .anyMatch( - definition -> - definition.getBaseVersionId() == null - || definition.getBaseVersionId() != baseVersionId - || !scriptPatchVersion.equals(definition.getScriptVersion()))) { + .anyMatch(definition -> + definition.getBaseVersionId() == null + || definition.getBaseVersionId() != baseVersionId + || !scriptPatchVersion.equals(definition.getScriptVersion()))) { throw new IllegalArgumentException("script_patch_base_version_mismatch"); } defs = defs.stream().sorted(java.util.Comparator.comparing(ScriptDefinition::getName)).toList(); diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptScheduleInstanceServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptScheduleInstanceServiceImpl.java index b535e43e14..8271f6bc44 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptScheduleInstanceServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptScheduleInstanceServiceImpl.java @@ -218,10 +218,9 @@ && blankToEmpty(runtimeState.getScriptPatchPinnedControlPlaneRequestId()).isBlan .findByTenantIdAndScriptPatchVersionOrderByScriptIdAscEventTypeAscScheduleDefinitionIdAsc( tenantKey, scriptPatchVersion); if (definitions.stream() - .anyMatch( - definition -> - definition.getBaseVersionId() == null - || definition.getBaseVersionId() != pinnedScriptPatchBaseVersionId)) { + .anyMatch(definition -> + definition.getBaseVersionId() == null + || definition.getBaseVersionId() != pinnedScriptPatchBaseVersionId)) { markRetainedSchedulesPending(tenantId, gameInstanceId); return; } @@ -306,17 +305,16 @@ && blankToEmpty(runtimeState.getScriptPatchPinnedControlPlaneRequestId()).isBlan List deletes = existing.stream() - .filter( - instance -> - !desiredKeys.contains( - scopeKey( - instance.getPlayableStateScope(), - instance.getPluginId(), - instance.getPluginVersionId(), - applicableBindingId(instance), - instance.getScheduleDefinitionId(), - instance.getTargetScopeType(), - instance.getTargetScopeId()))) + .filter(instance -> + !desiredKeys.contains( + scopeKey( + instance.getPlayableStateScope(), + instance.getPluginId(), + instance.getPluginVersionId(), + applicableBindingId(instance), + instance.getScheduleDefinitionId(), + instance.getTargetScopeType(), + instance.getTargetScopeId()))) .toList(); if (!deletes.isEmpty()) { scheduleInstanceRepository.deleteAll(deletes); @@ -783,10 +781,8 @@ private Map> bindingsByScriptEvent( .findByTenantIdAndScriptPatchVersionOrderByEventTypeAscEventSchemaVersionAscPriorityAscScriptIdAsc( tenantId, scriptPatchVersion); if (patchBindings.stream() - .anyMatch( - binding -> - binding.getBaseVersionId() == null - || binding.getBaseVersionId() != baseVersionId)) { + .anyMatch(binding -> + binding.getBaseVersionId() == null || binding.getBaseVersionId() != baseVersionId)) { return null; } for (ScriptEventBinding binding : patchBindings) { @@ -1066,13 +1062,12 @@ && hasRetainedMaterializationEvidence(instance)) { instance.getCadenceValue(), perScheduleCandidateLimit) .stream() - .map( - dueTick -> - TimerFiringCandidate.suppressedTick( - instance, - dueTick, - blankToEmpty(instance.getRuntimeRegionId()), - instance.getRuntimeRegionEpoch())) + .map(dueTick -> + TimerFiringCandidate.suppressedTick( + instance, + dueTick, + blankToEmpty(instance.getRuntimeRegionId()), + instance.getRuntimeRegionEpoch())) .toList() : List.of(); List fireDueTicks = @@ -1349,12 +1344,10 @@ private List roundRobinCandidates( Map> bySchedule = new java.util.LinkedHashMap<>(); candidates.stream() .sorted(timerCandidateComparator()) - .forEach( - candidate -> - bySchedule - .computeIfAbsent( - scheduleKey(candidate.instance()), ignored -> new ArrayList<>()) - .add(candidate)); + .forEach(candidate -> + bySchedule + .computeIfAbsent(scheduleKey(candidate.instance()), ignored -> new ArrayList<>()) + .add(candidate)); List selected = new ArrayList<>(); int pass = 0; while (selected.size() < maxFirings) { diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java index 764ba0303a..1d21259b8a 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImpl.java @@ -596,11 +596,10 @@ private boolean executePostEvaluationFenceDisposition( applyPostEvaluationFenceDisposition(workItem, fenceFailure); return false; } - transactionTemplate.execute( - status -> { - applyPostEvaluationFenceDisposition(workItem, fenceFailure); - return null; - }); + transactionTemplate.execute(status -> { + applyPostEvaluationFenceDisposition(workItem, fenceFailure); + return null; + }); return false; } @@ -612,11 +611,10 @@ private void commitPostEvaluationFenceState(ScriptWorkItem workItem) { clearAuthorityUnavailableRetryState(workItem); return; } - transactionTemplate.execute( - status -> { - clearAuthorityUnavailableRetryState(workItem); - return null; - }); + transactionTemplate.execute(status -> { + clearAuthorityUnavailableRetryState(workItem); + return null; + }); } private void applyPostEvaluationFenceDisposition(ScriptWorkItem workItem, String fenceFailure) { @@ -1440,15 +1438,14 @@ private Map templateVariables(ScriptWorkItem workItem) { @SuppressWarnings("unchecked") Map payload = objectMapper.readValue(workItem.getPayloadJson(), LinkedHashMap.class); - payload.forEach( - (key, value) -> { - if (value == null - || value instanceof String - || value instanceof Number - || value instanceof Boolean) { - variables.put("payload." + key, value == null ? "" : value.toString()); - } - }); + payload.forEach((key, value) -> { + if (value == null + || value instanceof String + || value instanceof Number + || value instanceof Boolean) { + variables.put("payload." + key, value == null ? "" : value.toString()); + } + }); } catch (Exception ex) { throw new IllegalArgumentException("payload_json_invalid"); } @@ -1688,14 +1685,13 @@ private void updateAudit( Long workItemId, String stage, String outcome, String reason, Instant now) { auditRepository .findByWorkItemId(workItemId) - .ifPresent( - audit -> { - audit.setFinalStage(stage); - audit.setFinalOutcome(outcome); - audit.setFinalReason(reason); - audit.setUpdatedAt(now); - auditRepository.save(audit); - }); + .ifPresent(audit -> { + audit.setFinalStage(stage); + audit.setFinalOutcome(outcome); + audit.setFinalReason(reason); + audit.setUpdatedAt(now); + auditRepository.save(audit); + }); } private void recordTerminalHandoffOutcome( @@ -1791,10 +1787,9 @@ private Optional readCurrentPluginRuntimeState(ScriptWorkIte workItem.getTenantId(), workItem.getGameInstanceId(), pluginId); } Optional state = - pluginFenceReadTransactionTemplate.execute( - ignored -> - pluginRuntimeStateRepository.findByTenantIdAndGameInstanceIdAndPluginId( - workItem.getTenantId(), workItem.getGameInstanceId(), pluginId)); + pluginFenceReadTransactionTemplate.execute(ignored -> + pluginRuntimeStateRepository.findByTenantIdAndGameInstanceIdAndPluginId( + workItem.getTenantId(), workItem.getGameInstanceId(), pluginId)); return state == null ? Optional.empty() : state; } diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImpl.java index a8a8c4d2f1..6bc97a2936 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImpl.java @@ -302,11 +302,10 @@ public List claimPendingForEvaluation(int maxItems) { List items = workItemRepository.findByStatusForUpdateOrderByCreatedAtAscIdAsc( STATUS_PENDING_EVALUATION, now, PageRequest.of(0, maxItems)); - items.forEach( - item -> { - item.setStatus(STATUS_EVALUATING); - item.setUpdatedAt(now); - }); + items.forEach(item -> { + item.setStatus(STATUS_EVALUATING); + item.setUpdatedAt(now); + }); List saved = List.copyOf(workItemRepository.saveAll(items)); saved.forEach(rolloutProjectionService::refreshForWorkItem); return saved; @@ -328,11 +327,10 @@ public List claimPendingForEvaluation(List workItemIds, in STATUS_PENDING_EVALUATION, now, PageRequest.of(0, maxItems)); - items.forEach( - item -> { - item.setStatus(STATUS_EVALUATING); - item.setUpdatedAt(now); - }); + items.forEach(item -> { + item.setStatus(STATUS_EVALUATING); + item.setUpdatedAt(now); + }); List saved = List.copyOf(workItemRepository.saveAll(items)); saved.forEach(rolloutProjectionService::refreshForWorkItem); return saved; @@ -391,16 +389,15 @@ public Optional getPatchStatus(String tenantId, String scrip requireText(scriptPatchVersion, "script_patch_version"); return readinessProjectionService .getProjection(tenantId, scriptPatchVersion) - .map( - readiness -> { - PublicationMetadata metadata = - publicationMetadata(tenantId, readiness.baseVersionId(), scriptPatchVersion); - return PatchStatusSummary.fromProjection( - readiness, - metadata.baseVersionId(), - metadata.abilitySchemaDigest(), - metadata.publication()); - }); + .map(readiness -> { + PublicationMetadata metadata = + publicationMetadata(tenantId, readiness.baseVersionId(), scriptPatchVersion); + return PatchStatusSummary.fromProjection( + readiness, + metadata.baseVersionId(), + metadata.abilitySchemaDigest(), + metadata.publication()); + }); } @Override @@ -410,21 +407,19 @@ public List listPatchStatuses( requireText(tenantId, "tenant_id"); PublicationMetadataCache publicationMetadataCache = new PublicationMetadataCache(); return readinessProjectionService.listProjections(tenantId).stream() - .map( - readiness -> { - PublicationMetadata metadata = - publicationMetadataCache.get( - tenantId, readiness.baseVersionId(), readiness.scriptPatchVersion()); - return PatchStatusSummary.fromProjection( - readiness, - metadata.baseVersionId(), - metadata.abilitySchemaDigest(), - metadata.publication()); - }) - .filter( - summary -> - status == ScriptPatchStatus.SCRIPT_PATCH_STATUS_UNSPECIFIED - || summary.status() == status) + .map(readiness -> { + PublicationMetadata metadata = + publicationMetadataCache.get( + tenantId, readiness.baseVersionId(), readiness.scriptPatchVersion()); + return PatchStatusSummary.fromProjection( + readiness, + metadata.baseVersionId(), + metadata.abilitySchemaDigest(), + metadata.publication()); + }) + .filter(summary -> + status == ScriptPatchStatus.SCRIPT_PATCH_STATUS_UNSPECIFIED + || summary.status() == status) .filter(summary -> changedAfterMs <= 0 || summary.lastChangedAtMs() > changedAfterMs) .filter(summary -> changedBeforeMs <= 0 || summary.lastChangedAtMs() < changedBeforeMs) .sorted(Comparator.comparingLong(PatchStatusSummary::lastChangedAtMs).reversed()) @@ -446,22 +441,21 @@ public AutomationDrainStatusSummary getAutomationDrainStatus( normalizedTenantId, normalizedGameInstanceId, normalizedRegionId); boolean statePresent = admissionStateLookup.isPresent(); AutomationAdmissionStateService.AdmissionStateSummary admissionState = - admissionStateLookup.orElseGet( - () -> - new AutomationAdmissionStateService.AdmissionStateSummary( - normalizedTenantId, - normalizedGameInstanceId, - normalizedRegionId, - "NORMAL", - 0L, - "", - "", - "", - 0L, - "", - AutomationAdmissionStateService.OUTCOME_NOT_FOUND, - "", - 0L)); + admissionStateLookup.orElseGet(() -> + new AutomationAdmissionStateService.AdmissionStateSummary( + normalizedTenantId, + normalizedGameInstanceId, + normalizedRegionId, + "NORMAL", + 0L, + "", + "", + "", + 0L, + "", + AutomationAdmissionStateService.OUTCOME_NOT_FOUND, + "", + 0L)); List scopedWorkItems = workItemRepository.findByScopeAndStatusesOrderByCreatedAtAscIdAsc( normalizedTenantId, @@ -748,16 +742,15 @@ private ReplayResult replayDeadLettersWithoutTransaction(ReplayDeadLettersComman Map completedPreflightResults = priorResults; ReplayTransactionOutcome transactionOutcome = - replayTransactionBoundary.inTransaction( - () -> - replayDeadLettersInTransaction( - command, - normalizedTenantId, - now, - reason, - fingerprint, - completedPreflightResults, - preflights)); + replayTransactionBoundary.inTransaction(() -> + replayDeadLettersInTransaction( + command, + normalizedTenantId, + now, + reason, + fingerprint, + completedPreflightResults, + preflights)); for (ScriptWorkItem claimedItem : transactionOutcome.claimedItems()) { // This refresh can consult Game Session when its local pin projection is stale. Keep that // authority read outside the durable replay transaction. Projection reads retry the refresh @@ -822,19 +815,18 @@ private ReplayTransactionOutcome replayDeadLettersInTransaction( command.workItemIds().stream() .map(ScriptWorkItemServiceImpl::parseWorkItemId) .sorted() - .forEach( - requestedLongId -> { - if (existingResults.containsKey(requestedLongId)) { - return; - } - ReplayPreflight preflight = preflights.get(requestedLongId); - if (preflight == null || preflight.snapshot() == null) { - return; - } - workItemRepository - .findByTenantIdAndIdForUpdate(normalizedTenantId, requestedLongId) - .ifPresent(item -> lockedById.put(requestedLongId, item)); - }); + .forEach(requestedLongId -> { + if (existingResults.containsKey(requestedLongId)) { + return; + } + ReplayPreflight preflight = preflights.get(requestedLongId); + if (preflight == null || preflight.snapshot() == null) { + return; + } + workItemRepository + .findByTenantIdAndIdForUpdate(normalizedTenantId, requestedLongId) + .ifPresent(item -> lockedById.put(requestedLongId, item)); + }); // Emit and persist outcomes in caller order, while using only the already locked current rows. List results = new ArrayList<>(); @@ -1600,19 +1592,18 @@ private OriginalFailureEvidence originalFailureEvidence(ScriptWorkItem item) { String workItemReason = blankToEmpty(item.getCancelReason()); return auditRepository .findByWorkItemId(item.getId()) - .map( - audit -> { - String auditReason = blankToEmpty(audit.getFinalReason()); - boolean consistent = - auditReason.isBlank() - || workItemReason.isBlank() - || auditReason.equals(workItemReason); - return new OriginalFailureEvidence( - blankToEmpty(audit.getFinalStage()), - auditReason, - blankToEmpty(audit.getFinalOutcome()), - consistent); - }) + .map(audit -> { + String auditReason = blankToEmpty(audit.getFinalReason()); + boolean consistent = + auditReason.isBlank() + || workItemReason.isBlank() + || auditReason.equals(workItemReason); + return new OriginalFailureEvidence( + blankToEmpty(audit.getFinalStage()), + auditReason, + blankToEmpty(audit.getFinalOutcome()), + consistent); + }) .orElse(new OriginalFailureEvidence("", workItemReason, "", true)); } @@ -1622,14 +1613,13 @@ private ReplayResult replayResultFromDurable( Map persisted) { List results = command.workItemIds().stream() - .map( - id -> { - ScriptDeadLetterReplayRepository.ReplayItem result = - persisted.get(parseWorkItemId(id)); - return result == null - ? new ReplayItemResult(id, "rejected", "replay_result_missing", 0L) - : toReplayItemResult(id, result); - }) + .map(id -> { + ScriptDeadLetterReplayRepository.ReplayItem result = + persisted.get(parseWorkItemId(id)); + return result == null + ? new ReplayItemResult(id, "rejected", "replay_result_missing", 0L) + : toReplayItemResult(id, result); + }) .toList(); ReplayCounts counts = replayCounts(results); return new ReplayResult( @@ -1639,10 +1629,9 @@ private ReplayResult replayResultFromDurable( private static ReplayCounts replayCounts(List results) { long replayed = results.stream() - .filter( - result -> - "retried_evaluation".equals(result.outcome()) - || "resumed_dispatch".equals(result.outcome())) + .filter(result -> + "retried_evaluation".equals(result.outcome()) + || "resumed_dispatch".equals(result.outcome())) .count(); long rejected = results.stream().filter(result -> "rejected".equals(result.outcome())).count(); return new ReplayCounts(replayed, rejected); @@ -1696,12 +1685,11 @@ private void refreshReadinessProjectionsIfNeeded(List items) { .filter(item -> "onLoad".equals(item.getEventType())) .map(item -> item.getTenantId() + "\u0000" + item.getScriptPatchVersion()) .collect(Collectors.toSet()) - .forEach( - key -> { - int delimiter = key.indexOf('\u0000'); - readinessProjectionService.refreshFromOnLoadWorkItems( - key.substring(0, delimiter), key.substring(delimiter + 1)); - }); + .forEach(key -> { + int delimiter = key.indexOf('\u0000'); + readinessProjectionService.refreshFromOnLoadWorkItems( + key.substring(0, delimiter), key.substring(delimiter + 1)); + }); } private void cancel(ScriptWorkItem item, String reason, Instant now) { @@ -1710,14 +1698,13 @@ private void cancel(ScriptWorkItem item, String reason, Instant now) { item.setUpdatedAt(now); auditRepository .findByWorkItemId(item.getId()) - .ifPresent( - audit -> { - audit.setFinalStage("ADMISSION"); - audit.setFinalOutcome("canceled"); - audit.setFinalReason(reason); - audit.setUpdatedAt(now); - auditRepository.save(audit); - }); + .ifPresent(audit -> { + audit.setFinalStage("ADMISSION"); + audit.setFinalOutcome("canceled"); + audit.setFinalReason(reason); + audit.setUpdatedAt(now); + auditRepository.save(audit); + }); } record RuntimeScopeKey(String tenantId, String gameInstanceId, String regionId) {} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/TemporalScriptPatchReadinessActivitiesImpl.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/TemporalScriptPatchReadinessActivitiesImpl.java index 9d6897fb71..b91e220292 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/TemporalScriptPatchReadinessActivitiesImpl.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/TemporalScriptPatchReadinessActivitiesImpl.java @@ -30,22 +30,20 @@ public ScriptPatchReadinessWorkflowSnapshot refreshAndLoadStatus( readinessProjectionService.refreshFromOnLoadWorkItems(tenantId, scriptPatchVersion); return readinessProjectionService .getProjection(tenantId, scriptPatchVersion) - .map( - summary -> - new ScriptPatchReadinessWorkflowSnapshot( - summary.tenantId(), - summary.scriptPatchVersion(), - summary.status(), - summary.statusReason(), - summary.supersededByScriptPatchVersion(), - summary.lastChangedAtMs())) - .orElseThrow( - () -> - new IllegalStateException( - "SCRIPT_PATCH_READINESS_NOT_FOUND: tenantId=" - + tenantId - + ", scriptPatchVersion=" - + scriptPatchVersion)); + .map(summary -> + new ScriptPatchReadinessWorkflowSnapshot( + summary.tenantId(), + summary.scriptPatchVersion(), + summary.status(), + summary.statusReason(), + summary.supersededByScriptPatchVersion(), + summary.lastChangedAtMs())) + .orElseThrow(() -> + new IllegalStateException( + "SCRIPT_PATCH_READINESS_NOT_FOUND: tenantId=" + + tenantId + + ", scriptPatchVersion=" + + scriptPatchVersion)); } static String workflowId(String tenantId, String scriptPatchVersion) { diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java index 720ceb6938..0787f764d9 100644 --- a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java @@ -69,55 +69,53 @@ public AutomationEmptySelectedSourceIntakeReceipt readPublicationScope( requireNoAmbientOwnerSql("Automation publication receipt read"); requirePublicationScopeKey(targetNamespace, canonicalTenantId, gameDesignVersionRowId); - return dsl.transactionResult( - configuration -> { - DSLContext tx = DSL.using(configuration); - tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - var associations = - tx.fetch( - "SELECT canonical_version_id, intake_request_id FROM " - + ASSOCIATION - + " WHERE target_namespace = ? AND canonical_tenant_id = ? " - + "ORDER BY canonical_version_id", - targetNamespace, - canonicalTenantId); - if (associations.isEmpty()) { - throw new IllegalStateException( - "Automation selected-empty publication receipt is unavailable"); - } + return dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + var associations = + tx.fetch( + "SELECT canonical_version_id, intake_request_id FROM " + + ASSOCIATION + + " WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "ORDER BY canonical_version_id", + targetNamespace, + canonicalTenantId); + if (associations.isEmpty()) { + throw new IllegalStateException( + "Automation selected-empty publication receipt is unavailable"); + } - var matches = new ArrayList(); - for (Record association : associations) { - UUID associatedCanonicalVersionId = association.get(0, UUID.class); - UUID intakeRequestId = association.get(1, UUID.class); - if (associatedCanonicalVersionId == null || intakeRequestId == null) { - throw new CorruptReceiptException( - "Automation publication association identity is corrupt"); - } - AutomationEmptySelectedSourceIntakeReceipt receipt = - readValidated(tx, targetNamespace, intakeRequestId) - .orElseThrow( - () -> - new CorruptReceiptException( - "Automation publication association has no committed receipt")); - var target = receipt.authorizationBinding().selected().target(); - if (!canonicalTenantId.equals(receipt.canonicalTenantId()) - || !associatedCanonicalVersionId.equals(receipt.canonicalVersionId()) - || !canonicalTenantId.equals(target.canonicalTenantId()) - || !associatedCanonicalVersionId.equals(target.canonicalVersionId())) { - throw new CorruptReceiptException( - "Automation publication association differs from the retained selected target"); - } - if (target.gameDesignVersionRowId() == gameDesignVersionRowId) { - matches.add(receipt); - } - } - if (matches.size() != 1) { - throw new IllegalStateException( - "Automation selected-empty publication scope is missing or ambiguous"); - } - return matches.get(0); - }); + var matches = new ArrayList(); + for (Record association : associations) { + UUID associatedCanonicalVersionId = association.get(0, UUID.class); + UUID intakeRequestId = association.get(1, UUID.class); + if (associatedCanonicalVersionId == null || intakeRequestId == null) { + throw new CorruptReceiptException( + "Automation publication association identity is corrupt"); + } + AutomationEmptySelectedSourceIntakeReceipt receipt = + readValidated(tx, targetNamespace, intakeRequestId) + .orElseThrow(() -> + new CorruptReceiptException( + "Automation publication association has no committed receipt")); + var target = receipt.authorizationBinding().selected().target(); + if (!canonicalTenantId.equals(receipt.canonicalTenantId()) + || !associatedCanonicalVersionId.equals(receipt.canonicalVersionId()) + || !canonicalTenantId.equals(target.canonicalTenantId()) + || !associatedCanonicalVersionId.equals(target.canonicalVersionId())) { + throw new CorruptReceiptException( + "Automation publication association differs from the retained selected target"); + } + if (target.gameDesignVersionRowId() == gameDesignVersionRowId) { + matches.add(receipt); + } + } + if (matches.size() != 1) { + throw new IllegalStateException( + "Automation selected-empty publication scope is missing or ambiguous"); + } + return matches.get(0); + }); } /** @@ -167,70 +165,65 @@ public AutomationEmptySelectedSourceIntakeReceipt retainFresh( requireNoAmbientOwnerSql("Automation source intake transaction"); AutomationEmptySelectedSourceIntakeReceipt committed = - dsl.transactionResult( - configuration -> { - DSLContext tx = DSL.using(configuration); - tx.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); - lockAllocatorAndAssociations(tx); - lockSourceFamilies(tx); - - // This is the exact request/operation/scope phase of the lock order. A competing - // local founder has already completed its source census before these rows are read. - var previous = - readValidated(tx, binding.targetNamespace(), binding.intakeRequestId()); - if (previous.isPresent()) { - AutomationEmptySelectedSourceIntakeReceipt receipt = previous.orElseThrow(); - receipt.requireSameInputs(inputs); - return receipt; - } - requireNoPriorScopeOrOperation(tx, binding); - - Census census = censusAllSourceFamilies(tx); - census.requireFreshFoundingAllowed(); - - long maximumOccupiedKey = maximumOccupiedNumericKey(tx); - long localTenantKey = Math.addExact(maximumOccupiedKey, 1L); - long localVersionKey = Math.addExact(maximumOccupiedKey, 2L); - Census selectedScope = - censusSelectedNumericScope(tx, localTenantKey, localVersionKey); - selectedScope.requireSelectedScopeEmpty(); - - reserveCanonicalKey(tx, "TENANT", localTenantKey); - reserveCanonicalKey(tx, "VERSION", localVersionKey); - OffsetDateTime retainedAt = - requiredScalar(tx, "SELECT CURRENT_TIMESTAMP", OffsetDateTime.class) - .withOffsetSameInstant(ZoneOffset.UTC); - AutomationEmptySelectedSourceIntakeReceipt receipt = - AutomationEmptySelectedSourceIntakeReceipt.create( - inputs, - localTenantKey, - localVersionKey, - requestDigest, - census.scriptsRows(), - census.eventBindingRows(), - census.patchBaseBindingRows(), - census.unqualifiedScriptsRows(), - census.unqualifiedEventBindingRows(), - census.unqualifiedPatchBaseBindingRows(), - census.emptyAssociatedScriptsRows(), - census.emptyAssociatedEventBindingRows(), - census.emptyAssociatedPatchBaseBindingRows(), - selectedScope.scriptsRows(), - selectedScope.eventBindingRows(), - selectedScope.patchBaseBindingRows(), - retainedAt); - - insertAssociation(tx, receipt, retainedAt); - insertReceipt(tx, receipt, retainedAt); - return receipt; - }); + dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); + lockAllocatorAndAssociations(tx); + lockSourceFamilies(tx); + + // This is the exact request/operation/scope phase of the lock order. A competing + // local founder has already completed its source census before these rows are read. + var previous = readValidated(tx, binding.targetNamespace(), binding.intakeRequestId()); + if (previous.isPresent()) { + AutomationEmptySelectedSourceIntakeReceipt receipt = previous.orElseThrow(); + receipt.requireSameInputs(inputs); + return receipt; + } + requireNoPriorScopeOrOperation(tx, binding); + + Census census = censusAllSourceFamilies(tx); + census.requireFreshFoundingAllowed(); + + long maximumOccupiedKey = maximumOccupiedNumericKey(tx); + long localTenantKey = Math.addExact(maximumOccupiedKey, 1L); + long localVersionKey = Math.addExact(maximumOccupiedKey, 2L); + Census selectedScope = censusSelectedNumericScope(tx, localTenantKey, localVersionKey); + selectedScope.requireSelectedScopeEmpty(); + + reserveCanonicalKey(tx, "TENANT", localTenantKey); + reserveCanonicalKey(tx, "VERSION", localVersionKey); + OffsetDateTime retainedAt = + requiredScalar(tx, "SELECT CURRENT_TIMESTAMP", OffsetDateTime.class) + .withOffsetSameInstant(ZoneOffset.UTC); + AutomationEmptySelectedSourceIntakeReceipt receipt = + AutomationEmptySelectedSourceIntakeReceipt.create( + inputs, + localTenantKey, + localVersionKey, + requestDigest, + census.scriptsRows(), + census.eventBindingRows(), + census.patchBaseBindingRows(), + census.unqualifiedScriptsRows(), + census.unqualifiedEventBindingRows(), + census.unqualifiedPatchBaseBindingRows(), + census.emptyAssociatedScriptsRows(), + census.emptyAssociatedEventBindingRows(), + census.emptyAssociatedPatchBaseBindingRows(), + selectedScope.scriptsRows(), + selectedScope.eventBindingRows(), + selectedScope.patchBaseBindingRows(), + retainedAt); + + insertAssociation(tx, receipt, retainedAt); + insertReceipt(tx, receipt, retainedAt); + return receipt; + }); AutomationEmptySelectedSourceIntakeReceipt readBack = read(committed.targetNamespace(), committed.intakeRequestId()) - .orElseThrow( - () -> - new CorruptReceiptException( - "Committed Automation source receipt is unavailable")); + .orElseThrow(() -> + new CorruptReceiptException("Committed Automation source receipt is unavailable")); if (!Arrays.equals(committed.canonicalBytes(), readBack.canonicalBytes()) || !committed.receiptDigest().equals(readBack.receiptDigest()) || !committed.requestDigest().equals(readBack.requestDigest())) { diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java index 0ede369ba3..c36ea32119 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationClaimAndRetentionRepositoryIntegrationTest.java @@ -310,13 +310,12 @@ void concurrentPinnedIngressClaimsHaveOnePostgresWinnerAndOneLoser() throws Exce new ArrayList<>(); for (int i = 0; i < 2; i++) { futures.add( - executor.submit( - () -> { - ready.countDown(); - await(start); - return new ScriptEventIngressAuditRepository(dsl) - .insertIfAbsentByIdentity(pinnedIngressClaim()); - })); + executor.submit(() -> { + ready.countDown(); + await(start); + return new ScriptEventIngressAuditRepository(dsl) + .insertIfAbsentByIdentity(pinnedIngressClaim()); + })); } assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); @@ -358,13 +357,12 @@ void concurrentPreInstanceOnLoadClaimsWithNullableScopeHaveOnePostgresWinnerAndO new ArrayList<>(); for (int i = 0; i < 2; i++) { futures.add( - executor.submit( - () -> { - ready.countDown(); - await(start); - return new ScriptEventIngressAuditRepository(dsl) - .insertIfAbsentByIdentity(preInstanceIngressClaim()); - })); + executor.submit(() -> { + ready.countDown(); + await(start); + return new ScriptEventIngressAuditRepository(dsl) + .insertIfAbsentByIdentity(preInstanceIngressClaim()); + })); } assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); @@ -387,13 +385,12 @@ void concurrentPinnedWorkClaimsHaveOnePostgresWinnerAndOneLoser() throws Excepti List> futures = new ArrayList<>(); for (int i = 0; i < 2; i++) { futures.add( - executor.submit( - () -> { - ready.countDown(); - await(start); - return new ScriptWorkItemRepository(dsl) - .insertIfAbsentByTriggerIdentity(pinnedWorkItem()); - })); + executor.submit(() -> { + ready.countDown(); + await(start); + return new ScriptWorkItemRepository(dsl) + .insertIfAbsentByTriggerIdentity(pinnedWorkItem()); + })); } assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); @@ -413,13 +410,12 @@ void concurrentUnpinnedWorkClaimsHaveOnePostgresWinnerAndOneLoser() throws Excep List> futures = new ArrayList<>(); for (int i = 0; i < 2; i++) { futures.add( - executor.submit( - () -> { - ready.countDown(); - await(start); - return new ScriptWorkItemRepository(dsl) - .insertIfAbsentByTriggerIdentity(unpinnedWorkItem()); - })); + executor.submit(() -> { + ready.countDown(); + await(start); + return new ScriptWorkItemRepository(dsl) + .insertIfAbsentByTriggerIdentity(unpinnedWorkItem()); + })); } assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); @@ -509,11 +505,10 @@ void scriptOnlyPluginIdentityDefaultsToEmptyAndLookupFindsTheCanonicalRow() { .findByTenantIdAndPluginIdAndPluginVersionIdAndStatusInOrderByCreatedAtAscIdAsc( "tenant-script-only", null, null, List.of("PENDING_EVALUATION"))) .singleElement() - .satisfies( - item -> { - assertThat(item.getPluginId()).isEmpty(); - assertThat(item.getPluginVersionId()).isEmpty(); - }); + .satisfies(item -> { + assertThat(item.getPluginId()).isEmpty(); + assertThat(item.getPluginVersionId()).isEmpty(); + }); } @Test @@ -562,20 +557,19 @@ void replayRequestsRoundTripPerTenantAndResultsHydrateRetainedFailureEvidence() assertThat(replayRepository.findResults("tenant-replay-a", tenantA.id())) .singleElement() - .satisfies( - result -> { - assertThat(result.requestedWorkItemId()).isEqualTo(9001L); - assertThat(result.workItemId()).isNull(); - assertThat(result.outcome()).isEqualTo("rejected"); - assertThat(result.rejectionReason()).isEqualTo("not_found_or_not_owned"); - assertThat(result.failureReason()).isEmpty(); - assertThat(result.scriptPinEpoch()).isEqualTo(2L); - assertThat(result.pluginActivationEpoch()).isEqualTo(4L); - assertThat(result.lifecycleRevision()).isEqualTo(5L); - assertThat(result.failureGeneration()).isEqualTo(3L); - assertThat(result.originalFailureStage()).isEqualTo("DSL_EVAL"); - assertThat(result.originalFailureReason()).isEqualTo("sandbox_error"); - }); + .satisfies(result -> { + assertThat(result.requestedWorkItemId()).isEqualTo(9001L); + assertThat(result.workItemId()).isNull(); + assertThat(result.outcome()).isEqualTo("rejected"); + assertThat(result.rejectionReason()).isEqualTo("not_found_or_not_owned"); + assertThat(result.failureReason()).isEmpty(); + assertThat(result.scriptPinEpoch()).isEqualTo(2L); + assertThat(result.pluginActivationEpoch()).isEqualTo(4L); + assertThat(result.lifecycleRevision()).isEqualTo(5L); + assertThat(result.failureGeneration()).isEqualTo(3L); + assertThat(result.originalFailureStage()).isEqualTo("DSL_EVAL"); + assertThat(result.originalFailureReason()).isEqualTo("sandbox_error"); + }); assertThat(replayRepository.findResults("tenant-replay-b", tenantB.id())).isEmpty(); assertThat( dsl.fetchValue( @@ -690,11 +684,10 @@ void scriptPatchPinProjectionRoundTripsGeneratedPinEpoch() { assertThat(saved.getLastObservedControlPlaneRequestId()).isEqualTo("pin-request-1"); assertThat(pinProjectionRepository.findByTenantIdAndGameInstanceId("tenant-1", "instance-1")) .get() - .satisfies( - found -> { - assertThat(found.getScriptPinEpoch()).isEqualTo(2L); - assertThat(found.getObservedPinnedScriptPatchVersion()).isEqualTo("patch-1"); - }); + .satisfies(found -> { + assertThat(found.getScriptPinEpoch()).isEqualTo(2L); + assertThat(found.getObservedPinnedScriptPatchVersion()).isEqualTo("patch-1"); + }); } @Test @@ -734,15 +727,13 @@ void concurrentAdmissionRetriesAdvanceOnePauseEpochAndReturnOneDurableResult() t List> futures = new ArrayList<>(); for (int i = 0; i < 2; i++) { futures.add( - executor.submit( - () -> { - DSLContext transactionRoot = - newDsl("automation-admission-retry-" + System.nanoTime()); - ready.countDown(); - await(start); - return transactionRoot.transactionResult( - configuration -> admissionService(configuration.dsl()).setMode(command)); - })); + executor.submit(() -> { + DSLContext transactionRoot = newDsl("automation-admission-retry-" + System.nanoTime()); + ready.countDown(); + await(start); + return transactionRoot.transactionResult( + configuration -> admissionService(configuration.dsl()).setMode(command)); + })); } assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); @@ -782,20 +773,19 @@ void concurrentAdmissionFingerprintConflictKeepsOneWinnerAndOneHistoryRow() thro List> futures = new ArrayList<>(); for (SetAdmissionModeCommand command : commands) { futures.add( - executor.submit( - () -> { - DSLContext transactionRoot = - newDsl("automation-admission-conflict-" + System.nanoTime()); - ready.countDown(); - await(start); - try { - return MutationAttempt.success( - transactionRoot.transactionResult( - configuration -> admissionService(configuration.dsl()).setMode(command))); - } catch (RuntimeException exception) { - return MutationAttempt.failure(exception); - } - })); + executor.submit(() -> { + DSLContext transactionRoot = + newDsl("automation-admission-conflict-" + System.nanoTime()); + ready.countDown(); + await(start); + try { + return MutationAttempt.success( + transactionRoot.transactionResult( + configuration -> admissionService(configuration.dsl()).setMode(command))); + } catch (RuntimeException exception) { + return MutationAttempt.failure(exception); + } + })); } assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); @@ -832,15 +822,14 @@ void concurrentDistinctAdmissionRequestsShareOnePauseEpochAndPersistBothResults( List> futures = new ArrayList<>(); for (SetAdmissionModeCommand command : commands) { futures.add( - executor.submit( - () -> { - DSLContext transactionRoot = - newDsl("automation-admission-distinct-" + System.nanoTime()); - ready.countDown(); - await(start); - return transactionRoot.transactionResult( - configuration -> admissionService(configuration.dsl()).setMode(command)); - })); + executor.submit(() -> { + DSLContext transactionRoot = + newDsl("automation-admission-distinct-" + System.nanoTime()); + ready.countDown(); + await(start); + return transactionRoot.transactionResult( + configuration -> admissionService(configuration.dsl()).setMode(command)); + })); } assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); @@ -854,18 +843,16 @@ void concurrentDistinctAdmissionRequestsShareOnePauseEpochAndPersistBothResults( .isEqualTo(1); assertThat( summaries.stream() - .filter( - s -> - AutomationAdmissionStateService.OUTCOME_ALREADY_APPLIED.equals(s.outcome())) + .filter(s -> + AutomationAdmissionStateService.OUTCOME_ALREADY_APPLIED.equals(s.outcome())) .count()) .isEqualTo(1); assertThat(summaries) - .allSatisfy( - summary -> { - assertThat(summary.targetMode()).isEqualTo("PAUSED_FOR_ROLLBACK"); - assertThat(summary.admissionEpoch()).isEqualTo(2L); - assertThat(summary.requestFingerprint()).matches("[0-9a-f]{64}"); - }); + .allSatisfy(summary -> { + assertThat(summary.targetMode()).isEqualTo("PAUSED_FOR_ROLLBACK"); + assertThat(summary.admissionEpoch()).isEqualTo(2L); + assertThat(summary.requestFingerprint()).matches("[0-9a-f]{64}"); + }); assertThat(dsl.fetchCount(AUTOMATION_ADMISSION_STATES)).isEqualTo(1); assertThat(dsl.fetchCount(AUTOMATION_ADMISSION_REQUEST_HISTORY)).isEqualTo(2); @@ -882,16 +869,15 @@ void concurrentDistinctAdmissionRequestsShareOnePauseEpochAndPersistBothResults( .fetch(); assertThat(historyRows) .hasSize(2) - .allSatisfy( - row -> { - assertThat(row.getMode()).isEqualTo("PAUSED_FOR_ROLLBACK"); - assertThat(row.getAdmissionEpoch()).isEqualTo(2L); - assertThat(row.getRequestFingerprint()).matches("[0-9a-f]{64}"); - assertThat(row.getOutcome()) - .isIn( - AutomationAdmissionStateService.OUTCOME_APPLIED, - AutomationAdmissionStateService.OUTCOME_ALREADY_APPLIED); - }); + .allSatisfy(row -> { + assertThat(row.getMode()).isEqualTo("PAUSED_FOR_ROLLBACK"); + assertThat(row.getAdmissionEpoch()).isEqualTo(2L); + assertThat(row.getRequestFingerprint()).matches("[0-9a-f]{64}"); + assertThat(row.getOutcome()) + .isIn( + AutomationAdmissionStateService.OUTCOME_APPLIED, + AutomationAdmissionStateService.OUTCOME_ALREADY_APPLIED); + }); assertThat(historyRows) .extracting(row -> row.getControlPlaneRequestId()) .containsExactlyInAnyOrder( @@ -906,22 +892,16 @@ void concurrentDistinctAdmissionRequestsShareOnePauseEpochAndPersistBothResults( @Test void workflowRequestIdCanSpanModeKeysAndReadbackReturnsTheCurrentResult() { AdmissionStateSummary pause = - dsl.transactionResult( - configuration -> - admissionService(configuration.dsl()) - .setMode( - admissionCommand( - "PAUSED_FOR_ROLLBACK", - "workflow-admission-modes", - "actor-1", - "pause"))); + dsl.transactionResult(configuration -> + admissionService(configuration.dsl()) + .setMode( + admissionCommand( + "PAUSED_FOR_ROLLBACK", "workflow-admission-modes", "actor-1", "pause"))); AdmissionStateSummary normal = - dsl.transactionResult( - configuration -> - admissionService(configuration.dsl()) - .setMode( - admissionCommand( - "NORMAL", "workflow-admission-modes", "actor-1", "resume"))); + dsl.transactionResult(configuration -> + admissionService(configuration.dsl()) + .setMode( + admissionCommand("NORMAL", "workflow-admission-modes", "actor-1", "resume"))); assertThat(pause.outcome()).isEqualTo(AutomationAdmissionStateService.OUTCOME_APPLIED); assertThat(pause.admissionEpoch()).isEqualTo(2L); @@ -944,10 +924,9 @@ void workflowRequestIdCanSpanModeKeysAndReadbackReturnsTheCurrentResult() { .containsExactlyInAnyOrder("NORMAL", "PAUSED_FOR_ROLLBACK"); Optional readback = - dsl.transactionResult( - configuration -> - admissionService(configuration.dsl()) - .findState("tenant-admission", "instance-admission", "region-admission")); + dsl.transactionResult(configuration -> + admissionService(configuration.dsl()) + .findState("tenant-admission", "instance-admission", "region-admission")); assertThat(readback).isPresent(); assertThat(readback.orElseThrow()).isEqualTo(normal); } @@ -1008,10 +987,9 @@ void newRequestForCurrentModeStoresAlreadyAppliedAndExactRetryReturnsSameDurable @Test void missingAdmissionReadOnlyLookupDoesNotCreateStateOrHistory() { Optional missing = - dsl.transactionResult( - configuration -> - admissionService(configuration.dsl()) - .findState("tenant-admission", "instance-admission", "region-admission")); + dsl.transactionResult(configuration -> + admissionService(configuration.dsl()) + .findState("tenant-admission", "instance-admission", "region-admission")); assertThat(missing).isEmpty(); assertThat(dsl.fetchCount(AUTOMATION_ADMISSION_STATES)).isZero(); @@ -1020,44 +998,35 @@ void missingAdmissionReadOnlyLookupDoesNotCreateStateOrHistory() { @Test void databaseEnforcesAdmissionRequestIdentityPair() { - assertThatThrownBy( - () -> - dsl.insertInto(AUTOMATION_ADMISSION_STATES) - .set(AUTOMATION_ADMISSION_STATES.TENANT_ID, "tenant-invalid-fingerprint") - .set( - AUTOMATION_ADMISSION_STATES.GAME_INSTANCE_ID, - "instance-invalid-fingerprint") - .set(AUTOMATION_ADMISSION_STATES.REGION_ID, "region-invalid-fingerprint") - .set( - AUTOMATION_ADMISSION_STATES.CONTROL_PLANE_REQUEST_FINGERPRINT, - REQUEST_DIGEST) - .execute()) + assertThatThrownBy(() -> + dsl.insertInto(AUTOMATION_ADMISSION_STATES) + .set(AUTOMATION_ADMISSION_STATES.TENANT_ID, "tenant-invalid-fingerprint") + .set(AUTOMATION_ADMISSION_STATES.GAME_INSTANCE_ID, "instance-invalid-fingerprint") + .set(AUTOMATION_ADMISSION_STATES.REGION_ID, "region-invalid-fingerprint") + .set(AUTOMATION_ADMISSION_STATES.CONTROL_PLANE_REQUEST_FINGERPRINT, REQUEST_DIGEST) + .execute()) .isInstanceOf(DataAccessException.class) .hasMessageContaining("ck_automation_admission_state_request_identity"); - assertThatThrownBy( - () -> - dsl.insertInto(AUTOMATION_ADMISSION_STATES) - .set(AUTOMATION_ADMISSION_STATES.TENANT_ID, "tenant-invalid-request") - .set(AUTOMATION_ADMISSION_STATES.GAME_INSTANCE_ID, "instance-invalid-request") - .set(AUTOMATION_ADMISSION_STATES.REGION_ID, "region-invalid-request") - .set( - AUTOMATION_ADMISSION_STATES.CONTROL_PLANE_REQUEST_ID, - "request-without-fingerprint") - .execute()) + assertThatThrownBy(() -> + dsl.insertInto(AUTOMATION_ADMISSION_STATES) + .set(AUTOMATION_ADMISSION_STATES.TENANT_ID, "tenant-invalid-request") + .set(AUTOMATION_ADMISSION_STATES.GAME_INSTANCE_ID, "instance-invalid-request") + .set(AUTOMATION_ADMISSION_STATES.REGION_ID, "region-invalid-request") + .set( + AUTOMATION_ADMISSION_STATES.CONTROL_PLANE_REQUEST_ID, + "request-without-fingerprint") + .execute()) .isInstanceOf(DataAccessException.class) .hasMessageContaining("ck_automation_admission_state_request_identity"); - assertThatThrownBy( - () -> - dsl.insertInto(AUTOMATION_ADMISSION_STATES) - .set(AUTOMATION_ADMISSION_STATES.TENANT_ID, "tenant-invalid-blank-request") - .set( - AUTOMATION_ADMISSION_STATES.GAME_INSTANCE_ID, - "instance-invalid-blank-request") - .set(AUTOMATION_ADMISSION_STATES.REGION_ID, "region-invalid-blank-request") - .set(AUTOMATION_ADMISSION_STATES.CONTROL_PLANE_REQUEST_ID, " ") - .execute()) + assertThatThrownBy(() -> + dsl.insertInto(AUTOMATION_ADMISSION_STATES) + .set(AUTOMATION_ADMISSION_STATES.TENANT_ID, "tenant-invalid-blank-request") + .set(AUTOMATION_ADMISSION_STATES.GAME_INSTANCE_ID, "instance-invalid-blank-request") + .set(AUTOMATION_ADMISSION_STATES.REGION_ID, "region-invalid-blank-request") + .set(AUTOMATION_ADMISSION_STATES.CONTROL_PLANE_REQUEST_ID, " ") + .execute()) .isInstanceOf(DataAccessException.class) .hasMessageContaining("ck_automation_admission_state_request_identity"); @@ -1080,45 +1049,41 @@ void databaseEnforcesAdmissionRequestIdentityPair() { .execute()) .isEqualTo(1); - assertThatThrownBy( - () -> - dsl.insertInto(AUTOMATION_ADMISSION_REQUEST_HISTORY) - .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.TENANT_ID, "tenant-history-empty") - .set( - AUTOMATION_ADMISSION_REQUEST_HISTORY.GAME_INSTANCE_ID, - "instance-history-empty") - .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.REGION_ID, "region-history-empty") - .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.MODE, "PAUSED_FOR_ROLLBACK") - .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.CONTROL_PLANE_REQUEST_ID, "") - .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.REQUEST_FINGERPRINT, REQUEST_DIGEST) - .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.ADMISSION_EPOCH, 2L) - .set( - AUTOMATION_ADMISSION_REQUEST_HISTORY.OUTCOME, - AutomationAdmissionStateService.OUTCOME_APPLIED) - .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.ACTOR_PRINCIPAL, "actor-1") - .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.REASON, "rollback") - .execute()) + assertThatThrownBy(() -> + dsl.insertInto(AUTOMATION_ADMISSION_REQUEST_HISTORY) + .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.TENANT_ID, "tenant-history-empty") + .set( + AUTOMATION_ADMISSION_REQUEST_HISTORY.GAME_INSTANCE_ID, "instance-history-empty") + .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.REGION_ID, "region-history-empty") + .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.MODE, "PAUSED_FOR_ROLLBACK") + .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.CONTROL_PLANE_REQUEST_ID, "") + .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.REQUEST_FINGERPRINT, REQUEST_DIGEST) + .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.ADMISSION_EPOCH, 2L) + .set( + AUTOMATION_ADMISSION_REQUEST_HISTORY.OUTCOME, + AutomationAdmissionStateService.OUTCOME_APPLIED) + .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.ACTOR_PRINCIPAL, "actor-1") + .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.REASON, "rollback") + .execute()) .isInstanceOf(DataAccessException.class) .hasMessageContaining("ck_automation_admission_request_history_fingerprint"); - assertThatThrownBy( - () -> - dsl.insertInto(AUTOMATION_ADMISSION_REQUEST_HISTORY) - .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.TENANT_ID, "tenant-history-space") - .set( - AUTOMATION_ADMISSION_REQUEST_HISTORY.GAME_INSTANCE_ID, - "instance-history-space") - .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.REGION_ID, "region-history-space") - .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.MODE, "PAUSED_FOR_ROLLBACK") - .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.CONTROL_PLANE_REQUEST_ID, " ") - .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.REQUEST_FINGERPRINT, REQUEST_DIGEST) - .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.ADMISSION_EPOCH, 2L) - .set( - AUTOMATION_ADMISSION_REQUEST_HISTORY.OUTCOME, - AutomationAdmissionStateService.OUTCOME_APPLIED) - .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.ACTOR_PRINCIPAL, "actor-1") - .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.REASON, "rollback") - .execute()) + assertThatThrownBy(() -> + dsl.insertInto(AUTOMATION_ADMISSION_REQUEST_HISTORY) + .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.TENANT_ID, "tenant-history-space") + .set( + AUTOMATION_ADMISSION_REQUEST_HISTORY.GAME_INSTANCE_ID, "instance-history-space") + .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.REGION_ID, "region-history-space") + .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.MODE, "PAUSED_FOR_ROLLBACK") + .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.CONTROL_PLANE_REQUEST_ID, " ") + .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.REQUEST_FINGERPRINT, REQUEST_DIGEST) + .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.ADMISSION_EPOCH, 2L) + .set( + AUTOMATION_ADMISSION_REQUEST_HISTORY.OUTCOME, + AutomationAdmissionStateService.OUTCOME_APPLIED) + .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.ACTOR_PRINCIPAL, "actor-1") + .set(AUTOMATION_ADMISSION_REQUEST_HISTORY.REASON, "rollback") + .execute()) .isInstanceOf(DataAccessException.class) .hasMessageContaining("ck_automation_admission_request_history_fingerprint"); @@ -1157,33 +1122,28 @@ void renewalWinsAgainstStaleReclaimAndReclaimAdvancesTheFence() throws Exception DSLContext ownerDsl = newDsl(ownerApplicationName); DSLContext reclaimDsl = newDsl("automation-claim-reclaim-" + System.nanoTime()); Future renewal = - executor.submit( - () -> - ownerDsl.transactionResult( - configuration -> { - boolean renewed = - new ScriptEventIngressAuditRepository(configuration.dsl()) - .renewClaimIfCurrent(ownerClaim, RENEWED_AT); - ownerLockHeld.countDown(); - await(releaseOwner); - return renewed; - })); + executor.submit(() -> + ownerDsl.transactionResult(configuration -> { + boolean renewed = + new ScriptEventIngressAuditRepository(configuration.dsl()) + .renewClaimIfCurrent(ownerClaim, RENEWED_AT); + ownerLockHeld.countDown(); + await(releaseOwner); + return renewed; + })); assertThat(ownerLockHeld.await(5, TimeUnit.SECONDS)).isTrue(); AtomicLong reclaimBackendPid = new AtomicLong(); CountDownLatch reclaimStarted = new CountDownLatch(1); Future> reclaim = - executor.submit( - () -> - reclaimDsl.transactionResult( - configuration -> { - DSLContext transactionDsl = configuration.dsl(); - reclaimBackendPid.set(currentBackendPid(transactionDsl)); - reclaimStarted.countDown(); - return new ScriptEventIngressAuditRepository(transactionDsl) - .reclaimStaleInProgress( - ownerClaim, STALE_BEFORE, RENEWED_AT.plusSeconds(1)); - })); + executor.submit(() -> + reclaimDsl.transactionResult(configuration -> { + DSLContext transactionDsl = configuration.dsl(); + reclaimBackendPid.set(currentBackendPid(transactionDsl)); + reclaimStarted.countDown(); + return new ScriptEventIngressAuditRepository(transactionDsl) + .reclaimStaleInProgress(ownerClaim, STALE_BEFORE, RENEWED_AT.plusSeconds(1)); + })); assertThat(reclaimStarted.await(5, TimeUnit.SECONDS)).isTrue(); awaitPostgresLockWait(reclaimBackendPid.get()); releaseOwner.countDown(); @@ -1220,35 +1180,31 @@ void retentionWaitsForParentLockAndDisposesFkChildrenBeforeParent() throws Excep DSLContext lockDsl = newDsl(lockApplicationName); DSLContext cleanupDsl = newDsl("automation-retention-cleanup-" + System.nanoTime()); Future lock = - executor.submit( - () -> - lockDsl.transactionResult( - configuration -> { - configuration - .dsl() - .selectFrom(SCRIPT_WORK_ITEMS) - .where(SCRIPT_WORK_ITEMS.ID.eq(parent.getId())) - .forUpdate() - .fetchOne(); - parentLockHeld.countDown(); - await(releaseParent); - return null; - })); + executor.submit(() -> + lockDsl.transactionResult(configuration -> { + configuration + .dsl() + .selectFrom(SCRIPT_WORK_ITEMS) + .where(SCRIPT_WORK_ITEMS.ID.eq(parent.getId())) + .forUpdate() + .fetchOne(); + parentLockHeld.countDown(); + await(releaseParent); + return null; + })); assertThat(parentLockHeld.await(5, TimeUnit.SECONDS)).isTrue(); AtomicLong cleanupBackendPid = new AtomicLong(); CountDownLatch cleanupStarted = new CountDownLatch(1); Future cleanup = - executor.submit( - () -> - cleanupDsl.transactionResult( - configuration -> { - DSLContext transactionDsl = configuration.dsl(); - cleanupBackendPid.set(currentBackendPid(transactionDsl)); - cleanupStarted.countDown(); - return new ScriptWorkItemRepository(transactionDsl) - .deleteByStatusAndUpdatedAtBefore("HANDED_OFF", Instant.now()); - })); + executor.submit(() -> + cleanupDsl.transactionResult(configuration -> { + DSLContext transactionDsl = configuration.dsl(); + cleanupBackendPid.set(currentBackendPid(transactionDsl)); + cleanupStarted.countDown(); + return new ScriptWorkItemRepository(transactionDsl) + .deleteByStatusAndUpdatedAtBefore("HANDED_OFF", Instant.now()); + })); assertThat(cleanupStarted.await(5, TimeUnit.SECONDS)).isTrue(); awaitPostgresLockWait(cleanupBackendPid.get()); releaseParent.countDown(); @@ -1277,25 +1233,21 @@ void retentionAndParentCleanupSerializeParentBeforeChildWithoutDeadlock() throws CountDownLatch start = new CountDownLatch(1); try { Future parentCleanup = - executor.submit( - () -> - parentCleanupDsl.transactionResult( - configuration -> { - ready.countDown(); - await(start); - return new ScriptWorkItemRepository(configuration.dsl()) - .deleteByStatusAndUpdatedAtBefore("HANDED_OFF", now); - })); + executor.submit(() -> + parentCleanupDsl.transactionResult(configuration -> { + ready.countDown(); + await(start); + return new ScriptWorkItemRepository(configuration.dsl()) + .deleteByStatusAndUpdatedAtBefore("HANDED_OFF", now); + })); Future handoffCleanup = - executor.submit( - () -> - handoffCleanupDsl.transactionResult( - configuration -> { - ready.countDown(); - await(start); - return new ScriptHandoffEventRepository(configuration.dsl()) - .deleteExpiredRetentionEvidence(cutoff, now); - })); + executor.submit(() -> + handoffCleanupDsl.transactionResult(configuration -> { + ready.countDown(); + await(start); + return new ScriptHandoffEventRepository(configuration.dsl()) + .deleteExpiredRetentionEvidence(cutoff, now); + })); assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); start.countDown(); @@ -1326,38 +1278,34 @@ void retentionRechecksSiblingHoldCommittedAfterCandidateSnapshot() throws Except CountDownLatch releaseHold = new CountDownLatch(1); DSLContext holdDsl = newDsl("automation-retention-sibling-hold-" + System.nanoTime()); Future hold = - executor.submit( - () -> - holdDsl.transactionResult( - configuration -> { - configuration - .dsl() - .update(SCRIPT_HANDOFF_EVENTS) - .set( - SCRIPT_HANDOFF_EVENTS.RETENTION_HOLD_UNTIL, - now.plusSeconds(60).atOffset(ZoneOffset.UTC)) - .where(SCRIPT_HANDOFF_EVENTS.ID.eq(siblingId)) - .execute(); - holdStarted.countDown(); - await(releaseHold); - return null; - })); + executor.submit(() -> + holdDsl.transactionResult(configuration -> { + configuration + .dsl() + .update(SCRIPT_HANDOFF_EVENTS) + .set( + SCRIPT_HANDOFF_EVENTS.RETENTION_HOLD_UNTIL, + now.plusSeconds(60).atOffset(ZoneOffset.UTC)) + .where(SCRIPT_HANDOFF_EVENTS.ID.eq(siblingId)) + .execute(); + holdStarted.countDown(); + await(releaseHold); + return null; + })); assertThat(holdStarted.await(5, TimeUnit.SECONDS)).isTrue(); AtomicLong cleanupBackendPid = new AtomicLong(); CountDownLatch cleanupStarted = new CountDownLatch(1); DSLContext cleanupDsl = newDsl("automation-retention-sibling-cleanup-" + System.nanoTime()); Future cleanup = - executor.submit( - () -> - cleanupDsl.transactionResult( - configuration -> { - DSLContext transactionDsl = configuration.dsl(); - cleanupBackendPid.set(currentBackendPid(transactionDsl)); - cleanupStarted.countDown(); - return new ScriptHandoffEventRepository(transactionDsl) - .deleteExpiredRetentionEvidence(cutoff, now); - })); + executor.submit(() -> + cleanupDsl.transactionResult(configuration -> { + DSLContext transactionDsl = configuration.dsl(); + cleanupBackendPid.set(currentBackendPid(transactionDsl)); + cleanupStarted.countDown(); + return new ScriptHandoffEventRepository(transactionDsl) + .deleteExpiredRetentionEvidence(cutoff, now); + })); assertThat(cleanupStarted.await(5, TimeUnit.SECONDS)).isTrue(); awaitPostgresLockWait(cleanupBackendPid.get()); releaseHold.countDown(); @@ -1388,44 +1336,40 @@ void retentionRechecksReplayReceiptCommittedAfterCandidateSnapshot() throws Exce CountDownLatch releaseReceipt = new CountDownLatch(1); DSLContext receiptDsl = newDsl("automation-retention-receipt-" + System.nanoTime()); Future receipt = - executor.submit( - () -> - receiptDsl.transactionResult( - configuration -> { - new ScriptDeadLetterReplayRepository(configuration.dsl()) - .saveResult( - "tenant-1", - request.id(), - parent.getId(), - parent.getId(), - "rejected", - "retention-race", - "", - 2L, - 0L, - 0L, - 1L, - now); - receiptStarted.countDown(); - await(releaseReceipt); - return null; - })); + executor.submit(() -> + receiptDsl.transactionResult(configuration -> { + new ScriptDeadLetterReplayRepository(configuration.dsl()) + .saveResult( + "tenant-1", + request.id(), + parent.getId(), + parent.getId(), + "rejected", + "retention-race", + "", + 2L, + 0L, + 0L, + 1L, + now); + receiptStarted.countDown(); + await(releaseReceipt); + return null; + })); assertThat(receiptStarted.await(5, TimeUnit.SECONDS)).isTrue(); AtomicLong cleanupBackendPid = new AtomicLong(); CountDownLatch cleanupStarted = new CountDownLatch(1); DSLContext cleanupDsl = newDsl("automation-retention-receipt-cleanup-" + System.nanoTime()); Future cleanup = - executor.submit( - () -> - cleanupDsl.transactionResult( - configuration -> { - DSLContext transactionDsl = configuration.dsl(); - cleanupBackendPid.set(currentBackendPid(transactionDsl)); - cleanupStarted.countDown(); - return new ScriptHandoffEventRepository(transactionDsl) - .deleteExpiredRetentionEvidence(cutoff, now); - })); + executor.submit(() -> + cleanupDsl.transactionResult(configuration -> { + DSLContext transactionDsl = configuration.dsl(); + cleanupBackendPid.set(currentBackendPid(transactionDsl)); + cleanupStarted.countDown(); + return new ScriptHandoffEventRepository(transactionDsl) + .deleteExpiredRetentionEvidence(cutoff, now); + })); assertThat(cleanupStarted.await(5, TimeUnit.SECONDS)).isTrue(); awaitPostgresLockWait(cleanupBackendPid.get()); releaseReceipt.countDown(); @@ -1453,36 +1397,32 @@ void retentionRechecksParentStatusCommittedAfterCandidateSnapshot() throws Excep CountDownLatch releaseStatus = new CountDownLatch(1); DSLContext statusDsl = newDsl("automation-retention-parent-status-" + System.nanoTime()); Future status = - executor.submit( - () -> - statusDsl.transactionResult( - configuration -> { - configuration - .dsl() - .update(SCRIPT_WORK_ITEMS) - .set(SCRIPT_WORK_ITEMS.STATUS, "DEAD_LETTERED") - .where(SCRIPT_WORK_ITEMS.ID.eq(parent.getId())) - .execute(); - statusStarted.countDown(); - await(releaseStatus); - return null; - })); + executor.submit(() -> + statusDsl.transactionResult(configuration -> { + configuration + .dsl() + .update(SCRIPT_WORK_ITEMS) + .set(SCRIPT_WORK_ITEMS.STATUS, "DEAD_LETTERED") + .where(SCRIPT_WORK_ITEMS.ID.eq(parent.getId())) + .execute(); + statusStarted.countDown(); + await(releaseStatus); + return null; + })); assertThat(statusStarted.await(5, TimeUnit.SECONDS)).isTrue(); AtomicLong cleanupBackendPid = new AtomicLong(); CountDownLatch cleanupStarted = new CountDownLatch(1); DSLContext cleanupDsl = newDsl("automation-retention-status-cleanup-" + System.nanoTime()); Future cleanup = - executor.submit( - () -> - cleanupDsl.transactionResult( - configuration -> { - DSLContext transactionDsl = configuration.dsl(); - cleanupBackendPid.set(currentBackendPid(transactionDsl)); - cleanupStarted.countDown(); - return new ScriptHandoffEventRepository(transactionDsl) - .deleteExpiredRetentionEvidence(cutoff, now); - })); + executor.submit(() -> + cleanupDsl.transactionResult(configuration -> { + DSLContext transactionDsl = configuration.dsl(); + cleanupBackendPid.set(currentBackendPid(transactionDsl)); + cleanupStarted.countDown(); + return new ScriptHandoffEventRepository(transactionDsl) + .deleteExpiredRetentionEvidence(cutoff, now); + })); assertThat(cleanupStarted.await(5, TimeUnit.SECONDS)).isTrue(); awaitPostgresLockWait(cleanupBackendPid.get()); releaseStatus.countDown(); diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresFixture.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresFixture.java index e193216ed5..be6de2cc29 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresFixture.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresFixture.java @@ -131,10 +131,9 @@ private static TemplateConfigSourceSnapshot templateSnapshot( DraftCommitBinding authored = authoredBinding(declarationPayload); TemplateConfigOwnerSourceInventoryDeclaration ownerDeclaration = TemplateConfigSourceValues.mutations(authored).stream() - .filter( - mutation -> - mutation.operation() - == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .filter(mutation -> + mutation.operation() + == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) .findFirst() .orElseThrow(); @@ -364,15 +363,14 @@ private static PublicEvidence publicInventory( 0, 0, selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .map(unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) .toList(), emptyInboundClosure()); var ownerScope = diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java index cc9ff1c293..320e25f561 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java @@ -227,12 +227,11 @@ void repeatableReadWritersFailWhenReservationRequiresReadCommittedIsolation() try (Connection staleRowWriter = repeatableReadSnapshot()) { commitCanonicalEmptySourceFixture(9301L, 9302L); try { - assertThatThrownBy( - () -> - execute( - staleRowWriter, - "INSERT INTO scripts (tenant_id, name, version, definition) " - + "VALUES (9301, 'stale-snapshot-script', 'v1', '{}')")) + assertThatThrownBy(() -> + execute( + staleRowWriter, + "INSERT INTO scripts (tenant_id, name, version, definition) " + + "VALUES (9301, 'stale-snapshot-script', 'v1', '{}')")) .isInstanceOf(SQLException.class) .hasMessageContaining( "Automation authored-source row writes require READ COMMITTED isolation"); diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java index 4eaf8de2f1..a485ad8f6c 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java @@ -242,14 +242,13 @@ void retainsCanonicalEmptyCensusAndExactReadbackAcrossCorrelationIndependentRetr assertThat(unchangedReceipt).isNotNull(); assertThat(unchangedReceipt.get(0, byte[].class)).containsExactly(first.canonicalBytes()); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE automation_empty_selected_source_receipt SET receipt_bytes = ? " - + "WHERE target_namespace = ? AND intake_request_id = ?", - first.canonicalBytes(), - first.targetNamespace(), - first.intakeRequestId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE automation_empty_selected_source_receipt SET receipt_bytes = ? " + + "WHERE target_namespace = ? AND intake_request_id = ?", + first.canonicalBytes(), + first.targetNamespace(), + first.intakeRequestId())) .rootCause() .hasMessageContaining("Automation empty-source intake records are immutable"); @@ -276,12 +275,11 @@ void retainsCanonicalEmptyCensusAndExactReadbackAcrossCorrelationIndependentRetr } assertThatThrownBy(() -> repository.readCommittedTerminal(fixture.authorization())) .isInstanceOf(AutomationEmptySelectedSourceIntakeRepository.CorruptReceiptException.class); - assertThatThrownBy( - () -> - repository.readPublicationScope( - AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, - AutomationEmptySelectedSourceIntakePostgresFixture.TENANT, - fixture.authorization().selected().target().gameDesignVersionRowId())) + assertThatThrownBy(() -> + repository.readPublicationScope( + AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, + AutomationEmptySelectedSourceIntakePostgresFixture.TENANT, + fixture.authorization().selected().target().gameDesignVersionRowId())) .isInstanceOf(AutomationEmptySelectedSourceIntakeRepository.CorruptReceiptException.class); } @@ -325,10 +323,8 @@ void priorCanonicalScopeStillProducesTheIntakeConflict() { 90003L, 90004L); - assertThatThrownBy( - () -> - repository.retainFresh( - conflictingFixture.inputs(), requestDigest(conflictingFixture))) + assertThatThrownBy(() -> + repository.retainFresh(conflictingFixture.inputs(), requestDigest(conflictingFixture))) .isInstanceOf(AutomationEmptySelectedSourceIntakeRepository.IntakeConflictException.class) .hasMessage("Automation canonical scope or owner operation is already associated"); } @@ -350,12 +346,11 @@ void selectedEmptyPublicationReaderUsesTheRetainedTargetProofAndReturnsSchemaSix gameDesignVersionRowId) .canonicalBytes()) .containsExactly(receipt.canonicalBytes()); - assertThatThrownBy( - () -> - repository.readPublicationScope( - AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, - AutomationEmptySelectedSourceIntakePostgresFixture.TENANT, - gameDesignVersionRowId + 1L)) + assertThatThrownBy(() -> + repository.readPublicationScope( + AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, + AutomationEmptySelectedSourceIntakePostgresFixture.TENANT, + gameDesignVersionRowId + 1L)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("missing or ambiguous"); @@ -394,15 +389,14 @@ void selectedEmptyPublicationReaderUsesTheRetainedTargetProofAndReturnsSchemaSix receipt.targetNamespace(), receipt.intakeRequestId()) .get(0, String.class); - assertThatThrownBy( - () -> - new AutomationSelectedEmptyPublicationDigestService( - AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, repository) - .getDraftDesignDigest( - PublicationDigestRequestBinding.full( - AutomationEmptySelectedSourceIntakePostgresFixture.TENANT.toString(), - Long.toString(gameDesignVersionRowId), - "publish-request-2"))) + assertThatThrownBy(() -> + new AutomationSelectedEmptyPublicationDigestService( + AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, repository) + .getDraftDesignDigest( + PublicationDigestRequestBinding.full( + AutomationEmptySelectedSourceIntakePostgresFixture.TENANT.toString(), + Long.toString(gameDesignVersionRowId), + "publish-request-2"))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("original retained World freeze"); String rowAfterMismatchedPublicationRead = diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeServiceIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeServiceIntegrationTest.java index cf01ece9cb..1de1319011 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeServiceIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeServiceIntegrationTest.java @@ -74,14 +74,12 @@ void freshTypedInputsReachRepositoryOnlyAfterTwoAccountEchoesAndWorldEcho() { when(repository.retainFresh(any(SelectedOwnerEmptySourceInputs.class), anyString())) .thenReturn(receipt); when(accountClient.read(any())) - .thenAnswer( - invocation -> - new SelectedOwnerIntakeAuthorizationReadEvidence(invocation.getArgument(0))); + .thenAnswer(invocation -> + new SelectedOwnerIntakeAuthorizationReadEvidence(invocation.getArgument(0))); when(worldClient.read(any())) - .thenAnswer( - invocation -> - new SelectedOwnerWorldInventoryReadEvidence( - invocation.getArgument(0), fixture.worldEvidence().inventory())); + .thenAnswer(invocation -> + new SelectedOwnerWorldInventoryReadEvidence( + invocation.getArgument(0), fixture.worldEvidence().inventory())); var service = new AutomationEmptySelectedSourceIntakeService( @@ -164,46 +162,40 @@ void unavailableOrMismatchedAccountAndWorldEchoesNeverReachFreshRetention() { AtomicInteger accountReads = new AtomicInteger(); when(accountClient.read(any())) - .thenAnswer( - invocation -> { - var request = - invocation.getArgument( - 0, SelectedOwnerIntakeAuthorizationReadEvidence.Request.class); - int call = accountReads.incrementAndGet(); - if (failure == ReadFailure.FIRST_ACCOUNT_UNAVAILABLE && call == 1 - || failure == ReadFailure.FINAL_ACCOUNT_UNAVAILABLE && call == 2) { - return null; - } - if (failure == ReadFailure.FIRST_ACCOUNT_MISMATCH && call == 1 - || failure == ReadFailure.FINAL_ACCOUNT_MISMATCH && call == 2) { - request = mismatched(request); - } - return new SelectedOwnerIntakeAuthorizationReadEvidence(request); - }); + .thenAnswer(invocation -> { + var request = + invocation.getArgument( + 0, SelectedOwnerIntakeAuthorizationReadEvidence.Request.class); + int call = accountReads.incrementAndGet(); + if (failure == ReadFailure.FIRST_ACCOUNT_UNAVAILABLE && call == 1 + || failure == ReadFailure.FINAL_ACCOUNT_UNAVAILABLE && call == 2) { + return null; + } + if (failure == ReadFailure.FIRST_ACCOUNT_MISMATCH && call == 1 + || failure == ReadFailure.FINAL_ACCOUNT_MISMATCH && call == 2) { + request = mismatched(request); + } + return new SelectedOwnerIntakeAuthorizationReadEvidence(request); + }); AtomicInteger worldReads = new AtomicInteger(); when(worldClient.read(any())) - .thenAnswer( - invocation -> { - var request = - invocation.getArgument( - 0, SelectedOwnerWorldInventoryReadEvidence.Request.class); - worldReads.incrementAndGet(); - if (failure == ReadFailure.WORLD_UNAVAILABLE) return null; - if (failure == ReadFailure.WORLD_MISMATCH) request = mismatched(request); - return new SelectedOwnerWorldInventoryReadEvidence( - request, fixture.worldEvidence().inventory()); - }); + .thenAnswer(invocation -> { + var request = + invocation.getArgument(0, SelectedOwnerWorldInventoryReadEvidence.Request.class); + worldReads.incrementAndGet(); + if (failure == ReadFailure.WORLD_UNAVAILABLE) return null; + if (failure == ReadFailure.WORLD_MISMATCH) request = mismatched(request); + return new SelectedOwnerWorldInventoryReadEvidence( + request, fixture.worldEvidence().inventory()); + }); var service = new AutomationEmptySelectedSourceIntakeService( repository, accountClient, worldClient, NAMESPACE); - assertThatThrownBy( - () -> - withGameDesignPeer( - () -> - service.retain( - NAMESPACE, fixture.authorization(), fixture.freezeEvidence()))) + assertThatThrownBy(() -> + withGameDesignPeer(() -> + service.retain(NAMESPACE, fixture.authorization(), fixture.freezeEvidence()))) .as(failure.name()) .isInstanceOf(IllegalStateException.class); diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java index 113ea88800..1e7843ed46 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -64,11 +64,10 @@ void actualConfiguredHistoryNotHardcodedHistoryBindsInstallation() throws Except try (Fixture f = fixture(null, history)) { var evidence = f.owner().read(request()); assertThat(evidence.catalog().families()) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo(history); - assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.CONTROL_ONLY); - }); + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo(history); + assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.CONTROL_ONLY); + }); assertThat(f.owner().readExact(evidence.request())).isEqualTo(evidence); assertThat( f.dsl @@ -101,32 +100,28 @@ void completeLiveCensusIncludesEveryEmptyTableAndExplicitBlockingFamiliesAndNonS "script_work_items", "plugin_runtime_states")) { assertThat(catalog.families()) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo(name); - assertThat(family.stateClass()).isEqualTo(StateClass.UNKNOWN); - assertThat(family.freshDisposition()) - .isEqualTo(FreshDisposition.STATE_CLASS_UNKNOWN_BLOCKING); - }); + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo(name); + assertThat(family.stateClass()).isEqualTo(StateClass.UNKNOWN); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.STATE_CLASS_UNKNOWN_BLOCKING); + }); } assertThat(catalog.families()) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo("faction_standing"); - assertThat(family.stateClass()).isEqualTo(StateClass.UNRESOLVED); - assertThat(family.freshDisposition()) - .isEqualTo(FreshDisposition.OWNERSHIP_DRIFT_BLOCKING); - assertThat(family.ownerConsequence()) - .contains( - "Social", "retained-row disposition", "not Automation FRESH ownership"); - }) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo("script_schedule_instances"); - assertThat(family.stateClass()).isEqualTo(StateClass.S2); - assertThat(family.freshDisposition()) - .isEqualTo(FreshDisposition.NAMESPACE_MAPPING_BLOCKING); - }); + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo("faction_standing"); + assertThat(family.stateClass()).isEqualTo(StateClass.UNRESOLVED); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.OWNERSHIP_DRIFT_BLOCKING); + assertThat(family.ownerConsequence()) + .contains("Social", "retained-row disposition", "not Automation FRESH ownership"); + }) + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo("script_schedule_instances"); + assertThat(family.stateClass()).isEqualTo(StateClass.S2); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.NAMESPACE_MAPPING_BLOCKING); + }); assertThat(catalog.families()) .anyMatch(family -> family.familyId().equals("saga_instance")) .anyMatch(family -> family.familyId().equals("saga_step")) @@ -142,11 +137,10 @@ void completeLiveCensusIncludesEveryEmptyTableAndExplicitBlockingFamiliesAndNonS GapId.QUEUE_DISCOVERY_AND_ENCODING, GapId.QUEUE_POINTER_RETENTION); assertThat(catalog.families()) - .noneMatch( - family -> - family.familyId().contains("charge_record") - || family.familyId().equals("redis_queue") - || family.familyId().equals("script_firing_claims")); + .noneMatch(family -> + family.familyId().contains("charge_record") + || family.familyId().equals("redis_queue") + || family.familyId().equals("script_firing_claims")); assertThat(catalog.schemaFacts()) .anyMatch(fact -> fact.kind() == FactKind.ROUTINE) .anyMatch(fact -> fact.kind() == FactKind.MIGRATION) @@ -225,10 +219,9 @@ void forwardUpgradePreservesPopulatedPredecessorRowsHistorySequencesAndSourceGua assertThatThrownBy( () -> f.dsl.execute("DELETE FROM automation_empty_source_numeric_key_reservation")) .hasMessageContaining("immutable"); - assertThatThrownBy( - () -> - f.dsl.execute( - "INSERT INTO scripts(tenant_id,name,version,definition) VALUES(1,'forbidden','patch','{}')")) + assertThatThrownBy(() -> + f.dsl.execute( + "INSERT INTO scripts(tenant_id,name,version,definition) VALUES(1,'forbidden','patch','{}')")) .hasMessageContaining("reserved by an immutable empty-source receipt"); migration(f.source, f.schema, f.history, null).validate(); } @@ -332,10 +325,9 @@ void removalClassificationAndNonSqlGapChangesInvalidateWithoutOverwritingEvidenc read.readRequestId()) .get(0, byte[].class)) .isEqualTo(AutomationRuntimeFamilyCatalogCodec.evidenceBytes(original)); - assertThatThrownBy( - () -> - f.dsl.execute( - "UPDATE automation_runtime_catalog_non_sql_gap SET disposition='UNRESOLVED_BLOCKING'")) + assertThatThrownBy(() -> + f.dsl.execute( + "UPDATE automation_runtime_catalog_non_sql_gap SET disposition='UNRESOLVED_BLOCKING'")) .hasMessageContaining("immutable"); } } @@ -404,13 +396,12 @@ void metadataEpochSnapshotRetentionAndCompleteSqlFrameBindingCannotBeBypassed() try (Fixture f = fixture(null)) { var original = f.owner().read(request()); for (String consequence : List.of(" ", "\t")) { - assertThatThrownBy( - () -> - f.dsl.execute( - "INSERT INTO automation_runtime_family_classification VALUES" - + " ('npc_memory.value','npc_memory','value','RUNTIME_PAYLOAD','UNKNOWN'," - + "'STATE_CLASS_UNKNOWN_BLOCKING','UNRESOLVED_RETAINED',?)", - consequence)) + assertThatThrownBy(() -> + f.dsl.execute( + "INSERT INTO automation_runtime_family_classification VALUES" + + " ('npc_memory.value','npc_memory','value','RUNTIME_PAYLOAD','UNKNOWN'," + + "'STATE_CLASS_UNKNOWN_BLOCKING','UNRESOLVED_RETAINED',?)", + consequence)) .hasMessageContaining("ck_automation_runtime_family_consequence"); } for (String table : @@ -423,35 +414,32 @@ void metadataEpochSnapshotRetentionAndCompleteSqlFrameBindingCannotBeBypassed() .hasMessageContaining("immutable"); assertThatThrownBy(() -> f.dsl.execute("TRUNCATE " + table + " CASCADE")) .hasMessageContaining("immutable"); - assertThatThrownBy( - () -> - f.dsl.execute( - "UPDATE " - + table - + " SET " - + (table.equals("automation_runtime_family_classification") - ? "family_id=family_id" - : table.equals("automation_runtime_catalog_non_sql_gap") - ? "gap_id=gap_id" - : "catalog_epoch=catalog_epoch"))) + assertThatThrownBy(() -> + f.dsl.execute( + "UPDATE " + + table + + " SET " + + (table.equals("automation_runtime_family_classification") + ? "family_id=family_id" + : table.equals("automation_runtime_catalog_non_sql_gap") + ? "gap_id=gap_id" + : "catalog_epoch=catalog_epoch"))) .hasMessageContaining("immutable"); } - assertThatThrownBy( - () -> - f.dsl.execute( - "INSERT INTO automation_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 3,catalog_bytes,catalog_digest FROM automation_runtime_family_catalog_epoch WHERE catalog_epoch=2")) + assertThatThrownBy(() -> + f.dsl.execute( + "INSERT INTO automation_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" + + " SELECT 3,catalog_bytes,catalog_digest FROM automation_runtime_family_catalog_epoch WHERE catalog_epoch=2")) .hasMessageContaining("exact classified installed schema"); - assertThatThrownBy( - () -> - f.dsl.execute( - "INSERT INTO automation_runtime_family_catalog_snapshot" - + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id,catalog_epoch,catalog_digest,evidence_bytes,evidence_digest)" - + " SELECT ?,target_namespace,request_bytes,request_digest,?,catalog_epoch,catalog_digest,evidence_bytes,evidence_digest" - + " FROM automation_runtime_family_catalog_snapshot WHERE read_request_id=?", - UUID.randomUUID(), - UUID.randomUUID(), - original.request().readRequestId())) + assertThatThrownBy(() -> + f.dsl.execute( + "INSERT INTO automation_runtime_family_catalog_snapshot" + + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id,catalog_epoch,catalog_digest,evidence_bytes,evidence_digest)" + + " SELECT ?,target_namespace,request_bytes,request_digest,?,catalog_epoch,catalog_digest,evidence_bytes,evidence_digest" + + " FROM automation_runtime_family_catalog_snapshot WHERE read_request_id=?", + UUID.randomUUID(), + UUID.randomUUID(), + original.request().readRequestId())) .hasMessageContaining("complete exact request and evidence"); assertThat(f.count("automation_runtime_family_catalog_snapshot")).isEqualTo(1); } @@ -469,10 +457,9 @@ void realProducerReturnsCompleteCorrelatedEvidenceWithoutRuntimeWritesAndRejects .orElseThrow(); Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .run( - () -> - service.readAutomationRuntimeFamilyCatalog( - AutomationRuntimeFamilyCatalogCodec.toRequest(read), collector)); + .run(() -> + service.readAutomationRuntimeFamilyCatalog( + AutomationRuntimeFamilyCatalogCodec.toRequest(read), collector)); assertThat(collector.error).isNull(); assertThat(collector.completed).isTrue(); var evidence = AutomationRuntimeFamilyCatalogCodec.fromResponse(read, collector.value); @@ -505,21 +492,20 @@ void viewSecurityOptionsInvalidateReadRetryAndFreshCaptureWithoutChangingRetaine var original = f.owner().read(read); assertThat(original.catalog().catalogEpoch()).isEqualTo(2); assertThat(original.catalog().schemaFacts()) - .anySatisfy( - fact -> { - assertThat(fact.kind()).isEqualTo(FactKind.VIEW); - assertThat(fact.identity()).isEqualTo("catalog_security_probe"); - assertThat(fact.definitionDigest()) - .isEqualTo( - f.dsl - .fetchSingle( - "SELECT 'sha256:'||encode(sha256(convert_to(" - + "jsonb_build_array(pg_get_viewdef(c.oid,true),c.reloptions)::text,'UTF8')),'hex')" - + " FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace" - + " WHERE n.nspname=? AND c.relname='catalog_security_probe'", - f.schema) - .get(0, String.class)); - }); + .anySatisfy(fact -> { + assertThat(fact.kind()).isEqualTo(FactKind.VIEW); + assertThat(fact.identity()).isEqualTo("catalog_security_probe"); + assertThat(fact.definitionDigest()) + .isEqualTo( + f.dsl + .fetchSingle( + "SELECT 'sha256:'||encode(sha256(convert_to(" + + "jsonb_build_array(pg_get_viewdef(c.oid,true),c.reloptions)::text,'UTF8')),'hex')" + + " FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace" + + " WHERE n.nspname=? AND c.relname='catalog_security_probe'", + f.schema) + .get(0, String.class)); + }); assertThat(f.owner().read(read)).isEqualTo(original); assertThat(f.owner().readExact(read)).isEqualTo(original); String definition = @@ -597,15 +583,14 @@ void catalogViewOptionsUpgradeRetainsV1004DataHistoryEpochAndSnapshot() throws E ? "V1004__automation_owner_runtime_family_catalog.sql" : "V1005__automation_catalog_view_options.sql"; assertThat(current.catalog().schemaFacts()) - .anySatisfy( - fact -> { - assertThat(fact.kind()).isEqualTo(FactKind.MIGRATION); - assertThat(fact.identity()).isEqualTo("catalog-installation:" + version); - assertThat(fact.definitionDigest()) - .isEqualTo( - AutomationRuntimeFamilyCatalog.sha256( - script.getBytes(java.nio.charset.StandardCharsets.UTF_8))); - }); + .anySatisfy(fact -> { + assertThat(fact.kind()).isEqualTo(FactKind.MIGRATION); + assertThat(fact.identity()).isEqualTo("catalog-installation:" + version); + assertThat(fact.definitionDigest()) + .isEqualTo( + AutomationRuntimeFamilyCatalog.sha256( + script.getBytes(java.nio.charset.StandardCharsets.UTF_8))); + }); } migration(f.source, f.schema, f.history, null).validate(); } diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java index b626b27d1e..469bc09184 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java @@ -176,10 +176,9 @@ void readsStoredCommittedEmptyReceiptOverAccountMtlsAndRejectsWrongNamespace() t wrongClient.init(); assertThatThrownBy(() -> wrongClient.read(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - e -> - assertThat(Status.fromThrowable(e).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(e -> + assertThat(Status.fromThrowable(e).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } finally { wrongClient.close(); } diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/PluginRuntimeLifecycleFenceIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/PluginRuntimeLifecycleFenceIntegrationTest.java index 6c89c99e18..f6094a442c 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/PluginRuntimeLifecycleFenceIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/PluginRuntimeLifecycleFenceIntegrationTest.java @@ -114,25 +114,21 @@ void failedReceiptIsImmutableAndLifecycleAdvisoryLockSerializesConcurrentActivat ExecutorService executor = Executors.newFixedThreadPool(2); try { Future firstTransaction = - executor.submit( - () -> - dsl.transaction( - configuration -> { - new PluginRuntimeStateRepository(DSL.using(configuration)) - .lockLifecycleScope("1", "game-1", "plugin-1"); - firstHasLock.countDown(); - await(releaseFirst); - })); + executor.submit(() -> + dsl.transaction(configuration -> { + new PluginRuntimeStateRepository(DSL.using(configuration)) + .lockLifecycleScope("1", "game-1", "plugin-1"); + firstHasLock.countDown(); + await(releaseFirst); + })); assertThat(firstHasLock.await(5, TimeUnit.SECONDS)).isTrue(); Future secondTransaction = - executor.submit( - () -> - dsl.transaction( - configuration -> { - secondReachedLockCall.countDown(); - new PluginRuntimeStateRepository(DSL.using(configuration)) - .lockLifecycleScope("1", "game-1", "plugin-1"); - })); + executor.submit(() -> + dsl.transaction(configuration -> { + secondReachedLockCall.countDown(); + new PluginRuntimeStateRepository(DSL.using(configuration)) + .lockLifecycleScope("1", "game-1", "plugin-1"); + })); assertThat(secondReachedLockCall.await(5, TimeUnit.SECONDS)).isTrue(); Thread.sleep(100); assertThat(secondTransaction.isDone()).isFalse(); @@ -161,26 +157,22 @@ void lifecycleAdvisoryLockDoesNotSerializeJavaHashCollidingScopes() throws Excep Future secondTransaction = null; try { firstTransaction = - executor.submit( - () -> - dsl.transaction( - configuration -> { - new PluginRuntimeStateRepository(DSL.using(configuration)) - .lockLifecycleScope("tenant-1", "game-1", firstPluginId); - firstHasLock.countDown(); - await(releaseFirst); - })); + executor.submit(() -> + dsl.transaction(configuration -> { + new PluginRuntimeStateRepository(DSL.using(configuration)) + .lockLifecycleScope("tenant-1", "game-1", firstPluginId); + firstHasLock.countDown(); + await(releaseFirst); + })); assertThat(firstHasLock.await(5, TimeUnit.SECONDS)).isTrue(); secondTransaction = - executor.submit( - () -> - dsl.transaction( - configuration -> { - secondReachedLockCall.countDown(); - new PluginRuntimeStateRepository(DSL.using(configuration)) - .lockLifecycleScope("tenant-1", "game-1", secondPluginId); - secondHasLock.countDown(); - })); + executor.submit(() -> + dsl.transaction(configuration -> { + secondReachedLockCall.countDown(); + new PluginRuntimeStateRepository(DSL.using(configuration)) + .lockLifecycleScope("tenant-1", "game-1", secondPluginId); + secondHasLock.countDown(); + })); assertThat(secondReachedLockCall.await(5, TimeUnit.SECONDS)).isTrue(); assertThat(secondHasLock.await(5, TimeUnit.SECONDS)).isTrue(); releaseFirst.countDown(); @@ -194,76 +186,74 @@ void lifecycleAdvisoryLockDoesNotSerializeJavaHashCollidingScopes() throws Excep @Test void nextEligibleDefaultUsesUtcWhenSessionTimezoneIsNonUtc() { - dsl.transaction( - configuration -> { - DSLContext transactionDsl = DSL.using(configuration); - transactionDsl.execute("SET LOCAL TIME ZONE 'Pacific/Auckland'"); - transactionDsl.execute( - "insert into script_work_items " - + "(tenant_id, game_instance_id, region_id, region_epoch, entity_id, script_id, " - + "plugin_id, plugin_version_id, event_type, event_schema_version, " - + "script_patch_version, script_event_id, source_service, trigger_mode) " - + "values ('tenant-utc', 'instance-utc', 'region-1', 1, 'entity-1', 'script-1', " - + "'plugin-1', 'version-1', 'onCommand', '1', 'patch-1', " - + "'event-utc-default', 'test', 'MANUAL')"); - - assertThat( - transactionDsl.fetchValue( - "select next_eligible_at = pg_catalog.timezone('UTC', current_timestamp) " - + "from script_work_items where script_event_id = 'event-utc-default'", - Boolean.class)) - .isEqualTo(Boolean.TRUE); - }); + dsl.transaction(configuration -> { + DSLContext transactionDsl = DSL.using(configuration); + transactionDsl.execute("SET LOCAL TIME ZONE 'Pacific/Auckland'"); + transactionDsl.execute( + "insert into script_work_items " + + "(tenant_id, game_instance_id, region_id, region_epoch, entity_id, script_id, " + + "plugin_id, plugin_version_id, event_type, event_schema_version, " + + "script_patch_version, script_event_id, source_service, trigger_mode) " + + "values ('tenant-utc', 'instance-utc', 'region-1', 1, 'entity-1', 'script-1', " + + "'plugin-1', 'version-1', 'onCommand', '1', 'patch-1', " + + "'event-utc-default', 'test', 'MANUAL')"); + + assertThat( + transactionDsl.fetchValue( + "select next_eligible_at = pg_catalog.timezone('UTC', current_timestamp) " + + "from script_work_items where script_event_id = 'event-utc-default'", + Boolean.class)) + .isEqualTo(Boolean.TRUE); + }); } @Test void retryEligibilityUsesUtcWhenSessionTimezoneIsNonUtc() { - dsl.transaction( - configuration -> { - DSLContext transactionDsl = DSL.using(configuration); - transactionDsl.execute("SET LOCAL TIME ZONE 'Pacific/Auckland'"); - transactionDsl.execute( - "insert into script_work_items " - + "(tenant_id, game_instance_id, region_id, region_epoch, entity_id, script_id, " - + "plugin_id, plugin_version_id, event_type, event_schema_version, " - + "script_patch_version, script_event_id, source_service, trigger_mode) " - + "values ('tenant-utc', 'instance-utc', 'region-1', 1, 'entity-1', 'script-1', " - + "'plugin-1', 'version-1', 'onCommand', '1', 'patch-1', " - + "'event-utc-retry', 'test', 'MANUAL')"); - Long workItemId = - transactionDsl - .fetchSingle( - "select id from script_work_items where script_event_id = 'event-utc-retry'") - .get("id", Long.class); - assertThat(workItemId).isNotNull(); - transactionDsl.execute( - "update script_work_items " - + "set next_eligible_at = pg_catalog.timezone('UTC', current_timestamp) " - + "+ interval '1 hour' where script_event_id = 'event-utc-retry'"); - - ScriptWorkItemRepository repository = new ScriptWorkItemRepository(transactionDsl); - Instant futureEligibleAt = Instant.now().plusSeconds(86_400); - assertThat( - repository.findByIdInAndStatusForUpdateOrderByCreatedAtAscIdAsc( - List.of(workItemId), - "PENDING_EVALUATION", - futureEligibleAt, - PageRequest.of(0, 10))) - .isEmpty(); - - transactionDsl.execute( - "update script_work_items " - + "set next_eligible_at = pg_catalog.timezone('UTC', current_timestamp) " - + "- interval '1 minute' where script_event_id = 'event-utc-retry'"); - - assertThat( - repository.findByIdInAndStatusForUpdateOrderByCreatedAtAscIdAsc( - List.of(workItemId), - "PENDING_EVALUATION", - futureEligibleAt, - PageRequest.of(0, 10))) - .hasSize(1); - }); + dsl.transaction(configuration -> { + DSLContext transactionDsl = DSL.using(configuration); + transactionDsl.execute("SET LOCAL TIME ZONE 'Pacific/Auckland'"); + transactionDsl.execute( + "insert into script_work_items " + + "(tenant_id, game_instance_id, region_id, region_epoch, entity_id, script_id, " + + "plugin_id, plugin_version_id, event_type, event_schema_version, " + + "script_patch_version, script_event_id, source_service, trigger_mode) " + + "values ('tenant-utc', 'instance-utc', 'region-1', 1, 'entity-1', 'script-1', " + + "'plugin-1', 'version-1', 'onCommand', '1', 'patch-1', " + + "'event-utc-retry', 'test', 'MANUAL')"); + Long workItemId = + transactionDsl + .fetchSingle( + "select id from script_work_items where script_event_id = 'event-utc-retry'") + .get("id", Long.class); + assertThat(workItemId).isNotNull(); + transactionDsl.execute( + "update script_work_items " + + "set next_eligible_at = pg_catalog.timezone('UTC', current_timestamp) " + + "+ interval '1 hour' where script_event_id = 'event-utc-retry'"); + + ScriptWorkItemRepository repository = new ScriptWorkItemRepository(transactionDsl); + Instant futureEligibleAt = Instant.now().plusSeconds(86_400); + assertThat( + repository.findByIdInAndStatusForUpdateOrderByCreatedAtAscIdAsc( + List.of(workItemId), + "PENDING_EVALUATION", + futureEligibleAt, + PageRequest.of(0, 10))) + .isEmpty(); + + transactionDsl.execute( + "update script_work_items " + + "set next_eligible_at = pg_catalog.timezone('UTC', current_timestamp) " + + "- interval '1 minute' where script_event_id = 'event-utc-retry'"); + + assertThat( + repository.findByIdInAndStatusForUpdateOrderByCreatedAtAscIdAsc( + List.of(workItemId), + "PENDING_EVALUATION", + futureEligibleAt, + PageRequest.of(0, 10))) + .hasSize(1); + }); } @Test @@ -473,57 +463,52 @@ void migrationFailsClosedOnRetainedEnabledRuntimeWithoutActiveVersion() { @Test void databaseRejectsIncoherentAndNegativePluginFencePairs() { - assertThatThrownBy( - () -> - dsl.execute( - "insert into plugin_runtime_states " - + "(tenant_id, game_instance_id, plugin_id, active_plugin_version_id, " - + "plugin_state, status_reason, plugin_activation_epoch, lifecycle_revision) " - + "values ('tenant-invalid', 'instance-active-zero', 'plugin-invalid', " - + "'version-active', 'PLUGIN_STATE_ENABLED', 'invalid', 0, 0)")) + assertThatThrownBy(() -> + dsl.execute( + "insert into plugin_runtime_states " + + "(tenant_id, game_instance_id, plugin_id, active_plugin_version_id, " + + "plugin_state, status_reason, plugin_activation_epoch, lifecycle_revision) " + + "values ('tenant-invalid', 'instance-active-zero', 'plugin-invalid', " + + "'version-active', 'PLUGIN_STATE_ENABLED', 'invalid', 0, 0)")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("ck_plugin_runtime_states_plugin_fence"); - assertThatThrownBy( - () -> - dsl.execute( - "insert into plugin_runtime_states " - + "(tenant_id, game_instance_id, plugin_id, plugin_state, " - + "status_reason, plugin_activation_epoch, lifecycle_revision) " - + "values ('tenant-invalid', 'instance-incoherent', 'plugin-invalid', " - + "'DISABLED', 'invalid', 1, 0)")) + assertThatThrownBy(() -> + dsl.execute( + "insert into plugin_runtime_states " + + "(tenant_id, game_instance_id, plugin_id, plugin_state, " + + "status_reason, plugin_activation_epoch, lifecycle_revision) " + + "values ('tenant-invalid', 'instance-incoherent', 'plugin-invalid', " + + "'DISABLED', 'invalid', 1, 0)")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("ck_plugin_runtime_states_plugin_fence"); - assertThatThrownBy( - () -> - dsl.execute( - "insert into plugin_runtime_states " - + "(tenant_id, game_instance_id, plugin_id, plugin_state, " - + "status_reason, plugin_activation_epoch, lifecycle_revision) " - + "values ('tenant-invalid', 'instance-negative', 'plugin-invalid', " - + "'DISABLED', 'invalid', -1, -1)")) + assertThatThrownBy(() -> + dsl.execute( + "insert into plugin_runtime_states " + + "(tenant_id, game_instance_id, plugin_id, plugin_state, " + + "status_reason, plugin_activation_epoch, lifecycle_revision) " + + "values ('tenant-invalid', 'instance-negative', 'plugin-invalid', " + + "'DISABLED', 'invalid', -1, -1)")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("ck_plugin_runtime_states_plugin_fence"); - assertThatThrownBy( - () -> - dsl.execute( - "insert into plugin_runtime_request_history " - + "(tenant_id, game_instance_id, plugin_id, operation, " - + "control_plane_request_id, request_fingerprint, plugin_state, " - + "plugin_activation_epoch, lifecycle_revision) " - + "values ('tenant-invalid', 'instance-incoherent', 'plugin-invalid', " - + "'DISABLE', 'request-incoherent', 'fingerprint', 'DISABLED', 1, 0)")) + assertThatThrownBy(() -> + dsl.execute( + "insert into plugin_runtime_request_history " + + "(tenant_id, game_instance_id, plugin_id, operation, " + + "control_plane_request_id, request_fingerprint, plugin_state, " + + "plugin_activation_epoch, lifecycle_revision) " + + "values ('tenant-invalid', 'instance-incoherent', 'plugin-invalid', " + + "'DISABLE', 'request-incoherent', 'fingerprint', 'DISABLED', 1, 0)")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("ck_plugin_runtime_request_history_plugin_fence"); - assertThatThrownBy( - () -> - dsl.execute( - "insert into plugin_runtime_request_history " - + "(tenant_id, game_instance_id, plugin_id, operation, " - + "control_plane_request_id, request_fingerprint, plugin_state, " - + "plugin_activation_epoch, lifecycle_revision) " - + "values ('tenant-invalid', 'instance-negative', 'plugin-invalid', " - + "'DISABLE', 'request-negative', 'fingerprint', 'DISABLED', -1, -1)")) + assertThatThrownBy(() -> + dsl.execute( + "insert into plugin_runtime_request_history " + + "(tenant_id, game_instance_id, plugin_id, operation, " + + "control_plane_request_id, request_fingerprint, plugin_state, " + + "plugin_activation_epoch, lifecycle_revision) " + + "values ('tenant-invalid', 'instance-negative', 'plugin-invalid', " + + "'DISABLE', 'request-negative', 'fingerprint', 'DISABLED', -1, -1)")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("ck_plugin_runtime_request_history_plugin_fence"); } diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptDefinitionRepositoryIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptDefinitionRepositoryIntegrationTest.java index 3e5bbc663f..1124852d64 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptDefinitionRepositoryIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptDefinitionRepositoryIntegrationTest.java @@ -119,13 +119,12 @@ void concurrentIdenticalFirstWritesReturnOneDurableIdentity() throws Exception { try { for (int i = 0; i < 2; i++) { futures.add( - executor.submit( - () -> { - ready.countDown(); - await(start); - return new ScriptDefinitionRepository(dsl) - .saveWithCreationResult(script("{\"value\":1}")); - })); + executor.submit(() -> { + ready.countDown(); + await(start); + return new ScriptDefinitionRepository(dsl) + .saveWithCreationResult(script("{\"value\":1}")); + })); } assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); @@ -309,12 +308,11 @@ void concurrentDifferingWritesKeepOneIdentityAndExposeDeterministicVersions() th try { for (String definition : List.of(firstDefinition, secondDefinition)) { futures.add( - executor.submit( - () -> { - ready.countDown(); - await(start); - return new ScriptDefinitionRepository(dsl).save(script(definition)); - })); + executor.submit(() -> { + ready.countDown(); + await(start); + return new ScriptDefinitionRepository(dsl).save(script(definition)); + })); } assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptPatchReadinessSingletonIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptPatchReadinessSingletonIntegrationTest.java index 27d3ff7440..8aacb07976 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptPatchReadinessSingletonIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptPatchReadinessSingletonIntegrationTest.java @@ -65,17 +65,15 @@ void concurrentPublishesLeaveOneActiveCandidate() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(2); try { Future first = - executor.submit( - () -> { - await(start); - beginInTransaction(transactionalDsl, transactionTemplate, "patch-a"); - }); + executor.submit(() -> { + await(start); + beginInTransaction(transactionalDsl, transactionTemplate, "patch-a"); + }); Future second = - executor.submit( - () -> { - await(start); - beginInTransaction(transactionalDsl, transactionTemplate, "patch-b"); - }); + executor.submit(() -> { + await(start); + beginInTransaction(transactionalDsl, transactionTemplate, "patch-b"); + }); start.countDown(); first.get(10, TimeUnit.SECONDS); second.get(10, TimeUnit.SECONDS); @@ -125,39 +123,34 @@ void newerGenerationWaitsForInFlightApplyAndFencesOldRegistryRebuild() throws Ex new ScriptPatchReadinessProjectionRepository(transactionalDsl), Mockito.mock(ScriptWorkItemRepository.class), transactionalDsl); - transactionTemplate.executeWithoutResult( - status -> - service.beginPatchReadiness("tenant-generation-race", 7L, "patch-old", List.of("a"))); + transactionTemplate.executeWithoutResult(status -> + service.beginPatchReadiness("tenant-generation-race", 7L, "patch-old", List.of("a"))); CountDownLatch oldApplyEntered = new CountDownLatch(1); CountDownLatch releaseOldApply = new CountDownLatch(1); ExecutorService executor = Executors.newFixedThreadPool(2); try { Future oldApply = - executor.submit( - () -> - transactionTemplate.execute( - status -> - service.applyIfCurrent( - "tenant-generation-race", - "patch-old", - List.of("a"), - ignored -> { - transactionalDsl.execute( - "insert into readiness_downstream_effects " - + "(patch_version, effect) values ('patch-old', 'applied')"); - oldApplyEntered.countDown(); - await(releaseOldApply); - }))); + executor.submit(() -> + transactionTemplate.execute(status -> + service.applyIfCurrent( + "tenant-generation-race", + "patch-old", + List.of("a"), + ignored -> { + transactionalDsl.execute( + "insert into readiness_downstream_effects " + + "(patch_version, effect) values ('patch-old', 'applied')"); + oldApplyEntered.countDown(); + await(releaseOldApply); + }))); assertThat(oldApplyEntered.await(5, TimeUnit.SECONDS)).isTrue(); Future newerBegin = - executor.submit( - () -> - transactionTemplate.executeWithoutResult( - status -> - service.beginPatchReadiness( - "tenant-generation-race", 8L, "patch-new", List.of("b")))); + executor.submit(() -> + transactionTemplate.executeWithoutResult(status -> + service.beginPatchReadiness( + "tenant-generation-race", 8L, "patch-new", List.of("b")))); awaitAdvisoryLockWait(dsl); assertThat(newerBegin.isDone()).isFalse(); @@ -171,13 +164,12 @@ void newerGenerationWaitsForInFlightApplyAndFencesOldRegistryRebuild() throws Ex AtomicBoolean oldRegistryRebuilt = new AtomicBoolean(); boolean oldRebuildAccepted = - transactionTemplate.execute( - status -> - service.rebuildRegistryIfCurrent( - "tenant-generation-race", - "patch-old", - List.of("a"), - () -> oldRegistryRebuilt.set(true))); + transactionTemplate.execute(status -> + service.rebuildRegistryIfCurrent( + "tenant-generation-race", + "patch-old", + List.of("a"), + () -> oldRegistryRebuilt.set(true))); assertThat(oldRebuildAccepted).isFalse(); assertThat(oldRegistryRebuilt.get()).isFalse(); assertThat( @@ -206,13 +198,12 @@ void newerGenerationWaitsForInFlightApplyAndFencesOldRegistryRebuild() throws Ex AtomicBoolean staleApplyRan = new AtomicBoolean(); boolean staleApplyAccepted = - transactionTemplate.execute( - status -> - service.applyIfCurrent( - "tenant-generation-race", - "patch-old", - List.of("a"), - ignored -> staleApplyRan.set(true))); + transactionTemplate.execute(status -> + service.applyIfCurrent( + "tenant-generation-race", + "patch-old", + List.of("a"), + ignored -> staleApplyRan.set(true))); assertThat(staleApplyAccepted).isFalse(); assertThat(staleApplyRan.get()).isFalse(); } @@ -233,30 +224,26 @@ void downstreamDatabaseFailureRollsBackWithReadinessProgressAndCanRetry() { new ScriptPatchReadinessProjectionRepository(transactionalDsl), Mockito.mock(ScriptWorkItemRepository.class), transactionalDsl); - transactionTemplate.executeWithoutResult( - status -> - service.beginPatchReadiness( - "tenant-downstream-rollback", 7L, "patch-retry", List.of("a"))); - - assertThatThrownBy( - () -> - transactionTemplate.executeWithoutResult( - status -> - service.applyIfCurrent( - "tenant-downstream-rollback", - "patch-retry", - List.of("a"), - ignored -> { - transactionalDsl.execute( - "insert into readiness_downstream_effects " - + "(patch_version, effect) values " - + "('patch-retry', 'schedule-refresh')"); - transactionalDsl.execute( - "insert into readiness_downstream_effects " - + "(patch_version, effect) values " - + "('patch-retry', 'instance-reconciliation')"); - throw new IllegalStateException("simulated downstream failure"); - }))) + transactionTemplate.executeWithoutResult(status -> + service.beginPatchReadiness("tenant-downstream-rollback", 7L, "patch-retry", List.of("a"))); + + assertThatThrownBy(() -> + transactionTemplate.executeWithoutResult(status -> + service.applyIfCurrent( + "tenant-downstream-rollback", + "patch-retry", + List.of("a"), + ignored -> { + transactionalDsl.execute( + "insert into readiness_downstream_effects " + + "(patch_version, effect) values " + + "('patch-retry', 'schedule-refresh')"); + transactionalDsl.execute( + "insert into readiness_downstream_effects " + + "(patch_version, effect) values " + + "('patch-retry', 'instance-reconciliation')"); + throw new IllegalStateException("simulated downstream failure"); + }))) .isInstanceOf(IllegalStateException.class) .hasMessage("simulated downstream failure"); @@ -278,17 +265,16 @@ void downstreamDatabaseFailureRollsBackWithReadinessProgressAndCanRetry() { .isEqualTo(Boolean.FALSE); boolean retryAccepted = - transactionTemplate.execute( - status -> - service.applyIfCurrent( - "tenant-downstream-rollback", - "patch-retry", - List.of("a"), - ignored -> - transactionalDsl.execute( - "insert into readiness_downstream_effects " - + "(patch_version, effect) values " - + "('patch-retry', 'retry-reconciled')"))); + transactionTemplate.execute(status -> + service.applyIfCurrent( + "tenant-downstream-rollback", + "patch-retry", + List.of("a"), + ignored -> + transactionalDsl.execute( + "insert into readiness_downstream_effects " + + "(patch_version, effect) values " + + "('patch-retry', 'retry-reconciled')"))); assertThat(retryAccepted).isEqualTo(Boolean.TRUE); assertThat( dsl.fetch( @@ -415,15 +401,14 @@ void migrationFailsClosedWhenLegacyUniqueIndexPredicateDrifts() { private void beginInTransaction( DSLContext dsl, TransactionTemplate transactionTemplate, String patchVersion) { - transactionTemplate.executeWithoutResult( - status -> { - ScriptPatchReadinessProjectionRepository repository = - new ScriptPatchReadinessProjectionRepository(dsl); - ScriptPatchReadinessProjectionServiceImpl service = - new ScriptPatchReadinessProjectionServiceImpl( - repository, Mockito.mock(ScriptWorkItemRepository.class), dsl); - service.beginPatchReadiness("tenant-concurrent", 1L, patchVersion, List.of(patchVersion)); - }); + transactionTemplate.executeWithoutResult(status -> { + ScriptPatchReadinessProjectionRepository repository = + new ScriptPatchReadinessProjectionRepository(dsl); + ScriptPatchReadinessProjectionServiceImpl service = + new ScriptPatchReadinessProjectionServiceImpl( + repository, Mockito.mock(ScriptWorkItemRepository.class), dsl); + service.beginPatchReadiness("tenant-concurrent", 1L, patchVersion, List.of(patchVersion)); + }); } private DSLContext migrateToLatest() { diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptPinEpochMigrationAndRolloutEventIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptPinEpochMigrationAndRolloutEventIntegrationTest.java index ae0f36dede..3d6e83fa42 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptPinEpochMigrationAndRolloutEventIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/ScriptPinEpochMigrationAndRolloutEventIntegrationTest.java @@ -185,31 +185,27 @@ void sourceServiceScopesHandlerWorkAndAuditIdentityWhileSameSourceRetriesDedupli void databaseEnforcesIngressPinTupleForPreInstanceAndInstanceRows() { DSLContext dsl = migrateToLatest(); - assertThatThrownBy( - () -> - insertIngressAudit( - dsl, "instance-null-epoch", null, "owner-null-epoch", "event-rejected")) + assertThatThrownBy(() -> + insertIngressAudit( + dsl, "instance-null-epoch", null, "owner-null-epoch", "event-rejected")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("ck_script_event_ingress_audit_pin_tuple"); - assertThatThrownBy( - () -> - insertIngressAudit( - dsl, null, 6L, "owner-null-instance", "event-rejected-null-instance")) + assertThatThrownBy(() -> + insertIngressAudit( + dsl, null, 6L, "owner-null-instance", "event-rejected-null-instance")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("ck_script_event_ingress_audit_pin_tuple"); - assertThatThrownBy( - () -> - insertIngressAudit( - dsl, "instance-positive-null-owner", 7L, null, "event-rejected-null-owner")) + assertThatThrownBy(() -> + insertIngressAudit( + dsl, "instance-positive-null-owner", 7L, null, "event-rejected-null-owner")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("ck_script_event_ingress_audit_pin_tuple"); - assertThatThrownBy( - () -> - insertIngressAudit( - dsl, "instance-positive-blank-owner", 8L, " ", "event-rejected-blank-owner")) + assertThatThrownBy(() -> + insertIngressAudit( + dsl, "instance-positive-blank-owner", 8L, " ", "event-rejected-blank-owner")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("ck_script_event_ingress_audit_pin_tuple"); diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/service/impl/ScriptDefinitionServiceTransactionIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/service/impl/ScriptDefinitionServiceTransactionIntegrationTest.java index cb0cf7a0e5..f16513b578 100644 --- a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/service/impl/ScriptDefinitionServiceTransactionIntegrationTest.java +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/service/impl/ScriptDefinitionServiceTransactionIntegrationTest.java @@ -148,10 +148,9 @@ void scriptPatchBaseBindingIsImmutableAcrossRetries() { status -> definitionRepository.bindScriptPatchBaseVersionId("1", VERSION, 1L)); assertThat(definitionRepository.findScriptPatchBaseVersionId("1", VERSION)).contains(1L); - assertThatThrownBy( - () -> - transactionTemplate.executeWithoutResult( - status -> definitionRepository.bindScriptPatchBaseVersionId("1", VERSION, 2L))) + assertThatThrownBy(() -> + transactionTemplate.executeWithoutResult( + status -> definitionRepository.bindScriptPatchBaseVersionId("1", VERSION, 2L))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("script_patch_base_version_conflict"); assertThat(definitionRepository.findScriptPatchBaseVersionId("1", VERSION)).contains(1L); @@ -169,14 +168,10 @@ void existingBindingWithMismatchedRetainedBaseIsRejected() { .where(SCRIPT_EVENT_BINDINGS.ID.eq(bindingRowId(name))) .execute(); - assertThatThrownBy( - () -> - updateInTransaction( - request( - initial.id(), - name, - "{\"value\":2}", - List.of(binding("binding-a", "scope-a"))))) + assertThatThrownBy(() -> + updateInTransaction( + request( + initial.id(), name, "{\"value\":2}", List.of(binding("binding-a", "scope-a"))))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("script_patch_base_version_conflict"); } @@ -193,14 +188,10 @@ void existingBindingWithNullRetainedBaseIsRejected() { .where(SCRIPT_EVENT_BINDINGS.ID.eq(bindingRowId(name))) .execute(); - assertThatThrownBy( - () -> - updateInTransaction( - request( - initial.id(), - name, - "{\"value\":2}", - List.of(binding("binding-a", "scope-a"))))) + assertThatThrownBy(() -> + updateInTransaction( + request( + initial.id(), name, "{\"value\":2}", List.of(binding("binding-a", "scope-a"))))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("script_patch_base_version_conflict"); } @@ -292,14 +283,13 @@ void bindingWriteFailureRollsBackDefinitionAndBindingsTogether() { } private ScriptDefinitionDto updateInTransaction(ScriptDefinitionDto request) { - return transactionTemplate.execute( - status -> { - try { - return service.updateScript(request); - } catch (SagaException exception) { - throw new UpdateFailedException(exception); - } - }); + return transactionTemplate.execute(status -> { + try { + return service.updateScript(request); + } catch (SagaException exception) { + throw new UpdateFailedException(exception); + } + }); } private UpdateOutcome updateAfterBarrier( diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/AutomationScriptingTemporalHostingTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/AutomationScriptingTemporalHostingTest.java index b4e24b7f28..53ab6ce076 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/AutomationScriptingTemporalHostingTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/AutomationScriptingTemporalHostingTest.java @@ -34,24 +34,23 @@ class AutomationScriptingTemporalHostingTest { @Test void automationScriptingModuleUsesSharedTemporalHostingPattern() { - contextRunner.run( - context -> { - TemporalTaskQueueResolver taskQueues = context.getBean(TemporalTaskQueueResolver.class); - WorkerFactory workerFactory = context.getBean(WorkerFactory.class); - Worker worker = context.getBean(Worker.class); - String taskQueue = taskQueues.forWorkflowFamily("script-patch-readiness"); + contextRunner.run(context -> { + TemporalTaskQueueResolver taskQueues = context.getBean(TemporalTaskQueueResolver.class); + WorkerFactory workerFactory = context.getBean(WorkerFactory.class); + Worker worker = context.getBean(Worker.class); + String taskQueue = taskQueues.forWorkflowFamily("script-patch-readiness"); - assertThat(taskQueue) - .isEqualTo("firemud:automation-scripting-service:script-patch-readiness"); - assertThat( - FiremudWorkflowIds.workflowId( - "script-patch-readiness", "tenant-1", "script-patch-version", "patch-1")) - .isEqualTo("script-patch-readiness:tenant-1:script-patch-version:patch-1"); + assertThat(taskQueue) + .isEqualTo("firemud:automation-scripting-service:script-patch-readiness"); + assertThat( + FiremudWorkflowIds.workflowId( + "script-patch-readiness", "tenant-1", "script-patch-version", "patch-1")) + .isEqualTo("script-patch-readiness:tenant-1:script-patch-version:patch-1"); - verify(workerFactory).newWorker(taskQueue); - verify(worker).registerWorkflowImplementationTypes(HostProbeWorkflowImpl.class); - verify(workerFactory).start(); - }); + verify(workerFactory).newWorker(taskQueue); + verify(worker).registerWorkflowImplementationTypes(HostProbeWorkflowImpl.class); + verify(workerFactory).start(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptEventAuditRepositoryTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptEventAuditRepositoryTest.java index 3d14054b5c..f7f904c8c6 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptEventAuditRepositoryTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptEventAuditRepositoryTest.java @@ -176,20 +176,19 @@ void timerAuditLookupRejectsNegativeEpochWithoutNormalizingToUnpinned() { new ScriptEventAuditRepository(DSL.using(SQLDialect.POSTGRES)); assertThatIllegalArgumentException() - .isThrownBy( - () -> - repository.findTimerAuditEvents( - "tenant-1", - "game-1", - "patch-1", - -1L, - null, - "script-1", - "onTimerExpire", - "", - null, - null, - PageRequest.of(0, 25))) + .isThrownBy(() -> + repository.findTimerAuditEvents( + "tenant-1", + "game-1", + "patch-1", + -1L, + null, + "script-1", + "onTimerExpire", + "", + null, + null, + PageRequest.of(0, 25))) .withMessage("script_pin_epoch must be non-negative"); } @@ -618,12 +617,11 @@ void changedAfterIncludesOlderCreatedMutableSnapshotChangedAfterCursor() { null, PageRequest.of(0, 25))) .singleElement() - .satisfies( - audit -> { - assertThat(audit.getId()).isEqualTo(7L); - assertThat(audit.getCreatedAt()).isEqualTo(createdAt); - assertThat(audit.getUpdatedAt()).isEqualTo(updatedAt); - }); + .satisfies(audit -> { + assertThat(audit.getId()).isEqualTo(7L); + assertThat(audit.getCreatedAt()).isEqualTo(createdAt); + assertThat(audit.getUpdatedAt()).isEqualTo(updatedAt); + }); String whereClause = whereClause(sqlRef.get()); assertThat(whereClause).contains("updated_at").doesNotContain("created_at"); diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptEventIngressAuditRepositoryTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptEventIngressAuditRepositoryTest.java index 6054cbde5a..113fe5851c 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptEventIngressAuditRepositoryTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptEventIngressAuditRepositoryTest.java @@ -475,12 +475,10 @@ private static String postgresTimestamp(Instant instant) { private static void assertContainsTimestamp(Object[] bindings, Instant expected) { assertThat( Arrays.stream(bindings) - .anyMatch( - binding -> - binding instanceof OffsetDateTime offsetDateTime - ? offsetDateTime.toInstant().equals(expected) - : binding instanceof String - && postgresTimestamp(expected).equals(binding))) + .anyMatch(binding -> + binding instanceof OffsetDateTime offsetDateTime + ? offsetDateTime.toInstant().equals(expected) + : binding instanceof String && postgresTimestamp(expected).equals(binding))) .as("bindings should contain timestamp %s", expected) .isTrue(); } diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepositoryTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepositoryTest.java index 43142bf527..68cae7f358 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepositoryTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptHandoffEventRepositoryTest.java @@ -158,90 +158,88 @@ void newLogicalCommandUsesEventIdConflictUpsert() { assertThat(saved.getLifecycleRevision()).isEqualTo(9L); assertThat(bindings).hasValueSatisfying(values -> assertThat(values).contains(7L, 9L)); assertThat(insertSql) - .hasValueSatisfying( - sql -> - assertThat(sql) - .contains( - "on conflict", - "event_id", - "script_pin_epoch", - "script_pin_control_plane_request_id", - "plugin_activation_epoch", - "lifecycle_revision", - "do update", - "handoff_outcome") - .doesNotContain("uuid")); + .hasValueSatisfying(sql -> + assertThat(sql) + .contains( + "on conflict", + "event_id", + "script_pin_epoch", + "script_pin_control_plane_request_id", + "plugin_activation_epoch", + "lifecycle_revision", + "do update", + "handoff_outcome") + .doesNotContain("uuid")); assertThat(conflictTarget(insertSql.get())) .contains("event_id") .doesNotContain("script_pin_epoch", "script_pin_control_plane_request_id"); assertThat(insertSql) - .hasValueSatisfying( - sql -> { - int updateStart = sql.indexOf(" do update"); - int whereStart = sql.indexOf(" where ", updateStart); - assertThat(updateStart).isGreaterThanOrEqualTo(0); - assertThat(whereStart).isGreaterThan(updateStart); - assertThat(sql.substring(updateStart, whereStart)) - .doesNotContain( - "tenant_id", - "game_instance_id", - "script_patch_version", - "script_pin_epoch", - "script_id", - "binding_id", - "plugin_id", - "plugin_version_id", - "plugin_activation_epoch", - "lifecycle_revision", - "work_item_id", - "command_ordinal", - "automation_dispatch_id", - "target_game_instance_id", - "target_region_id", - "target_region_epoch", - "target_entity_id", - "playable_state_scope", - "world_slug", - "realm_slug", - "pointer_version", - "source_kind", - "source_state", - "source_ordinal", - "source_due_tick_id", - "source_due_at_ms", - "emitted_command_text"); - assertThat(sql.substring(whereStart)) - .contains( - "event_id", - "tenant_id", - "game_instance_id", - "script_patch_version", - "script_pin_epoch", - "script_pin_control_plane_request_id", - "script_id", - "binding_id", - "plugin_id", - "plugin_version_id", - "plugin_activation_epoch", - "lifecycle_revision", - "work_item_id", - "command_ordinal", - "automation_dispatch_id", - "target_game_instance_id", - "target_region_id", - "target_region_epoch", - "target_entity_id", - "playable_state_scope", - "world_slug", - "realm_slug", - "pointer_version", - "source_kind", - "source_state", - "source_ordinal", - "source_due_tick_id", - "source_due_at_ms", - "emitted_command_text"); - }); + .hasValueSatisfying(sql -> { + int updateStart = sql.indexOf(" do update"); + int whereStart = sql.indexOf(" where ", updateStart); + assertThat(updateStart).isGreaterThanOrEqualTo(0); + assertThat(whereStart).isGreaterThan(updateStart); + assertThat(sql.substring(updateStart, whereStart)) + .doesNotContain( + "tenant_id", + "game_instance_id", + "script_patch_version", + "script_pin_epoch", + "script_id", + "binding_id", + "plugin_id", + "plugin_version_id", + "plugin_activation_epoch", + "lifecycle_revision", + "work_item_id", + "command_ordinal", + "automation_dispatch_id", + "target_game_instance_id", + "target_region_id", + "target_region_epoch", + "target_entity_id", + "playable_state_scope", + "world_slug", + "realm_slug", + "pointer_version", + "source_kind", + "source_state", + "source_ordinal", + "source_due_tick_id", + "source_due_at_ms", + "emitted_command_text"); + assertThat(sql.substring(whereStart)) + .contains( + "event_id", + "tenant_id", + "game_instance_id", + "script_patch_version", + "script_pin_epoch", + "script_pin_control_plane_request_id", + "script_id", + "binding_id", + "plugin_id", + "plugin_version_id", + "plugin_activation_epoch", + "lifecycle_revision", + "work_item_id", + "command_ordinal", + "automation_dispatch_id", + "target_game_instance_id", + "target_region_id", + "target_region_epoch", + "target_entity_id", + "playable_state_scope", + "world_slug", + "realm_slug", + "pointer_version", + "source_kind", + "source_state", + "source_ordinal", + "source_due_tick_id", + "source_due_at_ms", + "emitted_command_text"); + }); } @Test @@ -430,73 +428,72 @@ void rejectsExistingIdUpdateWhenOwnerRequestChanges() { .isInstanceOf(IllegalStateException.class) .hasMessage("Handoff event owner tuple conflict"); assertThat(updateSql) - .hasValueSatisfying( - sql -> { - int whereStart = sql.indexOf(" where "); - assertThat(whereStart).isGreaterThanOrEqualTo(0); - assertThat(sql.substring(0, whereStart)) - .doesNotContain( - "event_id", - "tenant_id", - "game_instance_id", - "script_patch_version", - "script_pin_epoch", - "script_id", - "binding_id", - "plugin_id", - "plugin_version_id", - "plugin_activation_epoch", - "lifecycle_revision", - "work_item_id", - "command_ordinal", - "automation_dispatch_id", - "target_game_instance_id", - "target_region_id", - "target_region_epoch", - "target_entity_id", - "playable_state_scope", - "world_slug", - "realm_slug", - "pointer_version", - "source_kind", - "source_state", - "source_ordinal", - "source_due_tick_id", - "source_due_at_ms", - "emitted_command_text"); - assertThat(sql.substring(whereStart)) - .contains( - "event_id", - "tenant_id", - "game_instance_id", - "row_version", - "script_patch_version", - "script_pin_epoch", - "script_pin_control_plane_request_id", - "script_id", - "binding_id", - "plugin_id", - "plugin_version_id", - "plugin_activation_epoch", - "lifecycle_revision", - "work_item_id", - "command_ordinal", - "automation_dispatch_id", - "target_game_instance_id", - "target_region_id", - "target_region_epoch", - "target_entity_id", - "playable_state_scope", - "world_slug", - "realm_slug", - "pointer_version", - "source_kind", - "source_state", - "source_ordinal", - "source_due_tick_id", - "source_due_at_ms", - "emitted_command_text"); - }); + .hasValueSatisfying(sql -> { + int whereStart = sql.indexOf(" where "); + assertThat(whereStart).isGreaterThanOrEqualTo(0); + assertThat(sql.substring(0, whereStart)) + .doesNotContain( + "event_id", + "tenant_id", + "game_instance_id", + "script_patch_version", + "script_pin_epoch", + "script_id", + "binding_id", + "plugin_id", + "plugin_version_id", + "plugin_activation_epoch", + "lifecycle_revision", + "work_item_id", + "command_ordinal", + "automation_dispatch_id", + "target_game_instance_id", + "target_region_id", + "target_region_epoch", + "target_entity_id", + "playable_state_scope", + "world_slug", + "realm_slug", + "pointer_version", + "source_kind", + "source_state", + "source_ordinal", + "source_due_tick_id", + "source_due_at_ms", + "emitted_command_text"); + assertThat(sql.substring(whereStart)) + .contains( + "event_id", + "tenant_id", + "game_instance_id", + "row_version", + "script_patch_version", + "script_pin_epoch", + "script_pin_control_plane_request_id", + "script_id", + "binding_id", + "plugin_id", + "plugin_version_id", + "plugin_activation_epoch", + "lifecycle_revision", + "work_item_id", + "command_ordinal", + "automation_dispatch_id", + "target_game_instance_id", + "target_region_id", + "target_region_epoch", + "target_entity_id", + "playable_state_scope", + "world_slug", + "realm_slug", + "pointer_version", + "source_kind", + "source_state", + "source_ordinal", + "source_due_tick_id", + "source_due_at_ms", + "emitted_command_text"); + }); } @Test @@ -544,13 +541,12 @@ void treatsEventIdAsImmutableOnExistingIdUpdate() { .isInstanceOf(IllegalStateException.class) .hasMessage("Handoff event immutable identity conflict"); assertThat(updateSql) - .hasValueSatisfying( - sql -> { - int whereStart = sql.indexOf(" where "); - assertThat(whereStart).isGreaterThanOrEqualTo(0); - assertThat(sql.substring(0, whereStart)).doesNotContain("event_id ="); - assertThat(sql.substring(whereStart)).contains("event_id", "row_version"); - }); + .hasValueSatisfying(sql -> { + int whereStart = sql.indexOf(" where "); + assertThat(whereStart).isGreaterThanOrEqualTo(0); + assertThat(sql.substring(0, whereStart)).doesNotContain("event_id ="); + assertThat(sql.substring(whereStart)).contains("event_id", "row_version"); + }); } @Test @@ -578,11 +574,10 @@ void retentionCleanupBindsUtcOffsetDateTimeForNullableHoldComparison() { assertThat(bindingsRef.get()).contains("2026-08-02 00:00:00+00:00"); assertThat(bindingsRef.get()).contains("DEAD_LETTERED"); assertThat(bindingsRef.get()) - .anySatisfy( - binding -> { - assertThat(binding).isInstanceOf(Number.class); - assertThat(((Number) binding).longValue()).isEqualTo(500L); - }); + .anySatisfy(binding -> { + assertThat(binding).isInstanceOf(Number.class); + assertThat(((Number) binding).longValue()).isEqualTo(500L); + }); String renderedSql = sqlRef.get().toLowerCase(Locale.ROOT).replaceAll("\\s+", " "); assertThat(renderedSql).contains("select \"retention_candidates\".\"id\""); assertThat(renderedSql) diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptPatchInstanceRolloutEventRepositoryTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptPatchInstanceRolloutEventRepositoryTest.java index c9482fa3c8..0bbc8fe1e8 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptPatchInstanceRolloutEventRepositoryTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptPatchInstanceRolloutEventRepositoryTest.java @@ -68,10 +68,9 @@ void rejectsPositivePinEpochWithoutOwnerRequestIdBeforeQuery() { new ScriptPatchInstanceRolloutEventRepository(DSL.using(SQLDialect.POSTGRES)); assertThatIllegalArgumentException() - .isThrownBy( - () -> - repository.findEvents( - "tenant-1", "game-1", "patch-1", 2L, null, "", null, null, Pageable.unpaged())) + .isThrownBy(() -> + repository.findEvents( + "tenant-1", "game-1", "patch-1", 2L, null, "", null, null, Pageable.unpaged())) .withMessage( "script_pin_control_plane_request_id must be present exactly when script_pin_epoch is positive"); } @@ -82,18 +81,17 @@ void rejectsOwnerRequestIdWithoutPositivePinEpochBeforeQuery() { new ScriptPatchInstanceRolloutEventRepository(DSL.using(SQLDialect.POSTGRES)); assertThatIllegalArgumentException() - .isThrownBy( - () -> - repository.findEvents( - "tenant-1", - "game-1", - "patch-1", - null, - "pin-request-1", - "", - null, - null, - Pageable.unpaged())) + .isThrownBy(() -> + repository.findEvents( + "tenant-1", + "game-1", + "patch-1", + null, + "pin-request-1", + "", + null, + null, + Pageable.unpaged())) .withMessage( "script_pin_control_plane_request_id must be present exactly when script_pin_epoch is positive"); } @@ -104,18 +102,17 @@ void rejectsZeroPinEpochWithOwnerRequestIdBeforeQuery() { new ScriptPatchInstanceRolloutEventRepository(DSL.using(SQLDialect.POSTGRES)); assertThatIllegalArgumentException() - .isThrownBy( - () -> - repository.findEvents( - "tenant-1", - "game-1", - "patch-1", - 0L, - "pin-request-1", - "", - null, - null, - Pageable.unpaged())) + .isThrownBy(() -> + repository.findEvents( + "tenant-1", + "game-1", + "patch-1", + 0L, + "pin-request-1", + "", + null, + null, + Pageable.unpaged())) .withMessage( "script_pin_control_plane_request_id must be present exactly when script_pin_epoch is positive"); } @@ -151,10 +148,9 @@ void rejectsNegativePinEpochBeforeQuery() { new ScriptPatchInstanceRolloutEventRepository(DSL.using(SQLDialect.POSTGRES)); assertThatIllegalArgumentException() - .isThrownBy( - () -> - repository.findEvents( - "tenant-1", "game-1", "patch-1", -1L, null, "", null, null, Pageable.unpaged())) + .isThrownBy(() -> + repository.findEvents( + "tenant-1", "game-1", "patch-1", -1L, null, "", null, null, Pageable.unpaged())) .withMessage("script_pin_epoch must be non-negative"); } @@ -249,17 +245,16 @@ void rejectsExistingIdUpdateWhenOwnerTupleChanges() { .isInstanceOf(OptimisticLockingFailureException.class) .hasMessage("Stale write rejected for script_patch_instance_rollout_events id=9"); assertThat(updateSql) - .hasValueSatisfying( - sql -> { - int whereStart = sql.indexOf(" where "); - assertThat(whereStart).isGreaterThanOrEqualTo(0); - assertThat(sql.substring(whereStart)) - .contains( - "row_version", - "script_patch_version", - "script_pin_epoch", - "last_observed_control_plane_request_id"); - }); + .hasValueSatisfying(sql -> { + int whereStart = sql.indexOf(" where "); + assertThat(whereStart).isGreaterThanOrEqualTo(0); + assertThat(sql.substring(whereStart)) + .contains( + "row_version", + "script_patch_version", + "script_pin_epoch", + "last_observed_control_plane_request_id"); + }); } @Test diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepositoryTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepositoryTest.java index 73d6c0602e..78631db6e5 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepositoryTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/repository/ScriptWorkItemRepositoryTest.java @@ -64,9 +64,8 @@ void replayCandidateLookupScopesTenantBeforeLockingRows() { assertThat(repository.findByTenantIdAndIdInForUpdateOrderByIdAsc("tenant-1", List.of(17L, 18L))) .isEmpty(); assertThat(sql) - .hasValueSatisfying( - statement -> - assertThat(statement).contains("tenant_id", "id", "order by", "for update")); + .hasValueSatisfying(statement -> + assertThat(statement).contains("tenant_id", "id", "order by", "for update")); } @Test @@ -86,11 +85,10 @@ void replayCandidateSnapshotScopesTenantWithoutLockingRows() { assertThat(repository.findByTenantIdAndIdInOrderByIdAsc("tenant-1", List.of(17L, 18L))) .isEmpty(); assertThat(sql) - .hasValueSatisfying( - statement -> { - assertThat(statement).contains("tenant_id", "id", "order by"); - assertThat(statement).doesNotContain("for update"); - }); + .hasValueSatisfying(statement -> { + assertThat(statement).contains("tenant_id", "id", "order by"); + assertThat(statement).doesNotContain("for update"); + }); } @Test @@ -242,17 +240,16 @@ void insertAndHydratePluginFencePersistsBothValues() { assertThat(saved.getAuthorityUnavailableRetryCount()).isEqualTo(2); assertThat(saved.getNextEligibleAt()).isEqualTo(Instant.parse("2026-08-01T00:00:03Z")); assertThat(insertSql) - .hasValueSatisfying( - sql -> - assertThat(sql) - .contains( - "plugin_activation_epoch", - "lifecycle_revision", - "failure_generation", - "authority_unavailable_since", - "authority_unavailable_count", - "authority_unavailable_retry_count", - "next_eligible_at")); + .hasValueSatisfying(sql -> + assertThat(sql) + .contains( + "plugin_activation_epoch", + "lifecycle_revision", + "failure_generation", + "authority_unavailable_since", + "authority_unavailable_count", + "authority_unavailable_retry_count", + "next_eligible_at")); } @Test @@ -273,11 +270,9 @@ void broadClaimQueryFiltersByNextEligibilityTime() { "PENDING_EVALUATION", Instant.parse("2026-08-01T00:00:00Z"), PageRequest.of(0, 10)); assertThat(sql) - .hasValueSatisfying( - statement -> - assertThat(statement) - .contains( - "status", "next_eligible_at", "is null", "<=", "order by", "created_at")); + .hasValueSatisfying(statement -> + assertThat(statement) + .contains("status", "next_eligible_at", "is null", "<=", "order by", "created_at")); } @Test @@ -301,11 +296,9 @@ void queuePointerClaimQueryFiltersByNextEligibilityTime() { PageRequest.of(0, 10)); assertThat(sql) - .hasValueSatisfying( - statement -> - assertThat(statement) - .contains( - "\"id\" in", "status", "next_eligible_at", "is null", "<=", "order by")); + .hasValueSatisfying(statement -> + assertThat(statement) + .contains("\"id\" in", "status", "next_eligible_at", "is null", "<=", "order by")); } @Test @@ -326,10 +319,9 @@ void broadNonPendingQueryTreatsNullNextEligibilityAsImmediatelyEligible() { "EVALUATING", Instant.parse("2026-08-01T00:00:00Z"), PageRequest.of(0, 10)); assertThat(sql) - .hasValueSatisfying( - statement -> - assertThat(statement) - .contains("status", "next_eligible_at", "is null", " or ", "<=", "order by")); + .hasValueSatisfying(statement -> + assertThat(statement) + .contains("status", "next_eligible_at", "is null", " or ", "<=", "order by")); } @Test @@ -353,17 +345,16 @@ void pointerNonPendingQueryTreatsNullNextEligibilityAsImmediatelyEligible() { PageRequest.of(0, 10)); assertThat(sql) - .hasValueSatisfying( - statement -> - assertThat(statement) - .contains( - "\"id\" in", - "status", - "next_eligible_at", - "is null", - " or ", - "<=", - "order by")); + .hasValueSatisfying(statement -> + assertThat(statement) + .contains( + "\"id\" in", + "status", + "next_eligible_at", + "is null", + " or ", + "<=", + "order by")); } @Test @@ -398,11 +389,9 @@ void pendingClaimUsesRetryEligibilityAndSkipLocked() { "PENDING_EVALUATION", PageRequest.of(0, 10))) .isEmpty(); assertThat(sql) - .hasValueSatisfying( - statement -> - assertThat(statement) - .contains( - "next_eligible_at", "current_timestamp", "for update", "skip locked")); + .hasValueSatisfying(statement -> + assertThat(statement) + .contains("next_eligible_at", "current_timestamp", "for update", "skip locked")); } @Test @@ -429,16 +418,15 @@ void cancellationClaimUsesBoundedScopeAndRowLock() { List.of("PENDING_EVALUATION", "EVALUATING"))) .isEmpty(); assertThat(sql) - .hasValueSatisfying( - statement -> - assertThat(statement) - .contains( - "tenant_id", - "script_patch_version", - "game_instance_id", - "region_id", - "for update", - "fetch next")); + .hasValueSatisfying(statement -> + assertThat(statement) + .contains( + "tenant_id", + "script_patch_version", + "game_instance_id", + "region_id", + "for update", + "fetch next")); } @Test @@ -468,35 +456,32 @@ void pluginCancellationClaimUsesBoundedScopeAndRowLock() { List.of("PENDING_EVALUATION", "EVALUATING"))) .isEmpty(); assertThat(sql) - .hasValueSatisfying( - statement -> - assertThat(statement) - .contains("id", "for update", "fetch next") - .satisfies( - scopedSql -> { - int whereIndex = scopedSql.indexOf(" where "); - int fetchIndex = scopedSql.indexOf("fetch next"); - assertThat(scopedSql.substring(whereIndex, fetchIndex)) - .contains( - "tenant_id", - "plugin_id", - "plugin_version_id", - "game_instance_id", - "region_id", - "status"); - })); + .hasValueSatisfying(statement -> + assertThat(statement) + .contains("id", "for update", "fetch next") + .satisfies(scopedSql -> { + int whereIndex = scopedSql.indexOf(" where "); + int fetchIndex = scopedSql.indexOf("fetch next"); + assertThat(scopedSql.substring(whereIndex, fetchIndex)) + .contains( + "tenant_id", + "plugin_id", + "plugin_version_id", + "game_instance_id", + "region_id", + "status"); + })); assertThat(bindings) - .hasValueSatisfying( - values -> - assertThat(values) - .contains( - "tenant-1", - "plugin-1", - "plugin-v1", - "game-1", - "region-1", - "PENDING_EVALUATION", - "EVALUATING")); + .hasValueSatisfying(values -> + assertThat(values) + .contains( + "tenant-1", + "plugin-1", + "plugin-v1", + "game-1", + "region-1", + "PENDING_EVALUATION", + "EVALUATING")); } @Test @@ -520,22 +505,20 @@ void replayClaimFencesStatusRowVersionAndFailureGeneration() { 11L, "tenant-1", 4, 3L, Instant.parse("2026-08-01T00:00:04Z"))) .isEmpty(); assertThat(sql) - .hasValueSatisfying( - statement -> - assertThat(statement) - .contains( - "update", - "status", - "cancel_reason", - "authority_unavailable_since", - "authority_unavailable_count", - "next_eligible_at", - "row_version", - "failure_generation") - .satisfies( - sqlText -> - assertThat(sqlText.substring(0, sqlText.indexOf(" returning "))) - .contains("cancel_reason"))); + .hasValueSatisfying(statement -> + assertThat(statement) + .contains( + "update", + "status", + "cancel_reason", + "authority_unavailable_since", + "authority_unavailable_count", + "next_eligible_at", + "row_version", + "failure_generation") + .satisfies(sqlText -> + assertThat(sqlText.substring(0, sqlText.indexOf(" returning "))) + .contains("cancel_reason"))); assertThat(bindings.get()) .containsSubsequence("PENDING_EVALUATION", null, null, 0, 0, null) .containsSubsequence(11L, "tenant-1", "DEAD_LETTERED", 4, 3L); @@ -593,18 +576,17 @@ void insertRejectsConflictingOwnerEvidenceAgainstExistingIdentity() { .hasMessage("script_pin_control_plane_request_id conflicts with existing identity"); assertThat(insertSql) - .hasValueSatisfying( - sql -> - assertThat(conflictClause(sql)) - .contains( - "where", - "script_pin_epoch", - "> 0", - "plugin_id", - "plugin_version_id", - "binding_id", - "source_service") - .doesNotContain("script_pin_control_plane_request_id")); + .hasValueSatisfying(sql -> + assertThat(conflictClause(sql)) + .contains( + "where", + "script_pin_epoch", + "> 0", + "plugin_id", + "plugin_version_id", + "binding_id", + "source_service") + .doesNotContain("script_pin_control_plane_request_id")); } @Test @@ -757,11 +739,10 @@ void scriptOnlyPluginLookupNormalizesBlankIdentityToCanonicalEmptyValues() { .findByTenantIdAndPluginIdAndPluginVersionIdAndStatusInOrderByCreatedAtAscIdAsc( "tenant-1", null, null, List.of("PENDING_EVALUATION"))) .singleElement() - .satisfies( - item -> { - assertThat(item.getPluginId()).isEmpty(); - assertThat(item.getPluginVersionId()).isEmpty(); - }); + .satisfies(item -> { + assertThat(item.getPluginId()).isEmpty(); + assertThat(item.getPluginVersionId()).isEmpty(); + }); assertThat(bindings.get()).contains("tenant-1", "", ""); } @@ -946,18 +927,17 @@ void terminalCleanupRequiresReceiptAndActiveHandoffHoldProof() { assertThat(repository.deleteByStatusAndUpdatedAtBefore("HANDED_OFF", Instant.EPOCH)).isZero(); assertThat(sql) - .hasValueSatisfying( - statement -> - assertThat(statement) - .contains( - "script_work_items", - "script_dead_letter_replay_results", - "script_handoff_events", - "retention_hold_until", - "handoff_outcome", - "regexp_replace", - "observed_at", - "current_timestamp")); + .hasValueSatisfying(statement -> + assertThat(statement) + .contains( + "script_work_items", + "script_dead_letter_replay_results", + "script_handoff_events", + "retention_hold_until", + "handoff_outcome", + "regexp_replace", + "observed_at", + "current_timestamp")); assertThat(sql.get()) .contains("script_handoff_events\".\"tenant_id\" = \"script_work_items\".\"tenant_id\"") .contains("script_handoff_events\".\"work_item_id\" = \"script_work_items\".\"id\""); @@ -983,11 +963,10 @@ void deadLetterBlockedMetricDoesNotUseChildAbsenceAsDeletionProof() { assertThat(repository.countTerminalRowsBlockedByEvidence("DEAD_LETTERED", Instant.EPOCH)) .isZero(); assertThat(sql) - .hasValueSatisfying( - statement -> - assertThat(statement) - .contains("script_work_items", "status", "updated_at") - .doesNotContain("script_event_audit", "script_handoff_events")); + .hasValueSatisfying(statement -> + assertThat(statement) + .contains("script_work_items", "status", "updated_at") + .doesNotContain("script_event_audit", "script_handoff_events")); } @Test @@ -1010,16 +989,15 @@ void replayReceiptBlockedMetricCountsOnlyAgedRowsWithRetainedReplayResults() { assertThat(repository.countTerminalRowsBlockedByReplayReceipts("HANDED_OFF", Instant.EPOCH)) .isZero(); assertThat(sql) - .hasValueSatisfying( - statement -> - assertThat(statement) - .contains( - "script_work_items", - "status", - "updated_at", - "script_dead_letter_replay_results") - .contains("work_item_id") - .doesNotContain("script_handoff_events")); + .hasValueSatisfying(statement -> + assertThat(statement) + .contains( + "script_work_items", + "status", + "updated_at", + "script_dead_letter_replay_results") + .contains("work_item_id") + .doesNotContain("script_handoff_events")); } @Test @@ -1040,28 +1018,27 @@ void deadLetterListingAppliesOptionalFiltersBeforeLimit() { "tenant-1", "game-1", "patch-1", "DEAD_LETTERED", PageRequest.of(0, 25)); assertThat(sql) - .hasValueSatisfying( - statement -> { - assertThat(statement) - .contains( - "where", - "tenant_id", - "game_instance_id", - "script_patch_version", - "status", - "fetch next"); - int whereIndex = statement.indexOf(" where "); - int fetchIndex = statement.indexOf("fetch next"); - assertThat(statement.indexOf("game_instance_id", whereIndex)) - .isGreaterThan(whereIndex) - .isLessThan(fetchIndex); - assertThat(statement.indexOf("script_patch_version", whereIndex)) - .isGreaterThan(whereIndex) - .isLessThan(fetchIndex); - assertThat(statement.indexOf("status", whereIndex)) - .isGreaterThan(whereIndex) - .isLessThan(fetchIndex); - }); + .hasValueSatisfying(statement -> { + assertThat(statement) + .contains( + "where", + "tenant_id", + "game_instance_id", + "script_patch_version", + "status", + "fetch next"); + int whereIndex = statement.indexOf(" where "); + int fetchIndex = statement.indexOf("fetch next"); + assertThat(statement.indexOf("game_instance_id", whereIndex)) + .isGreaterThan(whereIndex) + .isLessThan(fetchIndex); + assertThat(statement.indexOf("script_patch_version", whereIndex)) + .isGreaterThan(whereIndex) + .isLessThan(fetchIndex); + assertThat(statement.indexOf("status", whereIndex)) + .isGreaterThan(whereIndex) + .isLessThan(fetchIndex); + }); } private static ScriptWorkItemsRecord workItemRecord(long id, int rowVersion, long pinEpoch) { diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationAdmissionStateServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationAdmissionStateServiceImplTest.java index 931ebd77dd..edead608ec 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationAdmissionStateServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationAdmissionStateServiceImplTest.java @@ -42,12 +42,11 @@ void exactRequestRetryReturnsDurableResultAndChangedInputConflicts() { .thenReturn(Optional.empty()) .thenAnswer(invocation -> Optional.of(durableResult.get())); when(historyRepository.insertOrGet(any(AutomationAdmissionRequestHistory.class))) - .thenAnswer( - invocation -> { - AutomationAdmissionRequestHistory history = invocation.getArgument(0); - durableResult.set(history); - return history; - }); + .thenAnswer(invocation -> { + AutomationAdmissionRequestHistory history = invocation.getArgument(0); + durableResult.set(history); + return history; + }); AutomationAdmissionStateService service = service(repository, historyRepository); AutomationAdmissionStateService.SetAdmissionModeCommand command = command("actor-1", "rollback"); @@ -77,24 +76,22 @@ void workflowRequestIdCanApplyDistinctModeKeys() { when(repository.save(state)).thenReturn(state); AtomicReference durableResult = new AtomicReference<>(); when(historyRepository.find(anyString(), anyString(), anyString(), anyString(), anyString())) - .thenAnswer( - invocation -> { - AutomationAdmissionRequestHistory history = durableResult.get(); - return history != null - && invocation.getArgument(3, String.class).equals(history.getMode()) - && invocation - .getArgument(4, String.class) - .equals(history.getControlPlaneRequestId()) - ? Optional.of(history) - : Optional.empty(); - }); + .thenAnswer(invocation -> { + AutomationAdmissionRequestHistory history = durableResult.get(); + return history != null + && invocation.getArgument(3, String.class).equals(history.getMode()) + && invocation + .getArgument(4, String.class) + .equals(history.getControlPlaneRequestId()) + ? Optional.of(history) + : Optional.empty(); + }); when(historyRepository.insertOrGet(any(AutomationAdmissionRequestHistory.class))) - .thenAnswer( - invocation -> { - AutomationAdmissionRequestHistory history = invocation.getArgument(0); - durableResult.set(history); - return history; - }); + .thenAnswer(invocation -> { + AutomationAdmissionRequestHistory history = invocation.getArgument(0); + durableResult.set(history); + return history; + }); AutomationAdmissionStateService service = service(repository, historyRepository); AutomationAdmissionStateService.AdmissionStateSummary paused = @@ -127,29 +124,27 @@ void exactRetryOfEarlierPauseReturnsStoredResultAfterLaterNormalTransition() { AtomicReference pausedHistory = new AtomicReference<>(); AtomicReference normalHistory = new AtomicReference<>(); when(historyRepository.find(anyString(), anyString(), anyString(), anyString(), anyString())) - .thenAnswer( - invocation -> { - String mode = invocation.getArgument(3, String.class); - String requestId = invocation.getArgument(4, String.class); - AutomationAdmissionRequestHistory history = - "PAUSED_FOR_ROLLBACK".equals(mode) && "pause-request".equals(requestId) - ? pausedHistory.get() - : "NORMAL".equals(mode) && "normal-request".equals(requestId) - ? normalHistory.get() - : null; - return Optional.ofNullable(history); - }); + .thenAnswer(invocation -> { + String mode = invocation.getArgument(3, String.class); + String requestId = invocation.getArgument(4, String.class); + AutomationAdmissionRequestHistory history = + "PAUSED_FOR_ROLLBACK".equals(mode) && "pause-request".equals(requestId) + ? pausedHistory.get() + : "NORMAL".equals(mode) && "normal-request".equals(requestId) + ? normalHistory.get() + : null; + return Optional.ofNullable(history); + }); when(historyRepository.insertOrGet(any(AutomationAdmissionRequestHistory.class))) - .thenAnswer( - invocation -> { - AutomationAdmissionRequestHistory history = invocation.getArgument(0); - if ("PAUSED_FOR_ROLLBACK".equals(history.getMode())) { - pausedHistory.set(history); - } else { - normalHistory.set(history); - } - return history; - }); + .thenAnswer(invocation -> { + AutomationAdmissionRequestHistory history = invocation.getArgument(0); + if ("PAUSED_FOR_ROLLBACK".equals(history.getMode())) { + pausedHistory.set(history); + } else { + normalHistory.set(history); + } + return history; + }); AutomationAdmissionStateService service = service(repository, historyRepository); AutomationAdmissionStateService.SetAdmissionModeCommand pause = new AutomationAdmissionStateService.SetAdmissionModeCommand( @@ -461,11 +456,10 @@ void rejectsBlankSetModeBeforeAnyLookup(String mode) { Mockito.mock(AutomationAdmissionRequestHistoryRepository.class); AutomationAdmissionStateService service = service(repository, historyRepository); - assertThatThrownBy( - () -> - service.setMode( - new AutomationAdmissionStateService.SetAdmissionModeCommand( - "tenant-1", "game-1", "region-1", mode, "request-1", "actor-1", "reason"))) + assertThatThrownBy(() -> + service.setMode( + new AutomationAdmissionStateService.SetAdmissionModeCommand( + "tenant-1", "game-1", "region-1", mode, "request-1", "actor-1", "reason"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("mode is required"); verifyNoInteractions(repository, historyRepository); @@ -500,11 +494,10 @@ private static void assertBlankSetField( Mockito.mock(AutomationAdmissionRequestHistoryRepository.class); AutomationAdmissionStateService service = service(repository, historyRepository); - assertThatThrownBy( - () -> - service.setMode( - new AutomationAdmissionStateService.SetAdmissionModeCommand( - tenantId, gameInstanceId, "region-1", "NORMAL", requestId, actor, reason))) + assertThatThrownBy(() -> + service.setMode( + new AutomationAdmissionStateService.SetAdmissionModeCommand( + tenantId, gameInstanceId, "region-1", "NORMAL", requestId, actor, reason))) .isInstanceOf(IllegalArgumentException.class) .hasMessage(expectedMessageField + " is required"); verifyNoInteractions(repository, historyRepository); diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationQueueServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationQueueServiceImplTest.java index 0e639eef4c..182a26081f 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationQueueServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationQueueServiceImplTest.java @@ -101,11 +101,10 @@ void drainWorkItemsStopsAtConfiguredTickPointerBudget() { String queueKey = "automation:queue:{tenant:tenant-1:instance:instance-1}:entity-1"; AtomicInteger popCount = new AtomicInteger(); when(listOps.leftPop(queueKey)) - .thenAnswer( - invocation -> { - int index = popCount.getAndIncrement(); - return index < 50 ? pointerJson(41L + index) : null; - }); + .thenAnswer(invocation -> { + int index = popCount.getAndIncrement(); + return index < 50 ? pointerJson(41L + index) : null; + }); List drained = service.drainWorkItems("tenant-1", "instance-1", "entity-1"); diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcServiceTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcServiceTest.java index 626b4a1a75..ed7365ea6c 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcServiceTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingGrpcServiceTest.java @@ -122,11 +122,10 @@ void missingOrInvalidConfiguredWorkloadNamespaceDeniesDigestReadBeforeOwnerRead( SessionContext.setContext( null, List.of(), Map.of(), true, "game-design-service", "test-instance"); - runAsGameDesign( - () -> - assertEquals( - "PERMISSION_DENIED", - invokeDigest(service, fullDigestRequest("1", "7")).getError().getCode())); + runAsGameDesign(() -> + assertEquals( + "PERMISSION_DENIED", + invokeDigest(service, fullDigestRequest("1", "7")).getError().getCode())); } AutomationScriptingGrpcService service = @@ -142,11 +141,10 @@ void missingOrInvalidConfiguredWorkloadNamespaceDeniesDigestReadBeforeOwnerRead( null); SessionContext.setContext( null, List.of(), Map.of(), true, "game-design-service", "test-instance"); - runAsGameDesign( - () -> - assertEquals( - "PERMISSION_DENIED", - invokeDigest(service, fullDigestRequest("1", "7")).getError().getCode())); + runAsGameDesign(() -> + assertEquals( + "PERMISSION_DENIED", + invokeDigest(service, fullDigestRequest("1", "7")).getError().getCode())); } @Test @@ -171,22 +169,21 @@ void getDraftDesignDigestRejectsUnmappedVersionScope() { TEST_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - runAsGameDesign( - () -> - service.getDraftDesignDigest( - fullDigestRequest("1", "7"), - new StreamObserver<>() { - @Override - public void onNext(GetDraftDesignDigestResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - })); + runAsGameDesign(() -> + service.getDraftDesignDigest( + fullDigestRequest("1", "7"), + new StreamObserver<>() { + @Override + public void onNext(GetDraftDesignDigestResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + })); assertEquals("UNSUPPORTED_SCOPE", ref.get().getError().getCode()); } @@ -213,22 +210,21 @@ void getDraftDesignDigestRejectsUnsupportedPatchScopeWithValidBaseBinding() { TEST_NAMESPACE); AtomicReference ref = new AtomicReference<>(); - runAsGameDesign( - () -> - service.getDraftDesignDigest( - patchDigestRequest("1", "7", "patch:é:1"), - new StreamObserver<>() { - @Override - public void onNext(GetDraftDesignDigestResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - })); + runAsGameDesign(() -> + service.getDraftDesignDigest( + patchDigestRequest("1", "7", "patch:é:1"), + new StreamObserver<>() { + @Override + public void onNext(GetDraftDesignDigestResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + })); assertEquals("UNSUPPORTED_SCOPE", ref.get().getError().getCode()); } @@ -328,14 +324,13 @@ void getDraftDesignDigestRejectsWrongPeerAndUserOrAdminJwt() { () -> assertEquals("PERMISSION_DENIED", invokeDigest(service, request).getError().getCode())); - runAsGameDesign( - () -> { - SessionContext.setContext("42", List.of(), Map.of(), false, "game-design-service", null); - assertEquals("PERMISSION_DENIED", invokeDigest(service, request).getError().getCode()); - SessionContext.setContext( - "42", List.of("platformAdmin"), Map.of(), false, "game-design-service", null); - assertEquals("PERMISSION_DENIED", invokeDigest(service, request).getError().getCode()); - }); + runAsGameDesign(() -> { + SessionContext.setContext("42", List.of(), Map.of(), false, "game-design-service", null); + assertEquals("PERMISSION_DENIED", invokeDigest(service, request).getError().getCode()); + SessionContext.setContext( + "42", List.of("platformAdmin"), Map.of(), false, "game-design-service", null); + assertEquals("PERMISSION_DENIED", invokeDigest(service, request).getError().getCode()); + }); } @Test @@ -354,14 +349,11 @@ void getDraftDesignDigestRejectsWrongDigestBeforeUnsupportedScope() { SessionContext.setContext( null, List.of(), Map.of(), true, "game-design-service", "test-instance"); AtomicReference ref = new AtomicReference<>(); - runAsGameDesign( - () -> - ref.set( - invokeDigest( - service, - fullDigestRequest("1", "7").toBuilder() - .setRequestDigest("0".repeat(64)) - .build()))); + runAsGameDesign(() -> + ref.set( + invokeDigest( + service, + fullDigestRequest("1", "7").toBuilder().setRequestDigest("0".repeat(64)).build()))); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); } diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java index 2778f61393..728c77f448 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java @@ -38,9 +38,8 @@ void rejectsZeroTenantIdBeforeLookups() { gameSessionClient, new ObjectMapper()); - assertThatThrownBy( - () -> - service.validateActivation("0", "game-1", "patch-1", "town-crier", "town-crier-v2")) + assertThatThrownBy(() -> + service.validateActivation("0", "game-1", "patch-1", "town-crier", "town-crier-v2")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("tenantId must be positive"); verifyNoInteractions( @@ -78,9 +77,8 @@ void rejectsUnsupportedBuiltInCommandAlias() { gameSessionClient, new ObjectMapper()); - assertThatThrownBy( - () -> - service.validateActivation("1", "game-1", "patch-1", "town-crier", "town-crier-v2")) + assertThatThrownBy(() -> + service.validateActivation("1", "game-1", "patch-1", "town-crier", "town-crier-v2")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("PLUGIN_COMMAND_ALIAS_INVALID"); } @@ -125,9 +123,8 @@ void rejectsCommandAliasCollisionWithinInstanceScope() { gameSessionClient, new ObjectMapper()); - assertThatThrownBy( - () -> - service.validateActivation("1", "game-1", "patch-1", "town-crier", "town-crier-v2")) + assertThatThrownBy(() -> + service.validateActivation("1", "game-1", "patch-1", "town-crier", "town-crier-v2")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("PLUGIN_COMMAND_ALIAS_CONFLICT"); } @@ -167,9 +164,8 @@ void rejectsExclusiveBindingConflictWithActivePlugin() { gameSessionClient, new ObjectMapper()); - assertThatThrownBy( - () -> - service.validateActivation("1", "game-1", "patch-1", "town-crier", "town-crier-v2")) + assertThatThrownBy(() -> + service.validateActivation("1", "game-1", "patch-1", "town-crier", "town-crier-v2")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("PLUGIN_INSTANCE_BINDING_CONFLICT"); } diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImplTest.java index 79a210edf8..b66496c4c4 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginRuntimeStateServiceImplTest.java @@ -508,11 +508,10 @@ void alreadyDisabledNoopStoresReceiptAndExactRetryCannotMutateAfterReenable() { when(historyRepository.find("1", "game-1", "plugin-1", "disable-noop")) .thenAnswer(invocation -> Optional.ofNullable(receipt[0])); when(historyRepository.insertOrGet(Mockito.any(PluginRuntimeRequestHistory.class))) - .thenAnswer( - invocation -> { - receipt[0] = invocation.getArgument(0); - return receipt[0]; - }); + .thenAnswer(invocation -> { + receipt[0] = invocation.getArgument(0); + return receipt[0]; + }); PluginRuntimeStateServiceImpl service = service(repository, eventRepository, historyRepository); PluginRuntimeStateService.PluginStateCommand command = new PluginRuntimeStateService.PluginStateCommand( @@ -559,11 +558,10 @@ void alreadyEnabledActivationStoresReceiptWithoutChangingRuntimeState() { when(historyRepository.find("1", "game-1", "plugin-1", "activate-noop")) .thenAnswer(invocation -> Optional.ofNullable(receipt[0])); when(historyRepository.insertOrGet(Mockito.any(PluginRuntimeRequestHistory.class))) - .thenAnswer( - invocation -> { - receipt[0] = invocation.getArgument(0); - return receipt[0]; - }); + .thenAnswer(invocation -> { + receipt[0] = invocation.getArgument(0); + return receipt[0]; + }); when(gameDesignClient.getPublishedPluginVersion("1", "plugin-1", "plugin-v1")) .thenReturn( publishedPluginVersion( @@ -635,11 +633,10 @@ void drainOfAbsentStateRecordsOneStableFailureAndCannotBeReplayedAfterActivation when(historyRepository.find("1", "game-1", "plugin-1", "drain-1")) .thenAnswer(invocation -> Optional.ofNullable(receipt[0])); when(historyRepository.insertOrGet(Mockito.any(PluginRuntimeRequestHistory.class))) - .thenAnswer( - invocation -> { - receipt[0] = invocation.getArgument(0); - return receipt[0]; - }); + .thenAnswer(invocation -> { + receipt[0] = invocation.getArgument(0); + return receipt[0]; + }); PluginRuntimeStateServiceImpl service = service(repository, eventRepository, historyRepository); PluginRuntimeStateService.PluginStateCommand command = new PluginRuntimeStateService.PluginStateCommand( @@ -652,11 +649,10 @@ void drainOfAbsentStateRecordsOneStableFailureAndCannotBeReplayedAfterActivation assertThat(receipt[0].getPluginActivationEpoch()).isZero(); assertThat(receipt[0].getLifecycleRevision()).isZero(); assertThat(service.drain(command)).isFalse(); - assertThatThrownBy( - () -> - service.drain( - new PluginRuntimeStateService.PluginStateCommand( - "1", "game-1", "plugin-1", "drain-1", "operator", "changed-reason"))) + assertThatThrownBy(() -> + service.drain( + new PluginRuntimeStateService.PluginStateCommand( + "1", "game-1", "plugin-1", "drain-1", "operator", "changed-reason"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("control_plane_request_id already records a different plugin request"); @@ -829,17 +825,16 @@ void activationRejectsRequestIdRecordedForDrainBeforeAnyMutation() { preflightService, historyRepository); - assertThatThrownBy( - () -> - service.setActiveVersion( - new PluginRuntimeStateService.ActivationCommand( - "1", - "game-1", - "plugin-1", - "plugin-v1", - "shared-request", - "operator", - "activate"))) + assertThatThrownBy(() -> + service.setActiveVersion( + new PluginRuntimeStateService.ActivationCommand( + "1", + "game-1", + "plugin-1", + "plugin-v1", + "shared-request", + "operator", + "activate"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("control_plane_request_id already records a different plugin request"); @@ -869,11 +864,10 @@ void drainRejectsRequestIdRecordedForActivationBeforeAnyMutation() { (tenantId, gameInstanceId, scriptPatchVersion, pluginId, pluginVersionId) -> {}, historyRepository); - assertThatThrownBy( - () -> - service.drain( - new PluginRuntimeStateService.PluginStateCommand( - "1", "game-1", "plugin-1", "shared-request", "operator", "operator_drain"))) + assertThatThrownBy(() -> + service.drain( + new PluginRuntimeStateService.PluginStateCommand( + "1", "game-1", "plugin-1", "shared-request", "operator", "operator_drain"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("control_plane_request_id already records a different plugin request"); @@ -908,17 +902,16 @@ void changedActivationInputWithSameRequestIdIsRejectedBeforePreflight() { preflightService, historyRepository); - assertThatThrownBy( - () -> - service.setActiveVersion( - new PluginRuntimeStateService.ActivationCommand( - "1", - "game-1", - "plugin-1", - "plugin-v2", - "activation-request", - "operator", - "activate"))) + assertThatThrownBy(() -> + service.setActiveVersion( + new PluginRuntimeStateService.ActivationCommand( + "1", + "game-1", + "plugin-1", + "plugin-v2", + "activation-request", + "operator", + "activate"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("control_plane_request_id already records a different plugin request"); @@ -940,17 +933,16 @@ void activationRejectsCurrentRowRequestIdWithoutImmutableHistory() { .thenReturn(Optional.of(existing)); PluginRuntimeStateService service = service(repository, eventRepository, historyRepository); - assertThatThrownBy( - () -> - service.setActiveVersion( - new PluginRuntimeStateService.ActivationCommand( - "1", - "game-1", - "plugin-1", - "plugin-v1", - "reused-request", - "operator", - "activate"))) + assertThatThrownBy(() -> + service.setActiveVersion( + new PluginRuntimeStateService.ActivationCommand( + "1", + "game-1", + "plugin-1", + "plugin-v1", + "reused-request", + "operator", + "activate"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("control_plane_request_id has no immutable activation request history"); @@ -971,11 +963,10 @@ void transitionRejectsCurrentRowRequestIdWithoutImmutableHistory() { .thenReturn(Optional.of(existing)); PluginRuntimeStateService service = service(repository, eventRepository, historyRepository); - assertThatThrownBy( - () -> - service.disable( - new PluginRuntimeStateService.PluginStateCommand( - "1", "game-1", "plugin-1", "reused-request", "operator", "disable"))) + assertThatThrownBy(() -> + service.disable( + new PluginRuntimeStateService.PluginStateCommand( + "1", "game-1", "plugin-1", "reused-request", "operator", "disable"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("control_plane_request_id has no immutable plugin state request history"); @@ -1111,11 +1102,10 @@ void rejectsMissingActivationTarget() { Mockito.mock(GameSessionControlPlaneClient.class), Mockito.mock(ScriptScheduleInstanceService.class)); - assertThatThrownBy( - () -> - service.setActiveVersion( - new PluginRuntimeStateService.ActivationCommand( - "1", "game-1", "plugin-1", "", "req-1", "admin", ""))) + assertThatThrownBy(() -> + service.setActiveVersion( + new PluginRuntimeStateService.ActivationCommand( + "1", "game-1", "plugin-1", "", "req-1", "admin", ""))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("target_plugin_version_id is required"); } @@ -1132,11 +1122,10 @@ void rejectsOversizedActivationRequestIdBeforePersistence() { Mockito.mock(GameSessionControlPlaneClient.class), Mockito.mock(ScriptScheduleInstanceService.class)); - assertThatThrownBy( - () -> - service.setActiveVersion( - new PluginRuntimeStateService.ActivationCommand( - "1", "game-1", "plugin-1", "plugin-v1", "r".repeat(129), "admin", ""))) + assertThatThrownBy(() -> + service.setActiveVersion( + new PluginRuntimeStateService.ActivationCommand( + "1", "game-1", "plugin-1", "plugin-v1", "r".repeat(129), "admin", ""))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("control_plane_request_id must be at most 128 characters"); Mockito.verify(repository, Mockito.never()).save(Mockito.any()); @@ -1155,11 +1144,10 @@ void rejectsOversizedLifecycleRequestIdBeforePersistence() { Mockito.mock(GameSessionControlPlaneClient.class), Mockito.mock(ScriptScheduleInstanceService.class)); - assertThatThrownBy( - () -> - service.disable( - new PluginRuntimeStateService.PluginStateCommand( - "1", "game-1", "plugin-1", "r".repeat(129), "admin", ""))) + assertThatThrownBy(() -> + service.disable( + new PluginRuntimeStateService.PluginStateCommand( + "1", "game-1", "plugin-1", "r".repeat(129), "admin", ""))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("control_plane_request_id must be at most 128 characters"); Mockito.verify(repository, Mockito.never()).save(Mockito.any()); @@ -1202,11 +1190,10 @@ void rejectsActivationWhenSignerIsRevoked() { gameSessionClient, Mockito.mock(ScriptScheduleInstanceService.class)); - assertThatThrownBy( - () -> - service.setActiveVersion( - new PluginRuntimeStateService.ActivationCommand( - "1", "game-1", "plugin-1", "plugin-v1", "req-1", "admin", "activation"))) + assertThatThrownBy(() -> + service.setActiveVersion( + new PluginRuntimeStateService.ActivationCommand( + "1", "game-1", "plugin-1", "plugin-v1", "req-1", "admin", "activation"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("PLUGIN_SIGNER_REVOKED: plugin signer is revoked for activation"); Mockito.verifyNoInteractions(gameSessionClient); @@ -1248,11 +1235,10 @@ void rejectsActivationWhenComponentPolicyBlocksPlugin() { gameSessionClient, Mockito.mock(ScriptScheduleInstanceService.class)); - assertThatThrownBy( - () -> - service.setActiveVersion( - new PluginRuntimeStateService.ActivationCommand( - "1", "game-1", "plugin-1", "plugin-v1", "req-1", "admin", "activation"))) + assertThatThrownBy(() -> + service.setActiveVersion( + new PluginRuntimeStateService.ActivationCommand( + "1", "game-1", "plugin-1", "plugin-v1", "req-1", "admin", "activation"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("PLUGIN_COMPONENT_POLICY_BLOCKED: plugin component policy blocks activation"); Mockito.verifyNoInteractions(gameSessionClient); @@ -1322,11 +1308,10 @@ void rejectsActivationWhenBaseVersionDoesNotMatchRuntime() { gameSessionClient, Mockito.mock(ScriptScheduleInstanceService.class)); - assertThatThrownBy( - () -> - service.setActiveVersion( - new PluginRuntimeStateService.ActivationCommand( - "1", "game-1", "plugin-1", "plugin-v1", "req-1", "admin", "activation"))) + assertThatThrownBy(() -> + service.setActiveVersion( + new PluginRuntimeStateService.ActivationCommand( + "1", "game-1", "plugin-1", "plugin-v1", "req-1", "admin", "activation"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage( "PLUGIN_BASE_VERSION_MISMATCH: plugin base version does not match runtime version"); @@ -1365,11 +1350,10 @@ void rejectsActivationWhenRuntimeVersionIdIsNonPositiveBeforeReleaseBundleLookup gameSessionClient, scheduleInstanceService); - assertThatThrownBy( - () -> - service.setActiveVersion( - new PluginRuntimeStateService.ActivationCommand( - "1", "game-1", "plugin-1", "plugin-v1", "req-1", "admin", "activation"))) + assertThatThrownBy(() -> + service.setActiveVersion( + new PluginRuntimeStateService.ActivationCommand( + "1", "game-1", "plugin-1", "plugin-v1", "req-1", "admin", "activation"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("GAME_INSTANCE_RUNTIME_UNAVAILABLE: runtimeVersionId must be positive"); Mockito.verify(gameDesignClient, Mockito.never()) @@ -1440,11 +1424,10 @@ void rejectsActivationWhenAbilitySchemaDigestDoesNotMatchRuntimeVersion() { gameSessionClient, Mockito.mock(ScriptScheduleInstanceService.class)); - assertThatThrownBy( - () -> - service.setActiveVersion( - new PluginRuntimeStateService.ActivationCommand( - "1", "game-1", "plugin-1", "plugin-v1", "req-1", "admin", "activation"))) + assertThatThrownBy(() -> + service.setActiveVersion( + new PluginRuntimeStateService.ActivationCommand( + "1", "game-1", "plugin-1", "plugin-v1", "req-1", "admin", "activation"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage( "PLUGIN_ABILITY_SCHEMA_MISMATCH: plugin ability schema digest does not match runtime version"); @@ -1593,18 +1576,17 @@ void policyDecisionCommitsBeforeNextLifecycleLockIsAcquired() { AtomicInteger committedTransactions = new AtomicInteger(); List lockedPluginIds = new ArrayList<>(); when(transactionManager.getTransaction(Mockito.any(TransactionDefinition.class))) - .thenAnswer( - invocation -> { - TransactionDefinition definition = invocation.getArgument(0); - assertThat(definition.getPropagationBehavior()) - .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertThat(transactionActive.get()).isFalse(); - assertThat(lifecycleLockHeld.get()).isFalse(); - assertThat(acquiredLocks.get()).isEqualTo(committedTransactions.get()); - assertThat(externalReads.get()).isEqualTo(4); - transactionActive.set(true); - return new SimpleTransactionStatus(); - }); + .thenAnswer(invocation -> { + TransactionDefinition definition = invocation.getArgument(0); + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(transactionActive.get()).isFalse(); + assertThat(lifecycleLockHeld.get()).isFalse(); + assertThat(acquiredLocks.get()).isEqualTo(committedTransactions.get()); + assertThat(externalReads.get()).isEqualTo(4); + transactionActive.set(true); + return new SimpleTransactionStatus(); + }); Mockito.doAnswer( invocation -> { assertThat(transactionActive.get()).isTrue(); @@ -1648,12 +1630,11 @@ void policyDecisionCommitsBeforeNextLifecycleLockIsAcquired() { .thenAnswer(invocation -> invocation.getArgument(0)); when(gameDesignClient.getPublishedPluginVersion( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenAnswer( - invocation -> { - externalReads.incrementAndGet(); - return publishedPluginVersion( - PluginComponentPolicyDecision.PLUGIN_COMPONENT_POLICY_DECISION_ALLOWED, true); - }); + .thenAnswer(invocation -> { + externalReads.incrementAndGet(); + return publishedPluginVersion( + PluginComponentPolicyDecision.PLUGIN_COMPONENT_POLICY_DECISION_ALLOWED, true); + }); GetGameInstanceRuntimeStateResponse runtimeResponse = GetGameInstanceRuntimeStateResponse.newBuilder() .setRuntimeState( @@ -1665,11 +1646,10 @@ void policyDecisionCommitsBeforeNextLifecycleLockIsAcquired() { .build()) .build(); when(gameSessionClient.getGameInstanceRuntimeState("1", "game-1", "region-7")) - .thenAnswer( - invocation -> { - externalReads.incrementAndGet(); - return runtimeResponse; - }); + .thenAnswer(invocation -> { + externalReads.incrementAndGet(); + return runtimeResponse; + }); PluginRuntimeStateService service = new PluginRuntimeStateServiceImpl( repository, diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptDefinitionServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptDefinitionServiceImplTest.java index c4a2dbaa3d..14080773e9 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptDefinitionServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptDefinitionServiceImplTest.java @@ -314,17 +314,16 @@ void concurrentFirstWritesDoNotCompensateDurableWinnerWhenNonOwnerBindingFails() AtomicInteger saveCalls = new AtomicInteger(); CountDownLatch bothFirstWrites = new CountDownLatch(2); when(repository.saveWithCreationResult(any(ScriptDefinition.class))) - .thenAnswer( - invocation -> { - ScriptDefinition requested = invocation.getArgument(0); - bothFirstWrites.countDown(); - if (!bothFirstWrites.await(5, TimeUnit.SECONDS)) { - throw new IllegalStateException("concurrent first writes did not rendezvous"); - } - boolean owner = "{\"owner\":true}".equals(requested.getDefinition()); - saveCalls.incrementAndGet(); - return new ScriptDefinitionRepository.SaveResult(winner, owner); - }); + .thenAnswer(invocation -> { + ScriptDefinition requested = invocation.getArgument(0); + bothFirstWrites.countDown(); + if (!bothFirstWrites.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("concurrent first writes did not rendezvous"); + } + boolean owner = "{\"owner\":true}".equals(requested.getDefinition()); + saveCalls.incrementAndGet(); + return new ScriptDefinitionRepository.SaveResult(winner, owner); + }); doAnswer( invocation -> { Collection bindings = invocation.getArgument(0); @@ -342,9 +341,8 @@ void concurrentFirstWritesDoNotCompensateDurableWinnerWhenNonOwnerBindingFails() executor.submit( () -> service.updateScript(firstWriteDto("{\"owner\":true}", "binding-owner"))); Future nonOwner = - executor.submit( - () -> - service.updateScript(firstWriteDto("{\"non-owner\":true}", "binding-non-owner"))); + executor.submit(() -> + service.updateScript(firstWriteDto("{\"non-owner\":true}", "binding-non-owner"))); assertNotNull(owner.get(10, TimeUnit.SECONDS)); assertThatThrownBy(() -> nonOwner.get(10, TimeUnit.SECONDS)) diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressRequestDigestTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressRequestDigestTest.java index 1166de94b8..182ffecf64 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressRequestDigestTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressRequestDigestTest.java @@ -102,23 +102,19 @@ void bindsEachImmutableEventIdentityField() { "scriptPatchVersion", original.toBuilder().setScriptPatchVersion("patch-2").build()); assertThat(changedFields) - .allSatisfy( - (field, changed) -> - assertThat( - ScriptEventIngressRequestDigest.compute( - changed, "v1", "game-session-service")) - .as("changing %s", field) - .isNotEqualTo(originalDigest)); + .allSatisfy((field, changed) -> + assertThat( + ScriptEventIngressRequestDigest.compute(changed, "v1", "game-session-service")) + .as("changing %s", field) + .isNotEqualTo(originalDigest)); } @Test void rejectsDuplicateJsonObjectKeys() { TriggerScriptEventRequest duplicateKeys = request("{\"a\":1,\"a\":2}"); - assertThatThrownBy( - () -> - ScriptEventIngressRequestDigest.compute( - duplicateKeys, "v1", "game-session-service")) + assertThatThrownBy(() -> + ScriptEventIngressRequestDigest.compute(duplicateKeys, "v1", "game-session-service")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("JSON payload contains duplicate keys"); } @@ -127,10 +123,8 @@ void rejectsDuplicateJsonObjectKeys() { void rejectsDuplicateKeysAfterNfcNormalization() { TriggerScriptEventRequest duplicateKeys = request("{\"\\u00e9\":1,\"e\\u0301\":2}"); - assertThatThrownBy( - () -> - ScriptEventIngressRequestDigest.compute( - duplicateKeys, "v1", "game-session-service")) + assertThatThrownBy(() -> + ScriptEventIngressRequestDigest.compute(duplicateKeys, "v1", "game-session-service")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("duplicate keys after NFC normalization"); } diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java index ea59e034e5..516dd1599d 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptEventIngressServiceImplTest.java @@ -4333,26 +4333,24 @@ void concurrentIdenticalAdmissionsHaveOneClaimingResolver() throws Exception { AtomicReference row = new AtomicReference<>(); Object claimLock = new Object(); when(repository.insertIfAbsentByIdentity(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptEventIngressAudit candidate = invocation.getArgument(0); - boolean inserted; - synchronized (claimLock) { - inserted = row.compareAndSet(null, candidate); - if (inserted) { - candidate.setId(1L); - } - } - if (inserted) { - claimInserted.countDown(); - if (!allowWinnerToContinue.await(5, TimeUnit.SECONDS)) { - throw new AssertionError("timed out waiting for winner admission release"); - } - return new ScriptEventIngressAuditRepository.IdempotentInsertResult( - candidate, true); - } - return new ScriptEventIngressAuditRepository.IdempotentInsertResult(row.get(), false); - }); + .thenAnswer(invocation -> { + ScriptEventIngressAudit candidate = invocation.getArgument(0); + boolean inserted; + synchronized (claimLock) { + inserted = row.compareAndSet(null, candidate); + if (inserted) { + candidate.setId(1L); + } + } + if (inserted) { + claimInserted.countDown(); + if (!allowWinnerToContinue.await(5, TimeUnit.SECONDS)) { + throw new AssertionError("timed out waiting for winner admission release"); + } + return new ScriptEventIngressAuditRepository.IdempotentInsertResult(candidate, true); + } + return new ScriptEventIngressAuditRepository.IdempotentInsertResult(row.get(), false); + }); when(repository.renewClaimIfCurrent(Mockito.any(), Mockito.any())).thenReturn(true); when(repository.save(Mockito.any())).thenAnswer(invocation -> invocation.getArgument(0)); when(gameSessionClient.getGameInstanceRuntimeState("1", "game-1", "region-1")) @@ -4540,30 +4538,26 @@ void reclaimedClaimFencesStalledOwnerBeforeQuotaOrWorkItemEffects() throws Excep CountDownLatch releaseOldOwner = new CountDownLatch(1); AtomicInteger bindingCalls = new AtomicInteger(); when(repository.insertIfAbsentByIdentity(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptEventIngressAudit candidate = invocation.getArgument(0); - if (row.compareAndSet(null, candidate)) { - candidate.setId(11L); - candidate.setClaimStartedAt(java.time.Instant.now().minusSeconds(60)); - return new ScriptEventIngressAuditRepository.IdempotentInsertResult( - candidate, true); - } - return new ScriptEventIngressAuditRepository.IdempotentInsertResult(row.get(), false); - }); + .thenAnswer(invocation -> { + ScriptEventIngressAudit candidate = invocation.getArgument(0); + if (row.compareAndSet(null, candidate)) { + candidate.setId(11L); + candidate.setClaimStartedAt(java.time.Instant.now().minusSeconds(60)); + return new ScriptEventIngressAuditRepository.IdempotentInsertResult(candidate, true); + } + return new ScriptEventIngressAuditRepository.IdempotentInsertResult(row.get(), false); + }); when(repository.reclaimStaleInProgress(Mockito.any(), Mockito.any(), Mockito.any())) - .thenAnswer( - invocation -> { - row.get().setRowVersion(1); - return Optional.of(reclaimed); - }); + .thenAnswer(invocation -> { + row.get().setRowVersion(1); + return Optional.of(reclaimed); + }); when(repository.renewClaimIfCurrent(Mockito.any(), Mockito.any())) - .thenAnswer( - invocation -> { - ScriptEventIngressAudit claim = invocation.getArgument(0); - return (claim == row.get() && claim.getRowVersion() == 0) - || (claim == reclaimed && claim.getRowVersion() == 1); - }); + .thenAnswer(invocation -> { + ScriptEventIngressAudit claim = invocation.getArgument(0); + return (claim == row.get() && claim.getRowVersion() == 0) + || (claim == reclaimed && claim.getRowVersion() == 1); + }); when(repository.save(Mockito.any())).thenAnswer(invocation -> invocation.getArgument(0)); when(bindingRepository .findByTenantIdAndScriptPatchVersionAndEventTypeAndEventSchemaVersionAndEnabledTrueOrderByPriorityAscScriptIdAsc( @@ -4572,17 +4566,16 @@ void reclaimedClaimFencesStalledOwnerBeforeQuotaOrWorkItemEffects() throws Excep Mockito.anyLong(), Mockito.anyString(), Mockito.anyString())) - .thenAnswer( - invocation -> { - if (bindingCalls.getAndIncrement() == 0) { - oldOwnerEnteredResolution.countDown(); - if (!releaseOldOwner.await(5, TimeUnit.SECONDS)) { - throw new AssertionError("timed out waiting for claim reclaim"); - } - return List.of(binding("script-1", "ENTITY", "entity-1", "normal")); - } - return List.of(); - }); + .thenAnswer(invocation -> { + if (bindingCalls.getAndIncrement() == 0) { + oldOwnerEnteredResolution.countDown(); + if (!releaseOldOwner.await(5, TimeUnit.SECONDS)) { + throw new AssertionError("timed out waiting for claim reclaim"); + } + return List.of(binding("script-1", "ENTITY", "entity-1", "normal")); + } + return List.of(); + }); GameSessionControlPlaneClient gameSessionClient = Mockito.mock(GameSessionControlPlaneClient.class); when(gameSessionClient.getGameInstanceRuntimeState("1", "game-1", "region-1")) @@ -4803,14 +4796,13 @@ void pluginAdmissionClaimsBeforeReadingAndFinalizesWithThePositiveRuntimeFence() AtomicReference claimedActivationEpoch = new AtomicReference<>(); AtomicReference claimedLifecycleRevision = new AtomicReference<>(); when(repository.insertIfAbsentByIdentity(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptEventIngressAudit claim = invocation.getArgument(0); - claimedActivationEpoch.set(claim.getPluginActivationEpoch()); - claimedLifecycleRevision.set(claim.getLifecycleRevision()); - claim.setId(9L); - return new ScriptEventIngressAuditRepository.IdempotentInsertResult(claim, true); - }); + .thenAnswer(invocation -> { + ScriptEventIngressAudit claim = invocation.getArgument(0); + claimedActivationEpoch.set(claim.getPluginActivationEpoch()); + claimedLifecycleRevision.set(claim.getLifecycleRevision()); + claim.setId(9L); + return new ScriptEventIngressAuditRepository.IdempotentInsertResult(claim, true); + }); when(repository.renewClaimIfCurrent(Mockito.any(), Mockito.any())).thenReturn(true); ScriptEventBindingRepository bindingRepository = Mockito.mock(ScriptEventBindingRepository.class); @@ -5002,12 +4994,11 @@ void postClaimFailureLeavesClaimInProgressAndDoesNotFanOut() { ArgumentCaptor claimCaptor = ArgumentCaptor.forClass(ScriptEventIngressAudit.class); when(repository.insertIfAbsentByIdentity(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptEventIngressAudit claim = invocation.getArgument(0); - claim.setId(8L); - return new ScriptEventIngressAuditRepository.IdempotentInsertResult(claim, true); - }); + .thenAnswer(invocation -> { + ScriptEventIngressAudit claim = invocation.getArgument(0); + claim.setId(8L); + return new ScriptEventIngressAuditRepository.IdempotentInsertResult(claim, true); + }); when(repository.renewClaimIfCurrent(Mockito.any(), Mockito.any())).thenReturn(true); when(bindingRepository .findByTenantIdAndScriptPatchVersionAndEventTypeAndEventSchemaVersionAndEnabledTrueOrderByPriorityAscScriptIdAsc( @@ -5078,10 +5069,9 @@ void missingPersistedClaimIdFailsClosedBeforeHandlerEffects() { ScriptEventIngressAuditRepository repository = Mockito.mock(ScriptEventIngressAuditRepository.class); when(repository.insertIfAbsentByIdentity(Mockito.any())) - .thenAnswer( - invocation -> - new ScriptEventIngressAuditRepository.IdempotentInsertResult( - invocation.getArgument(0), true)); + .thenAnswer(invocation -> + new ScriptEventIngressAuditRepository.IdempotentInsertResult( + invocation.getArgument(0), true)); ScriptEventBindingRepository bindingRepository = Mockito.mock(ScriptEventBindingRepository.class); ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); @@ -5156,12 +5146,11 @@ private static ScriptEventIngressService claimTestService( private static void stubClaimRepository(ScriptEventIngressAuditRepository repository) { when(repository.insertIfAbsentByIdentity(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptEventIngressAudit claim = invocation.getArgument(0); - claim.setId(1L); - return new ScriptEventIngressAuditRepository.IdempotentInsertResult(claim, true); - }); + .thenAnswer(invocation -> { + ScriptEventIngressAudit claim = invocation.getArgument(0); + claim.setId(1L); + return new ScriptEventIngressAuditRepository.IdempotentInsertResult(claim, true); + }); when(repository.renewClaimIfCurrent(Mockito.any(), Mockito.any())).thenReturn(true); } diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java index 516bb1c72a..c36cd6f19e 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptGameplayCommandHandoffServiceImplTest.java @@ -162,23 +162,21 @@ void intentCommitsBeforeGameSessionRpcAndRpcRunsWithoutLocalTransaction() { GameSessionControlPlaneClient gameSessionClient = Mockito.mock(GameSessionControlPlaneClient.class); when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) - .thenAnswer( - invocation -> { - operations.add( - "runtime:" + TransactionSynchronizationManager.isActualTransactionActive()); - return currentRuntimeState(); - }); + .thenAnswer(invocation -> { + operations.add( + "runtime:" + TransactionSynchronizationManager.isActualTransactionActive()); + return currentRuntimeState(); + }); when(gameSessionClient.enqueueAutomationCommandIfAbsent(Mockito.any())) - .thenAnswer( - invocation -> { - operations.add( - "enqueue:" + TransactionSynchronizationManager.isActualTransactionActive()); - return EnqueueAutomationCommandIfAbsentResponse.newBuilder() - .setAccepted(true) - .setAdmissionOutcome("ENQUEUED") - .setCommandId("command-1") - .build(); - }); + .thenAnswer(invocation -> { + operations.add( + "enqueue:" + TransactionSynchronizationManager.isActualTransactionActive()); + return EnqueueAutomationCommandIfAbsentResponse.newBuilder() + .setAccepted(true) + .setAdmissionOutcome("ENQUEUED") + .setCommandId("command-1") + .build(); + }); ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); when(workItemRepository.save(Mockito.any())) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -186,27 +184,25 @@ void intentCommitsBeforeGameSessionRpcAndRpcRunsWithoutLocalTransaction() { Mockito.mock(ScriptHandoffEventRepository.class); List savedEvents = new ArrayList<>(); when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) - .thenAnswer( - invocation -> - savedEvents.isEmpty() ? Optional.empty() : Optional.of(savedEvents.getLast())); + .thenAnswer(invocation -> + savedEvents.isEmpty() ? Optional.empty() : Optional.of(savedEvents.getLast())); when(handoffEventRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptHandoffEvent event = invocation.getArgument(0); - if (event.getId() == null) { - event.setId(44L); - event.setRowVersion(0); - } else { - event.setRowVersion(event.getRowVersion() + 1); - } - savedEvents.add(event); - operations.add( - "handoff-save:" - + ("handoff_in_flight".equals(event.getHandoffOutcome()) - ? "intent" - : "response")); - return event; - }); + .thenAnswer(invocation -> { + ScriptHandoffEvent event = invocation.getArgument(0); + if (event.getId() == null) { + event.setId(44L); + event.setRowVersion(0); + } else { + event.setRowVersion(event.getRowVersion() + 1); + } + savedEvents.add(event); + operations.add( + "handoff-save:" + + ("handoff_in_flight".equals(event.getHandoffOutcome()) + ? "intent" + : "response")); + return event; + }); ScriptGameplayCommandHandoffServiceImpl service = new ScriptGameplayCommandHandoffServiceImpl( @@ -278,48 +274,46 @@ void concurrentAcceptedResultAfterResponseCheckCannotBeReplacedByStaleResponse() ScriptGameplayCommandHandoffService.EmittedCommand command = emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0); when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) - .thenAnswer( - invocation -> { - if (intentSaved.get() && concurrentWinnerInjected.compareAndSet(false, true)) { - ScriptHandoffEvent intent = persisted.get(); - ScriptHandoffEvent checkedIntent = - acceptedHandoffEvent(item, command, "handoff_in_flight"); - checkedIntent.setId(intent.getId()); - checkedIntent.setRowVersion(intent.getRowVersion()); - // Model a retry that commits after this response transaction has read the intent - // but before it attempts to append its older downstream response. - ScriptHandoffEvent winner = acceptedHandoffEvent(item, command, "duplicate_noop"); - winner.setId(intent.getId()); - winner.setRowVersion(intent.getRowVersion() + 1); - winner.setGameSessionCommandId("winner-command"); - persisted.set(winner); - return Optional.of(checkedIntent); - } - return Optional.ofNullable(persisted.get()); - }); + .thenAnswer(invocation -> { + if (intentSaved.get() && concurrentWinnerInjected.compareAndSet(false, true)) { + ScriptHandoffEvent intent = persisted.get(); + ScriptHandoffEvent checkedIntent = + acceptedHandoffEvent(item, command, "handoff_in_flight"); + checkedIntent.setId(intent.getId()); + checkedIntent.setRowVersion(intent.getRowVersion()); + // Model a retry that commits after this response transaction has read the intent + // but before it attempts to append its older downstream response. + ScriptHandoffEvent winner = acceptedHandoffEvent(item, command, "duplicate_noop"); + winner.setId(intent.getId()); + winner.setRowVersion(intent.getRowVersion() + 1); + winner.setGameSessionCommandId("winner-command"); + persisted.set(winner); + return Optional.of(checkedIntent); + } + return Optional.ofNullable(persisted.get()); + }); when(handoffEventRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptHandoffEvent event = invocation.getArgument(0); - saveCount.incrementAndGet(); - ScriptHandoffEvent current = persisted.get(); - if (event.getId() == null) { - event.setId(44L); - event.setRowVersion(5); - persisted.set(event); - intentSaved.set(true); - return event; - } - attemptedResponseWrite.set(event); - if (current == null - || !event.getId().equals(current.getId()) - || event.getRowVersion() != current.getRowVersion()) { - throw new IllegalStateException("stale handoff event write"); - } - event.setRowVersion(event.getRowVersion() + 1); - persisted.set(event); - return event; - }); + .thenAnswer(invocation -> { + ScriptHandoffEvent event = invocation.getArgument(0); + saveCount.incrementAndGet(); + ScriptHandoffEvent current = persisted.get(); + if (event.getId() == null) { + event.setId(44L); + event.setRowVersion(5); + persisted.set(event); + intentSaved.set(true); + return event; + } + attemptedResponseWrite.set(event); + if (current == null + || !event.getId().equals(current.getId()) + || event.getRowVersion() != current.getRowVersion()) { + throw new IllegalStateException("stale handoff event write"); + } + event.setRowVersion(event.getRowVersion() + 1); + persisted.set(event); + return event; + }); ScriptGameplayCommandHandoffServiceImpl service = new ScriptGameplayCommandHandoffServiceImpl( gameSessionClient, @@ -368,31 +362,29 @@ void retainedCommandResponseDoesNotAcceptMismatchedConcurrentChildWinner() { AtomicBoolean winnerInjected = new AtomicBoolean(); AtomicInteger saveCount = new AtomicInteger(); when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) - .thenAnswer( - invocation -> { - if (intentSaved.get() && winnerInjected.compareAndSet(false, true)) { - ScriptHandoffEvent intent = persisted.get(); - ScriptHandoffEvent winner = - concurrentAcceptedChild(item, command, intent, "retained-command"); - winner.setTargetEntityId("different-child"); - persisted.set(winner); - return Optional.of(winner); - } - return Optional.ofNullable(persisted.get()); - }); + .thenAnswer(invocation -> { + if (intentSaved.get() && winnerInjected.compareAndSet(false, true)) { + ScriptHandoffEvent intent = persisted.get(); + ScriptHandoffEvent winner = + concurrentAcceptedChild(item, command, intent, "retained-command"); + winner.setTargetEntityId("different-child"); + persisted.set(winner); + return Optional.of(winner); + } + return Optional.ofNullable(persisted.get()); + }); when(handoffEventRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptHandoffEvent event = invocation.getArgument(0); - saveCount.incrementAndGet(); - if (event.getId() == null) { - event.setId(44L); - event.setRowVersion(5); - persisted.set(event); - intentSaved.set(true); - } - return event; - }); + .thenAnswer(invocation -> { + ScriptHandoffEvent event = invocation.getArgument(0); + saveCount.incrementAndGet(); + if (event.getId() == null) { + event.setId(44L); + event.setRowVersion(5); + persisted.set(event); + intentSaved.set(true); + } + return event; + }); ScriptGameplayCommandHandoffServiceImpl service = handoffServiceForTest(gameSessionClient, handoffEventRepository); @@ -426,30 +418,28 @@ void retainedCommandResponseConvergesOnMatchingConcurrentAcceptedChild() { AtomicBoolean winnerInjected = new AtomicBoolean(); AtomicInteger saveCount = new AtomicInteger(); when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) - .thenAnswer( - invocation -> { - if (intentSaved.get() && winnerInjected.compareAndSet(false, true)) { - ScriptHandoffEvent intent = persisted.get(); - ScriptHandoffEvent winner = - concurrentAcceptedChild(item, command, intent, "retained-command"); - persisted.set(winner); - return Optional.of(winner); - } - return Optional.ofNullable(persisted.get()); - }); + .thenAnswer(invocation -> { + if (intentSaved.get() && winnerInjected.compareAndSet(false, true)) { + ScriptHandoffEvent intent = persisted.get(); + ScriptHandoffEvent winner = + concurrentAcceptedChild(item, command, intent, "retained-command"); + persisted.set(winner); + return Optional.of(winner); + } + return Optional.ofNullable(persisted.get()); + }); when(handoffEventRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptHandoffEvent event = invocation.getArgument(0); - saveCount.incrementAndGet(); - if (event.getId() == null) { - event.setId(44L); - event.setRowVersion(5); - persisted.set(event); - intentSaved.set(true); - } - return event; - }); + .thenAnswer(invocation -> { + ScriptHandoffEvent event = invocation.getArgument(0); + saveCount.incrementAndGet(); + if (event.getId() == null) { + event.setId(44L); + event.setRowVersion(5); + persisted.set(event); + intentSaved.set(true); + } + return event; + }); ScriptGameplayCommandHandoffServiceImpl service = handoffServiceForTest(gameSessionClient, handoffEventRepository); @@ -486,32 +476,30 @@ void retainedCommandResponseDoesNotOverwriteAdvancedOrConflictingIntent( AtomicBoolean mutationInjected = new AtomicBoolean(); AtomicInteger saveCount = new AtomicInteger(); when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) - .thenAnswer( - invocation -> { - if (intentSaved.get() && mutationInjected.compareAndSet(false, true)) { - ScriptHandoffEvent intent = persisted.get(); - ScriptHandoffEvent changed = acceptedHandoffEvent(item, command, currentOutcome); - changed.setId(intent.getId()); - changed.setRowVersion(currentRowVersion); - changed.setGameSessionCommandId(currentCommandId); - persisted.set(changed); - return Optional.of(changed); - } - return Optional.ofNullable(persisted.get()); - }); + .thenAnswer(invocation -> { + if (intentSaved.get() && mutationInjected.compareAndSet(false, true)) { + ScriptHandoffEvent intent = persisted.get(); + ScriptHandoffEvent changed = acceptedHandoffEvent(item, command, currentOutcome); + changed.setId(intent.getId()); + changed.setRowVersion(currentRowVersion); + changed.setGameSessionCommandId(currentCommandId); + persisted.set(changed); + return Optional.of(changed); + } + return Optional.ofNullable(persisted.get()); + }); when(handoffEventRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptHandoffEvent event = invocation.getArgument(0); - saveCount.incrementAndGet(); - if (event.getId() == null) { - event.setId(44L); - event.setRowVersion(5); - persisted.set(event); - intentSaved.set(true); - } - return event; - }); + .thenAnswer(invocation -> { + ScriptHandoffEvent event = invocation.getArgument(0); + saveCount.incrementAndGet(); + if (event.getId() == null) { + event.setId(44L); + event.setRowVersion(5); + persisted.set(event); + intentSaved.set(true); + } + return event; + }); ScriptGameplayCommandHandoffServiceImpl service = handoffServiceForTest(gameSessionClient, handoffEventRepository); @@ -552,31 +540,29 @@ void definitiveResponseDoesNotAcceptConcurrentWinnerWithDifferentIdentityOrComma AtomicBoolean winnerInjected = new AtomicBoolean(); AtomicInteger saveCount = new AtomicInteger(); when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) - .thenAnswer( - invocation -> { - if (intentSaved.get() && winnerInjected.compareAndSet(false, true)) { - ScriptHandoffEvent intent = persisted.get(); - ScriptHandoffEvent winner = - concurrentAcceptedChild(item, command, intent, winnerCommandId); - winner.setTargetEntityId(winnerTargetEntityId); - persisted.set(winner); - return Optional.of(winner); - } - return Optional.ofNullable(persisted.get()); - }); + .thenAnswer(invocation -> { + if (intentSaved.get() && winnerInjected.compareAndSet(false, true)) { + ScriptHandoffEvent intent = persisted.get(); + ScriptHandoffEvent winner = + concurrentAcceptedChild(item, command, intent, winnerCommandId); + winner.setTargetEntityId(winnerTargetEntityId); + persisted.set(winner); + return Optional.of(winner); + } + return Optional.ofNullable(persisted.get()); + }); when(handoffEventRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptHandoffEvent event = invocation.getArgument(0); - saveCount.incrementAndGet(); - if (event.getId() == null) { - event.setId(44L); - event.setRowVersion(5); - persisted.set(event); - intentSaved.set(true); - } - return event; - }); + .thenAnswer(invocation -> { + ScriptHandoffEvent event = invocation.getArgument(0); + saveCount.incrementAndGet(); + if (event.getId() == null) { + event.setId(44L); + event.setRowVersion(5); + persisted.set(event); + intentSaved.set(true); + } + return event; + }); ScriptGameplayCommandHandoffServiceImpl service = handoffServiceForTest(gameSessionClient, handoffEventRepository); @@ -615,38 +601,35 @@ void failedIntentCommitIsRetryableWhenCapturedStateMatchesAndNeverCallsCommandRp when(workItemRepository.findById(99L)).thenReturn(Optional.of(persistedWorkItem)); List savedRowVersions = new ArrayList<>(); when(workItemRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptWorkItem saved = invocation.getArgument(0); - savedRowVersions.add(saved.getRowVersion()); - saved.setRowVersion(saved.getRowVersion() + 1); - return saved; - }); + .thenAnswer(invocation -> { + ScriptWorkItem saved = invocation.getArgument(0); + savedRowVersions.add(saved.getRowVersion()); + saved.setRowVersion(saved.getRowVersion() + 1); + return saved; + }); ScriptHandoffEventRepository handoffEventRepository = Mockito.mock(ScriptHandoffEventRepository.class); AtomicReference siblingIntent = new AtomicReference<>(); when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal( Mockito.eq("1"), Mockito.eq(99L), Mockito.anyInt())) - .thenAnswer( - invocation -> - invocation.getArgument(2) == 1 - ? Optional.ofNullable(siblingIntent.get()) - : Optional.empty()); + .thenAnswer(invocation -> + invocation.getArgument(2) == 1 + ? Optional.ofNullable(siblingIntent.get()) + : Optional.empty()); when(handoffEventRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptHandoffEvent event = invocation.getArgument(0); - if (event.getCommandOrdinal() == 1) { - if (event.getId() == null) { - event.setId(45L); - event.setRowVersion(0); - } else { - event.setRowVersion(event.getRowVersion() + 1); - } - siblingIntent.set(event); - } - return event; - }); + .thenAnswer(invocation -> { + ScriptHandoffEvent event = invocation.getArgument(0); + if (event.getCommandOrdinal() == 1) { + if (event.getId() == null) { + event.setId(45L); + event.setRowVersion(0); + } else { + event.setRowVersion(event.getRowVersion() + 1); + } + siblingIntent.set(event); + } + return event; + }); ScriptWorkItem item = workItem(); item.setStatus(capturedStatus); ScriptGameplayCommandHandoffServiceImpl service = @@ -734,16 +717,15 @@ void failedMalformedOwnerIntentCommitRestoresDeadLetterPreparationMutations() { ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); when(workItemRepository.findById(99L)).thenReturn(Optional.of(persistedWorkItem)); when(workItemRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptWorkItem saved = invocation.getArgument(0); - assertThat(saved.getStatus()).isEqualTo("DEAD_LETTERED"); - assertThat(saved.getCancelReason()).isEqualTo("remote_response_invalid"); - assertThat(saved.getFailureGeneration()).isEqualTo(9L); - assertThat(saved.getUpdatedAt()).isNotEqualTo(originalUpdatedAt); - saved.setRowVersion(saved.getRowVersion() + 1); - return saved; - }); + .thenAnswer(invocation -> { + ScriptWorkItem saved = invocation.getArgument(0); + assertThat(saved.getStatus()).isEqualTo("DEAD_LETTERED"); + assertThat(saved.getCancelReason()).isEqualTo("remote_response_invalid"); + assertThat(saved.getFailureGeneration()).isEqualTo(9L); + assertThat(saved.getUpdatedAt()).isNotEqualTo(originalUpdatedAt); + saved.setRowVersion(saved.getRowVersion() + 1); + return saved; + }); ScriptHandoffEventRepository handoffEventRepository = Mockito.mock(ScriptHandoffEventRepository.class); when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) @@ -854,12 +836,11 @@ void failedIntentCommitWithoutIntentAndChangedStateRequiresReconciliation( persistedWorkItem.setRowVersion(persistedRowVersion); when(workItemRepository.findById(99L)).thenReturn(Optional.of(persistedWorkItem)); when(workItemRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptWorkItem saved = invocation.getArgument(0); - saved.setRowVersion(saved.getRowVersion() + 1); - return saved; - }); + .thenAnswer(invocation -> { + ScriptWorkItem saved = invocation.getArgument(0); + saved.setRowVersion(saved.getRowVersion() + 1); + return saved; + }); ScriptHandoffEventRepository handoffEventRepository = Mockito.mock(ScriptHandoffEventRepository.class); when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) @@ -914,14 +895,13 @@ void failedIntentCommitReadbackWithMatchingInFlightIntentRequiresReconciliation( ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); when(workItemRepository.findById(99L)).thenReturn(Optional.of(persistedWorkItem)); when(workItemRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptWorkItem saved = invocation.getArgument(0); - saved.setRowVersion(saved.getRowVersion() + 1); - persistedWorkItem.setStatus(saved.getStatus()); - persistedWorkItem.setRowVersion(saved.getRowVersion()); - return saved; - }); + .thenAnswer(invocation -> { + ScriptWorkItem saved = invocation.getArgument(0); + saved.setRowVersion(saved.getRowVersion() + 1); + persistedWorkItem.setStatus(saved.getStatus()); + persistedWorkItem.setRowVersion(saved.getRowVersion()); + return saved; + }); ScriptGameplayCommandHandoffService.EmittedCommand command = emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0); @@ -931,14 +911,13 @@ void failedIntentCommitReadbackWithMatchingInFlightIntentRequiresReconciliation( when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) .thenAnswer(invocation -> Optional.ofNullable(persistedIntent.get())); when(handoffEventRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptHandoffEvent saved = invocation.getArgument(0); - saved.setId(44L); - saved.setRowVersion(7); - persistedIntent.set(saved); - return saved; - }); + .thenAnswer(invocation -> { + ScriptHandoffEvent saved = invocation.getArgument(0); + saved.setId(44L); + saved.setRowVersion(7); + persistedIntent.set(saved); + return saved; + }); ScriptGameplayCommandHandoffServiceImpl service = new ScriptGameplayCommandHandoffServiceImpl( @@ -992,12 +971,11 @@ void failedIntentCommitWithUnchangedPriorRejectionIsRetryable(String priorOutcom ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); when(workItemRepository.findById(99L)).thenReturn(Optional.of(persistedWorkItem)); when(workItemRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptWorkItem saved = invocation.getArgument(0); - saved.setRowVersion(saved.getRowVersion() + 1); - return saved; - }); + .thenAnswer(invocation -> { + ScriptWorkItem saved = invocation.getArgument(0); + saved.setRowVersion(saved.getRowVersion() + 1); + return saved; + }); ScriptGameplayCommandHandoffService.EmittedCommand command = emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0); @@ -1060,12 +1038,11 @@ void failedIntentCommitWithConcurrentAcceptedWinnerRemainsUnresolved() { ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); when(workItemRepository.findById(99L)).thenReturn(Optional.of(persistedWorkItem)); when(workItemRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptWorkItem saved = invocation.getArgument(0); - saved.setRowVersion(saved.getRowVersion() + 1); - return saved; - }); + .thenAnswer(invocation -> { + ScriptWorkItem saved = invocation.getArgument(0); + saved.setRowVersion(saved.getRowVersion() + 1); + return saved; + }); ScriptGameplayCommandHandoffService.EmittedCommand command = emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0); @@ -1078,16 +1055,15 @@ void failedIntentCommitWithConcurrentAcceptedWinnerRemainsUnresolved() { when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) .thenAnswer(invocation -> Optional.of(durableIntent.get())); when(handoffEventRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptHandoffEvent attemptedIntent = invocation.getArgument(0); - ScriptHandoffEvent acceptedWinner = acceptedHandoffEvent(item, command, "enqueued"); - acceptedWinner.setId(attemptedIntent.getId()); - acceptedWinner.setRowVersion(attemptedIntent.getRowVersion() + 1); - acceptedWinner.setGameSessionCommandId("concurrent-command"); - durableIntent.set(acceptedWinner); - return attemptedIntent; - }); + .thenAnswer(invocation -> { + ScriptHandoffEvent attemptedIntent = invocation.getArgument(0); + ScriptHandoffEvent acceptedWinner = acceptedHandoffEvent(item, command, "enqueued"); + acceptedWinner.setId(attemptedIntent.getId()); + acceptedWinner.setRowVersion(attemptedIntent.getRowVersion() + 1); + acceptedWinner.setGameSessionCommandId("concurrent-command"); + durableIntent.set(acceptedWinner); + return attemptedIntent; + }); ScriptGameplayCommandHandoffServiceImpl service = new ScriptGameplayCommandHandoffServiceImpl( gameSessionClient, @@ -1133,12 +1109,11 @@ void failedIntentCommitWithPriorRejectionAndChangedWorkItemRequiresReconciliatio ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); when(workItemRepository.findById(99L)).thenReturn(Optional.of(persistedWorkItem)); when(workItemRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptWorkItem saved = invocation.getArgument(0); - saved.setRowVersion(saved.getRowVersion() + 1); - return saved; - }); + .thenAnswer(invocation -> { + ScriptWorkItem saved = invocation.getArgument(0); + saved.setRowVersion(saved.getRowVersion() + 1); + return saved; + }); ScriptGameplayCommandHandoffService.EmittedCommand command = emittedCommand("say hello", "entity-1", "7", "region-1", 12L, 34L, 0); @@ -1192,12 +1167,11 @@ void failedIntentCommitWithMismatchedDurableIdentityStillRequiresReconciliation( persistedWorkItem.setStatus("EVALUATING"); when(workItemRepository.findById(99L)).thenReturn(Optional.of(persistedWorkItem)); when(workItemRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptWorkItem saved = invocation.getArgument(0); - saved.setRowVersion(saved.getRowVersion() + 1); - return saved; - }); + .thenAnswer(invocation -> { + ScriptWorkItem saved = invocation.getArgument(0); + saved.setRowVersion(saved.getRowVersion() + 1); + return saved; + }); ScriptHandoffEventRepository handoffEventRepository = Mockito.mock(ScriptHandoffEventRepository.class); ScriptWorkItem item = workItem(); @@ -1210,19 +1184,17 @@ void failedIntentCommitWithMismatchedDurableIdentityStillRequiresReconciliation( AtomicBoolean intentSaved = new AtomicBoolean(); AtomicBoolean mismatchedReadReturned = new AtomicBoolean(); when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) - .thenAnswer( - invocation -> { - if (intentSaved.get() && mismatchedReadReturned.compareAndSet(false, true)) { - return Optional.of(mismatchedIntent); - } - return Optional.empty(); - }); + .thenAnswer(invocation -> { + if (intentSaved.get() && mismatchedReadReturned.compareAndSet(false, true)) { + return Optional.of(mismatchedIntent); + } + return Optional.empty(); + }); when(handoffEventRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - intentSaved.set(true); - return invocation.getArgument(0); - }); + .thenAnswer(invocation -> { + intentSaved.set(true); + return invocation.getArgument(0); + }); ScriptGameplayCommandHandoffServiceImpl service = new ScriptGameplayCommandHandoffServiceImpl( gameSessionClient, @@ -1387,12 +1359,11 @@ void retryableHandoffPublishesPointerAfterPendingStateAndProjection() { Mockito.mock(ScriptPatchInstanceRolloutProjectionService.class); List operations = new ArrayList<>(); when(workItemRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptWorkItem saved = invocation.getArgument(0); - operations.add("save:" + saved.getStatus()); - return saved; - }); + .thenAnswer(invocation -> { + ScriptWorkItem saved = invocation.getArgument(0); + operations.add("save:" + saved.getStatus()); + return saved; + }); Mockito.doAnswer( invocation -> { operations.add("refresh"); @@ -1677,9 +1648,8 @@ void retainedInFlightIntentDiscoveredBeforeUnavailableScopeOutcomeIsNotOverwritt ScriptHandoffEventRepository handoffEventRepository = Mockito.mock(ScriptHandoffEventRepository.class); when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) - .thenAnswer( - invocation -> - lookupCount.incrementAndGet() < 3 ? Optional.empty() : Optional.of(retained)); + .thenAnswer(invocation -> + lookupCount.incrementAndGet() < 3 ? Optional.empty() : Optional.of(retained)); ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); ScriptPatchInstanceRolloutProjectionService rolloutProjectionService = @@ -2564,10 +2534,9 @@ void malformedAcceptedGameSessionOutcomeRetainsInFlightReconciliationEvidence() assertThat(audit.getFinalReason()).isNull(); verify(handoffEventRepository) .save( - Mockito.argThat( - event -> - "handoff_in_flight".equals(event.getHandoffOutcome()) - && "handoff_in_flight".equals(event.getHandoffReason()))); + Mockito.argThat(event -> + "handoff_in_flight".equals(event.getHandoffOutcome()) + && "handoff_in_flight".equals(event.getHandoffReason()))); } @Test @@ -2652,14 +2621,13 @@ void exactReceiverFenceUnavailableLocalResponseRemainsInFlightWithIntentRetained when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) .thenReturn(Optional.empty()); when(handoffEventRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptHandoffEvent event = invocation.getArgument(0); - event.setId(44L); - event.setRowVersion(0); - savedIntent.set(event); - return event; - }); + .thenAnswer(invocation -> { + ScriptHandoffEvent event = invocation.getArgument(0); + event.setId(44L); + event.setRowVersion(0); + savedIntent.set(event); + return event; + }); ScriptWorkItem item = workItem(); ScriptGameplayCommandHandoffServiceImpl service = new ScriptGameplayCommandHandoffServiceImpl( @@ -2714,16 +2682,15 @@ void rejectedExistingCommandOwnershipResponseRetainsInFlightCommandIdentity( when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) .thenAnswer(invocation -> Optional.ofNullable(savedEvent.get())); when(handoffEventRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptHandoffEvent event = invocation.getArgument(0); - if (event.getId() == null) { - event.setId(44L); - } - event.setRowVersion(event.getRowVersion() + 1); - savedEvent.set(event); - return event; - }); + .thenAnswer(invocation -> { + ScriptHandoffEvent event = invocation.getArgument(0); + if (event.getId() == null) { + event.setId(44L); + } + event.setRowVersion(event.getRowVersion() + 1); + savedEvent.set(event); + return event; + }); ScriptWorkItem item = workItem(); ScriptGameplayCommandHandoffService service = new ScriptGameplayCommandHandoffServiceImpl( @@ -2771,14 +2738,13 @@ void exactReceiverFenceUnavailableRemoteResponseRemainsInFlightWithIntentRetaine when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) .thenReturn(Optional.empty()); when(handoffEventRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptHandoffEvent event = invocation.getArgument(0); - event.setId(44L); - event.setRowVersion(0); - savedIntent.set(event); - return event; - }); + .thenAnswer(invocation -> { + ScriptHandoffEvent event = invocation.getArgument(0); + event.setId(44L); + event.setRowVersion(0); + savedIntent.set(event); + return event; + }); ScriptWorkItem item = workItem(); ScriptGameplayCommandHandoffServiceImpl service = new ScriptGameplayCommandHandoffServiceImpl( @@ -3068,11 +3034,10 @@ void missingWorkItemBaseVersionFailsClosedBeforeLocalEnqueue() { .isEqualTo(ScriptHandoffOutcomeSupport.REASON_SCRIPT_PATCH_BASE_VERSION_UNAVAILABLE); verify(handoffEventRepository) .save( - Mockito.argThat( - event -> - "remote_rejected".equals(event.getHandoffOutcome()) - && ScriptHandoffOutcomeSupport.REASON_SCRIPT_PATCH_BASE_VERSION_UNAVAILABLE - .equals(event.getHandoffReason()))); + Mockito.argThat(event -> + "remote_rejected".equals(event.getHandoffOutcome()) + && ScriptHandoffOutcomeSupport.REASON_SCRIPT_PATCH_BASE_VERSION_UNAVAILABLE + .equals(event.getHandoffReason()))); verify(gameSessionClient, never()).enqueueAutomationCommandIfAbsent(Mockito.any()); verify(gameSessionClient, never()).scheduleRemoteFollowup(Mockito.any()); } @@ -3117,11 +3082,10 @@ void nonPositiveWorkItemBaseVersionFailsClosedBeforeRuntimeOwnerLookup( .isEqualTo(ScriptHandoffOutcomeSupport.REASON_SCRIPT_PATCH_BASE_VERSION_UNAVAILABLE); verify(handoffEventRepository) .save( - Mockito.argThat( - event -> - "remote_rejected".equals(event.getHandoffOutcome()) - && ScriptHandoffOutcomeSupport.REASON_SCRIPT_PATCH_BASE_VERSION_UNAVAILABLE - .equals(event.getHandoffReason()))); + Mockito.argThat(event -> + "remote_rejected".equals(event.getHandoffOutcome()) + && ScriptHandoffOutcomeSupport.REASON_SCRIPT_PATCH_BASE_VERSION_UNAVAILABLE + .equals(event.getHandoffReason()))); verifyNoInteractions(gameSessionClient); } diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchInstanceRolloutProjectionServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchInstanceRolloutProjectionServiceImplTest.java index 0346abc6c3..6d062e00c0 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchInstanceRolloutProjectionServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchInstanceRolloutProjectionServiceImplTest.java @@ -86,34 +86,30 @@ void rejectsPositiveEpochWithoutOwnerRequestIdOnFullReads() { .isInstanceOf(IllegalArgumentException.class) .hasMessage( "script_pin_control_plane_request_id must be present exactly when script_pin_epoch is positive"); - assertThatThrownBy( - () -> - service.listProjections( - "1", - "game-1", - "patch-1", - 2L, - "", - ScriptPatchInstanceRolloutStatus - .SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED, - 0L, - 0L)) + assertThatThrownBy(() -> + service.listProjections( + "1", + "game-1", + "patch-1", + 2L, + "", + ScriptPatchInstanceRolloutStatus.SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED, + 0L, + 0L)) .isInstanceOf(IllegalArgumentException.class) .hasMessage( "script_pin_control_plane_request_id must be present exactly when script_pin_epoch is positive"); - assertThatThrownBy( - () -> - service.listEvents( - "1", - "game-1", - "patch-1", - 2L, - null, - ScriptPatchInstanceRolloutStatus - .SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED, - 0L, - 0L, - 25)) + assertThatThrownBy(() -> + service.listEvents( + "1", + "game-1", + "patch-1", + 2L, + null, + ScriptPatchInstanceRolloutStatus.SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED, + 0L, + 0L, + 25)) .isInstanceOf(IllegalArgumentException.class) .hasMessage( "script_pin_control_plane_request_id must be present exactly when script_pin_epoch is positive"); @@ -141,34 +137,30 @@ void rejectsZeroEpochWithOwnerRequestIdOnFullReads() { .isInstanceOf(IllegalArgumentException.class) .hasMessage( "script_pin_control_plane_request_id must be present exactly when script_pin_epoch is positive"); - assertThatThrownBy( - () -> - service.listProjections( - "1", - "game-1", - "patch-1", - 0L, - "request-1", - ScriptPatchInstanceRolloutStatus - .SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED, - 0L, - 0L)) + assertThatThrownBy(() -> + service.listProjections( + "1", + "game-1", + "patch-1", + 0L, + "request-1", + ScriptPatchInstanceRolloutStatus.SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED, + 0L, + 0L)) .isInstanceOf(IllegalArgumentException.class) .hasMessage( "script_pin_control_plane_request_id must be present exactly when script_pin_epoch is positive"); - assertThatThrownBy( - () -> - service.listEvents( - "1", - "game-1", - "patch-1", - 0L, - "request-1", - ScriptPatchInstanceRolloutStatus - .SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED, - 0L, - 0L, - 25)) + assertThatThrownBy(() -> + service.listEvents( + "1", + "game-1", + "patch-1", + 0L, + "request-1", + ScriptPatchInstanceRolloutStatus.SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED, + 0L, + 0L, + 25)) .isInstanceOf(IllegalArgumentException.class) .hasMessage( "script_pin_control_plane_request_id must be present exactly when script_pin_epoch is positive"); @@ -213,15 +205,14 @@ void marksProjectionRepinnedWhenPatchReturnsAfterRollback() { when(repository.findByTenantIdAndGameInstanceIdAndScriptPatchVersion("1", "game-1", "patch-1")) .thenReturn(Optional.of(existing), Optional.of(existing)); when(repository.save(Mockito.any(ScriptPatchInstanceRolloutProjection.class))) - .thenAnswer( - invocation -> { - ScriptPatchInstanceRolloutProjection saved = invocation.getArgument(0); - existing.setRolloutStatus(saved.getRolloutStatus()); - existing.setStatusReason(saved.getStatusReason()); - existing.setLastChangedAt(saved.getLastChangedAt()); - existing.setProjectionRefreshedAt(saved.getProjectionRefreshedAt()); - return existing; - }); + .thenAnswer(invocation -> { + ScriptPatchInstanceRolloutProjection saved = invocation.getArgument(0); + existing.setRolloutStatus(saved.getRolloutStatus()); + existing.setStatusReason(saved.getStatusReason()); + existing.setLastChangedAt(saved.getLastChangedAt()); + existing.setProjectionRefreshedAt(saved.getProjectionRefreshedAt()); + return existing; + }); ScriptPatchInstanceRolloutProjectionServiceImpl service = new ScriptPatchInstanceRolloutProjectionServiceImpl( repository, @@ -297,18 +288,17 @@ void currentDiagnosticProjectionRollsBackWhenPositiveEpochProvesDifferentPatch() when(repository.findByTenantIdAndGameInstanceIdAndScriptPatchVersion("1", "game-1", "patch-1")) .thenReturn(Optional.of(existing), Optional.of(existing)); when(repository.save(Mockito.any(ScriptPatchInstanceRolloutProjection.class))) - .thenAnswer( - invocation -> { - ScriptPatchInstanceRolloutProjection saved = invocation.getArgument(0); - existing.setScriptPinEpoch(saved.getScriptPinEpoch()); - existing.setLastObservedControlPlaneRequestId( - saved.getLastObservedControlPlaneRequestId()); - existing.setRolloutStatus(saved.getRolloutStatus()); - existing.setStatusReason(saved.getStatusReason()); - existing.setLastChangedAt(saved.getLastChangedAt()); - existing.setProjectionRefreshedAt(saved.getProjectionRefreshedAt()); - return existing; - }); + .thenAnswer(invocation -> { + ScriptPatchInstanceRolloutProjection saved = invocation.getArgument(0); + existing.setScriptPinEpoch(saved.getScriptPinEpoch()); + existing.setLastObservedControlPlaneRequestId( + saved.getLastObservedControlPlaneRequestId()); + existing.setRolloutStatus(saved.getRolloutStatus()); + existing.setStatusReason(saved.getStatusReason()); + existing.setLastChangedAt(saved.getLastChangedAt()); + existing.setProjectionRefreshedAt(saved.getProjectionRefreshedAt()); + return existing; + }); ScriptPatchInstanceRolloutProjectionServiceImpl service = new ScriptPatchInstanceRolloutProjectionServiceImpl( repository, diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImplTest.java index 31978ed106..a6a9da3b84 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchPinProjectionServiceImplTest.java @@ -83,11 +83,9 @@ void refreshesProjectionFromRuntimeStateWhenMissing() { assertThat(lookup.summary().get().pointerVersion()).isEqualTo("17"); verify(repository) .save( - Mockito.argThat( - projection -> - projection.getScriptPinEpoch() == 8L - && Long.valueOf(7L) - .equals(projection.getPinnedScriptPatchBaseVersionId()))); + Mockito.argThat(projection -> + projection.getScriptPinEpoch() == 8L + && Long.valueOf(7L).equals(projection.getPinnedScriptPatchBaseVersionId()))); } @Test @@ -219,18 +217,17 @@ void returnsExplicitUnpinnedObservationWithoutPersistingProjection() { assertThat(lookup.errorCode()).isBlank(); assertThat(lookup.errorMessage()).isBlank(); assertThat(lookup.summary()) - .hasValueSatisfying( - summary -> { - assertThat(summary.observedPinnedScriptPatchVersion()).isBlank(); - assertThat(summary.scriptPinEpoch()).isZero(); - assertThat(summary.lastObservedControlPlaneRequestId()).isBlank(); - assertThat(summary.observedAtMs()).isZero(); - assertThat(summary.projectionAsOfMs()).isPositive(); - assertThat(summary.projectionLagMs()).isZero(); - assertThat(summary.projectionStale()).isFalse(); - assertThat(summary.runtimeRegionId()).isEqualTo("region-1"); - assertThat(summary.runtimeRegionEpoch()).isEqualTo(4L); - }); + .hasValueSatisfying(summary -> { + assertThat(summary.observedPinnedScriptPatchVersion()).isBlank(); + assertThat(summary.scriptPinEpoch()).isZero(); + assertThat(summary.lastObservedControlPlaneRequestId()).isBlank(); + assertThat(summary.observedAtMs()).isZero(); + assertThat(summary.projectionAsOfMs()).isPositive(); + assertThat(summary.projectionLagMs()).isZero(); + assertThat(summary.projectionStale()).isFalse(); + assertThat(summary.runtimeRegionId()).isEqualTo("region-1"); + assertThat(summary.runtimeRegionEpoch()).isEqualTo(4L); + }); verify(repository, never()).save(Mockito.any(ScriptPatchPinProjection.class)); verify(scheduleInstanceService).reconcileObservedRuntimeState("1", "game-1", unpinnedState); verify(repository).lockPinProjectionScope("1", "game-1"); @@ -289,12 +286,11 @@ void preservesPositiveProjectionWhenRefreshReportsUnpinned() { assertThat(lookup.errorCode()).isBlank(); assertThat(lookup.summary()) - .hasValueSatisfying( - summary -> { - assertThat(summary.observedPinnedScriptPatchVersion()).isEqualTo("patch-7"); - assertThat(summary.pinnedScriptPatchBaseVersionId()).isEqualTo(7L); - assertThat(summary.scriptPinEpoch()).isEqualTo(8L); - }); + .hasValueSatisfying(summary -> { + assertThat(summary.observedPinnedScriptPatchVersion()).isEqualTo("patch-7"); + assertThat(summary.pinnedScriptPatchBaseVersionId()).isEqualTo(7L); + assertThat(summary.scriptPinEpoch()).isEqualTo(8L); + }); verify(repository, never()).save(Mockito.any(ScriptPatchPinProjection.class)); verify(repository).lockPinProjectionScope("1", "game-1"); verifyNoInteractions(rolloutProjectionService, scheduleInstanceService); @@ -336,23 +332,21 @@ void rechecksProjectionUnderLockBeforeReconcilingUnpinnedRuntimeState() { Mockito.when(repository.findByTenantIdAndGameInstanceId("1", "game-1")) .thenAnswer(invocation -> Optional.ofNullable(currentProjection[0])); Mockito.when(repository.save(Mockito.any(ScriptPatchPinProjection.class))) - .thenAnswer( - invocation -> { - ScriptPatchPinProjection saved = invocation.getArgument(0); - saved.setId(1L); - currentProjection[0] = saved; - return saved; - }); + .thenAnswer(invocation -> { + ScriptPatchPinProjection saved = invocation.getArgument(0); + saved.setId(1L); + currentProjection[0] = saved; + return saved; + }); Mockito.when(gameSessionControlPlaneClient.getGameInstanceRuntimeState("1", "game-1", "")) - .thenAnswer( - invocation -> { - // A concurrent owner observation saves a positive projection after this lookup's - // initial empty read but before the stale unpinned response is processed. - serviceReference[0].observeRuntimeState("1", "game-1", positiveState); - return GetGameInstanceRuntimeStateResponse.newBuilder() - .setRuntimeState(unpinnedState) - .build(); - }); + .thenAnswer(invocation -> { + // A concurrent owner observation saves a positive projection after this lookup's + // initial empty read but before the stale unpinned response is processed. + serviceReference[0].observeRuntimeState("1", "game-1", positiveState); + return GetGameInstanceRuntimeStateResponse.newBuilder() + .setRuntimeState(unpinnedState) + .build(); + }); serviceReference[0] = new ScriptPatchPinProjectionServiceImpl( @@ -367,11 +361,10 @@ void rechecksProjectionUnderLockBeforeReconcilingUnpinnedRuntimeState() { assertThat(lookup.errorCode()).isBlank(); assertThat(lookup.summary()) - .hasValueSatisfying( - summary -> { - assertThat(summary.observedPinnedScriptPatchVersion()).isEqualTo("patch-8"); - assertThat(summary.scriptPinEpoch()).isEqualTo(8L); - }); + .hasValueSatisfying(summary -> { + assertThat(summary.observedPinnedScriptPatchVersion()).isEqualTo("patch-8"); + assertThat(summary.scriptPinEpoch()).isEqualTo(8L); + }); verify(scheduleInstanceService).reconcileObservedRuntimeState("1", "game-1", positiveState); verify(scheduleInstanceService, never()) .reconcileObservedRuntimeState("1", "game-1", unpinnedState); diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchReadinessProjectionServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchReadinessProjectionServiceImplTest.java index 4e323b135c..ccd4206ed8 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchReadinessProjectionServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchReadinessProjectionServiceImplTest.java @@ -355,15 +355,14 @@ void failedDownstreamWorkDoesNotRecordDatabaseCompletion() { ScriptPatchReadinessProjectionServiceImpl service = new ScriptPatchReadinessProjectionServiceImpl(repository, workItemRepository); - assertThatThrownBy( - () -> - service.applyIfCurrent( - "1", - "patch-active", - List.of("script-a"), - ignored -> { - throw new IllegalStateException("schedule_refresh_failed"); - })) + assertThatThrownBy(() -> + service.applyIfCurrent( + "1", + "patch-active", + List.of("script-a"), + ignored -> { + throw new IllegalStateException("schedule_refresh_failed"); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("schedule_refresh_failed"); assertThat(projection.isDatabaseDownstreamReconciled()).isFalse(); diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchVersionCommandServiceTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchVersionCommandServiceTest.java index 0c6e90ac88..f235ca2f14 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchVersionCommandServiceTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptPatchVersionCommandServiceTest.java @@ -44,17 +44,15 @@ void setup() { when(readinessProjectionService.beginPatchReadiness(any(), anyLong(), any(), any())) .thenReturn(true); when(readinessProjectionService.applyIfCurrent(any(), any(), any(), any())) - .thenAnswer( - invocation -> { - runDownstream(invocation, true); - return true; - }); + .thenAnswer(invocation -> { + runDownstream(invocation, true); + return true; + }); when(readinessProjectionService.rebuildRegistryIfCurrent(any(), any(), any(), any())) - .thenAnswer( - invocation -> { - runRegistryRebuild(invocation); - return true; - }); + .thenAnswer(invocation -> { + runRegistryRebuild(invocation); + return true; + }); service = new ScriptPatchVersionCommandService( repository, @@ -114,9 +112,8 @@ void notifyUpdateUsesCanonicalScriptSetAndRefreshesSchedules() { @Test void notifyUpdateRejectsDuplicateScriptNamesBeforeReadinessAdmission() { - assertThatThrownBy( - () -> - service.notifyUpdate("1", 1L, "v1-script.1", List.of("npc-barkeep", "npc-barkeep"))) + assertThatThrownBy(() -> + service.notifyUpdate("1", 1L, "v1-script.1", List.of("npc-barkeep", "npc-barkeep"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exactly one definition per unique requested name"); diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptScheduleDefinitionServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptScheduleDefinitionServiceImplTest.java index a633b46085..f0e711e885 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptScheduleDefinitionServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptScheduleDefinitionServiceImplTest.java @@ -35,10 +35,9 @@ void setup() { @Test void refreshPatchSchedulesRejectsZeroTenantIdBeforeRepositoryReads() { - assertThatThrownBy( - () -> - service.refreshPatchSchedules( - "0", "patch-1", List.of(new ScriptDefinition()), List.of("npc-guard"))) + assertThatThrownBy(() -> + service.refreshPatchSchedules( + "0", "patch-1", List.of(new ScriptDefinition()), List.of("npc-guard"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("tenantId must be positive"); @@ -89,25 +88,23 @@ void refreshPatchSchedulesPersistsIntervalAndTimerMetadata() { assertThat(saved) .filteredOn(schedule -> schedule.getScheduleDefinitionId().equals("guard.patrol.v1")) .singleElement() - .satisfies( - schedule -> { - assertThat(schedule.getScheduleKind()).isEqualTo("INTERVAL"); - assertThat(schedule.getCadenceUnit()).isEqualTo("TICKS"); - assertThat(schedule.getCadenceValue()).isEqualTo(30L); - assertThat(schedule.getPriorityTag()).isEqualTo("high"); - }); + .satisfies(schedule -> { + assertThat(schedule.getScheduleKind()).isEqualTo("INTERVAL"); + assertThat(schedule.getCadenceUnit()).isEqualTo("TICKS"); + assertThat(schedule.getCadenceValue()).isEqualTo(30L); + assertThat(schedule.getPriorityTag()).isEqualTo("high"); + }); assertThat(saved) .filteredOn(schedule -> schedule.getScheduleDefinitionId().equals("guard.alert.expire.v1")) .singleElement() - .satisfies( - schedule -> { - assertThat(schedule.getScheduleKind()).isEqualTo("TIMER"); - assertThat(schedule.getCadenceUnit()).isEqualTo("TICKS"); - assertThat(schedule.getCadenceValue()).isEqualTo(5L); - assertThat(schedule.getPriorityTag()).isEqualTo("normal"); - assertThat(schedule.getPluginId()).isEmpty(); - assertThat(schedule.getPluginVersionId()).isEmpty(); - }); + .satisfies(schedule -> { + assertThat(schedule.getScheduleKind()).isEqualTo("TIMER"); + assertThat(schedule.getCadenceUnit()).isEqualTo("TICKS"); + assertThat(schedule.getCadenceValue()).isEqualTo(5L); + assertThat(schedule.getPriorityTag()).isEqualTo("normal"); + assertThat(schedule.getPluginId()).isEmpty(); + assertThat(schedule.getPluginVersionId()).isEmpty(); + }); } @Test @@ -192,15 +189,13 @@ void refreshPatchSchedulesPersistsPluginOwnerMetadata() { List saved = captor.getValue(); assertThat(saved) .singleElement() - .satisfies( - schedule -> { - assertThat(schedule.getPluginId()).isEqualTo("town-crier"); - assertThat(schedule.getPluginVersionId()).isEqualTo("town-crier-v3"); - assertThat(schedule.getScheduleMetadataJson()) - .contains("\"pluginId\":\"town-crier\""); - assertThat(schedule.getScheduleMetadataJson()) - .contains("\"pluginVersionId\":\"town-crier-v3\""); - }); + .satisfies(schedule -> { + assertThat(schedule.getPluginId()).isEqualTo("town-crier"); + assertThat(schedule.getPluginVersionId()).isEqualTo("town-crier-v3"); + assertThat(schedule.getScheduleMetadataJson()).contains("\"pluginId\":\"town-crier\""); + assertThat(schedule.getScheduleMetadataJson()) + .contains("\"pluginVersionId\":\"town-crier-v3\""); + }); } @Test @@ -233,10 +228,8 @@ void refreshPatchSchedulesRejectsDuplicateScheduleDefinitionIdsAcrossPatch() { 1L, "patch-1")) .thenReturn(List.of(existing)); - assertThatThrownBy( - () -> - service.refreshPatchSchedules( - "1", "patch-1", List.of(script), List.of("npc-guard"))) + assertThatThrownBy(() -> + service.refreshPatchSchedules("1", "patch-1", List.of(script), List.of("npc-guard"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("duplicate_schedule_definition_id"); } @@ -290,10 +283,8 @@ void refreshPatchSchedulesRejectsInvalidCadence(String authoredCadence, boolean + jsonValue + "}}}"); - assertThatThrownBy( - () -> - service.refreshPatchSchedules( - "1", "patch-1", List.of(script), List.of("npc-guard"))) + assertThatThrownBy(() -> + service.refreshPatchSchedules("1", "patch-1", List.of(script), List.of("npc-guard"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("invalid_schedule_cadence"); verify(repository, never()).saveAll(org.mockito.ArgumentMatchers.any()); @@ -328,10 +319,8 @@ void refreshPatchSchedulesRejectsInvalidDelayTicksInsteadOfUsingDelayMs() { script.setDefinition( "{\"eventHandlers\":{\"onTimerExpire\":{\"scheduleDefinitionId\":\"guard.alert.expire.v1\",\"delayTicks\":1.5,\"delayMs\":5000}}}"); - assertThatThrownBy( - () -> - service.refreshPatchSchedules( - "1", "patch-1", List.of(script), List.of("npc-guard"))) + assertThatThrownBy(() -> + service.refreshPatchSchedules("1", "patch-1", List.of(script), List.of("npc-guard"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("invalid_schedule_cadence"); verify(repository, never()).saveAll(org.mockito.ArgumentMatchers.any()); @@ -365,10 +354,8 @@ void refreshPatchSchedulesRejectsInvalidTimerCadence( + fallback + "}}}"); - assertThatThrownBy( - () -> - service.refreshPatchSchedules( - "1", "patch-1", List.of(script), List.of("npc-guard"))) + assertThatThrownBy(() -> + service.refreshPatchSchedules("1", "patch-1", List.of(script), List.of("npc-guard"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("invalid_schedule_cadence"); verify(repository, never()).saveAll(org.mockito.ArgumentMatchers.any()); @@ -418,10 +405,9 @@ void refreshPatchSchedulesRejectsOneSidedOrContradictoryPluginOwner( + ownerJson + ",\"eventHandlers\":{\"onInterval\":{\"scheduleDefinitionId\":\"pulse.v1\",\"intervalTicks\":1}}}"); - assertThatThrownBy( - () -> - service.refreshPatchSchedules( - "1", "patch-1", List.of(script), List.of(script.getName()))) + assertThatThrownBy(() -> + service.refreshPatchSchedules( + "1", "patch-1", List.of(script), List.of(script.getName()))) .isInstanceOf(IllegalArgumentException.class) .hasMessage(expectedMessage); verify(repository, never()).saveAll(org.mockito.ArgumentMatchers.any()); @@ -465,10 +451,9 @@ void refreshPatchSchedulesRejectsContradictoryOwnersAcrossHandlers() { + "\"onTimerExpire\":{\"scheduleDefinitionId\":\"expire.v1\",\"delayMs\":1," + "\"pluginId\":\"other-plugin\",\"pluginVersionId\":\"v1\"}}}"); - assertThatThrownBy( - () -> - service.refreshPatchSchedules( - "1", "patch-1", List.of(script), List.of(script.getName()))) + assertThatThrownBy(() -> + service.refreshPatchSchedules( + "1", "patch-1", List.of(script), List.of(script.getName()))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("plugin_schedule_owner_contradictory"); verify(repository, never()).saveAll(org.mockito.ArgumentMatchers.any()); diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptScheduleInstanceServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptScheduleInstanceServiceImplTest.java index 44bbb3fe52..0876b78d6e 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptScheduleInstanceServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptScheduleInstanceServiceImplTest.java @@ -91,44 +91,38 @@ void setup() { gameSessionControlPlaneClient = mock(GameSessionControlPlaneClient.class); readinessProjectionService = mock(ScriptPatchReadinessProjectionService.class); when(readinessProjectionService.getProjection(any(), any())) - .thenAnswer( - invocation -> - Optional.of( - new ScriptPatchReadinessProjectionService.ReadinessStatusSummary( - invocation.getArgument(0), - invocation.getArgument(1), - 7L, - ScriptPatchStatus.SCRIPT_PATCH_STATUS_READY, - "ready_for_tenant", - "", - 1L))); - meterRegistry = new SimpleMeterRegistry(); - when(automationAdmissionStateService.getState(any(), any(), any())) - .thenAnswer( - invocation -> - new AutomationAdmissionStateService.AdmissionStateSummary( + .thenAnswer(invocation -> + Optional.of( + new ScriptPatchReadinessProjectionService.ReadinessStatusSummary( invocation.getArgument(0), invocation.getArgument(1), - invocation.getArgument(2), - "NORMAL", - 4L, - "", + 7L, + ScriptPatchStatus.SCRIPT_PATCH_STATUS_READY, + "ready_for_tenant", "", - 0L)); + 1L))); + meterRegistry = new SimpleMeterRegistry(); + when(automationAdmissionStateService.getState(any(), any(), any())) + .thenAnswer(invocation -> + new AutomationAdmissionStateService.AdmissionStateSummary( + invocation.getArgument(0), + invocation.getArgument(1), + invocation.getArgument(2), + "NORMAL", + 4L, + "", + "", + 0L)); when(automationAdmissionStateService.getState("1", "game-1", "region-1")) .thenReturn( new AutomationAdmissionStateService.AdmissionStateSummary( "1", "game-1", "region-1", "NORMAL", 4L, "", "", 0L)); when(workItemRepository.insertIfAbsentByTriggerIdentity(org.mockito.Mockito.any())) - .thenAnswer( - invocation -> - new ScriptWorkItemRepository.IdempotentInsertResult( - invocation.getArgument(0), true)); + .thenAnswer(invocation -> + new ScriptWorkItemRepository.IdempotentInsertResult(invocation.getArgument(0), true)); when(eventAuditRepository.insertIfAbsentByHandlerIdentity(org.mockito.Mockito.any())) - .thenAnswer( - invocation -> - new ScriptEventAuditRepository.IdempotentInsertResult( - invocation.getArgument(0), true)); + .thenAnswer(invocation -> + new ScriptEventAuditRepository.IdempotentInsertResult(invocation.getArgument(0), true)); when(gameDesignControlPlaneClient.getPublishedScriptPatchVersion(any(), anyLong(), any())) .thenReturn( GetPublishedScriptPatchVersionResponse.newBuilder() @@ -209,10 +203,9 @@ void reconcileObservedRuntimeStateRejectsZeroTenantIdBeforeScheduleLookup() { @Test void reconcileObservedRuntimeStateRejectsNullTransitionPluginIdBeforeLookup() { - assertThatThrownBy( - () -> - service.reconcileObservedRuntimeState( - "1", "game-1", GameInstanceRuntimeState.getDefaultInstance(), null, null)) + assertThatThrownBy(() -> + service.reconcileObservedRuntimeState( + "1", "game-1", GameInstanceRuntimeState.getDefaultInstance(), null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("transition_plugin_id must not be null"); @@ -393,31 +386,29 @@ void reconcileObservedRuntimeStateMaterializesMillisecondAndTickSchedules() { assertThat(saved) .filteredOn(instance -> instance.getScheduleDefinitionId().equals("guard.alert.expire.v1")) .singleElement() - .satisfies( - instance -> { - assertThat(instance.getMaterializationStatus()).isEqualTo("READY"); - assertThat(instance.getNextDueAt()).isEqualTo(Instant.ofEpochMilli(6_000L)); - assertThat(instance.getObservedRuntimeVersionId()).isEqualTo("runtime-v2"); - assertThat(instance.getScriptPinEpoch()).isEqualTo(1L); - assertThat(instance.getLastObservedControlPlaneRequestId()).isEqualTo("req-1"); - assertThat(instance.getPlayableStateScope()).isEqualTo("SHARED"); - assertThat(instance.getWorldSlug()).isEqualTo("demo"); - assertThat(instance.getRealmSlug()).isEqualTo("production"); - assertThat(instance.getPointerVersion()).isEqualTo("17"); - assertThat(instance.getTargetScopeType()).isEqualTo("ENTITY"); - assertThat(instance.getTargetScopeId()).isEqualTo("guard-1"); - assertThat(instance.getBindingPriority()).isEqualTo(10); - }); + .satisfies(instance -> { + assertThat(instance.getMaterializationStatus()).isEqualTo("READY"); + assertThat(instance.getNextDueAt()).isEqualTo(Instant.ofEpochMilli(6_000L)); + assertThat(instance.getObservedRuntimeVersionId()).isEqualTo("runtime-v2"); + assertThat(instance.getScriptPinEpoch()).isEqualTo(1L); + assertThat(instance.getLastObservedControlPlaneRequestId()).isEqualTo("req-1"); + assertThat(instance.getPlayableStateScope()).isEqualTo("SHARED"); + assertThat(instance.getWorldSlug()).isEqualTo("demo"); + assertThat(instance.getRealmSlug()).isEqualTo("production"); + assertThat(instance.getPointerVersion()).isEqualTo("17"); + assertThat(instance.getTargetScopeType()).isEqualTo("ENTITY"); + assertThat(instance.getTargetScopeId()).isEqualTo("guard-1"); + assertThat(instance.getBindingPriority()).isEqualTo(10); + }); assertThat(saved) .filteredOn(instance -> instance.getScheduleDefinitionId().equals("guard.patrol.v1")) .singleElement() - .satisfies( - instance -> { - assertThat(instance.getMaterializationStatus()).isEqualTo("PENDING_RUNTIME_PROGRESS"); - assertThat(instance.getNextDueAt()).isNull(); - assertThat(instance.getNextDueTickId()).isNull(); - assertThat(instance.isRequiresExclusiveEvent()).isTrue(); - }); + .satisfies(instance -> { + assertThat(instance.getMaterializationStatus()).isEqualTo("PENDING_RUNTIME_PROGRESS"); + assertThat(instance.getNextDueAt()).isNull(); + assertThat(instance.getNextDueTickId()).isNull(); + assertThat(instance.isRequiresExclusiveEvent()).isTrue(); + }); } @Test @@ -1386,9 +1377,8 @@ void pluginTransitionSeedCreatesWallClockDueAtFromCommittedTransitionTime() { verify(scheduleInstanceRepository).saveAll(captor.capture()); assertThat(captor.getValue()) .singleElement() - .satisfies( - instance -> - assertThat(instance.getNextDueAt()).isEqualTo(Instant.ofEpochMilli(15_000L))); + .satisfies(instance -> + assertThat(instance.getNextDueAt()).isEqualTo(Instant.ofEpochMilli(15_000L))); } @Test @@ -1731,17 +1721,16 @@ void observeRuntimeTickProgressAdvancesTickSchedulesFromHeartbeat() { verify(scheduleInstanceRepository).saveAll(captor.capture()); assertThat(captor.getValue()) .singleElement() - .satisfies( - instance -> { - assertThat(instance.getMaterializationStatus()).isEqualTo("READY"); - assertThat(instance.getRuntimeRegionId()).isEqualTo("region-1"); - assertThat(instance.getRuntimeRegionEpoch()).isEqualTo(12L); - assertThat(instance.getLastObservedTickId()).isEqualTo(100L); - assertThat(instance.getLastRuntimeProgressObservedAt()) - .isEqualTo(Instant.ofEpochMilli(5_000L)); - assertThat(instance.getNextDueTickId()).isEqualTo(130L); - assertThat(instance.getNextDueAt()).isNull(); - }); + .satisfies(instance -> { + assertThat(instance.getMaterializationStatus()).isEqualTo("READY"); + assertThat(instance.getRuntimeRegionId()).isEqualTo("region-1"); + assertThat(instance.getRuntimeRegionEpoch()).isEqualTo(12L); + assertThat(instance.getLastObservedTickId()).isEqualTo(100L); + assertThat(instance.getLastRuntimeProgressObservedAt()) + .isEqualTo(Instant.ofEpochMilli(5_000L)); + assertThat(instance.getNextDueTickId()).isEqualTo(130L); + assertThat(instance.getNextDueAt()).isNull(); + }); } @Test @@ -2124,24 +2113,21 @@ void reconcileObservedRuntimeStateFencesDueTimeOverflowAndContinuesWithLaterSche ArgumentCaptor> captor = ArgumentCaptor.forClass(List.class); verify(scheduleInstanceRepository).saveAll(captor.capture()); assertThat(captor.getValue()) - .filteredOn( - instance -> - instance.getScheduleDefinitionId().equals(overflow.getScheduleDefinitionId())) + .filteredOn(instance -> + instance.getScheduleDefinitionId().equals(overflow.getScheduleDefinitionId())) .singleElement() - .satisfies( - instance -> { - assertThat(instance.getMaterializationStatus()).isEqualTo("FENCED"); - assertThat(instance.getNextDueAt()).isNull(); - }); + .satisfies(instance -> { + assertThat(instance.getMaterializationStatus()).isEqualTo("FENCED"); + assertThat(instance.getNextDueAt()).isNull(); + }); assertThat(captor.getValue()) .filteredOn( instance -> instance.getScheduleDefinitionId().equals(later.getScheduleDefinitionId())) .singleElement() - .satisfies( - instance -> { - assertThat(instance.getMaterializationStatus()).isEqualTo("READY"); - assertThat(instance.getNextDueAt()).isEqualTo(Instant.ofEpochMilli(6_000L)); - }); + .satisfies(instance -> { + assertThat(instance.getMaterializationStatus()).isEqualTo("READY"); + assertThat(instance.getNextDueAt()).isEqualTo(Instant.ofEpochMilli(6_000L)); + }); } @Test @@ -2277,11 +2263,10 @@ void observeRuntimeTickProgressEmitsDueTimerWorkItemAndAdvancesPastObservedTick( verify(scheduleInstanceRepository).saveAll(scheduleCaptor.capture()); assertThat(scheduleCaptor.getValue()) .singleElement() - .satisfies( - instance -> { - assertThat(instance.getNextDueTickId()).isEqualTo(160L); - assertThat(instance.getLastObservedTickId()).isEqualTo(131L); - }); + .satisfies(instance -> { + assertThat(instance.getNextDueTickId()).isEqualTo(160L); + assertThat(instance.getLastObservedTickId()).isEqualTo(131L); + }); } @Test @@ -2800,13 +2785,12 @@ void observeRuntimeTickProgressStampsAndFiresDueWallClockTimer() { verify(scheduleInstanceRepository).saveAll(scheduleCaptor.capture()); assertThat(scheduleCaptor.getValue()) .singleElement() - .satisfies( - instance -> { - assertThat(instance.getRuntimeRegionId()).isEqualTo("region-1"); - assertThat(instance.getRuntimeRegionEpoch()).isEqualTo(12L); - assertThat(instance.getLastObservedTickId()).isEqualTo(131L); - assertThat(instance.getNextDueAt()).isNull(); - }); + .satisfies(instance -> { + assertThat(instance.getRuntimeRegionId()).isEqualTo("region-1"); + assertThat(instance.getRuntimeRegionEpoch()).isEqualTo(12L); + assertThat(instance.getLastObservedTickId()).isEqualTo(131L); + assertThat(instance.getNextDueAt()).isNull(); + }); } finally { TransactionSynchronizationManager.clearSynchronization(); } @@ -2979,14 +2963,13 @@ void timerCandidateDoesNotEmitUnderPluginFenceDisplacedAfterSelection() { "1", "game-1", "plugin-2")) .thenReturn(Optional.of(displacedOwner)); when(gameSessionControlPlaneClient.getGameInstanceRuntimeState("1", "game-1")) - .thenAnswer( - invocation -> { - timerInstance.setPluginId("plugin-2"); - timerInstance.setPluginVersionId("plugin-v2"); - timerInstance.setPluginActivationEpoch(2L); - timerInstance.setLifecycleRevision(2L); - return runtimeStateResponse("patch-1"); - }); + .thenAnswer(invocation -> { + timerInstance.setPluginId("plugin-2"); + timerInstance.setPluginVersionId("plugin-v2"); + timerInstance.setPluginActivationEpoch(2L); + timerInstance.setLifecycleRevision(2L); + return runtimeStateResponse("patch-1"); + }); ScriptScheduleInstanceService.RuntimeTickProgressResult result = service.observeRuntimeTickProgress(observation(131L, 6_000L)); @@ -3015,11 +2998,10 @@ void timerCandidateDoesNotRebindWhenBindingChangesAfterSelection() { "1", "game-1", "plugin-1")) .thenReturn(Optional.of(enabledPluginRuntimeState("plugin-1", "plugin-v1"))); when(gameSessionControlPlaneClient.getGameInstanceRuntimeState("1", "game-1")) - .thenAnswer( - invocation -> { - timerInstance.setBindingId("binding-after"); - return runtimeStateResponse("patch-1"); - }); + .thenAnswer(invocation -> { + timerInstance.setBindingId("binding-after"); + return runtimeStateResponse("patch-1"); + }); ScriptScheduleInstanceService.RuntimeTickProgressResult result = service.observeRuntimeTickProgress(observation(131L, 6_000L)); @@ -3446,12 +3428,11 @@ void observeRuntimeTickProgressSuppressesDueWallClockTimerWhenRuntimeScopeChange verify(scheduleInstanceRepository).saveAll(scheduleCaptor.capture()); assertThat(scheduleCaptor.getValue()) .singleElement() - .satisfies( - instance -> { - assertThat(instance.getRuntimeRegionId()).isEqualTo("region-new"); - assertThat(instance.getRuntimeRegionEpoch()).isEqualTo(12L); - assertThat(instance.getNextDueAt()).isEqualTo(Instant.ofEpochMilli(11_000L)); - }); + .satisfies(instance -> { + assertThat(instance.getRuntimeRegionId()).isEqualTo("region-new"); + assertThat(instance.getRuntimeRegionEpoch()).isEqualTo(12L); + assertThat(instance.getNextDueAt()).isEqualTo(Instant.ofEpochMilli(11_000L)); + }); assertThat( meterRegistry .get("automation_script_timer_runtime_fence_dropped_total") @@ -3591,12 +3572,11 @@ void observeRuntimeTickProgressRecordsCatchUpTruncationWithReasonLabels() { verify(eventAuditRepository).insertIfAbsentByHandlerIdentity(auditCaptor.capture()); verify(eventAuditRepository).save(any()); assertThat(auditCaptor.getAllValues()) - .anySatisfy( - audit -> { - assertThat(audit.getFinalReason()).isEqualTo("catch_up_truncated"); - assertThat(audit.getPluginId()).isEqualTo("plugin-1"); - assertThat(audit.getPluginVersionId()).isEqualTo("plugin-v1"); - }); + .anySatisfy(audit -> { + assertThat(audit.getFinalReason()).isEqualTo("catch_up_truncated"); + assertThat(audit.getPluginId()).isEqualTo("plugin-1"); + assertThat(audit.getPluginVersionId()).isEqualTo("plugin-v1"); + }); assertThat( meterRegistry .get("automation_script_timer_catchup_truncated_total") @@ -3662,9 +3642,8 @@ void skippedTimerMetricDoesNotPublishOnRollback() { .isNull(); assertThat(TransactionSynchronizationManager.getSynchronizations()).hasSize(2); TransactionSynchronizationManager.getSynchronizations() - .forEach( - synchronization -> - synchronization.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK)); + .forEach(synchronization -> + synchronization.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK)); assertThat(meterRegistry.find("automation_script_timer_catchup_truncated_total").counter()) .isNull(); } finally { @@ -3889,17 +3868,16 @@ void listTimerAuditEventsReturnsBoundedSummariesFromAuditRows() { assertThat(result) .singleElement() - .satisfies( - summary -> { - assertThat(summary.pluginId()).isEqualTo("plugin-1"); - assertThat(summary.pluginVersionId()).isEqualTo("plugin-v1"); - assertThat(summary.bindingId()).isEqualTo("binding-timer"); - assertThat(summary.finalReason()).isEqualTo("catch_up_truncated"); - assertThat(summary.sourceDueTickId()).isEqualTo(130L); - assertThat(summary.scriptPatchBaseVersionId()).isEqualTo(7L); - assertThat(summary.publication().baseVersionId()).isEqualTo(7L); - assertThat(summary.publication().versionId()).isEqualTo(17L); - }); + .satisfies(summary -> { + assertThat(summary.pluginId()).isEqualTo("plugin-1"); + assertThat(summary.pluginVersionId()).isEqualTo("plugin-v1"); + assertThat(summary.bindingId()).isEqualTo("binding-timer"); + assertThat(summary.finalReason()).isEqualTo("catch_up_truncated"); + assertThat(summary.sourceDueTickId()).isEqualTo(130L); + assertThat(summary.scriptPatchBaseVersionId()).isEqualTo(7L); + assertThat(summary.publication().baseVersionId()).isEqualTo(7L); + assertThat(summary.publication().versionId()).isEqualTo(17L); + }); verify(gameDesignControlPlaneClient).getPublishedScriptPatchVersion("1", 7L, "patch-1"); } @@ -3932,13 +3910,12 @@ void listTimerAuditEventsFailsClosedWhenHistoricalAuditBaseIsUnknown() { assertThat(result) .singleElement() - .satisfies( - summary -> { - assertThat(summary.scriptPatchBaseVersionId()).isZero(); - assertThat(summary.publication().baseVersionId()).isZero(); - assertThat(summary.publication().lookupErrorCode()) - .isEqualTo("PUBLICATION_SCOPE_UNAVAILABLE"); - }); + .satisfies(summary -> { + assertThat(summary.scriptPatchBaseVersionId()).isZero(); + assertThat(summary.publication().baseVersionId()).isZero(); + assertThat(summary.publication().lookupErrorCode()) + .isEqualTo("PUBLICATION_SCOPE_UNAVAILABLE"); + }); verify(gameDesignControlPlaneClient, never()) .getPublishedScriptPatchVersion(any(), anyLong(), any()); } @@ -3992,14 +3969,13 @@ void listInstancesAddsScriptPatchPublicationMetadata() { assertThat(result) .singleElement() - .satisfies( - summary -> { - assertThat(summary.scheduleDefinitionId()).isEqualTo("guard.alert.expire.v1"); - assertThat(summary.pluginId()).isEqualTo("plugin-1"); - assertThat(summary.pluginVersionId()).isEqualTo("plugin-v1"); - assertThat(summary.bindingId()).isEqualTo("binding-timer"); - assertThat(summary.publication().versionId()).isEqualTo(17L); - }); + .satisfies(summary -> { + assertThat(summary.scheduleDefinitionId()).isEqualTo("guard.alert.expire.v1"); + assertThat(summary.pluginId()).isEqualTo("plugin-1"); + assertThat(summary.pluginVersionId()).isEqualTo("plugin-v1"); + assertThat(summary.bindingId()).isEqualTo("binding-timer"); + assertThat(summary.publication().versionId()).isEqualTo(17L); + }); verify(gameDesignControlPlaneClient).getPublishedScriptPatchVersion("1", 7L, "patch-1"); } @@ -4021,12 +3997,11 @@ void listInstancesReportsUnavailablePublicationScopeWhenPersistedBaseIsUnknown() assertThat(result) .singleElement() - .satisfies( - summary -> { - assertThat(summary.publication().lookupErrorCode()) - .isEqualTo("PUBLICATION_SCOPE_UNAVAILABLE"); - assertThat(summary.publication().lookupErrorMessage()).contains("base_version_id"); - }); + .satisfies(summary -> { + assertThat(summary.publication().lookupErrorCode()) + .isEqualTo("PUBLICATION_SCOPE_UNAVAILABLE"); + assertThat(summary.publication().lookupErrorMessage()).contains("base_version_id"); + }); verify(gameDesignControlPlaneClient, never()) .getPublishedScriptPatchVersion(any(), anyLong(), any()); } @@ -4053,13 +4028,11 @@ void listInstancesLogsAndContainsPublicationLookupFailures() { assertThat(result) .singleElement() - .satisfies( - summary -> { - assertThat(summary.publication().lookupErrorCode()) - .isEqualTo("GAME_DESIGN_UNAVAILABLE"); - assertThat(summary.pluginPublication().lookupErrorCode()) - .isEqualTo("GAME_DESIGN_UNAVAILABLE"); - }); + .satisfies(summary -> { + assertThat(summary.publication().lookupErrorCode()).isEqualTo("GAME_DESIGN_UNAVAILABLE"); + assertThat(summary.pluginPublication().lookupErrorCode()) + .isEqualTo("GAME_DESIGN_UNAVAILABLE"); + }); } @Test diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java index ee96c8278d..6afe42c645 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemExecutionServiceImplTest.java @@ -629,12 +629,11 @@ void retriesLaterPluginFenceReadFailureAfterDurablyCommittedClaim() { Mockito.any(Pageable.class))) .thenReturn(List.of(item)); when(transactionManager.getTransaction(Mockito.any(TransactionDefinition.class))) - .thenAnswer( - invocation -> { - transactionDefinitions.add(invocation.getArgument(0)); - nextTransactionId.incrementAndGet(); - return transactionStatus; - }); + .thenAnswer(invocation -> { + transactionDefinitions.add(invocation.getArgument(0)); + nextTransactionId.incrementAndGet(); + return transactionStatus; + }); Mockito.doAnswer( invocation -> { committedStatuses.add(item.getStatus()); @@ -690,11 +689,10 @@ void retriesLaterPluginFenceReadFailureAfterDurablyCommittedClaim() { .findByTenantIdAndGameInstanceIdAndPluginId("1", "7", "plugin-1"); assertThat( transactionDefinitions.stream() - .filter( - definition -> - definition.getPropagationBehavior() - == TransactionDefinition.PROPAGATION_REQUIRES_NEW - && definition.isReadOnly()) + .filter(definition -> + definition.getPropagationBehavior() + == TransactionDefinition.PROPAGATION_REQUIRES_NEW + && definition.isReadOnly()) .count()) .isEqualTo(2); assertThat(nextTransactionId).hasValue(4); @@ -723,15 +721,14 @@ void retriesWhenPluginFenceRequiresNewTransactionCannotBeCreated() { Mockito.any(Pageable.class))) .thenReturn(List.of(item)); when(transactionManager.getTransaction(Mockito.any(TransactionDefinition.class))) - .thenAnswer( - invocation -> { - if (transactionCount.incrementAndGet() == 3) { - throw new CannotCreateTransactionException( - "plugin fence transaction unavailable", - new SQLTransientConnectionException("offline")); - } - return transactionStatus; - }); + .thenAnswer(invocation -> { + if (transactionCount.incrementAndGet() == 3) { + throw new CannotCreateTransactionException( + "plugin fence transaction unavailable", + new SQLTransientConnectionException("offline")); + } + return transactionStatus; + }); Mockito.doAnswer( invocation -> { item.setStatus("EVALUATING"); @@ -1119,13 +1116,12 @@ void retryablePostEvaluationRuntimeFenceDoesNotExhaustAuthorityBudget() { ScriptEventAudit audit = new ScriptEventAudit(); when(workItemService.claimPendingForEvaluation(1)).thenReturn(List.of(item)); when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) - .thenAnswer( - invocation -> { - // Model the exhausted outage budget reached during the evaluated handoff fence. - item.setAuthorityUnavailableSince(Instant.now().minus(Duration.ofMinutes(11))); - item.setAuthorityUnavailableCount(9); - return Optional.of(definition); - }); + .thenAnswer(invocation -> { + // Model the exhausted outage budget reached during the evaluated handoff fence. + item.setAuthorityUnavailableSince(Instant.now().minus(Duration.ofMinutes(11))); + item.setAuthorityUnavailableCount(9); + return Optional.of(definition); + }); when(auditRepository.findByWorkItemId(99L)).thenReturn(Optional.of(audit)); when(workItemRepository.save(item)).thenAnswer(invocation -> invocation.getArgument(0)); @@ -1545,12 +1541,11 @@ void claimsQueueIndexedWorkItemsBeforeFallingBackToDurableScan() { ArgumentCaptor auditCaptor = ArgumentCaptor.forClass(ScriptEventAudit.class); verify(auditRepository, Mockito.times(2)).save(auditCaptor.capture()); assertThat(auditCaptor.getAllValues()) - .allSatisfy( - audit -> { - assertThat(audit.getFinalStage()).isEqualTo("DSL_EVAL"); - assertThat(audit.getFinalOutcome()).isEqualTo("completed_no_commands"); - assertThat(audit.getFinalReason()).isEqualTo("script_emitted_no_commands"); - }); + .allSatisfy(audit -> { + assertThat(audit.getFinalStage()).isEqualTo("DSL_EVAL"); + assertThat(audit.getFinalOutcome()).isEqualTo("completed_no_commands"); + assertThat(audit.getFinalReason()).isEqualTo("script_emitted_no_commands"); + }); Mockito.verifyNoInteractions(handoffService); verify(workItemService).claimPendingForEvaluation(List.of(99L), 9); verify(workItemService).claimPendingForEvaluation(9); @@ -1738,12 +1733,11 @@ void commitsEachClaimBeforeEvaluationAndLeavesItUnresolvedAfterEvaluationRollbac fallback.setStatus("PENDING_EVALUATION"); when(transactionManager.getTransaction(Mockito.any(TransactionDefinition.class))) - .thenAnswer( - invocation -> { - assertThat(transactionActive.compareAndSet(false, true)).isTrue(); - currentTransactionId.set(nextTransactionId.incrementAndGet()); - return transactionStatus; - }); + .thenAnswer(invocation -> { + assertThat(transactionActive.compareAndSet(false, true)).isTrue(); + currentTransactionId.set(nextTransactionId.incrementAndGet()); + return transactionStatus; + }); Mockito.doAnswer( invocation -> { int committedTransactionId = currentTransactionId.get(); @@ -1775,13 +1769,12 @@ void commitsEachClaimBeforeEvaluationAndLeavesItUnresolvedAfterEvaluationRollbac Mockito.eq("PENDING_EVALUATION"), Mockito.any(Instant.class), Mockito.any(Pageable.class))) - .thenAnswer( - invocation -> { - assertThat(transactionActive).isFalse(); - // The durable scan returns both rows. Claiming rejects the indexed row because it - // is no longer PENDING_EVALUATION, while its sibling remains eligible. - return List.of(indexed, fallback); - }); + .thenAnswer(invocation -> { + assertThat(transactionActive).isFalse(); + // The durable scan returns both rows. Claiming rejects the indexed row because it + // is no longer PENDING_EVALUATION, while its sibling remains eligible. + return List.of(indexed, fallback); + }); Mockito.doAnswer( invocation -> { assertThat(transactionActive).isTrue(); @@ -1808,13 +1801,12 @@ void commitsEachClaimBeforeEvaluationAndLeavesItUnresolvedAfterEvaluationRollbac when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) .thenReturn(runtimeStateResponse()); when(handoffService.handoff(Mockito.eq(indexed), Mockito.any())) - .thenAnswer( - invocation -> { - assertThat(transactionActive).isFalse(); - remoteEffectAccepted.set(true); - return new ScriptGameplayCommandHandoffService.HandoffResult( - true, "ACCEPTED", "command-1", "", "", ""); - }); + .thenAnswer(invocation -> { + assertThat(transactionActive).isFalse(); + remoteEffectAccepted.set(true); + return new ScriptGameplayCommandHandoffService.HandoffResult( + true, "ACCEPTED", "command-1", "", "", ""); + }); when(workItemRepository.save(Mockito.any())) .thenAnswer(invocation -> invocation.getArgument(0)); when(auditRepository.findByWorkItemId(100L)).thenReturn(Optional.of(new ScriptEventAudit())); @@ -1890,12 +1882,11 @@ void finalizationRollbackAfterRemoteHandoffLeavesParentUnresolvedAndContinuesBat fallback.setStatus("PENDING_EVALUATION"); when(transactionManager.getTransaction(Mockito.any(TransactionDefinition.class))) - .thenAnswer( - invocation -> { - assertThat(transactionActive.compareAndSet(false, true)).isTrue(); - currentTransactionId.set(nextTransactionId.incrementAndGet()); - return transactionStatus; - }); + .thenAnswer(invocation -> { + assertThat(transactionActive.compareAndSet(false, true)).isTrue(); + currentTransactionId.set(nextTransactionId.incrementAndGet()); + return transactionStatus; + }); Mockito.doAnswer( invocation -> { int completedTransactionId = currentTransactionId.get(); @@ -1925,11 +1916,10 @@ void finalizationRollbackAfterRemoteHandoffLeavesParentUnresolvedAndContinuesBat Mockito.eq("PENDING_EVALUATION"), Mockito.any(Instant.class), Mockito.any(Pageable.class))) - .thenAnswer( - invocation -> { - assertThat(transactionActive).isFalse(); - return List.of(indexed, fallback); - }); + .thenAnswer(invocation -> { + assertThat(transactionActive).isFalse(); + return List.of(indexed, fallback); + }); Mockito.doAnswer( invocation -> { assertThat(transactionActive).isTrue(); @@ -1956,13 +1946,12 @@ void finalizationRollbackAfterRemoteHandoffLeavesParentUnresolvedAndContinuesBat when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) .thenReturn(runtimeStateResponse()); when(handoffService.handoff(Mockito.eq(indexed), Mockito.any())) - .thenAnswer( - invocation -> { - assertThat(transactionActive).isFalse(); - remoteEffectAccepted.set(true); - return new ScriptGameplayCommandHandoffService.HandoffResult( - true, "ACCEPTED", "command-1", "", "", ""); - }); + .thenAnswer(invocation -> { + assertThat(transactionActive).isFalse(); + remoteEffectAccepted.set(true); + return new ScriptGameplayCommandHandoffService.HandoffResult( + true, "ACCEPTED", "command-1", "", "", ""); + }); when(workItemRepository.save(Mockito.any())) .thenAnswer(invocation -> invocation.getArgument(0)); when(auditRepository.findByWorkItemId(Mockito.anyLong())) @@ -2046,12 +2035,11 @@ void processesClaimedWorkItemAndHandsOffRenderedCommands() { when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) .thenReturn(Optional.of(definition)); when(handoffService.handoff(Mockito.eq(item), Mockito.any())) - .thenAnswer( - invocation -> { - item.setStatus("HANDED_OFF"); - return new ScriptGameplayCommandHandoffService.HandoffResult( - true, "ENQUEUED", "auto-1", "", "", ""); - }); + .thenAnswer(invocation -> { + item.setStatus("HANDED_OFF"); + return new ScriptGameplayCommandHandoffService.HandoffResult( + true, "ENQUEUED", "auto-1", "", "", ""); + }); when(auditRepository.findByWorkItemId(99L)).thenReturn(Optional.of(audit)); when(workItemRepository.save(Mockito.any())) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -2778,12 +2766,11 @@ void evaluationCommitsBeforeHandoffLoopStarts() { item.setNextEligibleAt(Instant.parse("2026-09-01T00:01:00Z")); } when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) - .thenAnswer( - invocation -> { - operations.add( - "runtime:" + TransactionSynchronizationManager.isActualTransactionActive()); - return runtimeStateResponse(); - }); + .thenAnswer(invocation -> { + operations.add( + "runtime:" + TransactionSynchronizationManager.isActualTransactionActive()); + return runtimeStateResponse(); + }); item.setStatus("PENDING_EVALUATION"); when(workItemRepository.findByStatusOrderByCreatedAtAscIdAsc( Mockito.eq("PENDING_EVALUATION"), @@ -3104,19 +3091,17 @@ void partialFanoutPreservesAcceptedChildAndStopsAfterAmbiguousChild() { when(workItemRepository.save(Mockito.any())) .thenAnswer(invocation -> invocation.getArgument(0)); when(handoffService.handoff(Mockito.eq(item), Mockito.any())) - .thenAnswer( - invocation -> { - ScriptGameplayCommandHandoffService.EmittedCommand command = - invocation.getArgument(1); - attemptedOrdinals.add(command.ordinal()); - item.setStatus("HANDOFF_IN_FLIGHT"); - if (command.ordinal() == 0) { - return new ScriptGameplayCommandHandoffService.HandoffResult( - true, "ENQUEUED", "auto-1", "", "", ""); - } - return new ScriptGameplayCommandHandoffService.HandoffResult( - false, "HANDOFF_IN_FLIGHT", "", "", "", "HANDOFF_IN_FLIGHT"); - }); + .thenAnswer(invocation -> { + ScriptGameplayCommandHandoffService.EmittedCommand command = invocation.getArgument(1); + attemptedOrdinals.add(command.ordinal()); + item.setStatus("HANDOFF_IN_FLIGHT"); + if (command.ordinal() == 0) { + return new ScriptGameplayCommandHandoffService.HandoffResult( + true, "ENQUEUED", "auto-1", "", "", ""); + } + return new ScriptGameplayCommandHandoffService.HandoffResult( + false, "HANDOFF_IN_FLIGHT", "", "", "", "HANDOFF_IN_FLIGHT"); + }); ScriptWorkItemExecutionService service = pluginFenceService( @@ -3162,20 +3147,18 @@ void preparationUnavailableRecordsCurrentAndRemainingCommandsWithoutSiblingHando when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) .thenReturn(Optional.of(definition)); when(handoffService.handoff(Mockito.eq(item), Mockito.any())) - .thenAnswer( - invocation -> { - ScriptGameplayCommandHandoffService.EmittedCommand command = - invocation.getArgument(1); - attemptedOrdinals.add(command.ordinal()); - return new ScriptGameplayCommandHandoffService.HandoffResult( - false, - ScriptGameplayCommandHandoffService.OUTCOME_PREPARATION_UNAVAILABLE, - "", - "", - "", - "UNAVAILABLE", - errorMessage); - }); + .thenAnswer(invocation -> { + ScriptGameplayCommandHandoffService.EmittedCommand command = invocation.getArgument(1); + attemptedOrdinals.add(command.ordinal()); + return new ScriptGameplayCommandHandoffService.HandoffResult( + false, + ScriptGameplayCommandHandoffService.OUTCOME_PREPARATION_UNAVAILABLE, + "", + "", + "", + "UNAVAILABLE", + errorMessage); + }); when(workItemRepository.save(Mockito.any())) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -3232,24 +3215,22 @@ void persistedDownstreamUnavailableRejectionContinuesSiblingFanout() { when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) .thenReturn(Optional.of(definition)); when(handoffService.handoff(Mockito.eq(item), Mockito.any())) - .thenAnswer( - invocation -> { - ScriptGameplayCommandHandoffService.EmittedCommand command = - invocation.getArgument(1); - attemptedOrdinals.add(command.ordinal()); - if (command.ordinal() == 0) { - return new ScriptGameplayCommandHandoffService.HandoffResult( - false, - "REMOTE_REJECTED", - "", - "", - "", - "UNAVAILABLE", - "handoff preparation unavailable"); - } - return new ScriptGameplayCommandHandoffService.HandoffResult( - true, "ENQUEUED", "auto-" + command.ordinal(), "", "", ""); - }); + .thenAnswer(invocation -> { + ScriptGameplayCommandHandoffService.EmittedCommand command = invocation.getArgument(1); + attemptedOrdinals.add(command.ordinal()); + if (command.ordinal() == 0) { + return new ScriptGameplayCommandHandoffService.HandoffResult( + false, + "REMOTE_REJECTED", + "", + "", + "", + "UNAVAILABLE", + "handoff preparation unavailable"); + } + return new ScriptGameplayCommandHandoffService.HandoffResult( + true, "ENQUEUED", "auto-" + command.ordinal(), "", "", ""); + }); when(workItemRepository.save(Mockito.any())) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -3299,16 +3280,15 @@ void unexpectedItemFailureDoesNotAbortLaterClaimedItems() { when(workItemRepository.save(Mockito.any())) .thenAnswer(invocation -> invocation.getArgument(0)); when(handoffService.handoff(Mockito.any(), Mockito.any())) - .thenAnswer( - invocation -> { - ScriptWorkItem item = invocation.getArgument(0); - if (item == first) { - throw new IllegalStateException("unexpected handoff failure"); - } - second.setStatus("HANDED_OFF"); - return new ScriptGameplayCommandHandoffService.HandoffResult( - true, "ENQUEUED", "auto-2", "", "", ""); - }); + .thenAnswer(invocation -> { + ScriptWorkItem item = invocation.getArgument(0); + if (item == first) { + throw new IllegalStateException("unexpected handoff failure"); + } + second.setStatus("HANDED_OFF"); + return new ScriptGameplayCommandHandoffService.HandoffResult( + true, "ENQUEUED", "auto-2", "", "", ""); + }); ScriptWorkItemExecutionService service = new ScriptWorkItemExecutionServiceImpl( @@ -3372,12 +3352,11 @@ void retryableHandoffAttemptLeavesEvaluatedParentUnresolved( new ScriptGameplayCommandHandoffService.HandoffResult( false, outcome, "", "", "", errorCode)); when(workItemRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptWorkItem saved = invocation.getArgument(0); - operations.add("save:" + saved.getStatus()); - return saved; - }); + .thenAnswer(invocation -> { + ScriptWorkItem saved = invocation.getArgument(0); + operations.add("save:" + saved.getStatus()); + return saved; + }); Mockito.doAnswer( invocation -> { operations.add("refresh"); @@ -3472,29 +3451,27 @@ void failedPostEvaluationFenceCommitMarksParentUnresolvedWithoutDispatch() { Mockito.any(Pageable.class))) .thenReturn(List.of(item)); when(workItemService.claimPendingForEvaluation(Mockito.anyList(), Mockito.eq(1))) - .thenAnswer( - invocation -> { - item.setStatus("EVALUATING"); - return List.of(item); - }); + .thenAnswer(invocation -> { + item.setStatus("EVALUATING"); + return List.of(item); + }); when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) .thenReturn(Optional.of(definition)); when(gameSessionClient.getGameInstanceRuntimeState("1", "7", "region-1")) .thenReturn(runtimeStateResponse()); List savedRetryStates = new ArrayList<>(); when(workItemRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptWorkItem saved = invocation.getArgument(0); - savedRetryStates.add( - new RetryStateSnapshot( - saved.getAuthorityUnavailableSince(), - saved.getAuthorityUnavailableCount(), - saved.getNextEligibleAt(), - saved.getRowVersion())); - saved.setRowVersion(saved.getRowVersion() + 1); - return saved; - }); + .thenAnswer(invocation -> { + ScriptWorkItem saved = invocation.getArgument(0); + savedRetryStates.add( + new RetryStateSnapshot( + saved.getAuthorityUnavailableSince(), + saved.getAuthorityUnavailableCount(), + saved.getNextEligibleAt(), + saved.getRowVersion())); + saved.setRowVersion(saved.getRowVersion() + 1); + return saved; + }); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); ScriptWorkItemExecutionService service = new ScriptWorkItemExecutionServiceImpl( @@ -3602,30 +3579,27 @@ void realRetryableLocalHandoffResponseLeavesParentUnresolved(String errorCode) { when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) .thenReturn(Optional.of(definition)); when(workItemRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptWorkItem saved = invocation.getArgument(0); - saved.setRowVersion(saved.getRowVersion() + 1); - return saved; - }); + .thenAnswer(invocation -> { + ScriptWorkItem saved = invocation.getArgument(0); + saved.setRowVersion(saved.getRowVersion() + 1); + return saved; + }); List savedHandoffs = new ArrayList<>(); when(handoffEventRepository.findByTenantIdAndWorkItemIdAndCommandOrdinal("1", 99L, 0)) - .thenAnswer( - invocation -> - savedHandoffs.isEmpty() ? Optional.empty() : Optional.of(savedHandoffs.getLast())); + .thenAnswer(invocation -> + savedHandoffs.isEmpty() ? Optional.empty() : Optional.of(savedHandoffs.getLast())); when(handoffEventRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptHandoffEvent saved = invocation.getArgument(0); - if (saved.getId() == null) { - saved.setId(44L); - saved.setRowVersion(0); - } else { - saved.setRowVersion(saved.getRowVersion() + 1); - } - savedHandoffs.add(saved); - return saved; - }); + .thenAnswer(invocation -> { + ScriptHandoffEvent saved = invocation.getArgument(0); + if (saved.getId() == null) { + saved.setId(44L); + saved.setRowVersion(0); + } else { + saved.setRowVersion(saved.getRowVersion() + 1); + } + savedHandoffs.add(saved); + return saved; + }); ScriptGameplayCommandHandoffServiceImpl handoffService = new ScriptGameplayCommandHandoffServiceImpl( @@ -3700,13 +3674,12 @@ void retryableHandoffRollbackLeavesDetachedParentUnresolvedWithoutReadback() { when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) .thenReturn(Optional.of(definition)); when(handoffService.handoff(Mockito.eq(item), Mockito.any())) - .thenAnswer( - invocation -> { - item.setStatus("CANCELED"); - item.setRowVersion(8); - return new ScriptGameplayCommandHandoffService.HandoffResult( - false, "REMOTE_REJECTED", "", "", "", "QUEUE_UNAVAILABLE"); - }); + .thenAnswer(invocation -> { + item.setStatus("CANCELED"); + item.setRowVersion(8); + return new ScriptGameplayCommandHandoffService.HandoffResult( + false, "REMOTE_REJECTED", "", "", "", "QUEUE_UNAVAILABLE"); + }); when(workItemRepository.save(Mockito.any())) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -3748,12 +3721,11 @@ void retryableHandoffDispositionMarksInFlightParentWithoutChangingItsStatus() { when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) .thenReturn(Optional.of(definition)); when(handoffService.handoff(Mockito.eq(item), Mockito.any())) - .thenAnswer( - invocation -> { - item.setStatus("HANDOFF_IN_FLIGHT"); - return new ScriptGameplayCommandHandoffService.HandoffResult( - false, "REMOTE_REJECTED", "", "", "", "QUEUE_UNAVAILABLE"); - }); + .thenAnswer(invocation -> { + item.setStatus("HANDOFF_IN_FLIGHT"); + return new ScriptGameplayCommandHandoffService.HandoffResult( + false, "REMOTE_REJECTED", "", "", "", "QUEUE_UNAVAILABLE"); + }); ScriptWorkItemExecutionService service = new ScriptWorkItemExecutionServiceImpl( @@ -3851,20 +3823,18 @@ void retryablePluginFenceDuringFanoutLeavesWorkUnresolved(int acceptedChildren) when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-2")) .thenReturn(Optional.of(siblingDefinition)); when(pluginRepository.findByTenantIdAndGameInstanceIdAndPluginId("1", "7", "plugin-1")) - .thenAnswer( - invocation -> - pluginFenceReadCount.getAndIncrement() < 2 + acceptedChildren - ? Optional.of(current) - : Optional.empty()); + .thenAnswer(invocation -> + pluginFenceReadCount.getAndIncrement() < 2 + acceptedChildren + ? Optional.of(current) + : Optional.empty()); when(handoffService.handoff(Mockito.eq(item), Mockito.any())) - .thenAnswer( - invocation -> { - if (acceptedChildren > 0) { - item.setStatus("HANDOFF_IN_FLIGHT"); - } - return new ScriptGameplayCommandHandoffService.HandoffResult( - true, "ENQUEUED", "auto-1", "", "", ""); - }); + .thenAnswer(invocation -> { + if (acceptedChildren > 0) { + item.setStatus("HANDOFF_IN_FLIGHT"); + } + return new ScriptGameplayCommandHandoffService.HandoffResult( + true, "ENQUEUED", "auto-1", "", "", ""); + }); when(workItemRepository.save(Mockito.any())) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -3955,16 +3925,15 @@ void retainedOwnershipAndReceiverFenceResponsesStayNonterminalThroughExecutor( .thenAnswer( invocation -> Optional.ofNullable(handoffEvents.get(invocation.getArgument(2)))); when(handoffEventRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptHandoffEvent event = invocation.getArgument(0); - if (event.getId() == null) { - event.setId((long) event.getCommandOrdinal() + 44L); - } - event.setRowVersion(event.getRowVersion() + 1); - handoffEvents.put(event.getCommandOrdinal(), event); - return event; - }); + .thenAnswer(invocation -> { + ScriptHandoffEvent event = invocation.getArgument(0); + if (event.getId() == null) { + event.setId((long) event.getCommandOrdinal() + 44L); + } + event.setRowVersion(event.getRowVersion() + 1); + handoffEvents.put(event.getCommandOrdinal(), event); + return event; + }); ScriptGameplayCommandHandoffService handoffService = new ScriptGameplayCommandHandoffServiceImpl( gameSessionClient, @@ -4121,17 +4090,15 @@ void priorTerminalHandoffDispositionWinsOverTerminalPluginFenceAndClosesFanout() Optional.of(enabled), Optional.of(disabled)); when(handoffService.handoff(Mockito.eq(item), Mockito.any())) - .thenAnswer( - invocation -> { - ScriptGameplayCommandHandoffService.EmittedCommand command = - invocation.getArgument(1); - if (command.ordinal() == 0) { - return new ScriptGameplayCommandHandoffService.HandoffResult( - true, "ENQUEUED", "auto-1", "", "", ""); - } - return new ScriptGameplayCommandHandoffService.HandoffResult( - false, "REJECTED", "", "", "", "REMOTE_RESPONSE_INVALID"); - }); + .thenAnswer(invocation -> { + ScriptGameplayCommandHandoffService.EmittedCommand command = invocation.getArgument(1); + if (command.ordinal() == 0) { + return new ScriptGameplayCommandHandoffService.HandoffResult( + true, "ENQUEUED", "auto-1", "", "", ""); + } + return new ScriptGameplayCommandHandoffService.HandoffResult( + false, "REJECTED", "", "", "", "REMOTE_RESPONSE_INVALID"); + }); when(auditRepository.findByWorkItemId(99L)).thenReturn(Optional.of(audit)); when(workItemRepository.save(Mockito.any())) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -4557,21 +4524,19 @@ void terminalAggregateRejectionWinsOverLaterRetryableSibling() { when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) .thenReturn(Optional.of(definition)); when(handoffService.handoff(Mockito.eq(item), Mockito.any())) - .thenAnswer( - invocation -> { - ScriptGameplayCommandHandoffService.EmittedCommand command = - invocation.getArgument(1); - if (command.ordinal() == 0) { - return new ScriptGameplayCommandHandoffService.HandoffResult( - false, "RUNTIME_SCOPE_CHANGED", "", "", "", "RUNTIME_SCOPE_CHANGED"); - } - if (command.ordinal() == 1) { - return new ScriptGameplayCommandHandoffService.HandoffResult( - false, "REMOTE_REJECTED", "", "", "", "AUTHORITY_UNAVAILABLE"); - } - return new ScriptGameplayCommandHandoffService.HandoffResult( - true, "ENQUEUED", "auto-" + command.ordinal(), "", "", ""); - }); + .thenAnswer(invocation -> { + ScriptGameplayCommandHandoffService.EmittedCommand command = invocation.getArgument(1); + if (command.ordinal() == 0) { + return new ScriptGameplayCommandHandoffService.HandoffResult( + false, "RUNTIME_SCOPE_CHANGED", "", "", "", "RUNTIME_SCOPE_CHANGED"); + } + if (command.ordinal() == 1) { + return new ScriptGameplayCommandHandoffService.HandoffResult( + false, "REMOTE_REJECTED", "", "", "", "AUTHORITY_UNAVAILABLE"); + } + return new ScriptGameplayCommandHandoffService.HandoffResult( + true, "ENQUEUED", "auto-" + command.ordinal(), "", "", ""); + }); when(auditRepository.findByWorkItemId(99L)).thenReturn(Optional.of(audit)); when(workItemRepository.save(Mockito.any())) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -4645,12 +4610,11 @@ void supportsCommandSpecificTargetEntityTemplates() { when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) .thenReturn(Optional.of(definition)); when(handoffService.handoff(Mockito.eq(item), Mockito.any())) - .thenAnswer( - invocation -> { - item.setStatus("HANDED_OFF"); - return new ScriptGameplayCommandHandoffService.HandoffResult( - true, "ENQUEUED", "auto-1", "", "", ""); - }); + .thenAnswer(invocation -> { + item.setStatus("HANDED_OFF"); + return new ScriptGameplayCommandHandoffService.HandoffResult( + true, "ENQUEUED", "auto-1", "", "", ""); + }); when(auditRepository.findByWorkItemId(99L)).thenReturn(Optional.of(audit)); when(workItemRepository.save(Mockito.any())) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -4714,12 +4678,11 @@ void supportsExplicitTargetRuntimeScopeTemplates() { when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) .thenReturn(Optional.of(definition)); when(handoffService.handoff(Mockito.eq(item), Mockito.any())) - .thenAnswer( - invocation -> { - item.setStatus("HANDED_OFF"); - return new ScriptGameplayCommandHandoffService.HandoffResult( - true, "REMOTE_SCHEDULED", "", "coord-1", "followup-1", ""); - }); + .thenAnswer(invocation -> { + item.setStatus("HANDED_OFF"); + return new ScriptGameplayCommandHandoffService.HandoffResult( + true, "REMOTE_SCHEDULED", "", "coord-1", "followup-1", ""); + }); when(auditRepository.findByWorkItemId(99L)).thenReturn(Optional.of(audit)); when(workItemRepository.save(Mockito.any())) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -4781,18 +4744,17 @@ void supportsStructuredCommandAliasAndArguments() { when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) .thenReturn(Optional.of(definition)); when(handoffService.handoff(Mockito.eq(item), Mockito.any())) - .thenAnswer( - invocation -> - new ScriptGameplayCommandHandoffService.HandoffResult( - true, - "ENQUEUED", - "auto-" - + invocation - .getArgument(1) - .ordinal(), - "", - "", - "")); + .thenAnswer(invocation -> + new ScriptGameplayCommandHandoffService.HandoffResult( + true, + "ENQUEUED", + "auto-" + + invocation + .getArgument(1) + .ordinal(), + "", + "", + "")); when(auditRepository.findByWorkItemId(99L)).thenReturn(Optional.of(audit)); when(workItemRepository.save(Mockito.any())) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -4855,18 +4817,17 @@ void supportsMultiTargetCommandFanOut() { when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) .thenReturn(Optional.of(definition)); when(handoffService.handoff(Mockito.eq(item), Mockito.any())) - .thenAnswer( - invocation -> - new ScriptGameplayCommandHandoffService.HandoffResult( - true, - "ENQUEUED", - "auto-" - + invocation - .getArgument(1) - .ordinal(), - "", - "", - "")); + .thenAnswer(invocation -> + new ScriptGameplayCommandHandoffService.HandoffResult( + true, + "ENQUEUED", + "auto-" + + invocation + .getArgument(1) + .ordinal(), + "", + "", + "")); when(auditRepository.findByWorkItemId(99L)).thenReturn(Optional.of(audit)); when(workItemRepository.save(Mockito.any())) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -5139,18 +5100,17 @@ void supportsConditionalCommandEmissionWithoutOrdinalGaps() { when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) .thenReturn(Optional.of(definition)); when(handoffService.handoff(Mockito.eq(item), Mockito.any())) - .thenAnswer( - invocation -> - new ScriptGameplayCommandHandoffService.HandoffResult( - true, - "ENQUEUED", - "auto-" - + invocation - .getArgument(1) - .ordinal(), - "", - "", - "")); + .thenAnswer(invocation -> + new ScriptGameplayCommandHandoffService.HandoffResult( + true, + "ENQUEUED", + "auto-" + + invocation + .getArgument(1) + .ordinal(), + "", + "", + "")); when(auditRepository.findByWorkItemId(99L)).thenReturn(Optional.of(audit)); when(workItemRepository.save(Mockito.any())) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -6198,19 +6158,17 @@ private static ScriptWorkItemExecutionService.ExecutionBatchResult executeWithAm when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) .thenReturn(Optional.of(definition)); when(handoffService.handoff(Mockito.eq(item), Mockito.any())) - .thenAnswer( - invocation -> { - item.setStatus("HANDOFF_IN_FLIGHT"); - return new ScriptGameplayCommandHandoffService.HandoffResult( - false, "HANDOFF_IN_FLIGHT", "", "", "", "HANDOFF_IN_FLIGHT"); - }); + .thenAnswer(invocation -> { + item.setStatus("HANDOFF_IN_FLIGHT"); + return new ScriptGameplayCommandHandoffService.HandoffResult( + false, "HANDOFF_IN_FLIGHT", "", "", "", "HANDOFF_IN_FLIGHT"); + }); when(workItemRepository.save(Mockito.any())) - .thenAnswer( - invocation -> { - ScriptWorkItem persisted = invocation.getArgument(0); - persisted.setRowVersion(persisted.getRowVersion() + 1); - return persisted; - }); + .thenAnswer(invocation -> { + ScriptWorkItem persisted = invocation.getArgument(0); + persisted.setRowVersion(persisted.getRowVersion() + 1); + return persisted; + }); ScriptWorkItemExecutionService service = new ScriptWorkItemExecutionServiceImpl( @@ -6264,16 +6222,15 @@ private static ExecutionFixture executeDefinitionWithRejectedHandoff( when(definitionRepository.findByTenantIdAndScriptVersionAndName(1L, "patch-1", "script-1")) .thenReturn(Optional.of(definition)); when(handoffService.handoff(Mockito.eq(item), Mockito.any())) - .thenAnswer( - invocation -> { - item.setStatus(terminalStatus); - item.setCancelReason(reason); - audit.setFinalStage("HANDOFF"); - audit.setFinalOutcome(finalOutcome); - audit.setFinalReason(reason); - return new ScriptGameplayCommandHandoffService.HandoffResult( - false, reason, "", "", "", reason); - }); + .thenAnswer(invocation -> { + item.setStatus(terminalStatus); + item.setCancelReason(reason); + audit.setFinalStage("HANDOFF"); + audit.setFinalOutcome(finalOutcome); + audit.setFinalReason(reason); + return new ScriptGameplayCommandHandoffService.HandoffResult( + false, reason, "", "", "", reason); + }); when(auditRepository.findByWorkItemId(99L)).thenReturn(Optional.of(audit)); when(workItemRepository.save(Mockito.any())) .thenAnswer(invocation -> invocation.getArgument(0)); diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java index ae0417495d..da7de980a0 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/ScriptWorkItemServiceImplTest.java @@ -90,45 +90,35 @@ void replayAuthorityPreflightIsOutsideTheTransactionAndDurablePhaseGetsItsOwn() AtomicBoolean mutationCommitted = new AtomicBoolean(); new TransactionTemplate(transactionManager) - .execute( - status -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(TransactionSynchronizationManager.hasResource(dataSource)).isTrue(); - - boundary.withoutTransaction( - () -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()) - .isFalse(); - assertThat(TransactionSynchronizationManager.hasResource(dataSource)) - .isFalse(); - boundary.inTransaction( - () -> { - assertThat( - TransactionSynchronizationManager.isActualTransactionActive()) - .isTrue(); - assertThat(TransactionSynchronizationManager.hasResource(dataSource)) - .isTrue(); - TransactionSynchronizationManager.registerSynchronization( - new TransactionSynchronization() { - @Override - public void afterCommit() { - mutationCommitted.set(true); - } - }); - return null; - }); - assertThat(mutationCommitted).isTrue(); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()) - .isFalse(); - assertThat(TransactionSynchronizationManager.hasResource(dataSource)) - .isFalse(); - return null; - }); + .execute(status -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(dataSource)).isTrue(); + boundary.withoutTransaction(() -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.hasResource(dataSource)).isFalse(); + boundary.inTransaction(() -> { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); assertThat(TransactionSynchronizationManager.hasResource(dataSource)).isTrue(); + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public void afterCommit() { + mutationCommitted.set(true); + } + }); return null; }); + assertThat(mutationCommitted).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.hasResource(dataSource)).isFalse(); + return null; + }); + + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.hasResource(dataSource)).isTrue(); + return null; + }); } } @@ -157,10 +147,9 @@ ScriptDeadLetterReplayTransactionBoundary replayTransactionBoundary() { @Test void publicConstructorsRequireAnExplicitReplayTransactionBoundary() { assertThat(ScriptWorkItemServiceImpl.class.getConstructors()) - .allSatisfy( - constructor -> - assertThat(constructor.getParameterTypes()) - .contains(ScriptDeadLetterReplayTransactionBoundary.class)); + .allSatisfy(constructor -> + assertThat(constructor.getParameterTypes()) + .contains(ScriptDeadLetterReplayTransactionBoundary.class)); } @Test @@ -277,12 +266,11 @@ void completedReplayDuplicateReturnsStoredOutcomeWithoutFreshAuthorityReads() { assertThat(result.rejectedCount()).isZero(); assertThat(result.results()) .singleElement() - .satisfies( - replay -> { - assertThat(replay.workItemId()).isEqualTo(Long.toString(workItemId)); - assertThat(replay.outcome()).isEqualTo("retried_evaluation"); - assertThat(replay.failureGeneration()).isEqualTo(2L); - }); + .satisfies(replay -> { + assertThat(replay.workItemId()).isEqualTo(Long.toString(workItemId)); + assertThat(replay.outcome()).isEqualTo("retried_evaluation"); + assertThat(replay.failureGeneration()).isEqualTo(2L); + }); verify(replayRepository, Mockito.never()) .insertOrGet( Mockito.anyString(), @@ -317,11 +305,10 @@ void postCommitRolloutRefreshFailureIsRepairedByProjectionRead() { Mockito.anyInt(), Mockito.anyLong(), Mockito.any(Instant.class))) - .thenAnswer( - invocation -> { - item.setStatus("PENDING_EVALUATION"); - return Optional.of(item); - }); + .thenAnswer(invocation -> { + item.setStatus("PENDING_EVALUATION"); + return Optional.of(item); + }); when(workItemRepository.findByTenantIdAndGameInstanceIdAndScriptPatchVersion( "1", "game-1", "patch-1")) .thenReturn(List.of(item)); @@ -378,12 +365,11 @@ void postCommitRolloutRefreshFailureIsRepairedByProjectionRead() { Mockito.eq(1L), Mockito.eq(0L), Mockito.any(Instant.class))) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - durableCompletionCommitted.set(true); - return true; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + durableCompletionCommitted.set(true); + return true; + }); ScriptPatchPinProjectionService pinProjectionService = Mockito.mock(ScriptPatchPinProjectionService.class); @@ -391,21 +377,20 @@ void postCommitRolloutRefreshFailureIsRepairedByProjectionRead() { IllegalStateException unavailable = new IllegalStateException("pin owner temporarily unavailable"); when(pinProjectionService.getPinConvergence("1", "game-1")) - .thenAnswer( - invocation -> { - assertThat(durableCompletionCommitted).isTrue(); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - if (failFirstProjectionRefresh.getAndSet(false)) { - throw unavailable; - } - return new ScriptPatchPinProjectionService.PinConvergenceLookup( - Optional.of( - new ScriptPatchPinProjectionService.PinConvergenceSummary( - "1", "game-1", "patch-1", 7L, 1L, "req-1", 100L, 100L, 0L, false, "", 0L, - "", "", "")), - "", - ""); - }); + .thenAnswer(invocation -> { + assertThat(durableCompletionCommitted).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + if (failFirstProjectionRefresh.getAndSet(false)) { + throw unavailable; + } + return new ScriptPatchPinProjectionService.PinConvergenceLookup( + Optional.of( + new ScriptPatchPinProjectionService.PinConvergenceSummary( + "1", "game-1", "patch-1", 7L, 1L, "req-1", 100L, 100L, 0L, false, "", 0L, "", + "", "")), + "", + ""); + }); ScriptPatchInstanceRolloutProjectionRepository projectionRepository = Mockito.mock(ScriptPatchInstanceRolloutProjectionRepository.class); AtomicReference savedProjection = new AtomicReference<>(); @@ -416,12 +401,11 @@ void postCommitRolloutRefreshFailureIsRepairedByProjectionRead() { "1", "game-1", "patch-1", 1L)) .thenAnswer(invocation -> Optional.ofNullable(savedProjection.get())); when(projectionRepository.save(Mockito.any(ScriptPatchInstanceRolloutProjection.class))) - .thenAnswer( - invocation -> { - ScriptPatchInstanceRolloutProjection projection = invocation.getArgument(0); - savedProjection.set(projection); - return projection; - }); + .thenAnswer(invocation -> { + ScriptPatchInstanceRolloutProjection projection = invocation.getArgument(0); + savedProjection.set(projection); + return projection; + }); ScriptPatchInstanceRolloutProjectionServiceImpl rolloutProjectionService = new ScriptPatchInstanceRolloutProjectionServiceImpl( projectionRepository, @@ -729,10 +713,9 @@ void rejectsDirectReplayWhenRuntimeAuthorityUnavailableAfterTenantNormalization( assertThat(result.rejectedCount()).isEqualTo(1L); assertThat(result.results()) .singleElement() - .satisfies( - replay -> - assertThat(replay.rejectionReason()) - .isEqualTo("script_pin_authority_collaborator_unavailable")); + .satisfies(replay -> + assertThat(replay.rejectionReason()) + .isEqualTo("script_pin_authority_collaborator_unavailable")); assertThat(item.getStatus()).isEqualTo("DEAD_LETTERED"); assertThat(item.getAuthorityUnavailableRetryCount()).isEqualTo(4); assertThat(item.getNextEligibleAt()).isEqualTo(retryEligibilityAt); @@ -784,10 +767,9 @@ void replayCountsOnlyCanonicalRetriedOutcome() { Mockito.anyString(), Mockito.anyString(), Mockito.any())) - .thenAnswer( - invocation -> - new ScriptDeadLetterReplayRepository.ReplayRequest( - 1L, invocation.getArgument(2), "RUNNING", 0L, 0L)); + .thenAnswer(invocation -> + new ScriptDeadLetterReplayRepository.ReplayRequest( + 1L, invocation.getArgument(2), "RUNNING", 0L, 0L)); when(replayRepository.findResults("1", 1L)) .thenReturn( List.of( @@ -821,12 +803,11 @@ void replayCountsOnlyCanonicalRetriedOutcome() { assertThat(result.rejectedCount()).isEqualTo(1L); assertThat(result.results()) .singleElement() - .satisfies( - item -> { - assertThat(item.outcome()).isEqualTo("rejected"); - assertThat(item.rejectionReason()).isEqualTo("stage_evidence_unavailable"); - assertThat(item.failureReason()).isEmpty(); - }); + .satisfies(item -> { + assertThat(item.outcome()).isEqualTo("rejected"); + assertThat(item.rejectionReason()).isEqualTo("stage_evidence_unavailable"); + assertThat(item.failureReason()).isEmpty(); + }); } @Test @@ -854,10 +835,9 @@ void rejectsReplayAfterPartialFanoutAuthorityLossWithoutReenteringDsl() { Mockito.anyString(), Mockito.anyString(), Mockito.any(Instant.class))) - .thenAnswer( - invocation -> - new ScriptDeadLetterReplayRepository.ReplayRequest( - 7L, invocation.getArgument(2), "RUNNING", 0L, 0L)); + .thenAnswer(invocation -> + new ScriptDeadLetterReplayRepository.ReplayRequest( + 7L, invocation.getArgument(2), "RUNNING", 0L, 0L)); when(replayRepository.findResults("1", 7L)).thenReturn(List.of()); when(replayRepository.complete( Mockito.eq("1"), @@ -940,11 +920,10 @@ void rejectsReplayAfterPartialFanoutAuthorityLossWithoutReenteringDsl() { assertThat(result.rejectedCount()).isEqualTo(1L); assertThat(result.results()) .singleElement() - .satisfies( - replay -> { - assertThat(replay.outcome()).isEqualTo("rejected"); - assertThat(replay.rejectionReason()).isEqualTo("stage_evidence_unavailable"); - }); + .satisfies(replay -> { + assertThat(replay.outcome()).isEqualTo("rejected"); + assertThat(replay.rejectionReason()).isEqualTo("stage_evidence_unavailable"); + }); assertThat(originalStage).hasValue("TICK_HANDOFF"); assertThat(originalReason).hasValue("authority_unavailable"); assertThat(item.getCancelReason()).isEqualTo("authority_unavailable"); @@ -992,10 +971,9 @@ void rejectsReplayWithoutOriginalFailureEvidenceBeforeClaim() { Mockito.anyString(), Mockito.anyString(), Mockito.any(Instant.class))) - .thenAnswer( - invocation -> - new ScriptDeadLetterReplayRepository.ReplayRequest( - 8L, invocation.getArgument(2), "RUNNING", 0L, 0L)); + .thenAnswer(invocation -> + new ScriptDeadLetterReplayRepository.ReplayRequest( + 8L, invocation.getArgument(2), "RUNNING", 0L, 0L)); when(replayRepository.findResults("1", 8L)).thenReturn(List.of()); when(replayRepository.complete( Mockito.eq("1"), @@ -1132,10 +1110,9 @@ void completesAllAuthorityPreflightReadsBeforeTakingReplayRowLock() { Mockito.anyString(), Mockito.anyString(), Mockito.any(Instant.class))) - .thenAnswer( - invocation -> - new ScriptDeadLetterReplayRepository.ReplayRequest( - 1L, invocation.getArgument(2), "RUNNING", 0L, 0L)); + .thenAnswer(invocation -> + new ScriptDeadLetterReplayRepository.ReplayRequest( + 1L, invocation.getArgument(2), "RUNNING", 0L, 0L)); when(replayRepository.findResults("1", 1L)).thenReturn(List.of()); when(replayRepository.complete( Mockito.eq("1"), @@ -1244,12 +1221,11 @@ void rejectsReplayWhenSnapshotRowVersionOrFailureGenerationDriftsBeforeClaim( assertThat(result.replayedCount()).isZero(); assertThat(result.results()) .singleElement() - .satisfies( - replay -> { - assertThat(replay.outcome()).isEqualTo("rejected"); - assertThat(replay.rejectionReason()).isEqualTo("recovery_in_progress"); - assertThat(replay.failureGeneration()).isEqualTo(currentFailureGeneration); - }); + .satisfies(replay -> { + assertThat(replay.outcome()).isEqualTo("rejected"); + assertThat(replay.rejectionReason()).isEqualTo("recovery_in_progress"); + assertThat(replay.failureGeneration()).isEqualTo(currentFailureGeneration); + }); verify(workItemRepository, never()) .claimDeadLetterForReplay( Mockito.anyLong(), @@ -1271,10 +1247,9 @@ void replayAggregateCountsAreDerivedFromPerItemOutcomes() { Mockito.anyString(), Mockito.anyString(), Mockito.any())) - .thenAnswer( - invocation -> - new ScriptDeadLetterReplayRepository.ReplayRequest( - 1L, invocation.getArgument(2), "COMPLETED", 1L, 4L)); + .thenAnswer(invocation -> + new ScriptDeadLetterReplayRepository.ReplayRequest( + 1L, invocation.getArgument(2), "COMPLETED", 1L, 4L)); when(replayRepository.findResults("1", 1L)) .thenReturn( List.of( @@ -1377,11 +1352,10 @@ void rejectsReplayUnlessPersistedFailureClassIsKnownRetryable( assertThat(result.rejectedCount()).isEqualTo(1L); assertThat(result.results()) .singleElement() - .satisfies( - replay -> { - assertThat(replay.outcome()).isEqualTo("rejected"); - assertThat(replay.rejectionReason()).isEqualTo("stage_evidence_unavailable"); - }); + .satisfies(replay -> { + assertThat(replay.outcome()).isEqualTo("rejected"); + assertThat(replay.rejectionReason()).isEqualTo("stage_evidence_unavailable"); + }); assertThat(fixture.workItem().getStatus()).isEqualTo("DEAD_LETTERED"); verify(fixture.workItemRepository(), Mockito.never()) .claimDeadLetterForReplay( @@ -1438,11 +1412,10 @@ void rejectsTenantReplayWithoutExplicitWorkItemIds() { ScriptWorkItemRepository workItemRepository = Mockito.mock(ScriptWorkItemRepository.class); ScriptWorkItemService service = replayService(workItemRepository); - assertThatThrownBy( - () -> - service.replayDeadLetters( - new ScriptWorkItemService.ReplayDeadLettersCommand( - " 1 ", "", "", List.of(), "", 0L, 0L, 0, "req-91", "", ""))) + assertThatThrownBy(() -> + service.replayDeadLetters( + new ScriptWorkItemService.ReplayDeadLettersCommand( + " 1 ", "", "", List.of(), "", 0L, 0L, 0, "req-91", "", ""))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("invalid_work_item_ids"); verifyNoInteractions(workItemRepository); @@ -1642,13 +1615,12 @@ void cancellationContinuesAfterFullPageAndStopsAfterShortPage() { void pluginCancellationContinuesAfterFullPageAndStopsAfterShortPage() { List firstPage = IntStream.rangeClosed(1, ScriptWorkItemRepository.CANCELLATION_PAGE_SIZE) - .mapToObj( - id -> { - ScriptWorkItem item = cancelableWorkItem(id, "patch-1"); - item.setPluginId("plugin-1"); - item.setPluginVersionId("plugin-v1"); - return item; - }) + .mapToObj(id -> { + ScriptWorkItem item = cancelableWorkItem(id, "patch-1"); + item.setPluginId("plugin-1"); + item.setPluginVersionId("plugin-v1"); + return item; + }) .toList(); ScriptWorkItem secondItem = cancelableWorkItem(ScriptWorkItemRepository.CANCELLATION_PAGE_SIZE + 1L, "patch-1"); @@ -2679,39 +2651,34 @@ void rejectsOwnerRequestIdWithoutEpochOnAllFullRolloutReads() { Mockito.mock(PluginRuntimeStateService.class), gameDesignClient()); - assertThatThrownBy( - () -> - service.getPatchInstanceRolloutStatus( - "1", "game-1", "patch-1", 0L, "request-without-epoch")) + assertThatThrownBy(() -> + service.getPatchInstanceRolloutStatus( + "1", "game-1", "patch-1", 0L, "request-without-epoch")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("must be present exactly when script_pin_epoch is positive"); - assertThatThrownBy( - () -> - service.listPatchInstanceRollouts( - "1", - "game-1", - "patch-1", - 0L, - "request-without-epoch", - ScriptPatchInstanceRolloutStatus - .SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED, - 0L, - 0L)) + assertThatThrownBy(() -> + service.listPatchInstanceRollouts( + "1", + "game-1", + "patch-1", + 0L, + "request-without-epoch", + ScriptPatchInstanceRolloutStatus.SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED, + 0L, + 0L)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("must be present exactly when script_pin_epoch is positive"); - assertThatThrownBy( - () -> - service.listPatchInstanceRolloutEvents( - "1", - "game-1", - "patch-1", - 0L, - "request-without-epoch", - ScriptPatchInstanceRolloutStatus - .SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED, - 0L, - 0L, - 25)) + assertThatThrownBy(() -> + service.listPatchInstanceRolloutEvents( + "1", + "game-1", + "patch-1", + 0L, + "request-without-epoch", + ScriptPatchInstanceRolloutStatus.SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED, + 0L, + 0L, + 25)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("must be present exactly when script_pin_epoch is positive"); verifyNoInteractions(rolloutProjectionService); @@ -2738,33 +2705,29 @@ void rejectsPositiveEpochWithoutOwnerRequestIdOnAllFullRolloutReads() { () -> service.getPatchInstanceRolloutStatus("1", "game-1", "patch-1", 2L, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("must be present exactly when script_pin_epoch is positive"); - assertThatThrownBy( - () -> - service.listPatchInstanceRollouts( - "1", - "game-1", - "patch-1", - 2L, - " ", - ScriptPatchInstanceRolloutStatus - .SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED, - 0L, - 0L)) + assertThatThrownBy(() -> + service.listPatchInstanceRollouts( + "1", + "game-1", + "patch-1", + 2L, + " ", + ScriptPatchInstanceRolloutStatus.SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED, + 0L, + 0L)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("must be present exactly when script_pin_epoch is positive"); - assertThatThrownBy( - () -> - service.listPatchInstanceRolloutEvents( - "1", - "game-1", - "patch-1", - 2L, - null, - ScriptPatchInstanceRolloutStatus - .SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED, - 0L, - 0L, - 25)) + assertThatThrownBy(() -> + service.listPatchInstanceRolloutEvents( + "1", + "game-1", + "patch-1", + 2L, + null, + ScriptPatchInstanceRolloutStatus.SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED, + 0L, + 0L, + 25)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("must be present exactly when script_pin_epoch is positive"); verifyNoInteractions(rolloutProjectionService); @@ -2787,19 +2750,17 @@ void rejectsBlankRolloutEventTenantBeforeProjectionLookup() { Mockito.mock(PluginRuntimeStateService.class), gameDesignClient()); - assertThatThrownBy( - () -> - service.listPatchInstanceRolloutEvents( - "", - "game-1", - "patch-1", - 0L, - null, - ScriptPatchInstanceRolloutStatus - .SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED, - 0L, - 0L, - 25)) + assertThatThrownBy(() -> + service.listPatchInstanceRolloutEvents( + "", + "game-1", + "patch-1", + 0L, + null, + ScriptPatchInstanceRolloutStatus.SCRIPT_PATCH_INSTANCE_ROLLOUT_STATUS_UNSPECIFIED, + 0L, + 0L, + 25)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("tenant_id is required"); verifyNoInteractions(rolloutProjectionService); @@ -3139,11 +3100,10 @@ void rolloutEventsUseImmutablePatchBaseWithoutCurrentReadiness() { assertThat(events) .singleElement() - .satisfies( - event -> { - assertThat(event.publication().baseVersionId()).isEqualTo(7L); - assertThat(event.publication().versionId()).isEqualTo(17L); - }); + .satisfies(event -> { + assertThat(event.publication().baseVersionId()).isEqualTo(7L); + assertThat(event.publication().versionId()).isEqualTo(17L); + }); verify(gameDesignControlPlaneClient).getPublishedScriptPatchVersion("1", 7L, "patch-1"); verifyNoInteractions(readinessProjectionService); } @@ -3314,11 +3274,10 @@ void listDeadLettersUsesTheWorkItemsRetainedPatchBase() { assertThat(summaries) .singleElement() - .satisfies( - summary -> { - assertThat(summary.scriptPatchBaseVersionId()).isEqualTo(11L); - assertThat(summary.publication().baseVersionId()).isEqualTo(11L); - }); + .satisfies(summary -> { + assertThat(summary.scriptPatchBaseVersionId()).isEqualTo(11L); + assertThat(summary.publication().baseVersionId()).isEqualTo(11L); + }); verify(patchBaseRepository, never()).findScriptPatchBaseVersionId("1", "patch-1"); verify(gameDesignControlPlaneClient).getPublishedScriptPatchVersion("1", 11L, "patch-1"); } @@ -3354,13 +3313,12 @@ void listDeadLettersFailsClosedWhenRetainedPatchBaseIsNull() { assertThat(summaries) .singleElement() - .satisfies( - summary -> { - assertThat(summary.scriptPatchBaseVersionId()).isZero(); - assertThat(summary.publication().baseVersionId()).isZero(); - assertThat(summary.publication().lookupErrorCode()) - .isEqualTo("PUBLICATION_SCOPE_UNAVAILABLE"); - }); + .satisfies(summary -> { + assertThat(summary.scriptPatchBaseVersionId()).isZero(); + assertThat(summary.publication().baseVersionId()).isZero(); + assertThat(summary.publication().lookupErrorCode()) + .isEqualTo("PUBLICATION_SCOPE_UNAVAILABLE"); + }); verify(gameDesignControlPlaneClient, never()) .getPublishedScriptPatchVersion( Mockito.anyString(), Mockito.anyLong(), Mockito.anyString()); @@ -3796,10 +3754,9 @@ void rejectsPluginOwnedDeadLetterWhenRuntimeAuthorityIsUnavailable() { assertThat(result.rejectedCount()).isEqualTo(1L); assertThat(result.results()) .singleElement() - .satisfies( - replay -> - assertThat(replay.rejectionReason()) - .isEqualTo("script_pin_authority_collaborator_unavailable")); + .satisfies(replay -> + assertThat(replay.rejectionReason()) + .isEqualTo("script_pin_authority_collaborator_unavailable")); assertThat(item.getStatus()).isEqualTo("DEAD_LETTERED"); verify(pluginRuntimeStateService, Mockito.never()).getStatus("1", "game-1", "plugin-1"); } @@ -3910,10 +3867,9 @@ void propagatesGameSessionAuthorityReadFailureWithoutCompletingReplayRequest() { Mockito.anyString(), Mockito.anyString(), Mockito.any(Instant.class))) - .thenAnswer( - invocation -> - new ScriptDeadLetterReplayRepository.ReplayRequest( - 1L, invocation.getArgument(2), "RUNNING", 0L, 0L)); + .thenAnswer(invocation -> + new ScriptDeadLetterReplayRepository.ReplayRequest( + 1L, invocation.getArgument(2), "RUNNING", 0L, 0L)); when(replayRepository.findResults("1", 1L)).thenReturn(List.of()); GameSessionControlPlaneClient gameSessionControlPlaneClient = Mockito.mock(GameSessionControlPlaneClient.class); @@ -4033,12 +3989,11 @@ void concurrentSameRequestUsesWinningDurableResultsAfterPreflight() { assertThat(result.requestFingerprint()).isEqualTo(fingerprint); assertThat(result.results()) .singleElement() - .satisfies( - replay -> { - assertThat(replay.outcome()).isEqualTo("rejected"); - assertThat(replay.rejectionReason()).isEqualTo("recovery_in_progress"); - assertThat(replay.failureGeneration()).isEqualTo(6L); - }); + .satisfies(replay -> { + assertThat(replay.outcome()).isEqualTo("rejected"); + assertThat(replay.rejectionReason()).isEqualTo("recovery_in_progress"); + assertThat(replay.failureGeneration()).isEqualTo(6L); + }); verify(fixture.workItemRepository(), Mockito.never()) .findByTenantIdAndIdForUpdate("1", workItemId); verify(fixture.workItemRepository(), Mockito.never()) @@ -4152,9 +4107,8 @@ void rejectsReplayWhenPinnedPatchDoesNotMatch() { assertThat(result.rejectedCount()).isEqualTo(1L); assertThat(result.results()) .singleElement() - .satisfies( - replay -> - assertThat(replay.rejectionReason()).isEqualTo("script_patch_version_mismatch")); + .satisfies(replay -> + assertThat(replay.rejectionReason()).isEqualTo("script_patch_version_mismatch")); assertThat(item.getStatus()).isEqualTo("DEAD_LETTERED"); verify(workItemRepository, never()) .claimDeadLetterForReplay( @@ -4264,13 +4218,12 @@ void rejectsReplayWhenPinnedPatchBaseIsUnknownOrMismatched(long pinnedBaseVersio assertThat(result.rejectedCount()).isEqualTo(1L); assertThat(result.results()) .singleElement() - .satisfies( - replayResult -> - assertThat(replayResult.rejectionReason()) - .isEqualTo( - pinnedBaseVersionId <= 0L - ? "script_patch_base_version_unavailable" - : "script_patch_base_version_mismatch")); + .satisfies(replayResult -> + assertThat(replayResult.rejectionReason()) + .isEqualTo( + pinnedBaseVersionId <= 0L + ? "script_patch_base_version_unavailable" + : "script_patch_base_version_mismatch")); assertThat(item.getStatus()).isEqualTo("DEAD_LETTERED"); } @@ -4328,11 +4281,10 @@ void rejectsOnLoadDeadLetterWithCanonicalReplayReason() { assertThat(result.rejectedCount()).isEqualTo(1L); assertThat(result.results()) .singleElement() - .satisfies( - replay -> { - assertThat(replay.outcome()).isEqualTo("rejected"); - assertThat(replay.rejectionReason()).isEqualTo("onload_not_replayable"); - }); + .satisfies(replay -> { + assertThat(replay.outcome()).isEqualTo("rejected"); + assertThat(replay.rejectionReason()).isEqualTo("onload_not_replayable"); + }); assertThat(item.getStatus()).isEqualTo("DEAD_LETTERED"); verify(readinessProjectionService, Mockito.never()) .refreshFromOnLoadWorkItems(Mockito.anyString(), Mockito.anyString()); @@ -4425,9 +4377,8 @@ void rejectsOnLoadReplayBeforeReadinessLookup() { assertThat(result.rejectedCount()).isEqualTo(1L); assertThat(result.results()) .singleElement() - .satisfies( - replayResult -> - assertThat(replayResult.rejectionReason()).isEqualTo("onload_not_replayable")); + .satisfies(replayResult -> + assertThat(replayResult.rejectionReason()).isEqualTo("onload_not_replayable")); assertThat(item.getStatus()).isEqualTo("DEAD_LETTERED"); verify(readinessProjectionService, Mockito.never()).getProjection("1", "patch-1"); verify(workItemRepository, never()).save(item); @@ -4449,11 +4400,10 @@ void replayRejectsNonPositiveWorkItemIdBeforeRepositoryRead() { Mockito.mock(PluginRuntimeStateService.class), gameDesignClient()); - assertThatThrownBy( - () -> - service.replayDeadLetters( - new ScriptWorkItemService.ReplayDeadLettersCommand( - "1", "", "", List.of("0"), "", 0L, 0L, 0, "", "", ""))) + assertThatThrownBy(() -> + service.replayDeadLetters( + new ScriptWorkItemService.ReplayDeadLettersCommand( + "1", "", "", List.of("0"), "", 0L, 0L, 0, "", "", ""))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("work_item_id must be positive"); Mockito.verifyNoInteractions(workItemRepository); @@ -4504,11 +4454,10 @@ void replayRejectsDistinctTextualIdsThatParseToTheSameWorkItem() { Mockito.mock(PluginRuntimeStateService.class), gameDesignClient()); - assertThatThrownBy( - () -> - service.replayDeadLetters( - new ScriptWorkItemService.ReplayDeadLettersCommand( - "1", "", "", List.of("01", "1"), "", 0L, 0L, 0, "req-duplicate", "", ""))) + assertThatThrownBy(() -> + service.replayDeadLetters( + new ScriptWorkItemService.ReplayDeadLettersCommand( + "1", "", "", List.of("01", "1"), "", 0L, 0L, 0, "req-duplicate", "", ""))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("invalid_work_item_ids"); Mockito.verifyNoInteractions(workItemRepository); @@ -4538,21 +4487,20 @@ void replayRejectsPositivePreviewLimitWithoutPreviewToken() { Mockito.mock(ScriptDefinitionRepository.class), null); - assertThatThrownBy( - () -> - service.replayDeadLetters( - new ScriptWorkItemService.ReplayDeadLettersCommand( - "1", - "", - "", - List.of("101", "102"), - "", - 0L, - 0L, - 1, - "req-limit", - "admin", - "retry"))) + assertThatThrownBy(() -> + service.replayDeadLetters( + new ScriptWorkItemService.ReplayDeadLettersCommand( + "1", + "", + "", + List.of("101", "102"), + "", + 0L, + 0L, + 1, + "req-limit", + "admin", + "retry"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("replay_filters_require_preview"); Mockito.verifyNoInteractions(workItemRepository, replayRepository); @@ -4623,15 +4571,14 @@ void replayRejectsChangedRequestInputForReusedRequestId() { Mockito.anyString(), Mockito.anyString(), Mockito.any(Instant.class))) - .thenAnswer( - invocation -> { - storedFingerprint.compareAndSet(null, invocation.getArgument(2)); - storedRequest.compareAndSet( - null, - new ScriptDeadLetterReplayRepository.ReplayRequest( - 1L, storedFingerprint.get(), "RUNNING", 0L, 0L)); - return storedRequest.get(); - }); + .thenAnswer(invocation -> { + storedFingerprint.compareAndSet(null, invocation.getArgument(2)); + storedRequest.compareAndSet( + null, + new ScriptDeadLetterReplayRepository.ReplayRequest( + 1L, storedFingerprint.get(), "RUNNING", 0L, 0L)); + return storedRequest.get(); + }); when(replayRepository.findResults("1", 1L)).thenReturn(List.of()); ScriptWorkItemService service = scriptWorkItemService( @@ -4656,21 +4603,10 @@ void replayRejectsChangedRequestInputForReusedRequestId() { new ScriptWorkItemService.ReplayDeadLettersCommand( "1", "", "", List.of("101"), "", 0L, 0L, 0, "req-conflict", "admin", "retry")); - assertThatThrownBy( - () -> - service.replayDeadLetters( - new ScriptWorkItemService.ReplayDeadLettersCommand( - "1", - "", - "", - List.of("102"), - "", - 0L, - 0L, - 0, - "req-conflict", - "admin", - "retry"))) + assertThatThrownBy(() -> + service.replayDeadLetters( + new ScriptWorkItemService.ReplayDeadLettersCommand( + "1", "", "", List.of("102"), "", 0L, 0L, 0, "req-conflict", "admin", "retry"))) .isInstanceOf(ScriptWorkItemServiceImpl.ReplayIdempotencyConflictException.class) .hasMessage("control_plane_request_id already records a different replay request"); verify(workItemRepository).findByTenantIdAndIdInOrderByIdAsc("1", List.of(101L)); @@ -4968,11 +4904,10 @@ private static ReplayQueueFixture replayQueueFixture( Mockito.anyInt(), Mockito.anyLong(), Mockito.any(Instant.class))) - .thenAnswer( - invocation -> { - item.setStatus("PENDING_EVALUATION"); - return Optional.of(item); - }); + .thenAnswer(invocation -> { + item.setStatus("PENDING_EVALUATION"); + return Optional.of(item); + }); ScriptEventAuditRepository auditRepository = Mockito.mock(ScriptEventAuditRepository.class); when(auditRepository.findByWorkItemId(id)).thenReturn(Optional.of(audit)); GameSessionControlPlaneClient gameSessionControlPlaneClient = @@ -5026,11 +4961,10 @@ private static void assertRetryablePluginAuthority(PluginReplayFixture fixture) assertThat(result.rejectedCount()).isEqualTo(1L); assertThat(result.results()) .singleElement() - .satisfies( - replay -> { - assertThat(replay.outcome()).isEqualTo("rejected"); - assertThat(replay.rejectionReason()).isEqualTo("authority_unavailable"); - }); + .satisfies(replay -> { + assertThat(replay.outcome()).isEqualTo("rejected"); + assertThat(replay.rejectionReason()).isEqualTo("authority_unavailable"); + }); assertThat(fixture.workItem().getStatus()).isEqualTo("DEAD_LETTERED"); verify(fixture.replayRepository()) .saveResult( @@ -5104,10 +5038,9 @@ private static PluginReplayFixture pluginReplayFixture(long id) { Mockito.anyString(), Mockito.anyString(), Mockito.any(Instant.class))) - .thenAnswer( - invocation -> - new ScriptDeadLetterReplayRepository.ReplayRequest( - 1L, invocation.getArgument(2), "RUNNING", 0L, 0L)); + .thenAnswer(invocation -> + new ScriptDeadLetterReplayRepository.ReplayRequest( + 1L, invocation.getArgument(2), "RUNNING", 0L, 0L)); when(replayRepository.findResults("1", 1L)).thenReturn(List.of()); when(replayRepository.complete( Mockito.eq("1"), diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeValueTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeValueTest.java index 39549fb158..3a0d4bec21 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeValueTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeValueTest.java @@ -132,10 +132,9 @@ void configuredNamespaceRejectsMismatchedTargetBeforeAnyOwnerRead() { mock(SelectedOwnerIntakeAuthorizationReadClient.class); SelectedOwnerWorldInventoryReadClient worldInventoryReadClient = mock(SelectedOwnerWorldInventoryReadClient.class); - assertThatThrownBy( - () -> - new AutomationEmptySelectedSourceIntakeService( - repository, authorizationReadClient, worldInventoryReadClient, "bad namespace")) + assertThatThrownBy(() -> + new AutomationEmptySelectedSourceIntakeService( + repository, authorizationReadClient, worldInventoryReadClient, "bad namespace")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Canonical namespace"); @@ -242,10 +241,8 @@ void exactCommittedRequestRetryReturnsReceiptBeforeConsultingSettledAuthority() try (MockedStatic receiptStatic = mockStatic(AutomationEmptySelectedSourceIntakeReceipt.class)) { receiptStatic - .when( - () -> - AutomationEmptySelectedSourceIntakeReceipt.requestDigest( - namespace, binding, freeze)) + .when(() -> + AutomationEmptySelectedSourceIntakeReceipt.requestDigest(namespace, binding, freeze)) .thenReturn(requestDigest); assertThat(service.retain(namespace, binding, freeze)).isSameAs(receipt); } finally { diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java index bed367ea99..d9385cea45 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java @@ -150,24 +150,23 @@ private static GetDraftDesignDigestResponse invokeAsGameDesign( "spiffe://firemud/ns/test/sa/game-design-service", NAMESPACE, "game-design-service")) - .run( - () -> - receiver.getDraftDesignDigest( - request, - new StreamObserver<>() { - @Override - public void onNext(GetDraftDesignDigestResponse value) { - response.set(value); - } - - @Override - public void onError(Throwable error) { - throw new AssertionError(error); - } - - @Override - public void onCompleted() {} - })); + .run(() -> + receiver.getDraftDesignDigest( + request, + new StreamObserver<>() { + @Override + public void onNext(GetDraftDesignDigestResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable error) { + throw new AssertionError(error); + } + + @Override + public void onCompleted() {} + })); return response.get(); } } diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadServiceTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadServiceTest.java index 3600495cce..638f6649b4 100644 --- a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadServiceTest.java +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadServiceTest.java @@ -78,10 +78,8 @@ void missingReceiptIsNotConvertedToTerminalEvidence() { try { assertThatThrownBy(() -> service.read(request(binding))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.NOT_FOUND)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()).isEqualTo(Status.Code.NOT_FOUND)); } finally { accountContext.detach(previous); } @@ -101,10 +99,9 @@ void rejectsChangedTupleAndCorruptStoredReceipt() { try { assertThatThrownBy(() -> service.read(request(binding))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.ALREADY_EXISTS)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.ALREADY_EXISTS)); doThrow( new AutomationEmptySelectedSourceIntakeRepository.CorruptReceiptException( @@ -113,10 +110,8 @@ void rejectsChangedTupleAndCorruptStoredReceipt() { .readCommittedTerminal(binding); assertThatThrownBy(() -> service.read(request(binding))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.DATA_LOSS)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()).isEqualTo(Status.Code.DATA_LOSS)); } finally { accountContext.detach(previous); } @@ -143,17 +138,15 @@ void databaseOutagesAreSanitizedAsUnavailable() { assertThatThrownBy(() -> service.read(terminalRequest)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> { - var status = Status.fromThrowable(error); - assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); - assertThat(status.getDescription()) - .isEqualTo("Automation terminal receipt storage is unavailable"); - assertThat(status.getDescription()) - .doesNotContain("private jOOQ", "private Spring"); - assertThat(((StatusRuntimeException) error).getCause()).isNull(); - assertThat(((StatusRuntimeException) error).getTrailers()).isNull(); - }); + .satisfies(error -> { + var status = Status.fromThrowable(error); + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status.getDescription()) + .isEqualTo("Automation terminal receipt storage is unavailable"); + assertThat(status.getDescription()).doesNotContain("private jOOQ", "private Spring"); + assertThat(((StatusRuntimeException) error).getCause()).isNull(); + assertThat(((StatusRuntimeException) error).getTrailers()).isNull(); + }); var recovered = service.read(terminalRequest); assertThat(recovered.request()).isSameAs(terminalRequest); @@ -174,10 +167,9 @@ void rejectsWrongPeerEndUserAndAmbientSqlBeforeRepositoryLookup() { assertThatThrownBy(() -> service.read(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); var wrongPeer = new GrpcPeerIdentity( @@ -187,10 +179,9 @@ void rejectsWrongPeerEndUserAndAmbientSqlBeforeRepositoryLookup() { try { assertThatThrownBy(() -> service.read(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } finally { wrongContext.detach(previous); } @@ -201,28 +192,25 @@ void rejectsWrongPeerEndUserAndAmbientSqlBeforeRepositoryLookup() { SessionContext.setContext("1001", List.of(), Map.of()); assertThatThrownBy(() -> service.read(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); SessionContext.clear(); TransactionSynchronizationManager.setActualTransactionActive(true); assertThatThrownBy(() -> service.read(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); TransactionSynchronizationManager.setActualTransactionActive(false); TransactionSynchronizationManager.initSynchronization(); assertThatThrownBy(() -> service.read(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); TransactionSynchronizationManager.clearSynchronization(); } finally { accountContext.detach(previous); diff --git a/services/common-data-runtime/src/main/java/net/firedevops/firemud/cache/RedisScreenBufferService.java b/services/common-data-runtime/src/main/java/net/firedevops/firemud/cache/RedisScreenBufferService.java index 815b8d7906..913903f76b 100644 --- a/services/common-data-runtime/src/main/java/net/firedevops/firemud/cache/RedisScreenBufferService.java +++ b/services/common-data-runtime/src/main/java/net/firedevops/firemud/cache/RedisScreenBufferService.java @@ -123,13 +123,12 @@ public void replace( public Optional get(long tenantId, long gameInstanceId, long characterId) { return readPayload(tenantId, gameInstanceId, characterId) .filter(payload -> !payload.entries.isEmpty()) - .map( - payload -> - new BufferedScreen( - payload.entries.stream().map(EntryPayload::toPublicEntry).toList(), - payload.entries.size(), - payload.entries.stream().mapToInt(entry -> entry.lineCount).sum(), - payload.updatedAtMs)); + .map(payload -> + new BufferedScreen( + payload.entries.stream().map(EntryPayload::toPublicEntry).toList(), + payload.entries.size(), + payload.entries.stream().mapToInt(entry -> entry.lineCount).sum(), + payload.updatedAtMs)); } @Override diff --git a/services/common-data-runtime/src/test/java/net/firedevops/firemud/cache/ResumeTranscriptCanonicalizerTest.java b/services/common-data-runtime/src/test/java/net/firedevops/firemud/cache/ResumeTranscriptCanonicalizerTest.java index 17ae9ddfd5..16890ffb07 100644 --- a/services/common-data-runtime/src/test/java/net/firedevops/firemud/cache/ResumeTranscriptCanonicalizerTest.java +++ b/services/common-data-runtime/src/test/java/net/firedevops/firemud/cache/ResumeTranscriptCanonicalizerTest.java @@ -27,40 +27,38 @@ void sortsObjectKeysByTheirNfcNormalizedForm() { @Test void rejectsObjectKeysThatCollapseAfterNfcNormalization() { - assertThatThrownBy( - () -> - ResumeTranscriptCanonicalizer.canonicalJson( - 1L, - 2L, - 3L, - 4L, - 0L, - "VIEW", - "REPLAY", - "FULL", - "view", - "{\"e\\u0301\":1,\"é\":2}", - "text")) + assertThatThrownBy(() -> + ResumeTranscriptCanonicalizer.canonicalJson( + 1L, + 2L, + 3L, + 4L, + 0L, + "VIEW", + "REPLAY", + "FULL", + "view", + "{\"e\\u0301\":1,\"é\":2}", + "text")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("duplicate keys after NFC normalization"); } @Test void rejectsExactDuplicateJsonKeysBeforeCanonicalization() { - assertThatThrownBy( - () -> - ResumeTranscriptCanonicalizer.canonicalJson( - 1L, - 2L, - 3L, - 4L, - 0L, - "VIEW", - "REPLAY", - "FULL", - "view", - "{\"room\":\"R-1\",\"room\":\"R-2\"}", - "text")) + assertThatThrownBy(() -> + ResumeTranscriptCanonicalizer.canonicalJson( + 1L, + 2L, + 3L, + 4L, + 0L, + "VIEW", + "REPLAY", + "FULL", + "view", + "{\"room\":\"R-1\",\"room\":\"R-2\"}", + "text")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("duplicate keys"); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountAuthoritySourceEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountAuthoritySourceEventV1Codec.java index 3aa2dce1ed..e7ed49ea70 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountAuthoritySourceEventV1Codec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountAuthoritySourceEventV1Codec.java @@ -360,10 +360,9 @@ private static void exactFields(ObjectNode object, Set expected) { } object .fieldNames() - .forEachRemaining( - field -> { - if (!expected.contains(field)) throw invalid(field, "is not declared by this schema"); - }); + .forEachRemaining(field -> { + if (!expected.contains(field)) throw invalid(field, "is not declared by this schema"); + }); } private static void exact(ObjectNode object, String field, String expected) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/MembershipAuthorityEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/MembershipAuthorityEventV1Codec.java index 77f0c35189..594dd925d6 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/MembershipAuthorityEventV1Codec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/MembershipAuthorityEventV1Codec.java @@ -257,19 +257,16 @@ private static Map validateGenerationMap(JsonNode mapNode, Strin Map values = new TreeMap<>(); object .fields() - .forEachRemaining( - entry -> { - requireUuidKey(entry.getKey(), path); - JsonNode value = entry.getValue(); - if (value == null - || !value.isTextual() - || !isPositiveOwnerCounter(value.textValue())) { - throw invalid( - path + "." + entry.getKey(), - "must be a positive canonical decimal string in the owner range"); - } - values.put(entry.getKey(), value.textValue()); - }); + .forEachRemaining(entry -> { + requireUuidKey(entry.getKey(), path); + JsonNode value = entry.getValue(); + if (value == null || !value.isTextual() || !isPositiveOwnerCounter(value.textValue())) { + throw invalid( + path + "." + entry.getKey(), + "must be a positive canonical decimal string in the owner range"); + } + values.put(entry.getKey(), value.textValue()); + }); return Collections.unmodifiableMap(values); } @@ -340,26 +337,22 @@ private static void validateTenantBillingCutoff(JsonNode cutoffNode, String even } cutoffs .fields() - .forEachRemaining( - entry -> { - String tenantId = entry.getKey(); - requireUuidKey(tenantId, "authorityTuple.tenantBillingCutoff"); - if (!(entry.getValue() instanceof ObjectNode cutoff)) { - throw invalid( - "authorityTuple.tenantBillingCutoff." + tenantId, "must be an object"); - } - requireExactFields( - cutoff, TENANT_CUTOFF_FIELDS, Set.of(), "tenantBillingCutoff entry"); - requirePositiveDecimal( - cutoff, "tenantAuthorityGeneration", "tenantBillingCutoff entry"); - requirePositiveDecimal(cutoff, "tenantBillingSequence", "tenantBillingCutoff entry"); - requirePositiveDecimal(cutoff, "outboxSequence", "tenantBillingCutoff entry"); - requireExactText( - cutoff, - "outboxStreamKey", - EVENT_STREAM_PREFIX + "tenant/" + tenantId, - "tenantBillingCutoff entry"); - }); + .forEachRemaining(entry -> { + String tenantId = entry.getKey(); + requireUuidKey(tenantId, "authorityTuple.tenantBillingCutoff"); + if (!(entry.getValue() instanceof ObjectNode cutoff)) { + throw invalid("authorityTuple.tenantBillingCutoff." + tenantId, "must be an object"); + } + requireExactFields(cutoff, TENANT_CUTOFF_FIELDS, Set.of(), "tenantBillingCutoff entry"); + requirePositiveDecimal(cutoff, "tenantAuthorityGeneration", "tenantBillingCutoff entry"); + requirePositiveDecimal(cutoff, "tenantBillingSequence", "tenantBillingCutoff entry"); + requirePositiveDecimal(cutoff, "outboxSequence", "tenantBillingCutoff entry"); + requireExactText( + cutoff, + "outboxStreamKey", + EVENT_STREAM_PREFIX + "tenant/" + tenantId, + "tenantBillingCutoff entry"); + }); } private static MembershipEvent toEvidence(ObjectNode wire, String digest, String canonicalJson) { @@ -398,17 +391,16 @@ private static MembershipEvent toEvidence(ObjectNode wire, String digest, String tupleNode .get("tenantBillingCutoff") .fields() - .forEachRemaining( - entry -> { - JsonNode cutoff = entry.getValue(); - values.put( - entry.getKey(), - new TenantBillingCutoff( - cutoff.get("tenantAuthorityGeneration").textValue(), - cutoff.get("tenantBillingSequence").textValue(), - cutoff.get("outboxStreamKey").textValue(), - cutoff.get("outboxSequence").textValue())); - }); + .forEachRemaining(entry -> { + JsonNode cutoff = entry.getValue(); + values.put( + entry.getKey(), + new TenantBillingCutoff( + cutoff.get("tenantAuthorityGeneration").textValue(), + cutoff.get("tenantBillingSequence").textValue(), + cutoff.get("outboxStreamKey").textValue(), + cutoff.get("outboxSequence").textValue())); + }); tenantCutoffs = Optional.of(immutableMap(values)); } @@ -488,12 +480,11 @@ private static void requireExactFields( } object .fieldNames() - .forEachRemaining( - field -> { - if (!required.contains(field) && !optional.contains(field)) { - throw invalid(path + "." + field, "is not declared by this schema"); - } - }); + .forEachRemaining(field -> { + if (!required.contains(field) && !optional.contains(field)) { + throw invalid(path + "." + field, "is not declared by this schema"); + } + }); } private static String requireExactText( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java index 50d0df5684..cac03c100c 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidator.java @@ -626,41 +626,38 @@ private static void requireTupleShape( requireSupportedPrivateRealmGrantVersions(tuple, path); tuple .tenantBillingCutoff() - .ifPresent( - cutoffs -> { - MembershipAuthorityEventV1Codec.TenantBillingCutoff cutoff = - exactTenantCutoff(cutoffs, tenantId, path + ".tenantBillingCutoff"); - requirePositiveDecimal( - cutoff.tenantAuthorityGeneration(), - path + ".tenantBillingCutoff.tenantAuthorityGeneration"); - requirePositiveDecimal( - cutoff.tenantBillingSequence(), - path + ".tenantBillingCutoff.tenantBillingSequence"); - requireEquals( - EVENT_STREAM_PREFIX + "tenant/" + tenantId, - cutoff.outboxStreamKey(), - path + ".tenantBillingCutoff.outboxStreamKey"); - requirePositiveDecimal( - cutoff.outboxSequence(), path + ".tenantBillingCutoff.outboxSequence"); - }); + .ifPresent(cutoffs -> { + MembershipAuthorityEventV1Codec.TenantBillingCutoff cutoff = + exactTenantCutoff(cutoffs, tenantId, path + ".tenantBillingCutoff"); + requirePositiveDecimal( + cutoff.tenantAuthorityGeneration(), + path + ".tenantBillingCutoff.tenantAuthorityGeneration"); + requirePositiveDecimal( + cutoff.tenantBillingSequence(), path + ".tenantBillingCutoff.tenantBillingSequence"); + requireEquals( + EVENT_STREAM_PREFIX + "tenant/" + tenantId, + cutoff.outboxStreamKey(), + path + ".tenantBillingCutoff.outboxStreamKey"); + requirePositiveDecimal( + cutoff.outboxSequence(), path + ".tenantBillingCutoff.outboxSequence"); + }); tuple .accountSecurityCutoff() - .ifPresent( - cutoff -> { - requirePositiveDecimal( - cutoff.accountAuthorityGeneration(), - path + ".accountSecurityCutoff.accountAuthorityGeneration"); - requireEquals( - EVENT_STREAM_PREFIX + "account/" + accountId, - cutoff.outboxStreamKey(), - path + ".accountSecurityCutoff.outboxStreamKey"); - requirePositiveDecimal( - cutoff.outboxSequence(), path + ".accountSecurityCutoff.outboxSequence"); - requireEquals( - tuple.accountAuthorityGeneration(), - cutoff.accountAuthorityGeneration(), - path + ".accountSecurityCutoff.accountAuthorityGeneration"); - }); + .ifPresent(cutoff -> { + requirePositiveDecimal( + cutoff.accountAuthorityGeneration(), + path + ".accountSecurityCutoff.accountAuthorityGeneration"); + requireEquals( + EVENT_STREAM_PREFIX + "account/" + accountId, + cutoff.outboxStreamKey(), + path + ".accountSecurityCutoff.outboxStreamKey"); + requirePositiveDecimal( + cutoff.outboxSequence(), path + ".accountSecurityCutoff.outboxSequence"); + requireEquals( + tuple.accountAuthorityGeneration(), + cutoff.accountAuthorityGeneration(), + path + ".accountSecurityCutoff.accountAuthorityGeneration"); + }); } private static MembershipAuthorityEventV1Codec.TenantBillingCutoff exactTenantCutoff( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java index dd88e9fdcd..d13e80eabb 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidence.java @@ -141,10 +141,9 @@ public static RuntimePlayerAdmissionEntitlementEvidence fromOwnerEvaluation( requireUuid(requestId.toString()); var peer = GrpcPeerIdentity.parseUri(callerWorkload) - .filter( - value -> - value.uri().equals(callerWorkload) - && "game-session-service".equals(value.service())) + .filter(value -> + value.uri().equals(callerWorkload) + && "game-session-service".equals(value.service())) .orElseThrow(() -> invalid("Exact Game Session caller required")); if (verifiedConnectScopeTokenHash == null || !verifiedConnectScopeTokenHash.matches("sha256:[0-9a-f]{64}")) @@ -229,21 +228,19 @@ public static RuntimePlayerAdmissionEntitlementEvidence fromOwnerEvaluation( fields.put( "outboxCheckpoints", membership.checkpoints().stream() - .map( - checkpoint -> { - Map entry = new LinkedHashMap<>(); - entry.put("outboxStreamKey", checkpoint.outboxStreamKey()); - entry.put("outboxSequence", checkpoint.outboxSequence()); - membership.sourceEvidence().stream() - .filter(event -> event.outboxStreamKey().equals(checkpoint.outboxStreamKey())) - .findFirst() - .ifPresent( - event -> { - entry.put("sourceEventId", event.eventId()); - entry.put("sourceEventDigest", event.eventDigest()); - }); - return entry; - }) + .map(checkpoint -> { + Map entry = new LinkedHashMap<>(); + entry.put("outboxStreamKey", checkpoint.outboxStreamKey()); + entry.put("outboxSequence", checkpoint.outboxSequence()); + membership.sourceEvidence().stream() + .filter(event -> event.outboxStreamKey().equals(checkpoint.outboxStreamKey())) + .findFirst() + .ifPresent(event -> { + entry.put("sourceEventId", event.eventId()); + entry.put("sourceEventDigest", event.eventDigest()); + }); + return entry; + }) .toList()); fields.put("authoritySourceEvidence", membership.sourceEvidence()); fields.put("sourceReferences", source); @@ -304,10 +301,9 @@ public static RuntimePlayerAdmissionEntitlementEvidence parseCanonical(byte[] by "privateRealmGrantVersions"); if (!authority.keySet().containsAll(requiredTuple) || authority.keySet().stream() - .anyMatch( - k -> - !requiredTuple.contains(k) - && !Set.of("accountSecurityCutoff", "tenantBillingCutoff").contains(k)) + .anyMatch(k -> + !requiredTuple.contains(k) + && !Set.of("accountSecurityCutoff", "tenantBillingCutoff").contains(k)) || !list(authority.get("privateRealmGrantVersions")).isEmpty()) throw invalid("Closed public authority tuple required"); Optional accountCutoff = @@ -325,23 +321,22 @@ public static RuntimePlayerAdmissionEntitlementEvidence parseCanonical(byte[] by Map tenantCutoffs = new LinkedHashMap<>(); object(authority.get("tenantBillingCutoff")) - .forEach( - (tenant, raw) -> { - var cutoff = object(raw); - exact( - cutoff, - Set.of( - "tenantAuthorityGeneration", - "tenantBillingSequence", - "outboxStreamKey", - "outboxSequence")); - tenantCutoffs.put( - tenant, - new MembershipAuthorityEventV1Codec.TenantBillingCutoff( - text(cutoff.get("tenantAuthorityGeneration")), - text(cutoff.get("tenantBillingSequence")), - text(cutoff.get("outboxStreamKey")), text(cutoff.get("outboxSequence")))); - }); + .forEach((tenant, raw) -> { + var cutoff = object(raw); + exact( + cutoff, + Set.of( + "tenantAuthorityGeneration", + "tenantBillingSequence", + "outboxStreamKey", + "outboxSequence")); + tenantCutoffs.put( + tenant, + new MembershipAuthorityEventV1Codec.TenantBillingCutoff( + text(cutoff.get("tenantAuthorityGeneration")), + text(cutoff.get("tenantBillingSequence")), + text(cutoff.get("outboxStreamKey")), text(cutoff.get("outboxSequence")))); + }); var tuple = new MembershipAuthorityEventV1Codec.AuthorityTuple( text(authority.get("issuerAuthGeneration")), @@ -353,35 +348,32 @@ public static RuntimePlayerAdmissionEntitlementEvidence parseCanonical(byte[] by Optional.of(tenantCutoffs)); var checkpoints = list(fields.get("outboxCheckpoints")).stream() - .map( - raw -> { - var checkpoint = object(raw); - String stream = text(checkpoint.get("outboxStreamKey")); - String sequence = text(checkpoint.get("outboxSequence")); - return new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint( - stream, sequence); - }) + .map(raw -> { + var checkpoint = object(raw); + String stream = text(checkpoint.get("outboxStreamKey")); + String sequence = text(checkpoint.get("outboxSequence")); + return new RuntimeMembershipAuthorityEvidenceValidator.Checkpoint(stream, sequence); + }) .toList(); var events = list(fields.get("authoritySourceEvidence")).stream() - .map( - raw -> { - var event = object(raw); - exact( - event, - Set.of( - "outboxStreamKey", - "outboxSequence", - "eventId", - "eventDigest", - "canonicalEventJson")); - return new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( - text(event.get("outboxStreamKey")), - text(event.get("outboxSequence")), - text(event.get("eventId")), - text(event.get("eventDigest")), - text(event.get("canonicalEventJson"))); - }) + .map(raw -> { + var event = object(raw); + exact( + event, + Set.of( + "outboxStreamKey", + "outboxSequence", + "eventId", + "eventDigest", + "canonicalEventJson")); + return new RuntimeMembershipAuthorityEvidenceValidator.SourceEvidence( + text(event.get("outboxStreamKey")), + text(event.get("outboxSequence")), + text(event.get("eventId")), + text(event.get("eventDigest")), + text(event.get("canonicalEventJson"))); + }) .toList(); Snapshot membership = new Snapshot( @@ -494,11 +486,10 @@ private static void validateFacts(Map facts, Snapshot membership throw invalid("Complete quotas required"); quotas .values() - .forEach( - value -> { - if (!text(value).matches("0|[1-9][0-9]{0,18}") || Long.parseLong(text(value)) < 0) - throw invalid("Nonnegative quota required"); - }); + .forEach(value -> { + if (!text(value).matches("0|[1-9][0-9]{0,18}") || Long.parseLong(text(value)) < 0) + throw invalid("Nonnegative quota required"); + }); } private static Map tuple(Snapshot membership) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidence.java index fdbe2d3000..84edda01ff 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementEvidence.java @@ -263,11 +263,10 @@ private static byte[] canonicalize(Map fields) { private static Map object(Object value, String field) { if (!(value instanceof Map supplied)) throw invalid(field + " must be an object"); Map result = new LinkedHashMap<>(); - supplied.forEach( - (key, item) -> { - if (!(key instanceof String name)) throw invalid(field + " contains a non-text key"); - result.put(name, item); - }); + supplied.forEach((key, item) -> { + if (!(key instanceof String name)) throw invalid(field + " contains a non-text key"); + result.put(name, item); + }); return result; } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/TenantAuthorityEventV1Codec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/TenantAuthorityEventV1Codec.java index 5303c8b541..be4ff174d8 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/TenantAuthorityEventV1Codec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/TenantAuthorityEventV1Codec.java @@ -326,14 +326,12 @@ private static Map object(Object value, String field) { throw new IllegalArgumentException("Tenant authority event " + field + " is not an object"); } Map result = new LinkedHashMap<>(); - raw.forEach( - (key, fieldValue) -> { - if (!(key instanceof String textKey)) { - throw new IllegalArgumentException( - "Tenant authority event " + field + " has a bad key"); - } - result.put(textKey, fieldValue); - }); + raw.forEach((key, fieldValue) -> { + if (!(key instanceof String textKey)) { + throw new IllegalArgumentException("Tenant authority event " + field + " has a bad key"); + } + result.put(textKey, fieldValue); + }); return result; } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java index 2632939b7d..79f345925b 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/capacity/OriginalNewCapacityExecution.java @@ -65,11 +65,10 @@ public byte[] canonicalBytes() { "canonicalAttemptPayload", Base64.getEncoder().encodeToString(CapacityAdmissionDigest.preimage(request))); StringBuilder json = new StringBuilder("{"); - fields.forEach( - (name, value) -> { - if (json.length() > 1) json.append(','); - json.append('"').append(name).append("\":\"").append(value).append('"'); - }); + fields.forEach((name, value) -> { + if (json.length() > 1) json.append(','); + json.append('"').append(name).append("\":\"").append(value).append('"'); + }); try { return Rfc8785CanonicalJson.canonicalizeUtf8(json.append('}').toString()); } catch (java.io.IOException malformed) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputs.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputs.java index d90e70a218..82239679a6 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputs.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputs.java @@ -132,10 +132,9 @@ private static TemplateConfigOwnerSourceInventoryDeclaration requireOwnerDeclara return snapshot.ownerSourceInventoryDeclarations().stream() .filter(declaration -> declaration.owner() == owner) .findFirst() - .orElseThrow( - () -> - new IllegalArgumentException( - "Selected template config has no declaration for the authorized owner")); + .orElseThrow(() -> + new IllegalArgumentException( + "Selected template config has no declaration for the authorized owner")); } private static void requireNoOwnerTemplateReferences( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidence.java index c038a6b8aa..62f3f1a362 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidence.java @@ -257,12 +257,11 @@ static List canonicalSourceVector(List sourceEvi } List sources = sourceEvidenceVector.stream() - .map( - source -> { - Objects.requireNonNull(source, "sourceEvidenceVector child is required"); - byte[] exactBytes = source.canonicalBytes(); - return SourceEvidence.fromStored(exactBytes); - }) + .map(source -> { + Objects.requireNonNull(source, "sourceEvidenceVector child is required"); + byte[] exactBytes = source.canonicalBytes(); + return SourceEvidence.fromStored(exactBytes); + }) .sorted(Comparator.comparing(SourceEvidence::key)) .toList(); if (sources.stream().map(SourceEvidence::key).distinct().count() != sources.size()) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadEvidence.java index f6671fdad3..a06ac49427 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadEvidence.java @@ -11,22 +11,20 @@ public record GameDesignDraftTerminalReadEvidence( public GameDesignDraftTerminalReadEvidence { Objects.requireNonNull(request, "request"); ownerReadback = Objects.requireNonNull(ownerReadback, "ownerReadback"); - ownerReadback.ifPresent( - value -> { - if (value.owner() != DraftAuthorizationFenceBinding.Owner.GAME_DESIGN - || (value.outcome() != DraftAuthorizationFenceBinding.Outcome.COMMITTED - && value.outcome() - != DraftAuthorizationFenceBinding.Outcome.DEFINITIVELY_ABORTED)) { - throw new IllegalArgumentException( - "Game Design readback must be a committed or definitive-abort owner result"); - } - value.requireBinding(request.accountBinding()); - if (!Arrays.equals(value.fullBinding(), request.originalAccountBinding()) - || value.result().length == 0) { - throw new IllegalArgumentException( - "Game Design readback differs from the original binding or lacks result bytes"); - } - }); + ownerReadback.ifPresent(value -> { + if (value.owner() != DraftAuthorizationFenceBinding.Owner.GAME_DESIGN + || (value.outcome() != DraftAuthorizationFenceBinding.Outcome.COMMITTED + && value.outcome() != DraftAuthorizationFenceBinding.Outcome.DEFINITIVELY_ABORTED)) { + throw new IllegalArgumentException( + "Game Design readback must be a committed or definitive-abort owner result"); + } + value.requireBinding(request.accountBinding()); + if (!Arrays.equals(value.fullBinding(), request.originalAccountBinding()) + || value.result().length == 0) { + throw new IllegalArgumentException( + "Game Design readback differs from the original binding or lacks result bytes"); + } + }); } /** The canonical original Account binding and a separate fresh caller-owned read identity. */ diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java index 19d24a9de5..6b31469576 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadEvidence.java @@ -13,31 +13,29 @@ public record WorldDraftTerminalReadEvidence( public WorldDraftTerminalReadEvidence { Objects.requireNonNull(request, "request"); ownerReadback = Objects.requireNonNull(ownerReadback, "ownerReadback"); - ownerReadback.ifPresent( - value -> { - if (value.owner() != DraftAuthorizationFenceBinding.Owner.WORLD - || (value.outcome() != DraftAuthorizationFenceBinding.Outcome.DEFINITIVELY_ABORTED - && value.outcome() != DraftAuthorizationFenceBinding.Outcome.COMMITTED)) { - throw new IllegalArgumentException("World readback must be an exact terminal outcome"); - } - DraftAuthorizationFenceBinding binding = request.accountBinding(); - value.requireBinding(binding); - if (!Arrays.equals(value.fullBinding(), request.originalAccountBinding())) { - throw new IllegalArgumentException("World readback differs from the original binding"); - } - if (value.outcome() == DraftAuthorizationFenceBinding.Outcome.COMMITTED) { - WorldDraftTerminalReadGrpcCodec.requireCommittedResult(request, value); - } - }); + ownerReadback.ifPresent(value -> { + if (value.owner() != DraftAuthorizationFenceBinding.Owner.WORLD + || (value.outcome() != DraftAuthorizationFenceBinding.Outcome.DEFINITIVELY_ABORTED + && value.outcome() != DraftAuthorizationFenceBinding.Outcome.COMMITTED)) { + throw new IllegalArgumentException("World readback must be an exact terminal outcome"); + } + DraftAuthorizationFenceBinding binding = request.accountBinding(); + value.requireBinding(binding); + if (!Arrays.equals(value.fullBinding(), request.originalAccountBinding())) { + throw new IllegalArgumentException("World readback differs from the original binding"); + } + if (value.outcome() == DraftAuthorizationFenceBinding.Outcome.COMMITTED) { + WorldDraftTerminalReadGrpcCodec.requireCommittedResult(request, value); + } + }); } /** Returns the intake request identity from this validated committed World APPLIED result. */ public UUID appliedIntakeRequestId() { DraftAuthorizationFenceBinding.OwnerReadback readback = - ownerReadback.orElseThrow( - () -> - new IllegalStateException( - "World APPLIED intake request requires a committed terminal readback")); + ownerReadback.orElseThrow(() -> + new IllegalStateException( + "World APPLIED intake request requires a committed terminal readback")); if (readback.outcome() != DraftAuthorizationFenceBinding.Outcome.COMMITTED) { throw new IllegalStateException( "World APPLIED intake request requires a committed terminal readback"); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyEvidence.java index 59925b1cf1..051e08029a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyEvidence.java @@ -112,15 +112,14 @@ public List appliedEpochs() { return draftBinding(request.accountBinding()) .affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT) .stream() - .map( - unit -> - new AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .map(unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) .toList(); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalog.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalog.java index 34affb2a44..3cc10ea792 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalog.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalog.java @@ -278,10 +278,9 @@ public static AutomationRuntimeFamilyCatalog fromStored(byte[] bytes) { } RuntimeFamilyCatalogValidation.requireComplete( families.stream() - .map( - family -> - new RuntimeFamilyCatalogValidation.FamilyComponent( - family.relation(), family.component())) + .map(family -> + new RuntimeFamilyCatalogValidation.FamilyComponent( + family.relation(), family.component())) .toList(), structuralFacts); array(root.get("nonSqlGaps"), MAX_NON_SQL_GAPS); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalog.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalog.java index 4b78eb3013..5d2d0e0b77 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalog.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalog.java @@ -268,10 +268,9 @@ public static EntityRuntimeFamilyCatalog fromStored(byte[] bytes) { } RuntimeFamilyCatalogValidation.requireComplete( families.stream() - .map( - family -> - new RuntimeFamilyCatalogValidation.FamilyComponent( - family.relation(), family.component())) + .map(family -> + new RuntimeFamilyCatalogValidation.FamilyComponent( + family.relation(), family.component())) .toList(), structuralFacts); return new EntityRuntimeFamilyCatalog(epoch, families, facts, bytes); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadGrpcCodec.java index 0c439f8c8f..68fea8e64e 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadGrpcCodec.java @@ -106,11 +106,10 @@ public static ReadResult fromResponse( var descriptor = descriptorOutcome.descriptor(); List projections = response.getProjectionsList().stream() - .map( - projection -> - AuthoredInitialActorCoreProjection.fromStored( - projection.getCanonicalProjectionBytes().toByteArray(), - projection.getProjectionDigest())) + .map(projection -> + AuthoredInitialActorCoreProjection.fromStored( + projection.getCanonicalProjectionBytes().toByteArray(), + projection.getProjectionDigest())) .toList(); ReadResult result = new ReadResult(expectedRequest, associationRead, descriptor, projections); byte[] canonical = response.getCanonicalResultBytes().toByteArray(); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBinding.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBinding.java index 3162346168..2da5d19e78 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBinding.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBinding.java @@ -170,10 +170,9 @@ public static List resolveAll( List authoredActorPolicies = policySnapshot.policies().stream() .filter(value -> value.policy().worldSlug().equals(expectedWorldSlug)) - .filter( - value -> - value.policy().schemaVersion() - == RealmEntryPolicy.AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION) + .filter(value -> + value.policy().schemaVersion() + == RealmEntryPolicy.AUTHORED_INITIAL_ACTOR_CORE_SCHEMA_VERSION) .toList(); if (authoredActorPolicies.isEmpty()) { return List.of(); @@ -189,49 +188,46 @@ public static List resolveAll( List result = authoredActorPolicies.stream() - .map( - policy -> { - AuthoredInitialActorCore core = policy.policy().initialActorCore(); - List dispositions = - gameplayEntries.stream() - .filter(value -> value.family() == Family.DISPOSITIONS) - .filter(value -> value.definition().key().equals(core.dispositionKey())) - .toList(); - if (dispositions.size() != 1 - || !(dispositions.getFirst().definition() - instanceof Disposition disposition)) { - throw new IllegalArgumentException( - "Selected authored disposition is absent or ambiguous"); - } - List feedbackEntries = - gameplayEntries.stream() - .filter(value -> value.family() == Family.FEEDBACK) - .filter( - value -> - value.definition().key().equals(disposition.safeFeedbackKey())) - .toList(); - if (feedbackEntries.size() != 1 - || !(feedbackEntries.getFirst().definition() instanceof Feedback feedback)) { - throw new IllegalArgumentException( - "Disposition safeFeedbackKey is absent or ambiguous"); - } - return new AuthoredInitialActorCoreSourceBinding( - worldSourceOperationId, - worldSourceEvidenceDigest, - expectedWorldSlug, - publicationWorkflowId, - publicationOperationBytes, - publicationTerminalEvidenceBytes, - selectedCommit, - policySnapshotBytes, - policy, - gameplaySnapshotBytes, - manifest, - dispositions.getFirst(), - disposition, - feedbackEntries.getFirst(), - feedback); - }) + .map(policy -> { + AuthoredInitialActorCore core = policy.policy().initialActorCore(); + List dispositions = + gameplayEntries.stream() + .filter(value -> value.family() == Family.DISPOSITIONS) + .filter(value -> value.definition().key().equals(core.dispositionKey())) + .toList(); + if (dispositions.size() != 1 + || !(dispositions.getFirst().definition() instanceof Disposition disposition)) { + throw new IllegalArgumentException( + "Selected authored disposition is absent or ambiguous"); + } + List feedbackEntries = + gameplayEntries.stream() + .filter(value -> value.family() == Family.FEEDBACK) + .filter( + value -> value.definition().key().equals(disposition.safeFeedbackKey())) + .toList(); + if (feedbackEntries.size() != 1 + || !(feedbackEntries.getFirst().definition() instanceof Feedback feedback)) { + throw new IllegalArgumentException( + "Disposition safeFeedbackKey is absent or ambiguous"); + } + return new AuthoredInitialActorCoreSourceBinding( + worldSourceOperationId, + worldSourceEvidenceDigest, + expectedWorldSlug, + publicationWorkflowId, + publicationOperationBytes, + publicationTerminalEvidenceBytes, + selectedCommit, + policySnapshotBytes, + policy, + gameplaySnapshotBytes, + manifest, + dispositions.getFirst(), + disposition, + feedbackEntries.getFirst(), + feedback); + }) .toList(); return List.copyOf(result); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameplayRuleSource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameplayRuleSource.java index f21b6ecb50..bdfc97317f 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameplayRuleSource.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameplayRuleSource.java @@ -46,10 +46,9 @@ public record Mutation( .filter(value -> value.revisionId().equals(revisionId)) .filter(value -> value.revisionOrder().equals(revisionOrder)) .findFirst() - .orElseThrow( - () -> - new IllegalArgumentException( - "Rule mutation does not match an original Game Design revision")); + .orElseThrow(() -> + new IllegalArgumentException( + "Rule mutation does not match an original Game Design revision")); String expected; if (operation == OperationKind.UPSERT) { Objects.requireNonNull(definition); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidence.java index 3c0f67ecbd..ac9c4f72cb 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidence.java @@ -247,18 +247,17 @@ public static String computePolicySetDigest( policies.stream().collect(java.util.stream.Collectors.toMap(Policy::source, p -> p)); var orderedEvidence = ordered.stream() - .map( - source -> { - Policy policy = bySource.get(source); - return Map.of( - "policyId", policy.policyId().toString(), - "sourceCommitId", source.commitId().toString(), - "sourceRevisionId", source.revisionId().toString(), - "logicalRevisionId", source.logicalRevisionId(), - "worldSlug", source.policy().worldSlug(), - "realmSlug", source.policy().realmSlug(), - "policyDigest", policy.policyDigest()); - }) + .map(source -> { + Policy policy = bySource.get(source); + return Map.of( + "policyId", policy.policyId().toString(), + "sourceCommitId", source.commitId().toString(), + "sourceRevisionId", source.revisionId().toString(), + "logicalRevisionId", source.logicalRevisionId(), + "worldSlug", source.policy().worldSlug(), + "realmSlug", source.policy().realmSlug(), + "policyDigest", policy.policyDigest()); + }) .toList(); String evidence = RealmPolicySource.canonical( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidenceCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidenceCodec.java index 8f739ea559..d75dc5d2d6 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidenceCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicyPublishedEvidenceCodec.java @@ -169,17 +169,16 @@ private static String canonicalPayload(RealmPolicyPublishedEvidence.PublishedSet "sourceProvenanceKind", target.sourceProvenanceKind()); var policies = evidence.policies().stream() - .map( - policy -> - map( - "policyId", policy.policyId().toString(), - "source", - map( - "commitId", policy.source().commitId().toString(), - "revisionId", policy.source().revisionId().toString(), - "logicalRevisionId", policy.source().logicalRevisionId(), - "canonicalPolicyJson", policy.source().policy().canonicalJson()), - "policyDigest", policy.policyDigest())) + .map(policy -> + map( + "policyId", policy.policyId().toString(), + "source", + map( + "commitId", policy.source().commitId().toString(), + "revisionId", policy.source().revisionId().toString(), + "logicalRevisionId", policy.source().logicalRevisionId(), + "canonicalPolicyJson", policy.source().policy().canonicalJson()), + "policyDigest", policy.policyDigest())) .toList(); return RealmPolicySource.canonical( map( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySource.java index d304157186..8066020b8c 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySource.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/RealmPolicySource.java @@ -121,17 +121,16 @@ public static List draftOrdered(List policies) { static String policiesJson(List policies) { return canonical( draftOrdered(policies).stream() - .map( - policy -> - Map.of( - "commitId", - policy.commitId().toString(), - "revisionId", - policy.revisionId().toString(), - "logicalRevisionId", - policy.logicalRevisionId(), - "policy", - tree(policy.policy().canonicalJson()))) + .map(policy -> + Map.of( + "commitId", + policy.commitId().toString(), + "revisionId", + policy.revisionId().toString(), + "logicalRevisionId", + policy.logicalRevisionId(), + "policy", + tree(policy.policy().canonicalJson()))) .toList()); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadEvidence.java index c350bc6a44..b188cfab05 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadEvidence.java @@ -322,30 +322,28 @@ public static GameDesignPublicationTerminalEvidence.ReleaseContent releaseConten } List artifacts = bundle.getArtifactDigestsList().stream() - .map( - value -> - new AuthoredWorldReleaseAttestationEvidence.Artifact( - value.getUsageKey(), - value.getArtifactKind(), - value.getImmutableObjectKey(), - value.getContentDigest(), - value.getContentType(), - value.getArtifactSchemaVersion())) + .map(value -> + new AuthoredWorldReleaseAttestationEvidence.Artifact( + value.getUsageKey(), + value.getArtifactKind(), + value.getImmutableObjectKey(), + value.getContentDigest(), + value.getContentType(), + value.getArtifactSchemaVersion())) .toList(); List participants = bundle.getParticipantDigestsList().stream() - .map( - value -> - new GameDesignPublicationTerminalEvidence.Participant( - value.getParticipantKey(), - value.getScopeValue(), - null, - value.getAppliedCommitId(), - value.getContentDigest(), - value.getDigestSchemaVersion(), - value.hasAbilitySchemaDigest() ? value.getAbilitySchemaDigest() : null, - null, - null)) + .map(value -> + new GameDesignPublicationTerminalEvidence.Participant( + value.getParticipantKey(), + value.getScopeValue(), + null, + value.getAppliedCommitId(), + value.getContentDigest(), + value.getDigestSchemaVersion(), + value.hasAbilitySchemaDigest() ? value.getAbilitySchemaDigest() : null, + null, + null)) .toList(); return new GameDesignPublicationTerminalEvidence.ReleaseContent( UUID.fromString(bundle.getCanonicalTenantId()), diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationEvidence.java index 8d43cfc7ff..147bb59574 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationEvidence.java @@ -74,17 +74,15 @@ public record Result( Objects.requireNonNull(outcome); sourceScope = Objects.requireNonNull(sourceScope); authorization = Objects.requireNonNull(authorization); - sourceScope.ifPresent( - scope -> { - if (!request.targetNamespace().equals(scope.targetNamespace()) - || !request.intakeRequestId().equals(scope.intakeRequestId()) - || !request.selected().equals(scope.selected())) throw invalid(); - }); - authorization.ifPresent( - binding -> { - if (!request.intakeRequestId().equals(binding.intakeRequestId()) - || !request.selected().equals(binding.source().binding())) throw invalid(); - }); + sourceScope.ifPresent(scope -> { + if (!request.targetNamespace().equals(scope.targetNamespace()) + || !request.intakeRequestId().equals(scope.intakeRequestId()) + || !request.selected().equals(scope.selected())) throw invalid(); + }); + authorization.ifPresent(binding -> { + if (!request.intakeRequestId().equals(binding.intakeRequestId()) + || !request.selected().equals(binding.source().binding())) throw invalid(); + }); if (sourceScope.isPresent() && authorization.isPresent()) { var scope = sourceScope.orElseThrow(); var binding = authorization.orElseThrow(); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodec.java index d9592f5e85..f0ed784bed 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodec.java @@ -60,15 +60,12 @@ public static GameLogicIntakeAuthorizationResponse toResponse( .setOutcome(toWire(result.outcome())); result .sourceScope() - .ifPresent( - scope -> - builder.setPreliminarySourceScope(ByteString.copyFrom(scope.canonicalBytes()))); + .ifPresent(scope -> + builder.setPreliminarySourceScope(ByteString.copyFrom(scope.canonicalBytes()))); result .authorization() - .ifPresent( - binding -> - builder.setFinalizedIntakeAuthorization( - ByteString.copyFrom(binding.canonicalBytes()))); + .ifPresent(binding -> + builder.setFinalizedIntakeAuthorization(ByteString.copyFrom(binding.canonicalBytes()))); var response = builder.build(); requireWireSize(response.getSerializedSize()); return response; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadEvidence.java index f039ee5405..3bd9b63011 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadEvidence.java @@ -13,14 +13,12 @@ public record GameLogicIntakeTerminalReadEvidence( public GameLogicIntakeTerminalReadEvidence { Objects.requireNonNull(request); Objects.requireNonNull(terminal); - terminal.ifPresent( - value -> { - var expected = - new GameLogicGameplayRuleIntakeOperation( - request.targetNamespace(), request.binding()); - if (!Arrays.equals(expected.canonicalBytes(), value.operation().canonicalBytes())) - throw new IllegalArgumentException("Terminal differs from exact original intake"); - }); + terminal.ifPresent(value -> { + var expected = + new GameLogicGameplayRuleIntakeOperation(request.targetNamespace(), request.binding()); + if (!Arrays.equals(expected.canonicalBytes(), value.operation().canonicalBytes())) + throw new IllegalArgumentException("Terminal differs from exact original intake"); + }); } public record Request( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjection.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjection.java index be45aefd79..7f88a635cb 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjection.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjection.java @@ -46,9 +46,8 @@ public static String canonicalJson(GameplayRuleManifest source) { Map definitions = new HashMap<>(); complete .families() - .forEach( - (family, values) -> - values.forEach(value -> definitions.put(new Key(family, value.key()), value))); + .forEach((family, values) -> + values.forEach(value -> definitions.put(new Key(family, value.key()), value))); var pending = new ArrayDeque(); for (Family root : List.of(Family.ABILITIES, Family.ACTIONS)) complete.families().get(root).forEach(value -> pending.add(new Key(root, value.key()))); @@ -63,13 +62,12 @@ public static String canonicalJson(GameplayRuleManifest source) { Map> retained = new EnumMap<>(Family.class); complete .families() - .forEach( - (family, values) -> - retained.put( - family, - values.stream() - .filter(value -> visited.contains(new Key(family, value.key()))) - .toList())); + .forEach((family, values) -> + retained.put( + family, + values.stream() + .filter(value -> visited.contains(new Key(family, value.key()))) + .toList())); // Closure must itself remain a complete, valid inventory; do not repair missing edges with // defaults. var projection = new GameplayRuleManifest(retained); @@ -173,12 +171,11 @@ private static void dependencies( case SelectionPolicy value -> value .comparators() - .forEach( - comparator -> { - if (comparator.statField() == StatField.MAXIMUM) - add(pending, Family.RESOURCES, comparator.statKey()); - else numeric(pending, definitions, comparator.statKey()); - }); + .forEach(comparator -> { + if (comparator.statField() == StatField.MAXIMUM) + add(pending, Family.RESOURCES, comparator.statKey()); + else numeric(pending, definitions, comparator.statKey()); + }); case DefaultBinding value -> targets(pending, value.targetSets()); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleManifest.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleManifest.java index 82b803d7d4..1b85ad19e3 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleManifest.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleManifest.java @@ -855,14 +855,13 @@ public List arguments() { Objects.requireNonNull(families, "Explicit complete family inventory required"); if (!families.keySet().equals(Set.of(Family.values()))) fail("Missing/unknown rule family"); EnumMap> retained = new EnumMap<>(Family.class); - families.forEach( - (family, definitions) -> { - List values = copy(definitions); - unique(values.stream().map(Definition::key).toList()); - for (Definition definition : values) - if (definition.family() != family) fail("Definition belongs to another family"); - retained.put(family, values); - }); + families.forEach((family, definitions) -> { + List values = copy(definitions); + unique(values.stream().map(Definition::key).toList()); + for (Definition definition : values) + if (definition.family() != family) fail("Definition belongs to another family"); + retained.put(family, values); + }); families = java.util.Collections.unmodifiableMap(retained); validateReferences(families); } @@ -939,9 +938,8 @@ public static Definition definition(Family family, String json) { private static void validateReferences(Map> families) { Map> keys = new EnumMap<>(Family.class); - families.forEach( - (family, values) -> - keys.put(family, Set.copyOf(values.stream().map(Definition::key).toList()))); + families.forEach((family, values) -> + keys.put(family, Set.copyOf(values.stream().map(Definition::key).toList()))); Set stats = new HashSet<>(keys.get(Family.STATS)); for (String resource : keys.get(Family.RESOURCES)) if (!stats.add(resource)) fail("Resource/stat key collision"); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSource.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSource.java index 1a6e1514c5..c8885580f3 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSource.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamelogic/GameplayRuleSelectedSource.java @@ -103,14 +103,13 @@ private static List parseEntries( String expectedPayload = GameplayRuleSourceRevision.upsertPayload(definition); boolean originalRevision = origin.revisions().stream() - .anyMatch( - revision -> - revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE - && revision.revisionId().toString().equals(revisionId) - && revision.revisionOrder().equals(revisionOrder) - && expectedPayload.equals( - GameplayRuleManifest.canonical( - GameplayRuleManifest.tree(revision.payload())))); + .anyMatch(revision -> + revision.owner() == DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE + && revision.revisionId().toString().equals(revisionId) + && revision.revisionOrder().equals(revisionOrder) + && expectedPayload.equals( + GameplayRuleManifest.canonical( + GameplayRuleManifest.tree(revision.payload())))); if (!originalRevision) throw new IllegalArgumentException("Rule entry lacks exact original UPSERT revision"); result.add( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CurrentPrivatePlaytestLifecycleReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CurrentPrivatePlaytestLifecycleReadEvidence.java index 3a229615c7..7ee56f28e1 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CurrentPrivatePlaytestLifecycleReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/CurrentPrivatePlaytestLifecycleReadEvidence.java @@ -112,12 +112,11 @@ public record Evidence( public Evidence { Objects.requireNonNull(request, "request"); current = Objects.requireNonNull(current, "current"); - current.ifPresent( - snapshot -> { - if (!request.scope().equals(snapshot.scope())) { - throw new IllegalArgumentException("Current snapshot target differs from request"); - } - }); + current.ifPresent(snapshot -> { + if (!request.scope().equals(snapshot.scope())) { + throw new IllegalArgumentException("Current snapshot target differs from request"); + } + }); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GameSessionRuntimeFamilyCatalogCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GameSessionRuntimeFamilyCatalogCodec.java index 32261abf56..4a8c3b15c0 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GameSessionRuntimeFamilyCatalogCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamesession/GameSessionRuntimeFamilyCatalogCodec.java @@ -24,12 +24,11 @@ private GameSessionRuntimeFamilyCatalogCodec() {} public static byte[] requestBytes(Request request) { Objects.requireNonNull(request, "request"); - return encode( - out -> { - out.writeInt(REQUEST_V1); - uuid(out, request.readRequestId()); - bytes(out, request.targetNamespace().getBytes(StandardCharsets.US_ASCII)); - }); + return encode(out -> { + out.writeInt(REQUEST_V1); + uuid(out, request.readRequestId()); + bytes(out, request.targetNamespace().getBytes(StandardCharsets.US_ASCII)); + }); } public static Request requestFromStored(byte[] bytes) { @@ -48,14 +47,13 @@ public static Request requestFromStored(byte[] bytes) { public static byte[] evidenceBytes(Evidence evidence) { Objects.requireNonNull(evidence, "evidence"); byte[] result = - encode( - out -> { - out.writeInt(EVIDENCE_V1); - bytes(out, requestBytes(evidence.request())); - uuid(out, evidence.snapshotId()); - bytes(out, evidence.catalog().digest().getBytes(StandardCharsets.US_ASCII)); - bytes(out, evidence.catalog().exactBytes()); - }); + encode(out -> { + out.writeInt(EVIDENCE_V1); + bytes(out, requestBytes(evidence.request())); + uuid(out, evidence.snapshotId()); + bytes(out, evidence.catalog().digest().getBytes(StandardCharsets.US_ASCII)); + bytes(out, evidence.catalog().exactBytes()); + }); if (result.length > MAX_EVIDENCE_BYTES) throw new IllegalArgumentException("Oversized complete catalog evidence"); return result; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptor.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptor.java index fa607c7c60..e328b29f81 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptor.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptor.java @@ -62,9 +62,8 @@ private boolean requireVerifiedPeer() { && (expectedLeafSha256 == null || GrpcPeerCertificateEvidence.fromSslSession( call.getAttributes().get(Grpc.TRANSPORT_ATTR_SSL_SESSION)) - .filter( - certificate -> - expectedLeafSha256.equals(certificate.leafSha256())) + .filter(certificate -> + expectedLeafSha256.equals(certificate.leafSha256())) .isPresent()); if (!verified) { closed = true; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/TlsCertificateWatcher.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/TlsCertificateWatcher.java index 6896cff904..464f685482 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/TlsCertificateWatcher.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/TlsCertificateWatcher.java @@ -101,16 +101,12 @@ public TlsCertificateWatcher(List files, Runnable onChange) throws IOExcep } allRequiredRegistrationsValid.set(allRequiredDirectoriesRegistered()); retryExecutor = - Executors.newSingleThreadScheduledExecutor( - runnable -> { - Thread retryThread = - Thread.ofPlatform() - .daemon(true) - .name("tls-cert-reload-retry") - .unstarted(runnable); - retryExecutorThread.set(retryThread); - return retryThread; - }); + Executors.newSingleThreadScheduledExecutor(runnable -> { + Thread retryThread = + Thread.ofPlatform().daemon(true).name("tls-cert-reload-retry").unstarted(runnable); + retryExecutorThread.set(retryThread); + return retryThread; + }); thread = new Thread(this::processEvents, "tls-cert-watcher"); thread.setDaemon(true); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java index 7b8446dc58..ad9e04d957 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundle.java @@ -438,34 +438,32 @@ private static void validateTenantBillingCutoffs(Map cutoffs) { if (cutoffs.size() > 1) { throw denied("StartSession bundle must not widen tenant billing scope"); } - cutoffs.forEach( - (tenantId, raw) -> { - uuid(tenantId, "tenantBillingCutoff tenant ID"); - Map cutoff = object(raw, "tenantBillingCutoff entry"); - requireFields( - cutoff, - Set.of( - "tenantAuthorityGeneration", - "tenantBillingSequence", - "outboxStreamKey", - "outboxSequence"), - "tenantBillingCutoff entry"); - positiveNumber(cutoff.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); - positiveNumber(cutoff.get("tenantBillingSequence"), "tenantBillingSequence"); - boundedText(cutoff.get("outboxStreamKey"), "outboxStreamKey", 256); - positiveNumber(cutoff.get("outboxSequence"), "outboxSequence"); - }); + cutoffs.forEach((tenantId, raw) -> { + uuid(tenantId, "tenantBillingCutoff tenant ID"); + Map cutoff = object(raw, "tenantBillingCutoff entry"); + requireFields( + cutoff, + Set.of( + "tenantAuthorityGeneration", + "tenantBillingSequence", + "outboxStreamKey", + "outboxSequence"), + "tenantBillingCutoff entry"); + positiveNumber(cutoff.get("tenantAuthorityGeneration"), "tenantAuthorityGeneration"); + positiveNumber(cutoff.get("tenantBillingSequence"), "tenantBillingSequence"); + boundedText(cutoff.get("outboxStreamKey"), "outboxStreamKey", 256); + positiveNumber(cutoff.get("outboxSequence"), "outboxSequence"); + }); } private static void validateMembershipVersion(Map membership) { if (membership.size() > 1) { throw denied("StartSession bundle must not widen membership scope"); } - membership.forEach( - (tenantId, version) -> { - uuid(tenantId, "membershipVersion tenant ID"); - positiveNumber(version, "membershipVersion"); - }); + membership.forEach((tenantId, version) -> { + uuid(tenantId, "membershipVersion tenant ID"); + positiveNumber(version, "membershipVersion"); + }); } private static void validateTenantHumanEvidence(Map evidence) { @@ -499,11 +497,10 @@ private static void mapOfPositiveNumbers(Object raw, String field) { if (values.size() > 1) { throw denied(field + " must be limited to the selected tenant"); } - values.forEach( - (key, value) -> { - uuid(key, field + " tenant ID"); - positiveNumber(value, field); - }); + values.forEach((key, value) -> { + uuid(key, field + " tenant ID"); + positiveNumber(value, field); + }); } private static long positiveNumber(Object value, String field) { @@ -612,13 +609,12 @@ private static Map immutableObject(Map source) { private static Object immutableValue(Object value) { if (value instanceof Map map) { Map copy = new LinkedHashMap<>(); - map.forEach( - (key, nested) -> { - if (!(key instanceof String text)) { - throw denied("Object keys must be strings"); - } - copy.put(text, immutableValue(nested)); - }); + map.forEach((key, nested) -> { + if (!(key instanceof String text)) { + throw denied("Object keys must be strings"); + } + copy.put(text, immutableValue(nested)); + }); return Map.copyOf(copy); } if (value instanceof List list) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTuple.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTuple.java index fb7945a7df..0e7604ec35 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTuple.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTuple.java @@ -385,13 +385,12 @@ private static Map object(Object value, String field) { throw invalid(field + " must be an object"); } Map result = new LinkedHashMap<>(); - raw.forEach( - (key, member) -> { - if (!(key instanceof String text)) { - throw invalid(field + " has a non-string key"); - } - result.put(text, member); - }); + raw.forEach((key, member) -> { + if (!(key instanceof String text)) { + throw invalid(field + " has a non-string key"); + } + result.put(text, member); + }); return result; } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyReadGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyReadGrpcCodec.java index 5d05f0b6cb..34bf7f5fd4 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyReadGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyReadGrpcCodec.java @@ -209,10 +209,9 @@ private static void requireTarget( private static void requireSelector( PublishedRealmEntryPolicySetEvidence evidence, String worldSlug, String realmSlug) { if (evidence.policies().stream() - .noneMatch( - policy -> - policy.policy().worldSlug().equals(worldSlug) - && policy.policy().realmSlug().equals(realmSlug))) { + .noneMatch(policy -> + policy.policy().worldSlug().equals(worldSlug) + && policy.policy().realmSlug().equals(realmSlug))) { throw new IllegalArgumentException( "Published policy set does not contain the exact selector"); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java index 4a2a66354a..4726c67a4a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicySetEvidence.java @@ -390,18 +390,17 @@ public static String calculatePolicySetDigest( .toList(); List> orderedEvidence = orderedPolicies.stream() - .map( - policy -> { - Map row = new LinkedHashMap<>(); - row.put("policyId", policy.policyId().toString()); - row.put("sourceCommitId", policy.sourceCommitId().toString()); - row.put("sourceRevisionId", policy.sourceRevisionId().toString()); - row.put("logicalRevisionId", policy.logicalRevisionId()); - row.put("worldSlug", policy.policy().worldSlug()); - row.put("realmSlug", policy.policy().realmSlug()); - row.put("policyDigest", policy.policyDigest()); - return row; - }) + .map(policy -> { + Map row = new LinkedHashMap<>(); + row.put("policyId", policy.policyId().toString()); + row.put("sourceCommitId", policy.sourceCommitId().toString()); + row.put("sourceRevisionId", policy.sourceRevisionId().toString()); + row.put("logicalRevisionId", policy.logicalRevisionId()); + row.put("worldSlug", policy.policy().worldSlug()); + row.put("realmSlug", policy.policy().realmSlug()); + row.put("policyDigest", policy.policyDigest()); + return row; + }) .toList(); Map preimage = new LinkedHashMap<>(); preimage.put("schema", SET_DIGEST_SCHEMA); @@ -626,22 +625,21 @@ private Map toJsonObject() { root.put( "policies", policies.stream() - .map( - evidence -> { - Map row = new LinkedHashMap<>(); - row.put("policyId", evidence.policyId().toString()); - row.put("sourceCommitId", evidence.sourceCommitId().toString()); - row.put("sourceRevisionId", evidence.sourceRevisionId().toString()); - row.put("logicalRevisionId", evidence.logicalRevisionId()); - try { - row.put("policy", JSON.readTree(evidence.policy().canonicalJson())); - } catch (RuntimeException impossible) { - throw new IllegalStateException( - "Canonical realm policy became invalid", impossible); - } - row.put("policyDigest", evidence.policyDigest()); - return row; - }) + .map(evidence -> { + Map row = new LinkedHashMap<>(); + row.put("policyId", evidence.policyId().toString()); + row.put("sourceCommitId", evidence.sourceCommitId().toString()); + row.put("sourceRevisionId", evidence.sourceRevisionId().toString()); + row.put("logicalRevisionId", evidence.logicalRevisionId()); + try { + row.put("policy", JSON.readTree(evidence.policy().canonicalJson())); + } catch (RuntimeException impossible) { + throw new IllegalStateException( + "Canonical realm policy became invalid", impossible); + } + row.put("policyDigest", evidence.policyDigest()); + return row; + }) .toList()); return root; } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java index b682cb12c5..8ba17659b3 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryEvidence.java @@ -302,15 +302,14 @@ private static boolean appliedEpochsMatch( DraftCommitBinding selectedCommit, List actual) { List expected = selectedCommit.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .map(unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) .toList(); return !expected.isEmpty() && expected.equals(actual); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogFraming.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogFraming.java index 60846530b4..2b3a7381cc 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogFraming.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogFraming.java @@ -36,12 +36,11 @@ public RuntimeFamilyCatalogFraming( } public byte[] requestBytes(int magic, UUID requestId, String namespace) { - return encode( - out -> { - out.writeInt(magic); - uuid(out, requestId); - bytes(out, namespace.getBytes(StandardCharsets.US_ASCII)); - }); + return encode(out -> { + out.writeInt(magic); + uuid(out, requestId); + bytes(out, namespace.getBytes(StandardCharsets.US_ASCII)); + }); } public RequestFrame readRequest( @@ -64,14 +63,13 @@ public byte[] evidenceBytes( byte[] catalog, String oversizedMessage) { byte[] result = - encode( - out -> { - out.writeInt(magic); - bytes(out, request); - uuid(out, snapshotId); - bytes(out, digest.getBytes(StandardCharsets.US_ASCII)); - bytes(out, catalog); - }); + encode(out -> { + out.writeInt(magic); + bytes(out, request); + uuid(out, snapshotId); + bytes(out, digest.getBytes(StandardCharsets.US_ASCII)); + bytes(out, catalog); + }); if (result.length > maximumResponseBytes) throw new IllegalArgumentException(oversizedMessage); return result; } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalog.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalog.java index b9fce906e4..b35cddc8d6 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalog.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalog.java @@ -276,10 +276,9 @@ public static SocialRuntimeFamilyCatalog fromStored(byte[] bytes) { } RuntimeFamilyCatalogValidation.requireComplete( families.stream() - .map( - family -> - new RuntimeFamilyCatalogValidation.FamilyComponent( - family.relation(), family.component())) + .map(family -> + new RuntimeFamilyCatalogValidation.FamilyComponent( + family.relation(), family.component())) .toList(), structuralFacts); array(root.get("unimplementedContracts"), ContractGap.values().length); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/web/ReactiveRequestLoggingFilter.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/web/ReactiveRequestLoggingFilter.java index 5549ec26c5..10f0d72a48 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/web/ReactiveRequestLoggingFilter.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/web/ReactiveRequestLoggingFilter.java @@ -47,21 +47,20 @@ public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { return chain .filter(exchange) - .doFinally( - signalType -> { - long duration = System.currentTimeMillis() - start; - var statusCode = exchange.getResponse().getStatusCode(); - logger.info( - "HTTP request completed method={} path={} status={} durationMs={} service={} serviceInstanceId={} correlationId={} traceId={}", - request.getMethod(), - request.getPath().value(), - statusCode != null ? statusCode.value() : 200, - duration, - runtimeIdentity.service(), - runtimeIdentity.serviceInstanceId(), - correlationId, - valueOrUnknown(traceId)); - }); + .doFinally(signalType -> { + long duration = System.currentTimeMillis() - start; + var statusCode = exchange.getResponse().getStatusCode(); + logger.info( + "HTTP request completed method={} path={} status={} durationMs={} service={} serviceInstanceId={} correlationId={} traceId={}", + request.getMethod(), + request.getPath().value(), + statusCode != null ? statusCode.value() : 200, + duration, + runtimeIdentity.service(), + runtimeIdentity.serviceInstanceId(), + correlationId, + valueOrUnknown(traceId)); + }); } private static String resolveCorrelationId(String incoming) { diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java index 905932f518..86ce9b5845 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidence.java @@ -51,10 +51,9 @@ public record CanonicalGameplayRosterOwnerReadEvidence( public PublishedRealmEntryPolicyEvidence selectedPolicyEvidence() { return publishedPolicySetEvidence.policies().stream() - .filter( - evidence -> - evidence.policy().worldSlug().equals(request.worldSlug()) - && evidence.policy().realmSlug().equals(request.realmSlug())) + .filter(evidence -> + evidence.policy().worldSlug().equals(request.worldSlug()) + && evidence.policy().realmSlug().equals(request.realmSlug())) .findFirst() .orElseThrow(() -> new IllegalStateException("Exact published policy is unavailable")); } @@ -90,10 +89,9 @@ private static void requirePolicyMatches( } List matches = evidence.policies().stream() - .filter( - policy -> - policy.policy().worldSlug().equals(request.worldSlug()) - && policy.policy().realmSlug().equals(request.realmSlug())) + .filter(policy -> + policy.policy().worldSlug().equals(request.worldSlug()) + && policy.policy().realmSlug().equals(request.realmSlug())) .toList(); if (matches.size() != 1) { throw new IllegalArgumentException( diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java index dc4e77bde3..9fb0e29e9a 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidence.java @@ -330,21 +330,20 @@ private static Map parseOperationalRegionAssignments(JsonNode node) } Map assignments = new LinkedHashMap<>(); node.propertyNames() - .forEach( - canonicalRegionId -> { - JsonNode operationalRegion = node.get(canonicalRegionId); - if (operationalRegion == null || !operationalRegion.isTextual()) { - throw new IllegalArgumentException( - "operationalRegionAssignments values must be canonical UUID strings"); - } - UUID canonical = parseUuid(canonicalRegionId, "operationalRegionAssignments key"); - UUID operational = - parseUuid(operationalRegion.textValue(), "operationalRegionAssignments value"); - if (assignments.putIfAbsent(canonical, operational) != null) { - throw new IllegalArgumentException( - "operationalRegionAssignments contains duplicate canonical region identities"); - } - }); + .forEach(canonicalRegionId -> { + JsonNode operationalRegion = node.get(canonicalRegionId); + if (operationalRegion == null || !operationalRegion.isTextual()) { + throw new IllegalArgumentException( + "operationalRegionAssignments values must be canonical UUID strings"); + } + UUID canonical = parseUuid(canonicalRegionId, "operationalRegionAssignments key"); + UUID operational = + parseUuid(operationalRegion.textValue(), "operationalRegionAssignments value"); + if (assignments.putIfAbsent(canonical, operational) != null) { + throw new IllegalArgumentException( + "operationalRegionAssignments contains duplicate canonical region identities"); + } + }); return immutableOperationalRegionAssignments(assignments); } @@ -354,29 +353,27 @@ private static Map immutableOperationalRegionAssignments( if (assignments.isEmpty()) { throw new IllegalArgumentException("operationalRegionAssignments must be nonempty"); } - assignments.forEach( - (canonical, operational) -> { - requireNonNil(canonical, "operationalRegionAssignments canonical region ID"); - requireNonNil(operational, "operationalRegionAssignments operational region ID"); - }); + assignments.forEach((canonical, operational) -> { + requireNonNil(canonical, "operationalRegionAssignments canonical region ID"); + requireNonNil(operational, "operationalRegionAssignments operational region ID"); + }); Map ordered = new LinkedHashMap<>(); Set operationalIdentities = new HashSet<>(); assignments.entrySet().stream() .sorted((left, right) -> left.getKey().toString().compareTo(right.getKey().toString())) - .forEach( - entry -> { - UUID canonical = entry.getKey(); - UUID operational = entry.getValue(); - if (canonical.equals(operational)) { - throw new IllegalArgumentException( - "Canonical and operational region identities must be distinct"); - } - if (!operationalIdentities.add(operational)) { - throw new IllegalArgumentException( - "operationalRegionAssignments contains duplicate operational region identities"); - } - ordered.put(canonical, operational); - }); + .forEach(entry -> { + UUID canonical = entry.getKey(); + UUID operational = entry.getValue(); + if (canonical.equals(operational)) { + throw new IllegalArgumentException( + "Canonical and operational region identities must be distinct"); + } + if (!operationalIdentities.add(operational)) { + throw new IllegalArgumentException( + "operationalRegionAssignments contains duplicate operational region identities"); + } + ordered.put(canonical, operational); + }); return Collections.unmodifiableMap(ordered); } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java index c203eea267..6c647fee97 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationEvidence.java @@ -181,15 +181,14 @@ private static void requireRelation( } List boundTuples = draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) + .map(unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) .sorted( Comparator.comparing(OwnedAffectedTuple::owner) .thenComparing(OwnedAffectedTuple::aggregateType) @@ -325,17 +324,16 @@ private static Map requestJson(Request request) { value.put( "worldAffectedTuples", request.worldAffectedTuples().stream() - .map( - tuple -> { - Map item = new LinkedHashMap<>(); - item.put("owner", tuple.owner()); - item.put("aggregateType", tuple.aggregateType()); - item.put("aggregateId", tuple.aggregateId()); - item.put("scopeType", tuple.scopeType()); - item.put("scopeId", tuple.scopeId()); - item.put("expectedEpoch", tuple.expectedEpoch()); - return item; - }) + .map(tuple -> { + Map item = new LinkedHashMap<>(); + item.put("owner", tuple.owner()); + item.put("aggregateType", tuple.aggregateType()); + item.put("aggregateId", tuple.aggregateId()); + item.put("scopeType", tuple.scopeType()); + item.put("scopeId", tuple.scopeId()); + item.put("expectedEpoch", tuple.expectedEpoch()); + return item; + }) .toList()); return value; } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalog.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalog.java index 1332a17c4d..e8d64700e3 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalog.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalog.java @@ -225,10 +225,9 @@ public static WorldRuntimeFamilyCatalog fromStored(byte[] bytes) { } RuntimeFamilyCatalogValidation.requireComplete( families.stream() - .map( - family -> - new RuntimeFamilyCatalogValidation.FamilyComponent( - family.relation(), family.component())) + .map(family -> + new RuntimeFamilyCatalogValidation.FamilyComponent( + family.relation(), family.component())) .toList(), structuralFacts); return new WorldRuntimeFamilyCatalog(epoch, families, facts, bytes); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/AccountActorStagingEligibilityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/AccountActorStagingEligibilityEvidenceTest.java index 52ffc3f2df..b8772e40b8 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/AccountActorStagingEligibilityEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/AccountActorStagingEligibilityEvidenceTest.java @@ -57,60 +57,58 @@ void authorityAndDecisionDigestsBindDifferentRequestEvidence() { void rejectsTamperedAuthorityAndNonpositiveMembershipVersion() { AccountActorStagingEligibilityEvidence evidence = seal("ACTIVE", "ACTIVE", true, REQUEST_ID); - assertThatThrownBy( - () -> - new AccountActorStagingEligibilityEvidence( - evidence.schemaVersion(), - evidence.targetNamespace(), - evidence.requestId(), - evidence.canonicalAccountId(), - evidence.canonicalTenantId(), - evidence.purpose(), - evidence.currentness(), - evidence.observedAt(), - evidence.decision(), - evidence.accountUuidProvenance(), - evidence.accountLifecycleState(), - evidence.membershipLifecycleState(), - evidence.gameplayAdmissionAllowed(), - evidence.membershipAuthorityProvenance(), - evidence.membershipVersion() + 1L, - evidence.membershipAuthorityGeneration(), - evidence.tenantProvenanceKind(), - evidence.tenantSourceOperationId(), - evidence.tenantProvenanceDigest(), - evidence.membershipEventSequence(), - evidence.membershipEventId(), - evidence.membershipEventDigest(), - evidence.lastTransitionInvalidated(), - evidence.eligibilityDecisionDigest(), - evidence.authoritySnapshotDigest())) + assertThatThrownBy(() -> + new AccountActorStagingEligibilityEvidence( + evidence.schemaVersion(), + evidence.targetNamespace(), + evidence.requestId(), + evidence.canonicalAccountId(), + evidence.canonicalTenantId(), + evidence.purpose(), + evidence.currentness(), + evidence.observedAt(), + evidence.decision(), + evidence.accountUuidProvenance(), + evidence.accountLifecycleState(), + evidence.membershipLifecycleState(), + evidence.gameplayAdmissionAllowed(), + evidence.membershipAuthorityProvenance(), + evidence.membershipVersion() + 1L, + evidence.membershipAuthorityGeneration(), + evidence.tenantProvenanceKind(), + evidence.tenantSourceOperationId(), + evidence.tenantProvenanceDigest(), + evidence.membershipEventSequence(), + evidence.membershipEventId(), + evidence.membershipEventDigest(), + evidence.lastTransitionInvalidated(), + evidence.eligibilityDecisionDigest(), + evidence.authoritySnapshotDigest())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Authority snapshot digest does not match its fields"); - assertThatThrownBy( - () -> - AccountActorStagingEligibilityEvidence.seal( - NAMESPACE, - REQUEST_ID, - ACCOUNT_ID, - TENANT_ID, - AccountActorStagingEligibilityEvidence.Purpose.PUBLIC_PRODUCTION_STAGING_ONLY, - OBSERVED_AT, - "ACCOUNT_V29_MIGRATION", - "ACTIVE", - "ACTIVE", - true, - "EXPLICIT_JOIN", - 0L, - 1L, - "FRESH_GAME_DESIGN", - TENANT_OPERATION_ID, - "sha256:" + "a".repeat(64), - 1L, - MEMBERSHIP_EVENT_ID, - "sha256:" + "b".repeat(64), - false)) + assertThatThrownBy(() -> + AccountActorStagingEligibilityEvidence.seal( + NAMESPACE, + REQUEST_ID, + ACCOUNT_ID, + TENANT_ID, + AccountActorStagingEligibilityEvidence.Purpose.PUBLIC_PRODUCTION_STAGING_ONLY, + OBSERVED_AT, + "ACCOUNT_V29_MIGRATION", + "ACTIVE", + "ACTIVE", + true, + "EXPLICIT_JOIN", + 0L, + 1L, + "FRESH_GAME_DESIGN", + TENANT_OPERATION_ID, + "sha256:" + "a".repeat(64), + 1L, + MEMBERSHIP_EVENT_ID, + "sha256:" + "b".repeat(64), + false)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Positive membership authority counters are required"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidenceTest.java index aab060d32a..736f9723dc 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/RuntimeAccountIdentityEvidenceTest.java @@ -84,15 +84,14 @@ private static void assertInvalid( UUID canonicalAccountId, long sourceAccountRowId, String provenance) { - assertThatThrownBy( - () -> - new RuntimeAccountIdentityEvidence( - schemaVersion, - targetNamespace, - requestId, - canonicalAccountId, - sourceAccountRowId, - provenance)) + assertThatThrownBy(() -> + new RuntimeAccountIdentityEvidence( + schemaVersion, + targetNamespace, + requestId, + canonicalAccountId, + sourceAccountRowId, + provenance)) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java index a5baa0d795..e25d3786ba 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/StartSessionRedeemedOperationProjectionClientTest.java @@ -218,10 +218,9 @@ void boundedDeadlineLeavesTransportUncertaintyAndDoesNotRetry() throws Exception assertThatThrownBy(() -> client.read(fixture.postTuple(), OWNER_ATTEMPT_ID, OWNER_FENCE)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + .satisfies(failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); assertThat(applicationCalls).hasValue(1); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountFreshEnrollmentAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountFreshEnrollmentAuthorityEventV1CodecTest.java index e2f60faae5..3faf212503 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountFreshEnrollmentAuthorityEventV1CodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountFreshEnrollmentAuthorityEventV1CodecTest.java @@ -45,10 +45,9 @@ private static void assertRestrictionRoundTrip(String category, String state, St } private static void assertRestrictionRejected(String category, String state, String sourceKind) { - assertThatThrownBy( - () -> - AccountSecurityStateAuthorityEventV1Codec.sealRestriction( - preimage(category, state, sourceKind))) + assertThatThrownBy(() -> + AccountSecurityStateAuthorityEventV1Codec.sealRestriction( + preimage(category, state, sourceKind))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java index f668dadd08..5521b555f3 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java @@ -160,21 +160,19 @@ void restrictionVariantIsClosedAndKeepsCategoryOwnerAndClearanceIndependent() { assertThat(verifiedBan.restriction()).isPresent(); assertThat(verifiedLock.securityState()).isEmpty(); assertThat(verifiedBan.securityState()).isEmpty(); - assertThatThrownBy( - () -> - AccountSecurityStateAuthorityEventV1Codec.sealRestriction( - restrictionPreimage( - "platform_access_ban", "NONRESTRICTED", "ACCOUNT_SECURITY_RECOVERY"))) + assertThatThrownBy(() -> + AccountSecurityStateAuthorityEventV1Codec.sealRestriction( + restrictionPreimage( + "platform_access_ban", "NONRESTRICTED", "ACCOUNT_SECURITY_RECOVERY"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("restrictionSourceKind"); } @Test void familyDispatchRejectsUnknownVariantAndRestrictionExtraFields() { - assertThatThrownBy( - () -> - AccountSecurityStateAuthorityEventV1Codec.verifyFamily( - "{\"eventType\":\"ACCOUNT_AUTHORITY_CHANGED\"}")) + assertThatThrownBy(() -> + AccountSecurityStateAuthorityEventV1Codec.verifyFamily( + "{\"eventType\":\"ACCOUNT_AUTHORITY_CHANGED\"}")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("variant is unsupported"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java index ce55464658..1f50b93525 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorTest.java @@ -122,10 +122,9 @@ void missingMembershipStillRequiresItsPositiveCurrentAccountSource() { baseline.checkpoints().get(3)), List.of(baseline.sourceEvidence().getFirst())); assertThat(RuntimeMembershipAuthorityEvidenceValidator.validate(missing)).isEmpty(); - assertThatThrownBy( - () -> - RuntimeMembershipAuthorityEvidenceValidator.validate( - copyWith(missing, missing.checkpoints(), List.of()))) + assertThatThrownBy(() -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWith(missing, missing.checkpoints(), List.of()))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("one source for each positive checkpoint"); } @@ -154,10 +153,9 @@ void resealedHistoricalMembershipCannotLeadIssuerAccountFenceOrAccountCutoff() t // The supplied event is freshly sealed and valid independently of current carrier authority. assertThat(MembershipAuthorityEventV1Codec.verify(event.canonicalJson()).eventDigest()) .isEqualTo(event.eventDigest()); - assertThatThrownBy( - () -> - RuntimeMembershipAuthorityEvidenceValidator.validate( - copyWithMembershipSource(baseline, event))) + assertThatThrownBy(() -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWithMembershipSource(baseline, event))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("must not be ahead"); } @@ -377,10 +375,9 @@ void rejectsLowerAndHigherUnequalOpaqueTenantGenerationsWithoutOrdering() { for (String unequalGeneration : List.of("1", "3")) { MembershipEvent membership = membershipEvent(ACCOUNT_ID, TENANT_ID, unequalGeneration, cutoff); - assertThatThrownBy( - () -> - RuntimeMembershipAuthorityEvidenceValidator.validate( - copyWithMembershipSource(valid, membership))) + assertThatThrownBy(() -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWithMembershipSource(valid, membership))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("membership source tenantAuthorityGeneration current equality"); } @@ -407,10 +404,9 @@ void validatesCurrentBillingCutoffAgainstTheExactTenantSourceAndCheckpoint() { goodTuple.accountSecurityCutoff(), Optional.of(Map.of(TENANT_ID, wrongCutoff))); - assertThatThrownBy( - () -> - RuntimeMembershipAuthorityEvidenceValidator.validate( - copyWithTenantTuple(valid, tupleWithWrongCutoff))) + assertThatThrownBy(() -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWithTenantTuple(valid, tupleWithWrongCutoff))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("current tenant cutoff billing sequence"); } @@ -429,10 +425,9 @@ void rejectsDifferentSameGenerationHistoricalBillingCutoff() { MembershipEvent membership = membershipEvent(ACCOUNT_ID, TENANT_ID, "2", differentHistoricalCutoff); - assertThatThrownBy( - () -> - RuntimeMembershipAuthorityEvidenceValidator.validate( - copyWithMembershipSource(valid, membership))) + assertThatThrownBy(() -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWithMembershipSource(valid, membership))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("membership source tenantBillingCutoff current exact equality"); } @@ -450,10 +445,9 @@ void rejectsStaleCrossTenantAndMismatchedCheckpointTenantSourceEvidence() { valid.authorityTuple().privateRealmGrantVersions(), valid.authorityTuple().accountSecurityCutoff(), valid.authorityTuple().tenantBillingCutoff()); - assertThatThrownBy( - () -> - RuntimeMembershipAuthorityEvidenceValidator.validate( - copyWithTenantSource(valid, staleTuple, "1", valid.sourceEvidence().get(2)))) + assertThatThrownBy(() -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWithTenantSource(valid, staleTuple, "1", valid.sourceEvidence().get(2)))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("current tenant authority generation"); @@ -465,18 +459,16 @@ void rejectsStaleCrossTenantAndMismatchedCheckpointTenantSourceEvidence() { otherTenantEvent.eventId().toString(), otherTenantEvent.eventDigest(), new String(otherTenantEvent.payload(), java.nio.charset.StandardCharsets.UTF_8)); - assertThatThrownBy( - () -> - RuntimeMembershipAuthorityEvidenceValidator.validate( - copyWithTenantSource(valid, valid.authorityTuple(), "1", crossTenantCarrier))) + assertThatThrownBy(() -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWithTenantSource(valid, valid.authorityTuple(), "1", crossTenantCarrier))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("source event stream key"); - assertThatThrownBy( - () -> - RuntimeMembershipAuthorityEvidenceValidator.validate( - copyWithTenantSource( - valid, valid.authorityTuple(), "2", valid.sourceEvidence().get(2)))) + assertThatThrownBy(() -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWithTenantSource( + valid, valid.authorityTuple(), "2", valid.sourceEvidence().get(2)))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("sourceEvidence sequence must equal its exact current checkpoint"); } @@ -503,31 +495,27 @@ void rejectsCrossTenantFreshSourceAndBillingReceiptReferencesAtCodecBoundary() { TenantAuthorityEventV1Codec.tenantBillingEventId(requestId), "sha256:" + "6".repeat(64)); - assertThatThrownBy( - () -> - TenantAuthorityEventV1Codec.seal( - authorityRequest, source, 2L, 2L, 1L, billingReceipt)) + assertThatThrownBy(() -> + TenantAuthorityEventV1Codec.seal(authorityRequest, source, 2L, 2L, 1L, billingReceipt)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("billing request"); var otherTenantSource = tenantCreationEvidence(UUID.fromString(OTHER_TENANT_ID)); - assertThatThrownBy( - () -> - TenantAuthorityEventV1Codec.seal( - authorityRequest, - otherTenantSource, - 2L, - 2L, + assertThatThrownBy(() -> + TenantAuthorityEventV1Codec.seal( + authorityRequest, + otherTenantSource, + 2L, + 2L, + 1L, + new TenantAuthorityEventV1Codec.BillingReceipt( + UUID.fromString(TENANT_ID), + requestId, + requestDigest, + TenantAuthorityEventV1Codec.tenantBillingStreamKey(UUID.fromString(TENANT_ID)), 1L, - new TenantAuthorityEventV1Codec.BillingReceipt( - UUID.fromString(TENANT_ID), - requestId, - requestDigest, - TenantAuthorityEventV1Codec.tenantBillingStreamKey( - UUID.fromString(TENANT_ID)), - 1L, - TenantAuthorityEventV1Codec.tenantBillingEventId(requestId), - "sha256:" + "6".repeat(64)))) + TenantAuthorityEventV1Codec.tenantBillingEventId(requestId), + "sha256:" + "6".repeat(64)))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact source"); } @@ -545,13 +533,12 @@ void deniesMismatchedSourceScopeOriginalCarrierDigestAndMembershipVersion() { currentAccount.eventId(), "sha256:" + "0".repeat(64), currentAccount.canonicalJson()); - assertThatThrownBy( - () -> - RuntimeMembershipAuthorityEvidenceValidator.validate( - copyWith( - valid, - valid.checkpoints(), - List.of(forgedAccountCarrier, valid.sourceEvidence().get(1))))) + assertThatThrownBy(() -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWith( + valid, + valid.checkpoints(), + List.of(forgedAccountCarrier, valid.sourceEvidence().get(1))))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("source carrier eventDigest"); @@ -562,13 +549,12 @@ void deniesMismatchedSourceScopeOriginalCarrierDigestAndMembershipVersion() { currentAccount.eventId(), currentAccount.eventDigest(), " " + currentAccount.canonicalJson()); - assertThatThrownBy( - () -> - RuntimeMembershipAuthorityEvidenceValidator.validate( - copyWith( - valid, - valid.checkpoints(), - List.of(alteredCanonicalBytes, valid.sourceEvidence().get(1))))) + assertThatThrownBy(() -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWith( + valid, + valid.checkpoints(), + List.of(alteredCanonicalBytes, valid.sourceEvidence().get(1))))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("source carrier canonical event bytes"); @@ -580,13 +566,12 @@ void deniesMismatchedSourceScopeOriginalCarrierDigestAndMembershipVersion() { otherScope.eventId(), otherScope.eventDigest(), otherScope.canonicalJson()); - assertThatThrownBy( - () -> - RuntimeMembershipAuthorityEvidenceValidator.validate( - copyWith( - valid, - valid.checkpoints(), - List.of(valid.sourceEvidence().get(0), mismatchedScopeCarrier)))) + assertThatThrownBy(() -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWith( + valid, + valid.checkpoints(), + List.of(valid.sourceEvidence().get(0), mismatchedScopeCarrier)))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("source event stream key"); @@ -626,22 +611,19 @@ void preservesMalformedResetDigestDiagnosticWhenSecurityStateVerificationFails() accountSource.eventDigest(), malformedResetDigest); - assertThatThrownBy( - () -> - RuntimeMembershipAuthorityEvidenceValidator.validate( - copyWith( - valid, - valid.checkpoints(), - List.of(malformedSource, valid.sourceEvidence().get(1))))) + assertThatThrownBy(() -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWith( + valid, + valid.checkpoints(), + List.of(malformedSource, valid.sourceEvidence().get(1))))) .isInstanceOf(IllegalArgumentException.class) - .satisfies( - failure -> - assertThat(failure.getSuppressed()) - .anySatisfy( - diagnostic -> - assertThat(diagnostic.getMessage()) - .contains("eventDigest") - .contains("canonical event preimage"))); + .satisfies(failure -> + assertThat(failure.getSuppressed()) + .anySatisfy(diagnostic -> + assertThat(diagnostic.getMessage()) + .contains("eventDigest") + .contains("canonical event preimage"))); } @Test @@ -656,23 +638,21 @@ void reportsAccountSourceFailureWithEverySupportedDecoderDiagnostic() { accountSource.eventDigest(), "{\"unsupported\":true}"); - assertThatThrownBy( - () -> - RuntimeMembershipAuthorityEvidenceValidator.validate( - copyWith( - valid, - valid.checkpoints(), - List.of(malformedSource, valid.sourceEvidence().get(1))))) + assertThatThrownBy(() -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWith( + valid, + valid.checkpoints(), + List.of(malformedSource, valid.sourceEvidence().get(1))))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("account source") .hasMessageContaining("supported Account event schema") - .satisfies( - failure -> { - assertThat(failure.getSuppressed()).hasSize(4); - assertThat(failure.getSuppressed()) - .allSatisfy( - diagnostic -> assertThat(diagnostic.getMessage()).isNotNull().isNotBlank()); - }); + .satisfies(failure -> { + assertThat(failure.getSuppressed()).hasSize(4); + assertThat(failure.getSuppressed()) + .allSatisfy( + diagnostic -> assertThat(diagnostic.getMessage()).isNotNull().isNotBlank()); + }); } @Test @@ -681,20 +661,18 @@ void requiresSortedExactCheckpointAndSourceInventories() { List reversed = new ArrayList<>(valid.checkpoints()); java.util.Collections.reverse(reversed); - assertThatThrownBy( - () -> - RuntimeMembershipAuthorityEvidenceValidator.validate( - copyWith(valid, reversed, valid.sourceEvidence()))) + assertThatThrownBy(() -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWith(valid, reversed, valid.sourceEvidence()))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("sorted by stream key"); List duplicateSource = new ArrayList<>(valid.sourceEvidence()); duplicateSource.add(valid.sourceEvidence().get(0)); - assertThatThrownBy( - () -> - RuntimeMembershipAuthorityEvidenceValidator.validate( - copyWith(valid, valid.checkpoints(), duplicateSource))) + assertThatThrownBy(() -> + RuntimeMembershipAuthorityEvidenceValidator.validate( + copyWith(valid, valid.checkpoints(), duplicateSource))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("sourceEvidence"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java index 2ee2480c48..c82f0a3bc2 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimePlayerAdmissionEntitlementEvidenceTest.java @@ -94,10 +94,9 @@ void ownerEmissionRejectsOversizedRoleInventoryBeforeReturningEvidence() { original.issuanceFence(), original.checkpoints(), original.sourceEvidence()); - assertThatThrownBy( - () -> - RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( - REQUEST, PEER, SCOPE_HASH, oversized, target(), facts(), sources(), NOW)) + assertThatThrownBy(() -> + RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + REQUEST, PEER, SCOPE_HASH, oversized, target(), facts(), sources(), NOW)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Bounded list required"); } @@ -210,10 +209,9 @@ void legacyBearerBundleAndNewBundleWithRawFieldFailClosed() throws Exception { @Test void rawScopeCannotBeSuppliedAsTheVerifiedTokenHash() { - assertThatThrownBy( - () -> - RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( - REQUEST, PEER, SCOPE, membership(), target(), facts(), sources(), NOW)) + assertThatThrownBy(() -> + RuntimePlayerAdmissionEntitlementEvidence.fromOwnerEvaluation( + REQUEST, PEER, SCOPE, membership(), target(), facts(), sources(), NOW)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Verified connect scope token hash required"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodecTest.java index 05a52e836e..114b0752f4 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeTenantOperationEntitlementGrpcCodecTest.java @@ -60,10 +60,9 @@ void rejectsMissingDuplicateUnknownUnboundedAndNoncanonicalRequestMembers() thro byte[] duplicate = new byte[bytes.length * 2]; System.arraycopy(bytes, 0, duplicate, 0, bytes.length); System.arraycopy(bytes, 0, duplicate, bytes.length, bytes.length); - assertThatThrownBy( - () -> - RuntimeTenantOperationEntitlementGrpcCodec.parseRequest( - ReadTenantOperationEntitlementRequest.parseFrom(duplicate))) + assertThatThrownBy(() -> + RuntimeTenantOperationEntitlementGrpcCodec.parseRequest( + ReadTenantOperationEntitlementRequest.parseFrom(duplicate))) .isInstanceOf(IllegalArgumentException.class); } @@ -105,9 +104,8 @@ void rejectsResponseCardinalityUnknownFieldsBindingsAndBadCanonicalValue() { wire.toBuilder() .setRequest(0, RuntimeTenantOperationEntitlementGrpcCodec.toRequest(changed)) .build(); - assertThatThrownBy( - () -> - RuntimeTenantOperationEntitlementGrpcCodec.requireResponse(changed, substituted)) + assertThatThrownBy(() -> + RuntimeTenantOperationEntitlementGrpcCodec.requireResponse(changed, substituted)) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java index a8f6b0e863..afae186875 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/capacity/CapacityAdmissionDigestTest.java @@ -248,15 +248,14 @@ void nonCreatingEvidenceIsValidContentButCannotAuthorizeExecution() { TenantCapacityAdmission.State.RESERVED, denied.evidence().snapshotIdentity(), denied.evidence().evaluationIdentity()); - assertThatThrownBy( - () -> - new OriginalNewCapacityExecution( - denied, - reservation, - denied.identity().admissionId(), - "sha256:" + "a".repeat(64), - "owner-1", - 1)) + assertThatThrownBy(() -> + new OriginalNewCapacityExecution( + denied, + reservation, + denied.identity().admissionId(), + "sha256:" + "a".repeat(64), + "owner-1", + 1)) .isInstanceOf(IllegalArgumentException.class); for (Request invalid : @@ -316,15 +315,14 @@ void boundReleasedAndQuarantinedResultsCannotAuthorizeOriginalExecution() { request.evidence().snapshotIdentity(), request.evidence().evaluationIdentity()); reservation.requireBinding(request); - assertThatThrownBy( - () -> - new OriginalNewCapacityExecution( - request, - reservation, - request.identity().admissionId(), - "sha256:" + "a".repeat(64), - "owner-1", - 1)) + assertThatThrownBy(() -> + new OriginalNewCapacityExecution( + request, + reservation, + request.identity().admissionId(), + "sha256:" + "a".repeat(64), + "owner-1", + 1)) .as(state.name()) .isInstanceOf(IllegalArgumentException.class); } @@ -367,9 +365,8 @@ void evidenceIsStrictCanonicalAndCompleteChangedFieldsAlterDigest() { " " + json, json.replaceFirst("\"outboxSequence\":\"3\"", "\"outboxSequence\":\"4\""), "{\"bundleVersion\":\"1\"," + json.substring(1))) { - assertThatThrownBy( - () -> - Evidence.parse(changed.getBytes(StandardCharsets.UTF_8), Owner.WORLD_MANAGEMENT)) + assertThatThrownBy(() -> + Evidence.parse(changed.getBytes(StandardCharsets.UTF_8), Owner.WORLD_MANAGEMENT)) .isInstanceOf(IllegalArgumentException.class); } Evidence changed = diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClientTest.java index d263141833..85dc08115e 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeAuthorizationGrpcClientTest.java @@ -26,23 +26,20 @@ void requiresFileBackedWorkloadMtlsAndCanonicalNamespace() { var endpoints = new ServiceEndpointsProperties(); var plaintext = new CommonGrpcClientProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new AccountSelectedOwnerIntakeAuthorizationGrpcClient( - endpoints, plaintext, new GrpcChannelFactory(), "test")) + assertThatThrownBy(() -> + new AccountSelectedOwnerIntakeAuthorizationGrpcClient( + endpoints, plaintext, new GrpcChannelFactory(), "test")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountSelectedOwnerIntakeAuthorizationGrpcClient( - endpoints, new CommonGrpcClientProperties(), new GrpcChannelFactory(), "test")) + assertThatThrownBy(() -> + new AccountSelectedOwnerIntakeAuthorizationGrpcClient( + endpoints, new CommonGrpcClientProperties(), new GrpcChannelFactory(), "test")) .isInstanceOf(IllegalArgumentException.class); var properties = tlsFiles(); - assertThatThrownBy( - () -> - new AccountSelectedOwnerIntakeAuthorizationGrpcClient( - endpoints, properties, new GrpcChannelFactory(), "not/a/namespace")) + assertThatThrownBy(() -> + new AccountSelectedOwnerIntakeAuthorizationGrpcClient( + endpoints, properties, new GrpcChannelFactory(), "not/a/namespace")) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClientTest.java index 3217cdea5a..66b92e1cab 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClientTest.java @@ -27,22 +27,19 @@ void requiresFileBackedWorkloadMtlsAndCanonicalNamespace() { var endpoints = new ServiceEndpointsProperties(); var plaintext = new CommonGrpcClientProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( - endpoints, plaintext, new GrpcChannelFactory(), "test")) + assertThatThrownBy(() -> + new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( + endpoints, plaintext, new GrpcChannelFactory(), "test")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( - endpoints, new CommonGrpcClientProperties(), new GrpcChannelFactory(), "test")) + assertThatThrownBy(() -> + new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( + endpoints, new CommonGrpcClientProperties(), new GrpcChannelFactory(), "test")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( - endpoints, tlsFiles(), new GrpcChannelFactory(), "not/a/namespace")) + assertThatThrownBy(() -> + new AccountSelectedOwnerIntakeWorldClosureAuthorizationGrpcClient( + endpoints, tlsFiles(), new GrpcChannelFactory(), "not/a/namespace")) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java index 04d5a3f65a..9c31176e14 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerEmptySourceInputsTest.java @@ -146,42 +146,35 @@ void automationTerminalReadEchoesExactBindingAndRequiresCommittedEmptyReceipt() response.toBuilder() .setRequest(requestWire.toBuilder().setReadRequestId(UUID.randomUUID().toString())) .build(); - assertThatThrownBy( - () -> - AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( - request, changedEcho)) + assertThatThrownBy(() -> + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse(request, changedEcho)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setResult( - AutomationSelectedSourceIntakeTerminalResult - .AUTOMATION_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_UNSPECIFIED) - .build())) + assertThatThrownBy(() -> + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setResult( + AutomationSelectedSourceIntakeTerminalResult + .AUTOMATION_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_UNSPECIFIED) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( - request, response.toBuilder().clearCommittedEmptyReceipt().build())) + assertThatThrownBy(() -> + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, response.toBuilder().clearCommittedEmptyReceipt().build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( - request, - response.toBuilder().setReceiptDigest("sha256:" + "0".repeat(64)).build())) + assertThatThrownBy(() -> + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, response.toBuilder().setReceiptDigest("sha256:" + "0".repeat(64)).build())) .isInstanceOf(IllegalArgumentException.class); byte[] changedReceipt = response.getCommittedEmptyReceipt().toByteArray(); changedReceipt[changedReceipt.length - 1] ^= 1; - assertThatThrownBy( - () -> - AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setCommittedEmptyReceipt(ByteString.copyFrom(changedReceipt)) - .build())) + assertThatThrownBy(() -> + AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setCommittedEmptyReceipt(ByteString.copyFrom(changedReceipt)) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -358,11 +351,10 @@ void rejectsLegacyOrMissingWorldClosureAndEntitySpawnBindings() { Owner.ENTITY_MANAGEMENT, Options.defaults().withWorldProfile(WorldProfile.LEGACY_V1)); assertRejected(legacyWorld.authorization(), legacyWorld.worldInventoryReadEvidence()); - assertThatThrownBy( - () -> - fixture( - Owner.ENTITY_MANAGEMENT, - Options.defaults().withWorldProfile(WorldProfile.MISSING_CLOSURE_V2))) + assertThatThrownBy(() -> + fixture( + Owner.ENTITY_MANAGEMENT, + Options.defaults().withWorldProfile(WorldProfile.MISSING_CLOSURE_V2))) .isInstanceOf(IllegalArgumentException.class); Fixture entitySpawn = fixture(Owner.ENTITY_MANAGEMENT, Options.defaults().withSpawnBindings(1)); @@ -695,15 +687,14 @@ private static PublicEvidence publicInventory( 0, spawnBindings, selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .map(unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) .toList(), closure); var ownerScope = diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java index f761a805df..8c9d556885 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationBindingTest.java @@ -170,26 +170,23 @@ void rejectsActorMismatchAndSourceEvidenceForAnotherActorOrTenant() { UUID otherActor = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"); UUID otherTenant = id("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); - assertThatThrownBy( - () -> - new SelectedOwnerIntakeAuthorizationBinding( - content(Owner.ENTITY_MANAGEMENT, otherActor), unsortedSources(ACTOR))) + assertThatThrownBy(() -> + new SelectedOwnerIntakeAuthorizationBinding( + content(Owner.ENTITY_MANAGEMENT, otherActor), unsortedSources(ACTOR))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new SelectedOwnerIntakeAuthorizationBinding( - original.content(), - List.of( - evidence(SourceKind.ACCOUNT, ACTOR.toString(), "changed"), - evidence(SourceKind.TENANT, otherTenant.toString(), "tenant")))) + assertThatThrownBy(() -> + new SelectedOwnerIntakeAuthorizationBinding( + original.content(), + List.of( + evidence(SourceKind.ACCOUNT, ACTOR.toString(), "changed"), + evidence(SourceKind.TENANT, otherTenant.toString(), "tenant")))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new SelectedOwnerIntakeAuthorizationBinding( - original.content(), - List.of( - evidence(SourceKind.ACCOUNT, otherActor.toString(), "actor"), - evidence(SourceKind.TENANT, TENANT.toString(), "tenant")))) + assertThatThrownBy(() -> + new SelectedOwnerIntakeAuthorizationBinding( + original.content(), + List.of( + evidence(SourceKind.ACCOUNT, otherActor.toString(), "actor"), + evidence(SourceKind.TENANT, TENANT.toString(), "tenant")))) .isInstanceOf(IllegalArgumentException.class); } @@ -261,10 +258,9 @@ void rejectsCountOrderTrailingAndUnknownSchemaChanges() { null)); assertThatThrownBy(() -> SelectedOwnerIntakeAuthorizationBinding.fromStored(null)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SelectedOwnerIntakeAuthorizationBinding.fromStored( - new byte[SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 1])) + assertThatThrownBy(() -> + SelectedOwnerIntakeAuthorizationBinding.fromStored( + new byte[SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + 1])) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentialsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentialsTest.java index 991d91f0ad..713cb3a960 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentialsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerCredentialsTest.java @@ -35,10 +35,9 @@ void acceptsOnlyTheAuthorizeSelectedOwnerIntakeMethod() { headers, allowedMethod) .value()) .isEqualTo(SECRET); - assertThatThrownBy( - () -> - SelectedOwnerIntakeAuthorizationProducerCredentials.readAuthenticated( - headers, "other/Method")) + assertThatThrownBy(() -> + SelectedOwnerIntakeAuthorizationProducerCredentials.readAuthenticated( + headers, "other/Method")) .isInstanceOf(IllegalArgumentException.class); } @@ -60,15 +59,12 @@ void requiresExactlyOneCredentialAndRedactsItsTextRepresentation() { .getAuthorizeSelectedOwnerIntakeMethod() .getFullMethodName(); - assertThatThrownBy( - () -> - SelectedOwnerIntakeAuthorizationProducerCredentials.readAuthenticated( - missing, method)) + assertThatThrownBy(() -> + SelectedOwnerIntakeAuthorizationProducerCredentials.readAuthenticated(missing, method)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SelectedOwnerIntakeAuthorizationProducerCredentials.readAuthenticated( - duplicate, method)) + assertThatThrownBy(() -> + SelectedOwnerIntakeAuthorizationProducerCredentials.readAuthenticated( + duplicate, method)) .isInstanceOf(IllegalArgumentException.class); assertThat(credential.toString()).doesNotContain(SECRET); assertThat(SelectedOwnerIntakeAuthorizationProducerCredentials.forAuthorize(SECRET).toString()) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodecTest.java index e0dca16491..bbcd80ed1a 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationProducerProtoCodecTest.java @@ -68,10 +68,9 @@ void rejectsChangedTransportNamespaceIntakeOwnerAndSelectedDraftEchoes() { exactEcho.toBuilder().setSelectedDraftBinding(ByteString.copyFromUtf8("{}")).build()); for (var echo : changed) { - assertThatThrownBy( - () -> - SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse( - request, response.toBuilder().setRequest(echo).build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse( + request, response.toBuilder().setRequest(echo).build())) .isInstanceOf(IllegalArgumentException.class); } } @@ -119,9 +118,8 @@ void acceptsDifferentAccountSourceCaptureButRejectsMismatchedOwnerAndDigest() { response.toBuilder().setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)).build(); for (var changed : List.of(mismatchedOwnerBinding, wrongDigest)) { - assertThatThrownBy( - () -> - SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse(request, changed)) + assertThatThrownBy(() -> + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse(request, changed)) .isInstanceOf(IllegalArgumentException.class); } } @@ -179,15 +177,12 @@ void rejectsUnknownDefaultMalformedAndOversizedRequestValues() { .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) .build()) .build(); - assertThatThrownBy( - () -> - SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse( - request, nestedUnknown)) + assertThatThrownBy(() -> + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse(request, nestedUnknown)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse( - request, unknownResponse)) + assertThatThrownBy(() -> + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse( + request, unknownResponse)) .isInstanceOf(IllegalArgumentException.class); } @@ -210,9 +205,8 @@ void rejectsMalformedNoncanonicalOrOversizedAuthorizationBinding() { var missing = SelectedOwnerIntakeAuthorizationProducerResponse.getDefaultInstance(); for (var changed : List.of(malformed, oversized, missing)) { - assertThatThrownBy( - () -> - SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse(request, changed)) + assertThatThrownBy(() -> + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse(request, changed)) .isInstanceOf(IllegalArgumentException.class); } } @@ -231,9 +225,8 @@ void rejectsResponsesBeyondTheTwentyFourMibWireBudget() { assertThat(oversized.getSerializedSize()) .isGreaterThan(SelectedOwnerIntakeAuthorizationProducerProtoCodec.MAX_WIRE_BYTES); - assertThatThrownBy( - () -> - SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse(request, oversized)) + assertThatThrownBy(() -> + SelectedOwnerIntakeAuthorizationProducerProtoCodec.fromResponse(request, oversized)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodecTest.java index c2c0d07d48..6d84622a80 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeAuthorizationReadGrpcCodecTest.java @@ -134,10 +134,9 @@ void rejectsNonHeldSubstitutedAndUnknownResponses() { () -> SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromResponse(request, changed)) .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromResponse( - request, ReadHeldSelectedOwnerIntakeAuthorizationResponse.getDefaultInstance())) + assertThatThrownBy(() -> + SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromResponse( + request, ReadHeldSelectedOwnerIntakeAuthorizationResponse.getDefaultInstance())) .isInstanceOf(IllegalArgumentException.class); } @@ -161,14 +160,13 @@ void rejectsWireMessagesBeyondTheTwentyFourMibBudget() { .build(); assertThat(oversizedResponse.getSerializedSize()) .isGreaterThan(SelectedOwnerIntakeAuthorizationReadGrpcCodec.MAX_WIRE_BYTES); - assertThatThrownBy( - () -> - SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromResponse( - Request.create( - "test", - SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding( - Owner.ENTITY_MANAGEMENT)), - oversizedResponse)) + assertThatThrownBy(() -> + SelectedOwnerIntakeAuthorizationReadGrpcCodec.fromResponse( + Request.create( + "test", + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding( + Owner.ENTITY_MANAGEMENT)), + oversizedResponse)) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java index 05e70d8051..1bf01c1776 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java @@ -71,12 +71,11 @@ void closeReleasesClientMonitorBeforeDrainingCertificateCallback( GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); when(channelFactory.buildChannel( any(String.class), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) - .thenAnswer( - invocation -> { - ManagedChannel channel = mock(ManagedChannel.class); - channels.add(channel); - return channel; - }); + .thenAnswer(invocation -> { + ManagedChannel channel = mock(ManagedChannel.class); + channels.add(channel); + return channel; + }); ClientHandle handle = kind.create(endpoints, tls, channelFactory); client = handle.client(); handle.initialize().run(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java index 35d7f4ecde..a275abf477 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java @@ -46,10 +46,9 @@ void roundTripsCanonicalRequestWithIndependentTransportCorrelation() { @Test void rejectsDefaultUnknownAndChangedDigestRequestsWhileAcceptingClosedEntityOwner() { - assertThatThrownBy( - () -> - SelectedOwnerIntakeSettlementGrpcCodec.fromRequest( - SelectedOwnerIntakeSettlementRequest.getDefaultInstance())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSettlementGrpcCodec.fromRequest( + SelectedOwnerIntakeSettlementRequest.getDefaultInstance())) .isInstanceOf(IllegalArgumentException.class); var binding = diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClientMtlsTest.java index 91d329820b..4b3fda2d13 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadClientMtlsTest.java @@ -165,10 +165,9 @@ void boundsUnavailableAccountReadByFiveSecondDeadline() throws Exception { NAMESPACE, scope(DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, NAMESPACE)); assertThatThrownBy(() -> client.read(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); } } @@ -177,18 +176,13 @@ void requiresTlsAndReadableFileBackedCredentials() { var endpoints = new ServiceEndpointsProperties(); var plaintext = new CommonGrpcClientProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new GrpcSelectedOwnerIntakeSourceReadClient( - endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + assertThatThrownBy(() -> + new GrpcSelectedOwnerIntakeSourceReadClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GrpcSelectedOwnerIntakeSourceReadClient( - endpoints, - new CommonGrpcClientProperties(), - new GrpcChannelFactory(), - NAMESPACE)) + assertThatThrownBy(() -> + new GrpcSelectedOwnerIntakeSourceReadClient( + endpoints, new CommonGrpcClientProperties(), new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodecTest.java index 0366f41ff1..ab09c4a9ce 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadProtoCodecTest.java @@ -44,27 +44,23 @@ void rejectsUnsupportedSchemaWrongDomainNamespaceReaderPurposeAndCorrelation() { NAMESPACE, scope(Owner.ENTITY_MANAGEMENT)); var wire = SelectedOwnerIntakeSourceReadProtoCodec.toRequest(request); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( - wire.toBuilder().setSchemaVersion(2).build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setSchemaVersion(2).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( - wire.toBuilder().setTargetNamespace("other").build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setTargetNamespace("other").build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( - wire.toBuilder() - .setIntendedReader("spiffe://firemud/ns/test/sa/entity-management-service") - .build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder() + .setIntendedReader("spiffe://firemud/ns/test/sa/entity-management-service") + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( - wire.toBuilder().setPurpose("AUTOMATION_INTAKE_SOURCE").build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setPurpose("AUTOMATION_INTAKE_SOURCE").build())) .isInstanceOf(IllegalArgumentException.class); for (UUID reusedIdentity : List.of( @@ -74,18 +70,14 @@ void rejectsUnsupportedSchemaWrongDomainNamespaceReaderPurposeAndCorrelation() { request.scope().actorAccountId(), request.scope().selected().requestId(), request.scope().selected().commitId())) { - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( - wire.toBuilder().setReadRequestId(reusedIdentity.toString()).build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setReadRequestId(reusedIdentity.toString()).build())) .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( - wire.toBuilder() - .setReadRequestId("00000000-0000-0000-0000-000000000000") - .build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setReadRequestId("00000000-0000-0000-0000-000000000000").build())) .isInstanceOf(IllegalArgumentException.class); } @@ -96,35 +88,29 @@ void rejectsMissingUnknownOversizedAndDigestSubstitutedRequests() { NAMESPACE, scope(Owner.AUTOMATION_SCRIPTING)); var wire = SelectedOwnerIntakeSourceReadProtoCodec.toRequest(request); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( - wire.toBuilder().clearPreliminarySourceScope().build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().clearPreliminarySourceScope().build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( - wire.toBuilder().setPreliminaryScopeDigest("sha256:" + "0".repeat(64)).build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setPreliminaryScopeDigest("sha256:" + "0".repeat(64)).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( - wire.toBuilder() - .setPreliminarySourceScope(ByteString.copyFrom(new byte[] {1})) - .build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder() + .setPreliminarySourceScope(ByteString.copyFrom(new byte[] {1})) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( - wire.toBuilder().setUnknownFields(unknownField()).build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknownField()).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( - wire.toBuilder() - .setPurpose( - "x".repeat(SelectedOwnerIntakeSourceReadProtoCodec.MAX_WIRE_BYTES)) - .build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder() + .setPurpose("x".repeat(SelectedOwnerIntakeSourceReadProtoCodec.MAX_WIRE_BYTES)) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -136,28 +122,24 @@ void requiresACompletePermittedAndUnmodifiedResponseEcho() { var wire = SelectedOwnerIntakeSourceReadProtoCodec.toRequest(request); var response = SelectedOwnerIntakeSourceReadProtoCodec.toResponse(request); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( - request, - response.toBuilder() - .setRequest(wire.toBuilder().setReadRequestId(UUID.randomUUID().toString())) - .build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( + request, + response.toBuilder() + .setRequest(wire.toBuilder().setReadRequestId(UUID.randomUUID().toString())) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( - request, response.toBuilder().setPermitted(false).build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( + request, response.toBuilder().setPermitted(false).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( - request, response.toBuilder().clearRequest().build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( + request, response.toBuilder().clearRequest().build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( - request, response.toBuilder().setUnknownFields(unknownField()).build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( + request, response.toBuilder().setUnknownFields(unknownField()).build())) .isInstanceOf(IllegalArgumentException.class); var oversizedResponseUnknownFields = UnknownFieldSet.newBuilder() @@ -169,11 +151,10 @@ void requiresACompletePermittedAndUnmodifiedResponseEcho() { new byte[SelectedOwnerIntakeSourceReadProtoCodec.MAX_WIRE_BYTES])) .build()) .build(); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( - request, - response.toBuilder().setUnknownFields(oversizedResponseUnknownFields).build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceReadProtoCodec.fromResponse( + request, + response.toBuilder().setUnknownFields(oversizedResponseUnknownFields).build())) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScopeTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScopeTest.java index 534f448d55..183a33f8c7 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScopeTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSourceReadScopeTest.java @@ -132,10 +132,9 @@ void deniesUnknownOwnersAndCrossOwnerSchemaPurposeOrReader() throws Exception { var scope = scope(Owner.ENTITY_MANAGEMENT); for (Owner owner : List.of(Owner.WORLD_MANAGEMENT, Owner.GAME_LOGIC, Owner.GAME_DESIGN_CONTROL_PLANE)) - assertThatThrownBy( - () -> - new SelectedOwnerIntakeSourceReadScope( - owner, "test", OPERATION, FENCE, INTAKE, ACTOR, scope.selected())) + assertThatThrownBy(() -> + new SelectedOwnerIntakeSourceReadScope( + owner, "test", OPERATION, FENCE, INTAKE, ACTOR, scope.selected())) .isInstanceOf(IllegalArgumentException.class); for (String[] changed : List.of( @@ -269,17 +268,15 @@ void deniesMalformedTruncatedTrailingOversizedAndNoncanonicalInput() throws Exce scope.purpose()); assertThatThrownBy(() -> SelectedOwnerIntakeSourceReadScope.fromStored(padded)) .isInstanceOf(RuntimeException.class); - assertThatThrownBy( - () -> - new SelectedOwnerIntakeSourceReadScope( - scope.owner(), - "test", - OPERATION, - FENCE, - INTAKE, - ACTOR, - binding( - REQUEST, COMMIT, "x".repeat(SelectedOwnerIntakeSourceReadScope.MAX_BYTES)))) + assertThatThrownBy(() -> + new SelectedOwnerIntakeSourceReadScope( + scope.owner(), + "test", + OPERATION, + FENCE, + INTAKE, + ACTOR, + binding(REQUEST, COMMIT, "x".repeat(SelectedOwnerIntakeSourceReadScope.MAX_BYTES)))) .isInstanceOf(IllegalArgumentException.class); } @@ -293,21 +290,19 @@ void rejectsNilReservationIdentitiesAndUnsupportedNullOwner() { List.of(OPERATION, nil, INTAKE, ACTOR), List.of(OPERATION, FENCE, nil, ACTOR), List.of(OPERATION, FENCE, INTAKE, nil))) - assertThatThrownBy( - () -> - new SelectedOwnerIntakeSourceReadScope( - Owner.ENTITY_MANAGEMENT, - "test", - ids.get(0), - ids.get(1), - ids.get(2), - ids.get(3), - selected)) + assertThatThrownBy(() -> + new SelectedOwnerIntakeSourceReadScope( + Owner.ENTITY_MANAGEMENT, + "test", + ids.get(0), + ids.get(1), + ids.get(2), + ids.get(3), + selected)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new SelectedOwnerIntakeSourceReadScope( - null, "test", OPERATION, FENCE, INTAKE, ACTOR, selected)) + assertThatThrownBy(() -> + new SelectedOwnerIntakeSourceReadScope( + null, "test", OPERATION, FENCE, INTAKE, ACTOR, selected)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodecTest.java index e75fee51c6..692730527f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodecTest.java @@ -136,17 +136,15 @@ void rejectsNonHeldSubstitutedAndUnknownResponses() { .build())) .build(); for (var changed : List.of(notHeld, substituted, unknown, nestedUnknown)) { - assertThatThrownBy( - () -> - SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromResponse( - request, changed)) + assertThatThrownBy(() -> + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromResponse( + request, changed)) .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromResponse( - request, - ReadHeldSelectedOwnerWorldClosureAuthorizationResponse.getDefaultInstance())) + assertThatThrownBy(() -> + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromResponse( + request, + ReadHeldSelectedOwnerWorldClosureAuthorizationResponse.getDefaultInstance())) .isInstanceOf(IllegalArgumentException.class); } @@ -171,14 +169,13 @@ void rejectsMessagesBeyondTheTwentyFourMibBudget() { .build(); assertThat(oversizedResponse.getSerializedSize()) .isGreaterThan(SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.MAX_WIRE_BYTES); - assertThatThrownBy( - () -> - SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromResponse( - Request.create( - "test", - SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding( - Owner.ENTITY_MANAGEMENT)), - oversizedResponse)) + assertThatThrownBy(() -> + SelectedOwnerIntakeWorldClosureAuthorizationReadGrpcCodec.fromResponse( + Request.create( + "test", + SelectedOwnerIntakeAuthorizationReadEvidenceTest.binding( + Owner.ENTITY_MANAGEMENT)), + oversizedResponse)) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java index 4efc30ebba..c28a3a2ff5 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerWorldInventoryRecipientFieldsTest.java @@ -69,18 +69,16 @@ void rejectsChangedOriginalRecipientAndDerivedClosurePurposeForBothOwners() { assertThatThrownBy(() -> SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(base)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("freeze evidence"); - assertThatThrownBy( - () -> - SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest( - base.toBuilder() - .setIntendedReader("spiffe://firemud/ns/test/sa/world-management-service") - .build())) + assertThatThrownBy(() -> + SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest( + base.toBuilder() + .setIntendedReader("spiffe://firemud/ns/test/sa/world-management-service") + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("recipient differs"); - assertThatThrownBy( - () -> - SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest( - base.toBuilder().setClosureReadPurpose("ENTITY_INTAKE_RETENTION").build())) + assertThatThrownBy(() -> + SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest( + base.toBuilder().setClosureReadPurpose("ENTITY_INTAKE_RETENTION").build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("closure read purpose differs"); } @@ -150,16 +148,12 @@ void rejectsChangedCompleteRequestEchoAndInventoryDigest() { : zeroDigest) .build(); - assertThatThrownBy( - () -> - SelectedOwnerWorldInventoryReadGrpcCodec.fromResponse( - fixture.request(), changedEcho)) + assertThatThrownBy(() -> + SelectedOwnerWorldInventoryReadGrpcCodec.fromResponse(fixture.request(), changedEcho)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact selected-owner inventory read request"); - assertThatThrownBy( - () -> - SelectedOwnerWorldInventoryReadGrpcCodec.fromResponse( - fixture.request(), changedDigest)) + assertThatThrownBy(() -> + SelectedOwnerWorldInventoryReadGrpcCodec.fromResponse(fixture.request(), changedDigest)) .isInstanceOf(IllegalArgumentException.class); } @@ -216,10 +210,9 @@ void rejectsInventoryBoundToDifferentFreezeAcknowledgement() { var changedRequest = SelectedOwnerWorldInventoryReadGrpcCodec.fromRequest(changedRequestWire); assertThat(changedRequest.freezeEvidence()).isNotEqualTo(fixture.freezeEvidence()); - assertThatThrownBy( - () -> - SelectedOwnerWorldInventoryReadGrpcCodec.toResponse( - changedRequest, fixture.inventory())) + assertThatThrownBy(() -> + SelectedOwnerWorldInventoryReadGrpcCodec.toResponse( + changedRequest, fixture.inventory())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact selected-owner freeze"); } @@ -384,15 +377,14 @@ private static PublicEvidence publicInventory( 0, 0, selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .map(unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) .toList(), inboundClosure); var selection = account.input().selection(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountInitialAdmissionSettlementReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountInitialAdmissionSettlementReadGrpcCodecTest.java index 0eb49d77a5..91ec625ee5 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountInitialAdmissionSettlementReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountInitialAdmissionSettlementReadGrpcCodecTest.java @@ -58,10 +58,9 @@ void rejectsNonterminalAndChangedCompleteHoldDespiteSameOriginalProtection() { var pending = new GameSessionCanonicalInitialAdmissionOwnerProof( hold, Outcome.PENDING, null, null, null, false, null); - assertThatThrownBy( - () -> - new AccountInitialAdmissionSettlementReadEvidence( - evidence.readRequestId(), evidence.protection(), pending)) + assertThatThrownBy(() -> + new AccountInitialAdmissionSettlementReadEvidence( + evidence.readRequestId(), evidence.protection(), pending)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Nonterminal"); var changed = @@ -70,16 +69,13 @@ void rejectsNonterminalAndChangedCompleteHoldDespiteSameOriginalProtection() { var differentHold = new GameSessionCanonicalInitialAdmissionOwnerProof( changed, Outcome.ABORTED, null, null, "sha256:" + "a".repeat(64), true, Instant.EPOCH); - assertThatThrownBy( - () -> - new AccountInitialAdmissionSettlementReadEvidence( - evidence.readRequestId(), evidence.protection(), differentHold)) + assertThatThrownBy(() -> + new AccountInitialAdmissionSettlementReadEvidence( + evidence.readRequestId(), evidence.protection(), differentHold)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("complete protected hold"); - assertThatThrownBy( - () -> - new AccountInitialAdmissionSettlementReadInput( - new UUID(0L, 0L), evidence.protection())) + assertThatThrownBy(() -> + new AccountInitialAdmissionSettlementReadInput(new UUID(0L, 0L), evidence.protection())) .isInstanceOf(IllegalArgumentException.class); } @@ -104,10 +100,8 @@ void refusesMissingDuplicateUnknownAndSubstitutedRequestFields() { request.toBuilder().setAccountProtectionEvidence(0, ByteString.EMPTY).build(), request.toBuilder().setUnknownFields(unknown()).build()); for (var value : invalid) { - assertThatThrownBy( - () -> - AccountInitialAdmissionSettlementReadGrpcCodec.fromRequest( - value, "world-runtime")) + assertThatThrownBy(() -> + AccountInitialAdmissionSettlementReadGrpcCodec.fromRequest(value, "world-runtime")) .isInstanceOf(IllegalArgumentException.class); } assertThatThrownBy( @@ -121,10 +115,9 @@ void refusesMissingDuplicateUnknownAndSubstitutedRequestFields() { duplicateWire, request.getSerializedSize(), request.getSerializedSize()); - assertThatThrownBy( - () -> - AccountInitialAdmissionSettlementReadGrpcCodec.fromRequestWireBytes( - duplicateWire, "world-runtime")) + assertThatThrownBy(() -> + AccountInitialAdmissionSettlementReadGrpcCodec.fromRequestWireBytes( + duplicateWire, "world-runtime")) .isInstanceOf(IllegalArgumentException.class); } @@ -159,10 +152,8 @@ void refusesMissingDuplicateUnknownAndSubstitutedResponseFields() { .build(), response.toBuilder().setUnknownFields(unknown()).build()); for (var value : invalid) { - assertThatThrownBy( - () -> - AccountInitialAdmissionSettlementReadGrpcCodec.fromResponse( - evidence.input(), value)) + assertThatThrownBy(() -> + AccountInitialAdmissionSettlementReadGrpcCodec.fromResponse(evidence.input(), value)) .isInstanceOf(IllegalArgumentException.class); } } @@ -182,44 +173,37 @@ void refusesNoncanonicalNestedEvidenceMalformedFramingAndPurposeOverflow() { request.toBuilder() .setAccountProtectionEvidence(0, ByteString.copyFromUtf8(invalid)) .build(); - assertThatThrownBy( - () -> - AccountInitialAdmissionSettlementReadGrpcCodec.fromRequest( - changed, "world-runtime")) + assertThatThrownBy(() -> + AccountInitialAdmissionSettlementReadGrpcCodec.fromRequest(changed, "world-runtime")) .isInstanceOf(IllegalArgumentException.class); } var response = AccountInitialAdmissionSettlementReadGrpcCodec.toResponse(evidence); byte[] proof = response.getCanonicalGameSessionOwnerProof(0).toByteArray(); byte[] trailing = Arrays.copyOf(proof, proof.length + 1); - assertThatThrownBy( - () -> - AccountInitialAdmissionSettlementReadGrpcCodec.fromResponse( - evidence.input(), - response.toBuilder() - .setCanonicalGameSessionOwnerProof(0, ByteString.copyFrom(trailing)) - .build())) + assertThatThrownBy(() -> + AccountInitialAdmissionSettlementReadGrpcCodec.fromResponse( + evidence.input(), + response.toBuilder() + .setCanonicalGameSessionOwnerProof(0, ByteString.copyFrom(trailing)) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountInitialAdmissionSettlementReadGrpcCodec.fromRequest( - request.toBuilder() - .setAccountProtectionEvidence( - 0, - ByteString.copyFrom( - new byte - [AccountStartSessionAdmissionProtectionEvidence - .MAX_CANONICAL_BYTES - + 1])) - .build(), - "world-runtime")) + assertThatThrownBy(() -> + AccountInitialAdmissionSettlementReadGrpcCodec.fromRequest( + request.toBuilder() + .setAccountProtectionEvidence( + 0, + ByteString.copyFrom( + new byte + [AccountStartSessionAdmissionProtectionEvidence.MAX_CANONICAL_BYTES + + 1])) + .build(), + "world-runtime")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountInitialAdmissionSettlementReadGrpcCodec.fromResponseWireBytes( - evidence.input(), - new byte - [AccountInitialAdmissionSettlementReadGrpcCodec.MAX_RESPONSE_WIRE_BYTES - + 1])) + assertThatThrownBy(() -> + AccountInitialAdmissionSettlementReadGrpcCodec.fromResponseWireBytes( + evidence.input(), + new byte + [AccountInitialAdmissionSettlementReadGrpcCodec.MAX_RESPONSE_WIRE_BYTES + 1])) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionGrpcCodecTest.java index 8a8c4f3de1..9ed027eacb 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionAcquisitionGrpcCodecTest.java @@ -22,10 +22,9 @@ void rejectsDuplicateAndUnknownRequestFieldsBeforeDecodingOwnerBytes() { .addSchemaVersion(1) .addSchemaVersion(1) .build(); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromRequest( - duplicate, NAMESPACE)) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromRequest( + duplicate, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("duplicate field"); @@ -36,10 +35,9 @@ void rejectsDuplicateAndUnknownRequestFieldsBeforeDecodingOwnerBytes() { .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) .build()) .build(); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromRequest( - unknown, NAMESPACE)) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromRequest( + unknown, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); } @@ -47,10 +45,9 @@ void rejectsDuplicateAndUnknownRequestFieldsBeforeDecodingOwnerBytes() { @Test void rejectsNonCanonicalFenceTextAndRawDuplicateOccurrences() { var nonCanonicalFence = minimallyPopulatedRequest("01"); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromRequest( - nonCanonicalFence, NAMESPACE)) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromRequest( + nonCanonicalFence, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical positive unsigned decimal"); @@ -60,10 +57,9 @@ void rejectsNonCanonicalFenceTextAndRawDuplicateOccurrences() { .addSchemaVersion(1) .build() .toByteArray(); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromRequestWireBytes( - duplicateSchemaWire, NAMESPACE)) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromRequestWireBytes( + duplicateSchemaWire, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("duplicate field"); } @@ -81,17 +77,15 @@ void rejectsMismatchedTargetAndUnusableOriginalEvidence() { .addActivationRequestId(ACTIVATION) .addWorldPreparingEvidence(ByteString.copyFrom(new byte[] {1})) .build(); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromRequest( - request, NAMESPACE)) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.fromRequest( + request, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("target namespace"); - assertThatThrownBy( - () -> - new AccountStartSessionActivationProtectionAcquisitionInput( - new byte[] {1}, UUID.fromString(MUTATION), UUID.fromString(ATTEMPT), 7L, null)) + assertThatThrownBy(() -> + new AccountStartSessionActivationProtectionAcquisitionInput( + new byte[] {1}, UUID.fromString(MUTATION), UUID.fromString(ATTEMPT), 7L, null)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementGrpcCodecTest.java index 0931b0e2cd..04807ebcac 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionActivationProtectionSettlementGrpcCodecTest.java @@ -29,40 +29,34 @@ void roundTripsOnlyExactLookupIdentity() { @Test void rejectsDuplicateUnknownChangedAndNoncanonicalRequestFields() { var valid = AccountStartSessionActivationProtectionSettlementGrpcCodec.toRequest(input()); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionSettlementGrpcCodec.fromRequest( - valid.toBuilder().addAccountProtectionFence("18").build(), NAMESPACE)) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromRequest( + valid.toBuilder().addAccountProtectionFence("18").build(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionSettlementGrpcCodec.fromRequest( - valid.toBuilder().setTargetNamespace(0, "other-runtime").build(), NAMESPACE)) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromRequest( + valid.toBuilder().setTargetNamespace(0, "other-runtime").build(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionSettlementGrpcCodec.fromRequest( - valid.toBuilder().setAccountProtectionFence(0, "018").build(), NAMESPACE)) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromRequest( + valid.toBuilder().setAccountProtectionFence(0, "018").build(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionSettlementGrpcCodec.fromRequest( - valid.toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField( - 99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) - .build()) - .build(), - NAMESPACE)) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromRequest( + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(), + NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionSettlementGrpcCodec.fromRequest( - valid.toBuilder() - .setSettlementRequestId(0, "00000000-0000-0000-0000-000000000000") - .build(), - NAMESPACE)) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromRequest( + valid.toBuilder() + .setSettlementRequestId(0, "00000000-0000-0000-0000-000000000000") + .build(), + NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); } @@ -79,57 +73,49 @@ void responseMustEchoRequestIdentityAndContainCompleteTerminalBytes() { .addTerminalEvidenceCanonicalBytes(ByteString.copyFromUtf8("{}")) .build(); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionSettlementGrpcCodec.fromResponse( - input, - validShape.toBuilder() - .setSettlementRequestId(0, UUID.randomUUID().toString()) - .build())) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromResponse( + input, + validShape.toBuilder() + .setSettlementRequestId(0, UUID.randomUUID().toString()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("identity"); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionSettlementGrpcCodec.fromResponse( - input, validShape.toBuilder().setAccountProtectionFence(0, "19").build())) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromResponse( + input, validShape.toBuilder().setAccountProtectionFence(0, "19").build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("identity"); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionSettlementGrpcCodec.fromResponse( - input, - validShape.toBuilder() - .setAccountProtectionId(0, UUID.randomUUID().toString()) - .build())) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromResponse( + input, + validShape.toBuilder() + .setAccountProtectionId(0, UUID.randomUUID().toString()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("identity"); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionSettlementGrpcCodec.fromResponse( - input, - validShape.toBuilder().addSettledAt("2026-10-11T00:00:00.000001Z").build())) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromResponse( + input, validShape.toBuilder().addSettledAt("2026-10-11T00:00:00.000001Z").build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("identity"); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionSettlementGrpcCodec.fromResponse( - input, - validShape.toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField( - 99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) - .build()) - .build())) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromResponse( + input, + validShape.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionSettlementGrpcCodec.fromResponse( - input, - validShape.toBuilder() - .setTerminalEvidenceCanonicalBytes(0, ByteString.EMPTY) - .build())) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionSettlementGrpcCodec.fromResponse( + input, + validShape.toBuilder() + .setTerminalEvidenceCanonicalBytes(0, ByteString.EMPTY) + .build())) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest.java index 0a562d6fed..744cc925e3 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionAcquisitionGrpcCodecTest.java @@ -53,10 +53,9 @@ void roundTripsCompleteCanonicalRequestAndAccountEvidenceAndRejectsDifferentRequ assertThat(request.canonicalBytes()).containsExactly(fixture.request().canonicalBytes()); assertThat(evidence.canonicalBytes()).containsExactly(fixture.evidence().canonicalBytes()); assertThat(evidence.request().canonicalBytes()).containsExactly(request.canonicalBytes()); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromResponse( - fixture("different-request").request(), responseWire)) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromResponse( + fixture("different-request").request(), responseWire)) .isInstanceOf(IllegalArgumentException.class); } @@ -75,20 +74,15 @@ void rejectsUnknownDuplicateAndNoncanonicalEnvelopeFields() throws Exception { var duplicateSchema = request.toBuilder().addSchemaVersion(1).build(); var unsupportedSchema = request.toBuilder().clearSchemaVersion().addSchemaVersion(2).build(); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromRequest( - unknownRequest)) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromRequest(unknownRequest)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromRequest( - duplicateSchema)) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromRequest(duplicateSchema)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromRequest( - unsupportedSchema)) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromRequest( + unsupportedSchema)) .isInstanceOf(IllegalArgumentException.class); byte[] noncanonicalRequestBytes = @@ -100,10 +94,9 @@ void rejectsUnknownDuplicateAndNoncanonicalEnvelopeFields() throws Exception { .addSchemaVersion(1) .addRequestCanonicalBytes(ByteString.copyFrom(noncanonicalRequestBytes)) .build(); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromRequest( - noncanonicalRequest)) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromRequest( + noncanonicalRequest)) .isInstanceOf(IllegalArgumentException.class); ByteArrayOutputStream reorderedBytes = new ByteArrayOutputStream(); @@ -111,10 +104,9 @@ void rejectsUnknownDuplicateAndNoncanonicalEnvelopeFields() throws Exception { output.writeByteArray(2, fixture.request().canonicalBytes()); output.writeInt32(1, AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.SCHEMA_VERSION); output.flush(); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromRequestWireBytes( - reorderedBytes.toByteArray())) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromRequestWireBytes( + reorderedBytes.toByteArray())) .isInstanceOf(IllegalArgumentException.class); var response = @@ -129,15 +121,13 @@ void rejectsUnknownDuplicateAndNoncanonicalEnvelopeFields() throws Exception { .build(); var unsupportedResponseSchema = response.toBuilder().clearSchemaVersion().addSchemaVersion(2).build(); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromResponse( - fixture.request(), unknownResponse)) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromResponse( + fixture.request(), unknownResponse)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromResponse( - fixture.request(), unsupportedResponseSchema)) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromResponse( + fixture.request(), unsupportedResponseSchema)) .isInstanceOf(IllegalArgumentException.class); byte[] noncanonicalEvidenceBytes = @@ -149,10 +139,9 @@ void rejectsUnknownDuplicateAndNoncanonicalEnvelopeFields() throws Exception { .addSchemaVersion(1) .addEvidenceCanonicalBytes(ByteString.copyFrom(noncanonicalEvidenceBytes)) .build(); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromResponse( - fixture.request(), noncanonicalResponse)) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromResponse( + fixture.request(), noncanonicalResponse)) .isInstanceOf(IllegalArgumentException.class); } @@ -179,15 +168,13 @@ void rejectsOneByteBeyondEachPurposePayloadLimit() { + 1])) .build(); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromRequest( - oversizedRequest)) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromRequest( + oversizedRequest)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromResponse( - fixture("oversized-response").request(), oversizedResponse)) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionAcquisitionGrpcCodec.fromResponse( + fixture("oversized-response").request(), oversizedResponse)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidenceTest.java index 472ec9e50d..0df20cbac2 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionEvidenceTest.java @@ -118,31 +118,29 @@ void rejectsRequestProjectionHoldScopeExpiryAndCounterSubstitutions() throws Exc byte[] substitutedProjection = expectedProjection.clone(); substitutedProjection[substitutedProjection.length - 2] ^= 1; - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionRequest.create( - tuple.canonicalBytes(), - substitutedProjection, - GAME_SESSION_MUTATION, - GAME_SESSION_ATTEMPT, - 1L, - ORIGINAL_LEASE_EXPIRY, - ACCOUNT_PARTICIPATION, - 2L, - hold(tuple))) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionRequest.create( + tuple.canonicalBytes(), + substitutedProjection, + GAME_SESSION_MUTATION, + GAME_SESSION_ATTEMPT, + 1L, + ORIGINAL_LEASE_EXPIRY, + ACCOUNT_PARTICIPATION, + 2L, + hold(tuple))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionRequest.create( - tuple.canonicalBytes(), - expectedProjection, - GAME_SESSION_MUTATION, - GAME_SESSION_ATTEMPT, - 1L, - ORIGINAL_LEASE_EXPIRY.plusNanos(1), - ACCOUNT_PARTICIPATION, - 2L, - hold(tuple))) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionRequest.create( + tuple.canonicalBytes(), + expectedProjection, + GAME_SESSION_MUTATION, + GAME_SESSION_ATTEMPT, + 1L, + ORIGINAL_LEASE_EXPIRY.plusNanos(1), + ACCOUNT_PARTICIPATION, + 2L, + hold(tuple))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("microsecond"); @@ -153,9 +151,8 @@ void rejectsRequestProjectionHoldScopeExpiryAndCounterSubstitutions() throws Exc .isInstanceOf(IllegalArgumentException.class); Map alternateFraction = readObject(request(tuple).canonicalBytes()); alternateFraction.put("originalLeaseExpiresAt", "2026-10-09T10:20:30.45678Z"); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionRequest.decode(canonical(alternateFraction))) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionRequest.decode(canonical(alternateFraction))) .isInstanceOf(IllegalArgumentException.class); Map alternateOffset = readObject(request(tuple).canonicalBytes()); alternateOffset.put("originalLeaseExpiresAt", "2026-10-09T10:20:30.456789+00:00"); @@ -165,18 +162,17 @@ void rejectsRequestProjectionHoldScopeExpiryAndCounterSubstitutions() throws Exc WorldCanonicalInitialAdmissionHold.HoldIdentity wrongNamespace = hold(tuple, TENANT, "another-world-runtime"); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionRequest.create( - tuple.canonicalBytes(), - expectedProjection, - GAME_SESSION_MUTATION, - GAME_SESSION_ATTEMPT, - 1L, - ORIGINAL_LEASE_EXPIRY, - ACCOUNT_PARTICIPATION, - 2L, - wrongNamespace)) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionRequest.create( + tuple.canonicalBytes(), + expectedProjection, + GAME_SESSION_MUTATION, + GAME_SESSION_ATTEMPT, + 1L, + ORIGINAL_LEASE_EXPIRY, + ACCOUNT_PARTICIPATION, + 2L, + wrongNamespace)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("World hold scope"); @@ -194,10 +190,9 @@ void rejectsRequestProjectionHoldScopeExpiryAndCounterSubstitutions() throws Exc extra.put("opaqueAuthorizationReference", "must-not-be-retained"); assertThatThrownBy(() -> AccountStartSessionAdmissionProtectionRequest.decode(canonical(extra))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionRequest.decode( - withDuplicateSchema(request(tuple).canonicalBytes()))) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionRequest.decode( + withDuplicateSchema(request(tuple).canonicalBytes()))) .isInstanceOf(IllegalArgumentException.class); } @@ -225,37 +220,34 @@ void bindsCaptureReferenceToTupleAndRetainsCompleteChangedSourceEvidence() throw .containsExactly(changedSource.canonicalBytes()); byte[] wrongReference = captureReference(tuple, "18", "23", "18446744073709551615"); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionEvidence.create( - request, - ACCOUNT_PROTECTION, - 4L, - wrongReference, - sha256(wrongReference), - List.of(originalSource))) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionEvidence.create( + request, + ACCOUNT_PROTECTION, + 4L, + wrongReference, + sha256(wrongReference), + List.of(originalSource))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("original tuple bundle"); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionEvidence.create( - request, - ACCOUNT_PROTECTION, - 4L, - captureBytes, - "0".repeat(64), - List.of(originalSource))) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionEvidence.create( + request, + ACCOUNT_PROTECTION, + 4L, + captureBytes, + "0".repeat(64), + List.of(originalSource))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("digest differs"); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionEvidence.create( - request, - ACCOUNT_PROTECTION, - 4L, - captureBytes, - digest, - List.of(originalSource, originalSource))) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionEvidence.create( + request, + ACCOUNT_PROTECTION, + 4L, + captureBytes, + digest, + List.of(originalSource, originalSource))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("duplicate source keys"); } @@ -288,10 +280,9 @@ void rejectsEvidenceShapeDuplicatesTrailingBytesAndOverflowingCounters() throws assertThatThrownBy( () -> AccountStartSessionAdmissionProtectionEvidence.decode(canonical(extra))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionEvidence.decode( - withDuplicateSchema(evidence.canonicalBytes()))) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionEvidence.decode( + withDuplicateSchema(evidence.canonicalBytes()))) .isInstanceOf(IllegalArgumentException.class); byte[] trailing = Arrays.copyOf(evidence.canonicalBytes(), evidence.canonicalBytes().length + 1); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionSettlementEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionSettlementEvidenceTest.java index d68ac606d9..c5ed00a040 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionSettlementEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionAdmissionProtectionSettlementEvidenceTest.java @@ -107,10 +107,9 @@ void pendingMismatchedHoldAndWrongNextPointerCannotSettle() { false, terminal.terminalAt()); for (var invalid : List.of(pending, substituted, wrongPointer)) { - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionSettlementEvidence.create( - fixture.protection(), invalid)) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionSettlementEvidence.create( + fixture.protection(), invalid)) .isInstanceOf(IllegalArgumentException.class); } } @@ -181,10 +180,8 @@ void expectedClosedCommitMustUseExactlyPriorPointerPlusOne() { fixture.terminal().proofDigest(), false, fixture.terminal().terminalAt()); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionSettlementEvidence.create( - protection, changed)) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionSettlementEvidence.create(protection, changed)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact next pointer"); } @@ -236,26 +233,21 @@ void rejectsMalformedNoncanonicalBase64TruncatedAndOversizedProofs() throws Exce Base64.getEncoder().encodeToString(proof) + "\n")) { var changed = fields(bytes); changed.put(TERMINAL, invalid); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionSettlementEvidence.decode( - canonical(changed))) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionSettlementEvidence.decode(canonical(changed))) .isInstanceOf(IllegalArgumentException.class); } var changedProtection = fields(bytes); changedProtection.put(PROTECTION, Base64.getEncoder().encodeToString(new byte[] {1, 2, 3})); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionSettlementEvidence.decode( - canonical(changedProtection))) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionSettlementEvidence.decode( + canonical(changedProtection))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountStartSessionAdmissionProtectionSettlementEvidence.decode( - new byte - [AccountStartSessionAdmissionProtectionSettlementEvidence - .MAX_CANONICAL_BYTES - + 1])) + assertThatThrownBy(() -> + AccountStartSessionAdmissionProtectionSettlementEvidence.decode( + new byte + [AccountStartSessionAdmissionProtectionSettlementEvidence.MAX_CANONICAL_BYTES + + 1])) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClientTest.java index af82ce8558..b8b4ec30c9 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadClientTest.java @@ -25,25 +25,23 @@ class AccountStartSessionWorldParticipationHistoricalReadClientTest { void requiresFileBackedMtlsAndConfiguredNamespace(@TempDir Path directory) throws Exception { var plaintext = fileBacked(directory); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new AccountStartSessionWorldParticipationHistoricalReadClient( - new ServiceEndpointsProperties(), - plaintext, - new GrpcChannelFactory(), - "world-runtime")) + assertThatThrownBy(() -> + new AccountStartSessionWorldParticipationHistoricalReadClient( + new ServiceEndpointsProperties(), + plaintext, + new GrpcChannelFactory(), + "world-runtime")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mTLS"); var classpath = fileBacked(directory); classpath.setPrivateKey("classpath:private.key"); - assertThatThrownBy( - () -> - new AccountStartSessionWorldParticipationHistoricalReadClient( - new ServiceEndpointsProperties(), - classpath, - new GrpcChannelFactory(), - "world-runtime")) + assertThatThrownBy(() -> + new AccountStartSessionWorldParticipationHistoricalReadClient( + new ServiceEndpointsProperties(), + classpath, + new GrpcChannelFactory(), + "world-runtime")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("file-backed"); @@ -54,13 +52,12 @@ void requiresFileBackedMtlsAndConfiguredNamespace(@TempDir Path directory) throw new GrpcChannelFactory(), "world-runtime"); try { - assertThatThrownBy( - () -> - new AccountStartSessionWorldParticipationHistoricalReadClient( - new ServiceEndpointsProperties(), - fileBacked(directory), - new GrpcChannelFactory(), - "not a namespace")) + assertThatThrownBy(() -> + new AccountStartSessionWorldParticipationHistoricalReadClient( + new ServiceEndpointsProperties(), + fileBacked(directory), + new GrpcChannelFactory(), + "not a namespace")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("namespace"); assertThatThrownBy(() -> client.read(request("other-runtime"))) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest.java index cd5c2aba44..29735a59fe 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationHistoricalReadGrpcCodecTest.java @@ -62,36 +62,31 @@ void rejectsUnknownFieldsUnsupportedVersionMalformedReadIdAndIncompleteTuple() { UnknownFieldSet unknown = unknown(); var wire = AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toRequest(request); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest( - wire.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest( - wire.toBuilder().setSchemaVersion(2).build())) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest( + wire.toBuilder().setSchemaVersion(2).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unsupported"); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest( - wire.toBuilder().setReadRequestId(READ_ID + " ").build())) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest( + wire.toBuilder().setReadRequestId(READ_ID + " ").build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical non-nil UUID"); - assertThatThrownBy( - () -> - new AccountStartSessionWorldParticipationHistoricalReadRequest( - READ_ID, NAMESPACE, new byte[0])) + assertThatThrownBy(() -> + new AccountStartSessionWorldParticipationHistoricalReadRequest( + READ_ID, NAMESPACE, new byte[0])) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("empty or oversized"); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest( - wire.toBuilder() - .setOriginalPostAuthorizationTuple(com.google.protobuf.ByteString.EMPTY) - .build())) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromRequest( + wire.toBuilder() + .setOriginalPostAuthorizationTuple(com.google.protobuf.ByteString.EMPTY) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("empty or oversized"); } @@ -99,10 +94,9 @@ void rejectsUnknownFieldsUnsupportedVersionMalformedReadIdAndIncompleteTuple() { @Test void rejectsOnlyReservationOwnerCollisionAtRequestBoundary() { var original = originalTuple(NAMESPACE); - assertThatThrownBy( - () -> - new AccountStartSessionWorldParticipationHistoricalReadRequest( - original.reservationOwnerId(), NAMESPACE, original.canonicalBytes())) + assertThatThrownBy(() -> + new AccountStartSessionWorldParticipationHistoricalReadRequest( + original.reservationOwnerId(), NAMESPACE, original.canonicalBytes())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("distinct from the reservation owner"); @@ -134,35 +128,29 @@ void rejectsChangedRequestEchoUnknownResponseAndInconsistentRetainedIdentity() { .setReadRequestId("0fd3d542-a9f8-4b8f-b1df-79413650126c") .build()) .build(); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromResponse( - request, changedEcho)) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromResponse( + request, changedEcho)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("changed the exact"); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromResponse( - request, response.toBuilder().setUnknownFields(unknown()).build())) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromResponse( + request, response.toBuilder().setUnknownFields(unknown()).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setPreparationInputDigest("sha256:" + "0".repeat(64)) - .build())) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.fromResponse( + request, + response.toBuilder().setPreparationInputDigest("sha256:" + "0".repeat(64)).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("differs from the exact retained"); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toResponse( - request, - evidence( - new AccountStartSessionWorldParticipationHistoricalReadRequest( - READ_ID, NAMESPACE, originalTuple(NAMESPACE, 20L).canonicalBytes())))) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationHistoricalReadGrpcCodec.toResponse( + request, + evidence( + new AccountStartSessionWorldParticipationHistoricalReadRequest( + READ_ID, NAMESPACE, originalTuple(NAMESPACE, 20L).canonicalBytes())))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("changed the exact"); } @@ -171,40 +159,36 @@ READ_ID, NAMESPACE, originalTuple(NAMESPACE, 20L).canonicalBytes())))) void rejectsOversizedPreparationInputAndTupleAtClosedCarrierBoundary() { var request = request(); String oversized = "x".repeat(WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + 1); - assertThatThrownBy( - () -> - new AccountStartSessionWorldParticipationHistoricalReadEvidence( - request, - PARTICIPATION_ID, - 31L, - GAME_SESSION_ATTEMPT_ID, - 37L, - GAME_INSTANCE_ID, - oversized, - digest(oversized))) + assertThatThrownBy(() -> + new AccountStartSessionWorldParticipationHistoricalReadEvidence( + request, + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + GAME_INSTANCE_ID, + oversized, + digest(oversized))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("byte limit"); - assertThatThrownBy( - () -> - new AccountStartSessionWorldParticipationHistoricalReadRequest( - READ_ID, - NAMESPACE, - new byte - [StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES - + 1])) + assertThatThrownBy(() -> + new AccountStartSessionWorldParticipationHistoricalReadRequest( + READ_ID, + NAMESPACE, + new byte + [StartSessionPostAuthorizationExecutionTuple.MAX_CANONICAL_TUPLE_BYTES + 1])) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("empty or oversized"); - assertThatThrownBy( - () -> - new AccountStartSessionWorldParticipationHistoricalReadEvidence( - request, - PARTICIPATION_ID, - 0L, - GAME_SESSION_ATTEMPT_ID, - 37L, - GAME_INSTANCE_ID, - PREPARATION_INPUT, - digest(PREPARATION_INPUT))) + assertThatThrownBy(() -> + new AccountStartSessionWorldParticipationHistoricalReadEvidence( + request, + PARTICIPATION_ID, + 0L, + GAME_SESSION_ATTEMPT_ID, + 37L, + GAME_INSTANCE_ID, + PREPARATION_INPUT, + digest(PREPARATION_INPUT))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("fence must be positive"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementGrpcCodecTest.java index f48fdf3d93..afe9a20895 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationSettlementGrpcCodecTest.java @@ -79,51 +79,42 @@ void rejectsDuplicateUnknownChangedAndNoncanonicalRequestFields() { var input = input(); var request = AccountStartSessionWorldParticipationSettlementGrpcCodec.toRequest(input); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest( - request.toBuilder().addAccountWorldParticipationFence("32").build(), NAMESPACE)) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest( + request.toBuilder().addAccountWorldParticipationFence("32").build(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest( - request.toBuilder().setTargetNamespace(0, "another-runtime").build(), - NAMESPACE)) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest( + request.toBuilder().setTargetNamespace(0, "another-runtime").build(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest( - request.toBuilder().setAccountWorldParticipationFence(0, "031").build(), - NAMESPACE)) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest( + request.toBuilder().setAccountWorldParticipationFence(0, "031").build(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest( - request.toBuilder() - .setAccountWorldParticipationFence(0, "9223372036854775808") - .build(), - NAMESPACE)) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest( + request.toBuilder() + .setAccountWorldParticipationFence(0, "9223372036854775808") + .build(), + NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest( - request.toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField( - 99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) - .build()) - .build(), - NAMESPACE)) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest( + request.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(), + NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest( - request.toBuilder() - .setSettlementRequestId(0, "00000000-0000-0000-0000-000000000000") - .build(), - NAMESPACE)) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequest( + request.toBuilder() + .setSettlementRequestId(0, "00000000-0000-0000-0000-000000000000") + .build(), + NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical non-nil UUID"); @@ -132,10 +123,9 @@ void rejectsDuplicateUnknownChangedAndNoncanonicalRequestFields() { AccountStartSessionWorldParticipationSettlementGrpcCodec.toRequest(input).toByteArray(), request.getSerializedSize() + 1); noncanonicalWire[noncanonicalWire.length - 1] = 0; - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequestWireBytes( - noncanonicalWire, NAMESPACE)) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequestWireBytes( + noncanonicalWire, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); byte[] outOfOrderWire = @@ -147,10 +137,9 @@ void rejectsDuplicateUnknownChangedAndNoncanonicalRequestFields() { .build() .toByteArray(), request.toBuilder().clearAccountWorldParticipationFence().build().toByteArray()); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequestWireBytes( - outOfOrderWire, NAMESPACE)) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromRequestWireBytes( + outOfOrderWire, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("not canonical"); } @@ -161,77 +150,68 @@ void responseMustEchoLookupIdentityAndBindTerminalToParticipationAndNamespace() var terminal = terminal(NAMESPACE, PARTICIPATION_ID, 31L, Outcome.ABORTED); var valid = response(input, terminal, "2026-10-11T00:00:00.000001Z"); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( - input, - valid.toBuilder() - .setSettlementRequestId( - 0, uuid("e2a52c0c-c71f-4900-b1f2-c78f8b512a63").toString()) - .build())) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( + input, + valid.toBuilder() + .setSettlementRequestId( + 0, uuid("e2a52c0c-c71f-4900-b1f2-c78f8b512a63").toString()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("identity"); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( - input, - valid.toBuilder().setSettledAt(0, "2026-10-11T00:00:00.000000001Z").build())) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( + input, valid.toBuilder().setSettledAt(0, "2026-10-11T00:00:00.000000001Z").build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("microseconds"); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( - input, - valid.toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField( - 99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) - .build()) - .build())) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( + input, + valid.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( + input, + response( input, - response( - input, - terminal( - NAMESPACE, - uuid("e2a52c0c-c71f-4900-b1f2-c78f8b512a63"), - 31L, - Outcome.COMMITTED), - "2026-10-11T00:00:00.000001Z"))) + terminal( + NAMESPACE, + uuid("e2a52c0c-c71f-4900-b1f2-c78f8b512a63"), + 31L, + Outcome.COMMITTED), + "2026-10-11T00:00:00.000001Z"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact Account participation"); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( + input, + response( input, - response( - input, - terminal(NAMESPACE, PARTICIPATION_ID, 32L, Outcome.COMMITTED), - "2026-10-11T00:00:00.000001Z"))) + terminal(NAMESPACE, PARTICIPATION_ID, 32L, Outcome.COMMITTED), + "2026-10-11T00:00:00.000001Z"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact Account participation"); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( + input, + response( input, - response( - input, - terminal("another-runtime", PARTICIPATION_ID, 31L, Outcome.COMMITTED), - "2026-10-11T00:00:00.000001Z"))) + terminal("another-runtime", PARTICIPATION_ID, 31L, Outcome.COMMITTED), + "2026-10-11T00:00:00.000001Z"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact Account participation"); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( - input, - valid.toBuilder() - .setTerminalEvidenceCanonicalBytes(0, ByteString.copyFromUtf8("{}")) - .build())) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( + input, + valid.toBuilder() + .setTerminalEvidenceCanonicalBytes(0, ByteString.copyFromUtf8("{}")) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -253,22 +233,20 @@ void responseWireBytesMustUseCanonicalFieldOrder() { .toByteArray(), response.toBuilder().clearTerminalEvidenceCanonicalBytes().build().toByteArray()); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponseWireBytes( - input, outOfOrderWire)) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponseWireBytes( + input, outOfOrderWire)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("not canonical"); } @Test void rejectsIncompleteEvidenceAndTimestampPrecisionLoss() { - assertThatThrownBy( - () -> - new AccountStartSessionWorldParticipationSettlementEvidence( - SETTLEMENT_REQUEST_ID, - terminal(NAMESPACE, PARTICIPATION_ID, 31L, Outcome.COMMITTED), - Instant.parse("2026-10-11T00:00:00.000000001Z"))) + assertThatThrownBy(() -> + new AccountStartSessionWorldParticipationSettlementEvidence( + SETTLEMENT_REQUEST_ID, + terminal(NAMESPACE, PARTICIPATION_ID, 31L, Outcome.COMMITTED), + Instant.parse("2026-10-11T00:00:00.000000001Z"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("preserve PostgreSQL microseconds"); @@ -282,10 +260,9 @@ void rejectsIncompleteEvidenceAndTimestampPrecisionLoss() { .addSettledAt("2026-10-11T00:00:00.000001Z") .addTerminalEvidenceCanonicalBytes(ByteString.EMPTY) .build(); - assertThatThrownBy( - () -> - AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( - input, incomplete)) + assertThatThrownBy(() -> + AccountStartSessionWorldParticipationSettlementGrpcCodec.fromResponse( + input, incomplete)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java index f7693d6a4c..d3941b12d7 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java @@ -95,11 +95,10 @@ void actualMtlsPreservesLargeCompleteProtectionAndTerminalAcrossExactReplay() th var evidence = AccountInitialAdmissionSettlementReadGrpcCodecTest.evidence(Outcome.COMMITTED, true); assertThat(evidence.protection().canonicalBytes().length).isGreaterThan(4 * 1024 * 1024); - responder.set( - input -> - AccountInitialAdmissionSettlementReadGrpcCodec.toResponse( - new AccountInitialAdmissionSettlementReadEvidence( - input.readRequestId(), input.protection(), evidence.terminal()))); + responder.set(input -> + AccountInitialAdmissionSettlementReadGrpcCodec.toResponse( + new AccountInitialAdmissionSettlementReadEvidence( + input.readRequestId(), input.protection(), evidence.terminal()))); start("gs"); client = newClient("account", NAMESPACE); client.init(); @@ -167,9 +166,8 @@ void nativeTransportStatusesRemainUnchangedAndNoAutomaticRetryOccurs() throws Ex failure.set(status); int previous = bodies.get(); assertThatThrownBy(() -> client.read(evidence.input())) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()).isEqualTo(status.getCode())); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()).isEqualTo(status.getCode())); assertThat(bodies.get()).isEqualTo(previous + 1); } } @@ -190,10 +188,9 @@ private void assertWrongServer(String identity) throws Exception { client.init(); var input = AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED).input(); assertThatThrownBy(() -> client.read(input)) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(bodies.get()).isZero(); } @@ -204,10 +201,9 @@ void controlledReceiverRefusesNonAccountCertificateBeforeEvidenceDecode() throws client.init(); var input = AccountInitialAdmissionSettlementTestFixtures.evidence(Outcome.COMMITTED).input(); assertThatThrownBy(() -> client.read(input)) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); assertThat(bodies.get()).isZero(); } @@ -239,23 +235,20 @@ void requiresFileBackedTlsAndExplicitInitializationBeforeChannelUse() throws Exc var factory = mock(GrpcChannelFactory.class); var tls = LoopbackMtlsTestPki.placeholderTls(directory); tls.setPlaintext(true); - assertThatThrownBy( - () -> - new GrpcAccountInitialAdmissionSettlementReadClient( - new ServiceEndpointsProperties(), tls, factory, NAMESPACE)) + assertThatThrownBy(() -> + new GrpcAccountInitialAdmissionSettlementReadClient( + new ServiceEndpointsProperties(), tls, factory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); tls.setPlaintext(false); tls.setCertChain("classpath:client.crt"); - assertThatThrownBy( - () -> - new GrpcAccountInitialAdmissionSettlementReadClient( - new ServiceEndpointsProperties(), tls, factory, NAMESPACE)) + assertThatThrownBy(() -> + new GrpcAccountInitialAdmissionSettlementReadClient( + new ServiceEndpointsProperties(), tls, factory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); tls.setCertChain(directory.resolve("absent.crt").toString()); - assertThatThrownBy( - () -> - new GrpcAccountInitialAdmissionSettlementReadClient( - new ServiceEndpointsProperties(), tls, factory, NAMESPACE)) + assertThatThrownBy(() -> + new GrpcAccountInitialAdmissionSettlementReadClient( + new ServiceEndpointsProperties(), tls, factory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); client = new GrpcAccountInitialAdmissionSettlementReadClient( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionAcquisitionClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionAcquisitionClientTest.java index f78a87bea2..a0dad774d2 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionAcquisitionClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionActivationProtectionAcquisitionClientTest.java @@ -134,11 +134,10 @@ void closeDrainsAnActiveReloadCallbackWithoutHoldingTheClientMonitor(ClientKind .isTrue(); closeResult = - closeExecutor.submit( - () -> { - lifecycle.close().run(); - return null; - }); + closeExecutor.submit(() -> { + lifecycle.close().run(); + return null; + }); assertThat(awaitCondition(() -> !controlledWatcher.isRunning(), 5, TimeUnit.SECONDS)) .as("close reaches watcher shutdown while the callback is active") .isTrue(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionWorldParticipationSettlementClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionWorldParticipationSettlementClientTest.java index 6f31995664..7285e6bb0a 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionWorldParticipationSettlementClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountStartSessionWorldParticipationSettlementClientTest.java @@ -125,12 +125,11 @@ void closeReleasesClientMonitorBeforeDrainingCertificateCallback(@TempDir Path d eq(6565), any(CommonGrpcClientProperties.class), eq(true))) - .thenAnswer( - invocation -> { - ManagedChannel channel = mock(ManagedChannel.class); - channels.add(channel); - return channel; - }); + .thenAnswer(invocation -> { + ManagedChannel channel = mock(ManagedChannel.class); + channels.add(channel); + return channel; + }); client = new GrpcAccountStartSessionWorldParticipationSettlementClient( endpoints, tls, channelFactory, "world-runtime"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderClientTest.java index 89b40f3e9d..ce30d5fc00 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/AccountOriginalDraftOrderClientTest.java @@ -36,10 +36,9 @@ void requiresReadableFileBackedMutualTlsAndNamespace(@TempDir Path directory) th var factory = mock(GrpcChannelFactory.class); var tls = tls(directory); tls.setPlaintext(true); - assertThatThrownBy( - () -> - new AccountOriginalDraftOrderClient( - new ServiceEndpointsProperties(), tls, factory, "test")) + assertThatThrownBy(() -> + new AccountOriginalDraftOrderClient( + new ServiceEndpointsProperties(), tls, factory, "test")) .isInstanceOf(IllegalArgumentException.class); tls.setPlaintext(false); for (String bad : @@ -51,17 +50,15 @@ void requiresReadableFileBackedMutualTlsAndNamespace(@TempDir Path directory) th directory.resolve("missing.pem").toString() }) { tls.setCertChain(bad); - assertThatThrownBy( - () -> - new AccountOriginalDraftOrderClient( - new ServiceEndpointsProperties(), tls, factory, "test")) + assertThatThrownBy(() -> + new AccountOriginalDraftOrderClient( + new ServiceEndpointsProperties(), tls, factory, "test")) .isInstanceOf(IllegalArgumentException.class); } var valid = tls(directory); - assertThatThrownBy( - () -> - new AccountOriginalDraftOrderClient( - new ServiceEndpointsProperties(), valid, factory, "Test")) + assertThatThrownBy(() -> + new AccountOriginalDraftOrderClient( + new ServiceEndpointsProperties(), valid, factory, "Test")) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(factory); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBindingCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBindingCodecTest.java index 742d00dea7..dc84385909 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBindingCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftAuthorizationFenceBindingCodecTest.java @@ -71,16 +71,15 @@ void recentReauthenticationPolicySourcesUseOnlyClosedScopesAndRoundTripExactly() for (String unsupportedScope : List.of("PLATFORM", "OTHER/PLATFORM", "SELF_SERVICE_GAME_CREATION/OTHER")) { - assertThatThrownBy( - () -> - new SourceEvidence( - SourceKind.RECENT_REAUTH_POLICY, - unsupportedScope, - null, - "1", - null, - null, - new byte[] {1})) + assertThatThrownBy(() -> + new SourceEvidence( + SourceKind.RECENT_REAUTH_POLICY, + unsupportedScope, + null, + "1", + null, + null, + new byte[] {1})) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Unsupported recent reauthentication policy scope"); } @@ -90,16 +89,15 @@ void recentReauthenticationPolicySourcesUseOnlyClosedScopesAndRoundTripExactly() void recentReauthenticationPolicySourcesRejectInventedGenerationAndCheckpoints() { for (var fields : List.of(new String[] {"1", null, null}, new String[] {null, "invented-stream", "1"})) { - assertThatThrownBy( - () -> - new SourceEvidence( - SourceKind.RECENT_REAUTH_POLICY, - "SELF_SERVICE_GAME_CREATION/PLATFORM", - fields[0], - "1", - fields[1], - fields[2], - new byte[] {1})) + assertThatThrownBy(() -> + new SourceEvidence( + SourceKind.RECENT_REAUTH_POLICY, + "SELF_SERVICE_GAME_CREATION/PLATFORM", + fields[0], + "1", + fields[1], + fields[2], + new byte[] {1})) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Reauthentication policy has no generation or checkpoint"); } @@ -249,19 +247,15 @@ void v2OwnerReadbackUsesMatchingVersionAndOnlyAllowsRequiredOwners() { case 6 -> utf8("sha256:" + "f".repeat(64)); default -> binding(List.of(source())).canonicalBytes(); }); - assertThatThrownBy( - () -> - DraftAuthorizationFenceBinding.OwnerReadback.fromStored( - writeFrames(changedBinding))) + assertThatThrownBy(() -> + DraftAuthorizationFenceBinding.OwnerReadback.fromStored(writeFrames(changedBinding))) .isInstanceOf(IllegalArgumentException.class); } var mismatchedVersion = new ArrayList<>(frames); mismatchedVersion.set(0, utf8("account-draft-owner-readback/v1")); - assertThatThrownBy( - () -> - DraftAuthorizationFenceBinding.OwnerReadback.fromStored( - writeFrames(mismatchedVersion))) + assertThatThrownBy(() -> + DraftAuthorizationFenceBinding.OwnerReadback.fromStored(writeFrames(mismatchedVersion))) .isInstanceOf(IllegalArgumentException.class); var changedResult = new ArrayList<>(frames); @@ -435,15 +429,13 @@ void ownerReadbackRejectsCorruptFramingNoncanonicalFieldsAndContradictoryBinding () -> DraftAuthorizationFenceBinding.OwnerReadback.fromStored(writeFrames(fields))) .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - DraftAuthorizationFenceBinding.OwnerReadback.fromStored( - Arrays.copyOf(bytes, bytes.length - 1))) + assertThatThrownBy(() -> + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + Arrays.copyOf(bytes, bytes.length - 1))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - DraftAuthorizationFenceBinding.OwnerReadback.fromStored( - Arrays.copyOf(bytes, bytes.length + 1))) + assertThatThrownBy(() -> + DraftAuthorizationFenceBinding.OwnerReadback.fromStored( + Arrays.copyOf(bytes, bytes.length + 1))) .isInstanceOf(IllegalArgumentException.class); byte[] negative = bytes.clone(); ByteBuffer.wrap(negative).putInt(-1); @@ -457,10 +449,8 @@ void ownerReadbackRejectsCorruptFramingNoncanonicalFieldsAndContradictoryBinding var expandedV1Owner = readFrames(bytes); expandedV1Owner.set(1, utf8("ENTITY")); - assertThatThrownBy( - () -> - DraftAuthorizationFenceBinding.OwnerReadback.fromStored( - writeFrames(expandedV1Owner))) + assertThatThrownBy(() -> + DraftAuthorizationFenceBinding.OwnerReadback.fromStored(writeFrames(expandedV1Owner))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClientMtlsTest.java index cf7ec43736..00e4219ca2 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClientMtlsTest.java @@ -92,10 +92,9 @@ void trustedWrongAccountWorkloadAndNamespaceCannotReachTheHeldOwner() throws Exc assertThatThrownBy(() -> client.read(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(server.rpcStarts()).as(identity.alias()).hasValue(0); assertThat(server.ownerReads()).as(identity.alias()).hasValue(0); assertThat(server.clientPeerUri().get()).isNull(); @@ -114,12 +113,10 @@ void requiresAClientCertificateAndRejectsPlaintextOrMissingCertificateConfigurat new GrpcChannelFactory() .buildChannel("127.0.0.1:" + server.port(), 6565, noClientCertificate, false); try { - assertThatThrownBy( - () -> - AccountDraftCommitOrderReadServiceGrpc.newBlockingStub(channel) - .withDeadlineAfter(3, TimeUnit.SECONDS) - .readHeldOriginalCommitOrder( - DraftCommitOrderReadGrpcCodec.toRequest(request))) + assertThatThrownBy(() -> + AccountDraftCommitOrderReadServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .readHeldOriginalCommitOrder(DraftCommitOrderReadGrpcCodec.toRequest(request))) .satisfies( failure -> assertThat(isMissingClientCertificateHandshake(failure)).isTrue()); assertThat(server.rpcStarts()).hasValue(0); @@ -131,23 +128,21 @@ void requiresAClientCertificateAndRejectsPlaintextOrMissingCertificateConfigurat CommonGrpcClientProperties plaintext = pki.clientProperties(tempDirectory, pki.worldClient()); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new DraftCommitOrderReadClient( - endpoints(server.port()), plaintext, new GrpcChannelFactory(), NAMESPACE)) + assertThatThrownBy(() -> + new DraftCommitOrderReadClient( + endpoints(server.port()), plaintext, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("workload mTLS"); CommonGrpcClientProperties missingCertificate = pki.clientProperties(tempDirectory, pki.worldClient()); missingCertificate.setCertChain(""); - assertThatThrownBy( - () -> - new DraftCommitOrderReadClient( - endpoints(server.port()), - missingCertificate, - new GrpcChannelFactory(), - NAMESPACE)) + assertThatThrownBy(() -> + new DraftCommitOrderReadClient( + endpoints(server.port()), + missingCertificate, + new GrpcChannelFactory(), + NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("file-backed"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClientTest.java index afcd922f9b..8dad6cb1bf 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadClientTest.java @@ -50,10 +50,9 @@ void rejectsPlaintextWrongNamespaceAndUninitializedCallsBeforeTransport(@TempDir var factory = mock(GrpcChannelFactory.class); var plaintext = tls(directory); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new DraftCommitOrderReadClient( - new ServiceEndpointsProperties(), plaintext, factory, "test")) + assertThatThrownBy(() -> + new DraftCommitOrderReadClient( + new ServiceEndpointsProperties(), plaintext, factory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("workload mTLS"); @@ -153,12 +152,11 @@ void closeReleasesClientMonitorBeforeDrainingCertificateCallback(@TempDir Path d eq(6565), any(CommonGrpcClientProperties.class), eq(true))) - .thenAnswer( - invocation -> { - ManagedChannel channel = mock(ManagedChannel.class); - channels.add(channel); - return channel; - }); + .thenAnswer(invocation -> { + ManagedChannel channel = mock(ManagedChannel.class); + channels.add(channel); + return channel; + }); client = new DraftCommitOrderReadClient(endpoints, tls, factory, "test"); client.init(); DraftCommitOrderReadClient clientUnderTest = client; diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadGrpcCodecTest.java index 19ac65a8c6..a156d9f09f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftCommitOrderReadGrpcCodecTest.java @@ -40,21 +40,18 @@ void rejectsMalformedRequestsUnknownFieldsAndNonCanonicalReadIdentity() { .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); - assertThatThrownBy( - () -> - DraftCommitOrderReadGrpcCodec.fromRequest( - request.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + DraftCommitOrderReadGrpcCodec.fromRequest( + request.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - DraftCommitOrderReadGrpcCodec.fromRequest( - request.toBuilder().setReadRequestId("not-a-uuid").build())) + assertThatThrownBy(() -> + DraftCommitOrderReadGrpcCodec.fromRequest( + request.toBuilder().setReadRequestId("not-a-uuid").build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - DraftCommitOrderReadGrpcCodec.fromRequest( - request.toBuilder().setSchemaVersion(2).build())) + assertThatThrownBy(() -> + DraftCommitOrderReadGrpcCodec.fromRequest( + request.toBuilder().setSchemaVersion(2).build())) .isInstanceOf(IllegalArgumentException.class); } @@ -62,10 +59,9 @@ void rejectsMalformedRequestsUnknownFieldsAndNonCanonicalReadIdentity() { void rejectsOversizedOriginalBindingBeforeCanonicalParsing() { byte[] oversized = new byte[WorldOriginalDraftGraphApplyEvidence.MAX_BINDING_BYTES + 1]; - assertThatThrownBy( - () -> - new DraftCommitOrderReadEvidence.Request( - 1, "test", UUID.fromString("33333333-3333-4333-8333-333333333333"), oversized)) + assertThatThrownBy(() -> + new DraftCommitOrderReadEvidence.Request( + 1, "test", UUID.fromString("33333333-3333-4333-8333-333333333333"), oversized)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Complete original Account binding exceeds size limit"); assertThatThrownBy(() -> DraftCommitOrderReadEvidence.Request.create("test", oversized)) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftTerminalReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftTerminalReadClientMtlsTest.java index e566d0664d..94f9c4011f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftTerminalReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/DraftTerminalReadClientMtlsTest.java @@ -82,17 +82,15 @@ void gameDesignClientAcceptsBoundedResponseAboveOldFourMiBTransportLimit() throw client.init(); var configuredStub = gameDesignStub(client); - assertThatThrownBy( - () -> - configuredStub - .withMaxInboundMessageSize(4 * 1024 * 1024) - .readGameDesignDraftTerminalOutcome( - GameDesignDraftTerminalReadGrpcCodec.toRequest(request))) + assertThatThrownBy(() -> + configuredStub + .withMaxInboundMessageSize(4 * 1024 * 1024) + .readGameDesignDraftTerminalOutcome( + GameDesignDraftTerminalReadGrpcCodec.toRequest(request))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.RESOURCE_EXHAUSTED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.RESOURCE_EXHAUSTED)); var actual = client.read(request); assertThat(actual.ownerReadback().orElseThrow().canonicalBytes()) @@ -116,17 +114,15 @@ void worldClientAcceptsBoundedResponseAboveOldFourMiBTransportLimit() throws Exc client.init(); var configuredStub = worldStub(client); - assertThatThrownBy( - () -> - configuredStub - .withMaxInboundMessageSize(4 * 1024 * 1024) - .readWorldDraftTerminalOutcome( - WorldDraftTerminalReadGrpcCodec.toRequest(request))) + assertThatThrownBy(() -> + configuredStub + .withMaxInboundMessageSize(4 * 1024 * 1024) + .readWorldDraftTerminalOutcome( + WorldDraftTerminalReadGrpcCodec.toRequest(request))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.RESOURCE_EXHAUSTED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.RESOURCE_EXHAUSTED)); var actual = client.read(request); assertThat(actual.ownerReadback().orElseThrow().canonicalBytes()) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadClientTest.java index f87da93668..4558f30392 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadClientTest.java @@ -37,10 +37,9 @@ void rejectsPlaintextBeforeCreatingChannel(@TempDir Path directory) throws Excep CommonGrpcClientProperties tls = tls(directory); tls.setPlaintext(true); - assertThatThrownBy( - () -> - new GameDesignDraftTerminalReadClient( - new ServiceEndpointsProperties(), tls, channelFactory, "test")) + assertThatThrownBy(() -> + new GameDesignDraftTerminalReadClient( + new ServiceEndpointsProperties(), tls, channelFactory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("workload mTLS"); verifyNoInteractions(channelFactory); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadGrpcCodecTest.java index 85fc347b89..54318274d0 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/GameDesignDraftTerminalReadGrpcCodecTest.java @@ -55,10 +55,9 @@ void terminalReadbackAllowsMoreThanBindingLimitAndEnforcesProducerAndConsumerBou binding.inputDigest(), request.originalAccountBinding(), new byte[DraftTerminalReadGrpcLimits.MAX_OWNER_READBACK_BYTES]); - assertThatThrownBy( - () -> - GameDesignDraftTerminalReadGrpcCodec.toResponse( - request, Optional.of(oversizedReadback))) + assertThatThrownBy(() -> + GameDesignDraftTerminalReadGrpcCodec.toResponse( + request, Optional.of(oversizedReadback))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("owner readback"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClientTest.java index b7ba3a3a01..f4cee89e60 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldAuthoredVersionIdentityClientTest.java @@ -32,23 +32,20 @@ void refusesPlaintextMissingMaterialAndClasspathBeforeTransport(@TempDir Path di var factory = mock(GrpcChannelFactory.class); var tls = tls(directory); tls.setPlaintext(true); - assertThatThrownBy( - () -> - new WorldAuthoredVersionIdentityClient( - new ServiceEndpointsProperties(), tls, factory, "test")) + assertThatThrownBy(() -> + new WorldAuthoredVersionIdentityClient( + new ServiceEndpointsProperties(), tls, factory, "test")) .isInstanceOf(IllegalArgumentException.class); tls.setPlaintext(false); tls.setCaCert("classpath:ca.crt"); - assertThatThrownBy( - () -> - new WorldAuthoredVersionIdentityClient( - new ServiceEndpointsProperties(), tls, factory, "test")) + assertThatThrownBy(() -> + new WorldAuthoredVersionIdentityClient( + new ServiceEndpointsProperties(), tls, factory, "test")) .isInstanceOf(IllegalArgumentException.class); tls.setCaCert(directory.resolve("missing.crt").toString()); - assertThatThrownBy( - () -> - new WorldAuthoredVersionIdentityClient( - new ServiceEndpointsProperties(), tls, factory, "test")) + assertThatThrownBy(() -> + new WorldAuthoredVersionIdentityClient( + new ServiceEndpointsProperties(), tls, factory, "test")) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(factory); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadClientTest.java index 2c3eec91b6..802a9193c6 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadClientTest.java @@ -30,10 +30,9 @@ void rejectsPlaintextBeforeCreatingAChannel(@TempDir Path directory) throws Exce CommonGrpcClientProperties tls = tls(directory); tls.setPlaintext(true); - assertThatThrownBy( - () -> - new WorldDraftTerminalReadClient( - new ServiceEndpointsProperties(), tls, channelFactory, "test")) + assertThatThrownBy(() -> + new WorldDraftTerminalReadClient( + new ServiceEndpointsProperties(), tls, channelFactory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("workload mTLS"); verifyNoInteractions(channelFactory); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java index e34958050f..b5a5ae45e0 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldDraftTerminalReadGrpcCodecTest.java @@ -180,9 +180,8 @@ void terminalReadbackAllowsMoreThanBindingLimitAndEnforcesProducerAndConsumerBou binding.inputDigest(), request.originalAccountBinding(), new byte[DraftTerminalReadGrpcLimits.MAX_OWNER_READBACK_BYTES]); - assertThatThrownBy( - () -> - WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(oversizedReadback))) + assertThatThrownBy(() -> + WorldDraftTerminalReadGrpcCodec.toResponse(request, Optional.of(oversizedReadback))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("owner readback"); @@ -222,40 +221,37 @@ void exactAbortMustBeWorldAndMustEchoEveryRequestFieldAndOriginalBinding() { assertThat(decodedAbort.canonicalBytes()).containsExactly(abort.canonicalBytes()); assertThat(decodedAbort.fullBinding()).containsExactly(request.originalAccountBinding()); assertThat(decodedAbort.result()).containsExactly(1, 2, 3); - assertThatThrownBy( - () -> - WorldDraftTerminalReadGrpcCodec.toResponse( - request, - Optional.of( - new DraftAuthorizationFenceBinding.OwnerReadback( - Owner.GAME_DESIGN, - Outcome.DEFINITIVELY_ABORTED, - binding.operationId(), - binding.commitId(), - binding.fenceId(), - binding.inputDigest(), - request.originalAccountBinding(), - new byte[] {1})))) + assertThatThrownBy(() -> + WorldDraftTerminalReadGrpcCodec.toResponse( + request, + Optional.of( + new DraftAuthorizationFenceBinding.OwnerReadback( + Owner.GAME_DESIGN, + Outcome.DEFINITIVELY_ABORTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + request.originalAccountBinding(), + new byte[] {1})))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("World terminal response"); - assertThatThrownBy( - () -> - WorldDraftTerminalReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setReadRequestId(uuid("77777777-7777-4777-8777-777777777777").toString()) - .build())) + assertThatThrownBy(() -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setReadRequestId(uuid("77777777-7777-4777-8777-777777777777").toString()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("changed the exact read request"); - assertThatThrownBy( - () -> - WorldDraftTerminalReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setOriginalAccountBinding( - com.google.protobuf.ByteString.copyFrom(new byte[] {9})) - .build())) + assertThatThrownBy(() -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(new byte[] {9})) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("changed the exact read request"); } @@ -264,16 +260,14 @@ void exactAbortMustBeWorldAndMustEchoEveryRequestFieldAndOriginalBinding() { void rejectsUnknownFieldsAndContradictoryStatusPayloads() { var request = request(); var encoded = WorldDraftTerminalReadGrpcCodec.toRequest(request); - assertThatThrownBy( - () -> - WorldDraftTerminalReadGrpcCodec.fromRequest( - encoded.toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField( - 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) - .build()) - .build())) + assertThatThrownBy(() -> + WorldDraftTerminalReadGrpcCodec.fromRequest( + encoded.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); @@ -299,15 +293,14 @@ void exactCommittedCarrierRoundTripsAndRejectsStatusOwnerResultAndFullBindingSub .containsExactly(committed.canonicalBytes()); assertThat(evidence.appliedIntakeRequestId()) .isEqualTo(uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")); - assertThatThrownBy( - () -> - WorldDraftTerminalReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setStatus( - WorldDraftTerminalReadStatus - .WORLD_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED) - .build())) + assertThatThrownBy(() -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setStatus( + WorldDraftTerminalReadStatus + .WORLD_DRAFT_TERMINAL_READ_STATUS_DEFINITIVELY_ABORTED) + .build())) .hasMessageContaining("status differs"); var abort = new DraftAuthorizationFenceBinding.OwnerReadback( @@ -319,14 +312,13 @@ void exactCommittedCarrierRoundTripsAndRejectsStatusOwnerResultAndFullBindingSub committed.inputDigest(), committed.fullBinding(), new byte[] {1}); - assertThatThrownBy( - () -> - WorldDraftTerminalReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setOwnerReadbackBytes( - com.google.protobuf.ByteString.copyFrom(abort.canonicalBytes())) - .build())) + assertThatThrownBy(() -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOwnerReadbackBytes( + com.google.protobuf.ByteString.copyFrom(abort.canonicalBytes())) + .build())) .hasMessageContaining("status differs"); var wrongOwner = new DraftAuthorizationFenceBinding.OwnerReadback( @@ -338,14 +330,13 @@ void exactCommittedCarrierRoundTripsAndRejectsStatusOwnerResultAndFullBindingSub committed.inputDigest(), committed.fullBinding(), committed.result()); - assertThatThrownBy( - () -> - WorldDraftTerminalReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setOwnerReadbackBytes( - com.google.protobuf.ByteString.copyFrom(wrongOwner.canonicalBytes())) - .build())) + assertThatThrownBy(() -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOwnerReadbackBytes( + com.google.protobuf.ByteString.copyFrom(wrongOwner.canonicalBytes())) + .build())) .hasMessageContaining("World terminal response"); var substituted = new DraftAuthorizationFenceBinding.OwnerReadback( @@ -357,28 +348,25 @@ void exactCommittedCarrierRoundTripsAndRejectsStatusOwnerResultAndFullBindingSub committed.inputDigest(), committed.fullBinding(), new byte[] {1, 2, 3}); - assertThatThrownBy( - () -> - WorldDraftTerminalReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setOwnerReadbackBytes( - com.google.protobuf.ByteString.copyFrom(substituted.canonicalBytes())) - .build())) + assertThatThrownBy(() -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOwnerReadbackBytes( + com.google.protobuf.ByteString.copyFrom(substituted.canonicalBytes())) + .build())) .hasMessageContaining("substituted canonical APPLIED result"); - assertThatThrownBy( - () -> - WorldDraftTerminalReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setOriginalAccountBinding( - com.google.protobuf.ByteString.copyFrom(new byte[] {9})) - .build())) + assertThatThrownBy(() -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setOriginalAccountBinding( + com.google.protobuf.ByteString.copyFrom(new byte[] {9})) + .build())) .hasMessageContaining("changed the exact read request"); - assertThatThrownBy( - () -> - WorldDraftTerminalReadGrpcCodec.fromResponse( - request, response.toBuilder().clearOwnerReadbackBytes().build())) + assertThatThrownBy(() -> + WorldDraftTerminalReadGrpcCodec.fromResponse( + request, response.toBuilder().clearOwnerReadbackBytes().build())) .hasMessageContaining("bytes are required"); } @@ -711,10 +699,9 @@ private static void reverseFirstTwoInboundFamilies( } private static void assertGraph3Rejected(Graph3Fixture fixture) { - assertThatThrownBy( - () -> - WorldDraftTerminalReadGrpcCodec.toResponse( - fixture.request(), Optional.of(fixture.readback()))) + assertThatThrownBy(() -> + WorldDraftTerminalReadGrpcCodec.toResponse( + fixture.request(), Optional.of(fixture.readback()))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("invalid or substituted canonical APPLIED result"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyClientTest.java index 54875f86b0..d315488032 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyClientTest.java @@ -67,12 +67,11 @@ void closeReleasesClientMonitorBeforeDrainingCertificateCallback(@TempDir Path d GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); when(channelFactory.buildChannel( eq("world.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) - .thenAnswer( - invocation -> { - ManagedChannel channel = mock(ManagedChannel.class); - channels.add(channel); - return channel; - }); + .thenAnswer(invocation -> { + ManagedChannel channel = mock(ManagedChannel.class); + channels.add(channel); + return channel; + }); client = new WorldOriginalDraftGraphApplyClient(endpoints, tls, channelFactory, "test"); client.init(); WorldOriginalDraftGraphApplyClient clientUnderTest = client; @@ -204,23 +203,20 @@ void refusesPlaintextMissingMaterialAndClasspathBeforeTransport(@TempDir Path di var factory = mock(GrpcChannelFactory.class); var tls = tls(directory); tls.setPlaintext(true); - assertThatThrownBy( - () -> - new WorldOriginalDraftGraphApplyClient( - new ServiceEndpointsProperties(), tls, factory, "test")) + assertThatThrownBy(() -> + new WorldOriginalDraftGraphApplyClient( + new ServiceEndpointsProperties(), tls, factory, "test")) .isInstanceOf(IllegalArgumentException.class); tls.setPlaintext(false); tls.setCaCert("classpath:ca.crt"); - assertThatThrownBy( - () -> - new WorldOriginalDraftGraphApplyClient( - new ServiceEndpointsProperties(), tls, factory, "test")) + assertThatThrownBy(() -> + new WorldOriginalDraftGraphApplyClient( + new ServiceEndpointsProperties(), tls, factory, "test")) .isInstanceOf(IllegalArgumentException.class); tls.setCaCert(directory.resolve("missing.crt").toString()); - assertThatThrownBy( - () -> - new WorldOriginalDraftGraphApplyClient( - new ServiceEndpointsProperties(), tls, factory, "test")) + assertThatThrownBy(() -> + new WorldOriginalDraftGraphApplyClient( + new ServiceEndpointsProperties(), tls, factory, "test")) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(factory); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyGrpcCodecTest.java index fab1c9aef5..9bd1fdb639 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/authoring/WorldOriginalDraftGraphApplyGrpcCodecTest.java @@ -104,16 +104,14 @@ void rejectsUnsupportedOwnersSchemasNamespaceAndUnboundedOrUnknownInput() { () -> new WorldOriginalDraftGraphApplyEvidence.Request(2, "test", binding(true))) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> request("INVALID")).isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldOriginalDraftGraphApplyEvidence.Request.create( - "test", new byte[WorldOriginalDraftGraphApplyEvidence.MAX_BINDING_BYTES + 1])) + assertThatThrownBy(() -> + WorldOriginalDraftGraphApplyEvidence.Request.create( + "test", new byte[WorldOriginalDraftGraphApplyEvidence.MAX_BINDING_BYTES + 1])) .isInstanceOf(IllegalArgumentException.class); var wire = WorldOriginalDraftGraphApplyGrpcCodec.toRequest(request("test")); - assertThatThrownBy( - () -> - WorldOriginalDraftGraphApplyGrpcCodec.fromRequest( - wire.toBuilder().setUnknownFields(unknown()).build())) + assertThatThrownBy(() -> + WorldOriginalDraftGraphApplyGrpcCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknown()).build())) .isInstanceOf(IllegalArgumentException.class); } @@ -139,25 +137,23 @@ void rejectsEveryEchoSubstitutionEmptyOutcomeAndUnknownResponse() { void rejectsAbortOtherOwnerFullBindingAndAppliedEpochSubstitution() throws Exception { var request = request("test"); var committed = committed(request); - assertThatThrownBy( - () -> - WorldOriginalDraftGraphApplyGrpcCodec.toResponse( - request, - changed( - committed, - DraftAuthorizationFenceBinding.Owner.WORLD, - DraftAuthorizationFenceBinding.Outcome.DEFINITIVELY_ABORTED, - committed.result()))) + assertThatThrownBy(() -> + WorldOriginalDraftGraphApplyGrpcCodec.toResponse( + request, + changed( + committed, + DraftAuthorizationFenceBinding.Owner.WORLD, + DraftAuthorizationFenceBinding.Outcome.DEFINITIVELY_ABORTED, + committed.result()))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldOriginalDraftGraphApplyGrpcCodec.toResponse( - request, - changed( - committed, - DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, - DraftAuthorizationFenceBinding.Outcome.COMMITTED, - committed.result()))) + assertThatThrownBy(() -> + WorldOriginalDraftGraphApplyGrpcCodec.toResponse( + request, + changed( + committed, + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + committed.result()))) .isInstanceOf(IllegalArgumentException.class); var alternate = request("other"); assertThatThrownBy(() -> WorldOriginalDraftGraphApplyGrpcCodec.toResponse(alternate, committed)) @@ -167,11 +163,9 @@ void rejectsAbortOtherOwnerFullBindingAndAppliedEpochSubstitution() throws Excep .put("resultingEpoch", "9"); var wrongEpoch = net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8(json.toString()); - assertThatThrownBy( - () -> - WorldOriginalDraftGraphApplyGrpcCodec.toResponse( - request, - changed(committed, committed.owner(), committed.outcome(), wrongEpoch))) + assertThatThrownBy(() -> + WorldOriginalDraftGraphApplyGrpcCodec.toResponse( + request, changed(committed, committed.owner(), committed.outcome(), wrongEpoch))) .isInstanceOf(IllegalArgumentException.class); var otherBinding = request.accountBinding(); var differentAccount = @@ -189,12 +183,11 @@ void rejectsAbortOtherOwnerFullBindingAndAppliedEpochSubstitution() throws Excep otherBinding.normalizedInput(), otherBinding.inputDigest(), otherBinding.sources()); - assertThatThrownBy( - () -> - WorldOriginalDraftGraphApplyGrpcCodec.toResponse( - WorldOriginalDraftGraphApplyEvidence.Request.create( - "test", differentAccount.canonicalBytes()), - committed)) + assertThatThrownBy(() -> + WorldOriginalDraftGraphApplyGrpcCodec.toResponse( + WorldOriginalDraftGraphApplyEvidence.Request.create( + "test", differentAccount.canonicalBytes()), + committed)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/automation/AutomationAuthoredSourceInventoryDeclarationTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/automation/AutomationAuthoredSourceInventoryDeclarationTest.java index c3219fe5bf..a2c2794e43 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/automation/AutomationAuthoredSourceInventoryDeclarationTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/automation/AutomationAuthoredSourceInventoryDeclarationTest.java @@ -84,15 +84,13 @@ void rejectsEveryNonemptyFamilyAsUnsupported() { void rejectsNullInputMalformedUnicodeAndOversizedInput() { assertThatThrownBy(() -> AutomationAuthoredSourceInventoryDeclaration.parse(null)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AutomationAuthoredSourceInventoryDeclaration.parse( - "\"" + String.valueOf((char) 0xD800) + "\"")) + assertThatThrownBy(() -> + AutomationAuthoredSourceInventoryDeclaration.parse( + "\"" + String.valueOf((char) 0xD800) + "\"")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AutomationAuthoredSourceInventoryDeclaration.parse( - " ".repeat(AutomationAuthoredSourceInventoryDeclaration.MAX_JSON_BYTES + 1))) + assertThatThrownBy(() -> + AutomationAuthoredSourceInventoryDeclaration.parse( + " ".repeat(AutomationAuthoredSourceInventoryDeclaration.MAX_JSON_BYTES + 1))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("too large"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/config/CommonCoreAutoConfigurationTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/config/CommonCoreAutoConfigurationTest.java index 8bb717d186..e58194a6a6 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/config/CommonCoreAutoConfigurationTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/config/CommonCoreAutoConfigurationTest.java @@ -26,32 +26,27 @@ class CommonCoreAutoConfigurationTest { void keepsDefaultReadinessPostProcessorWhenApplicationProvidesUnrelatedOne() { contextRunner .withUserConfiguration(CustomPostProcessorConfiguration.class) - .run( - context -> { - assertThat(context).hasBean("postProcessor"); - assertThat(context) - .hasSingleBean(TlsCertificateReadinessHealthEndpointGroupsPostProcessor.class); - assertThat(context.getBeansOfType(HealthEndpointGroupsPostProcessor.class)) - .hasSize(2); - assertThat( - context.getBean("tlsCertificateReadinessHealthEndpointGroupsPostProcessor")) - .isNotSameAs(context.getBean("postProcessor")); - }); + .run(context -> { + assertThat(context).hasBean("postProcessor"); + assertThat(context) + .hasSingleBean(TlsCertificateReadinessHealthEndpointGroupsPostProcessor.class); + assertThat(context.getBeansOfType(HealthEndpointGroupsPostProcessor.class)).hasSize(2); + assertThat(context.getBean("tlsCertificateReadinessHealthEndpointGroupsPostProcessor")) + .isNotSameAs(context.getBean("postProcessor")); + }); } @Test void backsOffReadinessPostProcessorWhenApplicationProvidesSameType() { contextRunner .withUserConfiguration(CustomTlsReadinessPostProcessorConfiguration.class) - .run( - context -> { - assertThat(context) - .hasSingleBean(TlsCertificateReadinessHealthEndpointGroupsPostProcessor.class); - assertThat( - context.getBean( - TlsCertificateReadinessHealthEndpointGroupsPostProcessor.class)) - .isSameAs(context.getBean("tlsReadinessPostProcessor")); - }); + .run(context -> { + assertThat(context) + .hasSingleBean(TlsCertificateReadinessHealthEndpointGroupsPostProcessor.class); + assertThat( + context.getBean(TlsCertificateReadinessHealthEndpointGroupsPostProcessor.class)) + .isSameAs(context.getBean("tlsReadinessPostProcessor")); + }); } @Test @@ -59,34 +54,19 @@ void bindsReadinessGatePropertyForTcpProxy() { contextRunner .withPropertyValues( "spring.application.name=tcp-proxy-service", "firemud.tls.readiness-gate.enabled=false") - .run( - context -> { - assertThat(context) - .hasBean( + .run(context -> { + assertThat(context) + .hasBean( + TlsCertificateReadinessHealthEndpointGroupsPostProcessor + .TLS_CERTIFICATE_RELOAD_CONTRIBUTOR); + assertThat( + context.getBean( TlsCertificateReadinessHealthEndpointGroupsPostProcessor - .TLS_CERTIFICATE_RELOAD_CONTRIBUTOR); - assertThat( - context.getBean( - TlsCertificateReadinessHealthEndpointGroupsPostProcessor - .TLS_CERTIFICATE_RELOAD_CONTRIBUTOR)) - .isInstanceOf(HealthIndicator.class); - assertThat(context) - .hasSingleBean(TlsCertificateReadinessHealthEndpointGroupsPostProcessor.class); - HealthEndpointGroups groups = mock(HealthEndpointGroups.class); - assertSame( - groups, - context - .getBean(TlsCertificateReadinessHealthEndpointGroupsPostProcessor.class) - .postProcessHealthEndpointGroups(groups)); - }); - } - - @Test - void defaultsReadinessGateToOff() { - contextRunner.run( - context -> { + .TLS_CERTIFICATE_RELOAD_CONTRIBUTOR)) + .isInstanceOf(HealthIndicator.class); + assertThat(context) + .hasSingleBean(TlsCertificateReadinessHealthEndpointGroupsPostProcessor.class); HealthEndpointGroups groups = mock(HealthEndpointGroups.class); - assertSame( groups, context @@ -95,38 +75,50 @@ void defaultsReadinessGateToOff() { }); } + @Test + void defaultsReadinessGateToOff() { + contextRunner.run(context -> { + HealthEndpointGroups groups = mock(HealthEndpointGroups.class); + + assertSame( + groups, + context + .getBean(TlsCertificateReadinessHealthEndpointGroupsPostProcessor.class) + .postProcessHealthEndpointGroups(groups)); + }); + } + @Test void enablesReadinessGateWhenExplicitlyConfigured() { contextRunner .withPropertyValues("firemud.tls.readiness-gate.enabled=true") - .run( - context -> { - assertThat(context) - .hasBean( + .run(context -> { + assertThat(context) + .hasBean( + TlsCertificateReadinessHealthEndpointGroupsPostProcessor + .TLS_CERTIFICATE_RELOAD_CONTRIBUTOR); + assertThat( + context.getBean( TlsCertificateReadinessHealthEndpointGroupsPostProcessor - .TLS_CERTIFICATE_RELOAD_CONTRIBUTOR); - assertThat( - context.getBean( - TlsCertificateReadinessHealthEndpointGroupsPostProcessor - .TLS_CERTIFICATE_RELOAD_CONTRIBUTOR)) - .isInstanceOf(HealthIndicator.class); - HealthEndpointGroups groups = mock(HealthEndpointGroups.class); - HealthEndpointGroup readiness = mock(HealthEndpointGroup.class); - when(groups.get("readiness")).thenReturn(readiness); + .TLS_CERTIFICATE_RELOAD_CONTRIBUTOR)) + .isInstanceOf(HealthIndicator.class); + HealthEndpointGroups groups = mock(HealthEndpointGroups.class); + HealthEndpointGroup readiness = mock(HealthEndpointGroup.class); + when(groups.get("readiness")).thenReturn(readiness); - HealthEndpointGroups processed = - context - .getBean(TlsCertificateReadinessHealthEndpointGroupsPostProcessor.class) - .postProcessHealthEndpointGroups(groups); + HealthEndpointGroups processed = + context + .getBean(TlsCertificateReadinessHealthEndpointGroupsPostProcessor.class) + .postProcessHealthEndpointGroups(groups); - assertThat(processed).isNotSameAs(groups); - assertThat( - Objects.requireNonNull(processed.get("readiness")) - .isMember( - TlsCertificateReadinessHealthEndpointGroupsPostProcessor - .TLS_CERTIFICATE_RELOAD_CONTRIBUTOR)) - .isTrue(); - }); + assertThat(processed).isNotSameAs(groups); + assertThat( + Objects.requireNonNull(processed.get("readiness")) + .isMember( + TlsCertificateReadinessHealthEndpointGroupsPostProcessor + .TLS_CERTIFICATE_RELOAD_CONTRIBUTOR)) + .isTrue(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/EntityAuthoredSourceInventoryDeclarationTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/EntityAuthoredSourceInventoryDeclarationTest.java index 5c34ee6e17..a3b3225293 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/EntityAuthoredSourceInventoryDeclarationTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/EntityAuthoredSourceInventoryDeclarationTest.java @@ -126,15 +126,13 @@ void rejectsEveryNonemptyFamilyAsUnsupported() { void rejectsNullInputMalformedUnicodeAndOversizedInput() { assertThatThrownBy(() -> EntityAuthoredSourceInventoryDeclaration.parse(null)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - EntityAuthoredSourceInventoryDeclaration.parse( - "\"" + String.valueOf((char) 0xD800) + "\"")) + assertThatThrownBy(() -> + EntityAuthoredSourceInventoryDeclaration.parse( + "\"" + String.valueOf((char) 0xD800) + "\"")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - EntityAuthoredSourceInventoryDeclaration.parse( - " ".repeat(EntityAuthoredSourceInventoryDeclaration.MAX_JSON_BYTES + 1))) + assertThatThrownBy(() -> + EntityAuthoredSourceInventoryDeclaration.parse( + " ".repeat(EntityAuthoredSourceInventoryDeclaration.MAX_JSON_BYTES + 1))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("too large"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodecTest.java index 1061b90c2c..03a19ae69c 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodecTest.java @@ -82,37 +82,33 @@ void rejectsWrongOwnerNamespaceAndChangedOriginalBindingOrFreeze() { var request = Request.create(NAMESPACE, fixture.authorization(), freeze); var wire = EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(request); - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( - wire.toBuilder().setIntakeAuthorizationDigest("0".repeat(64)).build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder().setIntakeAuthorizationDigest("0".repeat(64)).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("digest"); byte[] changedBinding = fixture.authorization().canonicalBytes(); changedBinding[changedBinding.length - 1] ^= 1; - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( - wire.toBuilder() - .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(changedBinding)) - .build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(changedBinding)) + .build())) .isInstanceOf(IllegalArgumentException.class); var changedFreezeRequest = wire.getFreezeRequest().toBuilder().setRequestDigest("0".repeat(64)).build(); - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( - wire.toBuilder().setFreezeRequest(changedFreezeRequest).build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder().setFreezeRequest(changedFreezeRequest).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("freeze"); var changedFreezeAck = wire.getFreezeAcknowledgement().toBuilder().setAppliedCommitId("0".repeat(36)).build(); - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( - wire.toBuilder().setFreezeAcknowledgement(changedFreezeAck).build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder().setFreezeAcknowledgement(changedFreezeAck).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("freeze"); } @@ -126,61 +122,54 @@ void rejectsUnknownFieldsOversizedWireAndChangedFullResponseEchoOrDigest() { UnknownFieldSet.newBuilder() .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( - requestWire.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + requestWire.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unknown"); - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( - requestWire.toBuilder() - .setFreezeAcknowledgement( - requestWire.getFreezeAcknowledgement().toBuilder() - .setUnknownFields(unknown) - .build()) - .build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + requestWire.toBuilder() + .setFreezeAcknowledgement( + requestWire.getFreezeAcknowledgement().toBuilder() + .setUnknownFields(unknown) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( - RetainSelectedEntitySourceRequest.newBuilder() - .setOriginalIntakeAuthorizationBinding( - ByteString.copyFrom( - new byte - [EntitySelectedSourceIntakeCommandGrpcCodec - .MAX_REQUEST_WIRE_BYTES - + 1])) - .build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + RetainSelectedEntitySourceRequest.newBuilder() + .setOriginalIntakeAuthorizationBinding( + ByteString.copyFrom( + new byte + [EntitySelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES + + 1])) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("wire budget"); var response = EntitySelectedSourceIntakeCommandGrpcCodec.toResponse( new EntitySelectedSourceIntakeCommandEvidence(request, fixture.receipt())); - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse( - request, - response.toBuilder() - .setRequest( - response.getRequest().toBuilder() - .setTransportRequestId(UUID.randomUUID().toString()) - .build()) - .build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setTransportRequestId(UUID.randomUUID().toString()) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("changed"); - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse( - request, response.toBuilder().setReceiptDigest("0".repeat(64)).build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse( + request, response.toBuilder().setReceiptDigest("0".repeat(64)).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("digest"); - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse( - request, response.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse( + request, response.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unknown"); @@ -195,18 +184,15 @@ void rejectsUnknownFieldsOversizedWireAndChangedFullResponseEchoOrDigest() { void transportCorrelationMustBeCanonicalNonzeroAndNotReuseRetainedIdentity() { var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence(); var binding = fixture.authorization(); - assertThatThrownBy( - () -> - new Request( - Request.SCHEMA_VERSION, NAMESPACE, binding.operationId(), binding, freeze)) + assertThatThrownBy(() -> + new Request(Request.SCHEMA_VERSION, NAMESPACE, binding.operationId(), binding, freeze)) .isInstanceOf(IllegalArgumentException.class); var valid = Request.create(NAMESPACE, binding, freeze); - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( - EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(valid).toBuilder() - .setTransportRequestId("00000000-0000-0000-0000-000000000000") - .build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(valid).toBuilder() + .setTransportRequestId("00000000-0000-0000-0000-000000000000") + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("UUID"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodecTest.java index 7a7e4cc987..d87b007525 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcCodecTest.java @@ -82,48 +82,42 @@ void roundTripsCompleteCanonicalReceiptAndOriginalBindingBytes() { @Test void rejectsNamespaceReaderPurposeOwnerAndAuthorizationDrift() { var binding = fixture.authorization(); - assertThatThrownBy( - () -> - new EntitySelectedSourceIntakeTerminalReadEvidence.Request( - 1, "other", UUID.randomUUID(), binding)) + assertThatThrownBy(() -> + new EntitySelectedSourceIntakeTerminalReadEvidence.Request( + 1, "other", UUID.randomUUID(), binding)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new EntitySelectedSourceIntakeTerminalReadEvidence.Request( - 1, "test", UUID.randomUUID(), fixture.wrongOwnerAuthorization())) + assertThatThrownBy(() -> + new EntitySelectedSourceIntakeTerminalReadEvidence.Request( + 1, "test", UUID.randomUUID(), fixture.wrongOwnerAuthorization())) .isInstanceOf(IllegalArgumentException.class); var request = EntitySelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request()); - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest( - request.toBuilder() - .setIntendedReader("spiffe://firemud/ns/test/sa/entity-management-service") - .build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest( + request.toBuilder() + .setIntendedReader("spiffe://firemud/ns/test/sa/entity-management-service") + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest( - request.toBuilder().setTerminalReadPurpose("ENTITY_INTAKE_RETENTION").build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest( + request.toBuilder().setTerminalReadPurpose("ENTITY_INTAKE_RETENTION").build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest( - request.toBuilder() - .setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)) - .build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest( + request.toBuilder() + .setIntakeAuthorizationDigest("sha256:" + "0".repeat(64)) + .build())) .isInstanceOf(IllegalArgumentException.class); byte[] changedBinding = request.getOriginalIntakeAuthorizationBinding().toByteArray(); changedBinding[4] ^= 1; - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest( - request.toBuilder() - .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(changedBinding)) - .setIntakeAuthorizationDigest( - DraftAuthorizationFenceBinding.digest(changedBinding)) - .build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest( + request.toBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(changedBinding)) + .setIntakeAuthorizationDigest( + DraftAuthorizationFenceBinding.digest(changedBinding)) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -134,31 +128,27 @@ void rejectsChangedReceiptDigestEchoUnknownFieldsAndTrailingBytes() { EntitySelectedSourceIntakeTerminalReadGrpcCodec.toResponse( new EntitySelectedSourceIntakeTerminalReadEvidence(request, fixture.receipt())); - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setResult( - EntitySelectedSourceIntakeTerminalResult - .ENTITY_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_UNSPECIFIED) - .build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setResult( + EntitySelectedSourceIntakeTerminalResult + .ENTITY_SELECTED_SOURCE_INTAKE_TERMINAL_RESULT_UNSPECIFIED) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( - request, - response.toBuilder().setReceiptDigest("sha256:" + "0".repeat(64)).build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, response.toBuilder().setReceiptDigest("sha256:" + "0".repeat(64)).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setRequest( - response.getRequest().toBuilder() - .setReadRequestId("12121212-1212-4212-8212-121212121212")) - .build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setReadRequestId("12121212-1212-4212-8212-121212121212")) + .build())) .isInstanceOf(IllegalArgumentException.class); var requestUnknown = @@ -170,10 +160,8 @@ void rejectsChangedReceiptDigestEchoUnknownFieldsAndTrailingBytes() { () -> EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest(requestUnknown)) .isInstanceOf(IllegalArgumentException.class); var responseUnknown = response.toBuilder().setUnknownFields(unknownFields()).build(); - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( - request, responseUnknown)) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse(request, responseUnknown)) .isInstanceOf(IllegalArgumentException.class); byte[] trailing = @@ -181,26 +169,24 @@ void rejectsChangedReceiptDigestEchoUnknownFieldsAndTrailingBytes() { response.getCommittedEmptyReceipt().toByteArray(), response.getCommittedEmptyReceipt().size() + 1); trailing[trailing.length - 1] = 0x55; - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setCommittedEmptyReceipt(ByteString.copyFrom(trailing)) - .setReceiptDigest(DraftAuthorizationFenceBinding.digest(trailing)) - .build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setCommittedEmptyReceipt(ByteString.copyFrom(trailing)) + .setReceiptDigest(DraftAuthorizationFenceBinding.digest(trailing)) + .build())) .isInstanceOf(IllegalArgumentException.class); byte[] changedReceipt = response.getCommittedEmptyReceipt().toByteArray(); changedReceipt[changedReceipt.length - 1] ^= 1; - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setCommittedEmptyReceipt(ByteString.copyFrom(changedReceipt)) - .setReceiptDigest(DraftAuthorizationFenceBinding.digest(changedReceipt)) - .build())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setCommittedEmptyReceipt(ByteString.copyFrom(changedReceipt)) + .setReceiptDigest(DraftAuthorizationFenceBinding.digest(changedReceipt)) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -227,10 +213,9 @@ void rejectsOverBudgetRequestAndReceipt() { .toBuilder() .setCommittedEmptyReceipt(ByteString.copyFrom(oversizedReceipt)) .build(); - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( - request, oversizedResponse)) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse( + request, oversizedResponse)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AssetSourceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AssetSourceTest.java index eb8beecde7..fb4c0bed73 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AssetSourceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AssetSourceTest.java @@ -80,25 +80,23 @@ void referenceCannotRewriteItsBoundRequirednessOrRevisionIdentity() { binding(AssetSource.upsertPayload("1", "logo.png", AssetSource.Requiredness.REQUIRED)); var revision = binding.revisions().getFirst(); - assertThatThrownBy( - () -> - new AssetSource.Reference( - "logo.png", - "1", - AssetSource.Requiredness.OPTIONAL, - binding, - "0", - revision.revisionId())) + assertThatThrownBy(() -> + new AssetSource.Reference( + "logo.png", + "1", + AssetSource.Requiredness.OPTIONAL, + binding, + "0", + revision.revisionId())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AssetSource.Reference( - "logo.png", - "1", - AssetSource.Requiredness.REQUIRED, - binding, - "0", - UUID.randomUUID())) + assertThatThrownBy(() -> + new AssetSource.Reference( + "logo.png", + "1", + AssetSource.Requiredness.REQUIRED, + binding, + "0", + UUID.randomUUID())) .isInstanceOf(IllegalArgumentException.class); } @@ -111,18 +109,16 @@ void snapshotRejectsForeignTargetDuplicateKeysAndSourceAliases() { assertThatThrownBy(() -> AssetSource.replay(references, foreign)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AssetSource.Snapshot( - original, List.of(references.getFirst(), references.getFirst()))) + assertThatThrownBy(() -> + new AssetSource.Snapshot( + original, List.of(references.getFirst(), references.getFirst()))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AssetSource.replay( - references, - binding( - AssetSource.upsertPayload( - "1", "alias.png", AssetSource.Requiredness.REQUIRED)))) + assertThatThrownBy(() -> + AssetSource.replay( + references, + binding( + AssetSource.upsertPayload( + "1", "alias.png", AssetSource.Requiredness.REQUIRED)))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredCoreAndSpawnReadClientLifecycleTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredCoreAndSpawnReadClientLifecycleTest.java index bf9f40dc20..18b3826c6a 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredCoreAndSpawnReadClientLifecycleTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredCoreAndSpawnReadClientLifecycleTest.java @@ -81,12 +81,11 @@ void closeReleasesClientMonitorBeforeDrainingCertificateCallback( GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); when(channelFactory.buildChannel( any(String.class), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) - .thenAnswer( - invocation -> { - ManagedChannel channel = mock(ManagedChannel.class); - channels.add(channel); - return channel; - }); + .thenAnswer(invocation -> { + ManagedChannel channel = mock(ManagedChannel.class); + channels.add(channel); + return channel; + }); ClientHandle handle = kind.create(endpoints, tls, channelFactory); client = handle.client(); handle.initialize().run(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjectionTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjectionTest.java index 63d8a9b84d..81989b178e 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjectionTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreProjectionTest.java @@ -118,10 +118,8 @@ void rejectsChangedFieldsDigestUnknownDuplicateAndTrailingInput() { json.replace(TENANT.toString(), "99999999-9999-4999-8999-999999999999") .getBytes(StandardCharsets.UTF_8); assertRejected(changedTenant, projection.digest()); - assertThatThrownBy( - () -> - AuthoredInitialActorCoreProjection.fromStored( - projection.canonicalBytes(), digest('0'))) + assertThatThrownBy(() -> + AuthoredInitialActorCoreProjection.fromStored(projection.canonicalBytes(), digest('0'))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("digest differs"); @@ -428,15 +426,14 @@ private static String gameplaySnapshot( snapshot.put( "entries", entries.stream() - .map( - entry -> - Map.of( - "family", entry.family().name(), - "definitionJson", GameplayRuleManifest.canonical(entry.definition()), - "sourceBindingJson", entry.sourceBinding().canonicalJson(), - "sourceBindingDigest", entry.sourceBinding().digest(), - "revisionOrder", entry.revisionOrder(), - "revisionId", entry.revisionId().toString())) + .map(entry -> + Map.of( + "family", entry.family().name(), + "definitionJson", GameplayRuleManifest.canonical(entry.definition()), + "sourceBindingJson", entry.sourceBinding().canonicalJson(), + "sourceBindingDigest", entry.sourceBinding().digest(), + "revisionOrder", entry.revisionOrder(), + "revisionId", entry.revisionId().toString())) .toList()); return CommandSource.canonical(snapshot); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadClientTest.java index a55277a3d2..2414d29e76 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadClientTest.java @@ -42,10 +42,8 @@ void requiresExplicitInitializationExactNamespaceAndNoAmbientOwnerTransaction(@T assertThatThrownBy(() -> client.read(request)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not initialized"); - assertThatThrownBy( - () -> - client.read( - new ReadRequest(AuthoredInitialActorCoreReadTestFixture.request("other")))) + assertThatThrownBy(() -> + client.read(new ReadRequest(AuthoredInitialActorCoreReadTestFixture.request("other")))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("client identity"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadEvidenceTest.java index 61f1d915a5..f7188da0e7 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadEvidenceTest.java @@ -438,15 +438,14 @@ private static String gameplaySnapshot( snapshot.put( "entries", entries.stream() - .map( - entry -> - Map.of( - "family", entry.family().name(), - "definitionJson", GameplayRuleManifest.canonical(entry.definition()), - "sourceBindingJson", entry.sourceBinding().canonicalJson(), - "sourceBindingDigest", entry.sourceBinding().digest(), - "revisionOrder", entry.revisionOrder(), - "revisionId", entry.revisionId().toString())) + .map(entry -> + Map.of( + "family", entry.family().name(), + "definitionJson", GameplayRuleManifest.canonical(entry.definition()), + "sourceBindingJson", entry.sourceBinding().canonicalJson(), + "sourceBindingDigest", entry.sourceBinding().digest(), + "revisionOrder", entry.revisionOrder(), + "revisionId", entry.revisionId().toString())) .toList()); return CommandSource.canonical(snapshot); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadGrpcCodecTest.java index a41d74a8a9..7d568cae3f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreReadGrpcCodecTest.java @@ -40,10 +40,9 @@ void roundTripsExactReadRequestAndCompleteCanonicalResult() throws Exception { void rejectsMissingInitialUnknownAndChangedExactRequestSelectors() throws Exception { var fixture = AuthoredInitialActorCoreReadTestFixture.create(); var wire = AuthoredInitialActorCoreReadGrpcCodec.toRequest(new ReadRequest(fixture.request())); - assertThatThrownBy( - () -> - AuthoredInitialActorCoreReadGrpcCodec.fromRequest( - wire.toBuilder().clearAssociationRequest().build())) + assertThatThrownBy(() -> + AuthoredInitialActorCoreReadGrpcCodec.fromRequest( + wire.toBuilder().clearAssociationRequest().build())) .isInstanceOf(IllegalArgumentException.class); var noSelection = @@ -85,26 +84,23 @@ void rejectsChangedEchoCanonicalBytesDigestAndUnknownNestedFields() throws Excep ReadAuthoredInitialActorCoreResponse response = AuthoredInitialActorCoreReadGrpcCodec.toResponse(fixture.result()); - assertThatThrownBy( - () -> - AuthoredInitialActorCoreReadGrpcCodec.fromResponse( - changedRequest(fixture.request()), response)) + assertThatThrownBy(() -> + AuthoredInitialActorCoreReadGrpcCodec.fromResponse( + changedRequest(fixture.request()), response)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact request echo"); - assertThatThrownBy( - () -> - AuthoredInitialActorCoreReadGrpcCodec.fromResponse( - fixture.request(), - response.toBuilder() - .setCanonicalResultBytes(com.google.protobuf.ByteString.copyFromUtf8("{}")) - .build())) + assertThatThrownBy(() -> + AuthoredInitialActorCoreReadGrpcCodec.fromResponse( + fixture.request(), + response.toBuilder() + .setCanonicalResultBytes(com.google.protobuf.ByteString.copyFromUtf8("{}")) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical complete content"); - assertThatThrownBy( - () -> - AuthoredInitialActorCoreReadGrpcCodec.fromResponse( - fixture.request(), - response.toBuilder().setResultDigest("sha256:" + "0".repeat(64)).build())) + assertThatThrownBy(() -> + AuthoredInitialActorCoreReadGrpcCodec.fromResponse( + fixture.request(), + response.toBuilder().setResultDigest("sha256:" + "0".repeat(64)).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical complete content"); @@ -118,10 +114,8 @@ void rejectsChangedEchoCanonicalBytesDigestAndUnknownNestedFields() throws Excep .build()) .build()) .build(); - assertThatThrownBy( - () -> - AuthoredInitialActorCoreReadGrpcCodec.fromResponse( - fixture.request(), unknownNested)) + assertThatThrownBy(() -> + AuthoredInitialActorCoreReadGrpcCodec.fromResponse(fixture.request(), unknownNested)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBindingTest.java index c359e041bc..ec5bb58181 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBindingTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredInitialActorCoreSourceBindingTest.java @@ -60,24 +60,19 @@ void bindsExactPolicyAndGameplaySnapshotsWithFullDispositionFeedbackProvenance() assertThat(binding.canonicalBytes()).isNotEmpty(); assertThat(binding.digest()).matches("sha256:[0-9a-f]{64}"); assertThat(binding.canonicalBytes()) - .satisfies( - value -> - assertThat(new String(value, StandardCharsets.ISO_8859_1)) - .contains( - new String( - fixture.policy().canonicalJson().getBytes(StandardCharsets.UTF_8), - StandardCharsets.ISO_8859_1))); + .satisfies(value -> + assertThat(new String(value, StandardCharsets.ISO_8859_1)) + .contains( + new String( + fixture.policy().canonicalJson().getBytes(StandardCharsets.UTF_8), + StandardCharsets.ISO_8859_1))); assertThat(binding.canonicalBytes()) - .satisfies( - value -> - assertThat(new String(value, StandardCharsets.ISO_8859_1)) - .contains( - new String( - fixture - .gameplaySnapshot() - .snapshotJson() - .getBytes(StandardCharsets.UTF_8), - StandardCharsets.ISO_8859_1))); + .satisfies(value -> + assertThat(new String(value, StandardCharsets.ISO_8859_1)) + .contains( + new String( + fixture.gameplaySnapshot().snapshotJson().getBytes(StandardCharsets.UTF_8), + StandardCharsets.ISO_8859_1))); } @Test @@ -97,10 +92,9 @@ void strictDecoderRoundTripsExactBindingAndDefensivelyCopiesItsBytes() { byte[] exposed = decoded.canonicalBytes(); exposed[0] ^= 0x01; assertThat(decoded.canonicalBytes()).isEqualTo(original.canonicalBytes()); - assertThatThrownBy( - () -> - AuthoredInitialActorCoreSourceBinding.fromStored( - original.canonicalBytes(), digest('0'))) + assertThatThrownBy(() -> + AuthoredInitialActorCoreSourceBinding.fromStored( + original.canonicalBytes(), digest('0'))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("digest differs"); } @@ -113,10 +107,9 @@ void strictDecoderRejectsUnknownSchemaTrailingFramesAndSubstitutedPolicySource() var unknownSchema = new ByteArrayOutputStream(); DraftAuthorizationFenceBinding.frame(unknownSchema, "unknown-authored-core-binding/v9"); byte[] unknownBytes = unknownSchema.toByteArray(); - assertThatThrownBy( - () -> - AuthoredInitialActorCoreSourceBinding.fromStored( - unknownBytes, CommandSource.sha256(unknownBytes))) + assertThatThrownBy(() -> + AuthoredInitialActorCoreSourceBinding.fromStored( + unknownBytes, CommandSource.sha256(unknownBytes))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("source frame"); @@ -124,10 +117,9 @@ void strictDecoderRejectsUnknownSchemaTrailingFramesAndSubstitutedPolicySource() trailingFrame.writeBytes(canonicalBytes); DraftAuthorizationFenceBinding.frame(trailingFrame, "unexpected"); byte[] trailingBytes = trailingFrame.toByteArray(); - assertThatThrownBy( - () -> - AuthoredInitialActorCoreSourceBinding.fromStored( - trailingBytes, CommandSource.sha256(trailingBytes))) + assertThatThrownBy(() -> + AuthoredInitialActorCoreSourceBinding.fromStored( + trailingBytes, CommandSource.sha256(trailingBytes))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Trailing"); @@ -136,10 +128,9 @@ void strictDecoderRejectsUnknownSchemaTrailingFramesAndSubstitutedPolicySource() assertThat(policySnapshot).contains("Wayfarer"); frames.set(18, policySnapshot.replace("Wayfarer", "Wanderer").getBytes(StandardCharsets.UTF_8)); byte[] substitutedBytes = joinFrames(frames); - assertThatThrownBy( - () -> - AuthoredInitialActorCoreSourceBinding.fromStored( - substitutedBytes, CommandSource.sha256(substitutedBytes))) + assertThatThrownBy(() -> + AuthoredInitialActorCoreSourceBinding.fromStored( + substitutedBytes, CommandSource.sha256(substitutedBytes))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Policy source"); @@ -149,10 +140,9 @@ void strictDecoderRejectsUnknownSchemaTrailingFramesAndSubstitutedPolicySource() frames.set( 27, gameplaySnapshot.replace("newcomer", "intruder").getBytes(StandardCharsets.UTF_8)); byte[] corruptRulesBytes = joinFrames(frames); - assertThatThrownBy( - () -> - AuthoredInitialActorCoreSourceBinding.fromStored( - corruptRulesBytes, CommandSource.sha256(corruptRulesBytes))) + assertThatThrownBy(() -> + AuthoredInitialActorCoreSourceBinding.fromStored( + corruptRulesBytes, CommandSource.sha256(corruptRulesBytes))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Gameplay rule source"); @@ -160,10 +150,9 @@ void strictDecoderRejectsUnknownSchemaTrailingFramesAndSubstitutedPolicySource() frames = splitFrames(canonicalBytes); frames.set(27, splitFrames(changedSelectedCommit.canonicalBytes()).get(27)); byte[] changedRulesBytes = joinFrames(frames); - assertThatThrownBy( - () -> - AuthoredInitialActorCoreSourceBinding.fromStored( - changedRulesBytes, CommandSource.sha256(changedRulesBytes))) + assertThatThrownBy(() -> + AuthoredInitialActorCoreSourceBinding.fromStored( + changedRulesBytes, CommandSource.sha256(changedRulesBytes))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Gameplay rules differ"); } @@ -206,18 +195,14 @@ void resolvesOnlyTheAssociatedWorldAndFramesTheFullMixedWorldSnapshot() { assertThat(bindings).hasSize(1); assertThat(bindings.getFirst().policySource().policy().worldSlug()).isEqualTo("world"); assertThat(bindings.getFirst().canonicalBytes()) - .satisfies( - value -> - assertThat(new String(value, StandardCharsets.ISO_8859_1)) - .contains( - new String( - fixture.policySnapshot().canonicalBytes(), - StandardCharsets.ISO_8859_1))); + .satisfies(value -> + assertThat(new String(value, StandardCharsets.ISO_8859_1)) + .contains( + new String( + fixture.policySnapshot().canonicalBytes(), StandardCharsets.ISO_8859_1))); assertThat(bindings.getFirst().canonicalBytes()) - .satisfies( - value -> - assertThat(new String(value, StandardCharsets.ISO_8859_1)) - .contains("foreign-only")); + .satisfies(value -> + assertThat(new String(value, StandardCharsets.ISO_8859_1)).contains("foreign-only")); } @Test @@ -289,18 +274,17 @@ void rejectsPolicyOrRuleSnapshotsFromAnotherSelectedCommit() { fixture.binding().revisions(), fixture.binding().affectedUnits()); - assertThatThrownBy( - () -> - AuthoredInitialActorCoreSourceBinding.resolveAll( - SOURCE_OPERATION, - digest('a'), - "world", - "workflow-1", - bytes("publication operation bytes"), - bytes("release evidence bytes"), - otherCommit, - fixture.policySnapshot(), - fixture.gameplaySnapshot())) + assertThatThrownBy(() -> + AuthoredInitialActorCoreSourceBinding.resolveAll( + SOURCE_OPERATION, + digest('a'), + "world", + "workflow-1", + bytes("publication operation bytes"), + bytes("release evidence bytes"), + otherCommit, + fixture.policySnapshot(), + fixture.gameplaySnapshot())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("selected authored commit"); @@ -340,23 +324,17 @@ void rejectsMissingDispositionOrFeedbackAndPreservesOtherAuthoredRuleFamilies() var feedbackOnly = List.of(fixture.entries().getLast()); var feedbackOnlySnapshot = new GameplayRuleSelectedSource(snapshot(fixture.binding(), feedbackOnly)); - assertThatThrownBy( - () -> - resolve( - fixture, - SOURCE_OPERATION, - "world", - fixture.policySnapshot(), - feedbackOnlySnapshot)) + assertThatThrownBy(() -> + resolve( + fixture, SOURCE_OPERATION, "world", fixture.policySnapshot(), feedbackOnlySnapshot)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("disposition is absent"); Feedback changedFeedback = feedback("otherWelcome", "Welcome, traveler"); - assertThatThrownBy( - () -> - fixtureWithDefinitions( - List.of(disposition("newcomer", "welcome"), changedFeedback), List.of()) - .resolve()) + assertThatThrownBy(() -> + fixtureWithDefinitions( + List.of(disposition("newcomer", "welcome"), changedFeedback), List.of()) + .resolve()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("FEEDBACK"); @@ -384,14 +362,13 @@ void rejectsMissingDispositionOrFeedbackAndPreservesOtherAuthoredRuleFamilies() void rejectsEntryProvenanceThatDoesNotBelongToItsOriginalRevision() { Fixture fixture = fixture(List.of()); GameplayRuleSource.Entry entry = fixture.entries().getFirst(); - assertThatThrownBy( - () -> - new GameplayRuleSource.Entry( - entry.family(), - entry.definition(), - entry.sourceBinding(), - entry.revisionOrder(), - uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"))) + assertThatThrownBy(() -> + new GameplayRuleSource.Entry( + entry.family(), + entry.definition(), + entry.sourceBinding(), + entry.revisionOrder(), + uuid("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("original Game Design revision"); } @@ -521,14 +498,13 @@ private static Fixture withForeignWorldPolicy(Fixture fixture) { binding, "1", List.of(selectedPolicy, otherWorldPolicy)); List entries = fixture.entries().stream() - .map( - entry -> - new GameplayRuleSource.Entry( - entry.family(), - entry.definition(), - binding, - entry.revisionOrder(), - entry.revisionId())) + .map(entry -> + new GameplayRuleSource.Entry( + entry.family(), + entry.definition(), + binding, + entry.revisionOrder(), + entry.revisionId())) .toList(); return new Fixture( binding, diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java index 4aeaebbfff..0e6da7834d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldLaunchDescriptorGrpcCodecTest.java @@ -117,58 +117,51 @@ void getRequestAndResponseKeepReadCorrelationSeparateFromTheOriginalResolveIdent .build(); assertThat(AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse(getRequest, response)) .isEqualTo(descriptor); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( - getRequest, - response.toBuilder().setRequestId(UUID.randomUUID().toString()).build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( + getRequest, + response.toBuilder().setRequestId(UUID.randomUUID().toString()).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("request ID echo"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( - new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( - READ_REQUEST_ID, descriptor.request(), "sha256:" + "f".repeat(64)), - response)) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + READ_REQUEST_ID, descriptor.request(), "sha256:" + "f".repeat(64)), + response)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("result digest"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( - getRequest, - GetLaunchDescriptorResponse.newBuilder() - .setRequestId(wireRequest.getRequestId()) - .setError(ErrorDetail.getDefaultInstance()) - .build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( + getRequest, + GetLaunchDescriptorResponse.newBuilder() + .setRequestId(wireRequest.getRequestId()) + .setError(ErrorDetail.getDefaultInstance()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("rejected"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( - getRequest, - GetLaunchDescriptorResponse.newBuilder() - .setRequestId(wireRequest.getRequestId()) - .build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( + getRequest, + GetLaunchDescriptorResponse.newBuilder() + .setRequestId(wireRequest.getRequestId()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("no descriptor"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( - getRequest, response.toBuilder().setUnknownFields(UNKNOWN_FIELD).build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromGetResponse( + getRequest, response.toBuilder().setUnknownFields(UNKNOWN_FIELD).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( - descriptor.authoredWorldSourceOperationId(), - descriptor.request(), - descriptor.resultDigest())) + assertThatThrownBy(() -> + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + descriptor.authoredWorldSourceOperationId(), + descriptor.request(), + descriptor.resultDigest())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("distinct"); - assertThatThrownBy( - () -> - new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( - new UUID(0L, 0L), descriptor.request(), descriptor.resultDigest())) + assertThatThrownBy(() -> + new AuthoredWorldLaunchDescriptorGrpcCodec.GetRequest( + new UUID(0L, 0L), descriptor.request(), descriptor.resultDigest())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("nonnil"); } @@ -221,10 +214,9 @@ void completeBindingRoundTripsSupportedReleaseSchemasAndAllMappedSelections() th .setReleaseAttestation(unsupported) .build(); var wireRequest = AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(getRequest(descriptor)); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest, unsupportedResponse)) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + wireRequest, unsupportedResponse)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Release-attestation evidence is invalid"); } @@ -251,21 +243,19 @@ void completeReadPreservesWorldEvidenceAndRejectsMissingMalformedAndSubstitutedB response.getReleaseAttestation().toBuilder() .setWorldStartLocationEvidence(ByteString.copyFromUtf8("{} ")) .build())) { - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - request, response.toBuilder().setReleaseAttestation(invalid).build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, response.toBuilder().setReleaseAttestation(invalid).build())) .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - request, - response.toBuilder() - .setReleaseAttestation( - response.getReleaseAttestation().toBuilder() - .setUnknownFields(UNKNOWN_FIELD)) - .build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + response.toBuilder() + .setReleaseAttestation( + response.getReleaseAttestation().toBuilder() + .setUnknownFields(UNKNOWN_FIELD)) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -278,77 +268,63 @@ void resolveAndCompleteReadsRejectErrorsMissingBindingsAndChangedSelectors() thr var resolveResponse = ResolveLaunchDescriptorResponse.newBuilder().setLaunchDescriptor(wireDescriptor).build(); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( - descriptor.request(), - ResolveLaunchDescriptorResponse.newBuilder() - .setError(ErrorDetail.getDefaultInstance()) - .build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + ResolveLaunchDescriptorResponse.newBuilder() + .setError(ErrorDetail.getDefaultInstance()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("rejected"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( - descriptor.request(), ResolveLaunchDescriptorResponse.getDefaultInstance())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), ResolveLaunchDescriptorResponse.getDefaultInstance())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("no descriptor"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( - descriptor.request(), - resolveResponse.toBuilder() - .setLaunchDescriptor(wireDescriptor.toBuilder().clearAuthoredWorldBinding()) - .build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + resolveResponse.toBuilder() + .setLaunchDescriptor(wireDescriptor.toBuilder().clearAuthoredWorldBinding()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("no authored-world binding"); var wireRequest = AuthoredWorldLaunchDescriptorGrpcCodec.toGetRequest(getRequest(descriptor)); var completeResponse = completeResponse(wireRequest, world.launchBinding()); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest, - completeResponse.toBuilder() - .setError(ErrorDetail.getDefaultInstance()) - .build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + wireRequest, + completeResponse.toBuilder().setError(ErrorDetail.getDefaultInstance()).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("rejected"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest, - completeResponse.toBuilder() - .setRequestId(UUID.randomUUID().toString()) - .build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + wireRequest, + completeResponse.toBuilder().setRequestId(UUID.randomUUID().toString()).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("request ID echo"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest, - completeResponse.toBuilder().setUnknownFields(UNKNOWN_FIELD).build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + wireRequest, completeResponse.toBuilder().setUnknownFields(UNKNOWN_FIELD).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest, completeResponse.toBuilder().clearLaunchDescriptor().build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + wireRequest, completeResponse.toBuilder().clearLaunchDescriptor().build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("both descriptor and release"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest, completeResponse.toBuilder().clearReleaseAttestation().build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + wireRequest, completeResponse.toBuilder().clearReleaseAttestation().build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("both descriptor and release"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest.toBuilder() - .setExpectedRequestDigest("sha256:" + "f".repeat(64)) - .build(), - completeResponse)) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + wireRequest.toBuilder() + .setExpectedRequestDigest("sha256:" + "f".repeat(64)) + .build(), + completeResponse)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact read selector"); } @@ -362,55 +338,49 @@ void rejectsUnknownFieldsConflictingFlatDuplicatesAndLegacyTenantSelectors() thr var resolveResponse = ResolveLaunchDescriptorResponse.newBuilder().setLaunchDescriptor(evidenceMessage).build(); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( - descriptor.request(), - resolveResponse.toBuilder().setUnknownFields(UNKNOWN_FIELD).build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + resolveResponse.toBuilder().setUnknownFields(UNKNOWN_FIELD).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( - descriptor.request(), - resolveResponse.toBuilder() - .setLaunchDescriptor( - evidenceMessage.toBuilder().setUnknownFields(UNKNOWN_FIELD)) - .build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + resolveResponse.toBuilder() + .setLaunchDescriptor( + evidenceMessage.toBuilder().setUnknownFields(UNKNOWN_FIELD)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); var bindingWithUnknownField = evidenceMessage.getAuthoredWorldBinding().toBuilder() .setUnknownFields(UNKNOWN_FIELD) .build(); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( - descriptor.request(), - resolveResponse.toBuilder() - .setLaunchDescriptor( - evidenceMessage.toBuilder() - .setAuthoredWorldBinding(bindingWithUnknownField)) - .build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + resolveResponse.toBuilder() + .setLaunchDescriptor( + evidenceMessage.toBuilder() + .setAuthoredWorldBinding(bindingWithUnknownField)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( - descriptor.request(), - resolveResponse.toBuilder() - .setLaunchDescriptor( - evidenceMessage.toBuilder().setTenantId("legacy-tenant")) - .build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + resolveResponse.toBuilder() + .setLaunchDescriptor(evidenceMessage.toBuilder().setTenantId("legacy-tenant")) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("legacy tenant"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( - descriptor.request(), - resolveResponse.toBuilder() - .setLaunchDescriptor(evidenceMessage.toBuilder().setVersionId(43L)) - .build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + resolveResponse.toBuilder() + .setLaunchDescriptor(evidenceMessage.toBuilder().setVersionId(43L)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("does not match evidence"); @@ -423,20 +393,17 @@ void rejectsUnknownFieldsConflictingFlatDuplicatesAndLegacyTenantSelectors() thr completeResponse.getReleaseAttestation().getParticipantDigests(0).toBuilder() .setUnknownFields(UNKNOWN_FIELD)) .build(); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest, - completeResponse.toBuilder() - .setReleaseAttestation(releaseWithUnknownParticipant) - .build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + wireRequest, + completeResponse.toBuilder() + .setReleaseAttestation(releaseWithUnknownParticipant) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest.toBuilder().setUnknownFields(UNKNOWN_FIELD).build(), - completeResponse)) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + wireRequest.toBuilder().setUnknownFields(UNKNOWN_FIELD).build(), completeResponse)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); } @@ -534,11 +501,10 @@ void authoredWorldDigestVectorAndEmptyOptionalPresenceRemainStable() throws Exce AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( emptyFlagsEvidence)) .build())) - .satisfies( - readback -> { - assertThat(readback.requestedRuntimeFlagsJsonPresent()).isTrue(); - assertThat(readback.requestedRuntimeFlagsJson()).isEmpty(); - }); + .satisfies(readback -> { + assertThat(readback.requestedRuntimeFlagsJsonPresent()).isTrue(); + assertThat(readback.requestedRuntimeFlagsJson()).isEmpty(); + }); } @Test @@ -550,55 +516,49 @@ void rejectsChangedCanonicalDescriptorFieldsAndRequestSelectors() throws Excepti var resolveResponse = ResolveLaunchDescriptorResponse.newBuilder().setLaunchDescriptor(evidenceMessage).build(); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( - descriptor.request(), - resolveResponse.toBuilder().setUnknownFields(UNKNOWN_FIELD).build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + resolveResponse.toBuilder().setUnknownFields(UNKNOWN_FIELD).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( - descriptor.request(), - resolveResponse.toBuilder() - .setLaunchDescriptor( - evidenceMessage.toBuilder().setUnknownFields(UNKNOWN_FIELD)) - .build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + resolveResponse.toBuilder() + .setLaunchDescriptor( + evidenceMessage.toBuilder().setUnknownFields(UNKNOWN_FIELD)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); var bindingWithUnknownField = evidenceMessage.getAuthoredWorldBinding().toBuilder() .setUnknownFields(UNKNOWN_FIELD) .build(); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( - descriptor.request(), - resolveResponse.toBuilder() - .setLaunchDescriptor( - evidenceMessage.toBuilder() - .setAuthoredWorldBinding(bindingWithUnknownField)) - .build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + resolveResponse.toBuilder() + .setLaunchDescriptor( + evidenceMessage.toBuilder() + .setAuthoredWorldBinding(bindingWithUnknownField)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( - descriptor.request(), - resolveResponse.toBuilder() - .setLaunchDescriptor( - evidenceMessage.toBuilder().setTenantId("legacy-tenant")) - .build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + resolveResponse.toBuilder() + .setLaunchDescriptor(evidenceMessage.toBuilder().setTenantId("legacy-tenant")) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("legacy tenant"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( - descriptor.request(), - resolveResponse.toBuilder() - .setLaunchDescriptor(evidenceMessage.toBuilder().setVersionId(43L)) - .build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + resolveResponse.toBuilder() + .setLaunchDescriptor(evidenceMessage.toBuilder().setVersionId(43L)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("does not match evidence"); @@ -615,11 +575,10 @@ void rejectsChangedCanonicalDescriptorFieldsAndRequestSelectors() throws Excepti evidenceMessage.toBuilder().setReleaseBundleId(0L).build(), evidenceMessage.toBuilder().setPublishedReleaseBundleRef("other").build(), evidenceMessage.toBuilder().setRemapSetId("other").build())) { - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( - descriptor.request(), - resolveResponse.toBuilder().setLaunchDescriptor(changedDescriptor).build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + resolveResponse.toBuilder().setLaunchDescriptor(changedDescriptor).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("does not match evidence"); } @@ -631,15 +590,14 @@ void rejectsChangedCanonicalDescriptorFieldsAndRequestSelectors() throws Excepti requestWithTargetNamespaceAndWorldSlug( descriptor.request(), "other", descriptor.worldSlug()))) { var changedEvidence = descriptorWithRequest(descriptor, changedRequest); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( - descriptor.request(), - ResolveLaunchDescriptorResponse.newBuilder() - .setLaunchDescriptor( - AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( - changedEvidence)) - .build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor( + AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage( + changedEvidence)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact authored-world resolve request"); } @@ -649,11 +607,10 @@ void rejectsChangedCanonicalDescriptorFieldsAndRequestSelectors() throws Excepti .setAuthoredWorldBinding( evidenceMessage.getAuthoredWorldBinding().toBuilder().setSchemaVersion(99)) .build(); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( - descriptor.request(), - resolveResponse.toBuilder().setLaunchDescriptor(unsupportedSchema).build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromResolveResponse( + descriptor.request(), + resolveResponse.toBuilder().setLaunchDescriptor(unsupportedSchema).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Authored-world launch evidence is invalid"); @@ -666,20 +623,17 @@ void rejectsChangedCanonicalDescriptorFieldsAndRequestSelectors() throws Excepti completeResponse.getReleaseAttestation().getParticipantDigests(0).toBuilder() .setUnknownFields(UNKNOWN_FIELD)) .build(); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest, - completeResponse.toBuilder() - .setReleaseAttestation(releaseWithUnknownParticipant) - .build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + wireRequest, + completeResponse.toBuilder() + .setReleaseAttestation(releaseWithUnknownParticipant) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - wireRequest.toBuilder().setUnknownFields(UNKNOWN_FIELD).build(), - completeResponse)) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + wireRequest.toBuilder().setUnknownFields(UNKNOWN_FIELD).build(), completeResponse)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); } @@ -739,24 +693,20 @@ void completeReadRejectsUnknownFieldsOnArtifactAndErrorMessages() throws Excepti good.getReleaseAttestation().getArtifactDigests(0).toBuilder() .setUnknownFields(UNKNOWN_FIELD)) .build(); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - request, - good.toBuilder().setReleaseAttestation(releaseWithUnknownArtifact).build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder().setReleaseAttestation(releaseWithUnknownArtifact).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( - request, - good.toBuilder() - .setError( - ErrorDetail.newBuilder() - .setUnknownFields(UNKNOWN_FIELD) - .setCode("DENIED")) - .build())) + assertThatThrownBy(() -> + AuthoredWorldLaunchDescriptorGrpcCodec.fromCompleteResponse( + request, + good.toBuilder() + .setError( + ErrorDetail.newBuilder().setUnknownFields(UNKNOWN_FIELD).setCode("DENIED")) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); } @@ -817,20 +767,19 @@ private static AuthoredWorldReleaseAttestationEvidence retainedV1( AuthoredWorldReleaseAttestationEvidence release) { var participants = release.participantDigests().stream() - .map( - participant -> - new AuthoredWorldReleaseAttestationEvidence.Participant( + .map(participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( participant.participantKey(), - participant.scopeValue(), - participant.baseVersionIdPresent(), - participant.baseVersionId(), - participant.appliedCommitId(), - participant.contentDigest(), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - participant.participantKey(), - AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION), - participant.abilitySchemaDigestPresent(), - participant.abilitySchemaDigest())) + AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION), + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest())) .toList(); return AuthoredWorldReleaseAttestationEvidence.create( release.targetNamespace(), @@ -881,20 +830,19 @@ private static AuthoredWorldReleaseAttestationEvidence closureSelected( selected.appliedResultBytes()); var participants = release.participantDigests().stream() - .map( - participant -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - participant.participantKey(), - participant.scopeValue(), - participant.baseVersionIdPresent(), - participant.baseVersionId(), - participant.appliedCommitId(), - participant.contentDigest(), - "WORLD_MANAGEMENT".equals(participant.participantKey()) - ? 4 - : participant.digestSchemaVersion(), - participant.abilitySchemaDigestPresent(), - participant.abilitySchemaDigest())) + .map(participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + "WORLD_MANAGEMENT".equals(participant.participantKey()) + ? 4 + : participant.digestSchemaVersion(), + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest())) .toList(); return AuthoredWorldReleaseAttestationEvidence.createClosureSelector( release.targetNamespace(), diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java index 675196d45d..abdf83c34e 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AuthoredWorldReleaseAttestationSelectorTest.java @@ -66,44 +66,42 @@ void v3BindsClosureQualifiedWorldSchema4InItsOwnDomainAndSurvivesStoredReadback( var wrongWorldSchema = release.participantDigests().stream() - .map( - participant -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - participant.participantKey(), - participant.scopeValue(), - participant.baseVersionIdPresent(), - participant.baseVersionId(), - participant.appliedCommitId(), - participant.contentDigest(), - "WORLD_MANAGEMENT".equals(participant.participantKey()) - ? 3 - : participant.digestSchemaVersion(), - participant.abilitySchemaDigestPresent(), - participant.abilitySchemaDigest())) + .map(participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + "WORLD_MANAGEMENT".equals(participant.participantKey()) + ? 3 + : participant.digestSchemaVersion(), + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest())) .toList(); - assertThatThrownBy( - () -> - AuthoredWorldReleaseAttestationEvidence.createClosureSelector( - release.targetNamespace(), - release.descriptorResultDigest(), - release.canonicalTenantId(), - release.canonicalVersionId(), - release.worldSlug(), - release.authoredWorldSourceOperationId(), - release.authoredWorldSourceEvidenceDigest(), - release.launchDescriptorId(), - release.publishedReleaseBundleRef(), - release.versionStateEpoch(), - release.publishWorkflowId(), - release.commitId(), - wrongWorldSchema, - release.manifestHash(), - release.manifestSchemaVersion(), - release.requiredManifestAssetKeys(), - release.artifactDigests(), - release.commandDefinitions(), - release.generationConfigRevision(), - selector)) + assertThatThrownBy(() -> + AuthoredWorldReleaseAttestationEvidence.createClosureSelector( + release.targetNamespace(), + release.descriptorResultDigest(), + release.canonicalTenantId(), + release.canonicalVersionId(), + release.worldSlug(), + release.authoredWorldSourceOperationId(), + release.authoredWorldSourceEvidenceDigest(), + release.launchDescriptorId(), + release.publishedReleaseBundleRef(), + release.versionStateEpoch(), + release.publishWorkflowId(), + release.commitId(), + wrongWorldSchema, + release.manifestHash(), + release.manifestSchemaVersion(), + release.requiredManifestAssetKeys(), + release.artifactDigests(), + release.commandDefinitions(), + release.generationConfigRevision(), + selector)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Participant digest schema is unsupported"); } @@ -143,44 +141,42 @@ void v4BindsTheExactSelectedFullParticipantVectorInANewDomain() throws Exception "GAME_DESIGN_CONTROL_PLANE")) { var mixedParticipants = release.participantDigests().stream() - .map( - participant -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - participant.participantKey(), - participant.scopeValue(), - participant.baseVersionIdPresent(), - participant.baseVersionId(), - participant.appliedCommitId(), - participant.contentDigest(), - mixedOwner.equals(participant.participantKey()) - ? participant.digestSchemaVersion() - 1 - : participant.digestSchemaVersion(), - participant.abilitySchemaDigestPresent(), - participant.abilitySchemaDigest())) + .map(participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + mixedOwner.equals(participant.participantKey()) + ? participant.digestSchemaVersion() - 1 + : participant.digestSchemaVersion(), + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest())) .toList(); - assertThatThrownBy( - () -> - AuthoredWorldReleaseAttestationEvidence.createSelectedFull( - release.targetNamespace(), - release.descriptorResultDigest(), - release.canonicalTenantId(), - release.canonicalVersionId(), - release.worldSlug(), - release.authoredWorldSourceOperationId(), - release.authoredWorldSourceEvidenceDigest(), - release.launchDescriptorId(), - release.publishedReleaseBundleRef(), - release.versionStateEpoch(), - release.publishWorkflowId(), - release.commitId(), - mixedParticipants, - release.manifestHash(), - release.manifestSchemaVersion(), - release.requiredManifestAssetKeys(), - release.artifactDigests(), - release.commandDefinitions(), - release.generationConfigRevision(), - selector)) + assertThatThrownBy(() -> + AuthoredWorldReleaseAttestationEvidence.createSelectedFull( + release.targetNamespace(), + release.descriptorResultDigest(), + release.canonicalTenantId(), + release.canonicalVersionId(), + release.worldSlug(), + release.authoredWorldSourceOperationId(), + release.authoredWorldSourceEvidenceDigest(), + release.launchDescriptorId(), + release.publishedReleaseBundleRef(), + release.versionStateEpoch(), + release.publishWorkflowId(), + release.commitId(), + mixedParticipants, + release.manifestHash(), + release.manifestSchemaVersion(), + release.requiredManifestAssetKeys(), + release.artifactDigests(), + release.commandDefinitions(), + release.generationConfigRevision(), + selector)) .as("selected-full refuses retained participant schema for %s", mixedOwner) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Participant digest schema is unsupported"); @@ -202,20 +198,19 @@ void terminalReleaseProjectionAcceptsExactV2AndV3OwnerSchemasAndRejectsMixedSche var mixedParticipants = attestation.participantDigests().stream() - .map( - participant -> - "GAME_DESIGN_CONTROL_PLANE".equals(participant.participantKey()) - ? new AuthoredWorldReleaseAttestationEvidence.Participant( - participant.participantKey(), - participant.scopeValue(), - participant.baseVersionIdPresent(), - participant.baseVersionId(), - participant.appliedCommitId(), - participant.contentDigest(), - 1, - participant.abilitySchemaDigestPresent(), - participant.abilitySchemaDigest()) - : participant) + .map(participant -> + "GAME_DESIGN_CONTROL_PLANE".equals(participant.participantKey()) + ? new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + 1, + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest()) + : participant) .toList(); assertThatThrownBy(() -> terminalReleaseContent(attestation, mixedParticipants)) .isInstanceOf(IllegalArgumentException.class) @@ -238,20 +233,19 @@ private static GameDesignPublicationTerminalEvidence.ReleaseContent terminalRele attestation.artifactDigests(), attestation.requiredManifestAssetKeys(), participants.stream() - .map( - participant -> - new GameDesignPublicationTerminalEvidence.Participant( - participant.participantKey(), - participant.scopeValue(), - participant.baseVersionId(), - participant.appliedCommitId(), - participant.contentDigest(), - participant.digestSchemaVersion(), - participant.abilitySchemaDigestPresent() - ? participant.abilitySchemaDigest() - : null, - null, - null)) + .map(participant -> + new GameDesignPublicationTerminalEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + participant.digestSchemaVersion(), + participant.abilitySchemaDigestPresent() + ? participant.abilitySchemaDigest() + : null, + null, + null)) .toList(), attestation.commandDefinitions(), attestation.generationConfigRevision(), @@ -374,31 +368,30 @@ void selectedAttestationRejectsRetainedSchemaOneControlPlaneEvidence() throws Ex var retained = retainedV1Participants(selected.participantDigests()); assertThat(retained.getLast().digestSchemaVersion()).isEqualTo(1); assertThat(selected.participantDigests().getLast().digestSchemaVersion()).isEqualTo(2); - assertThatThrownBy( - () -> - new AuthoredWorldReleaseAttestationEvidence( - selected.schemaVersion(), - selected.targetNamespace(), - selected.descriptorResultDigest(), - selected.canonicalTenantId(), - selected.canonicalVersionId(), - selected.worldSlug(), - selected.authoredWorldSourceOperationId(), - selected.authoredWorldSourceEvidenceDigest(), - selected.launchDescriptorId(), - selected.publishedReleaseBundleRef(), - selected.versionStateEpoch(), - selected.publishWorkflowId(), - selected.commitId(), - retained, - selected.manifestHash(), - selected.manifestSchemaVersion(), - selected.requiredManifestAssetKeys(), - selected.artifactDigests(), - selected.commandDefinitions(), - selected.generationConfigRevision(), - selected.evidenceDigest(), - selector)) + assertThatThrownBy(() -> + new AuthoredWorldReleaseAttestationEvidence( + selected.schemaVersion(), + selected.targetNamespace(), + selected.descriptorResultDigest(), + selected.canonicalTenantId(), + selected.canonicalVersionId(), + selected.worldSlug(), + selected.authoredWorldSourceOperationId(), + selected.authoredWorldSourceEvidenceDigest(), + selected.launchDescriptorId(), + selected.publishedReleaseBundleRef(), + selected.versionStateEpoch(), + selected.publishWorkflowId(), + selected.commitId(), + retained, + selected.manifestHash(), + selected.manifestSchemaVersion(), + selected.requiredManifestAssetKeys(), + selected.artifactDigests(), + selected.commandDefinitions(), + selected.generationConfigRevision(), + selected.evidenceDigest(), + selector)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Participant digest schema is unsupported"); } @@ -458,21 +451,20 @@ private static List retaine List selected) { // Stipulated historical evidence, independently scoped to the retained-v1 contract. return selected.stream() - .map( - p -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - p.participantKey(), - p.scopeValue(), - p.baseVersionIdPresent(), - p.baseVersionId(), - p.appliedCommitId(), - "GAME_DESIGN_CONTROL_PLANE".equals(p.participantKey()) - ? "e".repeat(64) - : p.contentDigest(), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - p.participantKey(), AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION), - p.abilitySchemaDigestPresent(), - p.abilitySchemaDigest())) + .map(p -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + p.participantKey(), + p.scopeValue(), + p.baseVersionIdPresent(), + p.baseVersionId(), + p.appliedCommitId(), + "GAME_DESIGN_CONTROL_PLANE".equals(p.participantKey()) + ? "e".repeat(64) + : p.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + p.participantKey(), AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION), + p.abilitySchemaDigestPresent(), + p.abilitySchemaDigest())) .toList(); } @@ -553,19 +545,18 @@ private static AuthoredWorldReleaseAttestationEvidence release( int attestationSchemaVersion) { var participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - owner, - Long.toString(descriptor.versionId()), - false, - null, - selector.request().appliedCommitId(), - "b".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, attestationSchemaVersion), - "GAME_LOGIC".equals(owner), - "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .map(owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + "b".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, attestationSchemaVersion), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) .toList(); if (attestationSchemaVersion == AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/CommandSourceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/CommandSourceTest.java index 93a0281514..037b244400 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/CommandSourceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/CommandSourceTest.java @@ -50,33 +50,31 @@ void explicitDeleteRequiresAnExistingEffectiveCommandKey() { "0", id("delete-revision"), commit, CommandSource.OperationKind.DELETE, "look", null); assertThat(CommandSource.replay(inherited, List.of(delete))).isEmpty(); - assertThatThrownBy( - () -> - CommandSource.replay( - inherited, - List.of( - delete, - new CommandSource.Mutation( - "1", - id("second-delete-revision"), - commit, - CommandSource.OperationKind.DELETE, - "LOOK", - null)))) + assertThatThrownBy(() -> + CommandSource.replay( + inherited, + List.of( + delete, + new CommandSource.Mutation( + "1", + id("second-delete-revision"), + commit, + CommandSource.OperationKind.DELETE, + "LOOK", + null)))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Cannot delete an absent command definition key"); - assertThatThrownBy( - () -> - CommandSource.replay( - List.of(), - List.of( - new CommandSource.Mutation( - "0", - id("absent-delete-revision"), - commit, - CommandSource.OperationKind.DELETE, - "absent", - null)))) + assertThatThrownBy(() -> + CommandSource.replay( + List.of(), + List.of( + new CommandSource.Mutation( + "0", + id("absent-delete-revision"), + commit, + CommandSource.OperationKind.DELETE, + "absent", + null)))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Cannot delete an absent command definition key"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java index be18b8f2df..baba1284ee 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/DraftSynchronizedVisibilityEvidenceTest.java @@ -89,24 +89,22 @@ void rejectsIncompleteOrSubstitutedFenceAndOwnerResults() { assertThatThrownBy(() -> evidence(binding, vector.replace("WORLD_TEMPLATE", "OTHER"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("bound epoch declaration"); - assertThatThrownBy( - () -> - new DraftSynchronizedVisibilityEvidence( - request(), binding, "APPLYING", fence(binding, vector))) + assertThatThrownBy(() -> + new DraftSynchronizedVisibilityEvidence( + request(), binding, "APPLYING", fence(binding, vector))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("not bound"); - assertThatThrownBy( - () -> - new DraftSynchronizedVisibilityEvidence( - request(), - binding, - "SYNCHRONIZED", - new DraftSynchronizedVisibilityEvidence.Fence( - REQUEST_ID, - COMMIT_ID, - "sha256:" + "f".repeat(64), - vector, - OffsetDateTime.parse("2026-10-06T00:00:00Z")))) + assertThatThrownBy(() -> + new DraftSynchronizedVisibilityEvidence( + request(), + binding, + "SYNCHRONIZED", + new DraftSynchronizedVisibilityEvidence.Fence( + REQUEST_ID, + COMMIT_ID, + "sha256:" + "f".repeat(64), + vector, + OffsetDateTime.parse("2026-10-06T00:00:00Z")))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("full input"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java index 5687995444..26fb4786b2 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceClientMtlsTest.java @@ -115,17 +115,15 @@ void pinsGameDesignServerAndRoundTripsBothOwnerScopesOverLoopbackMtls() throws E start(pki.wrongServer()); try (var client = newClient(pki.gameDesignClient())) { client.init(); - assertThatThrownBy( - () -> - client.read( - request( - Owner.ENTITY_MANAGEMENT, - SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) + assertThatThrownBy(() -> + client.read( + request( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(calls).hasValue(2); } } @@ -156,17 +154,15 @@ void requiresExactClientCertificateAndRejectsExpiredServerOrClientCertificates() start(pki.gameDesignServer()); try (var client = newClient(pki.wrongClient())) { client.init(); - assertThatThrownBy( - () -> - client.read( - request( - Owner.ENTITY_MANAGEMENT, - SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) + assertThatThrownBy(() -> + client.read( + request( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); assertThat(calls).hasValue(1); } @@ -176,12 +172,11 @@ void requiresExactClientCertificateAndRejectsExpiredServerOrClientCertificates() start(pki.expiredGameDesignServer()); try (var client = newClient(pki.gameDesignClient())) { client.init(); - assertThatThrownBy( - () -> - client.read( - request( - Owner.ENTITY_MANAGEMENT, - SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) + assertThatThrownBy(() -> + client.read( + request( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) .isInstanceOf(StatusRuntimeException.class); assertThat(calls).hasValue(1); } @@ -192,12 +187,11 @@ void requiresExactClientCertificateAndRejectsExpiredServerOrClientCertificates() start(pki.gameDesignServer()); try (var client = newClient(pki.expiredGameDesignClient())) { client.init(); - assertThatThrownBy( - () -> - client.read( - request( - Owner.ENTITY_MANAGEMENT, - SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) + assertThatThrownBy(() -> + client.read( + request( + Owner.ENTITY_MANAGEMENT, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) .isInstanceOf(StatusRuntimeException.class); assertThat(calls).hasValue(1); } @@ -246,17 +240,15 @@ void boundsUnavailableReadByFiveSecondDeadline() throws Exception { start(pki.gameDesignServer()); try (var client = newClient(pki.gameDesignClient())) { client.init(); - assertThatThrownBy( - () -> - client.read( - request( - Owner.AUTOMATION_SCRIPTING, - SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) + assertThatThrownBy(() -> + client.read( + request( + Owner.AUTOMATION_SCRIPTING, + SelectedOwnerIntakeSourceTestFixtures.selectedRevisionPayload()))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); } } @@ -265,20 +257,18 @@ void requiresTlsAndReadableFileBackedCredentials() { var endpoints = new ServiceEndpointsProperties(); var plaintext = new CommonGrpcClientProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new GrpcSelectedOwnerIntakeSourceClient( - endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + assertThatThrownBy(() -> + new GrpcSelectedOwnerIntakeSourceClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); var classpath = new CommonGrpcClientProperties(); classpath.setCertChain("classpath:client.crt"); classpath.setPrivateKey("/tmp/client.key"); classpath.setCaCert("/tmp/ca.crt"); - assertThatThrownBy( - () -> - new GrpcSelectedOwnerIntakeSourceClient( - endpoints, classpath, new GrpcChannelFactory(), NAMESPACE)) + assertThatThrownBy(() -> + new GrpcSelectedOwnerIntakeSourceClient( + endpoints, classpath, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContentTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContentTest.java index b43910ce8f..ef1c49d150 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContentTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceContentTest.java @@ -295,10 +295,9 @@ void rejectsUnknownOrderDuplicateMissingTruncatedTrailingAndOversizedFrames() { assertInvalid(oversizedFrame, scope, null); byte[] oversizedEnvelope = new byte[SelectedOwnerIntakeSourceContent.MAX_BYTES + 1]; - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceContent.fromStored( - oversizedEnvelope, scope, "sha256:" + "0".repeat(64))) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceContent.fromStored( + oversizedEnvelope, scope, "sha256:" + "0".repeat(64))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodecTest.java index 1adbf6647b..42ab5f5c42 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/SelectedOwnerIntakeSourceProtoCodecTest.java @@ -95,16 +95,14 @@ void requiresTheFullUnchangedRequestEchoBeforeInspectingContent() { for (var substitution : substitutions) { var changedEcho = substitution.apply(response.getRequest().toBuilder()).build(); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceProtoCodec.fromResponse( - request, response.toBuilder().setRequest(changedEcho).build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, response.toBuilder().setRequest(changedEcho).build())) .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceProtoCodec.fromResponse( - request, response.toBuilder().clearRequest().build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, response.toBuilder().clearRequest().build())) .isInstanceOf(IllegalArgumentException.class); } @@ -119,23 +117,20 @@ void rejectsUnknownOuterAndNestedFields() { SelectedOwnerIntakeSourceProtoCodec.toResponse(request, content(request.scope(), 0)); var unknown = unknownFields(); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceProtoCodec.fromRequest( - wireRequest.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceProtoCodec.fromRequest( + wireRequest.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceProtoCodec.fromResponse( - request, response.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, response.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceProtoCodec.fromResponse( - request, - response.toBuilder() - .setRequest(response.getRequest().toBuilder().setUnknownFields(unknown)) - .build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, + response.toBuilder() + .setRequest(response.getRequest().toBuilder().setUnknownFields(unknown)) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -148,26 +143,21 @@ void rejectsContentDigestAndScopeSubstitution() { var original = content(request.scope(), 0); var response = SelectedOwnerIntakeSourceProtoCodec.toResponse(request, original); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceProtoCodec.fromResponse( - request, - response.toBuilder() - .setSelectedSourceDigest("sha256:" + "0".repeat(64)) - .build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, + response.toBuilder().setSelectedSourceDigest("sha256:" + "0".repeat(64)).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceProtoCodec.fromResponse( - request, - response.toBuilder() - .setSelectedSourceContent(ByteString.copyFromUtf8("changed")) - .build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, + response.toBuilder() + .setSelectedSourceContent(ByteString.copyFromUtf8("changed")) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceProtoCodec.fromResponse( - request, response.toBuilder().clearSelectedSourceContent().build())) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceProtoCodec.fromResponse( + request, response.toBuilder().clearSelectedSourceContent().build())) .isInstanceOf(IllegalArgumentException.class); var substitutedScope = scope(Owner.AUTOMATION_SCRIPTING, request.scope().selected()); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodecTest.java index 2be666331d..377ec408f2 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionLaunchDescriptorGrpcCodecTest.java @@ -87,27 +87,24 @@ void rejectsInitialSelectionPartialMixedUnknownAndWrongVersionResponses() throws var complete = StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( fixture.request(), fixture.associationRead(), fixture.descriptor()); - assertThatThrownBy( - () -> - StartSessionLaunchDescriptorGrpcCodec.fromResponse( - fixture.request(), complete.toBuilder().clearLaunchDescriptor().build())) + assertThatThrownBy(() -> + StartSessionLaunchDescriptorGrpcCodec.fromResponse( + fixture.request(), complete.toBuilder().clearLaunchDescriptor().build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - StartSessionLaunchDescriptorGrpcCodec.fromResponse( - fixture.request(), - complete.toBuilder() - .setApplicationFailure( - StartSessionLaunchDescriptorApplicationFailure.newBuilder() - .setCode("INVALID_TEMPLATE_CONFIGURATION") - .setMessage( - "INVALID_TEMPLATE_CONFIGURATION: captured source unavailable")) - .build())) + assertThatThrownBy(() -> + StartSessionLaunchDescriptorGrpcCodec.fromResponse( + fixture.request(), + complete.toBuilder() + .setApplicationFailure( + StartSessionLaunchDescriptorApplicationFailure.newBuilder() + .setCode("INVALID_TEMPLATE_CONFIGURATION") + .setMessage( + "INVALID_TEMPLATE_CONFIGURATION: captured source unavailable")) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - StartSessionLaunchDescriptorGrpcCodec.fromResponse( - fixture.request(), complete.toBuilder().setSchemaVersion(2).build())) + assertThatThrownBy(() -> + StartSessionLaunchDescriptorGrpcCodec.fromResponse( + fixture.request(), complete.toBuilder().setSchemaVersion(2).build())) .isInstanceOf(IllegalArgumentException.class); var unknown = @@ -145,10 +142,9 @@ void rejectsInitialSelectionPartialMixedUnknownAndWrongVersionResponses() throws .build()) .build()) .build(); - assertThatThrownBy( - () -> - StartSessionLaunchDescriptorGrpcCodec.fromResponse( - fixture.request(), unknownDescriptorBinding)) + assertThatThrownBy(() -> + StartSessionLaunchDescriptorGrpcCodec.fromResponse( + fixture.request(), unknownDescriptorBinding)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); } @@ -168,10 +164,9 @@ void roundTripsAClosedCorrelatedApplicationFailureWireOutcome() throws Exception assertThat(decoded.associationRead().request()).isEqualTo(fixture.request()); assertThat(decoded.outcome()) .isEqualTo(new StartSessionLaunchDescriptorGrpcCodec.ApplicationFailure(code, message)); - assertThatThrownBy( - () -> - StartSessionLaunchDescriptorGrpcCodec.toFailureResponse( - fixture.request(), fixture.associationRead(), "UNAVAILABLE", "unavailable")) + assertThatThrownBy(() -> + StartSessionLaunchDescriptorGrpcCodec.toFailureResponse( + fixture.request(), fixture.associationRead(), "UNAVAILABLE", "unavailable")) .isInstanceOf(IllegalArgumentException.class); } @@ -210,10 +205,9 @@ void rejectsDescriptorFieldsThatDoNotMatchTheOriginalAssociationAndRelease() thr original.publishedReleaseBundleRef(), false, null); - assertThatThrownBy( - () -> - StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( - fixture.request(), fixture.associationRead(), substituted)) + assertThatThrownBy(() -> + StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( + fixture.request(), fixture.associationRead(), substituted)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("original StartSession tuple and association"); @@ -231,10 +225,9 @@ void rejectsDescriptorFieldsThatDoNotMatchTheOriginalAssociationAndRelease() thr original.publishedReleaseBundleRef(), false, null); - assertThatThrownBy( - () -> - StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( - fixture.request(), fixture.associationRead(), substitutedVersion)) + assertThatThrownBy(() -> + StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( + fixture.request(), fixture.associationRead(), substitutedVersion)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("version or release"); @@ -252,10 +245,9 @@ void rejectsDescriptorFieldsThatDoNotMatchTheOriginalAssociationAndRelease() thr original.publishedReleaseBundleRef(), false, null); - assertThatThrownBy( - () -> - StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( - fixture.request(), fixture.associationRead(), changedRuntimeFlags)) + assertThatThrownBy(() -> + StartSessionLaunchDescriptorGrpcCodec.toDescriptorResponse( + fixture.request(), fixture.associationRead(), changedRuntimeFlags)) .isInstanceOf(IllegalArgumentException.class); var response = @@ -268,10 +260,9 @@ void rejectsDescriptorFieldsThatDoNotMatchTheOriginalAssociationAndRelease() thr .setVersionId(response.getLaunchDescriptor().getVersionId() + 1L) .build()) .build(); - assertThatThrownBy( - () -> - StartSessionLaunchDescriptorGrpcCodec.fromResponse( - fixture.request(), changedFlatVersion)) + assertThatThrownBy(() -> + StartSessionLaunchDescriptorGrpcCodec.fromResponse( + fixture.request(), changedFlatVersion)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodecTest.java index acb7bce812..04641cfbb4 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/StartSessionTemplateAssociationReadGrpcCodecTest.java @@ -79,10 +79,9 @@ void initialAndExactReplayHaveClosedDeterministicRequestVectors() { void rejectsMissingSelectionUnknownFieldsNoncanonicalIdsAndChangedNamespace() { var valid = StartSessionTemplateAssociationReadGrpcCodec.toRequest(request(new InitialConfigured())); - assertThatThrownBy( - () -> - StartSessionTemplateAssociationReadGrpcCodec.fromRequest( - valid.toBuilder().clearSelection().build())) + assertThatThrownBy(() -> + StartSessionTemplateAssociationReadGrpcCodec.fromRequest( + valid.toBuilder().clearSelection().build())) .isInstanceOf(IllegalArgumentException.class); var unknown = @@ -104,17 +103,16 @@ void rejectsMissingSelectionUnknownFieldsNoncanonicalIdsAndChangedNamespace() { .isInstanceOf(IllegalArgumentException.class); var tuple = postTuple("codec-namespace"); - assertThatThrownBy( - () -> - StartSessionTemplateAssociationReadGrpcCodec.toRequest( - new StartSessionTemplateAssociationReadEvidence.Request( - 1, - "another-runtime", - READ_ID, - tuple.canonicalBytes(), - ATTEMPT, - 8L, - new InitialConfigured()))) + assertThatThrownBy(() -> + StartSessionTemplateAssociationReadGrpcCodec.toRequest( + new StartSessionTemplateAssociationReadEvidence.Request( + 1, + "another-runtime", + READ_ID, + tuple.canonicalBytes(), + ATTEMPT, + 8L, + new InitialConfigured()))) .isInstanceOf(IllegalArgumentException.class); } @@ -143,10 +141,9 @@ void preservesChangedAttemptFieldsAndRejectsOversizedOrUnknownNestedFields() { [net.firedevops.firemud.common.operator.StartSessionPostAuthorizationExecutionTuple .MAX_CANONICAL_TUPLE_BYTES + 1]; - assertThatThrownBy( - () -> - new StartSessionTemplateAssociationReadEvidence.Request( - 1, "world-runtime", READ_ID, oversized, ATTEMPT, 8L, new InitialConfigured())) + assertThatThrownBy(() -> + new StartSessionTemplateAssociationReadEvidence.Request( + 1, "world-runtime", READ_ID, oversized, ATTEMPT, 8L, new InitialConfigured())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("bounded"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceValuesTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceValuesTest.java index 46ded48d82..2430e76416 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceValuesTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/TemplateConfigSourceValuesTest.java @@ -76,17 +76,14 @@ void rejectsWrongSchemaForEachOwner() { TemplateConfigSourceValues.ownerInventoryPayload(Owner.AUTOMATION_SCRIPTING, automation()); String entityPayload = TemplateConfigSourceValues.ownerInventoryPayload(Owner.ENTITY_MANAGEMENT, entity()); - assertThatThrownBy( - () -> - TemplateConfigSourceValues.mutations( - binding( - automationPayload.replace("\"schemaVersion\":2", "\"schemaVersion\":3")))) + assertThatThrownBy(() -> + TemplateConfigSourceValues.mutations( + binding(automationPayload.replace("\"schemaVersion\":2", "\"schemaVersion\":3")))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Automation"); - assertThatThrownBy( - () -> - TemplateConfigSourceValues.mutations( - binding(entityPayload.replace("\"schemaVersion\":3", "\"schemaVersion\":2")))) + assertThatThrownBy(() -> + TemplateConfigSourceValues.mutations( + binding(entityPayload.replace("\"schemaVersion\":3", "\"schemaVersion\":2")))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Entity"); } @@ -108,15 +105,11 @@ Owner.AUTOMATION_SCRIPTING, automation()), assertThatThrownBy(() -> TemplateConfigSourceValues.mutations(binding(unsupported))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("supported owner"); - assertThatThrownBy( - () -> - TemplateConfigSourceValues.ownerInventoryPayload( - Owner.ENTITY_MANAGEMENT, automation())) + assertThatThrownBy(() -> + TemplateConfigSourceValues.ownerInventoryPayload(Owner.ENTITY_MANAGEMENT, automation())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - TemplateConfigSourceValues.ownerInventoryPayload( - Owner.AUTOMATION_SCRIPTING, entity())) + assertThatThrownBy(() -> + TemplateConfigSourceValues.ownerInventoryPayload(Owner.AUTOMATION_SCRIPTING, entity())) .isInstanceOf(IllegalArgumentException.class); } @@ -126,28 +119,25 @@ void missingOrMismatchedRevisionUsesArgumentFailureForBothDeclarationsAndRowMuta TemplateConfigSourceValues.ownerInventoryPayload(Owner.AUTOMATION_SCRIPTING, automation()); var binding = binding(payload); UUID revisionId = binding.revisions().getFirst().revisionId(); - assertThatThrownBy( - () -> - new TemplateConfigOwnerSourceInventoryDeclaration( - Owner.AUTOMATION_SCRIPTING, automation(), binding, "1", revisionId)) + assertThatThrownBy(() -> + new TemplateConfigOwnerSourceInventoryDeclaration( + Owner.AUTOMATION_SCRIPTING, automation(), binding, "1", revisionId)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Exact original"); - assertThatThrownBy( - () -> - new TemplateConfigOwnerSourceInventoryDeclaration( - Owner.ENTITY_MANAGEMENT, entity(), binding, "0", UUID.randomUUID())) + assertThatThrownBy(() -> + new TemplateConfigOwnerSourceInventoryDeclaration( + Owner.ENTITY_MANAGEMENT, entity(), binding, "0", UUID.randomUUID())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Exact original"); - assertThatThrownBy( - () -> - new TemplateConfigSourceValues.Mutation( - binding, - "1", - revisionId, - TemplateConfigSourceValues.OperationKind.DELETE, - "1", - null, - null)) + assertThatThrownBy(() -> + new TemplateConfigSourceValues.Mutation( + binding, + "1", + revisionId, + TemplateConfigSourceValues.OperationKind.DELETE, + "1", + null, + null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Exact original"); var wrongOwner = @@ -159,10 +149,9 @@ Owner.ENTITY_MANAGEMENT, entity(), binding, "0", UUID.randomUUID())) List.of(new RevisionPayload("0", revisionId, Owner.WORLD_MANAGEMENT, payload)), List.of( new AffectedUnit(Owner.WORLD_MANAGEMENT, "inventory", "1", "inventory", "1", "0"))); - assertThatThrownBy( - () -> - new TemplateConfigOwnerSourceInventoryDeclaration( - Owner.AUTOMATION_SCRIPTING, automation(), wrongOwner, "0", revisionId)) + assertThatThrownBy(() -> + new TemplateConfigOwnerSourceInventoryDeclaration( + Owner.AUTOMATION_SCRIPTING, automation(), wrongOwner, "0", revisionId)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Exact original"); } @@ -185,16 +174,13 @@ void requiresTextualTargetScopeIdButAllowsAnEmptyValue() { assertThat(new TemplateConfigSourceValues.Config(validWithEmptyTargetId).canonicalJson()) .contains("\"targetScopeId\":\"\""); - assertThatThrownBy( - () -> - new TemplateConfigSourceValues.Config( - validWithEmptyTargetId.replace(",\"targetScopeId\":\"\"", ""))) + assertThatThrownBy(() -> + new TemplateConfigSourceValues.Config( + validWithEmptyTargetId.replace(",\"targetScopeId\":\"\"", ""))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new TemplateConfigSourceValues.Config( - validWithEmptyTargetId.replace( - "\"targetScopeId\":\"\"", "\"targetScopeId\":1"))) + assertThatThrownBy(() -> + new TemplateConfigSourceValues.Config( + validWithEmptyTargetId.replace("\"targetScopeId\":\"\"", "\"targetScopeId\":1"))) .isInstanceOf(IllegalArgumentException.class); } @@ -217,13 +203,12 @@ private static String templateConfig( private static DraftCommitBinding binding(String... payloads) { var revisions = IntStream.range(0, payloads.length) - .mapToObj( - i -> - new RevisionPayload( - Integer.toString(i), - UUID.randomUUID(), - Owner.GAME_DESIGN_CONTROL_PLANE, - payloads[i])) + .mapToObj(i -> + new RevisionPayload( + Integer.toString(i), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + payloads[i])) .toList(); return DraftCommitBinding.create( new TargetProof( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java index 45a7c564d2..6388e093b8 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/WorldCanonicalInstanceLifecycleClientMtlsTest.java @@ -130,10 +130,9 @@ void trustedWrongWorldWorkloadAndNamespaceCannotSendRequestMetadataOrBody() thro assertThatThrownBy(() -> client.read(expected.request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(serverCallStarts).as(wrongPeer.alias()).hasValue(0); assertThat(applicationCalls).as(wrongPeer.alias()).hasValue(0); stopTransport(); @@ -172,25 +171,17 @@ void refusesPlaintextClasspathFilesAndCallsBeforeExplicitInitialization() throws receivedPeerUri = new AtomicReference<>(); var plaintext = pki.clientProperties(tempDirectory); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new WorldCanonicalInstanceLifecycleClient( - new ServiceEndpointsProperties(), - plaintext, - new GrpcChannelFactory(), - NAMESPACE)) + assertThatThrownBy(() -> + new WorldCanonicalInstanceLifecycleClient( + new ServiceEndpointsProperties(), plaintext, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("workload mTLS"); var classpath = pki.clientProperties(tempDirectory); classpath.setCaCert("classpath:ca.crt"); - assertThatThrownBy( - () -> - new WorldCanonicalInstanceLifecycleClient( - new ServiceEndpointsProperties(), - classpath, - new GrpcChannelFactory(), - NAMESPACE)) + assertThatThrownBy(() -> + new WorldCanonicalInstanceLifecycleClient( + new ServiceEndpointsProperties(), classpath, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("file-backed"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java index 998d13be94..186f3ad533 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AccountGameLogicIntakeSettlementReadGrpcTest.java @@ -124,78 +124,65 @@ void rejectsChangedEvidenceOversizeTrailingAndNoncanonicalReceipts() { var evidence = evidence("test", 1, Outcome.RETAINED); var wire = AccountGameLogicIntakeSettlementProtoCodec.toResponse(evidence); var changed = evidence("test", 1, Outcome.RETAINED); - assertThatThrownBy( - () -> - new AccountGameLogicIntakeSettlementReadEvidence( - evidence.request(), changed.receipt())) + assertThatThrownBy(() -> + new AccountGameLogicIntakeSettlementReadEvidence(evidence.request(), changed.receipt())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountGameLogicIntakeSettlementReadEvidence( - AccountGameLogicIntakeSettlementReadEvidence.Request.create( - "other", evidence.request().binding()), - evidence.receipt())) + assertThatThrownBy(() -> + new AccountGameLogicIntakeSettlementReadEvidence( + AccountGameLogicIntakeSettlementReadEvidence.Request.create( + "other", evidence.request().binding()), + evidence.receipt())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameLogicIntakeSettlementProtoCodec.fromResponse( - evidence.request(), - wire.toBuilder() - .setSettlementReceiptDigest("sha256:" + "0".repeat(64)) - .build())) + assertThatThrownBy(() -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), + wire.toBuilder().setSettlementReceiptDigest("sha256:" + "0".repeat(64)).build())) .isInstanceOf(IllegalArgumentException.class); var unknown = com.google.protobuf.UnknownFieldSet.newBuilder() .addField( 99, com.google.protobuf.UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); - assertThatThrownBy( - () -> - AccountGameLogicIntakeSettlementProtoCodec.fromRequest( - wire.getRequest().toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + AccountGameLogicIntakeSettlementProtoCodec.fromRequest( + wire.getRequest().toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameLogicIntakeSettlementProtoCodec.fromResponse( - evidence.request(), - wire.toBuilder() - .setRequest(wire.getRequest().toBuilder().setUnknownFields(unknown)) - .build())) + assertThatThrownBy(() -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), + wire.toBuilder() + .setRequest(wire.getRequest().toBuilder().setUnknownFields(unknown)) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameLogicIntakeSettlementProtoCodec.fromResponse( - evidence.request(), - wire.toBuilder() - .setRequest(wire.getRequest().toBuilder().setTargetNamespace("other")) - .build())) + assertThatThrownBy(() -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), + wire.toBuilder() + .setRequest(wire.getRequest().toBuilder().setTargetNamespace("other")) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameLogicIntakeSettlementProtoCodec.fromResponse( - evidence.request(), - wire.toBuilder() - .setOriginalSettlementReceipt( - ByteString.copyFrom(changed.receipt().canonicalBytes())) - .setSettlementReceiptDigest(changed.receipt().digest()) - .build())) + assertThatThrownBy(() -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), + wire.toBuilder() + .setOriginalSettlementReceipt( + ByteString.copyFrom(changed.receipt().canonicalBytes())) + .setSettlementReceiptDigest(changed.receipt().digest()) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameLogicIntakeSettlementProtoCodec.fromResponse( - evidence.request(), wire.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), wire.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameLogicIntakeSettlementProtoCodec.fromRequest( - wire.getRequest().toBuilder().setIntakeAuthorizationDigest("changed").build())) + assertThatThrownBy(() -> + AccountGameLogicIntakeSettlementProtoCodec.fromRequest( + wire.getRequest().toBuilder().setIntakeAuthorizationDigest("changed").build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameLogicIntakeSettlementProtoCodec.fromRequest( - wire.getRequest().toBuilder() - .setOriginalIntakeAuthorization(ByteString.copyFrom(new byte[4194305])) - .build())) + assertThatThrownBy(() -> + AccountGameLogicIntakeSettlementProtoCodec.fromRequest( + wire.getRequest().toBuilder() + .setOriginalIntakeAuthorization(ByteString.copyFrom(new byte[4194305])) + .build())) .isInstanceOf(IllegalArgumentException.class); byte[] trailing = java.util.Arrays.copyOf( @@ -206,24 +193,21 @@ void rejectsChangedEvidenceOversizeTrailingAndNoncanonicalReceipts() { wrongSchema[Integer.BYTES] ^= 1; assertThatThrownBy(() -> AccountGameLogicIntakeSettlementEvidence.fromStored(wrongSchema)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameLogicIntakeSettlementProtoCodec.fromResponse( - evidence.request(), - wire.toBuilder() - .setOriginalSettlementReceipt( - ByteString.copyFrom( - new byte - [AccountGameLogicIntakeSettlementEvidence.MAX_CANONICAL_BYTES - + 1])) - .build())) + assertThatThrownBy(() -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), + wire.toBuilder() + .setOriginalSettlementReceipt( + ByteString.copyFrom( + new byte + [AccountGameLogicIntakeSettlementEvidence.MAX_CANONICAL_BYTES + 1])) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameLogicIntakeSettlementProtoCodec.fromResponse( - evidence.request(), - net.firedevops.firemud.account.v1.SettleGameLogicIntakeResponse - .getDefaultInstance())) + assertThatThrownBy(() -> + AccountGameLogicIntakeSettlementProtoCodec.fromResponse( + evidence.request(), + net.firedevops.firemud.account.v1.SettleGameLogicIntakeResponse + .getDefaultInstance())) .isInstanceOf(IllegalArgumentException.class); } @@ -232,10 +216,9 @@ void requiresFileBackedMtlsConfiguredNamespaceAndNoAmbientSql() throws Exception var endpoints = new ServiceEndpointsProperties(); var plaintext = new CommonGrpcClientProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new GrpcAccountGameLogicIntakeSettlementReadClient( - endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + assertThatThrownBy(() -> + new GrpcAccountGameLogicIntakeSettlementReadClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); client = new GrpcAccountGameLogicIntakeSettlementReadClient( @@ -245,11 +228,10 @@ endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) NAMESPACE); var evidence = evidence("test", 1, Outcome.ABORTED); assertSanitizedUnavailable(() -> client.read(evidence.request())); - assertThatThrownBy( - () -> - client.read( - AccountGameLogicIntakeSettlementReadEvidence.Request.create( - "other", evidence.request().binding()))) + assertThatThrownBy(() -> + client.read( + AccountGameLogicIntakeSettlementReadEvidence.Request.create( + "other", evidence.request().binding()))) .isInstanceOf(IllegalArgumentException.class); org.springframework.transaction.support.TransactionSynchronizationManager .setActualTransactionActive(true); @@ -290,10 +272,9 @@ void actualMtlsCarriesReceiptAboveFourMiBAndRejectsSubstitutedServerBeforeDispat client.init(); assertThatThrownBy(() -> client.read(large.request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(headers).hasValue(0); assertThat(bodies).hasValue(0); } @@ -382,13 +363,12 @@ private GrpcAccountGameLogicIntakeSettlementReadClient newClient( private static void assertSanitizedUnavailable(ThrowingCallable operation) { assertThatThrownBy(operation) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - var status = Status.fromThrowable(failure); - assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); - assertThat(status.getDescription()).isNull(); - assertThat(failure.getCause()).isNull(); - }); + .satisfies(failure -> { + var status = Status.fromThrowable(failure); + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status.getDescription()).isNull(); + assertThat(failure.getCause()).isNull(); + }); } /** These canonical bytes are deliberately synthetic transport evidence, not owner provenance. */ diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java index 242a40197b..2457ac4910 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/AutomationSelectedSourceIntakeTerminalReadClientMtlsTest.java @@ -84,9 +84,8 @@ void authenticatesAccountClientAndPinsSameNamespaceAutomationServer() throws Exc assertThatThrownBy(() -> client.read(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()).isEqualTo(Status.Code.NOT_FOUND)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()).isEqualTo(Status.Code.NOT_FOUND)); assertThat(calls).hasValue(1); server.shutdownNow(); @@ -95,10 +94,9 @@ void authenticatesAccountClientAndPinsSameNamespaceAutomationServer() throws Exc startServer(pki.wrongServer(), serverPort); assertThatThrownBy(() -> client.read(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(calls).hasValue(1); } @@ -113,14 +111,13 @@ void authenticatedMalformedResponseIsFailedPrecondition() throws Exception { client.init(); assertThatThrownBy(() -> client.read(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> { - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION); - assertThat(Status.fromThrowable(error).getDescription()) - .isEqualTo("Automation returned invalid terminal evidence"); - assertThat(error.getCause()).isInstanceOf(IllegalArgumentException.class); - }); + .satisfies(error -> { + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(Status.fromThrowable(error).getDescription()) + .isEqualTo("Automation returned invalid terminal evidence"); + assertThat(error.getCause()).isInstanceOf(IllegalArgumentException.class); + }); assertThat(calls).hasValue(1); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodecTest.java index d63824aaca..6b6ab0da35 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationGrpcCodecTest.java @@ -71,65 +71,56 @@ void rejectsUnknownChangedAndNoncanonicalEvidenceAndCredentialInputs() { GameLogicIntakeAuthorizationGrpcCodec.toResponse( GameLogicIntakeAuthorizationEvidence.Result.authorized( request, authorization(request))); - assertThatThrownBy( - () -> - GameLogicIntakeAuthorizationGrpcCodec.fromRequest( - wireRequest.toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField( - 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) - .build()) - .build())) + assertThatThrownBy(() -> + GameLogicIntakeAuthorizationGrpcCodec.fromRequest( + wireRequest.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicIntakeAuthorizationGrpcCodec.fromResponse( - request, - response.toBuilder() - .setRequest( - wireRequest.toBuilder() - .setTransportRequestId(UUID.randomUUID().toString()) - .build()) - .build())) + assertThatThrownBy(() -> + GameLogicIntakeAuthorizationGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + wireRequest.toBuilder() + .setTransportRequestId(UUID.randomUUID().toString()) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicIntakeAuthorizationGrpcCodec.fromResponse( - request, - response.toBuilder() - .setRequest( - wireRequest.toBuilder() - .setSelectedDraftBinding(ByteString.copyFromUtf8("{}")) - .build()) - .build())) + assertThatThrownBy(() -> + GameLogicIntakeAuthorizationGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + wireRequest.toBuilder() + .setSelectedDraftBinding(ByteString.copyFromUtf8("{}")) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicIntakeAuthorizationGrpcCodec.fromResponse( - request, response.toBuilder().setOutcomeValue(99).build())) + assertThatThrownBy(() -> + GameLogicIntakeAuthorizationGrpcCodec.fromResponse( + request, response.toBuilder().setOutcomeValue(99).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicIntakeAuthorizationGrpcCodec.fromRequest( - wireRequest.toBuilder() - .setSelectedDraftBinding( - ByteString.copyFrom( - new byte - [GameLogicIntakeAuthorizationEvidence.MAX_SELECTION_BYTES + 1])) - .build())) + assertThatThrownBy(() -> + GameLogicIntakeAuthorizationGrpcCodec.fromRequest( + wireRequest.toBuilder() + .setSelectedDraftBinding( + ByteString.copyFrom( + new byte[GameLogicIntakeAuthorizationEvidence.MAX_SELECTION_BYTES + 1])) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameLogicIntakeAuthorizationCredentials.Credential.of("contains whitespace")) + assertThatThrownBy(() -> + AccountGameLogicIntakeAuthorizationCredentials.Credential.of("contains whitespace")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GameLogicIntakeAuthorizationEvidence.Result( - request, - GameLogicIntakeAuthorizationEvidence.Outcome.FINALIZED, - Optional.of(scope(request)), - Optional.of(authorization(request)))) + assertThatThrownBy(() -> + new GameLogicIntakeAuthorizationEvidence.Result( + request, + GameLogicIntakeAuthorizationEvidence.Outcome.FINALIZED, + Optional.of(scope(request)), + Optional.of(authorization(request)))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java index 3d81fba34c..843633345f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeAuthorizationReadClientMtlsTest.java @@ -125,10 +125,9 @@ void pinsAccountServerAndRejectsOtherAuthenticatedCaller() throws Exception { client.init(); assertThatThrownBy(() -> client.read(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); assertThat(calls).hasValue(0); } @@ -310,12 +309,10 @@ private void close() throws Exception { private static void assertUnavailable(ThrowingCallable call) { assertThatThrownBy(call) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE); - assertThat(Status.fromThrowable(failure).getDescription()).isNull(); - assertThat(failure.getCause()).isNull(); - }); + .satisfies(failure -> { + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(Status.fromThrowable(failure).getDescription()).isNull(); + assertThat(failure.getCause()).isNull(); + }); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java index fd9514170f..a079262941 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeSourceReadTransportTest.java @@ -89,50 +89,41 @@ void roundTripsBothClosedProofsAndRejectsChangedEchoAndUnknownOrAbsentProof() { var response = GameLogicIntakeSourceReadProtoCodec.toResponse(request); assertThat(GameLogicIntakeSourceReadProtoCodec.fromResponse(request, response).request()) .isEqualTo(request); - assertThatThrownBy( - () -> - GameLogicIntakeSourceReadProtoCodec.fromResponse( - request, - response.toBuilder() - .setRequest( - wire.toBuilder().setReadRequestId(UUID.randomUUID().toString())) - .build())) + assertThatThrownBy(() -> + GameLogicIntakeSourceReadProtoCodec.fromResponse( + request, + response.toBuilder() + .setRequest(wire.toBuilder().setReadRequestId(UUID.randomUUID().toString())) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicIntakeSourceReadProtoCodec.fromResponse( - request, response.toBuilder().setPermitted(false).build())) + assertThatThrownBy(() -> + GameLogicIntakeSourceReadProtoCodec.fromResponse( + request, response.toBuilder().setPermitted(false).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicIntakeSourceReadProtoCodec.fromRequest( - wire.toBuilder().clearAuthorizationProof().build())) + assertThatThrownBy(() -> + GameLogicIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().clearAuthorizationProof().build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicIntakeSourceReadProtoCodec.fromRequest( - wire.toBuilder() - .setAuthorizationProofDigest("sha256:" + "0".repeat(64)) - .build())) + assertThatThrownBy(() -> + GameLogicIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setAuthorizationProofDigest("sha256:" + "0".repeat(64)).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicIntakeSourceReadProtoCodec.fromRequest( - wire.toBuilder().setPurpose("PUBLICATION").build())) + assertThatThrownBy(() -> + GameLogicIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder().setPurpose("PUBLICATION").build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicIntakeSourceReadProtoCodec.fromRequest( - wire.toBuilder() - .setUnknownFields( - com.google.protobuf.UnknownFieldSet.newBuilder() - .addField( - 99, - com.google.protobuf.UnknownFieldSet.Field.newBuilder() - .addVarint(1) - .build()) - .build()) - .build())) + assertThatThrownBy(() -> + GameLogicIntakeSourceReadProtoCodec.fromRequest( + wire.toBuilder() + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, + com.google.protobuf.UnknownFieldSet.Field.newBuilder() + .addVarint(1) + .build()) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class); } } @@ -196,18 +187,13 @@ void rejectsNamespaceAmbientSqlMissingTlsAndSubstitutedResponse() throws Excepti var endpoints = new ServiceEndpointsProperties(); var plaintext = new CommonGrpcClientProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new GrpcGameLogicIntakeSourceReadClient( - endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + assertThatThrownBy(() -> + new GrpcGameLogicIntakeSourceReadClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GrpcGameLogicIntakeSourceReadClient( - endpoints, - new CommonGrpcClientProperties(), - new GrpcChannelFactory(), - NAMESPACE)) + assertThatThrownBy(() -> + new GrpcGameLogicIntakeSourceReadClient( + endpoints, new CommonGrpcClientProperties(), new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); start(pki.server()); client = newClient(pki.client()); @@ -244,10 +230,9 @@ void boundsUnavailableReadByDeadline() throws Exception { client.init(); assertThatThrownBy(() -> client.read(requests().getFirst())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); } @Test @@ -265,10 +250,9 @@ void rejectsOtherAuthenticatedClientWorkload() throws Exception { client.init(); assertThatThrownBy(() -> client.read(requests().getFirst())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); assertThat(calls).hasValue(0); } @@ -576,12 +560,10 @@ private static GameplayRuleSelectedSource selectedSource(DraftCommitBinding bind private static void assertUnavailable(ThrowingCallable call) { assertThatThrownBy(call) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE); - assertThat(Status.fromThrowable(failure).getDescription()).isNull(); - assertThat(failure.getCause()).isNull(); - }); + .satisfies(failure -> { + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(Status.fromThrowable(failure).getDescription()).isNull(); + assertThat(failure.getCause()).isNull(); + }); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java index 9901ffc7ff..75ac570370 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicIntakeTerminalReadGrpcTest.java @@ -132,12 +132,11 @@ void closeReleasesClientMonitorBeforeDrainingCertificateCallback( GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); when(channelFactory.buildChannel( any(String.class), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) - .thenAnswer( - invocation -> { - ManagedChannel channel = mock(ManagedChannel.class); - channels.add(channel); - return channel; - }); + .thenAnswer(invocation -> { + ManagedChannel channel = mock(ManagedChannel.class); + channels.add(channel); + return channel; + }); ClientHandle handle = kind.create(endpoints, tls, channelFactory); client = handle.client(); handle.initialize().run(); @@ -372,10 +371,9 @@ void loopbackStrictMtlsTransportsLargeCanonicalTerminalAndPinsBothPeerIdentities client.init(); assertThatThrownBy(() -> client.read(large.request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(headers).hasValue(0); assertThat(bodies).hasValue(0); } @@ -445,13 +443,12 @@ private GameLogicIntakeTerminalReadClient newClient(Server target, IntakeTestPki private static void assertSanitizedUnavailable(ThrowingCallable operation) { assertThatThrownBy(operation) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - var status = Status.fromThrowable(failure); - assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); - assertThat(status.getDescription()).isNull(); - assertThat(failure.getCause()).isNull(); - }); + .satisfies(failure -> { + var status = Status.fromThrowable(failure); + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status.getDescription()).isNull(); + assertThat(failure.getCause()).isNull(); + }); } /** These canonical bytes are deliberately synthetic transport evidence, not owner provenance. */ diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBindingTest.java index 0c9b2f8a4d..ea0cb145c3 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBindingTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadBindingTest.java @@ -102,23 +102,18 @@ void freezesExactThreeFramePreimageAndRoundTripsTheRetainedAuthorization() throw @Test void rejectsMismatchedTenantVersionAndScriptPatchScope() { var authorization = authorization(OPERATION, FENCE, COMMIT, TENANT, 41); - assertThatThrownBy( - () -> - new GameLogicPublicationSourceReadBinding( - publicationRequest("88888888-8888-4888-8888-888888888888", "41"), - authorization)) + assertThatThrownBy(() -> + new GameLogicPublicationSourceReadBinding( + publicationRequest("88888888-8888-4888-8888-888888888888", "41"), authorization)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GameLogicPublicationSourceReadBinding( - publicationRequest(TENANT.toString(), "42"), authorization)) + assertThatThrownBy(() -> + new GameLogicPublicationSourceReadBinding( + publicationRequest(TENANT.toString(), "42"), authorization)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GameLogicPublicationSourceReadBinding( - PublicationDigestRequestBinding.patch( - TENANT.toString(), "41", "patch-1", "pub-1"), - authorization)) + assertThatThrownBy(() -> + new GameLogicPublicationSourceReadBinding( + PublicationDigestRequestBinding.patch(TENANT.toString(), "41", "patch-1", "pub-1"), + authorization)) .isInstanceOf(IllegalArgumentException.class); } @@ -160,59 +155,51 @@ void rejectsMalformedNoncanonicalTruncatedTrailingAndOversizedFrames() { publicationRequest, authorization(OPERATION, FENCE, COMMIT, TENANT, 41)) .canonicalBytes(); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadBinding.fromStored( - publicationRequest, concat(bytes("0"), valid))) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, concat(bytes("0"), valid))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadBinding.fromStored( - publicationRequest, concat(bytes("+"), valid))) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, concat(bytes("+"), valid))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadBinding.fromStored( - publicationRequest, java.util.Arrays.copyOf(valid, valid.length - 1))) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, java.util.Arrays.copyOf(valid, valid.length - 1))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadBinding.fromStored( - publicationRequest, - concat( - asciiFrame(GameLogicPublicationSourceReadBinding.SCHEMA), - asciiFrame(publicationRequest.canonicalPreimage())))) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, + concat( + asciiFrame(GameLogicPublicationSourceReadBinding.SCHEMA), + asciiFrame(publicationRequest.canonicalPreimage())))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadBinding.fromStored( - publicationRequest, concat(valid, asciiFrame(bytes("extra"))))) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, concat(valid, asciiFrame(bytes("extra"))))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadBinding.fromStored( - publicationRequest, - concat( - asciiFrame(GameLogicPublicationSourceReadBinding.SCHEMA), - asciiFrame(publicationRequest.canonicalPreimage()), - bytes("4194305:")))) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, + concat( + asciiFrame(GameLogicPublicationSourceReadBinding.SCHEMA), + asciiFrame(publicationRequest.canonicalPreimage()), + bytes("4194305:")))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadBinding.fromStored( - publicationRequest, - new byte[GameLogicPublicationSourceReadBinding.MAX_TOTAL_BYTES + 1])) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, + new byte[GameLogicPublicationSourceReadBinding.MAX_TOTAL_BYTES + 1])) .isInstanceOf(IllegalArgumentException.class); for (UUID identity : List.of(OPERATION, FENCE, COMMIT)) { - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadBinding.fromStored( - publicationRequest, - replaceFirst( - valid, - bytes(identity.toString()), - bytes("x" + identity.toString().substring(1))))) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadBinding.fromStored( + publicationRequest, + replaceFirst( + valid, + bytes(identity.toString()), + bytes("x" + identity.toString().substring(1))))) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadGrpcCodecTest.java index a5f9cc5fcb..e705491e1f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameLogicPublicationSourceReadGrpcCodecTest.java @@ -77,34 +77,27 @@ void rejectsChangedPublicationRequestIdentityScopeAndUnknownFields() { GetDraftDesignDigestRequest request = GameLogicPublicationSourceReadGrpcCodec.toRequest(fixture.binding()); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadGrpcCodec.fromRequest( - request.toBuilder().setDerivedWorkflowIdentity("publish:wrong").build())) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadGrpcCodec.fromRequest( + request.toBuilder().setDerivedWorkflowIdentity("publish:wrong").build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadGrpcCodec.fromRequest( - request.toBuilder().setRequestDigest("0".repeat(64)).build())) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadGrpcCodec.fromRequest( + request.toBuilder().setRequestDigest("0".repeat(64)).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadGrpcCodec.fromRequest( - request.toBuilder().setScriptPatchVersion("patch-1").build())) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadGrpcCodec.fromRequest( + request.toBuilder().setScriptPatchVersion("patch-1").build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadGrpcCodec.fromRequest( - request.toBuilder().setSourceReadBindingDigest("sha256:changed").build())) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadGrpcCodec.fromRequest( + request.toBuilder().setSourceReadBindingDigest("sha256:changed").build())) .isInstanceOf(IllegalArgumentException.class); byte[] substituted = request.getSourceReadBinding().toByteArray(); substituted[0] ^= 1; - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadGrpcCodec.fromRequest( - request.toBuilder() - .setSourceReadBinding(ByteString.copyFrom(substituted)) - .build())) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadGrpcCodec.fromRequest( + request.toBuilder().setSourceReadBinding(ByteString.copyFrom(substituted)).build())) .isInstanceOf(IllegalArgumentException.class); GetDraftDesignDigestRequest requestWithUnknown = @@ -128,28 +121,24 @@ void rejectsChangedResponseTenantVersionCommitAndBindingCorrelation() { response.toBuilder().setBaseVersionId("42").build(), response.toBuilder().setScriptPatchVersion("patch-1").build(), response.toBuilder().setSourceReadBindingDigest("sha256:changed").build())) { - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadGrpcCodec.fromResponse(fixture.binding(), changed)) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse(fixture.binding(), changed)) .isInstanceOf(IllegalArgumentException.class); } byte[] substitutedBinding = response.getSourceReadBinding().toByteArray(); substitutedBinding[substitutedBinding.length - 1] ^= 1; - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadGrpcCodec.fromResponse( - fixture.binding(), - response.toBuilder() - .setSourceReadBinding(ByteString.copyFrom(substitutedBinding)) - .build())) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), + response.toBuilder() + .setSourceReadBinding(ByteString.copyFrom(substitutedBinding)) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadGrpcCodec.fromResponse( - fixture.binding(), - response.toBuilder().setUnknownFields(unknownField()).build())) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), response.toBuilder().setUnknownFields(unknownField()).build())) .isInstanceOf(IllegalArgumentException.class); } @@ -159,16 +148,14 @@ void rejectsChangedTerminalDigestOperationFenceCommitAndNamespace() { GetDraftDesignDigestResponse response = GameLogicPublicationSourceReadGrpcCodec.toResponse(fixture.binding(), fixture.terminal()); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadGrpcCodec.fromResponse( - fixture.binding(), - response.toBuilder().setRetainedIntakeTerminalDigest("sha256:changed").build())) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), + response.toBuilder().setRetainedIntakeTerminalDigest("sha256:changed").build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadGrpcCodec.fromResponse( - fixture.binding(), response, "other")) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), response, "other")) .isInstanceOf(IllegalArgumentException.class); List substitutedBindings = @@ -193,9 +180,8 @@ void rejectsChangedTerminalDigestOperationFenceCommitAndNamespace() { GetDraftDesignDigestResponse changed = GameLogicPublicationSourceReadGrpcCodec.toResponse( substituted.binding(), substituted.terminal()); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadGrpcCodec.fromResponse(fixture.binding(), changed)) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse(fixture.binding(), changed)) .isInstanceOf(IllegalArgumentException.class); } @@ -206,10 +192,9 @@ void rejectsChangedTerminalDigestOperationFenceCommitAndNamespace() { ByteString.copyFrom(substitutedTerminal.terminal().canonicalBytes())) .setRetainedIntakeTerminalDigest(substitutedTerminal.terminal().digest()) .build(); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadGrpcCodec.fromResponse( - fixture.binding(), changedTerminal)) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), changedTerminal)) .isInstanceOf(IllegalArgumentException.class); } @@ -217,10 +202,9 @@ void rejectsChangedTerminalDigestOperationFenceCommitAndNamespace() { GetDraftDesignDigestResponse wrongNamespaceResponse = GameLogicPublicationSourceReadGrpcCodec.toResponse( wrongNamespace.binding(), wrongNamespace.terminal()); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadGrpcCodec.fromResponse( - wrongNamespace.binding(), wrongNamespaceResponse, NAMESPACE)) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + wrongNamespace.binding(), wrongNamespaceResponse, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); } @@ -230,46 +214,40 @@ void rejectsMissingAbortedMalformedOrOversizedTerminalAndNonemptyErrors() { GetDraftDesignDigestResponse response = GameLogicPublicationSourceReadGrpcCodec.toResponse(fixture.binding(), fixture.terminal()); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadGrpcCodec.fromResponse( - fixture.binding(), response.toBuilder().clearRetainedIntakeTerminal().build())) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), response.toBuilder().clearRetainedIntakeTerminal().build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadGrpcCodec.fromResponse( - fixture.binding(), - response.toBuilder() - .setRetainedIntakeTerminal(ByteString.copyFrom(new byte[] {1, 2, 3})) - .build())) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), + response.toBuilder() + .setRetainedIntakeTerminal(ByteString.copyFrom(new byte[] {1, 2, 3})) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadGrpcCodec.fromResponse( - fixture.binding(), - response.toBuilder() - .setRetainedIntakeTerminal( - ByteString.copyFrom( - new byte - [GameLogicPublicationSourceReadGrpcCodec.MAX_TERMINAL_BYTES - + 1])) - .build())) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), + response.toBuilder() + .setRetainedIntakeTerminal( + ByteString.copyFrom( + new byte + [GameLogicPublicationSourceReadGrpcCodec.MAX_TERMINAL_BYTES + 1])) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadGrpcCodec.fromResponse( - fixture.binding(), - response.toBuilder() - .setError(ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION").build()) - .build())) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse( + fixture.binding(), + response.toBuilder() + .setError(ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION").build()) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadGrpcCodec.toResponse( - fixture.binding(), - GameLogicGameplayRuleIntakeTerminal.aborted( - new GameLogicGameplayRuleIntakeOperation( - NAMESPACE, fixture.binding().authorization())))) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadGrpcCodec.toResponse( + fixture.binding(), + GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation( + NAMESPACE, fixture.binding().authorization())))) .isInstanceOf(IllegalArgumentException.class); } @@ -285,9 +263,8 @@ void rejectsChangedManifestAbilitySchemaVersionAndCanonicalization() { response.toBuilder().setAbilitySchemaDigest("sha256:changed").build(), response.toBuilder().setDigestSchemaVersion(2).build(), response.toBuilder().setCanonicalization("OTHER").build())) { - assertThatThrownBy( - () -> - GameLogicPublicationSourceReadGrpcCodec.fromResponse(fixture.binding(), changed)) + assertThatThrownBy(() -> + GameLogicPublicationSourceReadGrpcCodec.fromResponse(fixture.binding(), changed)) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjectionTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjectionTest.java index 979b73fabf..3a6d40d00e 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjectionTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjectionTest.java @@ -208,17 +208,13 @@ void rejectsIncompleteUnsupportedAndUnresolvedInputsEvenOutsideClosure() { assertThatThrownBy( () -> GameplayAbilitySchemaProjection.digest(new GameplayRuleManifest(unresolved))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameplayRuleManifest.fromStored( - roots() - .canonicalJson() - .replace("\"families\":", "\"unknown\":0,\"families\":"))) + assertThatThrownBy(() -> + GameplayRuleManifest.fromStored( + roots().canonicalJson().replace("\"families\":", "\"unknown\":0,\"families\":"))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameplayRuleManifest.fromStored( - roots().canonicalJson().replace("gameplay-rule-manifest/v1", "unsupported/v1"))) + assertThatThrownBy(() -> + GameplayRuleManifest.fromStored( + roots().canonicalJson().replace("gameplay-rule-manifest/v1", "unsupported/v1"))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayRuleManifestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayRuleManifestTest.java index 30f98523b7..83b88c014f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayRuleManifestTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayRuleManifestTest.java @@ -47,16 +47,15 @@ class GameplayRuleManifestTest { @Test void rejectsContinuousModifierOnResourceValue() { - assertThatThrownBy( - () -> - manifest( - MANA, - effect( - "continuous-mana-value", - Lifecycle.CONTINUOUS, - EffectOperation.ADD, - "mana", - StatField.VALUE))) + assertThatThrownBy(() -> + manifest( + MANA, + effect( + "continuous-mana-value", + Lifecycle.CONTINUOUS, + EffectOperation.ADD, + "mana", + StatField.VALUE))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("numeric STATS key"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java index 0b2a518885..9f791c4cca 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java @@ -83,9 +83,8 @@ void authenticatesAccountClientAndPinsSameNamespaceEntityServer() throws Excepti assertThatThrownBy(() -> client.read(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()).isEqualTo(Status.Code.NOT_FOUND)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()).isEqualTo(Status.Code.NOT_FOUND)); assertThat(calls).hasValue(1); server.shutdownNow(); @@ -94,10 +93,9 @@ void authenticatesAccountClientAndPinsSameNamespaceEntityServer() throws Excepti startServer(pki.wrongServer(), serverPort); assertThatThrownBy(() -> client.read(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(calls).hasValue(1); } @@ -112,14 +110,13 @@ void authenticatedMalformedResponseIsFailedPrecondition() throws Exception { client.init(); assertThatThrownBy(() -> client.read(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> { - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION); - assertThat(Status.fromThrowable(error).getDescription()) - .isEqualTo("Entity returned invalid terminal evidence"); - assertThat(error.getCause()).isInstanceOf(IllegalArgumentException.class); - }); + .satisfies(error -> { + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(Status.fromThrowable(error).getDescription()) + .isEqualTo("Entity returned invalid terminal evidence"); + assertThat(error.getCause()).isInstanceOf(IllegalArgumentException.class); + }); assertThat(calls).hasValue(1); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java index 894d6a57c7..011853d24d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeAuthorizationClientMtlsTest.java @@ -148,10 +148,9 @@ void pinsAccountServerAndRejectsWrongServerAndWrongAuthenticatedCaller() throws client.init(); assertThatThrownBy(() -> client.authorize(request(selected(1)), CREDENTIAL)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); assertThat(calls).hasValue(0); } @@ -182,10 +181,9 @@ void rejectsWrongNamespaceAmbientSqlAndUnavailableDeadline() throws Exception { client.init(); assertThatThrownBy(() -> client.authorize(original, CREDENTIAL)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); } @Test @@ -193,27 +191,21 @@ void refusesPlaintextAndClasspathOrMissingTlsMaterial() { var endpoints = new ServiceEndpointsProperties(); var plaintext = new CommonGrpcClientProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new GrpcGameLogicIntakeAuthorizationClient( - endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + assertThatThrownBy(() -> + new GrpcGameLogicIntakeAuthorizationClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GrpcGameLogicIntakeAuthorizationClient( - endpoints, - new CommonGrpcClientProperties(), - new GrpcChannelFactory(), - NAMESPACE)) + assertThatThrownBy(() -> + new GrpcGameLogicIntakeAuthorizationClient( + endpoints, new CommonGrpcClientProperties(), new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); var classpathMaterial = new CommonGrpcClientProperties(); classpathMaterial.setCertChain("classpath:account.crt"); classpathMaterial.setPrivateKey("classpath:account.key"); classpathMaterial.setCaCert("classpath:ca.crt"); - assertThatThrownBy( - () -> - new GrpcGameLogicIntakeAuthorizationClient( - endpoints, classpathMaterial, new GrpcChannelFactory(), NAMESPACE)) + assertThatThrownBy(() -> + new GrpcGameLogicIntakeAuthorizationClient( + endpoints, classpathMaterial, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); } @@ -259,11 +251,10 @@ void rejectsMalformedCreatorCredentialsBeforeRpcAndSanitizesMalformedEvidence() assertThatThrownBy(() -> client.authorize(request, CREDENTIAL)) .isInstanceOf(IllegalStateException.class) .hasMessage("Account returned invalid Game Logic intake authorization evidence") - .satisfies( - failure -> { - assertThat(failure.getCause()).isNull(); - assertThat(failure.getMessage()).doesNotContain(sensitive); - }); + .satisfies(failure -> { + assertThat(failure.getCause()).isNull(); + assertThat(failure.getMessage()).doesNotContain(sensitive); + }); assertThat(calls).hasValue(1); } @@ -381,13 +372,11 @@ private static void assertUnavailable( org.assertj.core.api.ThrowableAssert.ThrowingCallable call) { assertThatThrownBy(call) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE); - assertThat(Status.fromThrowable(failure).getDescription()).isNull(); - assertThat(failure.getCause()).isNull(); - }); + .satisfies(failure -> { + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(Status.fromThrowable(failure).getDescription()).isNull(); + assertThat(failure.getCause()).isNull(); + }); } private static GameLogicIntakeAuthorizationEvidence.Request request(DraftCommitBinding selected) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java index 840b5fa553..8269f742ab 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcGameLogicIntakeRetainClientMtlsTest.java @@ -98,10 +98,9 @@ void acceptsLargeTerminalFromExactGameLogicServerAndRejectsSubstitutedServer() t client.init(); assertThatThrownBy(() -> client.retain(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(calls).hasValue(0); assertThat(clientPeer.get()).isNull(); } @@ -181,12 +180,11 @@ private GrpcGameLogicIntakeRetainClient newClient(int port) throws Exception { private static void assertSanitizedUnavailable(ThrowingCallable operation) { assertThatThrownBy(operation) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - var status = Status.fromThrowable(failure); - assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); - assertThat(status.getDescription()).isNull(); - assertThat(failure.getCause()).isNull(); - }); + .satisfies(failure -> { + var status = Status.fromThrowable(failure); + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status.getDescription()).isNull(); + assertThat(failure.getCause()).isNull(); + }); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationClientTest.java index c3b8ed2963..4e90ce1c46 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationClientTest.java @@ -62,12 +62,11 @@ void closeReleasesClientMonitorBeforeDrainingCertificateCallback(@TempDir Path d eq(6565), any(CommonGrpcClientProperties.class), eq(true))) - .thenAnswer( - invocation -> { - ManagedChannel channel = mock(ManagedChannel.class); - channels.add(channel); - return channel; - }); + .thenAnswer(invocation -> { + ManagedChannel channel = mock(ManagedChannel.class); + channels.add(channel); + return channel; + }); client = new CanonicalGameInstanceLaunchAssociationClient(endpoints, tls, channelFactory, "test"); client.init(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java index 5e8d5e115d..97f8eea67c 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/CanonicalGameInstanceLaunchAssociationReadGrpcCodecTest.java @@ -100,10 +100,8 @@ void roundTripsOwnerAttemptAndFenceAndRejectsMissingMalformedOrNonpositiveProof( response.toBuilder().setCatalogRevision(0L).build(), response.toBuilder().setCatalogRevision(-1L).build() }) { - assertThatThrownBy( - () -> - CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( - request, invalid)) + assertThatThrownBy(() -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse(request, invalid)) .isInstanceOf(IllegalArgumentException.class); } @@ -120,10 +118,9 @@ void roundTripsOwnerAttemptAndFenceAndRejectsMissingMalformedOrNonpositiveProof( }) { var wireResponse = GetCanonicalGameInstanceLaunchAssociationResponse.parseFrom(invalidScope.toByteArray()); - assertThatThrownBy( - () -> - CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( - request, wireResponse)) + assertThatThrownBy(() -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + request, wireResponse)) .isInstanceOf(IllegalArgumentException.class); } } @@ -196,10 +193,8 @@ void accountOperationRoundTripsExactTupleAndOwnerSelectorAndRejectsPartialOrChan response.toBuilder().setExpectedOwnerMutationId(UUID.randomUUID().toString()).build(), response.toBuilder().setExpectedOwnerFence(5L).build(), response.toBuilder().setOwnerFence(5L).build())) { - assertThatThrownBy( - () -> - CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( - request, invalid)) + assertThatThrownBy(() -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse(request, invalid)) .isInstanceOf(IllegalArgumentException.class); } var worldRequest = @@ -214,25 +209,23 @@ void accountOperationRoundTripsExactTupleAndOwnerSelectorAndRejectsPartialOrChan request.expectedDescriptorRequestDigest(), request.expectedDescriptorResultDigest(), request.expectedReleaseAttestationEvidenceDigest()); - assertThatThrownBy( - () -> - CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( - worldRequest, response)) + assertThatThrownBy(() -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( + worldRequest, response)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new Request( - operation.ownerMutationId(), - request.targetNamespace(), - request.canonicalTenantId(), - request.worldSlug(), - request.gameInstanceUuid(), - request.controlPlaneRequestId(), - request.launchDescriptorId(), - request.expectedDescriptorRequestDigest(), - request.expectedDescriptorResultDigest(), - request.expectedReleaseAttestationEvidenceDigest(), - operation)) + assertThatThrownBy(() -> + new Request( + operation.ownerMutationId(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.gameInstanceUuid(), + request.controlPlaneRequestId(), + request.launchDescriptorId(), + request.expectedDescriptorRequestDigest(), + request.expectedDescriptorResultDigest(), + request.expectedReleaseAttestationEvidenceDigest(), + operation)) .isInstanceOf(IllegalArgumentException.class); } @@ -280,10 +273,9 @@ void rejectsChangedEchoMissingLaunchPairAndUnknownTopLevelOrNestedFields() throw .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) .build(); - assertThatThrownBy( - () -> - CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromRequest( - wire.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); for (var invalid : @@ -300,10 +292,8 @@ void rejectsChangedEchoMissingLaunchPairAndUnknownTopLevelOrNestedFields() throw .setReleaseAttestation( response.getReleaseAttestation().toBuilder().setUnknownFields(unknown)) .build())) { - assertThatThrownBy( - () -> - CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse( - request, invalid)) + assertThatThrownBy(() -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromResponse(request, invalid)) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodecTest.java index 4054a7c985..806dd5ec43 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamesession/HistoricalOriginalStartSessionOwnerEvidenceGrpcCodecTest.java @@ -81,10 +81,8 @@ void responseRequiresTheExactRequestEchoBeforeDecodingEvidence() { .getDefaultInstance()) .build(); - assertThatThrownBy( - () -> - HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromResponse( - request, response)) + assertThatThrownBy(() -> + HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromResponse(request, response)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("request echo"); } @@ -116,10 +114,8 @@ void responseRejectsUnknownNestedPinFields() { .getDefaultInstance()) .build(); - assertThatThrownBy( - () -> - HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromResponse( - request(), response)) + assertThatThrownBy(() -> + HistoricalOriginalStartSessionOwnerEvidenceGrpcCodec.fromResponse(request(), response)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining( "ReadHistoricalOriginalStartSessionOwnerEvidenceResponse.template_association_request contains unsupported fields"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java index 1fc70b1206..420399cfef 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClientTest.java @@ -135,13 +135,12 @@ void failedCertificateReloadMakesWatcherReadinessUnavailable(@TempDir Path direc client.init(); Files.writeString(certificate, "certificate-2"); - awaitCondition( - () -> { - Health health = TlsCertificateWatcher.health(); - return "OUT_OF_SERVICE".equals(health.getStatus().getCode()) - && ((Number) health.getDetails().get("unhealthyWatchers")).intValue() - >= unhealthyWatchersBefore + 1; - }); + awaitCondition(() -> { + Health health = TlsCertificateWatcher.health(); + return "OUT_OF_SERVICE".equals(health.getStatus().getCode()) + && ((Number) health.getDetails().get("unhealthyWatchers")).intValue() + >= unhealthyWatchersBefore + 1; + }); Health health = TlsCertificateWatcher.health(); assertThat(health.getStatus().getCode()).isEqualTo("OUT_OF_SERVICE"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactoryTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactoryTest.java index 9fd3341954..75a4400972 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactoryTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/BoundedGrpcServerFactoryTest.java @@ -39,13 +39,12 @@ void canonicalServerKeepAliveDefaultsPrecedeSupportedCustomizers() { var factory = new BoundedGrpcServerFactory( "127.0.0.1:0", - List.of( - customizer -> - customizer - .keepAliveTime(45, TimeUnit.SECONDS) - .keepAliveTimeout(7, TimeUnit.SECONDS) - .permitKeepAliveWithoutCalls(false) - .permitKeepAliveTime(60, TimeUnit.SECONDS)), + List.of(customizer -> + customizer + .keepAliveTime(45, TimeUnit.SECONDS) + .keepAliveTimeout(7, TimeUnit.SECONDS) + .permitKeepAliveWithoutCalls(false) + .permitKeepAliveTime(60, TimeUnit.SECONDS)), null, null, TlsServerCredentials.ClientAuth.NONE, @@ -68,12 +67,11 @@ void canonicalServerKeepAliveDefaultsPrecedeSupportedCustomizers() { @Test void rejectsDuplicateUnknownAndNonidenticalDescriptorConfiguration() { var method = method("test.Owner/Read", new AtomicInteger()); - assertThatThrownBy( - () -> - new GrpcRequestBytePolicy( - List.of( - new GrpcRequestBytePolicy.MethodBound(method, 1024), - new GrpcRequestBytePolicy.MethodBound(method, 1024)))) + assertThatThrownBy(() -> + new GrpcRequestBytePolicy( + List.of( + new GrpcRequestBytePolicy.MethodBound(method, 1024), + new GrpcRequestBytePolicy.MethodBound(method, 1024)))) .isInstanceOf(IllegalArgumentException.class); var policy = new GrpcRequestBytePolicy( @@ -90,9 +88,8 @@ void refusesAnUnwrappedServiceAddedByCustomizer() { var factory = new BoundedGrpcServerFactory( "127.0.0.1:0", - List.of( - builder -> - builder.addService(service(method("test.Bypass/Read", new AtomicInteger())))), + List.of(builder -> + builder.addService(service(method("test.Bypass/Read", new AtomicInteger())))), null, null, TlsServerCredentials.ClientAuth.NONE, @@ -160,18 +157,17 @@ void mtlsCompressedOrdinaryAndFutureMethodsRejectBeforeParserAndFallbackCannotBy var factory = new BoundedGrpcServerFactory( "127.0.0.1:0", - List.of( - builder -> { - builder.fallbackHandlerRegistry( - new HandlerRegistry() { - @Override - public ServerMethodDefinition lookupMethod( - String method, String authority) { - fallbackCalls.incrementAndGet(); - return service(unknown).getMethod(method); - } - }); - }), + List.of(builder -> { + builder.fallbackHandlerRegistry( + new HandlerRegistry() { + @Override + public ServerMethodDefinition lookupMethod( + String method, String authority) { + fallbackCalls.incrementAndGet(); + return service(unknown).getMethod(method); + } + }); + }), pki.keyManagerFactory(serverIdentity), pki.trustManagerFactory(), TlsServerCredentials.ClientAuth.REQUIRE, @@ -220,13 +216,12 @@ void mtlsCompressedOrdinaryAndFutureMethodsRejectBeforeParserAndFallbackCannotBy new byte[policy.transportMaximumBytes() + 1], Status.Code.RESOURCE_EXHAUSTED); assertThat(exceptionalParses).hasValue(1); - assertThatThrownBy( - () -> - ClientCalls.blockingUnaryCall( - noCertificate, - ordinary, - CallOptions.DEFAULT.withDeadlineAfter(3, TimeUnit.SECONDS), - new byte[0])) + assertThatThrownBy(() -> + ClientCalls.blockingUnaryCall( + noCertificate, + ordinary, + CallOptions.DEFAULT.withDeadlineAfter(3, TimeUnit.SECONDS), + new byte[0])) .satisfies(failure -> assertThat(Status.fromThrowable(failure).isOk()).isFalse()); assertThat(ordinaryParses).hasValue(1); } finally { @@ -285,11 +280,10 @@ private static MethodDescriptor method(String name, AtomicIntege } private static io.grpc.ServerCallHandler handler() { - return ServerCalls.asyncUnaryCall( - (request, observer) -> { - observer.onNext(new byte[0]); - observer.onCompleted(); - }); + return ServerCalls.asyncUnaryCall((request, observer) -> { + observer.onNext(new byte[0]); + observer.onCompleted(); + }); } private static ServerServiceDefinition service(MethodDescriptor method) { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/CommonGrpcRequestBoundsAutoConfigurationTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/CommonGrpcRequestBoundsAutoConfigurationTest.java index 63d62a3a46..b5943dbc33 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/CommonGrpcRequestBoundsAutoConfigurationTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/CommonGrpcRequestBoundsAutoConfigurationTest.java @@ -92,44 +92,40 @@ void explicitServerPermitIntervalBindsFromConfiguration() { @Test void productionAutoConfigurationDiscoversRegistersAndCallsRealServiceWithOrderedInterceptors() { - runner.run( - context -> { - assertThat(context) - .hasNotFailed() - .hasSingleBean(GrpcServerFactory.class) - .hasSingleBean(GrpcServerLifecycle.class); - assertThat(context.getBean(GrpcServiceDiscoverer.class)) - .isExactlyInstanceOf(DefaultGrpcServiceDiscoverer.class); - assertThat(context.getBean(GrpcServiceConfigurer.class)) - .isExactlyInstanceOf(DefaultGrpcServiceConfigurer.class); - assertThat(context.getBean(GrpcServerFactory.class)) - .isExactlyInstanceOf(BoundedGrpcServerFactory.class); - var lifecycle = context.getBean(GrpcServerLifecycle.class); - assertThat(lifecycle.getFactory()) - .isSameAs(context.getBean(BoundedGrpcServerFactory.class)); - assertThat(lifecycle.isRunning()).isTrue(); - var state = context.getBean(DiscoveryState.class); - assertThat(state.filtered).hasValue(1); - ManagedChannel channel = - NettyChannelBuilder.forAddress("127.0.0.1", lifecycle.getPort()) - .usePlaintext() - .build(); - try { - assertThat( - ClientCalls.blockingUnaryCall( - channel, - READ, - CallOptions.DEFAULT - .withDeadlineAfter(5, TimeUnit.SECONDS) - .withCompression("gzip"), - Empty.getDefaultInstance())) - .isEqualTo(Empty.getDefaultInstance()); - assertThat(state.events).containsExactly("first", "second", "handler"); - } finally { - channel.shutdownNow(); - assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); - } - }); + runner.run(context -> { + assertThat(context) + .hasNotFailed() + .hasSingleBean(GrpcServerFactory.class) + .hasSingleBean(GrpcServerLifecycle.class); + assertThat(context.getBean(GrpcServiceDiscoverer.class)) + .isExactlyInstanceOf(DefaultGrpcServiceDiscoverer.class); + assertThat(context.getBean(GrpcServiceConfigurer.class)) + .isExactlyInstanceOf(DefaultGrpcServiceConfigurer.class); + assertThat(context.getBean(GrpcServerFactory.class)) + .isExactlyInstanceOf(BoundedGrpcServerFactory.class); + var lifecycle = context.getBean(GrpcServerLifecycle.class); + assertThat(lifecycle.getFactory()).isSameAs(context.getBean(BoundedGrpcServerFactory.class)); + assertThat(lifecycle.isRunning()).isTrue(); + var state = context.getBean(DiscoveryState.class); + assertThat(state.filtered).hasValue(1); + ManagedChannel channel = + NettyChannelBuilder.forAddress("127.0.0.1", lifecycle.getPort()).usePlaintext().build(); + try { + assertThat( + ClientCalls.blockingUnaryCall( + channel, + READ, + CallOptions.DEFAULT + .withDeadlineAfter(5, TimeUnit.SECONDS) + .withCompression("gzip"), + Empty.getDefaultInstance())) + .isEqualTo(Empty.getDefaultInstance()); + assertThat(state.events).containsExactly("first", "second", "handler"); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + }); } @Test @@ -185,22 +181,21 @@ void explicitNoServerLifecycleBacksOffWithoutWeakeningFactoryDescriptorChecks() runner .withUserConfiguration(NoGrpcServerTestConfiguration.class) .withBean(GrpcRequestBytePolicy.class, GrpcRequestBytePolicy::createdRosterRetirement) - .run( - context -> { - assertThat(context) - .hasNotFailed() - .hasSingleBean(GrpcServerLifecycle.class) - .hasSingleBean(GrpcServerFactory.class) - .doesNotHaveBean("boundedGrpcServerLifecycle"); - var lifecycle = context.getBean(GrpcServerLifecycle.class); - assertThat(lifecycle).isSameAs(context.getBean("grpcServerLifecycle")); - verify(lifecycle, never()).start(); - var factory = context.getBean(GrpcServerFactory.class); - assertThat(factory).isExactlyInstanceOf(BoundedGrpcServerFactory.class); - assertThatThrownBy(factory::createServer) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("no exact registered descriptor"); - }); + .run(context -> { + assertThat(context) + .hasNotFailed() + .hasSingleBean(GrpcServerLifecycle.class) + .hasSingleBean(GrpcServerFactory.class) + .doesNotHaveBean("boundedGrpcServerLifecycle"); + var lifecycle = context.getBean(GrpcServerLifecycle.class); + assertThat(lifecycle).isSameAs(context.getBean("grpcServerLifecycle")); + verify(lifecycle, never()).start(); + var factory = context.getBean(GrpcServerFactory.class); + assertThat(factory).isExactlyInstanceOf(BoundedGrpcServerFactory.class); + assertThatThrownBy(factory::createServer) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no exact registered descriptor"); + }); } @Test @@ -214,24 +209,23 @@ void explicitNoServerFixtureAlsoBootsWhenFrameworkGrpcSupportIsExcluded() { DiscoveredServiceConfiguration.class, NoGrpcServerTestConfiguration.class) .withPropertyValues("spring.grpc.server.port=0", "spring.grpc.server.ssl.enabled=false") .withBean(GrpcRequestBytePolicy.class, GrpcRequestBytePolicy::createdRosterRetirement) - .run( - context -> { - assertThat(context) - .hasNotFailed() - .hasSingleBean(GrpcServerLifecycle.class) - .hasSingleBean(GrpcServerFactory.class) - .hasSingleBean(GrpcServiceConfigurer.class) - .doesNotHaveBean("boundedGrpcServerLifecycle"); - var lifecycle = context.getBean(GrpcServerLifecycle.class); - assertThat(lifecycle).isSameAs(context.getBean("grpcServerLifecycle")); - verify(lifecycle, never()).start(); - verifyNoInteractions(context.getBean(GrpcServiceConfigurer.class)); - var factory = context.getBean(GrpcServerFactory.class); - assertThat(factory).isExactlyInstanceOf(BoundedGrpcServerFactory.class); - assertThatThrownBy(factory::createServer) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("no exact registered descriptor"); - }); + .run(context -> { + assertThat(context) + .hasNotFailed() + .hasSingleBean(GrpcServerLifecycle.class) + .hasSingleBean(GrpcServerFactory.class) + .hasSingleBean(GrpcServiceConfigurer.class) + .doesNotHaveBean("boundedGrpcServerLifecycle"); + var lifecycle = context.getBean(GrpcServerLifecycle.class); + assertThat(lifecycle).isSameAs(context.getBean("grpcServerLifecycle")); + verify(lifecycle, never()).start(); + verifyNoInteractions(context.getBean(GrpcServiceConfigurer.class)); + var factory = context.getBean(GrpcServerFactory.class); + assertThat(factory).isExactlyInstanceOf(BoundedGrpcServerFactory.class); + assertThatThrownBy(factory::createServer) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no exact registered descriptor"); + }); } @Test @@ -240,38 +234,31 @@ void createdPolicyRequiresExplicitTransportOptInAndKeepsOrdinaryMethodsBounded() runner .withBean(GrpcRequestBytePolicy.class, GrpcRequestBytePolicy::createdRosterRetirement) .withBean(CreatedRosterService.class, CreatedRosterService::new); - createdRunner.run( - context -> { + createdRunner.run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context.getBean(GrpcServerProperties.class).getMaxInboundMessageSize().toBytes()) + .isEqualTo(GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + assertPurposeAndOrdinaryAdmission( + context.getBean(GrpcServerLifecycle.class).getPort(), Status.Code.RESOURCE_EXHAUSTED); + assertThat(context.getBean(DiscoveryState.class).events).doesNotContain("handler"); + }); + createdRunner + .withPropertyValues( + "spring.grpc.server.max-inbound-message-size=" + + CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_CONFIRMATION_BYTES + + "B") + .run(context -> { assertThat(context).hasNotFailed(); assertThat( context.getBean(GrpcServerProperties.class).getMaxInboundMessageSize().toBytes()) - .isEqualTo(GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES); + .isEqualTo( + CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_CONFIRMATION_BYTES); + // UNIMPLEMENTED comes from the generated base only after the actual eligible request + // parses. assertPurposeAndOrdinaryAdmission( - context.getBean(GrpcServerLifecycle.class).getPort(), Status.Code.RESOURCE_EXHAUSTED); + context.getBean(GrpcServerLifecycle.class).getPort(), Status.Code.UNIMPLEMENTED); assertThat(context.getBean(DiscoveryState.class).events).doesNotContain("handler"); }); - createdRunner - .withPropertyValues( - "spring.grpc.server.max-inbound-message-size=" - + CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_CONFIRMATION_BYTES - + "B") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat( - context - .getBean(GrpcServerProperties.class) - .getMaxInboundMessageSize() - .toBytes()) - .isEqualTo( - CanonicalGameplayRosterRetirementEvidence - .MAX_PLAYER_CREATED_CONFIRMATION_BYTES); - // UNIMPLEMENTED comes from the generated base only after the actual eligible request - // parses. - assertPurposeAndOrdinaryAdmission( - context.getBean(GrpcServerLifecycle.class).getPort(), Status.Code.UNIMPLEMENTED); - assertThat(context.getBean(DiscoveryState.class).events).doesNotContain("handler"); - }); createdRunner .withPropertyValues("spring.grpc.server.max-inbound-message-size=0B") .run(context -> assertThat(context).hasFailed()); @@ -308,25 +295,21 @@ private static void assertPurposeAndOrdinaryAdmission(int port, Status.Code purp try { var options = CallOptions.DEFAULT.withDeadlineAfter(5, TimeUnit.SECONDS).withCompression("gzip"); - assertThatThrownBy( - () -> - ClientCalls.blockingUnaryCall( - channel, - CanonicalGameplayRosterOwnerReadServiceGrpc - .getAcknowledgeCanonicalGameplayRosterRetirementMethod(), - options, - request)) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(purposeStatus)); - assertThatThrownBy( - () -> - ClientCalls.blockingUnaryCall( - channel, READ, options, Empty.newBuilder().setUnknownFields(unknown).build())) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.RESOURCE_EXHAUSTED)); + assertThatThrownBy(() -> + ClientCalls.blockingUnaryCall( + channel, + CanonicalGameplayRosterOwnerReadServiceGrpc + .getAcknowledgeCanonicalGameplayRosterRetirementMethod(), + options, + request)) + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(purposeStatus)); + assertThatThrownBy(() -> + ClientCalls.blockingUnaryCall( + channel, READ, options, Empty.newBuilder().setUnknownFields(unknown).build())) + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.RESOURCE_EXHAUSTED)); } finally { channel.shutdownNow(); assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); @@ -346,10 +329,9 @@ void alternateFactoryAndDuplicatePoliciesFailClosed() { @Test void missingExceptionsUseOrdinaryCeilingAndUnknownOrUnboundedTransportCannotWidenIt() { - runner.run( - context -> - assertThat(context.getBean(GrpcRequestBytePolicy.class).transportMaximumBytes()) - .isEqualTo(GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES)); + runner.run(context -> + assertThat(context.getBean(GrpcRequestBytePolicy.class).transportMaximumBytes()) + .isEqualTo(GrpcRequestBytePolicy.ORDINARY_MAXIMUM_BYTES)); runner .withPropertyValues("spring.grpc.server.max-inbound-message-size=5MB") .run(context -> assertThat(context).hasFailed()); @@ -387,11 +369,10 @@ DiscoveredService discoveredService(DiscoveryState state) { GrpcServerFactoryCustomizer serviceFilter(DiscoveryState state) { return factory -> ((DefaultGrpcServerFactory) factory) - .setServiceFilter( - (service, ignored) -> { - state.filtered.incrementAndGet(); - return true; - }); + .setServiceFilter((service, ignored) -> { + state.filtered.incrementAndGet(); + return true; + }); } @Bean @@ -427,12 +408,11 @@ public ServerServiceDefinition bindService() { return ServerServiceDefinition.builder("test.Discovered") .addMethod( READ, - ServerCalls.asyncUnaryCall( - (request, observer) -> { - state.events.add("handler"); - observer.onNext(Empty.getDefaultInstance()); - observer.onCompleted(); - })) + ServerCalls.asyncUnaryCall((request, observer) -> { + state.events.add("handler"); + observer.onNext(Empty.getDefaultInstance()); + observer.onCompleted(); + })) .build(); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicyTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicyTest.java index 4ab7c49949..bccb10419d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicyTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/FileBackedGrpcMtlsPolicyTest.java @@ -80,10 +80,9 @@ void rejectsMissingClasspathInvalidDirectoryAndNonexistentMaterial(@TempDir Path void acceptsResolvedReadableFiles(@TempDir Path directory) throws Exception { CommonGrpcClientProperties properties = propertiesWithFiles(directory); - assertThatCode( - () -> - requireResolved( - properties, new GrpcTlsMaterialResolver(), "test read requires workload mTLS")) + assertThatCode(() -> + requireResolved( + properties, new GrpcTlsMaterialResolver(), "test read requires workload mTLS")) .doesNotThrowAnyException(); } @@ -100,20 +99,18 @@ public ResolvedGrpcTlsMaterial resolve(CommonGrpcClientProperties ignored) { classpathResource, classpathResource, classpathResource); } }; - assertThatThrownBy( - () -> - requireResolved(properties, classpathResolver, "test read requires workload mTLS")) + assertThatThrownBy(() -> + requireResolved(properties, classpathResolver, "test read requires workload mTLS")) .isInstanceOf(IllegalStateException.class) .hasMessage("test read requires readable file-backed workload mTLS"); CommonGrpcClientProperties directoryProperties = propertiesWithFiles(directory); directoryProperties.setCaCert(directory.toString()); - assertThatThrownBy( - () -> - requireResolved( - directoryProperties, - new GrpcTlsMaterialResolver(), - "test read requires workload mTLS")) + assertThatThrownBy(() -> + requireResolved( + directoryProperties, + new GrpcTlsMaterialResolver(), + "test read requires workload mTLS")) .isInstanceOf(IllegalStateException.class) .hasMessage("test read requires readable file-backed workload mTLS"); } @@ -123,12 +120,11 @@ void rejectsPlaintextAndResolverFailuresWithPurposeSpecificMessages(@TempDir Pat throws Exception { CommonGrpcClientProperties plaintext = propertiesWithFiles(directory); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - requireResolved( - plaintext, - new GrpcTlsMaterialResolver(), - "StartSession authorization requires file-backed workload mTLS")) + assertThatThrownBy(() -> + requireResolved( + plaintext, + new GrpcTlsMaterialResolver(), + "StartSession authorization requires file-backed workload mTLS")) .isInstanceOf(IllegalStateException.class) .hasMessage("StartSession authorization requires file-backed workload mTLS"); @@ -140,12 +136,11 @@ public ResolvedGrpcTlsMaterial resolve(CommonGrpcClientProperties ignored) throw new IOException("sensitive resolver detail"); } }; - assertThatThrownBy( - () -> - requireResolved( - propertiesWithFiles(directory), - failingResolver, - "Account authorization requires workload mTLS")) + assertThatThrownBy(() -> + requireResolved( + propertiesWithFiles(directory), + failingResolver, + "Account authorization requires workload mTLS")) .isInstanceOf(IllegalStateException.class) .hasMessage("test read requires readable file-backed workload mTLS") .hasMessageNotContaining("sensitive resolver detail"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptorTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptorTest.java index 134849527f..925689afb8 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptorTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/GrpcServerPeerIdentityClientInterceptorTest.java @@ -116,10 +116,9 @@ void configuredIdentityMustBeOneExactCanonicalWorkloadUri() { .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> new GrpcServerPeerIdentityClientInterceptor("not-a-workload")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GrpcServerPeerIdentityClientInterceptor( - "spiffe://FIREMUD/ns/firemud/sa/game-design-service")) + assertThatThrownBy(() -> + new GrpcServerPeerIdentityClientInterceptor( + "spiffe://FIREMUD/ns/firemud/sa/game-design-service")) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/TlsCertificateWatcherTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/TlsCertificateWatcherTest.java index 7592dc7b64..e67aa6f554 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/TlsCertificateWatcherTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/grpc/TlsCertificateWatcherTest.java @@ -464,16 +464,15 @@ void closeWaitsForActiveReloadCallbackBeforeReturning(@TempDir Path directory) t CountDownLatch closeFinished = new CountDownLatch(1); Thread closeThread = - new Thread( - () -> { - try { - watcher.close(); - } catch (Throwable e) { - closeFailure.set(e); - } finally { - closeFinished.countDown(); - } - }); + new Thread(() -> { + try { + watcher.close(); + } catch (Throwable e) { + closeFailure.set(e); + } finally { + closeFinished.countDown(); + } + }); closeThread.start(); assertFalse(closeFinished.await(200, TimeUnit.MILLISECONDS)); @@ -718,35 +717,33 @@ void registrationRecoveryWaitsForActiveReloadCallback(@TempDir Path directory) t CountDownLatch releaseLock = new CountDownLatch(1); CountDownLatch recoveryStarted = new CountDownLatch(1); Thread lockHolder = - new Thread( - () -> { - callbackMonitor.lock(); - try { - lockAcquired.countDown(); - try { - releaseLock.await(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } finally { - callbackMonitor.unlock(); - } - }); + new Thread(() -> { + callbackMonitor.lock(); + try { + lockAcquired.countDown(); + try { + releaseLock.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } finally { + callbackMonitor.unlock(); + } + }); lockHolder.start(); try { assertTrue(lockAcquired.await(5, TimeUnit.SECONDS)); AtomicBoolean recoveryFinished = new AtomicBoolean(); Thread recovery = - new Thread( - () -> { - try { - recoveryStarted.countDown(); - retryMethod.invoke(watcher); - recoveryFinished.set(true); - } catch (ReflectiveOperationException e) { - throw new AssertionError("failed to invoke registration recovery", e); - } - }); + new Thread(() -> { + try { + recoveryStarted.countDown(); + retryMethod.invoke(watcher); + recoveryFinished.set(true); + } catch (ReflectiveOperationException e) { + throw new AssertionError("failed to invoke registration recovery", e); + } + }); recovery.start(); assertTrue(recoveryStarted.await(5, TimeUnit.SECONDS)); assertFalse(callbackInvoked.await(100, TimeUnit.MILLISECONDS)); @@ -780,14 +777,13 @@ void lockWaiterIsNotTrackedAndCannotReloadAfterClose(@TempDir Path directory) th AtomicReference waiterFailure = new AtomicReference<>(); callbackMonitor.lock(); Thread waiter = - new Thread( - () -> { - try { - invokeReloadCallback(watcher, false); - } catch (Throwable failure) { - waiterFailure.set(failure); - } - }); + new Thread(() -> { + try { + invokeReloadCallback(watcher, false); + } catch (Throwable failure) { + waiterFailure.set(failure); + } + }); waiter.start(); try { awaitLockWaiter(waiter); @@ -827,27 +823,25 @@ void closePreventsCallbackRegistrationWaitingOnCallbackState(@TempDir Path direc callbackStateMonitorField.setAccessible(true); Object callbackStateMonitor = callbackStateMonitorField.get(watcher); Thread invocation = - new Thread( - () -> { - try { - invokeReloadCallback(watcher, false); - } catch (Throwable failure) { - invocationFailure.set(failure); - } - }); + new Thread(() -> { + try { + invokeReloadCallback(watcher, false); + } catch (Throwable failure) { + invocationFailure.set(failure); + } + }); CountDownLatch closeFinished = new CountDownLatch(1); Thread closeThread = - new Thread( - () -> { - closeStarted.set(true); - try { - watcher.close(); - } catch (Throwable failure) { - closeFailure.set(failure); - } finally { - closeFinished.countDown(); - } - }); + new Thread(() -> { + closeStarted.set(true); + try { + watcher.close(); + } catch (Throwable failure) { + closeFailure.set(failure); + } finally { + closeFinished.countDown(); + } + }); synchronized (callbackStateMonitor) { invocation.start(); @@ -875,14 +869,13 @@ private static Future submitRetryCallback(TlsCertificateWatcher watcher) thro ScheduledExecutorService retryExecutor = retryExecutor(watcher); Method retryMethod = TlsCertificateWatcher.class.getDeclaredMethod("retryReloadCallback"); retryMethod.setAccessible(true); - return retryExecutor.submit( - () -> { - try { - retryMethod.invoke(watcher); - } catch (ReflectiveOperationException e) { - throw new AssertionError("failed to invoke callback retry", e); - } - }); + return retryExecutor.submit(() -> { + try { + retryMethod.invoke(watcher); + } catch (ReflectiveOperationException e) { + throw new AssertionError("failed to invoke callback retry", e); + } + }); } private static ScheduledExecutorService retryExecutor(TlsCertificateWatcher watcher) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodecTest.java index a982f458da..e078450a0d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/CharacterCreateOperatorActionCodecTest.java @@ -148,10 +148,9 @@ void rejectsRawStringAndCompleteActionBoundsBeforeParsing() throws IOException { raw.replace( "\"canonicalCreationInput\":\"{}\"", "\"canonicalCreationInput\":\"" + tooLongValue + "\"")); - assertThatThrownBy( - () -> - CharacterCreateOperatorActionCodec.decode( - new byte[CharacterCreateOperatorActionCodec.MAX_RAW_BYTES + 1])) + assertThatThrownBy(() -> + CharacterCreateOperatorActionCodec.decode( + new byte[CharacterCreateOperatorActionCodec.MAX_RAW_BYTES + 1])) .isInstanceOf(IllegalArgumentException.class); } @@ -546,9 +545,8 @@ private static String rawBase() throws IOException { } private static void assertRejected(String raw) { - assertThatThrownBy( - () -> - CharacterCreateOperatorActionCodec.decode(raw.getBytes(StandardCharsets.US_ASCII))) + assertThatThrownBy(() -> + CharacterCreateOperatorActionCodec.decode(raw.getBytes(StandardCharsets.US_ASCII))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodecTest.java index a31ffcdfbf..608f93ff2d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/operator/StartSessionOperatorActionCodecTest.java @@ -143,10 +143,9 @@ void exposesOnlyTypedImmutableStartSessionFields() throws IOException { @Test void rejectsRawUtf8AndActionSpecificOversizeInputs() throws IOException { - assertThatThrownBy( - () -> - StartSessionOperatorActionCodec.decode( - new byte[] {'{', '"', (byte) 0xff, '"', ':', '1', '}'})) + assertThatThrownBy(() -> + StartSessionOperatorActionCodec.decode( + new byte[] {'{', '"', (byte) 0xff, '"', ':', '1', '}'})) .isInstanceOf(IllegalArgumentException.class); byte[] oversizedRaw = new byte[StartSessionOperatorActionCodec.MAX_RAW_BYTES + 1]; @@ -155,17 +154,15 @@ void rejectsRawUtf8AndActionSpecificOversizeInputs() throws IOException { String base = findVector("base").path("input").asText(); String oversizedReason = base.replace("scheduled launch", "x".repeat(1_001)); - assertThatThrownBy( - () -> - StartSessionOperatorActionCodec.decode( - oversizedReason.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + StartSessionOperatorActionCodec.decode( + oversizedReason.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); String oversizedClientIp = base.replace("192.0.2.1", "x".repeat(129)); - assertThatThrownBy( - () -> - StartSessionOperatorActionCodec.decode( - oversizedClientIp.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + StartSessionOperatorActionCodec.decode( + oversizedClientIp.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); } @@ -180,10 +177,8 @@ void auditReasonUsesExplicitSharedWhitespaceSet() throws IOException { for (int codePoint : sharedWhitespaceCodepoints) { String blankReason = new String(Character.toChars(codePoint)); String blankInput = replaceAuditReason(base, blankReason); - assertThatThrownBy( - () -> - StartSessionOperatorActionCodec.decode( - blankInput.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + StartSessionOperatorActionCodec.decode(blankInput.getBytes(StandardCharsets.UTF_8))) .as("blank audit reason U+%04X", codePoint) .isInstanceOf(IllegalArgumentException.class); @@ -209,24 +204,21 @@ void auditReasonUsesExplicitSharedWhitespaceSet() throws IOException { @Test void rejectsObjectMemberAndArrayElementLimitViolations() { String tooManyMembers = "{" + String.join(",", Collections.nCopies(17, "\"k\":0")) + "}"; - assertThatThrownBy( - () -> - StartSessionOperatorActionCodec.canonicalGrammarValueForTest( - tooManyMembers.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + StartSessionOperatorActionCodec.canonicalGrammarValueForTest( + tooManyMembers.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); String tooManyElements = "[" + String.join(",", Collections.nCopies(65, "0")) + "]"; - assertThatThrownBy( - () -> - StartSessionOperatorActionCodec.canonicalGrammarValueForTest( - tooManyElements.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + StartSessionOperatorActionCodec.canonicalGrammarValueForTest( + tooManyElements.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); String tooDeep = "[".repeat(9) + "0" + "]".repeat(9); - assertThatThrownBy( - () -> - StartSessionOperatorActionCodec.canonicalGrammarValueForTest( - tooDeep.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + StartSessionOperatorActionCodec.canonicalGrammarValueForTest( + tooDeep.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadClientTest.java index 4e42f49414..c81b9fe297 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadClientTest.java @@ -35,10 +35,9 @@ void rejectsPlaintextWrongNamespaceAndUninitializedCallsBeforeTransport(@TempDir var factory = mock(GrpcChannelFactory.class); var plaintext = tls(directory); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new AccountPublicationAuthorizationReadClient( - new ServiceEndpointsProperties(), plaintext, factory, "test")) + assertThatThrownBy(() -> + new AccountPublicationAuthorizationReadClient( + new ServiceEndpointsProperties(), plaintext, factory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("workload mTLS"); @@ -47,15 +46,14 @@ void rejectsPlaintextWrongNamespaceAndUninitializedCallsBeforeTransport(@TempDir new ServiceEndpointsProperties(), tls(directory), factory, "test"); try { var request = AccountPublicationAuthorizationReadGrpcCodecTest.request(); - assertThatThrownBy( - () -> - client.read( - new AccountPublicationAuthorizationReadEvidence.Request( - request.schemaVersion(), - "other", - request.readRequestId(), - request.originalPublicationAuthorizationBinding(), - request.publicationAuthorizationDigest()))) + assertThatThrownBy(() -> + client.read( + new AccountPublicationAuthorizationReadEvidence.Request( + request.schemaVersion(), + "other", + request.readRequestId(), + request.originalPublicationAuthorizationBinding(), + request.publicationAuthorizationDigest()))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("configured workload namespace"); assertThatThrownBy(() -> client.read(request)) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadGrpcCodecTest.java index 10146d0b76..9d52aeddad 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountPublicationAuthorizationReadGrpcCodecTest.java @@ -49,40 +49,37 @@ void rejectsOversizedBindingsAndRequestResponseEnvelopesBeforeDecoding() { byte[] oversizedBinding = new byte[AccountPublicationAuthorizationReadEvidence.MAX_BINDING_BYTES + 1]; - assertThatThrownBy( - () -> - new AccountPublicationAuthorizationReadEvidence.Request( - AccountPublicationAuthorizationReadEvidence.Request.SCHEMA_VERSION, - "test", - UUID.randomUUID(), - oversizedBinding, - request.publicationAuthorizationDigest())) + assertThatThrownBy(() -> + new AccountPublicationAuthorizationReadEvidence.Request( + AccountPublicationAuthorizationReadEvidence.Request.SCHEMA_VERSION, + "test", + UUID.randomUUID(), + oversizedBinding, + request.publicationAuthorizationDigest())) .isInstanceOf(IllegalArgumentException.class) .hasMessage( "Complete original Account publication authorization binding exceeds size limit"); ReadHeldPublicationAuthorizationRequest wireRequest = AccountPublicationAuthorizationReadGrpcCodec.toRequest(request); - assertThatThrownBy( - () -> - AccountPublicationAuthorizationReadGrpcCodec.fromRequest( - wireRequest.toBuilder() - .setOriginalPublicationAuthorizationBinding( - ByteString.copyFrom(oversizedBinding)) - .build())) + assertThatThrownBy(() -> + AccountPublicationAuthorizationReadGrpcCodec.fromRequest( + wireRequest.toBuilder() + .setOriginalPublicationAuthorizationBinding( + ByteString.copyFrom(oversizedBinding)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessage( "Complete original Account publication authorization binding exceeds size limit"); var wireResponse = AccountPublicationAuthorizationReadGrpcCodec.toHeldResponse(request); - assertThatThrownBy( - () -> - AccountPublicationAuthorizationReadGrpcCodec.fromResponse( - request, - wireResponse.toBuilder() - .setOriginalPublicationAuthorizationBinding( - ByteString.copyFrom(oversizedBinding)) - .build())) + assertThatThrownBy(() -> + AccountPublicationAuthorizationReadGrpcCodec.fromResponse( + request, + wireResponse.toBuilder() + .setOriginalPublicationAuthorizationBinding( + ByteString.copyFrom(oversizedBinding)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessage( "Complete original Account publication authorization binding exceeds size limit"); @@ -92,9 +89,8 @@ void rejectsOversizedBindingsAndRequestResponseEnvelopesBeforeDecoding() { .setTargetNamespace( "x".repeat(AccountPublicationAuthorizationReadGrpcCodec.MAX_MESSAGE_BYTES)) .build(); - assertThatThrownBy( - () -> - AccountPublicationAuthorizationReadGrpcCodec.fromRequest(oversizedRequestEnvelope)) + assertThatThrownBy(() -> + AccountPublicationAuthorizationReadGrpcCodec.fromRequest(oversizedRequestEnvelope)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Account publication authorization read request exceeds size limit"); @@ -103,10 +99,9 @@ void rejectsOversizedBindingsAndRequestResponseEnvelopesBeforeDecoding() { .setTargetNamespace( "x".repeat(AccountPublicationAuthorizationReadGrpcCodec.MAX_MESSAGE_BYTES)) .build(); - assertThatThrownBy( - () -> - AccountPublicationAuthorizationReadGrpcCodec.fromResponse( - request, oversizedResponseEnvelope)) + assertThatThrownBy(() -> + AccountPublicationAuthorizationReadGrpcCodec.fromResponse( + request, oversizedResponseEnvelope)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Account publication authorization read response exceeds size limit"); } @@ -119,28 +114,24 @@ void rejectsMalformedRequestsUnknownFieldsAndChangedBindingDigest() { .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); - assertThatThrownBy( - () -> - AccountPublicationAuthorizationReadGrpcCodec.fromRequest( - request.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + AccountPublicationAuthorizationReadGrpcCodec.fromRequest( + request.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - AccountPublicationAuthorizationReadGrpcCodec.fromRequest( - request.toBuilder().setReadRequestId("not-a-uuid").build())) + assertThatThrownBy(() -> + AccountPublicationAuthorizationReadGrpcCodec.fromRequest( + request.toBuilder().setReadRequestId("not-a-uuid").build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountPublicationAuthorizationReadGrpcCodec.fromRequest( - request.toBuilder().setSchemaVersion(2).build())) + assertThatThrownBy(() -> + AccountPublicationAuthorizationReadGrpcCodec.fromRequest( + request.toBuilder().setSchemaVersion(2).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountPublicationAuthorizationReadGrpcCodec.fromRequest( - request.toBuilder() - .setPublicationAuthorizationDigest("sha256:" + "0".repeat(64)) - .build())) + assertThatThrownBy(() -> + AccountPublicationAuthorizationReadGrpcCodec.fromRequest( + request.toBuilder() + .setPublicationAuthorizationDigest("sha256:" + "0".repeat(64)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Account publication authorization read request is invalid") .hasRootCauseMessage( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java index 5affea2688..518496aef0 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java @@ -35,19 +35,17 @@ void clear() { @Test void requiresReadableFileBackedMutualTlsAndNamespace(@TempDir Path directory) throws Exception { var factory = mock(GrpcChannelFactory.class); - assertThatThrownBy( - () -> - new AccountSelectedPublicationOrderClient( - new ServiceEndpointsProperties(), null, factory, "test")) + assertThatThrownBy(() -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), null, factory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Account selected-publication") .hasNoCause(); var tls = tls(directory); tls.setPlaintext(true); - assertThatThrownBy( - () -> - new AccountSelectedPublicationOrderClient( - new ServiceEndpointsProperties(), tls, factory, "test")) + assertThatThrownBy(() -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), tls, factory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Account selected-publication"); tls.setPlaintext(false); @@ -61,10 +59,9 @@ void requiresReadableFileBackedMutualTlsAndNamespace(@TempDir Path directory) th }) { tls.setCertChain(bad); Throwable failure = - catchThrowable( - () -> - new AccountSelectedPublicationOrderClient( - new ServiceEndpointsProperties(), tls, factory, "test")); + catchThrowable(() -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), tls, factory, "test")); assertThat(failure) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Account selected-publication") @@ -74,10 +71,9 @@ void requiresReadableFileBackedMutualTlsAndNamespace(@TempDir Path directory) th } } var valid = tls(directory); - assertThatThrownBy( - () -> - new AccountSelectedPublicationOrderClient( - new ServiceEndpointsProperties(), valid, factory, "Test")) + assertThatThrownBy(() -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), valid, factory, "Test")) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(factory); } @@ -91,10 +87,9 @@ void validatesExactConfiguredTlsPathsBeforeCreatingAChannel(@TempDir Path direct certChainTls.setCertChain(certChainTls.getCertChain() + " "); assertThat(Files.exists(Path.of(certChainTls.getCertChain()))).isFalse(); assertThat(Files.isReadable(Path.of(certChainTls.getCertChain().trim()))).isTrue(); - assertThatThrownBy( - () -> - new AccountSelectedPublicationOrderClient( - new ServiceEndpointsProperties(), certChainTls, factory, "test")) + assertThatThrownBy(() -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), certChainTls, factory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Account selected-publication") .hasMessageNotContaining(certChainTls.getCertChain()) @@ -104,10 +99,9 @@ void validatesExactConfiguredTlsPathsBeforeCreatingAChannel(@TempDir Path direct privateKeyTls.setPrivateKey(privateKeyTls.getPrivateKey() + " "); assertThat(Files.exists(Path.of(privateKeyTls.getPrivateKey()))).isFalse(); assertThat(Files.isReadable(Path.of(privateKeyTls.getPrivateKey().trim()))).isTrue(); - assertThatThrownBy( - () -> - new AccountSelectedPublicationOrderClient( - new ServiceEndpointsProperties(), privateKeyTls, factory, "test")) + assertThatThrownBy(() -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), privateKeyTls, factory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Account selected-publication") .hasMessageNotContaining(privateKeyTls.getPrivateKey()) @@ -117,10 +111,9 @@ void validatesExactConfiguredTlsPathsBeforeCreatingAChannel(@TempDir Path direct caCertTls.setCaCert(caCertTls.getCaCert() + " "); assertThat(Files.exists(Path.of(caCertTls.getCaCert()))).isFalse(); assertThat(Files.isReadable(Path.of(caCertTls.getCaCert().trim()))).isTrue(); - assertThatThrownBy( - () -> - new AccountSelectedPublicationOrderClient( - new ServiceEndpointsProperties(), caCertTls, factory, "test")) + assertThatThrownBy(() -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), caCertTls, factory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Account selected-publication") .hasMessageNotContaining(caCertTls.getCaCert()) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java index df0baf31a5..bcb1480051 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java @@ -150,10 +150,9 @@ void roundTripsMaximumCanonicalSelectionWithLargerBoundedBinding() { "n".repeat(AccountSelectedPublicationOrderGrpcCodec.MAX_SELECTION_BYTES)); assertThat(oversizedSelection.canonicalBytes()) .hasSizeGreaterThan(AccountSelectedPublicationOrderGrpcCodec.MAX_SELECTION_BYTES); - assertThatThrownBy( - () -> - AccountSelectedPublicationOrderGrpcCodec.Request.create( - "test", oversizedSelection, CREDENTIAL)) + assertThatThrownBy(() -> + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", oversizedSelection, CREDENTIAL)) .isInstanceOf(IllegalArgumentException.class) .hasNoCause(); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClientTest.java index c7efe63fe5..ad72054823 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClientTest.java @@ -53,10 +53,9 @@ void requiresFileBackedMtlsWithAccountSettlementContext(@TempDir Path directory) var factory = mock(GrpcChannelFactory.class); var plaintext = new CommonGrpcClientProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new AccountSelectedPublicationSettlementClient( - endpoints, plaintext, factory, NAMESPACE)) + assertThatThrownBy(() -> + new AccountSelectedPublicationSettlementClient( + endpoints, plaintext, factory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Account publication settlement") .hasNoCause(); @@ -66,10 +65,9 @@ void requiresFileBackedMtlsWithAccountSettlementContext(@TempDir Path directory) classpath.setCertChain("classpath:client.crt"); classpath.setPrivateKey(directory.resolve("client.key").toString()); classpath.setCaCert(directory.resolve("ca.crt").toString()); - assertThatThrownBy( - () -> - new AccountSelectedPublicationSettlementClient( - endpoints, classpath, factory, NAMESPACE)) + assertThatThrownBy(() -> + new AccountSelectedPublicationSettlementClient( + endpoints, classpath, factory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Account publication settlement") .hasMessageNotContaining("classpath:client.crt") diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java index 39f7bd3eab..f5c1169862 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java @@ -94,11 +94,9 @@ void rejectsMalformedAndNoncanonicalRequestsAndUnknownFields() throws Exception .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - AccountSelectedPublicationSettlementGrpcCodec.Request.create( - "test", - new byte[GameDesignPublicationOperationBinding.MAX_OPERATION_BYTES + 1])) + assertThatThrownBy(() -> + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", new byte[GameDesignPublicationOperationBinding.MAX_OPERATION_BYTES + 1])) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("4 MiB"); } @@ -181,9 +179,8 @@ void enforcesCompleteSerializedMessageBudgetBeforeReceiptDecoding() throws Excep "test", operation.canonicalBytes()); byte[] oversizedReceipt = new byte[AccountSelectedPublicationSettlementGrpcCodec.MAX_MESSAGE_BYTES]; - assertThatThrownBy( - () -> - AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, oversizedReceipt)) + assertThatThrownBy(() -> + AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, oversizedReceipt)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("32 MiB"); @@ -195,10 +192,8 @@ void enforcesCompleteSerializedMessageBudgetBeforeReceiptDecoding() throws Excep .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) .setSettlementReceipt(ByteString.copyFrom(oversizedReceipt)) .build(); - assertThatThrownBy( - () -> - AccountSelectedPublicationSettlementGrpcCodec.fromResponse( - request, oversizedResponse)) + assertThatThrownBy(() -> + AccountSelectedPublicationSettlementGrpcCodec.fromResponse(request, oversizedResponse)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("32 MiB"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadClientTest.java index de1e2bf271..5ebdfb5249 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadClientTest.java @@ -41,31 +41,27 @@ void requiresReadableFileBackedMaterialAndCanonicalNamespace(@TempDir Path direc directory.toString())) { var invalid = tls(directory); invalid.setCertChain(badPath); - assertThatThrownBy( - () -> - new AuthoredDraftPublishSelectionReadClient( - new ServiceEndpointsProperties(), invalid, factory, "test")) + assertThatThrownBy(() -> + new AuthoredDraftPublishSelectionReadClient( + new ServiceEndpointsProperties(), invalid, factory, "test")) .isInstanceOf(IllegalArgumentException.class); } var noKey = tls(directory); noKey.setPrivateKey(null); - assertThatThrownBy( - () -> - new AuthoredDraftPublishSelectionReadClient( - new ServiceEndpointsProperties(), noKey, factory, "test")) + assertThatThrownBy(() -> + new AuthoredDraftPublishSelectionReadClient( + new ServiceEndpointsProperties(), noKey, factory, "test")) .isInstanceOf(IllegalArgumentException.class); var noCa = tls(directory); noCa.setCaCert(null); - assertThatThrownBy( - () -> - new AuthoredDraftPublishSelectionReadClient( - new ServiceEndpointsProperties(), noCa, factory, "test")) + assertThatThrownBy(() -> + new AuthoredDraftPublishSelectionReadClient( + new ServiceEndpointsProperties(), noCa, factory, "test")) .isInstanceOf(IllegalArgumentException.class); var valid = tls(directory); - assertThatThrownBy( - () -> - new AuthoredDraftPublishSelectionReadClient( - new ServiceEndpointsProperties(), valid, factory, "Test")) + assertThatThrownBy(() -> + new AuthoredDraftPublishSelectionReadClient( + new ServiceEndpointsProperties(), valid, factory, "Test")) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(factory); } @@ -92,10 +88,9 @@ void rejectsPlaintextWrongNamespaceAndUninitializedCallsBeforeTransport(@TempDir var factory = mock(GrpcChannelFactory.class); var plaintext = tls(directory); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new AuthoredDraftPublishSelectionReadClient( - new ServiceEndpointsProperties(), plaintext, factory, "test")) + assertThatThrownBy(() -> + new AuthoredDraftPublishSelectionReadClient( + new ServiceEndpointsProperties(), plaintext, factory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("workload mTLS"); @@ -104,15 +99,14 @@ void rejectsPlaintextWrongNamespaceAndUninitializedCallsBeforeTransport(@TempDir new ServiceEndpointsProperties(), tls(directory), factory, "test"); try { var request = AuthoredDraftPublishSelectionReadGrpcCodecTest.request(); - assertThatThrownBy( - () -> - client.read( - new AuthoredDraftPublishSelectionReadEvidence.Request( - request.schemaVersion(), - "other", - request.readRequestId(), - request.originalSelection(), - request.selectionDigest()))) + assertThatThrownBy(() -> + client.read( + new AuthoredDraftPublishSelectionReadEvidence.Request( + request.schemaVersion(), + "other", + request.readRequestId(), + request.originalSelection(), + request.selectionDigest()))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("configured workload namespace"); assertThatThrownBy(() -> client.read(request)) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadGrpcCodecTest.java index adcbb6d0b5..28981e0126 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AuthoredDraftPublishSelectionReadGrpcCodecTest.java @@ -28,10 +28,9 @@ void rejectsNilNoncanonicalIdentityAndMalformedOrNoncanonicalSelectionBytes() { "00000000-0000-0000-0000-000000000000", "AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA", "1-1-1-1-1")) { - assertThatThrownBy( - () -> - AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( - request.toBuilder().setReadRequestId(invalidId).build())) + assertThatThrownBy(() -> + AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( + request.toBuilder().setReadRequestId(invalidId).build())) .isInstanceOf(IllegalArgumentException.class); } String canonical = binding().canonicalJson(); @@ -42,19 +41,17 @@ void rejectsNilNoncanonicalIdentityAndMalformedOrNoncanonicalSelectionBytes() { (" " + canonical).getBytes(StandardCharsets.UTF_8), (canonical.substring(0, canonical.length() - 1) + ",\"unknown\":\"value\"}") .getBytes(StandardCharsets.UTF_8))) { - assertThatThrownBy( - () -> - AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( - request.toBuilder() - .setOriginalSelection(ByteString.copyFrom(invalidBytes)) - .build())) + assertThatThrownBy(() -> + AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( + request.toBuilder() + .setOriginalSelection(ByteString.copyFrom(invalidBytes)) + .build())) .isInstanceOf(IllegalArgumentException.class); } for (String namespace : List.of("", "Test", "test.other")) { - assertThatThrownBy( - () -> - AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( - request.toBuilder().setTargetNamespace(namespace).build())) + assertThatThrownBy(() -> + AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( + request.toBuilder().setTargetNamespace(namespace).build())) .isInstanceOf(IllegalArgumentException.class); } } @@ -99,26 +96,22 @@ void rejectsMalformedRequestsUnknownFieldsAndChangedBindingDigest() { .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); - assertThatThrownBy( - () -> - AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( - request.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( + request.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( - request.toBuilder().setReadRequestId("not-a-uuid").build())) + assertThatThrownBy(() -> + AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( + request.toBuilder().setReadRequestId("not-a-uuid").build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( - request.toBuilder().setSchemaVersion(2).build())) + assertThatThrownBy(() -> + AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( + request.toBuilder().setSchemaVersion(2).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( - request.toBuilder().setSelectionDigest("sha256:" + "0".repeat(64)).build())) + assertThatThrownBy(() -> + AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest( + request.toBuilder().setSelectionDigest("sha256:" + "0".repeat(64)).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Selected Draft publication read request is invalid") .hasCauseInstanceOf(IllegalArgumentException.class); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AutomationSelectedSourceIntakeCommandGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AutomationSelectedSourceIntakeCommandGrpcCodecTest.java index 8b3007c481..30f269aa22 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AutomationSelectedSourceIntakeCommandGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AutomationSelectedSourceIntakeCommandGrpcCodecTest.java @@ -82,58 +82,52 @@ void rejectsUnknownFieldsOversizedWireAndChangedFreezeOrAuthorizationScope() { .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); - assertThatThrownBy( - () -> - AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest( - wire.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unknown"); - assertThatThrownBy( - () -> - AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest( - wire.toBuilder().setIntakeAuthorizationDigest("0".repeat(64)).build())) + assertThatThrownBy(() -> + AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder().setIntakeAuthorizationDigest("0".repeat(64)).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("digest"); - assertThatThrownBy( - () -> - AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest( - wire.toBuilder() - .setFreezeRequest( - wire.getFreezeRequest().toBuilder().setUnknownFields(unknown).build()) - .build())) + assertThatThrownBy(() -> + AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder() + .setFreezeRequest( + wire.getFreezeRequest().toBuilder().setUnknownFields(unknown).build()) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest( - wire.toBuilder() - .setOriginalIntakeAuthorizationBinding( - ByteString.copyFrom( - new byte - [AutomationSelectedSourceIntakeCommandGrpcCodec - .MAX_REQUEST_WIRE_BYTES - + 1])) - .build())) + assertThatThrownBy(() -> + AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder() + .setOriginalIntakeAuthorizationBinding( + ByteString.copyFrom( + new byte + [AutomationSelectedSourceIntakeCommandGrpcCodec + .MAX_REQUEST_WIRE_BYTES + + 1])) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("wire budget"); var otherNamespaceFreeze = freeze("other"); - assertThatThrownBy( - () -> - new AutomationSelectedSourceIntakeCommandEvidence.Request( - AutomationSelectedSourceIntakeCommandEvidence.Request.SCHEMA_VERSION, - "test", - id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), - binding, - otherNamespaceFreeze)) + assertThatThrownBy(() -> + new AutomationSelectedSourceIntakeCommandEvidence.Request( + AutomationSelectedSourceIntakeCommandEvidence.Request.SCHEMA_VERSION, + "test", + id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + binding, + otherNamespaceFreeze)) .isInstanceOf(IllegalArgumentException.class); var wrongOwner = authorization( freeze.request().accountBinding().input().selection().selectedCommit(), Owner.ENTITY_MANAGEMENT); - assertThatThrownBy( - () -> - AutomationSelectedSourceIntakeCommandEvidence.Request.create( - "test", wrongOwner, freeze)) + assertThatThrownBy(() -> + AutomationSelectedSourceIntakeCommandEvidence.Request.create( + "test", wrongOwner, freeze)) .isInstanceOf(IllegalArgumentException.class); } @@ -167,22 +161,19 @@ void responseRequiresExactFullRequestEchoAndEncodesReceiptBytesAndDigest() { .setContentDigest("b".repeat(64))) .build()) .build(); - assertThatThrownBy( - () -> - AutomationSelectedSourceIntakeCommandGrpcCodec.fromResponse(request, changedFreeze)) + assertThatThrownBy(() -> + AutomationSelectedSourceIntakeCommandGrpcCodec.fromResponse(request, changedFreeze)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("changed"); - assertThatThrownBy( - () -> - AutomationSelectedSourceIntakeCommandGrpcCodec.fromResponse( - request, - response.toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField( - 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) - .build()) - .build())) + assertThatThrownBy(() -> + AutomationSelectedSourceIntakeCommandGrpcCodec.fromResponse( + request, + response.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unknown"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBindingTest.java index 3f3da42652..b050cbc7de 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBindingTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationOperationBindingTest.java @@ -82,10 +82,9 @@ void digestCorrectChangedAppliedOperationAndGraphStillDeny() throws Exception { "sha256:" + java.util.HexFormat.of() .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(bytes)); - assertThatThrownBy( - () -> - WorldSelectedPublicationArtifactInventoryEvidence.fromRetainedSelection( - operation.account(), operation.world(), bytes, digest)) + assertThatThrownBy(() -> + WorldSelectedPublicationArtifactInventoryEvidence.fromRetainedSelection( + operation.account(), operation.world(), bytes, digest)) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java index bee71c9c09..9b9bb5d1b9 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java @@ -55,10 +55,9 @@ void rejectsUnknownMalformedNoncanonicalAndIncompleteFramedRequests() throws Exc var operation = WorldPublicationTerminalTestFixtures.operation(); var request = ReadRequest.create("test", operation.canonicalBytes()); var wire = GameDesignPublicationTerminalReadGrpcCodec.toRequest(request); - assertThatThrownBy( - () -> - GameDesignPublicationTerminalReadGrpcCodec.fromRequest( - wire.toBuilder().setUnknownFields(unknown()).build())) + assertThatThrownBy(() -> + GameDesignPublicationTerminalReadGrpcCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknown()).build())) .isInstanceOf(IllegalArgumentException.class); for (byte[] invalid : List.of( @@ -74,12 +73,9 @@ void rejectsUnknownMalformedNoncanonicalAndIncompleteFramedRequests() throws Exc replaceFrame(request.canonicalBytes(), 4, new byte[] {1}), java.util.Arrays.copyOf( request.canonicalBytes(), request.canonicalBytes().length + 1))) { - assertThatThrownBy( - () -> - GameDesignPublicationTerminalReadGrpcCodec.fromRequest( - wire.toBuilder() - .setCanonicalRequestBytes(ByteString.copyFrom(invalid)) - .build())) + assertThatThrownBy(() -> + GameDesignPublicationTerminalReadGrpcCodec.fromRequest( + wire.toBuilder().setCanonicalRequestBytes(ByteString.copyFrom(invalid)).build())) .isInstanceOf(IllegalArgumentException.class); } } @@ -95,10 +91,9 @@ void rejectsChangedEchoUnknownMalformedMissingAndSubstitutedTerminalResponses() var changedTerminal = WorldPublicationTerminalTestFixtures.terminal( WorldPublicationTerminalTestFixtures.operation(), Outcome.NO_PUBLICATION); - assertThatThrownBy( - () -> - GameDesignPublicationTerminalReadGrpcCodec.fromResponse( - request, wire.toBuilder().setUnknownFields(unknown()).build())) + assertThatThrownBy(() -> + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + request, wire.toBuilder().setUnknownFields(unknown()).build())) .isInstanceOf(IllegalArgumentException.class); for (byte[] invalid : List.of( @@ -111,13 +106,10 @@ void rejectsChangedEchoUnknownMalformedMissingAndSubstitutedTerminalResponses() replaceFrame(result.canonicalBytes(), 3, new byte[] {1}), replaceFrame(result.canonicalBytes(), 3, changedTerminal.canonicalBytes()), java.util.Arrays.copyOf(result.canonicalBytes(), result.canonicalBytes().length + 1))) { - assertThatThrownBy( - () -> - GameDesignPublicationTerminalReadGrpcCodec.fromResponse( - request, - wire.toBuilder() - .setCanonicalResponseBytes(ByteString.copyFrom(invalid)) - .build())) + assertThatThrownBy(() -> + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + request, + wire.toBuilder().setCanonicalResponseBytes(ByteString.copyFrom(invalid)).build())) .isInstanceOf(IllegalArgumentException.class); } var changedResult = @@ -141,10 +133,9 @@ void retainsDefensiveOperationBytesAndRejectsReusedOriginalIdentity() throws Exc byte[] returned = request.operationBytes(); java.util.Arrays.fill(returned, (byte) 0); assertThat(request.operationBytes()).containsExactly(operation.canonicalBytes()); - assertThatThrownBy( - () -> - new ReadRequest( - 1, "test", operation.account().operationId(), operation.canonicalBytes())) + assertThatThrownBy(() -> + new ReadRequest( + 1, "test", operation.account().operationId(), operation.canonicalBytes())) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublicationClientCloseLifecycleTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublicationClientCloseLifecycleTest.java index ec8833424b..8a7f3ca110 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublicationClientCloseLifecycleTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublicationClientCloseLifecycleTest.java @@ -41,10 +41,8 @@ class PublicationClientCloseLifecycleTest { @ResourceLock(Resources.SYSTEM_PROPERTIES) Stream sharesInitAndCloseLifecycleAcrossExplicitClients(@TempDir Path directory) { return clientCases().stream() - .map( - testCase -> - DynamicTest.dynamicTest( - testCase.name(), () -> assertLifecycle(testCase, directory))); + .map(testCase -> + DynamicTest.dynamicTest(testCase.name(), () -> assertLifecycle(testCase, directory))); } private static List clientCases() { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublicationDigestRequestBindingTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublicationDigestRequestBindingTest.java index 66d388a588..5fc2b24809 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublicationDigestRequestBindingTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublicationDigestRequestBindingTest.java @@ -79,25 +79,23 @@ void typedScopeFactoryPreservesScopeFieldsAndOwnerScopeProof() { @Test void typedScopeFactoryRejectsInactiveFieldsBeforeOwnerRead() { assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublicationDigestRequestBinding.forScope( - PublicationDigestRequestBinding.ScopeKind.FULL_VERSION, - "tenant", - "7", - "6", - "", - "request")); - assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublicationDigestRequestBinding.forScope( - PublicationDigestRequestBinding.ScopeKind.SCRIPT_PATCH, - "tenant", - "7", - "6", - "patch", - "request")); + .isThrownBy(() -> + PublicationDigestRequestBinding.forScope( + PublicationDigestRequestBinding.ScopeKind.FULL_VERSION, + "tenant", + "7", + "6", + "", + "request")); + assertThatIllegalArgumentException() + .isThrownBy(() -> + PublicationDigestRequestBinding.forScope( + PublicationDigestRequestBinding.ScopeKind.SCRIPT_PATCH, + "tenant", + "7", + "6", + "patch", + "request")); } @Test @@ -106,22 +104,19 @@ void changedOrOmittedBindingEvidenceFailsClosed() { PublicationDigestRequestBinding.full("tenant", "1", "request"); assertThatIllegalArgumentException() - .isThrownBy( - () -> - binding.validateSupplied( - "publish:tenant:publish-request:changed", binding.requestDigest())); + .isThrownBy(() -> + binding.validateSupplied( + "publish:tenant:publish-request:changed", binding.requestDigest())); assertThatIllegalArgumentException() .isThrownBy(() -> binding.validateSupplied(binding.derivedWorkflowIdentity(), null)); assertThatIllegalArgumentException() - .isThrownBy( - () -> - binding.validateSupplied( - binding.derivedWorkflowIdentity(), binding.requestDigest().toUpperCase())); + .isThrownBy(() -> + binding.validateSupplied( + binding.derivedWorkflowIdentity(), binding.requestDigest().toUpperCase())); assertThatIllegalArgumentException() - .isThrownBy( - () -> - binding.validateSupplied( - binding.derivedWorkflowIdentity(), binding.requestDigest().substring(1))); + .isThrownBy(() -> + binding.validateSupplied( + binding.derivedWorkflowIdentity(), binding.requestDigest().substring(1))); assertThatIllegalArgumentException() .isThrownBy(() -> PublicationDigestRequestBinding.full("tenant", "", "request")); assertThatIllegalArgumentException() @@ -134,14 +129,11 @@ void changedOrOmittedBindingEvidenceFailsClosed() { void malformedScopeVersionAndIdentifiersAreRejected() { PublicationDigestRequestBinding.validatePublicationIdentity("tenant", "request"); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublicationDigestRequestBinding.validatePublicationIdentity( - "tenant", "request:id")); + .isThrownBy(() -> + PublicationDigestRequestBinding.validatePublicationIdentity("tenant", "request:id")); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublicationDigestRequestBinding.validatePublicationIdentity(" tenant", "request")); + .isThrownBy(() -> + PublicationDigestRequestBinding.validatePublicationIdentity(" tenant", "request")); assertThatIllegalArgumentException() .isThrownBy(() -> PublicationDigestRequestBinding.full("tenant", "0", "request")); assertThatIllegalArgumentException() diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java index 9eadf7f472..d6b07aa0a7 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/PublishedRealmEntryPolicyEvidenceTest.java @@ -173,15 +173,14 @@ void childEvidenceRetainsTheCanonicalPolicyAndRejectsMalformedIdentity() { assertThat(evidence.policy().canonicalJson()).isEqualTo(policy.canonicalJson()); assertThat(evidence.policyId()).isEqualTo(POLICY_ID); assertThatIllegalArgumentException() - .isThrownBy( - () -> - new PublishedRealmEntryPolicyEvidence( - POLICY_ID, - SOURCE_COMMIT_ID, - SOURCE_REVISION_ID, - "main-policy-v1", - policy, - "not-a-digest")); + .isThrownBy(() -> + new PublishedRealmEntryPolicyEvidence( + POLICY_ID, + SOURCE_COMMIT_ID, + SOURCE_REVISION_ID, + "main-policy-v1", + policy, + "not-a-digest")); } private static String digest( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/RealmEntryPolicyTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/RealmEntryPolicyTest.java index 75b6ee89ad..1cf99847be 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/RealmEntryPolicyTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/RealmEntryPolicyTest.java @@ -147,101 +147,95 @@ void validatesOnlyExplicitCanonicalEmptyObjectCreationInput() { @Test void directPolicyConstructionCannotBypassVersionPolicyDescriptorPairing() { - assertThatThrownBy( - () -> - new RealmEntryPolicy( - 1, - "world", - "World", - "realm", - "Realm", - true, - true, - StateScope.SHARED, - EntryPolicy.PLAYER_CREATED, - null, - null, - "{}")) + assertThatThrownBy(() -> + new RealmEntryPolicy( + 1, + "world", + "World", + "realm", + "Realm", + true, + true, + StateScope.SHARED, + EntryPolicy.PLAYER_CREATED, + null, + null, + "{}")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new RealmEntryPolicy( - 1, - "world", - "World", - "realm", - "Realm", - true, - true, - StateScope.SHARED, - EntryPolicy.PRESEEDED_ONLY, - PlayerCreationDescriptor.parse(descriptor()), - null, - "{}")) + assertThatThrownBy(() -> + new RealmEntryPolicy( + 1, + "world", + "World", + "realm", + "Realm", + true, + true, + StateScope.SHARED, + EntryPolicy.PRESEEDED_ONLY, + PlayerCreationDescriptor.parse(descriptor()), + null, + "{}")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new RealmEntryPolicy( - 2, - "world", - "World", - "realm", - "Realm", - true, - true, - StateScope.SHARED, - EntryPolicy.PRESEEDED_ONLY, - null, - null, - "{}")) + assertThatThrownBy(() -> + new RealmEntryPolicy( + 2, + "world", + "World", + "realm", + "Realm", + true, + true, + StateScope.SHARED, + EntryPolicy.PRESEEDED_ONLY, + null, + null, + "{}")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new RealmEntryPolicy( - 2, - "world", - "World", - "realm", - "Realm", - true, - true, - StateScope.SHARED, - EntryPolicy.PLAYER_CREATED, - null, - null, - "{}")) + assertThatThrownBy(() -> + new RealmEntryPolicy( + 2, + "world", + "World", + "realm", + "Realm", + true, + true, + StateScope.SHARED, + EntryPolicy.PLAYER_CREATED, + null, + null, + "{}")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new RealmEntryPolicy( - 3, - "world", - "World", - "realm", - "Realm", - true, - true, - StateScope.SHARED, - EntryPolicy.PRESEEDED_ONLY, - null, - null, - "{}")) + assertThatThrownBy(() -> + new RealmEntryPolicy( + 3, + "world", + "World", + "realm", + "Realm", + true, + true, + StateScope.SHARED, + EntryPolicy.PRESEEDED_ONLY, + null, + null, + "{}")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new RealmEntryPolicy( - 3, - "world", - "World", - "realm", - "Realm", - true, - true, - StateScope.SHARED, - EntryPolicy.PLAYER_CREATED, - PlayerCreationDescriptor.parse(descriptor()), - null, - "{}")) + assertThatThrownBy(() -> + new RealmEntryPolicy( + 3, + "world", + "World", + "realm", + "Realm", + true, + true, + StateScope.SHARED, + EntryPolicy.PLAYER_CREATED, + PlayerCreationDescriptor.parse(descriptor()), + null, + "{}")) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/SelectedEmptyPublicationDigestSupportTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/SelectedEmptyPublicationDigestSupportTest.java index 71fcba0630..716dadd380 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/SelectedEmptyPublicationDigestSupportTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/SelectedEmptyPublicationDigestSupportTest.java @@ -47,16 +47,15 @@ void publicationVersionRowMustMatchTheRetainedSelectedTarget() { tenantId.toString(), Long.toString(retainedVersionRowId + 1L), publishRequestId); assertThatIllegalStateException() - .isThrownBy( - () -> - SelectedEmptyPublicationDigestSupport.requireOriginalPublicationRequest( - mismatchedRequest, - tenantId, - retainedVersionRowId + 1L, - versionId, - selectedCommitId, - freeze, - "Entity")) + .isThrownBy(() -> + SelectedEmptyPublicationDigestSupport.requireOriginalPublicationRequest( + mismatchedRequest, + tenantId, + retainedVersionRowId + 1L, + versionId, + selectedCommitId, + freeze, + "Entity")) .withMessageContaining( "publication version row differs from the original retained World freeze"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionClientTest.java index b22a24f24e..0039594bf2 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionClientTest.java @@ -62,12 +62,11 @@ void closeReleasesClientMonitorBeforeDrainingCertificateCallback(@TempDir Path d GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); when(channelFactory.buildChannel( eq("world.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) - .thenAnswer( - invocation -> { - ManagedChannel channel = mock(ManagedChannel.class); - channels.add(channel); - return channel; - }); + .thenAnswer(invocation -> { + ManagedChannel channel = mock(ManagedChannel.class); + channels.add(channel); + return channel; + }); client = new WorldPublicationTerminalCompletionClient(endpoints, tls, channelFactory, "test"); client.init(); WorldPublicationTerminalCompletionClient clientUnderTest = client; diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java index af7d66dd4a..1fb6db57c3 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java @@ -57,10 +57,9 @@ void historicalTerminalReadbackCannotEnterCurrentV2CompletionTransport() throws GameDesignPublicationTerminalEvidence.fromStored(historicalTerminal.canonicalBytes()) .operationBytes()) .containsExactly(original); - assertThatThrownBy( - () -> - WorldPublicationTerminalCompletionGrpcCodec.Request.create( - "test", original, historicalTerminal.canonicalBytes())) + assertThatThrownBy(() -> + WorldPublicationTerminalCompletionGrpcCodec.Request.create( + "test", original, historicalTerminal.canonicalBytes())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Complete canonical publication operation and terminal required"); @@ -111,19 +110,17 @@ void rejectsMalformedAndNoncanonicalRequestsAndUnknownFields() throws Exception .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - new WorldPublicationTerminalCompletionGrpcCodec.Request( - 2, - "test", - UUID.randomUUID(), - operation.canonicalBytes(), - terminal.canonicalBytes())) + assertThatThrownBy(() -> + new WorldPublicationTerminalCompletionGrpcCodec.Request( + 2, + "test", + UUID.randomUUID(), + operation.canonicalBytes(), + terminal.canonicalBytes())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldPublicationTerminalCompletionGrpcCodec.Request.create( - "test", operation.canonicalBytes(), new byte[0])) + assertThatThrownBy(() -> + WorldPublicationTerminalCompletionGrpcCodec.Request.create( + "test", operation.canonicalBytes(), new byte[0])) .isInstanceOf(IllegalArgumentException.class); } @@ -190,10 +187,8 @@ void rejectsChangedEchoStoredTerminalAndOverBudgetCompleteMessages() throws Exce ByteString.copyFrom( new byte[WorldPublicationTerminalCompletionGrpcCodec.MAX_MESSAGE_BYTES])) .build(); - assertThatThrownBy( - () -> - WorldPublicationTerminalCompletionGrpcCodec.fromResponse( - request, oversizedResponse)) + assertThatThrownBy(() -> + WorldPublicationTerminalCompletionGrpcCodec.fromResponse(request, oversizedResponse)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("32 MiB"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadClientTest.java index 5987851763..c7e152ddbe 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadClientTest.java @@ -41,30 +41,26 @@ void requiresReadableFileBackedMtlsAndCanonicalNamespace(@TempDir Path directory directory.toString())) { var invalid = tls(directory); invalid.setCertChain(badPath); - assertThatThrownBy( - () -> - new WorldPublicationTerminalReadClient( - new ServiceEndpointsProperties(), invalid, factory, "test")) + assertThatThrownBy(() -> + new WorldPublicationTerminalReadClient( + new ServiceEndpointsProperties(), invalid, factory, "test")) .isInstanceOf(IllegalArgumentException.class); } var noKey = tls(directory); noKey.setPrivateKey(null); - assertThatThrownBy( - () -> - new WorldPublicationTerminalReadClient( - new ServiceEndpointsProperties(), noKey, factory, "test")) + assertThatThrownBy(() -> + new WorldPublicationTerminalReadClient( + new ServiceEndpointsProperties(), noKey, factory, "test")) .isInstanceOf(IllegalArgumentException.class); var noCa = tls(directory); noCa.setCaCert(null); - assertThatThrownBy( - () -> - new WorldPublicationTerminalReadClient( - new ServiceEndpointsProperties(), noCa, factory, "test")) + assertThatThrownBy(() -> + new WorldPublicationTerminalReadClient( + new ServiceEndpointsProperties(), noCa, factory, "test")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new WorldPublicationTerminalReadClient( - new ServiceEndpointsProperties(), tls(directory), factory, "Test")) + assertThatThrownBy(() -> + new WorldPublicationTerminalReadClient( + new ServiceEndpointsProperties(), tls(directory), factory, "Test")) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(factory); } @@ -75,10 +71,9 @@ void rejectsPlaintextWrongNamespaceAndUninitializedCallsBeforeTransport(@TempDir var factory = mock(GrpcChannelFactory.class); var plaintext = tls(directory); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new WorldPublicationTerminalReadClient( - new ServiceEndpointsProperties(), plaintext, factory, "test")) + assertThatThrownBy(() -> + new WorldPublicationTerminalReadClient( + new ServiceEndpointsProperties(), plaintext, factory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("workload mTLS"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidenceTest.java index 89065a82ea..d6c9d54731 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalReadEvidenceTest.java @@ -10,14 +10,13 @@ class WorldPublicationTerminalReadEvidenceTest { @Test void rejectsAnOversizedOriginalOperationBeforeParsingTheTerminal() { - assertThatThrownBy( - () -> - new WorldPublicationTerminalReadEvidence.Request( - 1, - "test", - UUID.randomUUID(), - new byte[GameDesignPublicationOperationBinding.MAX_OPERATION_BYTES + 1], - new byte[] {1})) + assertThatThrownBy(() -> + new WorldPublicationTerminalReadEvidence.Request( + 1, + "test", + UUID.randomUUID(), + new byte[GameDesignPublicationOperationBinding.MAX_OPERATION_BYTES + 1], + new byte[] {1})) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Complete bounded original publication operation required") .hasNoCause(); @@ -32,18 +31,16 @@ void boundsCombinedWirePayloadBeforeCloningOrParsingTerminal() { - operationBytes; byte[] operation = new byte[operationBytes]; - assertThatThrownBy( - () -> - new WorldPublicationTerminalReadEvidence.Request( - 1, "test", UUID.randomUUID(), operation, new byte[terminalAtBoundary])) + assertThatThrownBy(() -> + new WorldPublicationTerminalReadEvidence.Request( + 1, "test", UUID.randomUUID(), operation, new byte[terminalAtBoundary])) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Canonical complete publication operation and terminal evidence required") .hasCauseInstanceOf(RuntimeException.class); - assertThatThrownBy( - () -> - new WorldPublicationTerminalReadEvidence.Request( - 1, "test", UUID.randomUUID(), operation, new byte[terminalAtBoundary + 1])) + assertThatThrownBy(() -> + new WorldPublicationTerminalReadEvidence.Request( + 1, "test", UUID.randomUUID(), operation, new byte[terminalAtBoundary + 1])) .isInstanceOf(IllegalArgumentException.class) .hasMessage("World publication terminal read exceeds the 32 MiB wire budget") .hasNoCause(); @@ -58,12 +55,9 @@ void wrapsMalformedOrNullWorldTerminalReadbackAsCanonicalInvalidInput() throws E "test", operation.canonicalBytes(), terminal.canonicalBytes()); for (byte[] malformed : new byte[][] {new byte[] {1}, null}) { - assertThatThrownBy( - () -> - WorldPublicationTerminalReadEvidence.fromOwnerRead( - request, - WorldPublicationTerminalReadEvidence.WorldOutcome.PUBLISHED, - malformed)) + assertThatThrownBy(() -> + WorldPublicationTerminalReadEvidence.fromOwnerRead( + request, WorldPublicationTerminalReadEvidence.WorldOutcome.PUBLISHED, malformed)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Canonical complete publication operation and terminal evidence required") .hasCauseInstanceOf(RuntimeException.class); @@ -110,57 +104,47 @@ void rejectsInvalidRequestBindingsAndAWorldOutcomeThatDoesNotMatchTheStoredPhase WorldPublicationTerminalReadEvidence.Request.create( "test", operation.canonicalBytes(), terminal.canonicalBytes()); - assertThatThrownBy( - () -> - new WorldPublicationTerminalReadEvidence.Request( - 2, - "test", - UUID.randomUUID(), - operation.canonicalBytes(), - terminal.canonicalBytes())) + assertThatThrownBy(() -> + new WorldPublicationTerminalReadEvidence.Request( + 2, + "test", + UUID.randomUUID(), + operation.canonicalBytes(), + terminal.canonicalBytes())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new WorldPublicationTerminalReadEvidence.Request( - 1, - "Test", - UUID.randomUUID(), - operation.canonicalBytes(), - terminal.canonicalBytes())) + assertThatThrownBy(() -> + new WorldPublicationTerminalReadEvidence.Request( + 1, + "Test", + UUID.randomUUID(), + operation.canonicalBytes(), + terminal.canonicalBytes())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new WorldPublicationTerminalReadEvidence.Request( - 1, - "test", - new UUID(0L, 0L), - operation.canonicalBytes(), - terminal.canonicalBytes())) + assertThatThrownBy(() -> + new WorldPublicationTerminalReadEvidence.Request( + 1, "test", new UUID(0L, 0L), operation.canonicalBytes(), terminal.canonicalBytes())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new WorldPublicationTerminalReadEvidence.Request( - 1, "test", UUID.randomUUID(), new byte[] {1}, terminal.canonicalBytes())) + assertThatThrownBy(() -> + new WorldPublicationTerminalReadEvidence.Request( + 1, "test", UUID.randomUUID(), new byte[] {1}, terminal.canonicalBytes())) .isInstanceOf(IllegalArgumentException.class); var changedOperation = WorldPublicationTerminalTestFixtures.operation(); var changedTerminal = WorldPublicationTerminalTestFixtures.terminal(changedOperation, Outcome.NO_PUBLICATION); - assertThatThrownBy( - () -> - new WorldPublicationTerminalReadEvidence.Request( - 1, - "test", - UUID.randomUUID(), - operation.canonicalBytes(), - changedTerminal.canonicalBytes())) + assertThatThrownBy(() -> + new WorldPublicationTerminalReadEvidence.Request( + 1, + "test", + UUID.randomUUID(), + operation.canonicalBytes(), + changedTerminal.canonicalBytes())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldPublicationTerminalReadEvidence.fromOwnerRead( - request, - WorldPublicationTerminalReadEvidence.WorldOutcome.PUBLISHED, - terminal.canonicalBytes())) + assertThatThrownBy(() -> + WorldPublicationTerminalReadEvidence.fromOwnerRead( + request, + WorldPublicationTerminalReadEvidence.WorldOutcome.PUBLISHED, + terminal.canonicalBytes())) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalTestFixtures.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalTestFixtures.java index d166957b5a..32825ffbd7 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalTestFixtures.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalTestFixtures.java @@ -31,25 +31,19 @@ static GameDesignPublicationTerminalEvidence terminal( var request = operation.world().request(); var participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new Participant( - owner, - Long.toString( - operation - .account() - .input() - .selection() - .target() - .gameDesignVersionRowId()), - null, - request.appliedCommitId(), - owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - owner.equals("GAME_LOGIC") ? DIGEST : null, - null, - null)) + .map(owner -> + new Participant( + owner, + Long.toString( + operation.account().input().selection().target().gameDesignVersionRowId()), + null, + request.appliedCommitId(), + owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + owner.equals("GAME_LOGIC") ? DIGEST : null, + null, + null)) .toList(); var release = new ReleaseContent( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeClientTest.java index 5876904e7e..000aa09dba 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeClientTest.java @@ -33,16 +33,14 @@ void requiresFileBackedMtlsAndCanonicalNamespace(@TempDir Path directory) throws var factory = mock(GrpcChannelFactory.class); var plaintext = tls(directory); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new WorldSelectedDraftPublicationFreezeClient( - new ServiceEndpointsProperties(), plaintext, factory, "test")) + assertThatThrownBy(() -> + new WorldSelectedDraftPublicationFreezeClient( + new ServiceEndpointsProperties(), plaintext, factory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("workload mTLS"); - assertThatThrownBy( - () -> - new WorldSelectedDraftPublicationFreezeClient( - new ServiceEndpointsProperties(), tls(directory), factory, "Test")) + assertThatThrownBy(() -> + new WorldSelectedDraftPublicationFreezeClient( + new ServiceEndpointsProperties(), tls(directory), factory, "Test")) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(factory); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodecTest.java index f4ae02f454..c8b4d08d69 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedDraftPublicationFreezeGrpcCodecTest.java @@ -42,10 +42,9 @@ void rejectsUnknownFieldsMalformedBindingsAndNoncanonicalRequestValues() { .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); - assertThatThrownBy( - () -> - WorldSelectedDraftPublicationFreezeGrpcCodec.fromRequest( - wire.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + WorldSelectedDraftPublicationFreezeGrpcCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); for (var changed : diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryClientTest.java index 4ec65676b3..f79ecc6ff7 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryClientTest.java @@ -33,16 +33,14 @@ void requiresFileBackedMtlsAndCanonicalNamespace(@TempDir Path directory) throws var factory = mock(GrpcChannelFactory.class); var plaintext = tls(directory); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new WorldSelectedPublicationArtifactInventoryClient( - new ServiceEndpointsProperties(), plaintext, factory, "test")) + assertThatThrownBy(() -> + new WorldSelectedPublicationArtifactInventoryClient( + new ServiceEndpointsProperties(), plaintext, factory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("workload mTLS"); - assertThatThrownBy( - () -> - new WorldSelectedPublicationArtifactInventoryClient( - new ServiceEndpointsProperties(), tls(directory), factory, "Test")) + assertThatThrownBy(() -> + new WorldSelectedPublicationArtifactInventoryClient( + new ServiceEndpointsProperties(), tls(directory), factory, "Test")) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(factory); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryGrpcCodecTest.java index b77ddf4ea6..ad3f0dc5ec 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldSelectedPublicationArtifactInventoryGrpcCodecTest.java @@ -117,22 +117,19 @@ void versionedInboundClosureRejectsMissingUnknownAndNonemptyFamilies() { model.inboundSourceClosure().familyCounts().get(5), model.inboundSourceClosure().familyCounts().get(6))); - assertThatThrownBy( - () -> - WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( - fixture.freezeEvidence(), withInboundClosure(inbound, nonempty))) + assertThatThrownBy(() -> + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + fixture.freezeEvidence(), withInboundClosure(inbound, nonempty))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported nonempty"); - assertThatThrownBy( - () -> - WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( - fixture.freezeEvidence(), withInboundClosure(inbound, unknown))) + assertThatThrownBy(() -> + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + fixture.freezeEvidence(), withInboundClosure(inbound, unknown))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("not canonical"); - assertThatThrownBy( - () -> - WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( - fixture.freezeEvidence(), withInboundClosure(inbound, null))) + assertThatThrownBy(() -> + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + fixture.freezeEvidence(), withInboundClosure(inbound, null))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("source model is unsupported or incomplete"); } @@ -149,19 +146,14 @@ void rejectsChangedFreezeDigestUnknownFieldsAndNoncanonicalOrOpenPublicBytes() { .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); - assertThatThrownBy( - () -> - WorldSelectedPublicationArtifactInventoryGrpcCodec.fromResponse( - fixture.freezeEvidence(), - response.toBuilder() - .setPublicInventoryDigest("sha256:" + "0".repeat(64)) - .build())) + assertThatThrownBy(() -> + WorldSelectedPublicationArtifactInventoryGrpcCodec.fromResponse( + fixture.freezeEvidence(), + response.toBuilder().setPublicInventoryDigest("sha256:" + "0".repeat(64)).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldSelectedPublicationArtifactInventoryGrpcCodec.fromResponse( - fixture.freezeEvidence(), - response.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + WorldSelectedPublicationArtifactInventoryGrpcCodec.fromResponse( + fixture.freezeEvidence(), response.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); @@ -192,10 +184,9 @@ void rejectsChangedFreezeDigestUnknownFieldsAndNoncanonicalOrOpenPublicBytes() { original.sourceModel(), original.artifactDecisions()); byte[] changedBytes = changedEvidence.canonicalBytes(); - assertThatThrownBy( - () -> - WorldSelectedPublicationArtifactInventoryEvidence.fromCanonicalBytes( - fixture.freezeEvidence(), changedBytes, sha256(changedBytes))) + assertThatThrownBy(() -> + WorldSelectedPublicationArtifactInventoryEvidence.fromCanonicalBytes( + fixture.freezeEvidence(), changedBytes, sha256(changedBytes))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("differs from exact selected Account order or freeze checkpoint"); @@ -297,19 +288,18 @@ void rejectsChangedFreezeDigestUnknownFieldsAndNoncanonicalOrOpenPublicBytes() { model.generationRuleInputCount(), model.spawnBindingCount(), model.appliedEpochs()); - assertThatThrownBy( - () -> - new PublicEvidence( - fixture.publicEvidence().schema(), - fixture.publicEvidence().schemaVersion(), - fixture.publicEvidence().completeness(), - fixture.publicEvidence().ownerScope(), - fixture.publicEvidence().selectedApplication(), - fixture.publicEvidence().accountOrder(), - fixture.publicEvidence().freeze(), - fixture.publicEvidence().checkpoint(), - unsupportedModel, - fixture.publicEvidence().artifactDecisions())) + assertThatThrownBy(() -> + new PublicEvidence( + fixture.publicEvidence().schema(), + fixture.publicEvidence().schemaVersion(), + fixture.publicEvidence().completeness(), + fixture.publicEvidence().ownerScope(), + fixture.publicEvidence().selectedApplication(), + fixture.publicEvidence().accountOrder(), + fixture.publicEvidence().freeze(), + fixture.publicEvidence().checkpoint(), + unsupportedModel, + fixture.publicEvidence().artifactDecisions())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("source model is unsupported or incomplete"); } @@ -382,15 +372,14 @@ static Fixture fixture() { 0, 0, commit.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .map(unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) .toList()); var publicEvidence = new PublicEvidence( @@ -515,10 +504,9 @@ private static PublicEvidence withInboundClosure( private static void assertRejectedPublicJson(Fixture fixture, String json) { byte[] bytes = json.getBytes(StandardCharsets.UTF_8); - assertThatThrownBy( - () -> - WorldSelectedPublicationArtifactInventoryEvidence.fromCanonicalBytes( - fixture.freezeEvidence(), bytes, sha256(bytes))) + assertThatThrownBy(() -> + WorldSelectedPublicationArtifactInventoryEvidence.fromCanonicalBytes( + fixture.freezeEvidence(), bytes, sha256(bytes))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/security/ProtectedPodUidProjectionTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/security/ProtectedPodUidProjectionTest.java index 4d93b0a935..70dc36eb6d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/security/ProtectedPodUidProjectionTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/security/ProtectedPodUidProjectionTest.java @@ -138,10 +138,8 @@ void rejectsNonCanonicalAtomicWriterDataLink() throws IOException { void rejectsWrongOwner() throws IOException { Projection projection = createProjection(POD_UID); - assertThatThrownBy( - () -> - ProtectedPodUidProjection.readForTesting( - projection.root(), projection.ownerUid() + 1)) + assertThatThrownBy(() -> + ProtectedPodUidProjection.readForTesting(projection.root(), projection.ownerUid() + 1)) .isInstanceOf(ProtectedPodUidProjection.ProtectedPodUidUnavailableException.class); } @@ -185,9 +183,8 @@ private Projection createProjection(String uidContents) throws IOException { } private void assertUnavailable(Projection projection) { - assertThatThrownBy( - () -> - ProtectedPodUidProjection.readForTesting(projection.root(), projection.ownerUid())) + assertThatThrownBy(() -> + ProtectedPodUidProjection.readForTesting(projection.root(), projection.ownerUid())) .isInstanceOf(ProtectedPodUidProjection.ProtectedPodUidUnavailableException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/security/ProtectedProjectionMountTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/security/ProtectedProjectionMountTest.java index 0cbcdf6e95..995788a4af 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/security/ProtectedProjectionMountTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/security/ProtectedProjectionMountTest.java @@ -67,10 +67,9 @@ void rejectsExactRootHiddenByAnAncestorOvermount() { BASE_MOUNT + "10 1 0:9 / /parent/projection ro - tmpfs tmpfs rw\n" + "20 1 0:9 /other /parent rw - tmpfs tmpfs rw\n"; - assertThatThrownBy( - () -> - ProtectedProjectionMount.parse( - Path.of("/parent/projection"), table.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + ProtectedProjectionMount.parse( + Path.of("/parent/projection"), table.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IOException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java index 86582e03dd..2a0a338891 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java @@ -176,13 +176,9 @@ void rejectsFreshCreationAndSourceEvidenceWithDifferentValidProvenance() { assertThat(creationEvidence().provenanceKind()).isEqualTo("NEW_GAME_ROW"); assertThat(retainedSourceEvidence.provenanceKind()).isEqualTo("RETAINED_GAME_V29"); - assertThatThrownBy( - () -> - RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( - capability(), - creationEvidence(), - retainedSourceEvidence, - retainedSourceLaunchRead)) + assertThatThrownBy(() -> + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestBytes( + capability(), creationEvidence(), retainedSourceEvidence, retainedSourceLaunchRead)) .isInstanceOf(RunOwnedInitialAdmissionFixtureWireCodec.InvalidWireDataException.class); } @@ -214,16 +210,14 @@ void retainsExactClaimCreationAndPolicySealAndRejectsReplaySubstitution() { validSourceReceiptJson() .replace( creationEvidence().creationRequestId().toString(), UUID.randomUUID().toString())); - assertThatThrownBy( - () -> - RunOwnedInitialAdmissionFixtureWireCodec.parseFixturePolicyRequestBytes( - Arrays.copyOf(request, request.length + 1))) + assertThatThrownBy(() -> + RunOwnedInitialAdmissionFixtureWireCodec.parseFixturePolicyRequestBytes( + Arrays.copyOf(request, request.length + 1))) .isInstanceOf(RunOwnedInitialAdmissionFixtureWireCodec.InvalidWireDataException.class); byte[] badLength = request.clone(); ByteBuffer.wrap(badLength).putInt(Integer.MAX_VALUE); - assertThatThrownBy( - () -> - RunOwnedInitialAdmissionFixtureWireCodec.parseFixturePolicyRequestBytes(badLength)) + assertThatThrownBy(() -> + RunOwnedInitialAdmissionFixtureWireCodec.parseFixturePolicyRequestBytes(badLength)) .isInstanceOf(RunOwnedInitialAdmissionFixtureWireCodec.InvalidWireDataException.class); } @@ -268,28 +262,23 @@ void closedFixtureAllocationReadRejectsChangedIdentitySealAndVersion() { response.toBuilder().setPlayableStateScopeValue(999).build(), response.toBuilder().setGameSessionTenantId(0L).build() }) { - assertThatThrownBy( - () -> - CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse( - result.request(), wrong)) + assertThatThrownBy(() -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse( + result.request(), wrong)) .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureRequest( - request.toBuilder().setUnknownFields(UNKNOWN_FIELD_SET).build())) + assertThatThrownBy(() -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureRequest( + request.toBuilder().setUnknownFields(UNKNOWN_FIELD_SET).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse( - result.request(), - response.toBuilder().setUnknownFields(UNKNOWN_FIELD_SET).build())) + assertThatThrownBy(() -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse( + result.request(), response.toBuilder().setUnknownFields(UNKNOWN_FIELD_SET).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse( - result.request(), - response.toBuilder().setCurrentGameInstanceStatus("RUNNING").build())) + assertThatThrownBy(() -> + CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse( + result.request(), + response.toBuilder().setCurrentGameInstanceStatus("RUNNING").build())) .isInstanceOf(IllegalArgumentException.class); } @@ -357,8 +346,8 @@ private static void assertInvalidReceiptBytes(byte[] bytes) { private static String validCapabilityJson() { return """ - {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":7,"gameTemplateId":17,"ownerAccountId":27,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","claimDigest":"%s"}\ - """ + {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":7,"gameTemplateId":17,"ownerAccountId":27,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","claimDigest":"%s"}\ + """ .formatted( RunOwnedInitialAdmissionFixtureWireCodec.CAPABILITY_SCHEMA, RUN_ID, diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java index 7f2b8cbb06..28bceba771 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/AuthoredWorldSourceEvidenceTest.java @@ -233,40 +233,38 @@ void rejectsUnsupportedVersionMalformedIdentitySelectorsAndDisplayName() { @Test void rejectsChangedRequestReceiptSourceBoundsAndUnknownProvenance() { AuthoredWorldSourceEvidence valid = evidence(PROVENANCE); - assertThatThrownBy( - () -> - new AuthoredWorldSourceEvidence( - valid.schemaVersion(), - valid.targetNamespace(), - valid.registrationRequestId(), - valid.operationId(), - "sha256:" + "0".repeat(64), - valid.canonicalTenantId(), - valid.tenantSlug(), - valid.worldSlug(), - valid.worldDisplayName(), - valid.sourceGameRowId(), - valid.sourceGameTenantKey(), - valid.provenanceKind(), - valid.evidenceDigest())) + assertThatThrownBy(() -> + new AuthoredWorldSourceEvidence( + valid.schemaVersion(), + valid.targetNamespace(), + valid.registrationRequestId(), + valid.operationId(), + "sha256:" + "0".repeat(64), + valid.canonicalTenantId(), + valid.tenantSlug(), + valid.worldSlug(), + valid.worldDisplayName(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind(), + valid.evidenceDigest())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Request digest"); - assertThatThrownBy( - () -> - new AuthoredWorldSourceEvidence( - valid.schemaVersion(), - valid.targetNamespace(), - valid.registrationRequestId(), - valid.operationId(), - valid.requestDigest(), - valid.canonicalTenantId(), - valid.tenantSlug(), - valid.worldSlug(), - valid.worldDisplayName(), - valid.sourceGameRowId(), - valid.sourceGameTenantKey(), - valid.provenanceKind(), - "sha256:" + "0".repeat(64))) + assertThatThrownBy(() -> + new AuthoredWorldSourceEvidence( + valid.schemaVersion(), + valid.targetNamespace(), + valid.registrationRequestId(), + valid.operationId(), + valid.requestDigest(), + valid.canonicalTenantId(), + valid.tenantSlug(), + valid.worldSlug(), + valid.worldDisplayName(), + valid.sourceGameRowId(), + valid.sourceGameTenantKey(), + valid.provenanceKind(), + "sha256:" + "0".repeat(64))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Evidence digest"); assertInvalid( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/CurrentTenantCreationAuthorizationGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/CurrentTenantCreationAuthorizationGrpcCodecTest.java index 1a800c9212..6b8c48794a 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/CurrentTenantCreationAuthorizationGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/CurrentTenantCreationAuthorizationGrpcCodecTest.java @@ -55,22 +55,17 @@ void rejectsUnknownFieldsSchemaAndNonCanonicalRequestIdentities() { assertThatThrownBy(() -> CurrentTenantCreationAuthorizationGrpcCodec.decodeRequest(unknown)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unknown"); - assertThatThrownBy( - () -> - CurrentTenantCreationAuthorizationGrpcCodec.decodeRequest( - valid.toBuilder().setSchemaVersion(2).build())) + assertThatThrownBy(() -> + CurrentTenantCreationAuthorizationGrpcCodec.decodeRequest( + valid.toBuilder().setSchemaVersion(2).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CurrentTenantCreationAuthorizationGrpcCodec.decodeRequest( - valid.toBuilder() - .setReadRequestId("00000000-0000-0000-0000-000000000000") - .build())) + assertThatThrownBy(() -> + CurrentTenantCreationAuthorizationGrpcCodec.decodeRequest( + valid.toBuilder().setReadRequestId("00000000-0000-0000-0000-000000000000").build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CurrentTenantCreationAuthorizationGrpcCodec.decodeRequest( - valid.toBuilder().setCreationRequestId("not-a-uuid").build())) + assertThatThrownBy(() -> + CurrentTenantCreationAuthorizationGrpcCodec.decodeRequest( + valid.toBuilder().setCreationRequestId("not-a-uuid").build())) .isInstanceOf(IllegalArgumentException.class); } @@ -80,38 +75,33 @@ void rejectsChangedBindingReadIdAndMalformedOrExpiredRangeValues() { var response = CurrentTenantCreationAuthorizationGrpcCodec.response(READ_ID, BINDING, validBefore); - assertThatThrownBy( - () -> - CurrentTenantCreationAuthorizationGrpcCodec.verifyResponse( - UUID.randomUUID(), BINDING, response)) + assertThatThrownBy(() -> + CurrentTenantCreationAuthorizationGrpcCodec.verifyResponse( + UUID.randomUUID(), BINDING, response)) .isInstanceOf(IllegalArgumentException.class) .hasRootCauseMessage( "Current tenant-creation authorization response changed its exact request"); - assertThatThrownBy( - () -> - CurrentTenantCreationAuthorizationGrpcCodec.verifyResponse( - READ_ID, - new Binding( - BINDING.targetNamespace(), - BINDING.creationRequestId(), - BINDING.accountAuthorizationOperationId(), - UUID.fromString("55555555-5555-4555-8555-555555555555"), - BINDING.creationRequestDigest(), - BINDING.accountAuthorizationDigest()), - response)) + assertThatThrownBy(() -> + CurrentTenantCreationAuthorizationGrpcCodec.verifyResponse( + READ_ID, + new Binding( + BINDING.targetNamespace(), + BINDING.creationRequestId(), + BINDING.accountAuthorizationOperationId(), + UUID.fromString("55555555-5555-4555-8555-555555555555"), + BINDING.creationRequestDigest(), + BINDING.accountAuthorizationDigest()), + response)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> CurrentTenantCreationAuthorizationGrpcCodec.response(READ_ID, BINDING, 0)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CurrentTenantCreationAuthorizationGrpcCodec.response( - READ_ID, BINDING, Long.MAX_VALUE)) + assertThatThrownBy(() -> + CurrentTenantCreationAuthorizationGrpcCodec.response(READ_ID, BINDING, Long.MAX_VALUE)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CurrentTenantCreationAuthorizationGrpcCodec.verifyResponse( - READ_ID, BINDING, response.toBuilder().setValidBeforeEpochMillis(0).build())) + assertThatThrownBy(() -> + CurrentTenantCreationAuthorizationGrpcCodec.verifyResponse( + READ_ID, BINDING, response.toBuilder().setValidBeforeEpochMillis(0).build())) .isInstanceOf(IllegalArgumentException.class); } @@ -128,10 +118,8 @@ void rejectsUnknownFieldsInResponse() { .build()) .build(); - assertThatThrownBy( - () -> - CurrentTenantCreationAuthorizationGrpcCodec.verifyResponse( - READ_ID, BINDING, unknown)) + assertThatThrownBy(() -> + CurrentTenantCreationAuthorizationGrpcCodec.verifyResponse(READ_ID, BINDING, unknown)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unknown"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreationEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreationEvidenceTest.java index 5e62a0a3e2..9a2db4a29d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreationEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreationEvidenceTest.java @@ -196,19 +196,18 @@ private static void assertInvalid( String sourceGameTenantKey, String provenanceKind, String evidenceDigest) { - assertThatThrownBy( - () -> - evidence( - schemaVersion, - namespace, - creationRequestId, - operationId, - requestDigest, - canonicalTenantId, - sourceGameRowId, - sourceGameTenantKey, - provenanceKind, - evidenceDigest)) + assertThatThrownBy(() -> + evidence( + schemaVersion, + namespace, + creationRequestId, + operationId, + requestDigest, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind, + evidenceDigest)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigestTest.java index 6478afe58e..f708b1ad20 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigestTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorDigestTest.java @@ -94,29 +94,21 @@ void bindsEveryCreationAndAccountAuthorizationIdentityComponent() { void rejectsUnsupportedVersionNilIdentityAndMalformedDigest() { FreshTenantCreationEvidence creation = creationEvidence(42L, "legacy-α"); - assertThatThrownBy( - () -> - FreshTenantCreatorDigest.evidenceDigest( - 2, creation, ACCOUNT_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST)) + assertThatThrownBy(() -> + FreshTenantCreatorDigest.evidenceDigest( + 2, creation, ACCOUNT_ID, AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - FreshTenantCreatorDigest.evidenceDigest( - 1, - creation, - new UUID(0L, 0L), - AUTHORIZATION_OPERATION_ID, - AUTHORIZATION_DIGEST)) + assertThatThrownBy(() -> + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, new UUID(0L, 0L), AUTHORIZATION_OPERATION_ID, AUTHORIZATION_DIGEST)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - FreshTenantCreatorDigest.evidenceDigest( - 1, creation, ACCOUNT_ID, new UUID(0L, 0L), AUTHORIZATION_DIGEST)) + assertThatThrownBy(() -> + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, ACCOUNT_ID, new UUID(0L, 0L), AUTHORIZATION_DIGEST)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - FreshTenantCreatorDigest.evidenceDigest( - 1, creation, ACCOUNT_ID, AUTHORIZATION_OPERATION_ID, "not-a-digest")) + assertThatThrownBy(() -> + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, ACCOUNT_ID, AUTHORIZATION_OPERATION_ID, "not-a-digest")) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidenceTest.java index 56569f3c18..2ceacc595c 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/FreshTenantCreatorEvidenceTest.java @@ -90,14 +90,9 @@ void rejectsUnsupportedVersionNilIdentitiesAndMalformedAuthorizationDigest() { AUTHORIZATION_DIGEST, correctDigest); assertInvalid(1, creation, ACCOUNT_ID, new UUID(0L, 0L), AUTHORIZATION_DIGEST, correctDigest); - assertThatThrownBy( - () -> - FreshTenantCreatorDigest.evidenceDigest( - 1, - creation, - ACCOUNT_ID, - AUTHORIZATION_OPERATION_ID, - "SHA256:" + "a".repeat(64))) + assertThatThrownBy(() -> + FreshTenantCreatorDigest.evidenceDigest( + 1, creation, ACCOUNT_ID, AUTHORIZATION_OPERATION_ID, "SHA256:" + "a".repeat(64))) .isInstanceOf(IllegalArgumentException.class); } @@ -150,15 +145,14 @@ private static void assertInvalid( UUID authorizationOperationId, String authorizationDigest, String evidenceDigest) { - assertThatThrownBy( - () -> - new FreshTenantCreatorEvidence( - schemaVersion, - creation, - accountId, - authorizationOperationId, - authorizationDigest, - evidenceDigest)) + assertThatThrownBy(() -> + new FreshTenantCreatorEvidence( + schemaVersion, + creation, + accountId, + authorizationOperationId, + authorizationDigest, + evidenceDigest)) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameTenantCreationDigestTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameTenantCreationDigestTest.java index 6a4b486f03..720d8b57ae 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameTenantCreationDigestTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameTenantCreationDigestTest.java @@ -8,10 +8,9 @@ class GameTenantCreationDigestTest { @Test void acceptsOwnerLimitsAndPreservesAbsentOrEmptyDescription() { - assertThatCode( - () -> - GameTenantCreationDigest.validateCandidateInputs( - "😀".repeat(36), "😀".repeat(100), "😀".repeat(255))) + assertThatCode(() -> + GameTenantCreationDigest.validateCandidateInputs( + "😀".repeat(36), "😀".repeat(100), "😀".repeat(255))) .doesNotThrowAnyException(); assertThatCode(() -> GameTenantCreationDigest.validateCandidateInputs("source", "", null)) .doesNotThrowAnyException(); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameTenantCreationOriginalOutcomeEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameTenantCreationOriginalOutcomeEvidenceTest.java index 1baeecd3c9..1c6a9970a8 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameTenantCreationOriginalOutcomeEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameTenantCreationOriginalOutcomeEvidenceTest.java @@ -54,27 +54,33 @@ void canonicalBytesRoundTripBothClosedOutcomesAndBindCompleteReceipt() { @Test void rejectsOpenShapesAndReceiptSubstitution() { - assertThatThrownBy( - () -> - new GameTenantCreationOriginalOutcomeEvidence( - 1, binding(), Outcome.CREATED, Optional.empty())) + assertThatThrownBy(() -> + new GameTenantCreationOriginalOutcomeEvidence( + 1, binding(), Outcome.CREATED, Optional.empty())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("requires its exact V30 receipt"); - assertThatThrownBy( - () -> - new GameTenantCreationOriginalOutcomeEvidence( - 1, binding(), Outcome.NOT_CREATED, Optional.of(receipt()))) + assertThatThrownBy(() -> + new GameTenantCreationOriginalOutcomeEvidence( + 1, binding(), Outcome.NOT_CREATED, Optional.of(receipt()))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("cannot contain a creation receipt"); - assertThatThrownBy( - () -> - new GameTenantCreationOriginalOutcomeEvidence( - 1, - binding(), - Outcome.CREATED, - Optional.of( - new FreshTenantCreationEvidence( - 1, + assertThatThrownBy(() -> + new GameTenantCreationOriginalOutcomeEvidence( + 1, + binding(), + Outcome.CREATED, + Optional.of( + new FreshTenantCreationEvidence( + 1, + NAMESPACE, + REQUEST_ID, + CREATION_OPERATION_ID, + "sha256:" + "c".repeat(64), + TENANT_ID, + 91L, + "fresh-tenant-01", + "NEW_GAME_ROW", + GameTenantCreationDigest.evidenceDigest( NAMESPACE, REQUEST_ID, CREATION_OPERATION_ID, @@ -82,22 +88,12 @@ void rejectsOpenShapesAndReceiptSubstitution() { TENANT_ID, 91L, "fresh-tenant-01", - "NEW_GAME_ROW", - GameTenantCreationDigest.evidenceDigest( - NAMESPACE, - REQUEST_ID, - CREATION_OPERATION_ID, - "sha256:" + "c".repeat(64), - TENANT_ID, - 91L, - "fresh-tenant-01", - "NEW_GAME_ROW"))))) + "NEW_GAME_ROW"))))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("does not match the original request binding"); - assertThatThrownBy( - () -> - new GameTenantCreationOriginalOutcomeEvidence( - 2, binding(), Outcome.NOT_CREATED, Optional.empty())) + assertThatThrownBy(() -> + new GameTenantCreationOriginalOutcomeEvidence( + 2, binding(), Outcome.NOT_CREATED, Optional.empty())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("schema"); } @@ -105,10 +101,9 @@ void rejectsOpenShapesAndReceiptSubstitution() { @Test void storedDecoderRejectsTruncationTrailingBytesUnknownSchemaAndOversize() { byte[] canonical = notCreated().canonicalBytes(); - assertThatThrownBy( - () -> - GameTenantCreationOriginalOutcomeEvidence.fromStored( - java.util.Arrays.copyOf(canonical, canonical.length - 1))) + assertThatThrownBy(() -> + GameTenantCreationOriginalOutcomeEvidence.fromStored( + java.util.Arrays.copyOf(canonical, canonical.length - 1))) .isInstanceOf(IllegalArgumentException.class); byte[] trailing = java.util.Arrays.copyOf(canonical, canonical.length + 1); @@ -145,35 +140,32 @@ void storedDecoderRejectsTruncationTrailingBytesUnknownSchemaAndOversize() { @Test void bindingRequiresCanonicalNamespaceNonnilUuidsAndLowercaseDigests() { - assertThatThrownBy( - () -> - new Binding( - "Fresh-Test", - REQUEST_ID, - ACCOUNT_OPERATION_ID, - ACCOUNT_ID, - CREATION_DIGEST, - ACCOUNT_DIGEST)) + assertThatThrownBy(() -> + new Binding( + "Fresh-Test", + REQUEST_ID, + ACCOUNT_OPERATION_ID, + ACCOUNT_ID, + CREATION_DIGEST, + ACCOUNT_DIGEST)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new Binding( - NAMESPACE, - new UUID(0L, 0L), - ACCOUNT_OPERATION_ID, - ACCOUNT_ID, - CREATION_DIGEST, - ACCOUNT_DIGEST)) + assertThatThrownBy(() -> + new Binding( + NAMESPACE, + new UUID(0L, 0L), + ACCOUNT_OPERATION_ID, + ACCOUNT_ID, + CREATION_DIGEST, + ACCOUNT_DIGEST)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new Binding( - NAMESPACE, - REQUEST_ID, - ACCOUNT_OPERATION_ID, - ACCOUNT_ID, - "SHA256:" + "a".repeat(64), - ACCOUNT_DIGEST)) + assertThatThrownBy(() -> + new Binding( + NAMESPACE, + REQUEST_ID, + ACCOUNT_OPERATION_ID, + ACCOUNT_ID, + "SHA256:" + "a".repeat(64), + ACCOUNT_DIGEST)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameTenantCreationOriginalOutcomeGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameTenantCreationOriginalOutcomeGrpcCodecTest.java index b39709c1d5..5a9806ec15 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameTenantCreationOriginalOutcomeGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/GameTenantCreationOriginalOutcomeGrpcCodecTest.java @@ -62,9 +62,8 @@ void requestDecoderRejectsOpenMalformedAndCrossNamespaceBindings() { valid.toBuilder().setAccountAuthorizationDigest("sha256:" + "A".repeat(64)).build(), valid.toBuilder().setUnknownFields(unknownField()).build() }) { - assertThatThrownBy( - () -> - GameTenantCreationOriginalOutcomeGrpcCodec.fromReadRequest(NAMESPACE, malformed)) + assertThatThrownBy(() -> + GameTenantCreationOriginalOutcomeGrpcCodec.fromReadRequest(NAMESPACE, malformed)) .isInstanceOf(IllegalArgumentException.class); } assertThatThrownBy( @@ -140,10 +139,8 @@ void responseDecoderRejectsEchoBindingDigestEnumAndNestedReceiptSubstitution() { .setCreatedReceipt(createdResponse.getCreatedReceipt()) .build() }) { - assertThatThrownBy( - () -> - GameTenantCreationOriginalOutcomeGrpcCodec.fromReadResponse( - READ_REQUEST, malformed)) + assertThatThrownBy(() -> + GameTenantCreationOriginalOutcomeGrpcCodec.fromReadResponse(READ_REQUEST, malformed)) .isInstanceOf(IllegalArgumentException.class); } @@ -159,10 +156,9 @@ void responseDecoderRejectsEchoBindingDigestEnumAndNestedReceiptSubstitution() { ACCOUNT_DIGEST), Outcome.NOT_CREATED, Optional.empty()); - assertThatThrownBy( - () -> - GameTenantCreationOriginalOutcomeGrpcCodec.toReadResponse( - READ_REQUEST, substitutedEvidence)) + assertThatThrownBy(() -> + GameTenantCreationOriginalOutcomeGrpcCodec.toReadResponse( + READ_REQUEST, substitutedEvidence)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact binding"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java index 67a888ac51..caa3edb116 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/RuntimeTenantIdentityEvidenceTest.java @@ -125,16 +125,15 @@ private static void assertInvalid( long sourceGameRowId, String sourceGameTenantKey, String provenanceKind) { - assertThatThrownBy( - () -> - new RuntimeTenantIdentityEvidence( - schemaVersion, - targetNamespace, - requestId, - canonicalTenantId, - sourceGameRowId, - sourceGameTenantKey, - provenanceKind)) + assertThatThrownBy(() -> + new RuntimeTenantIdentityEvidence( + schemaVersion, + targetNamespace, + requestId, + canonicalTenantId, + sourceGameRowId, + sourceGameTenantKey, + provenanceKind)) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClientTest.java index c3504af025..e9f10c3982 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeClientTest.java @@ -97,17 +97,16 @@ void requiresExplicitLifecycleAndExactConfiguredNamespace(@TempDir Path dir) thr assertThatThrownBy(() -> client.intake(INTAKE_REQUEST)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not initialized and available"); - assertThatThrownBy( - () -> - client.intake( - new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( - 1, - "other", - INTAKE_REQUEST.intakeRequestId(), - INTAKE_REQUEST.canonicalTenantId(), - INTAKE_REQUEST.worldSlug(), - INTAKE_REQUEST.sourceOperationId(), - INTAKE_REQUEST.expectedSourceEvidenceDigest()))) + assertThatThrownBy(() -> + client.intake( + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + "other", + INTAKE_REQUEST.intakeRequestId(), + INTAKE_REQUEST.canonicalTenantId(), + INTAKE_REQUEST.worldSlug(), + INTAKE_REQUEST.sourceOperationId(), + INTAKE_REQUEST.expectedSourceEvidenceDigest()))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("configured workload namespace"); assertThatThrownBy(() -> client.read(READ_REQUEST)) @@ -116,15 +115,14 @@ void requiresExplicitLifecycleAndExactConfiguredNamespace(@TempDir Path dir) thr assertThatThrownBy(() -> client.readById(BY_ID_READ_REQUEST)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not initialized and available"); - assertThatThrownBy( - () -> - client.readById( - new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( - 1, - "other", - BY_ID_READ_REQUEST.readRequestId(), - BY_ID_READ_REQUEST.intakeRequestId(), - BY_ID_READ_REQUEST.canonicalTenantId()))) + assertThatThrownBy(() -> + client.readById( + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, + "other", + BY_ID_READ_REQUEST.readRequestId(), + BY_ID_READ_REQUEST.intakeRequestId(), + BY_ID_READ_REQUEST.canonicalTenantId()))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("configured workload namespace"); verifyNoInteractions(channelFactory); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java index 80fb74bda4..a0d3aa7c5a 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/tenant/WorldAuthoredSourceIntakeGrpcCodecTest.java @@ -163,11 +163,10 @@ void rejectsChangedEchoesMalformedDigestsAndUnknownResponseFields() { ReadRequest readRequest = new ReadRequest(BINDING, READ_REQUEST_ID); ReadAuthoredWorldSourceIntakeResponse readResponse = WorldAuthoredSourceIntakeGrpcCodec.toReadResponse(readRequest, committedReceipt(BINDING)); - assertThatThrownBy( - () -> - WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse( - readRequest, - readResponse.toBuilder().setRequestId(INTAKE_REQUEST_ID.toString()).build())) + assertThatThrownBy(() -> + WorldAuthoredSourceIntakeGrpcCodec.fromReadResponse( + readRequest, + readResponse.toBuilder().setRequestId(INTAKE_REQUEST_ID.toString()).build())) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/AccountStartSessionActivationProtectionEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/AccountStartSessionActivationProtectionEvidenceTest.java index c32412cd5c..c0a2287dd4 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/AccountStartSessionActivationProtectionEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/AccountStartSessionActivationProtectionEvidenceTest.java @@ -152,10 +152,9 @@ void acquisitionCodecRejectsAChangedActivationOrOwnerAttempt() throws Exception first.gameSessionOwnerFence(), first.worldActivationRequest()); for (var changed : List.of(differentActivation, differentAttempt)) { - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionAcquisitionGrpcCodec.toResponse( - changed, namespace, firstEvidence)) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionAcquisitionGrpcCodec.toResponse( + changed, namespace, firstEvidence)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact original activation acquisition binding"); } @@ -384,96 +383,90 @@ void rejectsSubstitutedProjectionLeaseOwnerStateCaptureAndCanonicalBytes() throw CurrentGameInstanceStatus.STARTING); byte[] substitutedProjection = projection.clone(); substitutedProjection[substitutedProjection.length - 2] ^= 1; - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionRequest.create( - ACCOUNT_PARTICIPATION, - Long.MAX_VALUE, - valid.launchAssociation(), - currentAttempt( - valid, - substitutedProjection, - ORIGINAL_LEASE_EXPIRY, - GAME_SESSION_MUTATION, - GAME_SESSION_ATTEMPT, - Long.MAX_VALUE), - valid.worldActivationRequest())) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionRequest.create( + ACCOUNT_PARTICIPATION, + Long.MAX_VALUE, + valid.launchAssociation(), + currentAttempt( + valid, + substitutedProjection, + ORIGINAL_LEASE_EXPIRY, + GAME_SESSION_MUTATION, + GAME_SESSION_ATTEMPT, + Long.MAX_VALUE), + valid.worldActivationRequest())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("projection differs"); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionRequest.create( - ACCOUNT_PARTICIPATION, - Long.MAX_VALUE, - valid.launchAssociation(), - currentAttempt( - valid, - projection, - ORIGINAL_LEASE_EXPIRY.plusNanos(1), - GAME_SESSION_MUTATION, - GAME_SESSION_ATTEMPT, - Long.MAX_VALUE), - valid.worldActivationRequest())) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionRequest.create( + ACCOUNT_PARTICIPATION, + Long.MAX_VALUE, + valid.launchAssociation(), + currentAttempt( + valid, + projection, + ORIGINAL_LEASE_EXPIRY.plusNanos(1), + GAME_SESSION_MUTATION, + GAME_SESSION_ATTEMPT, + Long.MAX_VALUE), + valid.worldActivationRequest())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("microsecond"); - assertThatThrownBy( - () -> - request( - fixture, - tuple, - GS_READ_ID, - WORLD_READ_ID, - ACTIVATION_ID, - 7L, - CurrentGameInstanceStatus.RUNNING)) + assertThatThrownBy(() -> + request( + fixture, + tuple, + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 7L, + CurrentGameInstanceStatus.RUNNING)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining( "Original Account operation differs from its current owner or launch target"); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionRequest.create( - new UUID(0L, 0L), - Long.MAX_VALUE, - valid.launchAssociation(), - valid.originalCurrentAttempt(), - valid.worldActivationRequest())) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionRequest.create( + new UUID(0L, 0L), + Long.MAX_VALUE, + valid.launchAssociation(), + valid.originalCurrentAttempt(), + valid.worldActivationRequest())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("non-nil UUID"); - assertThatThrownBy( - () -> - new CanonicalGameInstanceLaunchAssociationReadEvidence.Result( - valid.launchAssociation().request(), - valid.launchAssociation().playableStateNamespaceId(), - valid.launchAssociation().playableStateScope(), - valid.launchAssociation().publicProduction(), - valid.launchAssociation().currentGameInstanceStatus(), - valid.launchAssociation().currentRowVersion(), - uuid("e5e5e5e5-e5e5-45e5-85e5-e5e5e5e5e5e5"), - valid.launchAssociation().ownerFence(), - valid.launchAssociation().canonicalRealmId(), - valid.launchAssociation().catalogRevision(), - valid.launchAssociation().launchBindingEvidence())) + assertThatThrownBy(() -> + new CanonicalGameInstanceLaunchAssociationReadEvidence.Result( + valid.launchAssociation().request(), + valid.launchAssociation().playableStateNamespaceId(), + valid.launchAssociation().playableStateScope(), + valid.launchAssociation().publicProduction(), + valid.launchAssociation().currentGameInstanceStatus(), + valid.launchAssociation().currentRowVersion(), + uuid("e5e5e5e5-e5e5-45e5-85e5-e5e5e5e5e5e5"), + valid.launchAssociation().ownerFence(), + valid.launchAssociation().canonicalRealmId(), + valid.launchAssociation().catalogRevision(), + valid.launchAssociation().launchBindingEvidence())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining( "Original Account operation differs from its current owner or launch target"); - assertThatThrownBy( - () -> - new CanonicalGameInstanceLaunchAssociationReadEvidence.Result( - valid.launchAssociation().request(), - valid.launchAssociation().playableStateNamespaceId(), - valid.launchAssociation().playableStateScope(), - valid.launchAssociation().publicProduction(), - valid.launchAssociation().currentGameInstanceStatus(), - valid.launchAssociation().currentRowVersion(), - valid.launchAssociation().ownerAttemptId(), - valid.launchAssociation().ownerFence() - 1L, - valid.launchAssociation().canonicalRealmId(), - valid.launchAssociation().catalogRevision(), - valid.launchAssociation().launchBindingEvidence())) + assertThatThrownBy(() -> + new CanonicalGameInstanceLaunchAssociationReadEvidence.Result( + valid.launchAssociation().request(), + valid.launchAssociation().playableStateNamespaceId(), + valid.launchAssociation().playableStateScope(), + valid.launchAssociation().publicProduction(), + valid.launchAssociation().currentGameInstanceStatus(), + valid.launchAssociation().currentRowVersion(), + valid.launchAssociation().ownerAttemptId(), + valid.launchAssociation().ownerFence() - 1L, + valid.launchAssociation().canonicalRealmId(), + valid.launchAssociation().catalogRevision(), + valid.launchAssociation().launchBindingEvidence())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining( "Original Account operation differs from its current owner or launch target"); @@ -496,22 +489,19 @@ void rejectsSubstitutedProjectionLeaseOwnerStateCaptureAndCanonicalBytes() throw List.of(source(fixture.selector.canonicalTenantId(), "source"))); Map extraEvidenceField = readObject(malformedEvidence.canonicalBytes()); extraEvidenceField.put("unsupported", "field"); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionEvidence.decode( - canonical(extraEvidenceField))) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionEvidence.decode(canonical(extraEvidenceField))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - request( - fixture, - originalTuple(fixture, "another-world-runtime", "namespace substitution"), - GS_READ_ID, - WORLD_READ_ID, - ACTIVATION_ID, - 7L, - CurrentGameInstanceStatus.STARTING)) + assertThatThrownBy(() -> + request( + fixture, + originalTuple(fixture, "another-world-runtime", "namespace substitution"), + GS_READ_ID, + WORLD_READ_ID, + ACTIVATION_ID, + 7L, + CurrentGameInstanceStatus.STARTING)) .isInstanceOf(IllegalArgumentException.class); } @@ -552,31 +542,29 @@ void rejectsChangedCaptureAndAcquisitionAfterOriginalLease() throws Exception { assertThatThrownBy(() -> evidence(request, capture, List.of(source), ORIGINAL_LEASE_EXPIRY)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("before the original lease expires"); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionEvidence.create( - request, - ACCOUNT_PROTECTION, - 1L, - ACQUIRED_AT, - capture, - "0".repeat(64), - List.of(source))) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionEvidence.create( + request, + ACCOUNT_PROTECTION, + 1L, + ACQUIRED_AT, + capture, + "0".repeat(64), + List.of(source))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("digest differs"); Map malformed = readObject(capture); malformed.put("controlPlaneRequestId", "another-original-request"); byte[] wrongCapture = canonical(malformed); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionEvidence.create( - request, - ACCOUNT_PROTECTION, - 1L, - ACQUIRED_AT, - wrongCapture, - sha256(wrongCapture), - List.of(source))) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionEvidence.create( + request, + ACCOUNT_PROTECTION, + 1L, + ACQUIRED_AT, + wrongCapture, + sha256(wrongCapture), + List.of(source))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("another original request"); } @@ -660,14 +648,13 @@ void retainedLaunchOperationEchoIsExactAndCannotOmitOwnerBinding() throws Except old.canonicalRealmId(), old.catalogRevision(), old.launchBindingEvidence()); - assertThatThrownBy( - () -> - AccountStartSessionActivationProtectionRequest.create( - ACCOUNT_PARTICIPATION, - Long.MAX_VALUE, - omittedOperation, - first.originalCurrentAttempt(), - first.worldActivationRequest())) + assertThatThrownBy(() -> + AccountStartSessionActivationProtectionRequest.create( + ACCOUNT_PARTICIPATION, + Long.MAX_VALUE, + omittedOperation, + first.originalCurrentAttempt(), + first.worldActivationRequest())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("complete original operation"); var wire = @@ -879,19 +866,18 @@ private static Fixture fixture(String launchDescriptorId) throws Exception { null); List participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - owner, - Long.toString(descriptor.versionId()), - false, - null, - selectedRequest.appliedCommitId(), - selectedRequest.contentDigest(), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - "GAME_LOGIC".equals(owner), - "GAME_LOGIC".equals(owner) ? "sha256:" + "2".repeat(64) : null)) + .map(owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selectedRequest.appliedCommitId(), + selectedRequest.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "2".repeat(64) : null)) .toList(); AuthoredWorldReleaseAttestationEvidence release = AuthoredWorldReleaseAttestationEvidence.create( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidenceTest.java index c67be1058d..51253a5861 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterOwnerReadEvidenceTest.java @@ -89,13 +89,12 @@ void rejectsExactPolicySetSealedForAnotherWorkloadNamespace() throws Exception { assertThat(policyOperation.world().request().targetNamespace()) .isNotEqualTo(wrongNamespaceRequest.targetNamespace()); - assertThatThrownBy( - () -> - new CanonicalGameplayRosterOwnerReadEvidence( - wrongNamespaceRequest, - evidence.admissionPointerSnapshotDigest(), - wrongNamespaceProof, - evidence.publishedPolicySetEvidence())) + assertThatThrownBy(() -> + new CanonicalGameplayRosterOwnerReadEvidence( + wrongNamespaceRequest, + evidence.admissionPointerSnapshotDigest(), + wrongNamespaceProof, + evidence.publishedPolicySetEvidence())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("target namespace"); } @@ -104,10 +103,9 @@ void rejectsExactPolicySetSealedForAnotherWorkloadNamespace() throws Exception { void rejectsNoncommittedStaleOrChangedRouteAndPolicyEvidence() throws Exception { var good = fixture(); var pending = pendingProof(good.gameSessionOwnerProof().holdIdentity()); - assertThatThrownBy( - () -> - new CanonicalGameplayRosterOwnerReadEvidence( - good.request(), "1".repeat(64), pending, good.publishedPolicySetEvidence())) + assertThatThrownBy(() -> + new CanonicalGameplayRosterOwnerReadEvidence( + good.request(), "1".repeat(64), pending, good.publishedPolicySetEvidence())) .isInstanceOf(IllegalArgumentException.class); var staleRequest = @@ -126,13 +124,12 @@ void rejectsNoncommittedStaleOrChangedRouteAndPolicyEvidence() throws Exception 71L, 74L, 82L); - assertThatThrownBy( - () -> - new CanonicalGameplayRosterOwnerReadEvidence( - staleRequest, - good.admissionPointerSnapshotDigest(), - good.gameSessionOwnerProof(), - good.publishedPolicySetEvidence())) + assertThatThrownBy(() -> + new CanonicalGameplayRosterOwnerReadEvidence( + staleRequest, + good.admissionPointerSnapshotDigest(), + good.gameSessionOwnerProof(), + good.publishedPolicySetEvidence())) .isInstanceOf(IllegalArgumentException.class); var wrongRealm = @@ -151,22 +148,20 @@ void rejectsNoncommittedStaleOrChangedRouteAndPolicyEvidence() throws Exception 71L, 73L, 82L); - assertThatThrownBy( - () -> - new CanonicalGameplayRosterOwnerReadEvidence( - wrongRealm, - good.admissionPointerSnapshotDigest(), - good.gameSessionOwnerProof(), - good.publishedPolicySetEvidence())) + assertThatThrownBy(() -> + new CanonicalGameplayRosterOwnerReadEvidence( + wrongRealm, + good.admissionPointerSnapshotDigest(), + good.gameSessionOwnerProof(), + good.publishedPolicySetEvidence())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new CanonicalGameplayRosterOwnerReadEvidence( - good.request(), - "A".repeat(64), - good.gameSessionOwnerProof(), - good.publishedPolicySetEvidence())) + assertThatThrownBy(() -> + new CanonicalGameplayRosterOwnerReadEvidence( + good.request(), + "A".repeat(64), + good.gameSessionOwnerProof(), + good.publishedPolicySetEvidence())) .isInstanceOf(IllegalArgumentException.class); } @@ -195,75 +190,63 @@ void grpcCodecRoundTripsCompleteProofAndRejectsUnknownPartialOrChangedEcho() thr .build(); assertThatThrownBy(() -> CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest(unknownRequest)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest( - wireRequest.toBuilder().setCanonicalAccountUuid("not-a-uuid").build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest( + wireRequest.toBuilder().setCanonicalAccountUuid("not-a-uuid").build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest( - wireRequest.toBuilder() - .setExpectedPointerVersion(Long.MAX_VALUE * -1L) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest( + wireRequest.toBuilder().setExpectedPointerVersion(Long.MAX_VALUE * -1L).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest( - wireRequest.toBuilder().setWorldSlug("x".repeat(3000)).build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromRequest( + wireRequest.toBuilder().setWorldSlug("x".repeat(3000)).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( - request, GetCanonicalGameplayRosterOwnerReadResponse.getDefaultInstance())) + assertThatThrownBy(() -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, GetCanonicalGameplayRosterOwnerReadResponse.getDefaultInstance())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setRequest( - wireRequest.toBuilder() - .setCanonicalAccountUuid( - uuid("99999999-9999-4999-8999-999999999999").toString()) - .build()) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + wireRequest.toBuilder() + .setCanonicalAccountUuid( + uuid("99999999-9999-4999-8999-999999999999").toString()) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField( - 101, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) - .build()) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(101, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( - request, response.toBuilder().clearPublishedPolicySetEvidence().build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, response.toBuilder().clearPublishedPolicySetEvidence().build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( - request, - response.toBuilder().setAdmissionPointerSnapshotDigest("A".repeat(64)).build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, + response.toBuilder().setAdmissionPointerSnapshotDigest("A".repeat(64)).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setPublishedPolicySetEvidence( - ByteString.copyFrom( - new byte - [CanonicalGameplayRosterOwnerReadEvidence.MAX_POLICY_SET_BYTES - + 1])) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setPublishedPolicySetEvidence( + ByteString.copyFrom( + new byte + [CanonicalGameplayRosterOwnerReadEvidence.MAX_POLICY_SET_BYTES + + 1])) + .build())) .isInstanceOf(IllegalArgumentException.class); var pending = pendingProof(evidence.gameSessionOwnerProof().holdIdentity()); @@ -277,10 +260,8 @@ void grpcCodecRoundTripsCompleteProofAndRejectsUnknownPartialOrChangedEcho() thr ByteString.copyFrom(evidence.publishedPolicySetEvidence().canonicalBytes())) .setAdmissionPointerSnapshotDigest(evidence.admissionPointerSnapshotDigest()) .build(); - assertThatThrownBy( - () -> - CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse( - request, nonCommittedResponse)) + assertThatThrownBy(() -> + CanonicalGameplayRosterOwnerReadGrpcCodec.fromResponse(request, nonCommittedResponse)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining( "Game Session proof is not the exact current committed roster target"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRecoveryEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRecoveryEvidenceTest.java index 58eebb2e5b..bf494bc262 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRecoveryEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterRecoveryEvidenceTest.java @@ -41,10 +41,9 @@ void createdRecoveryReturnsOnlyItsDistinctRosterAndKeepsExactOwnerFenceAndMarker .isEqualTo(owner); assertThatThrownBy(() -> CanonicalGameplayRosterReferenceEvidence.requireDereference(owner)) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterRecoveryEvidence.response( - request, UUID.randomUUID(), 1L, UUID.randomUUID(), null)) + assertThatThrownBy(() -> + CanonicalGameplayRosterRecoveryEvidence.response( + request, UUID.randomUUID(), 1L, UUID.randomUUID(), null)) .isInstanceOf(IllegalArgumentException.class); var noCapture = CanonicalGameplayRosterRecoveryEvidence.playerCreatedResponse( @@ -96,34 +95,29 @@ void recoveryBudgetsStayEightAnd128KiBWithClosedPolicySpecificReceiptFields() { int maximumRosterEnvelope = 66 * 1024 + 4096 + 256; assertThat(maximumRosterEnvelope) .isLessThanOrEqualTo(CanonicalGameplayRosterRecoveryEvidence.MAX_RESPONSE_BYTES); - assertThatThrownBy( - () -> - CanonicalGameplayRosterRecoveryEvidence.requireResponse( - request, - response.toBuilder() - .setCanonicalPlayerCreatedRosterReceipt( - CanonicalGameplayRosterReferenceEvidenceTest.logicalBytes( - 66 * 1024 + 1)) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterRecoveryEvidence.requireResponse( + request, + response.toBuilder() + .setCanonicalPlayerCreatedRosterReceipt( + CanonicalGameplayRosterReferenceEvidenceTest.logicalBytes(66 * 1024 + 1)) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterRecoveryEvidence.requireResponse( - request, - response.toBuilder() - .setCanonicalPlayerCreatedRosterReceipt( - CanonicalGameplayRosterReferenceEvidenceTest.logicalBytes( - 128 * 1024 + 1)) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterRecoveryEvidence.requireResponse( + request, + response.toBuilder() + .setCanonicalPlayerCreatedRosterReceipt( + CanonicalGameplayRosterReferenceEvidenceTest.logicalBytes(128 * 1024 + 1)) + .build())) .isInstanceOf(IllegalArgumentException.class); var unknown = UnknownFieldSet.newBuilder() .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) .build(); - assertThatThrownBy( - () -> - CanonicalGameplayRosterRecoveryEvidence.requireResponse( - request, response.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterRecoveryEvidence.requireResponse( + request, response.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class); var oldTarget = CanonicalGameplayRosterReferenceEvidence.target(fixture.original()).toBuilder() @@ -147,18 +141,16 @@ void recoveryBudgetsStayEightAnd128KiBWithClosedPolicySpecificReceiptFields() { oldRequest, UUID.randomUUID(), 1L, UUID.randomUUID(), oldReceipt); assertThat(CanonicalGameplayRosterRecoveryEvidence.requireResponse(oldRequest, oldResponse)) .isEqualTo(oldResponse); - assertThatThrownBy( - () -> - CanonicalGameplayRosterRecoveryEvidence.requireResponse( - oldRequest, - oldResponse.toBuilder() - .setCanonicalPlayerCreatedRosterReceipt(fixture.roster().toByteString()) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterRecoveryEvidence.requireResponse( + oldRequest, + oldResponse.toBuilder() + .setCanonicalPlayerCreatedRosterReceipt(fixture.roster().toByteString()) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterRecoveryEvidence.playerCreatedResponse( - oldRequest, UUID.randomUUID(), 1L, UUID.randomUUID(), null)) + assertThatThrownBy(() -> + CanonicalGameplayRosterRecoveryEvidence.playerCreatedResponse( + oldRequest, UUID.randomUUID(), 1L, UUID.randomUUID(), null)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidenceTest.java index 391e0759ba..d529032a86 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalGameplayRosterReferenceEvidenceTest.java @@ -44,16 +44,13 @@ void bindsReservedAndRecordedEvidenceToTheExactOriginalRequest() { java.util.UUID.fromString("12121212-1212-4212-8212-121212121212"), receipt); assertThat(CanonicalGameplayRosterReferenceEvidence.receipt(recorded)).isEqualTo(receipt); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.requireResponse( - request.toBuilder().setSessionUuid(UUID.randomUUID().toString()).build(), - recorded)) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + request.toBuilder().setSessionUuid(UUID.randomUUID().toString()).build(), recorded)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.requireResponse( - request.toBuilder().setTargetNamespace("foreign").build(), recorded)) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + request.toBuilder().setTargetNamespace("foreign").build(), recorded)) .isInstanceOf(IllegalArgumentException.class); } @@ -63,33 +60,29 @@ void unknownStatesFieldsAndChangedOriginalBindingsCannotBecomeReleaseEvidence() var reserved = CanonicalGameplayRosterReferenceEvidence.response( request, 1L, java.util.UUID.fromString("12121212-1212-4212-8212-121212121212"), null); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.requireResponse( - request, reserved.toBuilder().setStateValue(77).build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + request, reserved.toBuilder().setStateValue(77).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.requireRequest( - request.toBuilder().setOperationUuid(new UUID(0L, 0L).toString()).build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.requireRequest( + request.toBuilder().setOperationUuid(new UUID(0L, 0L).toString()).build())) .isInstanceOf(IllegalArgumentException.class); var unknown = UnknownFieldSet.newBuilder() .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) .build(); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.requireRequest( - request.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.requireRequest( + request.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class); var target = CanonicalGameplayRosterReferenceEvidence.target(request).toBuilder() .setUnknownFields(unknown) .build(); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.requireRequest( - request.toBuilder().setCanonicalTarget(target.toByteString()).build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.requireRequest( + request.toBuilder().setCanonicalTarget(target.toByteString()).build())) .isInstanceOf(IllegalArgumentException.class); } @@ -123,20 +116,16 @@ void positiveRetirementRequiresTheCompleteOriginalBindingAndStrictlyNewerOwnerPo .isEqualTo(retired); assertThatThrownBy(() -> CanonicalGameplayRosterReferenceEvidence.requireDereference(retired)) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.sealRetirement( - retired.toBuilder() - .setSupersedingPointerVersion(target.getPointerVersion()) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.sealRetirement( + retired.toBuilder() + .setSupersedingPointerVersion(target.getPointerVersion()) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.requireResponse( - request.toBuilder() - .setCanonicalAccountUuid(UUID.randomUUID().toString()) - .build(), - retired)) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + request.toBuilder().setCanonicalAccountUuid(UUID.randomUUID().toString()).build(), + retired)) .isInstanceOf(IllegalArgumentException.class); var replayClosed = retired.toBuilder() @@ -174,16 +163,13 @@ void recoveryFenceStopsDereferenceAndRequiresExactIndependentOwnerIdentity() { .isEqualTo(owner); assertThatThrownBy(() -> CanonicalGameplayRosterReferenceEvidence.requireDereference(owner)) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterRecoveryEvidence.requireOwnerRecovery( - recovery.toBuilder().setRecoveryUuid(UUID.randomUUID().toString()).build(), - owner)) + assertThatThrownBy(() -> + CanonicalGameplayRosterRecoveryEvidence.requireOwnerRecovery( + recovery.toBuilder().setRecoveryUuid(UUID.randomUUID().toString()).build(), owner)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.requireDereference( - owner.toBuilder().clearRecoveryUuid().setTerminalOutcome("DENIED").build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.requireDereference( + owner.toBuilder().clearRecoveryUuid().setTerminalOutcome("DENIED").build())) .isInstanceOf(IllegalStateException.class); } @@ -272,25 +258,22 @@ void createdMenuAndSelectedReplayRetainTheDistinctCompleteOriginalCreationReceip assertThatThrownBy( () -> CanonicalGameplayRosterReferenceEvidence.selectedAssignmentReceipt(selected)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.response( - original, 1L, UUID.randomUUID(), null)) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.response( + original, 1L, UUID.randomUUID(), null)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.request( - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - "gameplay", - fixture.roster().getRoster().getTarget())) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.request( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "gameplay", + fixture.roster().getRoster().getTarget())) .isInstanceOf(IllegalArgumentException.class); var foreignOriginal = original.toBuilder().setTargetNamespace("other").build(); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.requireResponse( - foreignOriginal, selected.toBuilder().setRequest(foreignOriginal).build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + foreignOriginal, selected.toBuilder().setRequest(foreignOriginal).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("workload namespace"); for (var changed : @@ -358,10 +341,9 @@ void fiveMebibyteSelectedReceiptRequiresExactCanonicalBytesAndRejectsTamperingAn .setCanonicalSelectedPlayerCreatedCharacterReceipt( canonicalSelectedBytes.concat(ByteString.copyFrom(duplicateRequestField))) .build(); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.requireResponse( - fixture.originalRequest(), noncanonical)) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + fixture.originalRequest(), noncanonical)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Selected PLAYER_CREATED receipt bytes are not canonical"); @@ -376,10 +358,9 @@ void fiveMebibyteSelectedReceiptRequiresExactCanonicalBytesAndRejectsTamperingAn original.toBuilder() .setCanonicalSelectedPlayerCreatedCharacterReceipt(tamperedSelected.toByteString()) .build(); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.requireResponse( - fixture.originalRequest(), tampered)) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + fixture.originalRequest(), tampered)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("binding changed"); @@ -389,10 +370,9 @@ void fiveMebibyteSelectedReceiptRequiresExactCanonicalBytesAndRejectsTamperingAn logicalBytes( CanonicalGameplayRosterReferenceEvidence.MAX_SELECTED_PLAYER_CREATED_BYTES + 1)) .build(); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.requireResponse( - fixture.originalRequest(), oversized)) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + fixture.originalRequest(), oversized)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Original roster selection owner binding is invalid"); } @@ -442,38 +422,34 @@ void createdSourceBytesAndPolicyBranchesAreClosedAndMutuallyExclusive() { var createdMenu = CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( created, 1L, UUID.randomUUID(), fixture.roster()); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.requireResponse( - created, - createdMenu.toBuilder() - .setCanonicalRosterReceipt(fixture.roster().getRoster().toByteString()) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + created, + createdMenu.toBuilder() + .setCanonicalRosterReceipt(fixture.roster().getRoster().toByteString()) + .build())) .isInstanceOf(IllegalArgumentException.class); var preseeded = request(); var reserved = CanonicalGameplayRosterReferenceEvidence.response(preseeded, 1L, UUID.randomUUID(), null); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.requireResponse( - preseeded, - reserved.toBuilder() - .setCanonicalPlayerCreatedRosterReceipt(fixture.roster().toByteString()) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + preseeded, + reserved.toBuilder() + .setCanonicalPlayerCreatedRosterReceipt(fixture.roster().toByteString()) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.requireResponse( - preseeded, - reserved.toBuilder() - .setCanonicalSelectedPlayerCreatedCharacterReceipt( - fixture.selected().toByteString()) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + preseeded, + reserved.toBuilder() + .setCanonicalSelectedPlayerCreatedCharacterReceipt( + fixture.selected().toByteString()) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( - preseeded, 1L, UUID.randomUUID(), null)) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + preseeded, 1L, UUID.randomUUID(), null)) .isInstanceOf(IllegalArgumentException.class); } @@ -535,20 +511,18 @@ void createdPurposeBudgetsRetainTheFullTerminalAndRejectOversizeWithoutHugeBacki var preseeded = request(); var reserved = CanonicalGameplayRosterReferenceEvidence.response(preseeded, 1L, UUID.randomUUID(), null); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.requireResponse( - preseeded, - reserved.toBuilder() - .setCanonicalRosterReceipt(logicalBytes(64 * 1024 + 1)) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.requireResponse( + preseeded, + reserved.toBuilder() + .setCanonicalRosterReceipt(logicalBytes(64 * 1024 + 1)) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.selectedAssignmentReceipt( - reserved.toBuilder() - .setCanonicalSelectedAssignmentReceipt(logicalBytes(8192 + 1)) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.selectedAssignmentReceipt( + reserved.toBuilder() + .setCanonicalSelectedAssignmentReceipt(logicalBytes(8192 + 1)) + .build())) .isInstanceOf(IllegalArgumentException.class); int completeSelectedEnvelope = CodedOutputStream.computeTagSize(18) @@ -580,10 +554,8 @@ void createdPurposeBudgetsRetainTheFullTerminalAndRejectOversizeWithoutHugeBacki CanonicalGameplayRosterReferenceEvidence.MAX_PLAYER_CREATED_RESPONSE_BYTES + 1)) .build())) { - assertThatThrownBy( - () -> - CanonicalGameplayRosterReferenceEvidence.requireResponse( - fixture.original(), changed)) + assertThatThrownBy(() -> + CanonicalGameplayRosterReferenceEvidence.requireResponse(fixture.original(), changed)) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClientMtlsTest.java index e63cbe4d93..c184f54bfc 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationClientMtlsTest.java @@ -149,10 +149,9 @@ void trustedWrongWorkloadOrNamespaceReleasesNoRequestHeadersOrBody() throws Exce client.init(); assertThatThrownBy(() -> client.prepare(request, operationInput, evidence.request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - exception -> - assertThat(Status.fromThrowable(exception).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(exception -> + assertThat(Status.fromThrowable(exception).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(headers).hasValue(0); assertThat(bodies).hasValue(0); stopTransport(); @@ -208,37 +207,28 @@ void rejectsUnsafeTlsAndMismatchedSelectorsBeforeSending(@TempDir Path directory var plaintext = pki.clientProperties(directory); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new CanonicalWorldInstancePreparationClient( - new ServiceEndpointsProperties(), - plaintext, - new GrpcChannelFactory(), - NAMESPACE)) + assertThatThrownBy(() -> + new CanonicalWorldInstancePreparationClient( + new ServiceEndpointsProperties(), plaintext, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mTLS"); var classpath = pki.clientProperties(directory); classpath.setCaCert("classpath:ca.crt"); - assertThatThrownBy( - () -> - new CanonicalWorldInstancePreparationClient( - new ServiceEndpointsProperties(), - classpath, - new GrpcChannelFactory(), - NAMESPACE)) + assertThatThrownBy(() -> + new CanonicalWorldInstancePreparationClient( + new ServiceEndpointsProperties(), classpath, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("file-backed"); var absentCertificate = pki.clientProperties(directory); absentCertificate.setCertChain(directory.resolve("absent-client.crt").toString()); - assertThatThrownBy( - () -> - new CanonicalWorldInstancePreparationClient( - new ServiceEndpointsProperties(), - absentCertificate, - new GrpcChannelFactory(), - NAMESPACE)) + assertThatThrownBy(() -> + new CanonicalWorldInstancePreparationClient( + new ServiceEndpointsProperties(), + absentCertificate, + new GrpcChannelFactory(), + NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("existing readable file"); @@ -448,19 +438,18 @@ private static WorldCanonicalInstanceLifecycleEvidence evidence() throws Excepti null); List participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - owner, - Long.toString(descriptor.versionId()), - false, - null, - selector.request().appliedCommitId(), - selector.request().contentDigest(), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - "GAME_LOGIC".equals(owner), - "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .map(owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) .toList(); AuthoredWorldReleaseAttestationEvidence release = AuthoredWorldReleaseAttestationEvidence.create( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java index 35349db60a..8788a84ff9 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/CanonicalWorldInstancePreparationGrpcCodecTest.java @@ -61,20 +61,18 @@ void rejectsChangedOuterAndInnerTuplesAndCompleteBindingSelectors() throws Excep response.toBuilder() .setRequest(response.getRequest().toBuilder().setWorldSlug("other-world")) .build(); - assertThatThrownBy( - () -> - CanonicalWorldInstancePreparationGrpcCodec.fromResponse( - request, evidence.request(), changedOuter)) + assertThatThrownBy(() -> + CanonicalWorldInstancePreparationGrpcCodec.fromResponse( + request, evidence.request(), changedOuter)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("changed the exact canonical preparation request"); var changedLifecycleRequest = copyLifecycleRequest( evidence.request(), uuid("99999999-9999-4999-8999-999999999999"), null, null); - assertThatThrownBy( - () -> - CanonicalWorldInstancePreparationGrpcCodec.fromResponse( - request, changedLifecycleRequest, response)) + assertThatThrownBy(() -> + CanonicalWorldInstancePreparationGrpcCodec.fromResponse( + request, changedLifecycleRequest, response)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("differs from the World lifecycle request"); @@ -90,9 +88,8 @@ void rejectsChangedOuterAndInnerTuplesAndCompleteBindingSelectors() throws Excep request.expectedDescriptorRequestDigest(), request.expectedDescriptorResultDigest(), request.expectedReleaseAttestationEvidenceDigest()); - assertThatThrownBy( - () -> - CanonicalWorldInstancePreparationGrpcCodec.toResponse(changedDescriptor, evidence)) + assertThatThrownBy(() -> + CanonicalWorldInstancePreparationGrpcCodec.toResponse(changedDescriptor, evidence)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("complete launch descriptor"); @@ -124,10 +121,9 @@ void rejectsChangedOuterAndInnerTuplesAndCompleteBindingSelectors() throws Excep WorldCanonicalInstanceLifecycleGrpcCodec.toResponse( changedInnerRequest, changedInnerEvidence)) .build(); - assertThatThrownBy( - () -> - CanonicalWorldInstancePreparationGrpcCodec.fromResponse( - request, evidence.request(), responseWithChangedInner)) + assertThatThrownBy(() -> + CanonicalWorldInstancePreparationGrpcCodec.fromResponse( + request, evidence.request(), responseWithChangedInner)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("changed exact read request"); } @@ -138,21 +134,19 @@ void rejectsMissingLifecycleOwnerErrorsAndUnknownNestedFields() throws Exception Request request = request(evidence); var response = CanonicalWorldInstancePreparationGrpcCodec.toResponse(request, evidence); - assertThatThrownBy( - () -> - CanonicalWorldInstancePreparationGrpcCodec.fromResponse( - request, evidence.request(), response.toBuilder().clearLifecycle().build())) + assertThatThrownBy(() -> + CanonicalWorldInstancePreparationGrpcCodec.fromResponse( + request, evidence.request(), response.toBuilder().clearLifecycle().build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("lifecycle response is required"); - assertThatThrownBy( - () -> - CanonicalWorldInstancePreparationGrpcCodec.fromResponse( - request, - evidence.request(), - PrepareCanonicalWorldInstanceResponse.newBuilder() - .setRequest(CanonicalWorldInstancePreparationGrpcCodec.toRequest(request)) - .setError(ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION")) - .build())) + assertThatThrownBy(() -> + CanonicalWorldInstancePreparationGrpcCodec.fromResponse( + request, + evidence.request(), + PrepareCanonicalWorldInstanceResponse.newBuilder() + .setRequest(CanonicalWorldInstancePreparationGrpcCodec.toRequest(request)) + .setError(ErrorDetail.newBuilder().setCode("FAILED_PRECONDITION")) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("rejected canonical instance preparation"); @@ -164,10 +158,9 @@ void rejectsMissingLifecycleOwnerErrorsAndUnknownNestedFields() throws Exception response.toBuilder() .setRequest(response.getRequest().toBuilder().setUnknownFields(unknown)) .build(); - assertThatThrownBy( - () -> - CanonicalWorldInstancePreparationGrpcCodec.fromResponse( - request, evidence.request(), unknownOuterRequest)) + assertThatThrownBy(() -> + CanonicalWorldInstancePreparationGrpcCodec.fromResponse( + request, evidence.request(), unknownOuterRequest)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); @@ -175,10 +168,9 @@ void rejectsMissingLifecycleOwnerErrorsAndUnknownNestedFields() throws Exception response.toBuilder() .setLifecycle(response.getLifecycle().toBuilder().setUnknownFields(unknown)) .build(); - assertThatThrownBy( - () -> - CanonicalWorldInstancePreparationGrpcCodec.fromResponse( - request, evidence.request(), unknownLifecycle)) + assertThatThrownBy(() -> + CanonicalWorldInstancePreparationGrpcCodec.fromResponse( + request, evidence.request(), unknownLifecycle)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); } @@ -186,24 +178,21 @@ void rejectsMissingLifecycleOwnerErrorsAndUnknownNestedFields() throws Exception @Test void requestDecoderUsesExistingCanonicalSelectorValidation() throws Exception { var valid = CanonicalWorldInstancePreparationGrpcCodec.toRequest(request(evidence())); - assertThatThrownBy( - () -> - CanonicalWorldInstancePreparationGrpcCodec.fromRequest( - valid.toBuilder() - .setReadRequestId("32345678-1234-4234-8234-123456789abc ") - .build())) + assertThatThrownBy(() -> + CanonicalWorldInstancePreparationGrpcCodec.fromRequest( + valid.toBuilder() + .setReadRequestId("32345678-1234-4234-8234-123456789abc ") + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical non-nil UUID"); - assertThatThrownBy( - () -> - CanonicalWorldInstancePreparationGrpcCodec.fromRequest( - valid.toBuilder().setTargetNamespace("Bad_Namespace").build())) + assertThatThrownBy(() -> + CanonicalWorldInstancePreparationGrpcCodec.fromRequest( + valid.toBuilder().setTargetNamespace("Bad_Namespace").build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical DNS label"); - assertThatThrownBy( - () -> - CanonicalWorldInstancePreparationGrpcCodec.fromRequest( - valid.toBuilder().setExpectedDescriptorResultDigest("not-a-digest").build())) + assertThatThrownBy(() -> + CanonicalWorldInstancePreparationGrpcCodec.fromRequest( + valid.toBuilder().setExpectedDescriptorResultDigest("not-a-digest").build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("expectedDescriptorResultDigest"); } @@ -214,10 +203,9 @@ void originalOperationIsRequiredAndEchoedExactlyForOwnerPreparation() throws Exc Request request = request(lifecycle); var operation = originalOperation(request); var wire = CanonicalWorldInstancePreparationGrpcCodec.toRequest(request, operation); - assertThatThrownBy( - () -> - CanonicalWorldInstancePreparationGrpcCodec.fromOriginalOperationRequest( - CanonicalWorldInstancePreparationGrpcCodec.toRequest(request))) + assertThatThrownBy(() -> + CanonicalWorldInstancePreparationGrpcCodec.fromOriginalOperationRequest( + CanonicalWorldInstancePreparationGrpcCodec.toRequest(request))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("original StartSession owner operation"); @@ -232,10 +220,9 @@ void originalOperationIsRequiredAndEchoedExactlyForOwnerPreparation() throws Exc .toBuilder() .setRequest(changedOperation) .build(); - assertThatThrownBy( - () -> - CanonicalWorldInstancePreparationGrpcCodec.fromResponse( - request, operation, lifecycle.request(), changedResponse)) + assertThatThrownBy(() -> + CanonicalWorldInstancePreparationGrpcCodec.fromResponse( + request, operation, lifecycle.request(), changedResponse)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("owner operation"); } @@ -245,29 +232,26 @@ void originalInputRejectsOpaqueTupleNilOwnersAndChangedSelectorScope() throws Ex var request = request(evidence()); var operation = originalOperation(request); var nil = new UUID(0, 0); - assertThatThrownBy( - () -> - new CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput( - new byte[] {1, 2, 3}, - operation.gameSessionOwnerMutationId(), - operation.gameSessionOwnerAttemptId(), - 1)) + assertThatThrownBy(() -> + new CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput( + new byte[] {1, 2, 3}, + operation.gameSessionOwnerMutationId(), + operation.gameSessionOwnerAttemptId(), + 1)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput( - operation.originalPostAuthorizationTuple(), - nil, - operation.gameSessionOwnerAttemptId(), - 1)) + assertThatThrownBy(() -> + new CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput( + operation.originalPostAuthorizationTuple(), + nil, + operation.gameSessionOwnerAttemptId(), + 1)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput( - operation.originalPostAuthorizationTuple(), - operation.gameSessionOwnerMutationId(), - nil, - 1)) + assertThatThrownBy(() -> + new CanonicalWorldInstancePreparationGrpcCodec.OriginalOperationInput( + operation.originalPostAuthorizationTuple(), + operation.gameSessionOwnerMutationId(), + nil, + 1)) .isInstanceOf(IllegalArgumentException.class); var otherTenant = new Request( @@ -446,19 +430,18 @@ private static WorldCanonicalInstanceLifecycleEvidence evidence() throws Excepti null); List participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - owner, - Long.toString(descriptor.versionId()), - false, - null, - selector.request().appliedCommitId(), - selector.request().contentDigest(), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - "GAME_LOGIC".equals(owner), - "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .map(owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) .toList(); AuthoredWorldReleaseAttestationEvidence release = AuthoredWorldReleaseAttestationEvidence.create( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java index 413c70a3c6..7c58961d24 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameDesignPublicationTerminalEvidenceCodecTest.java @@ -54,20 +54,19 @@ void selectedFullV4TerminalRoundTripsOnlyTheExactCompleteParticipantVector() thr fixture.operation().account(), selector)); var participants = previous.participantDigests().stream() - .map( - participant -> - new GameDesignPublicationTerminalEvidence.Participant( + .map(participant -> + new GameDesignPublicationTerminalEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( participant.participantKey(), - participant.scopeValue(), - participant.baseVersionId(), - participant.appliedCommitId(), - participant.contentDigest(), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - participant.participantKey(), - AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION), - participant.abilitySchemaDigest(), - participant.errorCode(), - participant.errorMessage())) + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION), + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage())) .toList(); var release = new GameDesignPublicationTerminalEvidence.ReleaseContent( @@ -120,23 +119,22 @@ void selectedFullV4TerminalRoundTripsOnlyTheExactCompleteParticipantVector() thr null, null, null)); - assertThatThrownBy( - () -> - new GameDesignPublicationTerminalEvidence.ReleaseContent( - previous.canonicalTenantId(), - previous.canonicalVersionId(), - previous.publishedReleaseBundleRef(), - previous.versionNumber(), - "v4", - previous.publishWorkflowId(), - previous.manifestHash(), - previous.manifestSchemaVersion(), - previous.artifactDigests(), - previous.requiredManifestAssetKeys(), - mixedParticipants, - previous.commandDefinitions(), - previous.generationConfigRevision(), - selector)) + assertThatThrownBy(() -> + new GameDesignPublicationTerminalEvidence.ReleaseContent( + previous.canonicalTenantId(), + previous.canonicalVersionId(), + previous.publishedReleaseBundleRef(), + previous.versionNumber(), + "v4", + previous.publishWorkflowId(), + previous.manifestHash(), + previous.manifestSchemaVersion(), + previous.artifactDigests(), + previous.requiredManifestAssetKeys(), + mixedParticipants, + previous.commandDefinitions(), + previous.generationConfigRevision(), + selector)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Incomplete or changed required participant proof"); } @@ -189,10 +187,9 @@ void maximumFrozenEpochIsRejectedAsInvalidEvidenceAndOrdinaryEpochRoundTrips() t .setCanonicalResponseBytes(ByteString.copyFrom(malformedResponseBytes.toByteArray())) .build(); - assertThatThrownBy( - () -> - GameDesignPublicationTerminalReadGrpcCodec.fromResponse( - maxEpochRequest, malformedWireResponse)) + assertThatThrownBy(() -> + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + maxEpochRequest, malformedWireResponse)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Published version-state epoch exceeds owner range"); } @@ -218,13 +215,12 @@ void publicationCounterAboveIntRangeIsRejectedAsInvalidTerminalReadEvidence() th replaceFrame(fixture.terminal().canonicalBytes(), 3, malformedRelease); byte[] malformedResponse = replaceFrame(result.canonicalBytes(), 3, malformedTerminal); - assertThatThrownBy( - () -> - GameDesignPublicationTerminalReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setCanonicalResponseBytes(ByteString.copyFrom(malformedResponse)) - .build())) + assertThatThrownBy(() -> + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(malformedResponse)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("supported range"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodecTest.java index 78c03f25e5..8aa8cae64b 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GameSessionCanonicalInitialAdmissionOwnerProofCodecTest.java @@ -113,32 +113,29 @@ void everyTerminalBindingAndResultChangeChangesCanonicalOwnerProofBytes() { void rejectsAmbiguousOrContradictoryTerminalFields() { var identity = holdIdentity(InitialAdmissionOrigin.NO_PRIOR_POINTER, null); - assertThatThrownBy( - () -> - new GameSessionCanonicalInitialAdmissionOwnerProof( - identity, Outcome.PENDING, null, null, "sha256:" + "a".repeat(64), false, null)) + assertThatThrownBy(() -> + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, Outcome.PENDING, null, null, "sha256:" + "a".repeat(64), false, null)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GameSessionCanonicalInitialAdmissionOwnerProof( - identity, - Outcome.ABORTED, - 14L, - null, - "sha256:" + "a".repeat(64), - true, - TERMINAL_AT)) + assertThatThrownBy(() -> + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + Outcome.ABORTED, + 14L, + null, + "sha256:" + "a".repeat(64), + true, + TERMINAL_AT)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GameSessionCanonicalInitialAdmissionOwnerProof( - identity, - Outcome.ABORTED, - null, - null, - "sha256:" + "a".repeat(64), - false, - TERMINAL_AT)) + assertThatThrownBy(() -> + new GameSessionCanonicalInitialAdmissionOwnerProof( + identity, + Outcome.ABORTED, + null, + null, + "sha256:" + "a".repeat(64), + false, + TERMINAL_AT)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionActivationTerminalReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionActivationTerminalReadClientTest.java index b0c558ac3d..5a1651ea11 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionActivationTerminalReadClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionActivationTerminalReadClientTest.java @@ -26,10 +26,9 @@ void requiresExplicitFileBackedMtlsBeforeAnyTransport(@TempDir Path directory) t GrpcChannelFactory factory = mock(GrpcChannelFactory.class); CommonGrpcClientProperties plaintext = fileBacked(directory); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new GrpcWorldOriginalStartSessionActivationTerminalReadClient( - new ServiceEndpointsProperties(), plaintext, factory, "world-runtime")) + assertThatThrownBy(() -> + new GrpcWorldOriginalStartSessionActivationTerminalReadClient( + new ServiceEndpointsProperties(), plaintext, factory, "world-runtime")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mTLS"); @@ -37,10 +36,9 @@ void requiresExplicitFileBackedMtlsBeforeAnyTransport(@TempDir Path directory) t classpath.setCertChain("classpath:client.crt"); classpath.setPrivateKey("/tmp/key"); classpath.setCaCert("/tmp/ca"); - assertThatThrownBy( - () -> - new GrpcWorldOriginalStartSessionActivationTerminalReadClient( - new ServiceEndpointsProperties(), classpath, factory, "world-runtime")) + assertThatThrownBy(() -> + new GrpcWorldOriginalStartSessionActivationTerminalReadClient( + new ServiceEndpointsProperties(), classpath, factory, "world-runtime")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("file-backed"); verifyNoInteractions(factory); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionProtectedActivationClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionProtectedActivationClientTest.java index fa52de1e2d..4aa2baf7ee 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionProtectedActivationClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/GrpcWorldOriginalStartSessionProtectedActivationClientTest.java @@ -23,10 +23,9 @@ void requiresExplicitFileBackedMtlsBeforeAnyTransport(@TempDir Path directory) t GrpcChannelFactory factory = mock(GrpcChannelFactory.class); CommonGrpcClientProperties plaintext = fileBacked(directory); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new GrpcWorldOriginalStartSessionProtectedActivationClient( - new ServiceEndpointsProperties(), plaintext, factory, "world-runtime")) + assertThatThrownBy(() -> + new GrpcWorldOriginalStartSessionProtectedActivationClient( + new ServiceEndpointsProperties(), plaintext, factory, "world-runtime")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mTLS"); @@ -34,10 +33,9 @@ void requiresExplicitFileBackedMtlsBeforeAnyTransport(@TempDir Path directory) t classpath.setCertChain("classpath:client.crt"); classpath.setPrivateKey("/tmp/key"); classpath.setCaCert("/tmp/ca"); - assertThatThrownBy( - () -> - new GrpcWorldOriginalStartSessionProtectedActivationClient( - new ServiceEndpointsProperties(), classpath, factory, "world-runtime")) + assertThatThrownBy(() -> + new GrpcWorldOriginalStartSessionProtectedActivationClient( + new ServiceEndpointsProperties(), classpath, factory, "world-runtime")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("file-backed"); verifyNoInteractions(factory); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java index 06df7a9fa0..b5f92c679b 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PreseededActorAssignmentOwnerReadEvidenceTest.java @@ -63,10 +63,8 @@ void rejectsChangedSelectorsPolicyReleaseUnknownFieldsAndPartialSourceEvidence() request.expectedCatalogRevision(), "9".repeat(64), request.expectedPublishedReleaseBundleRef()); - assertThatThrownBy( - () -> - new PreseededActorAssignmentOwnerReadEvidence( - changedDigest, evidence.sourceEvidence())) + assertThatThrownBy(() -> + new PreseededActorAssignmentOwnerReadEvidence(changedDigest, evidence.sourceEvidence())) .isInstanceOf(IllegalArgumentException.class); var changedRelease = @@ -85,10 +83,9 @@ void rejectsChangedSelectorsPolicyReleaseUnknownFieldsAndPartialSourceEvidence() request.expectedCatalogRevision(), request.expectedPolicyDigest(), "substituted-release"); - assertThatThrownBy( - () -> - new PreseededActorAssignmentOwnerReadEvidence( - changedRelease, evidence.sourceEvidence())) + assertThatThrownBy(() -> + new PreseededActorAssignmentOwnerReadEvidence( + changedRelease, evidence.sourceEvidence())) .isInstanceOf(IllegalArgumentException.class); var unknownRequest = @@ -100,18 +97,16 @@ void rejectsChangedSelectorsPolicyReleaseUnknownFieldsAndPartialSourceEvidence() .build(); assertThatThrownBy(() -> PreseededActorAssignmentOwnerReadGrpcCodec.fromRequest(unknownRequest)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - PreseededActorAssignmentOwnerReadGrpcCodec.fromResponse( - request, GetPreseededActorAssignmentOwnerReadResponse.getDefaultInstance())) + assertThatThrownBy(() -> + PreseededActorAssignmentOwnerReadGrpcCodec.fromResponse( + request, GetPreseededActorAssignmentOwnerReadResponse.getDefaultInstance())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - PreseededActorAssignmentOwnerReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setRequest(wireRequest.toBuilder().setRealmSlug("other").build()) - .build())) + assertThatThrownBy(() -> + PreseededActorAssignmentOwnerReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest(wireRequest.toBuilder().setRealmSlug("other").build()) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -133,10 +128,8 @@ void sourceRequestRequiresCommittedOwnerProofBeforeReadingCommittedPointer() thr null, false, null); - assertThatThrownBy( - () -> - PreseededActorAssignmentOwnerReadEvidence.sourceRequest( - evidence.request(), pending)) + assertThatThrownBy(() -> + PreseededActorAssignmentOwnerReadEvidence.sourceRequest(evidence.request(), pending)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Committed Game Session owner proof"); @@ -149,10 +142,8 @@ void sourceRequestRequiresCommittedOwnerProofBeforeReadingCommittedPointer() thr "sha256:" + "c".repeat(64), true, TERMINAL_AT); - assertThatThrownBy( - () -> - PreseededActorAssignmentOwnerReadEvidence.sourceRequest( - evidence.request(), aborted)) + assertThatThrownBy(() -> + PreseededActorAssignmentOwnerReadEvidence.sourceRequest(evidence.request(), aborted)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Committed Game Session owner proof"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java index cbd99d8356..d760e38579 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicyReadGrpcCodecTest.java @@ -66,44 +66,37 @@ void requestsRejectUnknownFieldsUnsupportedSchemaAndNoncanonicalIdentityOrSelect .build(); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( - validList.toBuilder().setUnknownFields(unknown).build())); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validList.toBuilder().setUnknownFields(unknown).build())); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( - validResolve.toBuilder().setSchemaVersion(2).build())); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validResolve.toBuilder().setSchemaVersion(2).build())); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( - validList.toBuilder() - .setReadRequestId("00000000-0000-0000-0000-000000000000") - .build())); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validList.toBuilder() + .setReadRequestId("00000000-0000-0000-0000-000000000000") + .build())); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( - validList.toBuilder() - .setCanonicalTenantId("BBBBBBBB-BBBB-4BBB-8BBB-BBBBBBBBBBBB") - .build())); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validList.toBuilder() + .setCanonicalTenantId("BBBBBBBB-BBBB-4BBB-8BBB-BBBBBBBBBBBB") + .build())); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( - validList.toBuilder().setTargetNamespace("Test").build())); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validList.toBuilder().setTargetNamespace("Test").build())); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( - validResolve.toBuilder().setWorldSlug("Main").build())); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validResolve.toBuilder().setWorldSlug("Main").build())); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( - validResolve.toBuilder().setRealmSlug("bad--slug").build())); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + validResolve.toBuilder().setRealmSlug("bad--slug").build())); } @Test @@ -113,55 +106,49 @@ void responsesRejectChangedEchoTargetAndMissingSelector() throws Exception { var response = PublishedRealmEntryPolicyReadGrpcCodec.toResponse(request, fixture.set()); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setRequest(response.getRequest().toBuilder().setTargetNamespace("other")) - .build())); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest(response.getRequest().toBuilder().setTargetNamespace("other")) + .build())); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setRequest( - response.getRequest().toBuilder() - .setReadRequestId("88888888-8888-4888-8888-888888888888")) - .build())); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setReadRequestId("88888888-8888-4888-8888-888888888888")) + .build())); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setRequest( - response.getRequest().toBuilder() - .setCanonicalTenantId("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")) - .build())); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setCanonicalTenantId("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")) + .build())); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setRequest( - response.getRequest().toBuilder() - .setCanonicalVersionId("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")) - .build())); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setCanonicalVersionId("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")) + .build())); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField( - 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) - .build()) - .build())); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())); var wrongTarget = new PublishedRealmEntryPolicyReadGrpcCodec.ListRequest( @@ -175,10 +162,8 @@ void responsesRejectChangedEchoTargetAndMissingSelector() throws Exception { .setPolicySetEvidence(ByteString.copyFrom(fixture.set().canonicalBytes())) .build(); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( - wrongTarget, substitutedEvidence)); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(wrongTarget, substitutedEvidence)); var resolve = resolveRequest(fixture, "99999999-9999-4999-8999-999999999999", "missing"); var missingSelectorResponse = @@ -187,23 +172,19 @@ void responsesRejectChangedEchoTargetAndMissingSelector() throws Exception { .setPolicySetEvidence(ByteString.copyFrom(fixture.set().canonicalBytes())) .build(); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( - resolve, missingSelectorResponse)); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(resolve, missingSelectorResponse)); var exactResolve = resolveRequest(fixture, "99999999-9999-4999-8999-999999999999", "main"); var exactResolveResponse = PublishedRealmEntryPolicyReadGrpcCodec.toResponse(exactResolve, fixture.set()); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( - exactResolve, - exactResolveResponse.toBuilder() - .setRequest( - exactResolveResponse.getRequest().toBuilder().setRealmSlug("side")) - .build())); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + exactResolve, + exactResolveResponse.toBuilder() + .setRequest(exactResolveResponse.getRequest().toBuilder().setRealmSlug("side")) + .build())); } @Test @@ -217,20 +198,17 @@ void bothReadShapesBindSealedNamespaceTenantAndVersion() throws Exception { originalList.canonicalTenantId(), originalList.canonicalVersionId()); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.toResponse( - crossNamespaceList, fixture.set())); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.toResponse(crossNamespaceList, fixture.set())); var substitutedList = ListPublishedRealmEntryPoliciesResponse.newBuilder() .setRequest(PublishedRealmEntryPolicyReadGrpcCodec.toRequest(crossNamespaceList)) .setPolicySetEvidence(ByteString.copyFrom(fixture.set().canonicalBytes())) .build(); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( - crossNamespaceList, substitutedList)); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + crossNamespaceList, substitutedList)); var crossTenantList = new PublishedRealmEntryPolicyReadGrpcCodec.ListRequest( @@ -239,9 +217,8 @@ void bothReadShapesBindSealedNamespaceTenantAndVersion() throws Exception { UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), originalList.canonicalVersionId()); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.toResponse(crossTenantList, fixture.set())); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.toResponse(crossTenantList, fixture.set())); var crossVersionList = new PublishedRealmEntryPolicyReadGrpcCodec.ListRequest( originalList.targetNamespace(), @@ -249,9 +226,8 @@ void bothReadShapesBindSealedNamespaceTenantAndVersion() throws Exception { originalList.canonicalTenantId(), UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb")); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.toResponse(crossVersionList, fixture.set())); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.toResponse(crossVersionList, fixture.set())); var originalResolve = resolveRequest(fixture, "99999999-9999-4999-8999-999999999999", "main"); var crossNamespaceResolve = @@ -263,20 +239,18 @@ void bothReadShapesBindSealedNamespaceTenantAndVersion() throws Exception { originalResolve.worldSlug(), originalResolve.realmSlug()); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.toResponse( - crossNamespaceResolve, fixture.set())); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.toResponse( + crossNamespaceResolve, fixture.set())); var substitutedResolve = ResolvePublishedRealmEntryPolicyResponse.newBuilder() .setRequest(PublishedRealmEntryPolicyReadGrpcCodec.toRequest(crossNamespaceResolve)) .setPolicySetEvidence(ByteString.copyFrom(fixture.set().canonicalBytes())) .build(); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( - crossNamespaceResolve, substitutedResolve)); + .isThrownBy(() -> + PublishedRealmEntryPolicyReadGrpcCodec.fromResponse( + crossNamespaceResolve, substitutedResolve)); } @Test diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java index 53c24b811b..67d5d924f0 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/PublishedRealmEntryPolicySetEvidenceTest.java @@ -114,31 +114,27 @@ void storedDraftSelectionRetainsCanonicalValidationAndTheNestedWireFailureCause( throws Exception { var selection = fixture(false).operation().account().input().selection(); - assertThatThrownBy( - () -> - AuthoredDraftPublishSelectionBinding.fromStored( - selection.canonicalJson() + " ", selection.digest())) + assertThatThrownBy(() -> + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson() + " ", selection.digest())) .isInstanceOf(IllegalArgumentException.class) - .satisfies( - failure -> { - assertThat(failure.getCause()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("not exact canonical JSON"); - }); + .satisfies(failure -> { + assertThat(failure.getCause()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not exact canonical JSON"); + }); ObjectNode corrupted = (ObjectNode) JSON.readTree(selection.canonicalJson()); corrupted.put("selectedCommitBindingJson", "{}"); String corruptedJson = JSON.writeValueAsString(corrupted); - assertThatThrownBy( - () -> - AuthoredDraftPublishSelectionBinding.fromStored(corruptedJson, selection.digest())) + assertThatThrownBy(() -> + AuthoredDraftPublishSelectionBinding.fromStored(corruptedJson, selection.digest())) .isInstanceOf(IllegalArgumentException.class) - .satisfies( - failure -> { - assertThat(failure.getCause()) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("corrupt"); - }); + .satisfies(failure -> { + assertThat(failure.getCause()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("corrupt"); + }); } @Test @@ -231,22 +227,21 @@ void completeSetRejectsCountMissingOrderDuplicateAndDigestChanges() throws Excep policy("mars", "Mars", "main", "Main", false, false), DIGEST)); assertThatIllegalArgumentException() - .isThrownBy( - () -> - PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( - fixture.target(), - set.versionNumber(), - set.sourceCommitId(), - set.sourceEpoch(), - set.publishedReleaseBundleRef(), - set.publishedReleaseBundleDigest(), - set.publishWorkflowId(), - set.manifestHash(), - set.publicationVersionStateEpoch(), - set.operationBytes(), - set.captureBytes(), - set.terminalEvidenceBytes(), - duplicateSource)); + .isThrownBy(() -> + PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( + fixture.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + set.captureBytes(), + set.terminalEvidenceBytes(), + duplicateSource)); } @Test @@ -275,108 +270,103 @@ void completeSetRejectsChildSourceScopeCaptureTerminalAndBundleSubstitution() th fixture.target().sourceGameTenantKey(), fixture.target().sourceProvenanceKind()); assertThatIllegalArgumentException() - .isThrownBy( - () -> - new PublishedRealmEntryPolicySetEvidence( - changedTarget, - set.versionNumber(), - set.sourceCommitId(), - set.sourceEpoch(), - set.publishedReleaseBundleRef(), - set.publishedReleaseBundleDigest(), - set.publishWorkflowId(), - set.manifestHash(), - set.publicationVersionStateEpoch(), - set.operationBytes(), - set.captureBytes(), - set.terminalEvidenceBytes(), - set.policyCount(), - set.policySetDigest(), - set.policies())); + .isThrownBy(() -> + new PublishedRealmEntryPolicySetEvidence( + changedTarget, + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + set.captureBytes(), + set.terminalEvidenceBytes(), + set.policyCount(), + set.policySetDigest(), + set.policies())); var changedOperation = operation(6L); assertThatIllegalArgumentException() - .isThrownBy( - () -> - new PublishedRealmEntryPolicySetEvidence( - set.target(), - set.versionNumber(), - set.sourceCommitId(), - set.sourceEpoch(), - set.publishedReleaseBundleRef(), - set.publishedReleaseBundleDigest(), - set.publishWorkflowId(), - set.manifestHash(), - set.publicationVersionStateEpoch(), - changedOperation.canonicalBytes(), - set.captureBytes(), - set.terminalEvidenceBytes(), - set.policyCount(), - set.policySetDigest(), - set.policies())); + .isThrownBy(() -> + new PublishedRealmEntryPolicySetEvidence( + set.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + changedOperation.canonicalBytes(), + set.captureBytes(), + set.terminalEvidenceBytes(), + set.policyCount(), + set.policySetDigest(), + set.policies())); byte[] substitutedCapture = capture(fixture.operation(), fixture.sourceBinding(), "44", fixture.sources()); assertThatIllegalArgumentException() - .isThrownBy( - () -> - new PublishedRealmEntryPolicySetEvidence( - set.target(), - set.versionNumber(), - set.sourceCommitId(), - set.sourceEpoch(), - set.publishedReleaseBundleRef(), - set.publishedReleaseBundleDigest(), - set.publishWorkflowId(), - set.manifestHash(), - set.publicationVersionStateEpoch(), - set.operationBytes(), - substitutedCapture, - set.terminalEvidenceBytes(), - set.policyCount(), - set.policySetDigest(), - set.policies())); + .isThrownBy(() -> + new PublishedRealmEntryPolicySetEvidence( + set.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + substitutedCapture, + set.terminalEvidenceBytes(), + set.policyCount(), + set.policySetDigest(), + set.policies())); var substitutedTerminal = terminal(fixture.operation(), fixture.release("generation-2"), 6L); assertThatIllegalArgumentException() - .isThrownBy( - () -> - new PublishedRealmEntryPolicySetEvidence( - set.target(), - set.versionNumber(), - set.sourceCommitId(), - set.sourceEpoch(), - set.publishedReleaseBundleRef(), - set.publishedReleaseBundleDigest(), - set.publishWorkflowId(), - set.manifestHash(), - set.publicationVersionStateEpoch(), - set.operationBytes(), - set.captureBytes(), - substitutedTerminal.canonicalBytes(), - set.policyCount(), - set.policySetDigest(), - set.policies())); + .isThrownBy(() -> + new PublishedRealmEntryPolicySetEvidence( + set.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + set.publishedReleaseBundleRef(), + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + set.captureBytes(), + substitutedTerminal.canonicalBytes(), + set.policyCount(), + set.policySetDigest(), + set.policies())); assertThatIllegalArgumentException() - .isThrownBy( - () -> - new PublishedRealmEntryPolicySetEvidence( - set.target(), - set.versionNumber(), - set.sourceCommitId(), - set.sourceEpoch(), - "substituted-bundle-reference", - set.publishedReleaseBundleDigest(), - set.publishWorkflowId(), - set.manifestHash(), - set.publicationVersionStateEpoch(), - set.operationBytes(), - set.captureBytes(), - set.terminalEvidenceBytes(), - set.policyCount(), - set.policySetDigest(), - set.policies())); + .isThrownBy(() -> + new PublishedRealmEntryPolicySetEvidence( + set.target(), + set.versionNumber(), + set.sourceCommitId(), + set.sourceEpoch(), + "substituted-bundle-reference", + set.publishedReleaseBundleDigest(), + set.publishWorkflowId(), + set.manifestHash(), + set.publicationVersionStateEpoch(), + set.operationBytes(), + set.captureBytes(), + set.terminalEvidenceBytes(), + set.policyCount(), + set.policySetDigest(), + set.policies())); } @Test @@ -452,30 +442,29 @@ static Fixture fixture(boolean includeSide) throws Exception { byte[] capture = capture(operation, sourceBinding, "43", sources); List policies = sources.stream() - .map( - source -> { - UUID policyId = UUID.fromString(source.policyId()); - String policyDigest = - PublishedRealmEntryPolicySetEvidence.policyDigest( - policyId, - target, - terminal.releaseContent().versionNumber(), - terminal.publishedReleaseBundleRef(), - terminal.publishedReleaseBundleDigest(), - terminal.releaseContent().publishWorkflowId(), - terminal.releaseContent().manifestHash(), - UUID.fromString(source.sourceCommitId()), - UUID.fromString(source.sourceRevisionId()), - source.logicalRevisionId(), - source.policy()); - return new PublishedRealmEntryPolicyEvidence( + .map(source -> { + UUID policyId = UUID.fromString(source.policyId()); + String policyDigest = + PublishedRealmEntryPolicySetEvidence.policyDigest( policyId, + target, + terminal.releaseContent().versionNumber(), + terminal.publishedReleaseBundleRef(), + terminal.publishedReleaseBundleDigest(), + terminal.releaseContent().publishWorkflowId(), + terminal.releaseContent().manifestHash(), UUID.fromString(source.sourceCommitId()), UUID.fromString(source.sourceRevisionId()), source.logicalRevisionId(), - source.policy(), - policyDigest); - }) + source.policy()); + return new PublishedRealmEntryPolicyEvidence( + policyId, + UUID.fromString(source.sourceCommitId()), + UUID.fromString(source.sourceRevisionId()), + source.logicalRevisionId(), + source.policy(), + policyDigest); + }) .toList(); var setDigest = PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( @@ -564,15 +553,14 @@ private static byte[] capture( throws IOException { List> policies = sources.stream() - .map( - source -> { - Map value = new LinkedHashMap<>(); - value.put("commitId", source.sourceCommitId()); - value.put("revisionId", source.sourceRevisionId()); - value.put("logicalRevisionId", source.logicalRevisionId()); - value.put("policy", JSON.readTree(source.policy().canonicalJson())); - return value; - }) + .map(source -> { + Map value = new LinkedHashMap<>(); + value.put("commitId", source.sourceCommitId()); + value.put("revisionId", source.sourceRevisionId()); + value.put("logicalRevisionId", source.logicalRevisionId()); + value.put("policy", JSON.readTree(source.policy().canonicalJson())); + return value; + }) .toList(); Map snapshot = new LinkedHashMap<>(); snapshot.put("schema", PublishedRealmEntryPolicySetEvidence.SNAPSHOT_SCHEMA); @@ -600,25 +588,19 @@ static ReleaseContent release( var request = operation.world().request(); var participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new Participant( - owner, - Long.toString( - operation - .account() - .input() - .selection() - .target() - .gameDesignVersionRowId()), - null, - request.appliedCommitId(), - owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - owner.equals("GAME_LOGIC") ? DIGEST : null, - null, - null)) + .map(owner -> + new Participant( + owner, + Long.toString( + operation.account().input().selection().target().gameDesignVersionRowId()), + null, + request.appliedCommitId(), + owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + owner.equals("GAME_LOGIC") ? DIGEST : null, + null, + null)) .toList(); return new ReleaseContent( request.canonicalTenantId(), diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldStateTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldStateTest.java index 061d7b3d0b..6bd8676bf7 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldStateTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldStateTest.java @@ -90,12 +90,11 @@ void rejectsChangedTargetScopeWithoutEquatingIndependentRequestIds() throws Exce 1L, null); - assertThatThrownBy( - () -> - new WorldCanonicalInitialAdmissionHoldState( - new HoldIdentity(mismatched, HOLD_ID, HOLD_FENCE), - WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING, - lifecycle)) + assertThatThrownBy(() -> + new WorldCanonicalInitialAdmissionHoldState( + new HoldIdentity(mismatched, HOLD_ID, HOLD_FENCE), + WorldCanonicalInitialAdmissionHoldState.HoldStatus.PENDING, + lifecycle)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("target scope"); @@ -156,24 +155,21 @@ void rejectsUnknownDuplicateNoncanonicalMalformedAndOversizedState() throws Exce java.util.Base64.getEncoder().encodeToString(state.holdIdentity().canonicalBytes()), "!")); assertInvalid(canonical + " "); - assertThatThrownBy( - () -> - WorldCanonicalInitialAdmissionHoldState.fromStored(new byte[] {(byte) 0xc3, 0x28})) + assertThatThrownBy(() -> + WorldCanonicalInitialAdmissionHoldState.fromStored(new byte[] {(byte) 0xc3, 0x28})) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("strict UTF-8"); - assertThatThrownBy( - () -> - WorldCanonicalInitialAdmissionHoldState.fromStored( - new byte[WorldCanonicalInitialAdmissionHoldState.MAX_CANONICAL_BYTES + 1])) + assertThatThrownBy(() -> + WorldCanonicalInitialAdmissionHoldState.fromStored( + new byte[WorldCanonicalInitialAdmissionHoldState.MAX_CANONICAL_BYTES + 1])) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("limit"); } private static void assertInvalid(String value) { - assertThatThrownBy( - () -> - WorldCanonicalInitialAdmissionHoldState.fromStored( - value.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + WorldCanonicalInitialAdmissionHoldState.fromStored( + value.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldTest.java index bd974c753e..238ca1854a 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldTest.java @@ -263,140 +263,132 @@ void everySupportedRequestFieldChangesTheCanonicalHoldBinding() { @Test void rejectsNilNoncanonicalAndInvalidScopeOrOriginInputs() { - assertThatThrownBy( - () -> - request( - "prod", - NIL_UUID, - "green-hollow", - REALM, - PLAYABLE_NAMESPACE, - GAME_INSTANCE, - VERSION, - 7L, - "gs-initial-admission-17", - REQUEST_DIGEST, - InitialAdmissionOrigin.NO_PRIOR_POINTER, - 12L, - null)) + assertThatThrownBy(() -> + request( + "prod", + NIL_UUID, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - request( - "prod", - TENANT, - "green-hollow", - REALM, - PLAYABLE_NAMESPACE, - GAME_INSTANCE, - VERSION, - 7L, - "gs-initial-admission-17", - REQUEST_DIGEST, - InitialAdmissionOrigin.NO_PRIOR_POINTER, - 12L, - null, - "PRIVATE")) + assertThatThrownBy(() -> + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null, + "PRIVATE")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("SHARED"); assertThatThrownBy( () -> Request.fromStored(utf8Bytes(NO_PRIOR_VECTOR.replace("SHARED", "ISOLATED")))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("SHARED"); - assertThatThrownBy( - () -> - Request.fromStored( - utf8Bytes(NO_PRIOR_VECTOR.replace("NO_PRIOR_POINTER", "FIRST_OPEN")))) + assertThatThrownBy(() -> + Request.fromStored( + utf8Bytes(NO_PRIOR_VECTOR.replace("NO_PRIOR_POINTER", "FIRST_OPEN")))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("initialAdmissionOrigin"); - assertThatThrownBy( - () -> - request( - "prod", - TENANT, - "green-hollow", - REALM, - PLAYABLE_NAMESPACE, - GAME_INSTANCE, - VERSION, - 7L, - "gs-initial-admission-17", - REQUEST_DIGEST, - InitialAdmissionOrigin.NO_PRIOR_POINTER, - 12L, - 1L)) + assertThatThrownBy(() -> + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + 1L)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("NO_PRIOR_POINTER"); - assertThatThrownBy( - () -> - request( - "prod", - TENANT, - "green-hollow", - REALM, - PLAYABLE_NAMESPACE, - GAME_INSTANCE, - VERSION, - 7L, - "gs-initial-admission-17", - REQUEST_DIGEST, - InitialAdmissionOrigin.EXPECT_CLOSED, - 12L, - null)) + assertThatThrownBy(() -> + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + REQUEST_DIGEST, + InitialAdmissionOrigin.EXPECT_CLOSED, + 12L, + null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("requires"); - assertThatThrownBy( - () -> - request( - "prod", - TENANT, - "green-hollow", - REALM, - PLAYABLE_NAMESPACE, - GAME_INSTANCE, - VERSION, - 7L, - "gs-initial-admission-17", - "A".repeat(64), - InitialAdmissionOrigin.NO_PRIOR_POINTER, - 12L, - null)) + assertThatThrownBy(() -> + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "gs-initial-admission-17", + "A".repeat(64), + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("lowercase"); - assertThatThrownBy( - () -> - request( - "prod", - TENANT, - "green-hollow", - REALM, - PLAYABLE_NAMESPACE, - GAME_INSTANCE, - VERSION, - 7L, - " ", - REQUEST_DIGEST, - InitialAdmissionOrigin.NO_PRIOR_POINTER, - 12L, - null)) + assertThatThrownBy(() -> + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + " ", + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("nonempty"); - assertThatThrownBy( - () -> - request( - "prod", - TENANT, - "green-hollow", - REALM, - PLAYABLE_NAMESPACE, - GAME_INSTANCE, - VERSION, - 7L, - "r".repeat(129), - REQUEST_DIGEST, - InitialAdmissionOrigin.NO_PRIOR_POINTER, - 12L, - null)) + assertThatThrownBy(() -> + request( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + GAME_INSTANCE, + VERSION, + 7L, + "r".repeat(129), + REQUEST_DIGEST, + InitialAdmissionOrigin.NO_PRIOR_POINTER, + 12L, + null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("bounded"); assertThatThrownBy(() -> new HoldIdentity(noPriorRequest(), NIL_UUID, HOLD_FENCE)) @@ -452,22 +444,20 @@ void parserRejectsInvalidUuidsOptionalRepresentationsCountersAliasesAndUnknownIn String identity = utf8(new HoldIdentity(noPriorRequest(), HOLD_ID, HOLD_FENCE).canonicalBytes()); - assertThatThrownBy( - () -> - HoldIdentity.fromStored( - utf8Bytes( - identity.replace( - "\"holdBindingDigest\":\"" + noPriorRequest().holdBindingDigest(), - "\"holdBindingDigest\":\"sha256:" + "0".repeat(64))))) + assertThatThrownBy(() -> + HoldIdentity.fromStored( + utf8Bytes( + identity.replace( + "\"holdBindingDigest\":\"" + noPriorRequest().holdBindingDigest(), + "\"holdBindingDigest\":\"sha256:" + "0".repeat(64))))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("digest"); - assertThatThrownBy( - () -> - HoldIdentity.fromStored( - utf8Bytes( - identity.replace( - "\"holdId\":", - "\"legacyHoldId\":\"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa\",\"holdId\":")))) + assertThatThrownBy(() -> + HoldIdentity.fromStored( + utf8Bytes( + identity.replace( + "\"holdId\":", + "\"legacyHoldId\":\"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa\",\"holdId\":")))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("closed object shape"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java index 1870730ea2..1b9eabe076 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldCanonicalInstanceLifecycleEvidenceTest.java @@ -108,10 +108,9 @@ void rejectsMalformedOperationalRegionAssignmentMapsAndFreezesCallerInput() thro + "\"}"; assertThat(stored).contains(assignmentField); String legacyShape = stored.replace("," + assignmentField, ""); - assertThatThrownBy( - () -> - WorldCanonicalInstanceLifecycleEvidence.fromStored( - legacyShape.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + legacyShape.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("missing or unsupported fields"); assertInvalidStoredAssignments(stored, assignmentField, "{}", "nonempty"); @@ -181,11 +180,10 @@ void rejectsChangedCanonicalIdentitiesAndEveryExpectedBindingDigest() throws Exc request.expectedDescriptorRequestDigest(), request.expectedDescriptorResultDigest(), request.expectedReleaseAttestationDigest()); - assertThatThrownBy( - () -> - WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse( - changedInstance, - WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(request, evidence))) + assertThatThrownBy(() -> + WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse( + changedInstance, + WorldCanonicalInstanceLifecycleGrpcCodec.toResponse(request, evidence))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("changed exact read request"); @@ -312,36 +310,34 @@ void rejectsChangedCanonicalIdentitiesAndEveryExpectedBindingDigest() throws Exc evidence.startLocation().tenantId(), evidence.startLocation().versionId(), uuid("66666666-6666-4666-8666-666666666666")); - assertThatThrownBy( - () -> - with( - evidence, - request, - evidence.launchBinding(), - changedSelector, - evidence.runtimeRoomInstanceId(), - evidence.lifecycleStatus(), - evidence.lifecycleEpoch(), - evidence.rowVersion(), - evidence.captureId(), - evidence.graphSha256(), - evidence.preparationInputDigest())) + assertThatThrownBy(() -> + with( + evidence, + request, + evidence.launchBinding(), + changedSelector, + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("release selector"); - assertThatThrownBy( - () -> - with( - evidence, - request, - evidence.launchBinding(), - evidence.startLocation(), - evidence.runtimeRoomInstanceId(), - evidence.lifecycleStatus(), - evidence.lifecycleEpoch(), - evidence.rowVersion(), - evidence.captureId(), - "f".repeat(64), - evidence.preparationInputDigest())) + assertThatThrownBy(() -> + with( + evidence, + request, + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + "f".repeat(64), + evidence.preparationInputDigest())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("graph digest"); } @@ -355,22 +351,21 @@ void rejectsUnselectedV1ReleaseAndMalformedLifecycleCountersOrDigests() throws E // Independent retained-v1 fixture; its GD digest is not the selected-v2 content hash. var v1Participants = release.participantDigests().stream() - .map( - participant -> - new AuthoredWorldReleaseAttestationEvidence.Participant( + .map(participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent(), + participant.baseVersionId(), + participant.appliedCommitId(), + "GAME_DESIGN_CONTROL_PLANE".equals(participant.participantKey()) + ? "e".repeat(64) + : participant.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( participant.participantKey(), - participant.scopeValue(), - participant.baseVersionIdPresent(), - participant.baseVersionId(), - participant.appliedCommitId(), - "GAME_DESIGN_CONTROL_PLANE".equals(participant.participantKey()) - ? "e".repeat(64) - : participant.contentDigest(), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - participant.participantKey(), - AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION), - participant.abilitySchemaDigestPresent(), - participant.abilitySchemaDigest())) + AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION), + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest())) .toList(); var v1Release = AuthoredWorldReleaseAttestationEvidence.create( @@ -407,56 +402,53 @@ void rejectsUnselectedV1ReleaseAndMalformedLifecycleCountersOrDigests() throws E null, null, v1Release.evidenceDigest()); - assertThatThrownBy( - () -> - with( - evidence, - v1Request, - new CompleteLaunchBindingEvidence(descriptor, v1Release), - evidence.startLocation(), - evidence.runtimeRoomInstanceId(), - evidence.lifecycleStatus(), - evidence.lifecycleEpoch(), - evidence.rowVersion(), - evidence.captureId(), - evidence.graphSha256(), - evidence.preparationInputDigest())) + assertThatThrownBy(() -> + with( + evidence, + v1Request, + new CompleteLaunchBindingEvidence(descriptor, v1Release), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("complete selected-release selector evidence"); assertInvalid(evidence, evidence.runtimeRoomInstanceId(), evidence.lifecycleEpoch(), -1); assertInvalid(evidence, evidence.runtimeRoomInstanceId(), 0, evidence.rowVersion()); assertInvalid(evidence, 0, evidence.lifecycleEpoch(), evidence.rowVersion()); - assertThatThrownBy( - () -> - with( - evidence, - evidence.request(), - evidence.launchBinding(), - evidence.startLocation(), - evidence.runtimeRoomInstanceId(), - evidence.lifecycleStatus(), - evidence.lifecycleEpoch(), - evidence.rowVersion(), - NIL, - evidence.graphSha256(), - evidence.preparationInputDigest())) + assertThatThrownBy(() -> + with( + evidence, + evidence.request(), + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + NIL, + evidence.graphSha256(), + evidence.preparationInputDigest())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("captureId"); - assertThatThrownBy( - () -> - with( - evidence, - evidence.request(), - evidence.launchBinding(), - evidence.startLocation(), - evidence.runtimeRoomInstanceId(), - evidence.lifecycleStatus(), - evidence.lifecycleEpoch(), - evidence.rowVersion(), - evidence.captureId(), - "A".repeat(64), - evidence.preparationInputDigest())) + assertThatThrownBy(() -> + with( + evidence, + evidence.request(), + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + "A".repeat(64), + evidence.preparationInputDigest())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("graphSha256"); } @@ -464,63 +456,47 @@ void rejectsUnselectedV1ReleaseAndMalformedLifecycleCountersOrDigests() throws E @Test void requestOnlyAcceptsProvedSharedPublicProductionIdentity() throws Exception { Request request = evidence().request(); - assertThatThrownBy( - () -> - copyRequest( - request, NIL, null, null, null, null, null, null, null, null, null, null)) + assertThatThrownBy(() -> + copyRequest(request, NIL, null, null, null, null, null, null, null, null, null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("readRequestId"); - assertThatThrownBy( - () -> - copyRequest( - request, - null, - null, - null, - null, - null, - "ISOLATED", - null, - null, - null, - null, - null)) + assertThatThrownBy(() -> + copyRequest( + request, null, null, null, null, null, "ISOLATED", null, null, null, null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("SHARED scope only"); - assertThatThrownBy( - () -> - new Request( - request.schemaVersion(), - request.readRequestId(), - request.targetNamespace(), - request.canonicalTenantId(), - request.worldSlug(), - request.canonicalGameInstanceId(), - request.playableStateNamespaceId(), - request.playableStateScope(), - false, - request.controlPlaneRequestId(), - request.canonicalVersionId(), - request.expectedDescriptorRequestDigest(), - request.expectedDescriptorResultDigest(), - request.expectedReleaseAttestationDigest())) + assertThatThrownBy(() -> + new Request( + request.schemaVersion(), + request.readRequestId(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.canonicalGameInstanceId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + false, + request.controlPlaneRequestId(), + request.canonicalVersionId(), + request.expectedDescriptorRequestDigest(), + request.expectedDescriptorResultDigest(), + request.expectedReleaseAttestationDigest())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("public-production evidence"); - assertThatThrownBy( - () -> - copyRequest( - request, - null, - null, - null, - null, - null, - null, - null, - null, - "not-a-digest", - null, - null)) + assertThatThrownBy(() -> + copyRequest( + request, + null, + null, + null, + null, + null, + null, + null, + null, + "not-a-digest", + null, + null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("expectedDescriptorRequestDigest"); } @@ -565,27 +541,24 @@ void preservesLongPrecisionAndRejectsOverflowOrNoncanonicalDecimalStrings() thro maxJson.replace( "\"runtimeRoomInstanceId\":\"" + Long.MAX_VALUE + "\"", "\"runtimeRoomInstanceId\":\"9223372036854775808\""); - assertThatThrownBy( - () -> - WorldCanonicalInstanceLifecycleEvidence.fromStored( - overflow.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + overflow.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("supported integer range"); String negative = maxJson.replace( "\"lifecycleEpoch\":\"" + Long.MAX_VALUE + "\"", "\"lifecycleEpoch\":\"-1\""); - assertThatThrownBy( - () -> - WorldCanonicalInstanceLifecycleEvidence.fromStored( - negative.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + negative.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical positive decimal"); String leadingZero = maxJson.replace("\"rowVersion\":\"" + Long.MAX_VALUE + "\"", "\"rowVersion\":\"01\""); - assertThatThrownBy( - () -> - WorldCanonicalInstanceLifecycleEvidence.fromStored( - leadingZero.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + leadingZero.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical nonnegative decimal"); } @@ -595,24 +568,21 @@ void rejectsClosedJsonAndProtobufUnknownOrDuplicateFields() throws Exception { WorldCanonicalInstanceLifecycleEvidence evidence = evidence(); String stored = new String(evidence.canonicalBytes(), StandardCharsets.UTF_8); String unknownField = stored.substring(0, 1) + "\"unsupported\":true," + stored.substring(1); - assertThatThrownBy( - () -> - WorldCanonicalInstanceLifecycleEvidence.fromStored( - unknownField.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + unknownField.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); String duplicate = stored.replace("\"schemaVersion\":1", "\"schemaVersion\":1,\"schemaVersion\":1"); - assertThatThrownBy( - () -> - WorldCanonicalInstanceLifecycleEvidence.fromStored( - duplicate.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + duplicate.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> Request.fromStored(new byte[] {(byte) 0xc3, 0x28})) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("strict UTF-8"); - assertThatThrownBy( - () -> - WorldCanonicalInstanceLifecycleEvidence.fromStored(new byte[] {(byte) 0xc3, 0x28})) + assertThatThrownBy(() -> + WorldCanonicalInstanceLifecycleEvidence.fromStored(new byte[] {(byte) 0xc3, 0x28})) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("strict UTF-8"); @@ -632,38 +602,35 @@ void rejectsClosedJsonAndProtobufUnknownOrDuplicateFields() throws Exception { .toBuilder() .setUnknownFields(unknown) .build(); - assertThatThrownBy( - () -> - WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse(evidence.request(), response)) + assertThatThrownBy(() -> + WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse(evidence.request(), response)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse( - evidence.request(), - ReadWorldCanonicalInstanceLifecycleResponse.newBuilder() - .setCanonicalResponseBytes(ByteString.EMPTY) - .build())) + assertThatThrownBy(() -> + WorldCanonicalInstanceLifecycleGrpcCodec.fromResponse( + evidence.request(), + ReadWorldCanonicalInstanceLifecycleResponse.newBuilder() + .setCanonicalResponseBytes(ByteString.EMPTY) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("required"); } private static void assertRejectedRequest( WorldCanonicalInstanceLifecycleEvidence evidence, Request changed, String message) { - assertThatThrownBy( - () -> - with( - evidence, - changed, - evidence.launchBinding(), - evidence.startLocation(), - evidence.runtimeRoomInstanceId(), - evidence.lifecycleStatus(), - evidence.lifecycleEpoch(), - evidence.rowVersion(), - evidence.captureId(), - evidence.graphSha256(), - evidence.preparationInputDigest())) + assertThatThrownBy(() -> + with( + evidence, + changed, + evidence.launchBinding(), + evidence.startLocation(), + evidence.runtimeRoomInstanceId(), + evidence.lifecycleStatus(), + evidence.lifecycleEpoch(), + evidence.rowVersion(), + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(message); } @@ -673,20 +640,19 @@ private static void assertInvalid( long runtimeRoomInstanceId, long lifecycleEpoch, long rowVersion) { - assertThatThrownBy( - () -> - with( - evidence, - evidence.request(), - evidence.launchBinding(), - evidence.startLocation(), - runtimeRoomInstanceId, - evidence.lifecycleStatus(), - lifecycleEpoch, - rowVersion, - evidence.captureId(), - evidence.graphSha256(), - evidence.preparationInputDigest())) + assertThatThrownBy(() -> + with( + evidence, + evidence.request(), + evidence.launchBinding(), + evidence.startLocation(), + runtimeRoomInstanceId, + evidence.lifecycleStatus(), + lifecycleEpoch, + rowVersion, + evidence.captureId(), + evidence.graphSha256(), + evidence.preparationInputDigest())) .isInstanceOf(IllegalArgumentException.class); } @@ -764,10 +730,9 @@ private static void assertInvalidStoredAssignments( String stored, String assignmentField, String replacement, String message) { String malformed = stored.replace(assignmentField, "\"operationalRegionAssignments\":" + replacement); - assertThatThrownBy( - () -> - WorldCanonicalInstanceLifecycleEvidence.fromStored( - malformed.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + WorldCanonicalInstanceLifecycleEvidence.fromStored( + malformed.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining(message); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidenceTest.java index 9534727da0..cc1d5ccbc2 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldDraftStartLocationEvidenceTest.java @@ -107,18 +107,17 @@ void fromStoredRejectsNilNoncanonicalAndDigestSubstitutedFields() throws Excepti assertRejected(changed(change)); } - assertThatThrownBy( - () -> - WorldDraftStartLocationEvidence.create( - "invalid/namespace", - OPERATION_ID, - REQUEST_ID, - COMMIT_ID, - FENCE_ID, - ACCOUNT_BINDING_DIGEST, - BINDING_DIGEST, - START_LOCATION, - GRAPH_DIGEST)) + assertThatThrownBy(() -> + WorldDraftStartLocationEvidence.create( + "invalid/namespace", + OPERATION_ID, + REQUEST_ID, + COMMIT_ID, + FENCE_ID, + ACCOUNT_BINDING_DIGEST, + BINDING_DIGEST, + START_LOCATION, + GRAPH_DIGEST)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalEvidenceTest.java index 245dae1b3f..a51c89a9a1 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalEvidenceTest.java @@ -119,10 +119,8 @@ void rejectsMissingFenceChangedResultAndAlteredReceiptIdentity() throws Exceptio null, nextActive(request.worldActivationRequest().preparing())); - assertThatThrownBy( - () -> - WorldOriginalStartSessionActivationTerminalEvidence.create( - protection, committed, 0L)) + assertThatThrownBy(() -> + WorldOriginalStartSessionActivationTerminalEvidence.create(protection, committed, 0L)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("positive"); var changedRequest = @@ -135,10 +133,9 @@ void rejectsMissingFenceChangedResultAndAlteredReceiptIdentity() throws Exceptio WorldCanonicalInstanceActivation.Outcome.COMMITTED, null, nextActive(changedRequest.preparing())); - assertThatThrownBy( - () -> - WorldOriginalStartSessionActivationTerminalEvidence.create( - protection, substitutedResult, WORLD_FENCE)) + assertThatThrownBy(() -> + WorldOriginalStartSessionActivationTerminalEvidence.create( + protection, substitutedResult, WORLD_FENCE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("differs from the original Account-protected"); @@ -293,19 +290,18 @@ private static Fixture fixture() throws Exception { null); List participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - owner, - Long.toString(descriptor.versionId()), - false, - null, - selector.appliedCommitId(), - selector.contentDigest(), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - "GAME_LOGIC".equals(owner), - "GAME_LOGIC".equals(owner) ? "sha256:" + "2".repeat(64) : null)) + .map(owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.appliedCommitId(), + selector.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "2".repeat(64) : null)) .toList(); var release = AuthoredWorldReleaseAttestationEvidence.create( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadGrpcCodecTest.java index f0f7f806e0..abe8b06085 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionActivationTerminalReadGrpcCodecTest.java @@ -16,10 +16,9 @@ void rejectsDuplicateFieldsBeforeEvidenceDecoding() { .addSchemaVersion(1) .build(); - assertThatThrownBy( - () -> - WorldOriginalStartSessionActivationTerminalReadGrpcCodec.fromRequest( - duplicate, "world-runtime")) + assertThatThrownBy(() -> + WorldOriginalStartSessionActivationTerminalReadGrpcCodec.fromRequest( + duplicate, "world-runtime")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("duplicate field"); } @@ -34,10 +33,9 @@ void rejectsUnknownFieldsBeforeEvidenceDecoding() { .build()) .build(); - assertThatThrownBy( - () -> - WorldOriginalStartSessionActivationTerminalReadGrpcCodec.fromRequest( - unknown, "world-runtime")) + assertThatThrownBy(() -> + WorldOriginalStartSessionActivationTerminalReadGrpcCodec.fromRequest( + unknown, "world-runtime")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionProtectedActivationGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionProtectedActivationGrpcCodecTest.java index 03f5190f44..a5afebc909 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionProtectedActivationGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldOriginalStartSessionProtectedActivationGrpcCodecTest.java @@ -48,10 +48,9 @@ void rejectsDuplicateUnknownOrMissingOuterFieldsBeforeInputUse() { .addTargetNamespace("world-runtime") .addAcquisitionInput(nested) .build(); - assertThatThrownBy( - () -> - WorldOriginalStartSessionProtectedActivationGrpcCodec.fromRequest( - duplicate, "world-runtime")) + assertThatThrownBy(() -> + WorldOriginalStartSessionProtectedActivationGrpcCodec.fromRequest( + duplicate, "world-runtime")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("duplicate"); @@ -65,18 +64,15 @@ void rejectsDuplicateUnknownOrMissingOuterFieldsBeforeInputUse() { .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build()) .build(); - assertThatThrownBy( - () -> - WorldOriginalStartSessionProtectedActivationGrpcCodec.fromRequest( - unknown, "world-runtime")) + assertThatThrownBy(() -> + WorldOriginalStartSessionProtectedActivationGrpcCodec.fromRequest( + unknown, "world-runtime")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - WorldOriginalStartSessionProtectedActivationGrpcCodec.fromRequest( - ActivateOriginalStartSessionProtectedRequest.getDefaultInstance(), - "world-runtime")) + assertThatThrownBy(() -> + WorldOriginalStartSessionProtectedActivationGrpcCodec.fromRequest( + ActivateOriginalStartSessionProtectedRequest.getDefaultInstance(), "world-runtime")) .isInstanceOf(IllegalArgumentException.class); } @@ -84,10 +80,9 @@ void rejectsDuplicateUnknownOrMissingOuterFieldsBeforeInputUse() { void rejectsMissingResponseReceiptAndOversizedResponseCarrier() { var empty = ActivateOriginalStartSessionProtectedResponse.newBuilder().addSchemaVersion(1).build(); - assertThatThrownBy( - () -> - WorldOriginalStartSessionProtectedActivationGrpcCodec.fromResponse( - mockInput(), "world-runtime", empty)) + assertThatThrownBy(() -> + WorldOriginalStartSessionProtectedActivationGrpcCodec.fromResponse( + mockInput(), "world-runtime", empty)) .isInstanceOf(IllegalArgumentException.class); assertThat(WorldOriginalStartSessionProtectedActivationGrpcCodec.MAX_RESPONSE_WIRE_BYTES) diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientMtlsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientMtlsTest.java index 2fa794f011..6776f19810 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientMtlsTest.java @@ -130,10 +130,9 @@ void trustedWrongWorldWorkloadAndNamespaceReleaseNoRequestMetadataOrBody() throw client.init(); assertThatThrownBy(() -> client.read(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - exception -> - assertThat(Status.fromThrowable(exception).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(exception -> + assertThat(Status.fromThrowable(exception).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(headers).hasValue(0); assertThat(bodies).hasValue(0); stopTransport(); @@ -167,10 +166,9 @@ void rejectsResponseAboveExplicitWireLimitAtGrpcTransport() throws Exception { assertThatThrownBy(() -> client.read(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - exception -> - assertThat(Status.fromThrowable(exception).getCode()) - .isEqualTo(Status.Code.RESOURCE_EXHAUSTED)); + .satisfies(exception -> + assertThat(Status.fromThrowable(exception).getCode()) + .isEqualTo(Status.Code.RESOURCE_EXHAUSTED)); assertThat(headers).hasValue(1); assertThat(bodies).hasValue(1); } @@ -186,19 +184,17 @@ void rejectsWrongLocalWorkloadPlaintextAndNonFileBackedTls() throws Exception { var plaintext = pki.clientProperties(tempDirectory, pki.entityClient()); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new WorldPublishedSpawnRequirementsClient( - endpoints(server), plaintext, new GrpcChannelFactory(), NAMESPACE)) + assertThatThrownBy(() -> + new WorldPublishedSpawnRequirementsClient( + endpoints(server), plaintext, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("workload mTLS"); var classpath = pki.clientProperties(tempDirectory, pki.entityClient()); classpath.setCaCert("classpath:ca.crt"); - assertThatThrownBy( - () -> - new WorldPublishedSpawnRequirementsClient( - endpoints(server), classpath, new GrpcChannelFactory(), NAMESPACE)) + assertThatThrownBy(() -> + new WorldPublishedSpawnRequirementsClient( + endpoints(server), classpath, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("file-backed"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientTest.java index 1e73376529..be83a9089d 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsClientTest.java @@ -14,13 +14,12 @@ class WorldPublishedSpawnRequirementsClientTest { void rejectsPlaintextAndInvalidNamespaceBeforeCreatingTransport() { var plaintext = new CommonGrpcClientProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new WorldPublishedSpawnRequirementsClient( - new ServiceEndpointsProperties(), - plaintext, - mock(GrpcChannelFactory.class), - "test")) + assertThatThrownBy(() -> + new WorldPublishedSpawnRequirementsClient( + new ServiceEndpointsProperties(), + plaintext, + mock(GrpcChannelFactory.class), + "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("workload mTLS"); @@ -28,10 +27,9 @@ void rejectsPlaintextAndInvalidNamespaceBeforeCreatingTransport() { tls.setCertChain(Path.of("missing.crt").toString()); tls.setPrivateKey(Path.of("missing.key").toString()); tls.setCaCert(Path.of("missing-ca.crt").toString()); - assertThatThrownBy( - () -> - new WorldPublishedSpawnRequirementsClient( - new ServiceEndpointsProperties(), tls, mock(GrpcChannelFactory.class), "Test")) + assertThatThrownBy(() -> + new WorldPublishedSpawnRequirementsClient( + new ServiceEndpointsProperties(), tls, mock(GrpcChannelFactory.class), "Test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical DNS label"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidenceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidenceTest.java index b2a8dcec71..7b4069375f 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidenceTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsEvidenceTest.java @@ -34,38 +34,36 @@ void deniesDuplicateIdentityAndNonIncreasingRevisionOrder() { var first = evidence.spawnRequirements().get(0); var second = evidence.spawnRequirements().get(1); - assertThatThrownBy( - () -> - new WorldPublishedSpawnRequirementsEvidence( - evidence.request(), - evidence.launchBinding(), - evidence.captureId(), - evidence.graphDigest(), - evidence.familyCounts(), - List.of( - first, - new WorldPublishedSpawnRequirementsEvidence.SpawnRequirement( - "9007199254740994", - second.revisionId(), - first.spawnBindingId(), - second.roomTemplate(), - second.entityTemplate(), - second.spawnCount(), - second.respawnDelaySeconds())), - evidence.generationRequirements())) + assertThatThrownBy(() -> + new WorldPublishedSpawnRequirementsEvidence( + evidence.request(), + evidence.launchBinding(), + evidence.captureId(), + evidence.graphDigest(), + evidence.familyCounts(), + List.of( + first, + new WorldPublishedSpawnRequirementsEvidence.SpawnRequirement( + "9007199254740994", + second.revisionId(), + first.spawnBindingId(), + second.roomTemplate(), + second.entityTemplate(), + second.spawnCount(), + second.respawnDelaySeconds())), + evidence.generationRequirements())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("binding identity"); - assertThatThrownBy( - () -> - new WorldPublishedSpawnRequirementsEvidence( - evidence.request(), - evidence.launchBinding(), - evidence.captureId(), - evidence.graphDigest(), - evidence.familyCounts(), - List.of(second, first), - evidence.generationRequirements())) + assertThatThrownBy(() -> + new WorldPublishedSpawnRequirementsEvidence( + evidence.request(), + evidence.launchBinding(), + evidence.captureId(), + evidence.graphDigest(), + evidence.familyCounts(), + List.of(second, first), + evidence.generationRequirements())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("strictly increasing revision order"); } @@ -74,16 +72,15 @@ void deniesDuplicateIdentityAndNonIncreasingRevisionOrder() { void bindsGraphDigestToTheReleaseSelectorReceipt() { var evidence = WorldPublishedSpawnRequirementsGrpcCodecTest.evidence(); - assertThatThrownBy( - () -> - new WorldPublishedSpawnRequirementsEvidence( - evidence.request(), - evidence.launchBinding(), - evidence.captureId(), - "sha256:" + "f".repeat(64), - evidence.familyCounts(), - evidence.spawnRequirements(), - evidence.generationRequirements())) + assertThatThrownBy(() -> + new WorldPublishedSpawnRequirementsEvidence( + evidence.request(), + evidence.launchBinding(), + evidence.captureId(), + "sha256:" + "f".repeat(64), + evidence.familyCounts(), + evidence.spawnRequirements(), + evidence.generationRequirements())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("graph digest"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodecTest.java index bb83428378..68a5197587 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedSpawnRequirementsGrpcCodecTest.java @@ -70,10 +70,8 @@ void acceptsTheMaximumResponseWireSizeAndRejectsOneByteOver() { response, WorldPublishedSpawnRequirementsGrpcCodec.MAX_RESPONSE_WIRE_BYTES + 1); assertThat(overLimit.getSerializedSize()) .isEqualTo(WorldPublishedSpawnRequirementsGrpcCodec.MAX_RESPONSE_WIRE_BYTES + 1); - assertThatThrownBy( - () -> - WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( - expected.request(), overLimit)) + assertThatThrownBy(() -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse(expected.request(), overLimit)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("maximum wire size"); } @@ -84,55 +82,48 @@ void rejectsChangedRequestScopeReleaseAndMalformedCapture() { var response = WorldPublishedSpawnRequirementsGrpcCodec.toResponse(expected.request(), expected); - assertThatThrownBy( - () -> - WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( - expected.request(), - response.toBuilder() - .setRequest( - response.getRequest().toBuilder().setReadRequestId(OTHER_ID.toString())) - .build())) + assertThatThrownBy(() -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setRequest( + response.getRequest().toBuilder().setReadRequestId(OTHER_ID.toString())) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( - expected.request(), - response.toBuilder().setGraphDigest("sha256:" + "f".repeat(64)).build())) + assertThatThrownBy(() -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder().setGraphDigest("sha256:" + "f".repeat(64)).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("graph digest"); - assertThatThrownBy( - () -> - WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( - expected.request(), - response.toBuilder() - .setRequest( - response.getRequest().toBuilder() - .setExpectedReleaseAttestationDigest("sha256:" + "f".repeat(64))) - .build())) + assertThatThrownBy(() -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setExpectedReleaseAttestationDigest("sha256:" + "f".repeat(64))) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("changed the exact source-read request"); - assertThatThrownBy( - () -> - WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( - expected.request(), - response.toBuilder() - .setCompleteLaunchBinding( - response.getCompleteLaunchBinding().toBuilder() - .setReleaseAttestation( - response - .getCompleteLaunchBinding() - .getReleaseAttestation() - .toBuilder() - .setCanonicalTenantId(OTHER_ID.toString()))) - .build())) + assertThatThrownBy(() -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setCompleteLaunchBinding( + response.getCompleteLaunchBinding().toBuilder() + .setReleaseAttestation( + response + .getCompleteLaunchBinding() + .getReleaseAttestation() + .toBuilder() + .setCanonicalTenantId(OTHER_ID.toString()))) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( - expected.request(), - response.toBuilder() - .setCaptureId("00000000-0000-0000-0000-000000000000") - .build())) + assertThatThrownBy(() -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder().setCaptureId("00000000-0000-0000-0000-000000000000").build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("captureId"); } @@ -142,75 +133,68 @@ void rejectsMissingNestedEvidenceUnknownFieldsAndChangedAuthoredScope() { var expected = evidence(); var response = WorldPublishedSpawnRequirementsGrpcCodec.toResponse(expected.request(), expected); - assertThatThrownBy( - () -> - WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( - expected.request(), response.toBuilder().clearRequest().build())) + assertThatThrownBy(() -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), response.toBuilder().clearRequest().build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( - expected.request(), response.toBuilder().clearCompleteLaunchBinding().build())) + assertThatThrownBy(() -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), response.toBuilder().clearCompleteLaunchBinding().build())) .isInstanceOf(IllegalArgumentException.class); UnknownFieldSet unknown = UnknownFieldSet.newBuilder() .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); - assertThatThrownBy( - () -> - WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( - expected.request(), response.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), response.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( - expected.request(), - response.toBuilder() - .setRequest(response.getRequest().toBuilder().setUnknownFields(unknown)) - .build())) + assertThatThrownBy(() -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setRequest(response.getRequest().toBuilder().setUnknownFields(unknown)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( - expected.request(), - response.toBuilder() - .setRequest( - response.getRequest().toBuilder() - .setLaunchBindingRequest( - response.getRequest().getLaunchBindingRequest().toBuilder() - .setUnknownFields(unknown))) - .build())) + assertThatThrownBy(() -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setLaunchBindingRequest( + response.getRequest().getLaunchBindingRequest().toBuilder() + .setUnknownFields(unknown))) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( - expected.request(), - response.toBuilder() - .setSpawnRequirements( - 0, - response.getSpawnRequirements(0).toBuilder() - .setRoomTemplate( - response.getSpawnRequirements(0).getRoomTemplate().toBuilder() - .setTenantId(OTHER_ID.toString()))) - .build())) + assertThatThrownBy(() -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setSpawnRequirements( + 0, + response.getSpawnRequirements(0).toBuilder() + .setRoomTemplate( + response.getSpawnRequirements(0).getRoomTemplate().toBuilder() + .setTenantId(OTHER_ID.toString()))) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical tenant/version context"); - assertThatThrownBy( - () -> - WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( - expected.request(), - response.toBuilder() - .setSpawnRequirements( - 0, - response.getSpawnRequirements(0).toBuilder() - .setRoomTemplate( - response.getSpawnRequirements(0).getRoomTemplate().toBuilder() - .setUnknownFields(unknown))) - .build())) + assertThatThrownBy(() -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + expected.request(), + response.toBuilder() + .setSpawnRequirements( + 0, + response.getSpawnRequirements(0).toBuilder() + .setRoomTemplate( + response.getSpawnRequirements(0).getRoomTemplate().toBuilder() + .setUnknownFields(unknown))) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); } @@ -236,43 +220,39 @@ void requiresAllSixExplicitCountsAndRejectsCountListMismatch() { .setFamily(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_GENERATION_RULE) .setCount(1) .build(); - assertThatThrownBy( - () -> - new WorldPublishedSpawnRequirementsEvidence( - populated.request(), - populated.launchBinding(), - populated.captureId(), - populated.graphDigest(), - List.of( - populated.familyCounts().get(0), - populated.familyCounts().get(1), - populated.familyCounts().get(2), - populated.familyCounts().get(3), - new WorldPublishedSpawnRequirementsEvidence.FamilyCount( - badCount.getFamily(), badCount.getCount()), - populated.familyCounts().get(5)), - populated.spawnRequirements(), - populated.generationRequirements())) + assertThatThrownBy(() -> + new WorldPublishedSpawnRequirementsEvidence( + populated.request(), + populated.launchBinding(), + populated.captureId(), + populated.graphDigest(), + List.of( + populated.familyCounts().get(0), + populated.familyCounts().get(1), + populated.familyCounts().get(2), + populated.familyCounts().get(3), + new WorldPublishedSpawnRequirementsEvidence.FamilyCount( + badCount.getFamily(), badCount.getCount()), + populated.familyCounts().get(5)), + populated.spawnRequirements(), + populated.generationRequirements())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("count differs"); - assertThatThrownBy( - () -> - WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( - populated.request(), - response.toBuilder() - .setFamilyCounts(4, response.getFamilyCounts(4).toBuilder().setCount(1)) - .build())) + assertThatThrownBy(() -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + populated.request(), + response.toBuilder() + .setFamilyCounts(4, response.getFamilyCounts(4).toBuilder().setCount(1)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("count differs"); - assertThatThrownBy( - () -> - WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( - empty.request(), - emptyResponse.toBuilder() - .setFamilyCounts( - 0, emptyResponse.getFamilyCounts(0).toBuilder().clearCount()) - .build())) + assertThatThrownBy(() -> + WorldPublishedSpawnRequirementsGrpcCodec.fromResponse( + empty.request(), + emptyResponse.toBuilder() + .setFamilyCounts(0, emptyResponse.getFamilyCounts(0).toBuilder().clearCount()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("not explicitly present"); } @@ -457,19 +437,18 @@ private static CompleteLaunchBindingEvidence completeBinding() { "remap-set"); var participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - owner, - Long.toString(descriptor.versionId()), - false, - null, - selection.appliedCommitId(), - "b".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - "GAME_LOGIC".equals(owner), - "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .map(owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selection.appliedCommitId(), + "b".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) .toList(); AuthoredWorldReleaseAttestationEvidence release = AuthoredWorldReleaseAttestationEvidence.create( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClientTest.java index ef8eb74b79..6ce1615384 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationClientTest.java @@ -33,10 +33,9 @@ void rejectsPlaintextAndWrongNamespaceBeforeCreatingTransport(@TempDir Path dire var channelFactory = mock(GrpcChannelFactory.class); var plaintext = tls(directory); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new WorldPublishedStartLocationClient( - new ServiceEndpointsProperties(), plaintext, channelFactory, "test")) + assertThatThrownBy(() -> + new WorldPublishedStartLocationClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("workload mTLS"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java index 3d9ce13d9e..62dc1f4335 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldPublishedStartLocationGrpcCodecTest.java @@ -45,49 +45,43 @@ void rejectsChangedSelectionAndSubstitutedReceiptAccountOrAppliedBytes() throws ReadWorldPublishedStartLocationResponse response = WorldPublishedStartLocationGrpcCodec.toResponse(evidence.request(), evidence); - assertThatThrownBy( - () -> - WorldPublishedStartLocationGrpcCodec.fromResponse( - evidence.request(), - response.toBuilder() - .setPublicationFence( - uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString()) - .build())) + assertThatThrownBy(() -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setPublicationFence(uuid("dddddddd-dddd-4ddd-8ddd-dddddddddddd").toString()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("changed exact selection"); - assertThatThrownBy( - () -> - WorldPublishedStartLocationGrpcCodec.fromResponse( - evidence.request(), - response.toBuilder() - .setSelectorReceiptBytes(ByteString.copyFrom(new byte[] {1})) - .build())) + assertThatThrownBy(() -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setSelectorReceiptBytes(ByteString.copyFrom(new byte[] {1})) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldPublishedStartLocationGrpcCodec.fromResponse( - evidence.request(), - response.toBuilder() - .setOriginalAccountBindingBytes(ByteString.copyFrom(new byte[] {1})) - .build())) + assertThatThrownBy(() -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setOriginalAccountBindingBytes(ByteString.copyFrom(new byte[] {1})) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldPublishedStartLocationGrpcCodec.fromResponse( - evidence.request(), - response.toBuilder() - .setAppliedResultBytes(ByteString.copyFrom(new byte[] {1})) - .build())) + assertThatThrownBy(() -> + WorldPublishedStartLocationGrpcCodec.fromResponse( + evidence.request(), + response.toBuilder() + .setAppliedResultBytes(ByteString.copyFrom(new byte[] {1})) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new WorldPublishedStartLocationEvidence( - evidence.request(), - evidence.selectorReceiptBytes(), - evidence.originalAccountBindingBytes(), - new byte[] {1})) + assertThatThrownBy(() -> + new WorldPublishedStartLocationEvidence( + evidence.request(), + evidence.selectorReceiptBytes(), + evidence.originalAccountBindingBytes(), + new byte[] {1})) .isInstanceOf(IllegalArgumentException.class); var changedIntake = @@ -105,13 +99,12 @@ void rejectsChangedSelectionAndSubstitutedReceiptAccountOrAppliedBytes() throws evidence.request().contentDigest(), evidence.request().digestSchemaVersion(), evidence.request().worldAffectedTuples()); - assertThatThrownBy( - () -> - new WorldPublishedStartLocationEvidence( - changedIntake, - evidence.selectorReceiptBytes(), - evidence.originalAccountBindingBytes(), - evidence.appliedResultBytes())) + assertThatThrownBy(() -> + new WorldPublishedStartLocationEvidence( + changedIntake, + evidence.selectorReceiptBytes(), + evidence.originalAccountBindingBytes(), + evidence.appliedResultBytes())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("intake request"); } @@ -167,15 +160,14 @@ private static UUID uuid(String value) { private static void assertInvalidExpectedEpoch( WorldPublishedStartLocationEvidence.OwnedAffectedTuple template, String expectedEpoch) { - assertThatThrownBy( - () -> - new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( - template.owner(), - template.aggregateType(), - template.aggregateId(), - template.scopeType(), - template.scopeId(), - expectedEpoch)) + assertThatThrownBy(() -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + template.owner(), + template.aggregateType(), + template.aggregateId(), + template.scopeType(), + template.scopeId(), + expectedEpoch)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical non-negative decimal"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClientTest.java index ec3a991993..9ffd58b2a2 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClientTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadClientTest.java @@ -68,12 +68,11 @@ void closeReleasesClientMonitorBeforeDrainingCertificateCallback(@TempDir Path d GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); when(channelFactory.buildChannel( eq("world.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) - .thenAnswer( - invocation -> { - ManagedChannel channel = mock(ManagedChannel.class); - channels.add(channel); - return channel; - }); + .thenAnswer(invocation -> { + ManagedChannel channel = mock(ManagedChannel.class); + channels.add(channel); + return channel; + }); client = new WorldStartSessionExecutionTerminalReadClient( endpoints, tls, channelFactory, "world-runtime"); @@ -235,25 +234,23 @@ void requiresFileBackedMtlsInitializationAndAnIndependentCallerTransaction( @TempDir Path directory) throws Exception { var plaintext = fileBacked(directory); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new WorldStartSessionExecutionTerminalReadClient( - new ServiceEndpointsProperties(), - plaintext, - new GrpcChannelFactory(), - "world-runtime")) + assertThatThrownBy(() -> + new WorldStartSessionExecutionTerminalReadClient( + new ServiceEndpointsProperties(), + plaintext, + new GrpcChannelFactory(), + "world-runtime")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mTLS"); var classpath = fileBacked(directory); classpath.setCaCert("classpath:ca.crt"); - assertThatThrownBy( - () -> - new WorldStartSessionExecutionTerminalReadClient( - new ServiceEndpointsProperties(), - classpath, - new GrpcChannelFactory(), - "world-runtime")) + assertThatThrownBy(() -> + new WorldStartSessionExecutionTerminalReadClient( + new ServiceEndpointsProperties(), + classpath, + new GrpcChannelFactory(), + "world-runtime")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("file-backed"); diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodecTest.java index ffe9ba7080..f5ae908320 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalReadGrpcCodecTest.java @@ -78,36 +78,32 @@ void rejectsUnknownFieldsMalformedIdentityAndMixedNamespaceBeforeUse() { .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) .build(); - assertThatThrownBy( - () -> - WorldStartSessionExecutionTerminalReadGrpcCodec.fromRequest( - WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request).toBuilder() - .setUnknownFields(unknown) - .build())) + assertThatThrownBy(() -> + WorldStartSessionExecutionTerminalReadGrpcCodec.fromRequest( + WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request).toBuilder() + .setUnknownFields(unknown) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - WorldStartSessionExecutionTerminalReadGrpcCodec.fromRequest( - WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request).toBuilder() - .setReadRequestId("d1f41bfb-265a-4f3b-8b2a-124cba20ce43 ") - .build())) + assertThatThrownBy(() -> + WorldStartSessionExecutionTerminalReadGrpcCodec.fromRequest( + WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request).toBuilder() + .setReadRequestId("d1f41bfb-265a-4f3b-8b2a-124cba20ce43 ") + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical non-nil UUID"); - assertThatThrownBy( - () -> - WorldStartSessionExecutionTerminalReadGrpcCodec.fromRequest( - WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request).toBuilder() - .setAccountWorldParticipationFence(0L) - .build())) + assertThatThrownBy(() -> + WorldStartSessionExecutionTerminalReadGrpcCodec.fromRequest( + WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request).toBuilder() + .setAccountWorldParticipationFence(0L) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("positive"); - assertThatThrownBy( - () -> - WorldStartSessionExecutionTerminalReadGrpcCodec.fromRequest( - WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request).toBuilder() - .setTargetNamespace("other-runtime") - .build())) + assertThatThrownBy(() -> + WorldStartSessionExecutionTerminalReadGrpcCodec.fromRequest( + WorldStartSessionExecutionTerminalReadGrpcCodec.toRequest(request).toBuilder() + .setTargetNamespace("other-runtime") + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("differs from the exact original"); } @@ -140,17 +136,15 @@ void rejectsSubstitutedTerminalIdentityOrReadCorrelation() { .setCanonicalTerminalBytes( com.google.protobuf.ByteString.copyFrom(valid.canonicalBytes())) .build(); - assertThatThrownBy( - () -> - WorldStartSessionExecutionTerminalReadGrpcCodec.fromResponse( - request, changedCorrelation)) + assertThatThrownBy(() -> + WorldStartSessionExecutionTerminalReadGrpcCodec.fromResponse( + request, changedCorrelation)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("changed the exact"); - assertThatThrownBy( - () -> - WorldStartSessionExecutionTerminalReadGrpcCodec.fromResponse( - request, changedCorrelation.toBuilder().setUnknownFields(unknown()).build())) + assertThatThrownBy(() -> + WorldStartSessionExecutionTerminalReadGrpcCodec.fromResponse( + request, changedCorrelation.toBuilder().setUnknownFields(unknown()).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalTest.java index 9ae8b909ce..dc434a3611 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/world/WorldStartSessionExecutionTerminalTest.java @@ -288,58 +288,55 @@ void retainsEveryBindingAndFenceAndRejectsScopeSubstitution() throws Exception { Outcome.COMMITTED), original); - assertThatThrownBy( - () -> - new WorldStartSessionExecutionTerminal( - tuple.canonicalBytes(), - PARTICIPATION_ID, - 31L, - GAME_SESSION_ATTEMPT_ID, - 37L, - "another-runtime", - TENANT, - REQUEST_ID, - GAME_INSTANCE_ID, - digest(PREPARATION_INPUT), - PREPARATION_INPUT, - 41L, - Outcome.COMMITTED)) + assertThatThrownBy(() -> + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + "another-runtime", + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("scope"); - assertThatThrownBy( - () -> - new WorldStartSessionExecutionTerminal( - tuple.canonicalBytes(), - PARTICIPATION_ID, - 31L, - GAME_SESSION_ATTEMPT_ID, - 37L, - NAMESPACE, - uuid("d4053e2e-598d-47bd-b7d3-4288e702e276"), - REQUEST_ID, - GAME_INSTANCE_ID, - digest(PREPARATION_INPUT), - PREPARATION_INPUT, - 41L, - Outcome.COMMITTED)) + assertThatThrownBy(() -> + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + uuid("d4053e2e-598d-47bd-b7d3-4288e702e276"), + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("scope"); - assertThatThrownBy( - () -> - new WorldStartSessionExecutionTerminal( - tuple.canonicalBytes(), - PARTICIPATION_ID, - 31L, - GAME_SESSION_ATTEMPT_ID, - 37L, - NAMESPACE, - TENANT, - "substituted-request-id", - GAME_INSTANCE_ID, - digest(PREPARATION_INPUT), - PREPARATION_INPUT, - 41L, - Outcome.COMMITTED)) + assertThatThrownBy(() -> + new WorldStartSessionExecutionTerminal( + tuple.canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + "substituted-request-id", + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("scope"); @@ -395,10 +392,9 @@ void rejectsMalformedDuplicateUnknownTrailingAndNoncanonicalStoredValues() throw () -> WorldStartSessionExecutionTerminal.fromStored(new byte[] {(byte) 0xc3, 0x28})) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("strict UTF-8"); - assertThatThrownBy( - () -> - WorldStartSessionExecutionTerminal.fromStored( - new byte[WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + 1])) + assertThatThrownBy(() -> + WorldStartSessionExecutionTerminal.fromStored( + new byte[WorldStartSessionExecutionTerminal.MAX_CANONICAL_BYTES + 1])) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("byte limit"); @@ -449,40 +445,38 @@ void requiresCanonicalPositiveBigintStringsNonNilUuidsAndExactInputDigest() thro .worldExecutionFence()) .isEqualTo(Long.MAX_VALUE); - assertThatThrownBy( - () -> - new WorldStartSessionExecutionTerminal( - originalTuple().canonicalBytes(), - PARTICIPATION_ID, - 31L, - GAME_SESSION_ATTEMPT_ID, - 37L, - NAMESPACE, - TENANT, - REQUEST_ID, - GAME_INSTANCE_ID, - digest("changed input"), - PREPARATION_INPUT, - 41L, - Outcome.COMMITTED)) + assertThatThrownBy(() -> + new WorldStartSessionExecutionTerminal( + originalTuple().canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest("changed input"), + PREPARATION_INPUT, + 41L, + Outcome.COMMITTED)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("preparationInputDigest"); - assertThatThrownBy( - () -> - new WorldStartSessionExecutionTerminal( - originalTuple().canonicalBytes(), - PARTICIPATION_ID, - 31L, - GAME_SESSION_ATTEMPT_ID, - 37L, - NAMESPACE, - TENANT, - REQUEST_ID, - GAME_INSTANCE_ID, - digest(PREPARATION_INPUT), - "{ \"selected\" : \"different exact bytes\" }", - 41L, - Outcome.COMMITTED)) + assertThatThrownBy(() -> + new WorldStartSessionExecutionTerminal( + originalTuple().canonicalBytes(), + PARTICIPATION_ID, + 31L, + GAME_SESSION_ATTEMPT_ID, + 37L, + NAMESPACE, + TENANT, + REQUEST_ID, + GAME_INSTANCE_ID, + digest(PREPARATION_INPUT), + "{ \"selected\" : \"different exact bytes\" }", + 41L, + Outcome.COMMITTED)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("preparationInputDigest"); } @@ -578,10 +572,8 @@ private static byte[] withField(byte[] source, String field, Object replacement) } private static void assertInvalid(String value) { - assertThatThrownBy( - () -> - WorldStartSessionExecutionTerminal.fromStored( - value.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + WorldStartSessionExecutionTerminal.fromStored(value.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/account/authority/GrantAuthorityScopeCodecTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/account/authority/GrantAuthorityScopeCodecTest.java index f9a866334d..925148ad45 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/account/authority/GrantAuthorityScopeCodecTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/account/authority/GrantAuthorityScopeCodecTest.java @@ -247,21 +247,18 @@ void rejectsSlugNormalizationAndAcceptsOneByteSlugs() { .isEqualTo(minimumScope); for (String invalidSlug : new String[] {"", "World", " word", "word ", "é", "e\u0301"}) { - assertThatThrownBy( - () -> - new GrantAuthorityScopeCodec.Scope( - ACCOUNT_ID, TENANT_ID, invalidSlug, "realm", LIFECYCLE_ID)) + assertThatThrownBy(() -> + new GrantAuthorityScopeCodec.Scope( + ACCOUNT_ID, TENANT_ID, invalidSlug, "realm", LIFECYCLE_ID)) .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - new GrantAuthorityScopeCodec.Scope( - ACCOUNT_ID, TENANT_ID, "a".repeat(121), "realm", LIFECYCLE_ID)) + assertThatThrownBy(() -> + new GrantAuthorityScopeCodec.Scope( + ACCOUNT_ID, TENANT_ID, "a".repeat(121), "realm", LIFECYCLE_ID)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GrantAuthorityScopeCodec.Scope( - ACCOUNT_ID, TENANT_ID, "world", "z".repeat(121), LIFECYCLE_ID)) + assertThatThrownBy(() -> + new GrantAuthorityScopeCodec.Scope( + ACCOUNT_ID, TENANT_ID, "world", "z".repeat(121), LIFECYCLE_ID)) .isInstanceOf(IllegalArgumentException.class); assertRejectedRaw( @@ -306,17 +303,14 @@ private static String alterUnusedFinalBase64Bits(String scopeId) { } private static void assertRejectedScopeId(String scopeId) { - assertThatThrownBy( - () -> - GrantAuthorityScopeCodec.parseScopeId(scopeId, GrantAuthorityScopeCodec.V1_BOUNDS)) + assertThatThrownBy(() -> + GrantAuthorityScopeCodec.parseScopeId(scopeId, GrantAuthorityScopeCodec.V1_BOUNDS)) .isInstanceOf(IllegalArgumentException.class); } private static void assertRejectedOutboxKey(String key) { - assertThatThrownBy( - () -> - GrantAuthorityScopeCodec.parseOutboxStreamKey( - key, GrantAuthorityScopeCodec.V1_BOUNDS)) + assertThatThrownBy(() -> + GrantAuthorityScopeCodec.parseOutboxStreamKey(key, GrantAuthorityScopeCodec.V1_BOUNDS)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/account/authority/RealmGrantAuthorityEventV1CodecTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/account/authority/RealmGrantAuthorityEventV1CodecTest.java index 0142d3d9c4..8d1ca62d27 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/account/authority/RealmGrantAuthorityEventV1CodecTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/account/authority/RealmGrantAuthorityEventV1CodecTest.java @@ -406,209 +406,196 @@ void acceptsNfcReasonAtItsUtf8LimitAndRejectsOverLimitOrNonNfcReason() { .auditReason()) .isEqualTo(multibyteAtLimit); - assertThatThrownBy( - () -> - preimage( - REQUEST_ID, - GRANT, - 2, - GENERATION, - "ACTIVE", - EXPIRED_AT, - ACTOR_ID, - "CREATE", - MUTATION_DIGEST, - String.valueOf((char) 1).repeat(4097), - 7)) + assertThatThrownBy(() -> + preimage( + REQUEST_ID, + GRANT, + 2, + GENERATION, + "ACTIVE", + EXPIRED_AT, + ACTOR_ID, + "CREATE", + MUTATION_DIGEST, + String.valueOf((char) 1).repeat(4097), + 7)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("4096 UTF-8 bytes"); - assertThatThrownBy( - () -> - preimage( - REQUEST_ID, - GRANT, - 2, - GENERATION, - "ACTIVE", - EXPIRED_AT, - ACTOR_ID, - "CREATE", - MUTATION_DIGEST, - "before" + (char) 0 + "after", - 7)) + assertThatThrownBy(() -> + preimage( + REQUEST_ID, + GRANT, + 2, + GENERATION, + "ACTIVE", + EXPIRED_AT, + ACTOR_ID, + "CREATE", + MUTATION_DIGEST, + "before" + (char) 0 + "after", + 7)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("NUL"); - assertThatThrownBy( - () -> - preimage( - REQUEST_ID, - GRANT, - 2, - GENERATION, - "ACTIVE", - EXPIRED_AT, - ACTOR_ID, - "CREATE", - MUTATION_DIGEST, - "é".repeat(2049), - 7)) + assertThatThrownBy(() -> + preimage( + REQUEST_ID, + GRANT, + 2, + GENERATION, + "ACTIVE", + EXPIRED_AT, + ACTOR_ID, + "CREATE", + MUTATION_DIGEST, + "é".repeat(2049), + 7)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("4096 UTF-8 bytes"); - assertThatThrownBy( - () -> - preimage( - REQUEST_ID, - GRANT, - 2, - GENERATION, - "ACTIVE", - EXPIRED_AT, - ACTOR_ID, - "CREATE", - MUTATION_DIGEST, - "cafe" + (char) 0x0301, - 7)) + assertThatThrownBy(() -> + preimage( + REQUEST_ID, + GRANT, + 2, + GENERATION, + "ACTIVE", + EXPIRED_AT, + ACTOR_ID, + "CREATE", + MUTATION_DIGEST, + "cafe" + (char) 0x0301, + 7)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("NFC"); - assertThatThrownBy( - () -> - preimage( - REQUEST_ID, - GRANT, - 2, - GENERATION, - "ACTIVE", - EXPIRED_AT, - ACTOR_ID, - "CREATE", - MUTATION_DIGEST, - String.valueOf((char) 0x0085), - 7)) + assertThatThrownBy(() -> + preimage( + REQUEST_ID, + GRANT, + 2, + GENERATION, + "ACTIVE", + EXPIRED_AT, + ACTOR_ID, + "CREATE", + MUTATION_DIGEST, + String.valueOf((char) 0x0085), + 7)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("must not be blank"); } @Test void rejectsInvalidCountersStatesMutationsDigestsAndNilIdentities() { - assertThatThrownBy( - () -> - preimage( - REQUEST_ID, - GRANT, - 0, - GENERATION, - "ACTIVE", - EXPIRED_AT, - ACTOR_ID, - "CREATE", - MUTATION_DIGEST, - AUDIT_REASON, - 7)) + assertThatThrownBy(() -> + preimage( + REQUEST_ID, + GRANT, + 0, + GENERATION, + "ACTIVE", + EXPIRED_AT, + ACTOR_ID, + "CREATE", + MUTATION_DIGEST, + AUDIT_REASON, + 7)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - preimage( - REQUEST_ID, - GRANT, - 2, - GENERATION, - "ACTIVE", - EXPIRED_AT, - ACTOR_ID, - "CREATE", - MUTATION_DIGEST, - AUDIT_REASON, - -1)) + assertThatThrownBy(() -> + preimage( + REQUEST_ID, + GRANT, + 2, + GENERATION, + "ACTIVE", + EXPIRED_AT, + ACTOR_ID, + "CREATE", + MUTATION_DIGEST, + AUDIT_REASON, + -1)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - preimage( - REQUEST_ID, - GRANT, - 2, - GENERATION, - "UNKNOWN", - EXPIRED_AT, - ACTOR_ID, - "CREATE", - MUTATION_DIGEST, - AUDIT_REASON, - 7)) + assertThatThrownBy(() -> + preimage( + REQUEST_ID, + GRANT, + 2, + GENERATION, + "UNKNOWN", + EXPIRED_AT, + ACTOR_ID, + "CREATE", + MUTATION_DIGEST, + AUDIT_REASON, + 7)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - preimage( - REQUEST_ID, - GRANT, - 2, - GENERATION, - "ACTIVE", - EXPIRED_AT, - ACTOR_ID, - "DELETE", - MUTATION_DIGEST, - AUDIT_REASON, - 7)) + assertThatThrownBy(() -> + preimage( + REQUEST_ID, + GRANT, + 2, + GENERATION, + "ACTIVE", + EXPIRED_AT, + ACTOR_ID, + "DELETE", + MUTATION_DIGEST, + AUDIT_REASON, + 7)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - preimage( - REQUEST_ID, - GRANT, - 2, - GENERATION, - "ACTIVE", - EXPIRED_AT, - ACTOR_ID, - "CREATE", - "sha256:" + MUTATION_DIGEST, - AUDIT_REASON, - 7)) + assertThatThrownBy(() -> + preimage( + REQUEST_ID, + GRANT, + 2, + GENERATION, + "ACTIVE", + EXPIRED_AT, + ACTOR_ID, + "CREATE", + "sha256:" + MUTATION_DIGEST, + AUDIT_REASON, + 7)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - preimage( - new UUID(0L, 0L), - GRANT, - 2, - GENERATION, - "ACTIVE", - EXPIRED_AT, - ACTOR_ID, - "CREATE", - MUTATION_DIGEST, - AUDIT_REASON, - 7)) + assertThatThrownBy(() -> + preimage( + new UUID(0L, 0L), + GRANT, + 2, + GENERATION, + "ACTIVE", + EXPIRED_AT, + ACTOR_ID, + "CREATE", + MUTATION_DIGEST, + AUDIT_REASON, + 7)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - preimage( - REQUEST_ID, - GRANT, - 2, - GENERATION, - "ACTIVE", - EXPIRED_AT, - new UUID(0L, 0L), - "CREATE", - MUTATION_DIGEST, - AUDIT_REASON, - 7)) + assertThatThrownBy(() -> + preimage( + REQUEST_ID, + GRANT, + 2, + GENERATION, + "ACTIVE", + EXPIRED_AT, + new UUID(0L, 0L), + "CREATE", + MUTATION_DIGEST, + AUDIT_REASON, + 7)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - preimage( - REQUEST_ID, - GRANT, - 2, - GENERATION, - "REVOKED", - EXPIRED_AT, - ACTOR_ID, - "CREATE", - MUTATION_DIGEST, - AUDIT_REASON, - 7)) + assertThatThrownBy(() -> + preimage( + REQUEST_ID, + GRANT, + 2, + GENERATION, + "REVOKED", + EXPIRED_AT, + ACTOR_ID, + "CREATE", + MUTATION_DIGEST, + AUDIT_REASON, + 7)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/authoring/DraftCommitBindingTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/authoring/DraftCommitBindingTest.java index 7e02ff59a5..031216e1be 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/authoring/DraftCommitBindingTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/authoring/DraftCommitBindingTest.java @@ -82,19 +82,17 @@ void rejectsMissingOrNonArrayStoredCollections() { ObjectNode missingRevisions = (ObjectNode) json.readTree(original.canonicalJson()); missingRevisions.remove("revisions"); - assertThatThrownBy( - () -> - DraftCommitBinding.fromStored( - json.writeValueAsString(missingRevisions), original.digest())) + assertThatThrownBy(() -> + DraftCommitBinding.fromStored( + json.writeValueAsString(missingRevisions), original.digest())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("corrupt"); ObjectNode invalidAffectedUnits = (ObjectNode) json.readTree(original.canonicalJson()); invalidAffectedUnits.put("affectedUnits", "not-an-array"); - assertThatThrownBy( - () -> - DraftCommitBinding.fromStored( - json.writeValueAsString(invalidAffectedUnits), original.digest())) + assertThatThrownBy(() -> + DraftCommitBinding.fromStored( + json.writeValueAsString(invalidAffectedUnits), original.digest())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("corrupt"); } @@ -102,37 +100,34 @@ void rejectsMissingOrNonArrayStoredCollections() { @Test void rejectsOmittedDuplicateOrInconsistentCanonicalOrder() { DraftCommitBinding original = binding(); - assertThatThrownBy( - () -> - DraftCommitBinding.create( - original.target(), - original.requestId(), - original.commitId(), - original.baseCommitId(), - List.of(original.revisions().get(0)), - original.affectedUnits())) + assertThatThrownBy(() -> + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + List.of(original.revisions().get(0)), + original.affectedUnits())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("owner set"); - assertThatThrownBy( - () -> - DraftCommitBinding.create( - original.target(), - original.requestId(), - original.commitId(), - original.baseCommitId(), - List.of(original.revisions().get(0), original.revisions().get(0)), - original.affectedUnits())) + assertThatThrownBy(() -> + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + List.of(original.revisions().get(0), original.revisions().get(0)), + original.affectedUnits())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical array order"); - assertThatThrownBy( - () -> - DraftCommitBinding.create( - original.target(), - original.requestId(), - original.commitId(), - original.baseCommitId(), - original.revisions(), - List.of(original.affectedUnits().get(0), original.affectedUnits().get(0)))) + assertThatThrownBy(() -> + DraftCommitBinding.create( + original.target(), + original.requestId(), + original.commitId(), + original.baseCommitId(), + original.revisions(), + List.of(original.affectedUnits().get(0), original.affectedUnits().get(0)))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("duplicate affected"); } @@ -141,39 +136,36 @@ void rejectsOmittedDuplicateOrInconsistentCanonicalOrder() { void rejectsNonCanonicalCountersAndNilOrUnprovedTargetIdentity() { DraftCommitBinding original = binding(); AffectedUnit affected = original.affectedUnits().getFirst(); - assertThatThrownBy( - () -> - new AffectedUnit( - affected.owner(), - affected.aggregateType(), - affected.aggregateId(), - affected.scopeType(), - affected.scopeId(), - "01")) + assertThatThrownBy(() -> + new AffectedUnit( + affected.owner(), + affected.aggregateType(), + affected.aggregateId(), + affected.scopeType(), + affected.scopeId(), + "01")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical nonnegative decimal"); - assertThatThrownBy( - () -> - new TargetProof( - new UUID(0L, 0L), - original.target().canonicalVersionId(), - 1, - "tenant-source", - 2, - "tenant-source", - "NEW_GAME_ROW")) + assertThatThrownBy(() -> + new TargetProof( + new UUID(0L, 0L), + original.target().canonicalVersionId(), + 1, + "tenant-source", + 2, + "tenant-source", + "NEW_GAME_ROW")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical non-nil UUID"); - assertThatThrownBy( - () -> - new TargetProof( - original.target().canonicalTenantId(), - original.target().canonicalVersionId(), - 1, - "tenant-source", - 2, - "different-source", - "NEW_GAME_ROW")) + assertThatThrownBy(() -> + new TargetProof( + original.target().canonicalTenantId(), + original.target().canonicalVersionId(), + 1, + "tenant-source", + 2, + "different-source", + "NEW_GAME_ROW")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("must match exactly"); } diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalogTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalogTest.java index 99cc58e22d..5edba01249 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalogTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/automation/AutomationRuntimeFamilyCatalogTest.java @@ -120,10 +120,8 @@ void unknownDuplicateMissingInconsistentAndTrailingCatalogFieldsRefuse() { CATALOG.replace("Namespace and actor class unresolved; no clone.", ""), CATALOG + "{}" }) { - assertThatThrownBy( - () -> - AutomationRuntimeFamilyCatalog.fromStored( - invalid.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AutomationRuntimeFamilyCatalog.fromStored(invalid.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); } } @@ -162,16 +160,13 @@ void familyFactGapAndSourceBoundsAreIndependentOfNoPayloadRows() { CATALOG.replace(FACT, ""), CATALOG.replace(GAP, "") }) { - assertThatThrownBy( - () -> - AutomationRuntimeFamilyCatalog.fromStored( - invalid.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AutomationRuntimeFamilyCatalog.fromStored(invalid.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - AutomationRuntimeFamilyCatalog.fromStored( - new byte[AutomationRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 1])) + assertThatThrownBy(() -> + AutomationRuntimeFamilyCatalog.fromStored( + new byte[AutomationRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 1])) .isInstanceOf(IllegalArgumentException.class); } @@ -183,61 +178,52 @@ void duplicateUnknownOversizedAndChangedCorrelationWireValuesRefuse() { UnknownFieldSet.newBuilder() .addField(9, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); - assertThatThrownBy( - () -> - AutomationRuntimeFamilyCatalogCodec.fromRequest( - request.toBuilder() - .addCanonicalRequestBytes(request.getCanonicalRequestBytes(0)) - .build())) + assertThatThrownBy(() -> + AutomationRuntimeFamilyCatalogCodec.fromRequest( + request.toBuilder() + .addCanonicalRequestBytes(request.getCanonicalRequestBytes(0)) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AutomationRuntimeFamilyCatalogCodec.fromRequest( - request.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + AutomationRuntimeFamilyCatalogCodec.fromRequest( + request.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AutomationRuntimeFamilyCatalogCodec.fromRequest( - request.toBuilder() - .setCanonicalRequestBytes(0, ByteString.copyFrom(new byte[1025])) - .build())) + assertThatThrownBy(() -> + AutomationRuntimeFamilyCatalogCodec.fromRequest( + request.toBuilder() + .setCanonicalRequestBytes(0, ByteString.copyFrom(new byte[1025])) + .build())) .isInstanceOf(IllegalArgumentException.class); var evidence = new Evidence(read, UUID.randomUUID(), catalog()); var response = AutomationRuntimeFamilyCatalogCodec.toResponse(read, evidence); - assertThatThrownBy( - () -> - AutomationRuntimeFamilyCatalogCodec.fromResponse( - new Request(UUID.randomUUID(), "test"), response)) + assertThatThrownBy(() -> + AutomationRuntimeFamilyCatalogCodec.fromResponse( + new Request(UUID.randomUUID(), "test"), response)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AutomationRuntimeFamilyCatalogCodec.fromResponse( - new Request(read.readRequestId(), "other"), response)) + assertThatThrownBy(() -> + AutomationRuntimeFamilyCatalogCodec.fromResponse( + new Request(read.readRequestId(), "other"), response)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AutomationRuntimeFamilyCatalogCodec.fromResponse( - read, - response.toBuilder() - .addCanonicalResponseBytes(response.getCanonicalResponseBytes(0)) - .build())) + assertThatThrownBy(() -> + AutomationRuntimeFamilyCatalogCodec.fromResponse( + read, + response.toBuilder() + .addCanonicalResponseBytes(response.getCanonicalResponseBytes(0)) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AutomationRuntimeFamilyCatalogCodec.fromResponse( - read, response.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + AutomationRuntimeFamilyCatalogCodec.fromResponse( + read, response.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AutomationRuntimeFamilyCatalogCodec.fromResponse( - read, - response.toBuilder() - .setCanonicalResponseBytes( - 0, - ByteString.copyFrom( - new byte - [AutomationRuntimeFamilyCatalogCodec.MAX_RESPONSE_BYTES + 1])) - .build())) + assertThatThrownBy(() -> + AutomationRuntimeFamilyCatalogCodec.fromResponse( + read, + response.toBuilder() + .setCanonicalResponseBytes( + 0, + ByteString.copyFrom( + new byte[AutomationRuntimeFamilyCatalogCodec.MAX_RESPONSE_BYTES + 1])) + .build())) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogTest.java index dd6ea6870d..78f02e56f3 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/entity/EntityRuntimeFamilyCatalogTest.java @@ -105,25 +105,23 @@ void conditionalAndUnresolvedAreExplicitFactsNotSuccessfulRowClassifications() { FreshDisposition.BLOCKING_HOLDER_CLOSURE) .stateClass()) .isEqualTo(StateClass.CONDITIONAL_HOLDER); - assertThatThrownBy( - () -> - new Family( - "item_instances", - "item_instances", - "", - Role.RUNTIME_PAYLOAD, - StateClass.S3, - FreshDisposition.BLOCKING_HOLDER_CLOSURE)) + assertThatThrownBy(() -> + new Family( + "item_instances", + "item_instances", + "", + Role.RUNTIME_PAYLOAD, + StateClass.S3, + FreshDisposition.BLOCKING_HOLDER_CLOSURE)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new Family( - "item_visible_ref_counters", - "item_visible_ref_counters", - "", - Role.ALLOCATOR, - StateClass.S3, - FreshDisposition.BLOCKING_ALLOCATOR_CLASS)) + assertThatThrownBy(() -> + new Family( + "item_visible_ref_counters", + "item_visible_ref_counters", + "", + Role.ALLOCATOR, + StateClass.S3, + FreshDisposition.BLOCKING_ALLOCATOR_CLASS)) .isInstanceOf(IllegalArgumentException.class); } @@ -178,10 +176,9 @@ void arrayAndByteBoundsDoNotDependOnPayloadAbsence() { assertThatThrownBy( () -> EntityRuntimeFamilyCatalog.fromStored(invalid.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - EntityRuntimeFamilyCatalog.fromStored( - new byte[EntityRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 1])) + assertThatThrownBy(() -> + EntityRuntimeFamilyCatalog.fromStored( + new byte[EntityRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 1])) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> EntityRuntimeFamilyCatalog.fromStored(new byte[] {(byte) 0xc3, 0x28})) .isInstanceOf(IllegalArgumentException.class); @@ -191,28 +188,25 @@ void arrayAndByteBoundsDoNotDependOnPayloadAbsence() { void duplicateUnknownOversizedAndChangedCorrelationFramesRefuse() { var read = request(); var wire = EntityRuntimeFamilyCatalogCodec.toRequest(read); - assertThatThrownBy( - () -> - EntityRuntimeFamilyCatalogCodec.fromRequest( - wire.toBuilder() - .addCanonicalRequestBytes(wire.getCanonicalRequestBytes(0)) - .build())) + assertThatThrownBy(() -> + EntityRuntimeFamilyCatalogCodec.fromRequest( + wire.toBuilder() + .addCanonicalRequestBytes(wire.getCanonicalRequestBytes(0)) + .build())) .isInstanceOf(IllegalArgumentException.class); var unknown = UnknownFieldSet.newBuilder() .addField(9, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); - assertThatThrownBy( - () -> - EntityRuntimeFamilyCatalogCodec.fromRequest( - wire.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + EntityRuntimeFamilyCatalogCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - EntityRuntimeFamilyCatalogCodec.fromRequest( - wire.toBuilder() - .setCanonicalRequestBytes(0, ByteString.copyFrom(new byte[1025])) - .build())) + assertThatThrownBy(() -> + EntityRuntimeFamilyCatalogCodec.fromRequest( + wire.toBuilder() + .setCanonicalRequestBytes(0, ByteString.copyFrom(new byte[1025])) + .build())) .isInstanceOf(IllegalArgumentException.class); var evidence = new Evidence(read, UUID.randomUUID(), catalog()); var response = EntityRuntimeFamilyCatalogCodec.toResponse(read, evidence); @@ -232,10 +226,9 @@ void duplicateUnknownOversizedAndChangedCorrelationFramesRefuse() { .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> EntityRuntimeFamilyCatalogCodec.fromResponse(request(), response)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - EntityRuntimeFamilyCatalogCodec.fromResponse( - new Request(read.readRequestId(), "other"), response)) + assertThatThrownBy(() -> + EntityRuntimeFamilyCatalogCodec.fromResponse( + new Request(read.readRequestId(), "other"), response)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> new Request(new UUID(0, 0), "test")) .isInstanceOf(IllegalArgumentException.class); diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/CurrentPrivatePlaytestLifecycleReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/CurrentPrivatePlaytestLifecycleReadGrpcCodecTest.java index 030457e230..1e24083ba1 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/CurrentPrivatePlaytestLifecycleReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/CurrentPrivatePlaytestLifecycleReadGrpcCodecTest.java @@ -75,17 +75,15 @@ void responseRejectsChangedCorrelationUnknownFieldsAndTrailingFrames() { assertThatThrownBy( () -> CurrentPrivatePlaytestLifecycleReadGrpcCodec.fromResponse(otherRequest, response)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CurrentPrivatePlaytestLifecycleReadGrpcCodec.fromResponse( - expected, - response.toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField( - 99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) - .build()) - .build())) + assertThatThrownBy(() -> + CurrentPrivatePlaytestLifecycleReadGrpcCodec.fromResponse( + expected, + response.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class); ByteArrayOutputStream trailing = new ByteArrayOutputStream(); @@ -102,46 +100,41 @@ void responseRejectsChangedCorrelationUnknownFieldsAndTrailingFrames() { @Test void requestAndResponseEnforceWireBoundsAndRequiredCanonicalPayload() { - assertThatThrownBy( - () -> - CurrentPrivatePlaytestLifecycleReadGrpcCodec.parseRequest( - net.firedevops.firemud.gamesession.v1.ReadCurrentPrivatePlaytestLifecycleRequest - .getDefaultInstance())) + assertThatThrownBy(() -> + CurrentPrivatePlaytestLifecycleReadGrpcCodec.parseRequest( + net.firedevops.firemud.gamesession.v1.ReadCurrentPrivatePlaytestLifecycleRequest + .getDefaultInstance())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CurrentPrivatePlaytestLifecycleReadGrpcCodec.parseRequest( - net.firedevops.firemud.gamesession.v1.ReadCurrentPrivatePlaytestLifecycleRequest - .newBuilder() - .setCanonicalEvidence( - ByteString.copyFrom( - new byte - [CurrentPrivatePlaytestLifecycleReadGrpcCodec - .MAX_REQUEST_WIRE_BYTES])) - .build())) + assertThatThrownBy(() -> + CurrentPrivatePlaytestLifecycleReadGrpcCodec.parseRequest( + net.firedevops.firemud.gamesession.v1.ReadCurrentPrivatePlaytestLifecycleRequest + .newBuilder() + .setCanonicalEvidence( + ByteString.copyFrom( + new byte + [CurrentPrivatePlaytestLifecycleReadGrpcCodec + .MAX_REQUEST_WIRE_BYTES])) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CurrentPrivatePlaytestLifecycleReadGrpcCodec.parseRequest( - CurrentPrivatePlaytestLifecycleReadGrpcCodec.toRequest(request()).toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField( - 99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) - .build()) - .build())) + assertThatThrownBy(() -> + CurrentPrivatePlaytestLifecycleReadGrpcCodec.parseRequest( + CurrentPrivatePlaytestLifecycleReadGrpcCodec.toRequest(request()).toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CurrentPrivatePlaytestLifecycleReadGrpcCodec.fromResponse( - request(), - ReadCurrentPrivatePlaytestLifecycleResponse.newBuilder() - .setCanonicalEvidence( - ByteString.copyFrom( - new byte - [CurrentPrivatePlaytestLifecycleReadGrpcCodec - .MAX_RESPONSE_WIRE_BYTES])) - .build())) + assertThatThrownBy(() -> + CurrentPrivatePlaytestLifecycleReadGrpcCodec.fromResponse( + request(), + ReadCurrentPrivatePlaytestLifecycleResponse.newBuilder() + .setCanonicalEvidence( + ByteString.copyFrom( + new byte + [CurrentPrivatePlaytestLifecycleReadGrpcCodec + .MAX_RESPONSE_WIRE_BYTES])) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -153,65 +146,63 @@ void snapshotRejectsImpossibleReadStateAndSelectionAfterObservation() { assertThat(snapshotAt(valid, ReadState.EXPIRED, valid.forkExpiresAt()).readState()) .isEqualTo(ReadState.EXPIRED); - assertThatThrownBy( - () -> - new Snapshot( - valid.scope(), - valid.selectionRequestId(), - valid.selectionHeadRevision(), - valid.selectionRequestDigest(), - valid.selectedAt(), - valid.preparationRequestId(), - valid.preparationRequestDigest(), - valid.playtestLifecycleId(), - valid.playableStateNamespaceId(), - valid.playtestStateGeneration(), - valid.forkExpiresAt(), - valid.preparationState(), - ReadState.EXPIRED, - valid.observedAt(), - valid.canonicalVersionId(), - valid.sourceCatalogRealmId(), - valid.sourceCatalogRequestId(), - valid.sourceCatalogRevision(), - valid.publishedReleaseBundleRef(), - valid.publishedReleaseBundleDigest(), - valid.privatePolicyId(), - valid.privatePolicyDigest(), - valid.policySourceCommitId(), - valid.policySourceRevisionId(), - valid.policyLogicalRevisionId(), - valid.policySetDigest())) + assertThatThrownBy(() -> + new Snapshot( + valid.scope(), + valid.selectionRequestId(), + valid.selectionHeadRevision(), + valid.selectionRequestDigest(), + valid.selectedAt(), + valid.preparationRequestId(), + valid.preparationRequestDigest(), + valid.playtestLifecycleId(), + valid.playableStateNamespaceId(), + valid.playtestStateGeneration(), + valid.forkExpiresAt(), + valid.preparationState(), + ReadState.EXPIRED, + valid.observedAt(), + valid.canonicalVersionId(), + valid.sourceCatalogRealmId(), + valid.sourceCatalogRequestId(), + valid.sourceCatalogRevision(), + valid.publishedReleaseBundleRef(), + valid.publishedReleaseBundleDigest(), + valid.privatePolicyId(), + valid.privatePolicyDigest(), + valid.policySourceCommitId(), + valid.policySourceRevisionId(), + valid.policyLogicalRevisionId(), + valid.policySetDigest())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new Snapshot( - valid.scope(), - valid.selectionRequestId(), - valid.selectionHeadRevision(), - valid.selectionRequestDigest(), - valid.observedAt().plusSeconds(1), - valid.preparationRequestId(), - valid.preparationRequestDigest(), - valid.playtestLifecycleId(), - valid.playableStateNamespaceId(), - valid.playtestStateGeneration(), - valid.forkExpiresAt(), - valid.preparationState(), - valid.readState(), - valid.observedAt(), - valid.canonicalVersionId(), - valid.sourceCatalogRealmId(), - valid.sourceCatalogRequestId(), - valid.sourceCatalogRevision(), - valid.publishedReleaseBundleRef(), - valid.publishedReleaseBundleDigest(), - valid.privatePolicyId(), - valid.privatePolicyDigest(), - valid.policySourceCommitId(), - valid.policySourceRevisionId(), - valid.policyLogicalRevisionId(), - valid.policySetDigest())) + assertThatThrownBy(() -> + new Snapshot( + valid.scope(), + valid.selectionRequestId(), + valid.selectionHeadRevision(), + valid.selectionRequestDigest(), + valid.observedAt().plusSeconds(1), + valid.preparationRequestId(), + valid.preparationRequestDigest(), + valid.playtestLifecycleId(), + valid.playableStateNamespaceId(), + valid.playtestStateGeneration(), + valid.forkExpiresAt(), + valid.preparationState(), + valid.readState(), + valid.observedAt(), + valid.canonicalVersionId(), + valid.sourceCatalogRealmId(), + valid.sourceCatalogRequestId(), + valid.sourceCatalogRevision(), + valid.publishedReleaseBundleRef(), + valid.publishedReleaseBundleDigest(), + valid.privatePolicyId(), + valid.privatePolicyDigest(), + valid.policySourceCommitId(), + valid.policySourceRevisionId(), + valid.policyLogicalRevisionId(), + valid.policySetDigest())) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/GameSessionRuntimeFamilyCatalogTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/GameSessionRuntimeFamilyCatalogTest.java index 8bee859382..c0924cb34b 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/GameSessionRuntimeFamilyCatalogTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/GameSessionRuntimeFamilyCatalogTest.java @@ -32,12 +32,11 @@ class GameSessionRuntimeFamilyCatalogTest { """; private static final String GAPS = Arrays.stream(GapId.values()) - .map( - id -> - "{\"id\":\"" - + id.name() - + "\",\"disposition\":\"UNRESOLVED_BLOCKING\"," - + "\"ownerConsequence\":\"Controlled known non-SQL gap, not a complete Redis census.\"}") + .map(id -> + "{\"id\":\"" + + id.name() + + "\",\"disposition\":\"UNRESOLVED_BLOCKING\"," + + "\"ownerConsequence\":\"Controlled known non-SQL gap, not a complete Redis census.\"}") .collect(Collectors.joining(",")); private static final String PREFIX = """ @@ -127,10 +126,8 @@ void closedSchemaRejectsUnknownDuplicateMissingWrongTypedInconsistentAndTrailing CATALOG.replace("sha256:" + "a".repeat(64), "sha256:" + "A".repeat(64)), CATALOG + "{}" }) { - assertThatThrownBy( - () -> - GameSessionRuntimeFamilyCatalog.fromStored( - invalid.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + GameSessionRuntimeFamilyCatalog.fromStored(invalid.getBytes(StandardCharsets.UTF_8))) .as(invalid) .isInstanceOf(IllegalArgumentException.class); } @@ -158,16 +155,13 @@ void completeFamilyFactAndKnownGapSetsAreBoundedWithoutPartialSuccess() { CATALOG.replace(GAPS, firstGap), CATALOG.replace("Namespace and replacement class unresolved; no clone.", "x".repeat(1025)) }) { - assertThatThrownBy( - () -> - GameSessionRuntimeFamilyCatalog.fromStored( - invalid.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + GameSessionRuntimeFamilyCatalog.fromStored(invalid.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - GameSessionRuntimeFamilyCatalog.fromStored( - new byte[GameSessionRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 1])) + assertThatThrownBy(() -> + GameSessionRuntimeFamilyCatalog.fromStored( + new byte[GameSessionRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 1])) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> GameSessionRuntimeFamilyCatalog.fromStored(new byte[] {(byte) 0xc3, 0x28})) @@ -186,10 +180,9 @@ void catalogAtTheExactByteBoundRoundTripsWithoutTruncationOrReserialization() { GameSessionRuntimeFamilyCatalogCodec.evidenceFromStored( GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(evidence))) .isEqualTo(evidence); - assertThatThrownBy( - () -> - GameSessionRuntimeFamilyCatalog.fromStored( - Arrays.copyOf(complete, complete.length + 1))) + assertThatThrownBy(() -> + GameSessionRuntimeFamilyCatalog.fromStored( + Arrays.copyOf(complete, complete.length + 1))) .isInstanceOf(IllegalArgumentException.class); } @@ -211,10 +204,8 @@ void exactOrderedTableAndComponentCoverageCannotOmitOrReorderAFamily() { complete.replace(FACT + "," + laterFact, FACT), complete.replace("\"familyId\":\"gameplay_command\"", "\"familyId\":\"other\"") }) { - assertThatThrownBy( - () -> - GameSessionRuntimeFamilyCatalog.fromStored( - invalid.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + GameSessionRuntimeFamilyCatalog.fromStored(invalid.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java index da3848fcf0..5cfccfd6c1 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptClientMtlsTest.java @@ -110,10 +110,9 @@ void rejectsWrongClientPeerAndChangedGameSessionServerPeer() throws Exception { assertThatThrownBy( () -> client.read(OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); assertThat(lastPeerUri).hasValue(OTHER_CLIENT_URI); assertThat(calls).hasValue(1); } @@ -126,10 +125,9 @@ void rejectsWrongClientPeerAndChangedGameSessionServerPeer() throws Exception { assertThatThrownBy( () -> client.read(OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(calls).hasValue(callsBeforeWrongServer); } } @@ -197,10 +195,9 @@ void boundsUnavailableReadWithFiveSecondRpcDeadline() throws Exception { assertThatThrownBy( () -> client.read(OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); } } @@ -209,10 +206,9 @@ void requiresMutualTlsFileBackedCredentialsAndExplicitInitialization() throws Ex var endpoints = new ServiceEndpointsProperties(); var plaintext = pki.clientProperties(tempDirectory, pki.accountClient()); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new GrpcOriginalStartSessionCurrentAttemptClient( - endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + assertThatThrownBy(() -> + new GrpcOriginalStartSessionCurrentAttemptClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mTLS"); diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java index b827d51273..5dfa28240f 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceGrpcCodecTest.java @@ -73,18 +73,14 @@ void rejectsUnknownFieldsChangedEchoPhaseProjectionDigestAndMalformedSelectors() request, Instant.parse("2030-01-01T00:00:00Z"), request.canonicalPostAuthorizationTuple())); - assertThatThrownBy( - () -> - OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( - request, response.toBuilder().setPhaseState("COMMITTED").build())) + assertThatThrownBy(() -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, response.toBuilder().setPhaseState("COMMITTED").build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( - request, - response.toBuilder() - .setAccountRedemptionProjectionDigest("0".repeat(64)) - .build())) + assertThatThrownBy(() -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, + response.toBuilder().setAccountRedemptionProjectionDigest("0".repeat(64)).build())) .isInstanceOf(IllegalArgumentException.class); var unknownTimestamp = response.toBuilder() @@ -96,27 +92,24 @@ void rejectsUnknownFieldsChangedEchoPhaseProjectionDigestAndMalformedSelectors() .build()) .build()) .build(); - assertThatThrownBy( - () -> - OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( - request, unknownTimestamp)) + assertThatThrownBy(() -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + request, unknownTimestamp)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( - new Request( - UUID.fromString("04444444-4444-4444-8444-444444444444"), - "world-runtime", - request.canonicalPostAuthorizationTuple(), - ATTEMPT, - MUTATION, - 8L), - response)) + assertThatThrownBy(() -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( + new Request( + UUID.fromString("04444444-4444-4444-8444-444444444444"), + "world-runtime", + request.canonicalPostAuthorizationTuple(), + ATTEMPT, + MUTATION, + 8L), + response)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest( - wire.toBuilder().setExpectedOwnerFence(0L).build())) + assertThatThrownBy(() -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromRequest( + wire.toBuilder().setExpectedOwnerFence(0L).build())) .isInstanceOf(IllegalArgumentException.class); } @@ -147,10 +140,9 @@ void rejectsGoogleTimestampSecondsOutsideRangeOnEncodingAndDecoding() { new Instant[] { Instant.ofEpochSecond(-62_135_596_801L), Instant.ofEpochSecond(253_402_300_800L) }) { - assertThatThrownBy( - () -> - OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( - new Result(request, outside, projection))) + assertThatThrownBy(() -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse( + new Result(request, outside, projection))) .isInstanceOf(IllegalArgumentException.class); } @@ -163,10 +155,8 @@ void rejectsGoogleTimestampSecondsOutsideRangeOnEncodingAndDecoding() { .setOriginalLeaseExpiresAt( Timestamp.newBuilder().setSeconds(outsideSeconds).setNanos(0).build()) .build(); - assertThatThrownBy( - () -> - OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( - request, response)) + assertThatThrownBy(() -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse(request, response)) .isInstanceOf(IllegalArgumentException.class); } } @@ -190,10 +180,8 @@ void rejectsInvalidGoogleTimestampNanosOnDecoding() { .setNanos(invalidNanos) .build()) .build(); - assertThatThrownBy( - () -> - OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse( - request, response)) + assertThatThrownBy(() -> + OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.fromResponse(request, response)) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceTest.java index 7ef734d94c..103cc54ce9 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/OriginalStartSessionCurrentAttemptEvidenceTest.java @@ -62,12 +62,11 @@ void rejectsChangedNamespaceNilCorrelationAttemptMutationAndNonpositiveFence() { assertThatThrownBy(() -> new Request(READ_ID, "world-runtime", tuple, ATTEMPT, MUTATION, 0L)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("positive"); - assertThatThrownBy( - () -> - new Result( - new Request(READ_ID, "world-runtime", tuple, ATTEMPT, MUTATION, 8L), - java.time.Instant.EPOCH, - new byte[0])) + assertThatThrownBy(() -> + new Result( + new Request(READ_ID, "world-runtime", tuple, ATTEMPT, MUTATION, 8L), + java.time.Instant.EPOCH, + new byte[0])) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("projection"); } diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/PrivateWorldPreparationReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/PrivateWorldPreparationReadGrpcCodecTest.java index d70eecf1db..073d5f20be 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/PrivateWorldPreparationReadGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/PrivateWorldPreparationReadGrpcCodecTest.java @@ -51,33 +51,30 @@ void selectedBuildFramesBindFreshReadSourceAndExactWorldSelector() throws Except () -> PrivateWorldPreparationBuildGrpcCodec.fromResponse(request(snapshot), wire)) .isInstanceOf(IllegalArgumentException.class); var unrelated = snapshot(); - assertThatThrownBy( - () -> - new PrivateWorldPreparationBuildGrpcCodec.Build( - new PrivateWorldPreparationReadEvidence.Evidence(request(unrelated), unrelated), - world)) + assertThatThrownBy(() -> + new PrivateWorldPreparationBuildGrpcCodec.Build( + new PrivateWorldPreparationReadEvidence.Evidence(request(unrelated), unrelated), + world)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - PrivateWorldPreparationBuildGrpcCodec.fromResponse( - request, - wire.toBuilder() - .setCanonicalEvidence( - ByteString.copyFrom( - new byte - [PrivateWorldPreparationBuildGrpcCodec.MAX_RESPONSE_WIRE_BYTES - + 1])) - .build())) + assertThatThrownBy(() -> + PrivateWorldPreparationBuildGrpcCodec.fromResponse( + request, + wire.toBuilder() + .setCanonicalEvidence( + ByteString.copyFrom( + new byte + [PrivateWorldPreparationBuildGrpcCodec.MAX_RESPONSE_WIRE_BYTES + + 1])) + .build())) .isInstanceOf(IllegalArgumentException.class); var unknown = com.google.protobuf.UnknownFieldSet.newBuilder() .addField( 2, com.google.protobuf.UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); - assertThatThrownBy( - () -> - PrivateWorldPreparationBuildGrpcCodec.fromResponse( - request, wire.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + PrivateWorldPreparationBuildGrpcCodec.fromResponse( + request, wire.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class); } @@ -110,18 +107,16 @@ void pendingProtectionFramesBindOperationRequestHoldAndCompleteSource() { assertThat(held.admissionAllowed()).isFalse(); assertThatThrownBy(() -> PrivatePreparationProtectionGrpcCodec.fromResponse(read, acquired)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - PrivatePreparationProtectionGrpcCodec.fromResponse( - new PrivatePreparationProtectionGrpcCodec.Acquire(UUID.randomUUID(), evidence), - acquired)) + assertThatThrownBy(() -> + PrivatePreparationProtectionGrpcCodec.fromResponse( + new PrivatePreparationProtectionGrpcCodec.Acquire(UUID.randomUUID(), evidence), + acquired)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - PrivatePreparationProtectionGrpcCodec.response( - new PrivatePreparationProtectionGrpcCodec.Read( - UUID.randomUUID(), held.requestId(), held.holdId(), 2, held.sourceDigest()), - held)) + assertThatThrownBy(() -> + PrivatePreparationProtectionGrpcCodec.response( + new PrivatePreparationProtectionGrpcCodec.Read( + UUID.randomUUID(), held.requestId(), held.holdId(), 2, held.sourceDigest()), + held)) .isInstanceOf(IllegalArgumentException.class); } @@ -138,19 +133,17 @@ void protectionRejectsOversizedAndUnknownWireFrames() { .addField( 99, com.google.protobuf.UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); - assertThatThrownBy( - () -> - PrivatePreparationProtectionGrpcCodec.parse( - wire.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + PrivatePreparationProtectionGrpcCodec.parse( + wire.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - PrivatePreparationProtectionGrpcCodec.parse( - wire.toBuilder() - .setCanonicalEvidence( - ByteString.copyFrom( - new byte[PrivatePreparationProtectionGrpcCodec.MAX_WIRE_BYTES + 1])) - .build())) + assertThatThrownBy(() -> + PrivatePreparationProtectionGrpcCodec.parse( + wire.toBuilder() + .setCanonicalEvidence( + ByteString.copyFrom( + new byte[PrivatePreparationProtectionGrpcCodec.MAX_WIRE_BYTES + 1])) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -185,40 +178,36 @@ void responseRequiresCanonicalRuntimeIdentityAndDigestAndRejectsV1() { var bytes = wire.getCanonicalEvidence(); int frames = frameCount(bytes); - assertThatThrownBy( - () -> - PrivateWorldPreparationReadGrpcCodec.fromResponse( - request, - wire.toBuilder() - .setCanonicalEvidence( - replaceFrame( - bytes, frames - 4, id("different-runtime-instance").toString())) - .build())) + assertThatThrownBy(() -> + PrivateWorldPreparationReadGrpcCodec.fromResponse( + request, + wire.toBuilder() + .setCanonicalEvidence( + replaceFrame( + bytes, frames - 4, id("different-runtime-instance").toString())) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - PrivateWorldPreparationReadGrpcCodec.fromResponse( - request, - wire.toBuilder() - .setCanonicalEvidence( - replaceFrame(bytes, frames - 3, "sha256:" + "b".repeat(64))) - .build())) + assertThatThrownBy(() -> + PrivateWorldPreparationReadGrpcCodec.fromResponse( + request, + wire.toBuilder() + .setCanonicalEvidence( + replaceFrame(bytes, frames - 3, "sha256:" + "b".repeat(64))) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - PrivateWorldPreparationReadGrpcCodec.fromResponse( - request, - wire.toBuilder().setCanonicalEvidence(removeFrame(bytes, frames - 2)).build())) + assertThatThrownBy(() -> + PrivateWorldPreparationReadGrpcCodec.fromResponse( + request, + wire.toBuilder().setCanonicalEvidence(removeFrame(bytes, frames - 2)).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - PrivateWorldPreparationReadGrpcCodec.fromResponse( - request, - wire.toBuilder() - .setCanonicalEvidence( - replaceFrame( - bytes, 0, "game-session-private-world-preparation-response/v1")) - .build())) + assertThatThrownBy(() -> + PrivateWorldPreparationReadGrpcCodec.fromResponse( + request, + wire.toBuilder() + .setCanonicalEvidence( + replaceFrame( + bytes, 0, "game-session-private-world-preparation-response/v1")) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -250,61 +239,48 @@ void requestAndResponseRejectUnknownTrailingOversizeAndChangedEcho() { UnknownFieldSet.newBuilder() .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); - assertThatThrownBy( - () -> - PrivateWorldPreparationReadGrpcCodec.parseRequest( - wireRequest.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + PrivateWorldPreparationReadGrpcCodec.parseRequest( + wireRequest.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - PrivateWorldPreparationReadGrpcCodec.fromResponse( - request, wireResponse.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + PrivateWorldPreparationReadGrpcCodec.fromResponse( + request, wireResponse.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - PrivateWorldPreparationReadGrpcCodec.parseRequest( - wireRequest.toBuilder() - .setCanonicalEvidence( - wireRequest - .getCanonicalEvidence() - .concat(ByteString.copyFromUtf8("0:"))) - .build())) + assertThatThrownBy(() -> + PrivateWorldPreparationReadGrpcCodec.parseRequest( + wireRequest.toBuilder() + .setCanonicalEvidence( + wireRequest.getCanonicalEvidence().concat(ByteString.copyFromUtf8("0:"))) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - PrivateWorldPreparationReadGrpcCodec.fromResponse( - request, - wireResponse.toBuilder() - .setCanonicalEvidence( - wireResponse - .getCanonicalEvidence() - .concat(ByteString.copyFromUtf8("0:"))) - .build())) + assertThatThrownBy(() -> + PrivateWorldPreparationReadGrpcCodec.fromResponse( + request, + wireResponse.toBuilder() + .setCanonicalEvidence( + wireResponse.getCanonicalEvidence().concat(ByteString.copyFromUtf8("0:"))) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - PrivateWorldPreparationReadGrpcCodec.parseRequest( - ReadPrivateWorldPreparationRequest.newBuilder() - .setCanonicalEvidence( - ByteString.copyFrom( - new byte - [PrivateWorldPreparationReadGrpcCodec.MAX_REQUEST_WIRE_BYTES])) - .build())) + assertThatThrownBy(() -> + PrivateWorldPreparationReadGrpcCodec.parseRequest( + ReadPrivateWorldPreparationRequest.newBuilder() + .setCanonicalEvidence( + ByteString.copyFrom( + new byte[PrivateWorldPreparationReadGrpcCodec.MAX_REQUEST_WIRE_BYTES])) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - PrivateWorldPreparationReadGrpcCodec.fromResponse( - request, - ReadPrivateWorldPreparationResponse.newBuilder() - .setCanonicalEvidence( - ByteString.copyFrom( - new byte - [PrivateWorldPreparationReadGrpcCodec.MAX_RESPONSE_WIRE_BYTES])) - .build())) + assertThatThrownBy(() -> + PrivateWorldPreparationReadGrpcCodec.fromResponse( + request, + ReadPrivateWorldPreparationResponse.newBuilder() + .setCanonicalEvidence( + ByteString.copyFrom( + new byte[PrivateWorldPreparationReadGrpcCodec.MAX_RESPONSE_WIRE_BYTES])) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - PrivateWorldPreparationReadGrpcCodec.fromResponse(request(snapshot), wireResponse)) + assertThatThrownBy(() -> + PrivateWorldPreparationReadGrpcCodec.fromResponse(request(snapshot), wireResponse)) .isInstanceOf(IllegalArgumentException.class); } @@ -313,48 +289,43 @@ void rejectsNoncanonicalUuidCountersAndMismatchedExpectedPreparation() { var snapshot = snapshot(); var request = request(snapshot); var bytes = PrivateWorldPreparationReadGrpcCodec.toRequest(request).getCanonicalEvidence(); - assertThatThrownBy( - () -> - PrivateWorldPreparationReadGrpcCodec.parseRequest( - ReadPrivateWorldPreparationRequest.newBuilder() - .setCanonicalEvidence( - replaceFrame( - bytes, - 3, - snapshot - .scope() - .tenantId() - .toString() - .toUpperCase(java.util.Locale.ROOT))) - .build())) + assertThatThrownBy(() -> + PrivateWorldPreparationReadGrpcCodec.parseRequest( + ReadPrivateWorldPreparationRequest.newBuilder() + .setCanonicalEvidence( + replaceFrame( + bytes, + 3, + snapshot + .scope() + .tenantId() + .toString() + .toUpperCase(java.util.Locale.ROOT))) + .build())) .isInstanceOf(IllegalArgumentException.class); var response = PrivateWorldPreparationReadGrpcCodec.toResponse(request, snapshot); - assertThatThrownBy( - () -> - PrivateWorldPreparationReadGrpcCodec.fromResponse( - request, - response.toBuilder() - .setCanonicalEvidence( - replaceFrame(response.getCanonicalEvidence(), 4, "01")) - .build())) + assertThatThrownBy(() -> + PrivateWorldPreparationReadGrpcCodec.fromResponse( + request, + response.toBuilder() + .setCanonicalEvidence(replaceFrame(response.getCanonicalEvidence(), 4, "01")) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - PrivateWorldPreparationReadGrpcCodec.toResponse( - new PrivateWorldPreparationReadGrpcCodec.Request( - UUID.randomUUID(), snapshot.scope(), UUID.randomUUID()), - snapshot)) + assertThatThrownBy(() -> + PrivateWorldPreparationReadGrpcCodec.toResponse( + new PrivateWorldPreparationReadGrpcCodec.Request( + UUID.randomUUID(), snapshot.scope(), UUID.randomUUID()), + snapshot)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new Selection( - snapshot.selection().requestId(), - null, - null, - 1, - DIGEST, - NOW, - snapshot.selection().originalRequest())) + assertThatThrownBy(() -> + new Selection( + snapshot.selection().requestId(), + null, + null, + 1, + DIGEST, + NOW, + snapshot.selection().originalRequest())) .isInstanceOf(IllegalArgumentException.class); } @@ -365,24 +336,22 @@ void malformedSourceTimestampsAndPolicyRemainCallerFrameErrors() { var wire = PrivateWorldPreparationReadGrpcCodec.toResponse(request, snapshot); // ABSENT selection: selectedAt, createdAt, forkExpiresAt and final observedAt. for (int frame : new int[] {6, 15, 16, frameCount(wire.getCanonicalEvidence()) - 1}) { - assertThatThrownBy( - () -> - PrivateWorldPreparationReadGrpcCodec.fromResponse( - request, - wire.toBuilder() - .setCanonicalEvidence( - replaceFrame(wire.getCanonicalEvidence(), frame, "not-an-instant")) - .build())) + assertThatThrownBy(() -> + PrivateWorldPreparationReadGrpcCodec.fromResponse( + request, + wire.toBuilder() + .setCanonicalEvidence( + replaceFrame(wire.getCanonicalEvidence(), frame, "not-an-instant")) + .build())) .isInstanceOf(IllegalArgumentException.class); } // RealmEntryPolicy already normalizes malformed JSON at its parsing boundary. - assertThatThrownBy( - () -> - PrivateWorldPreparationReadGrpcCodec.fromResponse( - request, - wire.toBuilder() - .setCanonicalEvidence(replaceFrame(wire.getCanonicalEvidence(), 36, "{")) - .build())) + assertThatThrownBy(() -> + PrivateWorldPreparationReadGrpcCodec.fromResponse( + request, + wire.toBuilder() + .setCanonicalEvidence(replaceFrame(wire.getCanonicalEvidence(), 36, "{")) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -406,16 +375,15 @@ void stableComparisonExcludesOnlyObservationAndCorrelationAndExpiryNeverBecomesR .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> snapshot.requireCurrentAt(snapshot.preparation().forkExpiresAt())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new Snapshot( - snapshot.scope(), - snapshot.selection(), - snapshot.preparation(), - snapshot.source(), - snapshot.target(), - snapshot.runtimeAllocation(), - snapshot.preparation().forkExpiresAt())) + assertThatThrownBy(() -> + new Snapshot( + snapshot.scope(), + snapshot.selection(), + snapshot.preparation(), + snapshot.source(), + snapshot.target(), + snapshot.runtimeAllocation(), + snapshot.preparation().forkExpiresAt())) .isInstanceOf(IllegalArgumentException.class); } @@ -481,9 +449,9 @@ private static Snapshot snapshot(long targetRevision, Scope scope, UUID canonica var policy = RealmEntryPolicy.parse( """ - {"schemaVersion":1,"worldSlug":"world","worldDisplayName":"World","realmSlug":"private", - "realmDisplayName":"Private","visible":true,"publicProduction":false,"stateScope":"ISOLATED","entryPolicy":"PRESEEDED_ONLY"} - """, + {"schemaVersion":1,"worldSlug":"world","worldDisplayName":"World","realmSlug":"private", + "realmDisplayName":"Private","visible":true,"publicProduction":false,"stateScope":"ISOLATED","entryPolicy":"PRESEEDED_ONLY"} + """, JsonMapper.builder().build()); var source = new Source( diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/StartSessionAccountRedemptionProjectionTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/StartSessionAccountRedemptionProjectionTest.java index 2973424671..7b6ab0096e 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/StartSessionAccountRedemptionProjectionTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/gamesession/StartSessionAccountRedemptionProjectionTest.java @@ -42,17 +42,15 @@ void exactLargeFencesRemainDistinctAcrossCurrentOwnerProjectionReplay() { StartSessionAccountRedemptionProjection.decodeOwnerTuple(retained) .reservationClaimFence()) .isEqualTo(fence); - assertThatCode( - () -> - StartSessionAccountRedemptionProjection.requireCurrentBinding(retained, original)) + assertThatCode(() -> + StartSessionAccountRedemptionProjection.requireCurrentBinding(retained, original)) .doesNotThrowAnyException(); assertThat(StartSessionAccountRedemptionProjection.fromOriginalTuple(original)) .containsExactly(retained); var changed = withReservationFence(baseline, fence == Long.MAX_VALUE ? fence - 1 : fence + 1); - assertThatThrownBy( - () -> - StartSessionAccountRedemptionProjection.requireCurrentBinding(retained, changed)) + assertThatThrownBy(() -> + StartSessionAccountRedemptionProjection.requireCurrentBinding(retained, changed)) .isInstanceOf(IllegalArgumentException.class); } } @@ -96,16 +94,14 @@ void independentlyRetainedOwnerTupleRejectsSourceFenceAndLinearizationSubstituti original.reservationClaimFence(), original.authorityEvidenceBundleBytes(), changedReference); - assertThatThrownBy( - () -> - StartSessionAccountRedemptionProjection.requireCurrentBinding( - ownerEvidence, substituted)) + assertThatThrownBy(() -> + StartSessionAccountRedemptionProjection.requireCurrentBinding( + ownerEvidence, substituted)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("differs"); - assertThatThrownBy( - () -> - StartSessionAccountRedemptionProjection.requireHistoricalBinding( - ownerEvidence, substituted)) + assertThatThrownBy(() -> + StartSessionAccountRedemptionProjection.requireHistoricalBinding( + ownerEvidence, substituted)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("differs"); } @@ -124,10 +120,8 @@ void ownerEvidenceRejectsChangedBundleVersionAndSourceVersion() throws Exception }) { assertThat(changed).isNotEqualTo(json); byte[] candidate = Rfc8785CanonicalJson.canonicalizeUtf8(changed); - assertThatThrownBy( - () -> - StartSessionAccountRedemptionProjection.requireCurrentBinding( - candidate, original)) + assertThatThrownBy(() -> + StartSessionAccountRedemptionProjection.requireCurrentBinding(candidate, original)) .isInstanceOf(IllegalArgumentException.class); } } @@ -157,10 +151,8 @@ void scalarV1ProjectionRemainsBytePreservedHistoricalEvidenceAndFailsCurrentUse( "issuanceFence", Long.parseLong(original.issuanceFence())))); byte[] before = oldBytes.clone(); - assertThatCode( - () -> - StartSessionAccountRedemptionProjection.requireHistoricalBinding( - oldBytes, original)) + assertThatCode(() -> + StartSessionAccountRedemptionProjection.requireHistoricalBinding(oldBytes, original)) .doesNotThrowAnyException(); assertThat(oldBytes).containsExactly(before); assertThatThrownBy( diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/RealmGrantMutationTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/RealmGrantMutationTest.java index 409e514df4..2602f70da3 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/RealmGrantMutationTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/RealmGrantMutationTest.java @@ -34,14 +34,11 @@ void operationSpecificAbsenceAndExpectedRevisionAreEnforced() { .isInstanceOf(IllegalArgumentException.class); for (Operation operation : new Operation[] {Operation.EXTEND, Operation.REVOKE, Operation.REGRANT}) { - assertThatThrownBy( - () -> - mutation( - operation, null, operation == Operation.REVOKE ? null : EXPIRY, "change")) + assertThatThrownBy(() -> + mutation(operation, null, operation == Operation.REVOKE ? null : EXPIRY, "change")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - mutation(operation, 0L, operation == Operation.REVOKE ? null : EXPIRY, "change")) + assertThatThrownBy(() -> + mutation(operation, 0L, operation == Operation.REVOKE ? null : EXPIRY, "change")) .isInstanceOf(IllegalArgumentException.class); } assertThatThrownBy(() -> mutation(Operation.REVOKE, 1L, EXPIRY, "revoke")) diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java index 0c820e4388..2ed09390eb 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionAuthorityEvidenceBundleTest.java @@ -90,15 +90,11 @@ void rejectsChangedTupleActorScopeRequestOrRawMutationDigest() throws Exception tuple.controlPlaneRequestId(), ACTOR_ID, changedAction); StartSessionPreAuthorizationReservationTuple changedRequest = tuple("other-request"); - assertThatThrownBy( - () -> - StartSessionAuthorityEvidenceBundle.decode(bytes) - .requireTupleBinding(changedDigest)) + assertThatThrownBy(() -> + StartSessionAuthorityEvidenceBundle.decode(bytes).requireTupleBinding(changedDigest)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - StartSessionAuthorityEvidenceBundle.decode(bytes) - .requireTupleBinding(changedRequest)) + assertThatThrownBy(() -> + StartSessionAuthorityEvidenceBundle.decode(bytes).requireTupleBinding(changedRequest)) .isInstanceOf(IllegalArgumentException.class); Map prefixedDigest = read(bytes); @@ -161,26 +157,20 @@ void rejectsMalformedUtf8DuplicateKeysTrailingTokensAndNoncanonicalBytes() throw assertThatThrownBy(() -> StartSessionAuthorityEvidenceBundle.decode(malformedUtf8)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - StartSessionAuthorityEvidenceBundle.decode( - duplicate.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + StartSessionAuthorityEvidenceBundle.decode(duplicate.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - StartSessionAuthorityEvidenceBundle.decode( - (new String(valid, StandardCharsets.UTF_8) + "{}") - .getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + StartSessionAuthorityEvidenceBundle.decode( + (new String(valid, StandardCharsets.UTF_8) + "{}") + .getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - StartSessionAuthorityEvidenceBundle.decode( - (new String(valid, StandardCharsets.UTF_8) + " ") - .getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + StartSessionAuthorityEvidenceBundle.decode( + (new String(valid, StandardCharsets.UTF_8) + " ").getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - StartSessionAuthorityEvidenceBundle.decode(Arrays.copyOf(valid, valid.length - 1))) + assertThatThrownBy(() -> + StartSessionAuthorityEvidenceBundle.decode(Arrays.copyOf(valid, valid.length - 1))) .isInstanceOf(IllegalArgumentException.class); } @@ -195,57 +185,50 @@ void rejectsInvalidExpiryAndReferenceOverflowOrMismatch() throws Exception { StartSessionAuthorityEvidenceBundle decoded = StartSessionAuthorityEvidenceBundle.decode(canonical(validValue(tuple))); - assertThatThrownBy( - () -> - decoded.requireReferenceBinding( - new StartSessionAuthorityEvidenceBundle.BundleReference( - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "18", "23", "17"))) + assertThatThrownBy(() -> + decoded.requireReferenceBinding( + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "18", "23", "17"))) .isInstanceOf(IllegalArgumentException.class); assertThat( - org.assertj.core.api.Assertions.catchThrowable( - () -> - decoded.requireReferenceBinding( - new StartSessionAuthorityEvidenceBundle.BundleReference( - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "24", "17")))) + org.assertj.core.api.Assertions.catchThrowable(() -> + decoded.requireReferenceBinding( + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, "17", "24", "17")))) .isNull(); - assertThatThrownBy( - () -> - new StartSessionAuthorityEvidenceBundle.BundleReference( - "authorityEvidenceBundle/v2", "17", "23", "17")) + assertThatThrownBy(() -> + new StartSessionAuthorityEvidenceBundle.BundleReference( + "authorityEvidenceBundle/v2", "17", "23", "17")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new StartSessionAuthorityEvidenceBundle.BundleReference( - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, - "17", - "9223372036854775808", - "17")) + assertThatThrownBy(() -> + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "9223372036854775808", + "17")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new StartSessionAuthorityEvidenceBundle.BundleReference( - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, - "9223372036854775808", - "23", - "17")) + assertThatThrownBy(() -> + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "9223372036854775808", + "23", + "17")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new StartSessionAuthorityEvidenceBundle.BundleReference( - StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, - "17", - "23", - "18446744073709551616")) + assertThatThrownBy(() -> + new StartSessionAuthorityEvidenceBundle.BundleReference( + StartSessionAuthorityEvidenceBundle.BUNDLE_VERSION, + "17", + "23", + "18446744073709551616")) .isInstanceOf(IllegalArgumentException.class); } @Test void rejectsOversizedBundlesAndOutOfScopeTenantAuthority() throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple("bundle-bounds"); - assertThatThrownBy( - () -> - StartSessionAuthorityEvidenceBundle.decode( - new byte[StartSessionAuthorityEvidenceBundle.MAX_BUNDLE_BYTES + 1])) + assertThatThrownBy(() -> + StartSessionAuthorityEvidenceBundle.decode( + new byte[StartSessionAuthorityEvidenceBundle.MAX_BUNDLE_BYTES + 1])) .isInstanceOf(IllegalArgumentException.class); Map widened = mutableValue(tuple); diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTupleTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTupleTest.java index cf1aea88d5..434b438941 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTupleTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPostAuthorizationExecutionTupleTest.java @@ -53,34 +53,31 @@ void rejectsWorkloadFingerprintReferenceAndDirectTupleSubstitution() throws Exce byte[] bundle = bundle(pre, "17"); StartSessionAuthorityEvidenceBundle.BundleReference reference = reference("17"); - assertThatThrownBy( - () -> - StartSessionPostAuthorizationExecutionTuple.createHuman( - pre, - "spiffe://firemud/ns/another-runtime/sa/logging-admin-service", - FINGERPRINT, - RESERVATION_OWNER, - 19L, - bundle, - reference)) + assertThatThrownBy(() -> + StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + "spiffe://firemud/ns/another-runtime/sa/logging-admin-service", + FINGERPRINT, + RESERVATION_OWNER, + 19L, + bundle, + reference)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("same-namespace"); - assertThatThrownBy( - () -> - StartSessionPostAuthorizationExecutionTuple.createHuman( - pre, - WORKLOAD, - "sha256:" + "b".repeat(64), - RESERVATION_OWNER, - 19L, - bundle, - reference)) + assertThatThrownBy(() -> + StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, + WORKLOAD, + "sha256:" + "b".repeat(64), + RESERVATION_OWNER, + 19L, + bundle, + reference)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("fingerprint"); - assertThatThrownBy( - () -> - StartSessionPostAuthorizationExecutionTuple.createHuman( - pre, WORKLOAD, FINGERPRINT, RESERVATION_OWNER, 19L, bundle, reference("18"))) + assertThatThrownBy(() -> + StartSessionPostAuthorizationExecutionTuple.createHuman( + pre, WORKLOAD, FINGERPRINT, RESERVATION_OWNER, 19L, bundle, reference("18"))) .isInstanceOf(IllegalArgumentException.class); Map changed = @@ -101,11 +98,9 @@ void returnsDefensiveEvidenceCopiesAndRejectsNonCanonicalOrUnknownTupleFields() assertThat(tuple.canonicalBytes()[0]).isNotEqualTo((byte) '!'); assertThat(tuple.authorityEvidenceBundleBytes()[0]).isNotEqualTo((byte) '!'); - assertThatThrownBy( - () -> - StartSessionPostAuthorizationExecutionTuple.decode( - (tuple.canonicalJson() + " ") - .getBytes(java.nio.charset.StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + StartSessionPostAuthorizationExecutionTuple.decode( + (tuple.canonicalJson() + " ").getBytes(java.nio.charset.StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); Map unknown = JSON.readValue(tuple.canonicalBytes(), Map.class); diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java index 1b83f4c8ef..ae730d2310 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/operator/StartSessionPreAuthorizationReservationTupleTest.java @@ -99,21 +99,16 @@ void strictDecoderRejectsNoncanonicalAndUnsupportedTupleShapes() { () -> StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(" " + json)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical JSON"); - assertThatThrownBy( - () -> - StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( - withUnknownRootField)) + assertThatThrownBy(() -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(withUnknownRootField)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(missingTargetOwner)) + assertThatThrownBy(() -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(missingTargetOwner)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported fields"); - assertThatThrownBy( - () -> - StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( - invalidExpectedVersion)) + assertThatThrownBy(() -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(invalidExpectedVersion)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("expectedVersion"); assertThatThrownBy( diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogValidationTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogValidationTest.java index a8c7891e4a..719e917f83 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogValidationTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/runtimecatalog/RuntimeFamilyCatalogValidationTest.java @@ -79,26 +79,23 @@ void everyInstalledTableAndDeclaredComponentNeedsExactFacts() { var component = new FamilyComponent("runtime", "state"); RuntimeFamilyCatalogValidation.requireComplete( List.of(root, component), List.of(column, table)); - assertThatThrownBy( - () -> - RuntimeFamilyCatalogValidation.requireComplete( - List.of(component), List.of(column, table))) + assertThatThrownBy(() -> + RuntimeFamilyCatalogValidation.requireComplete( + List.of(component), List.of(column, table))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Every installed table"); - assertThatThrownBy( - () -> - RuntimeFamilyCatalogValidation.requireComplete( - List.of(root, component), List.of(table))) + assertThatThrownBy(() -> + RuntimeFamilyCatalogValidation.requireComplete( + List.of(root, component), List.of(table))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Missing family component"); assertThatThrownBy( () -> RuntimeFamilyCatalogValidation.requireComplete(List.of(root), List.of(column))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Missing family table"); - assertThatThrownBy( - () -> - RuntimeFamilyCatalogValidation.requireComplete( - List.of(root), List.of(table, new SchemaFact("TABLE", "unknown", DIGEST)))) + assertThatThrownBy(() -> + RuntimeFamilyCatalogValidation.requireComplete( + List.of(root), List.of(table, new SchemaFact("TABLE", "unknown", DIGEST)))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Every installed table"); } diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalogTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalogTest.java index 588b974763..0f5104218b 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalogTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/social/SocialRuntimeFamilyCatalogTest.java @@ -142,10 +142,8 @@ void familyAndFactBoundsAreIndependentOfRowAbsence() { + fact + "]," + gaps; - assertThatThrownBy( - () -> - SocialRuntimeFamilyCatalog.fromStored( - manyFamilies.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + SocialRuntimeFamilyCatalog.fromStored(manyFamilies.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); String compactFact = "{\"kind\":\"TYPE\",\"identity\":\"x\",\"definitionDigest\":\"sha256:" @@ -168,62 +166,53 @@ void familyAndFactBoundsAreIndependentOfRowAbsence() { void rejectsDuplicateUnknownOversizedAndChangedCorrelationWireValues() { var request = new Request(UUID.randomUUID(), "test"); var wire = SocialRuntimeFamilyCatalogCodec.toRequest(request); - assertThatThrownBy( - () -> - SocialRuntimeFamilyCatalogCodec.fromRequest( - wire.toBuilder() - .addCanonicalRequestBytes(wire.getCanonicalRequestBytes(0)) - .build())) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SocialRuntimeFamilyCatalogCodec.fromRequest( - wire.toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField( - 9, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) - .build()) - .build())) + assertThatThrownBy(() -> + SocialRuntimeFamilyCatalogCodec.fromRequest( + wire.toBuilder() + .addCanonicalRequestBytes(wire.getCanonicalRequestBytes(0)) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SocialRuntimeFamilyCatalogCodec.fromRequest( - wire.toBuilder() - .setCanonicalRequestBytes(0, ByteString.copyFrom(new byte[1025])) - .build())) + assertThatThrownBy(() -> + SocialRuntimeFamilyCatalogCodec.fromRequest( + wire.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(9, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> + SocialRuntimeFamilyCatalogCodec.fromRequest( + wire.toBuilder() + .setCanonicalRequestBytes(0, ByteString.copyFrom(new byte[1025])) + .build())) .isInstanceOf(IllegalArgumentException.class); var evidence = new Evidence(request, UUID.randomUUID(), catalog()); var response = SocialRuntimeFamilyCatalogCodec.toResponse(request, evidence); - assertThatThrownBy( - () -> - SocialRuntimeFamilyCatalogCodec.fromResponse( - new Request(UUID.randomUUID(), "test"), response)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SocialRuntimeFamilyCatalogCodec.fromResponse( - new Request(request.readRequestId(), "other"), response)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SocialRuntimeFamilyCatalogCodec.fromResponse( - request, - response.toBuilder() - .addCanonicalResponseBytes(response.getCanonicalResponseBytes(0)) - .build())) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SocialRuntimeFamilyCatalogCodec.fromResponse( - request, - response.toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField( - 9, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) - .build()) - .build())) + assertThatThrownBy(() -> + SocialRuntimeFamilyCatalogCodec.fromResponse( + new Request(UUID.randomUUID(), "test"), response)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> + SocialRuntimeFamilyCatalogCodec.fromResponse( + new Request(request.readRequestId(), "other"), response)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> + SocialRuntimeFamilyCatalogCodec.fromResponse( + request, + response.toBuilder() + .addCanonicalResponseBytes(response.getCanonicalResponseBytes(0)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> + SocialRuntimeFamilyCatalogCodec.fromResponse( + request, + response.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(9, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -232,15 +221,13 @@ void refusesTruncationTrailingDataDigestTamperingInvalidUtf8AndSourceBounds() { var evidence = new Evidence(new Request(UUID.randomUUID(), "test"), UUID.randomUUID(), catalog()); byte[] bytes = SocialRuntimeFamilyCatalogCodec.evidenceBytes(evidence); - assertThatThrownBy( - () -> - SocialRuntimeFamilyCatalogCodec.evidenceFromStored( - Arrays.copyOf(bytes, bytes.length - 1))) + assertThatThrownBy(() -> + SocialRuntimeFamilyCatalogCodec.evidenceFromStored( + Arrays.copyOf(bytes, bytes.length - 1))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SocialRuntimeFamilyCatalogCodec.evidenceFromStored( - Arrays.copyOf(bytes, bytes.length + 1))) + assertThatThrownBy(() -> + SocialRuntimeFamilyCatalogCodec.evidenceFromStored( + Arrays.copyOf(bytes, bytes.length + 1))) .isInstanceOf(IllegalArgumentException.class); int digestOffset = 4 + 4 + SocialRuntimeFamilyCatalogCodec.requestBytes(evidence.request()).length + 16 + 4; @@ -249,10 +236,9 @@ void refusesTruncationTrailingDataDigestTamperingInvalidUtf8AndSourceBounds() { .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> SocialRuntimeFamilyCatalog.fromStored(new byte[] {(byte) 0xc3, 0x28})) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - SocialRuntimeFamilyCatalog.fromStored( - new byte[SocialRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 1])) + assertThatThrownBy(() -> + SocialRuntimeFamilyCatalog.fromStored( + new byte[SocialRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 1])) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> new Request(new UUID(0, 0), "test")) .isInstanceOf(IllegalArgumentException.class); diff --git a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogTest.java b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogTest.java index c9f8ac334d..5bea9fdbda 100644 --- a/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogTest.java +++ b/services/common-platform-core/src/test/java/unit/net/firedevops/firemud/common/world/WorldRuntimeFamilyCatalogTest.java @@ -58,9 +58,8 @@ void familyAndFactArrayBoundsAreIndependentOfPayloadRowAbsence() { + "],\"schemaFacts\":[" + fact + "]}"; - assertThatThrownBy( - () -> - WorldRuntimeFamilyCatalog.fromStored(manyFamilies.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + WorldRuntimeFamilyCatalog.fromStored(manyFamilies.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); String compactFact = "{\"kind\":\"TYPE\",\"identity\":\"x\",\"definitionDigest\":\"sha256:" @@ -135,50 +134,43 @@ void refusesUnknownDuplicateMissingUnsupportedOrInconsistentCatalogFacts() { void rejectsUnknownDuplicateOversizedAndChangedCorrelationWireValues() { var read = new Request(UUID.randomUUID(), "test"); var request = WorldRuntimeFamilyCatalogCodec.toRequest(read); - assertThatThrownBy( - () -> - WorldRuntimeFamilyCatalogCodec.fromRequest( - request.toBuilder() - .addCanonicalRequestBytes(request.getCanonicalRequestBytes(0)) - .build())) + assertThatThrownBy(() -> + WorldRuntimeFamilyCatalogCodec.fromRequest( + request.toBuilder() + .addCanonicalRequestBytes(request.getCanonicalRequestBytes(0)) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldRuntimeFamilyCatalogCodec.fromRequest( - request.toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField( - 9, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) - .build()) - .build())) + assertThatThrownBy(() -> + WorldRuntimeFamilyCatalogCodec.fromRequest( + request.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(9, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldRuntimeFamilyCatalogCodec.fromRequest( - request.toBuilder() - .setCanonicalRequestBytes(0, ByteString.copyFrom(new byte[1025])) - .build())) + assertThatThrownBy(() -> + WorldRuntimeFamilyCatalogCodec.fromRequest( + request.toBuilder() + .setCanonicalRequestBytes(0, ByteString.copyFrom(new byte[1025])) + .build())) .isInstanceOf(IllegalArgumentException.class); var evidence = new Evidence(read, UUID.randomUUID(), catalog()); var response = WorldRuntimeFamilyCatalogCodec.toResponse(read, evidence); - assertThatThrownBy( - () -> - WorldRuntimeFamilyCatalogCodec.fromResponse( - new Request(UUID.randomUUID(), "test"), response)) + assertThatThrownBy(() -> + WorldRuntimeFamilyCatalogCodec.fromResponse( + new Request(UUID.randomUUID(), "test"), response)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldRuntimeFamilyCatalogCodec.fromResponse( - new Request(read.readRequestId(), "other"), response)) + assertThatThrownBy(() -> + WorldRuntimeFamilyCatalogCodec.fromResponse( + new Request(read.readRequestId(), "other"), response)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldRuntimeFamilyCatalogCodec.fromResponse( - read, - response.toBuilder() - .addCanonicalResponseBytes(response.getCanonicalResponseBytes(0)) - .build())) + assertThatThrownBy(() -> + WorldRuntimeFamilyCatalogCodec.fromResponse( + read, + response.toBuilder() + .addCanonicalResponseBytes(response.getCanonicalResponseBytes(0)) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -187,15 +179,13 @@ void refusesTruncationTrailingDataDigestTamperingInvalidUtf8AndSourceBounds() { var evidence = new Evidence(new Request(UUID.randomUUID(), "test"), UUID.randomUUID(), catalog()); byte[] bytes = WorldRuntimeFamilyCatalogCodec.evidenceBytes(evidence); - assertThatThrownBy( - () -> - WorldRuntimeFamilyCatalogCodec.evidenceFromStored( - Arrays.copyOf(bytes, bytes.length - 1))) + assertThatThrownBy(() -> + WorldRuntimeFamilyCatalogCodec.evidenceFromStored( + Arrays.copyOf(bytes, bytes.length - 1))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldRuntimeFamilyCatalogCodec.evidenceFromStored( - Arrays.copyOf(bytes, bytes.length + 1))) + assertThatThrownBy(() -> + WorldRuntimeFamilyCatalogCodec.evidenceFromStored( + Arrays.copyOf(bytes, bytes.length + 1))) .isInstanceOf(IllegalArgumentException.class); // The digest string is outside the catalog bytes, so a complete parse must still refuse it. int digestOffset = @@ -205,10 +195,9 @@ void refusesTruncationTrailingDataDigestTamperingInvalidUtf8AndSourceBounds() { .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> WorldRuntimeFamilyCatalog.fromStored(new byte[] {(byte) 0xc3, 0x28})) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldRuntimeFamilyCatalog.fromStored( - new byte[WorldRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 1])) + assertThatThrownBy(() -> + WorldRuntimeFamilyCatalog.fromStored( + new byte[WorldRuntimeFamilyCatalog.MAX_CATALOG_BYTES + 1])) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> new Request(new UUID(0, 0), "test")) .isInstanceOf(IllegalArgumentException.class); diff --git a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java index 5ed99a5545..09a9931c06 100644 --- a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/AuthoringFixtures.java @@ -72,15 +72,14 @@ public static WorldPublishedStartLocationEvidence startLocationEvidence() throws new String(account.gameDesignBinding(), StandardCharsets.UTF_8), account.inputDigest()); List tuples = draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) + .map(unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) .toList(); var request = new WorldPublishedStartLocationEvidence.Request( @@ -140,19 +139,18 @@ public static WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence(String s null); List participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - owner, - Long.toString(descriptor.versionId()), - false, - null, - selector.request().appliedCommitId(), - selector.request().contentDigest(), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - "GAME_LOGIC".equals(owner), - "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) + .map(owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + selector.request().appliedCommitId(), + selector.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "c".repeat(64) : null)) .toList(); AuthoredWorldReleaseAttestationEvidence release = AuthoredWorldReleaseAttestationEvidence.create( @@ -341,23 +339,22 @@ private static DraftAuthorizationFenceBinding.OwnerReadback committedReadback( result.put( "appliedEpochs", draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - Map.of( - "aggregateType", - unit.aggregateType(), - "aggregateId", - unit.aggregateId(), - "scopeType", - unit.scopeType(), - "scopeId", - unit.scopeId(), - "expectedEpoch", - unit.expectedEpoch(), - "resultingEpoch", - new java.math.BigInteger(unit.expectedEpoch()) - .add(java.math.BigInteger.ONE) - .toString())) + .map(unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new java.math.BigInteger(unit.expectedEpoch()) + .add(java.math.BigInteger.ONE) + .toString())) .toList()); return new DraftAuthorizationFenceBinding.OwnerReadback( Owner.WORLD, diff --git a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/PlayerCreatedPublishedPolicyFixtures.java b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/PlayerCreatedPublishedPolicyFixtures.java index ac0366deff..29bf1e82e9 100644 --- a/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/PlayerCreatedPublishedPolicyFixtures.java +++ b/services/common-platform-core/src/testFixtures/java/net/firedevops/firemud/common/testing/PlayerCreatedPublishedPolicyFixtures.java @@ -117,15 +117,14 @@ public static Prepared prepare(DraftCommitBinding selected) throws Exception { var result = JSON.readTree(applied.result()); var tuples = selected.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) + .map(unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) .toList(); var world = new WorldPublishedStartLocationEvidence( diff --git a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java index 66735b2195..e7b95839e9 100644 --- a/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java +++ b/services/common-redis-contracts/src/main/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptor.java @@ -109,11 +109,9 @@ public record RedisScriptDescriptor( boolean fullKeyCompanion = keys.stream() - .anyMatch( - key -> - key.hashTagDeclaration() == HashTagDeclaration.FULL_KEY_ANCHOR - || key.hashTagDeclaration() - == HashTagDeclaration.EXACT_FULL_KEY_ANCHOR_TAG); + .anyMatch(key -> + key.hashTagDeclaration() == HashTagDeclaration.FULL_KEY_ANCHOR + || key.hashTagDeclaration() == HashTagDeclaration.EXACT_FULL_KEY_ANCHOR_TAG); if (fullKeyCompanion && (keys.size() != 2 || keys.get(0).hashTagDeclaration() != HashTagDeclaration.FULL_KEY_ANCHOR diff --git a/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalogTest.java b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalogTest.java index d6d99d6f36..beffed13ef 100644 --- a/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalogTest.java +++ b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptCatalogTest.java @@ -41,19 +41,17 @@ void aggregatesContributionsAndRequiresExactScriptIdentity() { void rejectsDuplicateScriptIdentityAndContributionOwnerMismatch() { RedisScriptDescriptor first = descriptor("account.control-ui.v1", "account-service"); RedisScriptDescriptor duplicate = descriptor("account.control-ui.v1", "account-service"); - assertThatThrownBy( - () -> - RedisScriptCatalog.fromContributions( - List.of( - contribution("account-service", List.of(first)), - contribution("account-service", List.of(duplicate))))) + assertThatThrownBy(() -> + RedisScriptCatalog.fromContributions( + List.of( + contribution("account-service", List.of(first)), + contribution("account-service", List.of(duplicate))))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Duplicate Redis script descriptor identity"); - assertThatThrownBy( - () -> - RedisScriptCatalog.fromContributions( - List.of(contribution("game-session-service", List.of(first))))) + assertThatThrownBy(() -> + RedisScriptCatalog.fromContributions( + List.of(contribution("game-session-service", List.of(first))))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("owner does not match contribution"); } @@ -63,27 +61,21 @@ void rejectsNullAndEmptyContributionsAndNullDescriptors() { assertThatThrownBy(() -> RedisScriptCatalog.fromContributions(null)) .isInstanceOf(NullPointerException.class); assertThat(RedisScriptCatalog.fromContributions(List.of()).descriptors()).isEmpty(); - assertThatThrownBy( - () -> - RedisScriptCatalog.fromContributions(Arrays.asList((RedisScriptContribution) null))) + assertThatThrownBy(() -> + RedisScriptCatalog.fromContributions(Arrays.asList((RedisScriptContribution) null))) .isInstanceOf(NullPointerException.class); - assertThatThrownBy( - () -> - RedisScriptCatalog.fromContributions( - List.of(contribution("account-service", List.of())))) + assertThatThrownBy(() -> + RedisScriptCatalog.fromContributions( + List.of(contribution("account-service", List.of())))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("cannot be empty"); - assertThatThrownBy( - () -> - RedisScriptCatalog.fromContributions( - List.of( - contribution( - "account-service", Arrays.asList((RedisScriptDescriptor) null))))) + assertThatThrownBy(() -> + RedisScriptCatalog.fromContributions( + List.of( + contribution("account-service", Arrays.asList((RedisScriptDescriptor) null))))) .isInstanceOf(NullPointerException.class); - assertThatThrownBy( - () -> - RedisScriptCatalog.fromContributions( - List.of(contribution("account-service", null)))) + assertThatThrownBy(() -> + RedisScriptCatalog.fromContributions(List.of(contribution("account-service", null)))) .isInstanceOf(NullPointerException.class); } @@ -104,10 +96,9 @@ void rejectsContributionAndDescriptorCountOverflow() { for (int index = 0; index <= RedisScriptCatalog.MAX_DESCRIPTORS; index++) { tooManyDescriptors.add(descriptor("account.script-" + index + ".v1", "account-service")); } - assertThatThrownBy( - () -> - RedisScriptCatalog.fromContributions( - List.of(contribution("account-service", tooManyDescriptors)))) + assertThatThrownBy(() -> + RedisScriptCatalog.fromContributions( + List.of(contribution("account-service", tooManyDescriptors)))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("descriptor count exceeds its bound"); } @@ -119,20 +110,19 @@ void limitsInstalledProviderRealizationBeforeRejectingContributionOverflow() { ClassLoader classLoader = getClass().getClassLoader(); Stream> providers = IntStream.range(0, RedisScriptCatalog.MAX_CONTRIBUTIONS + 20) - .mapToObj( - ignored -> - new ServiceLoader.Provider<>() { - @Override - public Class type() { - return RedisScriptContribution.class; - } - - @Override - public RedisScriptContribution get() { - INSTALLED_PROVIDER_GET_CALLS.incrementAndGet(); - return null; - } - }); + .mapToObj(ignored -> + new ServiceLoader.Provider<>() { + @Override + public Class type() { + return RedisScriptContribution.class; + } + + @Override + public RedisScriptContribution get() { + INSTALLED_PROVIDER_GET_CALLS.incrementAndGet(); + return null; + } + }); when(installed.stream()).thenReturn(providers); try (MockedStatic serviceLoader = mockStatic(ServiceLoader.class)) { diff --git a/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java index cd6b3f4fb9..b5f0b6117a 100644 --- a/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java +++ b/services/common-redis-contracts/src/test/java/net/firedevops/firemud/common/redis/contracts/RedisScriptDescriptorTest.java @@ -44,13 +44,12 @@ void fullKeyAnchorRequiresExactlyOneOrderedExplicitCompanion() { List.of(anchor, ordinary), List.of(ordinary, companion), List.of(anchor, companion, ordinary))) { - assertThatThrownBy( - () -> - fullKeyDescriptor( - "account-tenant-creation-admission.v1", - "account-service", - RedisScriptDescriptor.RedisRole.COORDINATION, - invalid)) + assertThatThrownBy(() -> + fullKeyDescriptor( + "account-tenant-creation-admission.v1", + "account-service", + RedisScriptDescriptor.RedisRole.COORDINATION, + invalid)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("full-key anchor slot binding"); } @@ -145,32 +144,30 @@ void rejectsMalformedResourceAndDigest() { @Test void rejectsMalformedAndDuplicateKeyIdentities() { - assertThatThrownBy( - () -> - descriptor( - null, - null, - List.of( - new RedisScriptDescriptor.KeySpec( - "1record", - "session:control:", - RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), - null, - null)) + assertThatThrownBy(() -> + descriptor( + null, + null, + List.of( + new RedisScriptDescriptor.KeySpec( + "1record", + "session:control:", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + null, + null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("KEYS name"); - assertThatThrownBy( - () -> - descriptor( - null, - null, - List.of( - new RedisScriptDescriptor.KeySpec( - "record", - "session/control", - RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), - null, - null)) + assertThatThrownBy(() -> + descriptor( + null, + null, + List.of( + new RedisScriptDescriptor.KeySpec( + "record", + "session/control", + RedisScriptDescriptor.HashTagDeclaration.NOT_REQUIRED)), + null, + null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("ownedPrefix"); var key = @@ -190,14 +187,13 @@ void rejectsMalformedAndDuplicateKeyIdentities() { @Test void rejectsMalformedAndDuplicateArgumentAndOutcomeIdentities() { - assertThatThrownBy( - () -> - descriptor( - null, - null, - null, - List.of(new RedisScriptDescriptor.ArgumentSpec("request-id")), - null)) + assertThatThrownBy(() -> + descriptor( + null, + null, + null, + List.of(new RedisScriptDescriptor.ArgumentSpec("request-id")), + null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("ARGV name"); var argument = new RedisScriptDescriptor.ArgumentSpec("requestId"); @@ -205,18 +201,17 @@ void rejectsMalformedAndDuplicateArgumentAndOutcomeIdentities() { .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("duplicate ARGV"); - assertThatThrownBy( - () -> - descriptor( - null, - null, - null, - null, - List.of( - new RedisScriptDescriptor.OutcomeSpec( - "created", - RedisScriptDescriptor.OutcomeCategory.SUCCESS, - RedisScriptDescriptor.MutationEffect.MUTATING)))) + assertThatThrownBy(() -> + descriptor( + null, + null, + null, + null, + List.of( + new RedisScriptDescriptor.OutcomeSpec( + "created", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING)))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("outcome code"); var outcome = @@ -228,12 +223,11 @@ void rejectsMalformedAndDuplicateArgumentAndOutcomeIdentities() { .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("duplicate outcome"); - assertThatThrownBy( - () -> - new RedisScriptDescriptor.OutcomeSpec( - "CONFLICT", - RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, - RedisScriptDescriptor.MutationEffect.MUTATING)) + assertThatThrownBy(() -> + new RedisScriptDescriptor.OutcomeSpec( + "CONFLICT", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.MUTATING)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("must be non-mutating"); } diff --git a/services/common-saga/src/main/java/net/firedevops/firemud/common/saga/persistence/SagaInstanceRepository.java b/services/common-saga/src/main/java/net/firedevops/firemud/common/saga/persistence/SagaInstanceRepository.java index 96962411ab..97816c8fb3 100644 --- a/services/common-saga/src/main/java/net/firedevops/firemud/common/saga/persistence/SagaInstanceRepository.java +++ b/services/common-saga/src/main/java/net/firedevops/firemud/common/saga/persistence/SagaInstanceRepository.java @@ -55,31 +55,29 @@ public List findAll() { return dsl.select(ID, SAGA_NAME, STATE, CREATED_AT, UPDATED_AT) .from(sagaInstance) .orderBy(ID.desc()) - .fetch( - record -> { - SagaInstance entity = new SagaInstance(); - entity.setId(record.get(ID)); - entity.setSagaName(record.get(SAGA_NAME)); - entity.setState(record.get(STATE)); - entity.setCreatedAt(JooqPersistenceSupport.toInstant(record.get(CREATED_AT))); - entity.setUpdatedAt(JooqPersistenceSupport.toInstant(record.get(UPDATED_AT))); - return entity; - }); + .fetch(record -> { + SagaInstance entity = new SagaInstance(); + entity.setId(record.get(ID)); + entity.setSagaName(record.get(SAGA_NAME)); + entity.setState(record.get(STATE)); + entity.setCreatedAt(JooqPersistenceSupport.toInstant(record.get(CREATED_AT))); + entity.setUpdatedAt(JooqPersistenceSupport.toInstant(record.get(UPDATED_AT))); + return entity; + }); } public Optional findById(Long id) { return dsl.select(ID, SAGA_NAME, STATE, CREATED_AT, UPDATED_AT) .from(sagaInstance) .where(ID.eq(id)) - .fetchOptional( - record -> { - SagaInstance entity = new SagaInstance(); - entity.setId(record.get(ID)); - entity.setSagaName(record.get(SAGA_NAME)); - entity.setState(record.get(STATE)); - entity.setCreatedAt(JooqPersistenceSupport.toInstant(record.get(CREATED_AT))); - entity.setUpdatedAt(JooqPersistenceSupport.toInstant(record.get(UPDATED_AT))); - return entity; - }); + .fetchOptional(record -> { + SagaInstance entity = new SagaInstance(); + entity.setId(record.get(ID)); + entity.setSagaName(record.get(SAGA_NAME)); + entity.setState(record.get(STATE)); + entity.setCreatedAt(JooqPersistenceSupport.toInstant(record.get(CREATED_AT))); + entity.setUpdatedAt(JooqPersistenceSupport.toInstant(record.get(UPDATED_AT))); + return entity; + }); } } diff --git a/services/common-saga/src/main/java/net/firedevops/firemud/common/saga/persistence/SagaStepRepository.java b/services/common-saga/src/main/java/net/firedevops/firemud/common/saga/persistence/SagaStepRepository.java index 2488065900..3903eb9e41 100644 --- a/services/common-saga/src/main/java/net/firedevops/firemud/common/saga/persistence/SagaStepRepository.java +++ b/services/common-saga/src/main/java/net/firedevops/firemud/common/saga/persistence/SagaStepRepository.java @@ -62,17 +62,16 @@ public List findByInstanceId(Long instanceId) { .from(sagaStep) .where(INSTANCE_ID.eq(instanceId)) .orderBy(ID.asc()) - .fetch( - record -> { - SagaStep entity = new SagaStep(); - entity.setId(record.get(ID)); - entity.setInstanceId(record.get(INSTANCE_ID)); - entity.setName(record.get(NAME)); - entity.setStatus(record.get(STATUS)); - entity.setAttempt(record.get(ATTEMPT) == null ? 0 : record.get(ATTEMPT)); - entity.setCreatedAt(JooqPersistenceSupport.toInstant(record.get(CREATED_AT))); - entity.setUpdatedAt(JooqPersistenceSupport.toInstant(record.get(UPDATED_AT))); - return entity; - }); + .fetch(record -> { + SagaStep entity = new SagaStep(); + entity.setId(record.get(ID)); + entity.setInstanceId(record.get(INSTANCE_ID)); + entity.setName(record.get(NAME)); + entity.setStatus(record.get(STATUS)); + entity.setAttempt(record.get(ATTEMPT) == null ? 0 : record.get(ATTEMPT)); + entity.setCreatedAt(JooqPersistenceSupport.toInstant(record.get(CREATED_AT))); + entity.setUpdatedAt(JooqPersistenceSupport.toInstant(record.get(UPDATED_AT))); + return entity; + }); } } diff --git a/services/common-saga/src/test/java/unit/net/firedevops/firemud/common/saga/SagaRunnerTest.java b/services/common-saga/src/test/java/unit/net/firedevops/firemud/common/saga/SagaRunnerTest.java index 5167ba40d1..53242f2066 100644 --- a/services/common-saga/src/test/java/unit/net/firedevops/firemud/common/saga/SagaRunnerTest.java +++ b/services/common-saga/src/test/java/unit/net/firedevops/firemud/common/saga/SagaRunnerTest.java @@ -21,19 +21,17 @@ void setup() { instanceRepository = Mockito.mock(SagaInstanceRepository.class); stepRepository = Mockito.mock(SagaStepRepository.class); Mockito.when(instanceRepository.save(any())) - .thenAnswer( - inv -> { - net.firedevops.firemud.common.saga.persistence.SagaInstance inst = inv.getArgument(0); - inst.setId(1L); - return inst; - }); + .thenAnswer(inv -> { + net.firedevops.firemud.common.saga.persistence.SagaInstance inst = inv.getArgument(0); + inst.setId(1L); + return inst; + }); Mockito.when(stepRepository.save(any())) - .thenAnswer( - inv -> { - net.firedevops.firemud.common.saga.persistence.SagaStep step = inv.getArgument(0); - step.setId(1L); - return step; - }); + .thenAnswer(inv -> { + net.firedevops.firemud.common.saga.persistence.SagaStep step = inv.getArgument(0); + step.setId(1L); + return step; + }); runner = new SagaRunner( new SagaMetrics(new SimpleMeterRegistry()), instanceRepository, stepRepository); diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidence.java b/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidence.java index eb42f2e370..e1bf602312 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidence.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidence.java @@ -365,11 +365,10 @@ private static void exact(Map object, Set fields) { private static Map object(Object value) { if (!(value instanceof Map map)) throw invalid(); Map result = new LinkedHashMap<>(); - map.forEach( - (key, child) -> { - if (!(key instanceof String text)) throw invalid(); - result.put(text, child); - }); + map.forEach((key, child) -> { + if (!(key instanceof String text)) throw invalid(); + result.put(text, child); + }); return result; } diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java b/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java index 22bc86bd2b..fed4075081 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/gamesession/CanonicalGameplayAdmissionDecisionReadGrpcCodec.java @@ -179,27 +179,26 @@ public static VisiblePublicProductionTargets fromDiscoveryResponse( Set realms = new HashSet<>(); List targets = response.getCurrentTargetsList().stream() - .map( - wire -> { - requireWireSize( - wire.getSerializedSize(), - MAX_TARGET_RESOLUTION_RESPONSE_WIRE_BYTES, - "discovery target"); - Target target = parseTargetEvidence(wire); - if (!expected.targetNamespace().equals(target.targetNamespace()) - || !"SHARED".equals(target.playableStateScope()) - || !("PRESEEDED_ONLY".equals(target.characterCreationPolicy()) - || "PLAYER_CREATED".equals(target.characterCreationPolicy())) - || target.ownerProofOutcome() != OwnerProofOutcome.COMMITTED - || target.positiveDurableAbort() - || !tenants.add(target.canonicalTenantId()) - || !tenantSlugs.add(target.tenantSlug()) - || !realms.add(target.realmId())) { - throw invalid( - "Discovery requires unique current public SHARED owner targets with a supported creation policy"); - } - return target; - }) + .map(wire -> { + requireWireSize( + wire.getSerializedSize(), + MAX_TARGET_RESOLUTION_RESPONSE_WIRE_BYTES, + "discovery target"); + Target target = parseTargetEvidence(wire); + if (!expected.targetNamespace().equals(target.targetNamespace()) + || !"SHARED".equals(target.playableStateScope()) + || !("PRESEEDED_ONLY".equals(target.characterCreationPolicy()) + || "PLAYER_CREATED".equals(target.characterCreationPolicy())) + || target.ownerProofOutcome() != OwnerProofOutcome.COMMITTED + || target.positiveDurableAbort() + || !tenants.add(target.canonicalTenantId()) + || !tenantSlugs.add(target.tenantSlug()) + || !realms.add(target.realmId())) { + throw invalid( + "Discovery requires unique current public SHARED owner targets with a supported creation policy"); + } + return target; + }) .toList(); return new VisiblePublicProductionTargets(expected, targets); } @@ -736,18 +735,17 @@ private static void requirePublishedWorldLifecycle( var content = terminal.releaseContent(); var participants = content.participantDigests().stream() - .map( - participant -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - participant.participantKey(), - participant.scopeValue(), - participant.baseVersionId() != null, - participant.baseVersionId(), - participant.appliedCommitId(), - participant.contentDigest(), - participant.digestSchemaVersion(), - participant.abilitySchemaDigest() != null, - participant.abilitySchemaDigest())) + .map(participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId() != null, + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + participant.digestSchemaVersion(), + participant.abilitySchemaDigest() != null, + participant.abilitySchemaDigest())) .toList(); int attestationSchema = switch (content.attestationSchemaVersion()) { diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtProfileClaimSupport.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtProfileClaimSupport.java index 43399fa59d..230006dfc5 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtProfileClaimSupport.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/AccountJwtProfileClaimSupport.java @@ -130,15 +130,14 @@ static Map requireGenerationMap(Object value) { private static Map requireGenerationMap(Object value, boolean decimalCounters) { Map source = requireObjectMap(value); Map result = new LinkedHashMap<>(); - source.forEach( - (key, generation) -> { - requireUuid(key); - result.put( - key, - decimalCounters - ? requirePositiveDecimalLong(generation) - : requirePositiveLong(generation)); - }); + source.forEach((key, generation) -> { + requireUuid(key); + result.put( + key, + decimalCounters + ? requirePositiveDecimalLong(generation) + : requirePositiveLong(generation)); + }); return result; } @@ -288,25 +287,24 @@ private static void validateTenantBillingCutoff(Object value, boolean decimalCou if (cutoffs.isEmpty()) { throw invalid(); } - cutoffs.forEach( - (tenantId, cutoffValue) -> { - requireUuid(tenantId); - Map cutoff = requireObjectMap(cutoffValue); - if (!cutoff - .keySet() - .equals( - Set.of( - "tenantAuthorityGeneration", - "tenantBillingSequence", - "outboxStreamKey", - "outboxSequence"))) { - throw invalid(); - } - requirePositiveCounter(cutoff.get("tenantAuthorityGeneration"), decimalCounters); - requirePositiveCounter(cutoff.get("tenantBillingSequence"), decimalCounters); - requirePositiveCounter(cutoff.get("outboxSequence"), decimalCounters); - requireBoundedText(cutoff.get("outboxStreamKey"), 2048); - }); + cutoffs.forEach((tenantId, cutoffValue) -> { + requireUuid(tenantId); + Map cutoff = requireObjectMap(cutoffValue); + if (!cutoff + .keySet() + .equals( + Set.of( + "tenantAuthorityGeneration", + "tenantBillingSequence", + "outboxStreamKey", + "outboxSequence"))) { + throw invalid(); + } + requirePositiveCounter(cutoff.get("tenantAuthorityGeneration"), decimalCounters); + requirePositiveCounter(cutoff.get("tenantBillingSequence"), decimalCounters); + requirePositiveCounter(cutoff.get("outboxSequence"), decimalCounters); + requireBoundedText(cutoff.get("outboxStreamKey"), 2048); + }); } static void requireBoundedText(Object value, int maximumLength) { diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java index 051e4009be..059908590b 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/ControlUiJwtProfileValidator.java @@ -62,14 +62,13 @@ public static void validateClaims(Map claims, int maxControlUiTe Map scopedRoles = AccountJwtProfileClaimSupport.requireObjectMap(claims.get("scopedRoles")); - scopedRoles.forEach( - (tenantId, roles) -> { - AccountJwtProfileClaimSupport.requireUuid(tenantId); - AccountJwtProfileClaimSupport.requireRoleList(roles); - if (((List) roles).isEmpty() || tenantId.equals(claims.get("accountId"))) { - throw AccountJwtProfileClaimSupport.invalid(); - } - }); + scopedRoles.forEach((tenantId, roles) -> { + AccountJwtProfileClaimSupport.requireUuid(tenantId); + AccountJwtProfileClaimSupport.requireRoleList(roles); + if (((List) roles).isEmpty() || tenantId.equals(claims.get("accountId"))) { + throw AccountJwtProfileClaimSupport.invalid(); + } + }); if (!scopedRoles.keySet().containsAll(tenantGenerations.keySet())) { throw AccountJwtProfileClaimSupport.invalid(); } diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfile.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfile.java index 4763a6164c..8ac8d5bd4a 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfile.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfile.java @@ -88,13 +88,11 @@ public static Map authorityTuple( throw new IllegalArgumentException( "Account security cutoff presence does not match the source generation"); } - accountSecurityCutoff.ifPresent( - cutoff -> { - if (!Long.toString(accountAuthorityGeneration) - .equals(cutoff.accountAuthorityGeneration())) { - throw new IllegalArgumentException("Account security cutoff generation is stale"); - } - }); + accountSecurityCutoff.ifPresent(cutoff -> { + if (!Long.toString(accountAuthorityGeneration).equals(cutoff.accountAuthorityGeneration())) { + throw new IllegalArgumentException("Account security cutoff generation is stale"); + } + }); Map tuple = new LinkedHashMap<>(); tuple.put("issuerAuthGeneration", Long.toString(issuerAuthGeneration)); tuple.put("accountAuthorityGeneration", Long.toString(accountAuthorityGeneration)); diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java index 17584d3171..24e78c00d0 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecord.java @@ -599,35 +599,32 @@ private static Map parseObject(String json, String field) { private static Map requireObject(Object value, String field) { if (!(value instanceof Map map)) throw invalid(field + " must be an object"); Map result = new LinkedHashMap<>(); - map.forEach( - (key, item) -> { - if (!(key instanceof String name) || item == null || result.put(name, item) != null) { - throw invalid(field + " contains an invalid member"); - } - }); + map.forEach((key, item) -> { + if (!(key instanceof String name) || item == null || result.put(name, item) != null) { + throw invalid(field + " contains an invalid member"); + } + }); return result; } private static Map immutableMap(Map input) { Map copy = new LinkedHashMap<>(); - input.forEach( - (key, value) -> { - if (key == null || value == null) throw invalid("Null registry field is forbidden"); - copy.put(key, deepImmutable(value)); - }); + input.forEach((key, value) -> { + if (key == null || value == null) throw invalid("Null registry field is forbidden"); + copy.put(key, deepImmutable(value)); + }); return Map.copyOf(copy); } private static Object deepImmutable(Object value) { if (value instanceof Map map) { Map nested = new LinkedHashMap<>(); - map.forEach( - (key, item) -> { - if (!(key instanceof String name) || item == null) { - throw invalid("Null or invalid nested registry field is forbidden"); - } - nested.put(name, deepImmutable(item)); - }); + map.forEach((key, item) -> { + if (!(key instanceof String name) || item == null) { + throw invalid("Null or invalid nested registry field is forbidden"); + } + nested.put(name, deepImmutable(item)); + }); return Map.copyOf(nested); } if (value instanceof List list) { diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java index 6add8183bd..897e900319 100644 --- a/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java @@ -453,11 +453,10 @@ private static Map copyStringMap(Map source, Str throw new IllegalArgumentException("Missing " + field); } Map result = new LinkedHashMap<>(); - source.forEach( - (key, value) -> { - requireCanonicalUuidText(key, field + " key"); - result.put(key, requirePositiveLongDecimal(value, field)); - }); + source.forEach((key, value) -> { + requireCanonicalUuidText(key, field + " key"); + result.put(key, requirePositiveLongDecimal(value, field)); + }); return Collections.unmodifiableMap(result); } @@ -1279,11 +1278,10 @@ private static Map immutableMap( throw new IllegalArgumentException("Missing " + field); } Map result = new LinkedHashMap<>(); - source.forEach( - (key, value) -> { - requireCanonicalUuidText(key, field + " key"); - result.put(key, Objects.requireNonNull(value, field + " value")); - }); + source.forEach((key, value) -> { + requireCanonicalUuidText(key, field + " key"); + result.put(key, Objects.requireNonNull(value, field + " value")); + }); return Collections.unmodifiableMap(result); } diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidenceTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidenceTest.java index 1fe597cdc1..d2550bb245 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidenceTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseEvidenceTest.java @@ -70,10 +70,9 @@ void rejectsBaselineMissingExtraScalarWrongTenantAndMismatchedGeneration() { rejects(c -> object(c, "membershipBaseline").put("membershipVersion", Map.of(TENANT, "01"))); rejects(c -> object(c, "membershipBaseline").put("membershipVersion", Map.of(TENANT, 1L))); rejects(c -> object(c, "membershipBaseline").put("membershipAuthorityGeneration", "2")); - rejects( - c -> - object(c, "membershipBaseline") - .put("membershipVersion", Map.of(TENANT, "9223372036854775808"))); + rejects(c -> + object(c, "membershipBaseline") + .put("membershipVersion", Map.of(TENANT, "9223372036854775808"))); } @Test @@ -120,11 +119,10 @@ void retainsExplicitPriorGenerationWithoutDerivingHistory() { .isEqualTo(priorValue); rejects(c -> c.put("expectedOldBindingGeneration", "0")); rejects(c -> c.put("expectedOldBindingGeneration", null)); - rejects( - c -> { - c.put("leaseKind", "RESUME"); - c.put("resumeEpisodeId", OTHER); - }); + rejects(c -> { + c.put("leaseKind", "RESUME"); + c.put("resumeEpisodeId", OTHER); + }); } @Test @@ -142,12 +140,10 @@ void rejectsExpiredLongerThanSlaOrExtendingTokenAndNoncanonicalParsing() { .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.parseCanonical(null)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseEvidence.parseCanonical( - json.replace( - "\"schemaVersion\":\"1\"", - "\"schemaVersion\":\"1\",\"schemaVersion\":\"1\""))) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseEvidence.parseCanonical( + json.replace( + "\"schemaVersion\":\"1\"", "\"schemaVersion\":\"1\",\"schemaVersion\":\"1\""))) .isInstanceOf(IllegalArgumentException.class); } @@ -215,32 +211,27 @@ void cutoffReferencesMustBeCoveredByCompleteCheckpointCoordinates() { @Test void rejectsOversizedDeepCyclicAndNullCarriersBeforeBuildingUnboundedEvidence() { - rejects( - c -> - c.put( - "large", "a".repeat(AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + 1))); + rejects(c -> + c.put("large", "a".repeat(AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + 1))); rejects(c -> c.put("large", "界".repeat(22000))); - rejects( - c -> { - Map nested = Map.of("leaf", "value"); - for (int index = 0; index < 10; index++) { - nested = Map.of("nested", nested); - } - c.put("nested", nested); - }); + rejects(c -> { + Map nested = Map.of("leaf", "value"); + for (int index = 0; index < 10; index++) { + nested = Map.of("nested", nested); + } + c.put("nested", nested); + }); rejects(c -> c.put("cycle", c)); rejects(c -> c.put("nullable", null)); assertThatThrownBy(() -> AccountGameplayAdmissionLeaseEvidence.fromCarrier(null)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseEvidence.parseCanonical( - " ".repeat(AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + 1))) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseEvidence.parseCanonical( + " ".repeat(AccountGameplayAdmissionLeaseEvidence.MAX_EVIDENCE_BYTES + 1))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseEvidence.parseCanonical( - "[".repeat(10) + "\"value\"" + "]".repeat(10))) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseEvidence.parseCanonical( + "[".repeat(10) + "\"value\"" + "]".repeat(10))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodecTest.java index 9af28102ba..0067556435 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/AccountGameplayAdmissionLeaseGrpcCodecTest.java @@ -81,34 +81,29 @@ class AccountGameplayAdmissionLeaseGrpcCodecTest { decisionRequest, decisionWire); assertThat(decodedDecision.candidate()).isEqualTo(candidate(original)); assertThat(decodedDecision.targetEvidence()).isEqualTo(target(original)); - assertThatThrownBy( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.fromDecisionResponse( - decisionRequest, - decisionWire.toBuilder().setPurpose(0, "provisional-decision/v1").build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.fromDecisionResponse( + decisionRequest, + decisionWire.toBuilder().setPurpose(0, "provisional-decision/v1").build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.fromDecisionResponse( - decisionRequest, - decisionWire.toBuilder().addCandidateSha256("a".repeat(64)).build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.fromDecisionResponse( + decisionRequest, + decisionWire.toBuilder().addCandidateSha256("a".repeat(64)).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.fromDecisionResponse( - decisionRequest, decisionWire.toBuilder().setBindingGeneration(0, "1").build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.fromDecisionResponse( + decisionRequest, decisionWire.toBuilder().setBindingGeneration(0, "1").build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.fromDecisionResponse( - decisionRequest, - decisionWire.toBuilder().setClosureReadbackSha256(0, "A".repeat(64)).build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.fromDecisionResponse( + decisionRequest, + decisionWire.toBuilder().setClosureReadbackSha256(0, "A".repeat(64)).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.fromDecisionResponse( - decisionRequest, - decisionWire.toBuilder().setAbandonmentUuid(0, CLEANUP_ID.toString()).build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.fromDecisionResponse( + decisionRequest, + decisionWire.toBuilder().setAbandonmentUuid(0, CLEANUP_ID.toString()).build())) .isInstanceOf(IllegalArgumentException.class); var abort = new AccountGameplayAdmissionNeverAdmittedGrpcCodec.AbortEvidence( @@ -124,52 +119,45 @@ class AccountGameplayAdmissionLeaseGrpcCodecTest { .isEqualTo(abort); assertThat(request.toString()).doesNotContain(JWT); for (int state : List.of(0, 1, 2, 999)) { - assertThatThrownBy( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseResponse( - request, response.toBuilder().setStateValue(0, state).build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseResponse( + request, response.toBuilder().setStateValue(0, state).build())) .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseResponse( - request, response.toBuilder().addSchemaVersion(1).build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseResponse( + request, response.toBuilder().addSchemaVersion(1).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseRequest( - wireRequest.toBuilder() - .setTransitionUuid(0, "00000000-0000-0000-0000-000000000000") - .build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseRequest( + wireRequest.toBuilder() + .setTransitionUuid(0, "00000000-0000-0000-0000-000000000000") + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseRequest( - wireRequest.toBuilder().addPresentedInitialGsaCompactJwt(JWT).build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseRequest( + wireRequest.toBuilder().addPresentedInitialGsaCompactJwt(JWT).build())) .isInstanceOf(IllegalArgumentException.class); var unknown = UnknownFieldSet.newBuilder() .addField(100, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); - assertThatThrownBy( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseResponse( - request, response.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseResponse( + request, response.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseDecisionRequest( - decisionWireRequest.toBuilder() - .setExpectedLeaseEvidenceUtf8( - 0, ByteString.copyFromUtf8(original.canonicalJson() + " ")) - .build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseDecisionRequest( + decisionWireRequest.toBuilder() + .setExpectedLeaseEvidenceUtf8( + 0, ByteString.copyFromUtf8(original.canonicalJson() + " ")) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseRequest( - wireRequest.toBuilder() - .setPresentedInitialGsaCompactJwt(0, "x".repeat(256 * 1024)) - .build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseRequest( + wireRequest.toBuilder() + .setPresentedInitialGsaCompactJwt(0, "x".repeat(256 * 1024)) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -311,10 +299,9 @@ void refusesLegacyUuidIssuerEvenWhenIssuerGenerationMatches() { assertThat(legacyIssuerCandidate.getIssuerAuthGeneration(0)) .isEqualTo(canonicalCandidate.getIssuerAuthGeneration(0)); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( - wire.toBuilder().setExpectedCandidate(0, legacyIssuerCandidate).build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( + wire.toBuilder().setExpectedCandidate(0, legacyIssuerCandidate).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unsupported issuer identity") .hasMessageContaining("legacy UUID issuer identities require explicit recovery"); @@ -392,10 +379,9 @@ void originalNewCredentialCarrierKeepsHandleOpaqueAndRejectsUnboundClaims() thro AccountGameplayAdmissionLeaseGrpcCodec.toResolvedAbortResponse( abortRequest(lease, DECISION_ID), lease, CLEANUP_ID, abortResolution(lease)) .getAbortResolution(0); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.parseIssueOriginalNewCredentialResponse( - request, response.toBuilder().addAbortResolution(resolutionWire).build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.parseIssueOriginalNewCredentialResponse( + request, response.toBuilder().addAbortResolution(resolutionWire).build())) .isInstanceOf(IllegalArgumentException.class); assertAbortRejected( abortRequest(lease, DECISION_ID), @@ -445,10 +431,9 @@ void originalNewCredentialCarrierKeepsHandleOpaqueAndRejectsUnboundClaims() thro leaseFence, "102", checkpointsSha256)) { - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.toIssueOriginalNewCredentialResponse( - request, lease, State.COMMITTED, DECISION_ID, ack, changedCredential)) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.toIssueOriginalNewCredentialResponse( + request, lease, State.COMMITTED, DECISION_ID, ack, changedCredential)) .as("independently rejects changed %s", changedClaim) .isInstanceOf(IllegalArgumentException.class); } @@ -468,49 +453,42 @@ void rejectsMissingDuplicateAndUnknownAcquireAndResponseFields() { .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( - wireRequest.toBuilder().clearExpectedCandidate().build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( + wireRequest.toBuilder().clearExpectedCandidate().build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( - wireRequest.toBuilder().addSchemaVersion(1).build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( + wireRequest.toBuilder().addSchemaVersion(1).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( - wireRequest.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( + wireRequest.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( - wireRequest.toBuilder() - .setExpectedCandidate( - 0, - wireRequest.getExpectedCandidate(0).toBuilder() - .addAccountUuid(OTHER.toString())) - .build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( + wireRequest.toBuilder() + .setExpectedCandidate( + 0, + wireRequest.getExpectedCandidate(0).toBuilder() + .addAccountUuid(OTHER.toString())) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( - wireRequest.toBuilder() - .setExpectedTarget( - 0, - wireRequest.getExpectedTarget(0).toBuilder().setUnknownFields(unknown)) - .build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( + wireRequest.toBuilder() + .setExpectedTarget( + 0, wireRequest.getExpectedTarget(0).toBuilder().setUnknownFields(unknown)) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.toAcquireRequest( - REQUEST_ID, - JWT, - withGameInstance(candidate(lease), OTHER), - target(lease), - new BigInteger(HIGH))) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.toAcquireRequest( + REQUEST_ID, + JWT, + withGameInstance(candidate(lease), OTHER), + target(lease), + new BigInteger(HIGH))) .isInstanceOf(IllegalArgumentException.class); var parsedRequest = AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest(wireRequest); @@ -561,13 +539,12 @@ void rejectsCommittedWithoutCompleteAckAndKeepsAbortDecisionUnknownExplicit() { assertThat(aborted.getBindingDecisionUuidCount()).isZero(); assertThat(aborted.getOriginalLeaseEvidenceUtf8(0).toByteArray()) .containsExactly(originalBytes); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.parseAbortRequest( - abortWire.toBuilder() - .addBindingDecisionUuid(DECISION_ID.toString()) - .addBindingDecisionUuid(OTHER.toString()) - .build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAbortRequest( + abortWire.toBuilder() + .addBindingDecisionUuid(DECISION_ID.toString()) + .addBindingDecisionUuid(OTHER.toString()) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -636,10 +613,9 @@ void rejectsAbortResolutionWithDifferentLeaseCleanupOrSelectedDecision() { resolution.toBuilder().setBindingDecisionUuid(0, OTHER.toString()).build())) { assertAbortRejected(request, response.toBuilder().setAbortResolution(0, changed).build()); } - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.toResolvedAbortResponse( - request, lease, OTHER, abortResolution(lease))) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.toResolvedAbortResponse( + request, lease, OTHER, abortResolution(lease))) .isInstanceOf(IllegalArgumentException.class); } @@ -696,20 +672,13 @@ void rejectsMissingDuplicateUnknownAndNoncanonicalAbortResolutionFields() { assertAbortRejected(request, response.toBuilder().setAbortResolution(0, changed).build()); } } - assertThatThrownBy( - () -> - new AbortResolutionEvidence( - OTHER, OTHER, BigInteger.ZERO, lease.sha256(), CLEANUP_ID, DECISION_ID)) + assertThatThrownBy(() -> + new AbortResolutionEvidence( + OTHER, OTHER, BigInteger.ZERO, lease.sha256(), CLEANUP_ID, DECISION_ID)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AbortResolutionEvidence( - new UUID(0L, 0L), - OTHER, - BigInteger.ONE, - lease.sha256(), - CLEANUP_ID, - DECISION_ID)) + assertThatThrownBy(() -> + new AbortResolutionEvidence( + new UUID(0L, 0L), OTHER, BigInteger.ONE, lease.sha256(), CLEANUP_ID, DECISION_ID)) .isInstanceOf(IllegalArgumentException.class); } @@ -722,10 +691,9 @@ void rejectsAbortResolutionOnUnselectedAbortOtherPurposesAndKnownTerminal() { AccountGameplayAdmissionLeaseGrpcCodec.toResolvedAbortResponse( request, lease, CLEANUP_ID, abortResolution(lease)); assertAbortRejected(abortRequest(lease, null), response); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.toResolvedAbortResponse( - abortRequest(lease, null), lease, CLEANUP_ID, abortResolution(lease))) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.toResolvedAbortResponse( + abortRequest(lease, null), lease, CLEANUP_ID, abortResolution(lease))) .isInstanceOf(IllegalArgumentException.class); var read = AccountGameplayAdmissionLeaseGrpcCodec.parseReadRequest( @@ -758,15 +726,14 @@ void rejectsAbortResolutionOnUnselectedAbortOtherPurposesAndKnownTerminal() { AccountGameplayAdmissionLeaseGrpcCodec.parseIssueOriginalNewCredentialRequest( AccountGameplayAdmissionLeaseGrpcCodec.toIssueOriginalNewCredentialRequest( JWT, leaseBytes)); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.parseIssueOriginalNewCredentialResponse( - credentialRequest, - response.toBuilder() - .addOriginalNewCredential( - net.firedevops.firemud.account.v1.OriginalNewGameplayCredentialResult - .getDefaultInstance()) - .build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.parseIssueOriginalNewCredentialResponse( + credentialRequest, + response.toBuilder() + .addOriginalNewCredential( + net.firedevops.firemud.account.v1.OriginalNewGameplayCredentialResult + .getDefaultInstance()) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -838,10 +805,8 @@ void preservesOriginalBytesAcrossFinalizeAndReadAndRejectsChangedReadback() { 0, ByteString.copyFrom(changedLease.canonicalJson().getBytes(StandardCharsets.UTF_8))) .build(); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.parseReadResponse( - readRequest, changedReadback)) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.parseReadResponse(readRequest, changedReadback)) .isInstanceOf(IllegalArgumentException.class); } @@ -876,20 +841,19 @@ void validatesCompleteAckFenceAndUnsigned64TransactionIds() { assertThat(parsed.originalAckReceipt().finalizationXid()).isEqualTo(uint64MaxMinusOne); assertThat(parsed.originalAckReceipt().receiptXid()).isEqualTo(uint64Max); - assertThatThrownBy( - () -> - OriginalAckReceiptEvidence.fromFields( - 1, - REQUEST_ID, - ACCOUNT_ID, - leaseId, - lease.leaseFence().longValueExact(), - lease.sha256(), - DECISION_ID, - 1_015_000L, - uint64MaxPlusOne, - 1_014_999L, - uint64Max)) + assertThatThrownBy(() -> + OriginalAckReceiptEvidence.fromFields( + 1, + REQUEST_ID, + ACCOUNT_ID, + leaseId, + lease.leaseFence().longValueExact(), + lease.sha256(), + DECISION_ID, + 1_015_000L, + uint64MaxPlusOne, + 1_014_999L, + uint64Max)) .isInstanceOf(IllegalArgumentException.class); var wrongFence = @@ -905,10 +869,9 @@ void validatesCompleteAckFenceAndUnsigned64TransactionIds() { "101", 1_014_999L, "102"); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.toAcquireResponse( - request, lease, State.COMMITTED, DECISION_ID, null, wrongFence)) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.toAcquireResponse( + request, lease, State.COMMITTED, DECISION_ID, null, wrongFence)) .isInstanceOf(IllegalArgumentException.class); UnknownFieldSet unknown = @@ -943,19 +906,17 @@ void rejectsResumeAndExpectedOldGenerationLeaseForms() { resumeCarrier.put("resumeEpisodeId", OTHER.toString()); resumeCarrier.put("expectedOldBindingGeneration", "7"); var resume = AccountGameplayAdmissionLeaseEvidence.fromCarrier(resumeCarrier); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.toReadRequest( - JWT, resume.canonicalJson().getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.toReadRequest( + JWT, resume.canonicalJson().getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); var oldGenerationCarrier = AccountGameplayAdmissionLeaseEvidenceTest.fixture(); oldGenerationCarrier.put("expectedOldBindingGeneration", "7"); var oldGeneration = AccountGameplayAdmissionLeaseEvidence.fromCarrier(oldGenerationCarrier); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.toReadRequest( - JWT, oldGeneration.canonicalJson().getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.toReadRequest( + JWT, oldGeneration.canonicalJson().getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class); } @@ -977,10 +938,9 @@ void enforcesAcquireOriginalLeaseRequestAndResponseWireBounds() { .MAX_ACQUIRE_REQUEST_WIRE_BYTES])) .build()) .build(); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( - acquire.toBuilder().setUnknownFields(oversizedAcquireField).build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest( + acquire.toBuilder().setUnknownFields(oversizedAcquireField).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("wire bound"); @@ -1002,24 +962,19 @@ void enforcesAcquireOriginalLeaseRequestAndResponseWireBounds() { .MAX_ORIGINAL_LEASE_REQUEST_WIRE_BYTES])) .build()) .build(); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeRequest( - finalizeRequest.toBuilder() - .setUnknownFields(oversizedOriginalLeaseField) - .build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeRequest( + finalizeRequest.toBuilder().setUnknownFields(oversizedOriginalLeaseField).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("wire bound"); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.parseReadRequest( - readRequest.toBuilder().setUnknownFields(oversizedOriginalLeaseField).build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.parseReadRequest( + readRequest.toBuilder().setUnknownFields(oversizedOriginalLeaseField).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("wire bound"); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.parseAbortRequest( - abortRequest.toBuilder().setUnknownFields(oversizedOriginalLeaseField).build())) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAbortRequest( + abortRequest.toBuilder().setUnknownFields(oversizedOriginalLeaseField).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("wire bound"); @@ -1043,28 +998,23 @@ void enforcesAcquireOriginalLeaseRequestAndResponseWireBounds() { .build()) .build()) .build(); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireResponse( - parsedAcquire, oversizedResponse)) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireResponse( + parsedAcquire, oversizedResponse)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("wire bound"); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeResponse( - parsedFinalize, oversizedResponse)) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeResponse( + parsedFinalize, oversizedResponse)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("wire bound"); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.parseReadResponse( - parsedRead, oversizedResponse)) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.parseReadResponse(parsedRead, oversizedResponse)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("wire bound"); - assertThatThrownBy( - () -> - AccountGameplayAdmissionLeaseGrpcCodec.parseAbortResponse( - parsedAbort, oversizedResponse)) + assertThatThrownBy(() -> + AccountGameplayAdmissionLeaseGrpcCodec.parseAbortResponse( + parsedAbort, oversizedResponse)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("wire bound"); } diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/CanonicalGameplayAdmissionDecisionReadGrpcCodecTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/CanonicalGameplayAdmissionDecisionReadGrpcCodecTest.java index 48491eb874..e98ee99837 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/CanonicalGameplayAdmissionDecisionReadGrpcCodecTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/admission/CanonicalGameplayAdmissionDecisionReadGrpcCodecTest.java @@ -142,9 +142,8 @@ void discoveryRejectsOpenRequestShapeAndChangedResponseCorrelation() { wire.toBuilder().setReadRequestUuid(0, new UUID(0, 0).toString()).build(), wire.toBuilder().setTargetNamespace(0, "bad/namespace").build(), wire.toBuilder().setUnknownFields(unknown).build())) { - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseDiscoveryRequest(malformed)) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseDiscoveryRequest(malformed)) .isInstanceOf(IllegalArgumentException.class); } var response = @@ -158,10 +157,9 @@ void discoveryRejectsOpenRequestShapeAndChangedResponseCorrelation() { .build(), response.toBuilder().setRequest(0, wire.toBuilder().addTargetNamespace("test")).build(), response.toBuilder().setUnknownFields(unknown).build())) { - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( - request, malformed)) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, malformed)) .isInstanceOf(IllegalArgumentException.class); } } @@ -201,10 +199,9 @@ void discoveryRejectsDuplicateTenantAuthorityAndUnsupportedOrIncompleteTargets() .setCurrentTargets( 0, wire.toBuilder().setHoldBindingDigest(0, "sha256:" + "f".repeat(64))) .build())) { - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( - request, malformed)) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, malformed)) .isInstanceOf(IllegalArgumentException.class); } } @@ -222,10 +219,9 @@ void discoveryEnforcesCompleteTargetAndFourMiBEnvelopeBounds() { response.getCurrentTargets(0).toBuilder() .setWorldDisplayName(0, "x".repeat(64 * 1024)) .build(); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( - request, response.toBuilder().setCurrentTargets(0, oversizedTarget).build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, response.toBuilder().setCurrentTargets(0, oversizedTarget).build())) .isInstanceOf(IllegalArgumentException.class); var boundary = response.toBuilder().clearCurrentTargets(); for (int index = 0; index < 63; index++) { @@ -247,19 +243,17 @@ void discoveryEnforcesCompleteTargetAndFourMiBEnvelopeBounds() { last.setWorldDisplayName(0, last.getWorldDisplayName(0) + "x"); var oversized = complete.toBuilder().setCurrentTargets(63, last).build(); assertThat(oversized.getSerializedSize()).isEqualTo(4 * 1024 * 1024 + 1); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( - request, oversized)) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromDiscoveryResponse( + request, oversized)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("discovery response"); var oneMore = CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetEvidence(last.build()); var tooLargeTargets = new java.util.ArrayList<>(accepted.targets()); tooLargeTargets.set(63, oneMore); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( - request, tooLargeTargets)) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toDiscoveryResponse( + request, tooLargeTargets)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("discovery response"); assertThat(CanonicalGameplayAdmissionDecisionReadGrpcCodec.MAX_DISCOVERY_RESPONSE_WIRE_BYTES) @@ -347,10 +341,9 @@ void resolverRejectsUnknownDuplicateMissingAndChangedOriginalValues() throws Exc request.toBuilder().setUnknownFields(unknown).build(), request.toBuilder().setCatalogRevision(0, "01").build(), request.toBuilder().setPlayableStateScope(0, "ISOLATED").build())) { - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetResolutionRequest( - malformed)) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetResolutionRequest( + malformed)) .isInstanceOf(IllegalArgumentException.class); } var response = @@ -363,10 +356,9 @@ void resolverRejectsUnknownDuplicateMissingAndChangedOriginalValues() throws Exc .setRequest(0, request.toBuilder().setAccountUuid(0, OTHER.toString())) .build(), response.toBuilder().setUnknownFields(unknown).build())) { - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( - selector, malformed)) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( + selector, malformed)) .isInstanceOf(IllegalArgumentException.class); } } @@ -399,10 +391,9 @@ void resolverRejectsEveryRetainedTargetMismatchAndPlayerCreatedSubstitution() th for (var change : changes) { var changed = response.getCurrentTarget(0).toBuilder(); change.accept(changed); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( - selector, response.toBuilder().setCurrentTarget(0, changed).build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromTargetResolutionResponse( + selector, response.toBuilder().setCurrentTarget(0, changed).build())) .isInstanceOf(IllegalArgumentException.class); } } @@ -447,10 +438,9 @@ void strictPublishedReadRequiresOneExactFreshActiveWorldCapture() throws Excepti response.toBuilder() .setWorldLifecycleEvidence(0, ByteString.copyFromUtf8("{}")) .build())) { - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( - request, malformed)) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + request, malformed)) .isInstanceOf(IllegalArgumentException.class); } var original = lifecycle.request(); @@ -475,14 +465,12 @@ void strictPublishedReadRequiresOneExactFreshActiveWorldCapture() throws Excepti copyWorld(lifecycle, original, "TERMINATING", lifecycle.lifecycleEpoch()), copyWorld(lifecycle, original, "ACTIVE", lifecycle.lifecycleEpoch() + 1), copyWorld(lifecycle, changedRequest, "ACTIVE", lifecycle.lifecycleEpoch()))) { - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( - request, - response.toBuilder() - .setWorldLifecycleEvidence( - 0, ByteString.copyFrom(changed.canonicalBytes())) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + request, + response.toBuilder() + .setWorldLifecycleEvidence(0, ByteString.copyFrom(changed.canonicalBytes())) + .build())) .isInstanceOf(IllegalArgumentException.class); } assertThat( @@ -658,20 +646,17 @@ void rejectsMissingDuplicateAndUnknownWireFieldsAtEachClosedLevel() { .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest( - wireRequest.toBuilder().clearExpectedLeaseEvidenceUtf8().build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest( + wireRequest.toBuilder().clearExpectedLeaseEvidenceUtf8().build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest( - wireRequest.toBuilder().addSchemaVersion(1).build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest( + wireRequest.toBuilder().addSchemaVersion(1).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest( - wireRequest.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest( + wireRequest.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class); assertRejected(request, response.toBuilder().clearBindingGeneration().build()); @@ -759,111 +744,96 @@ void roundTripsClosedPublishedRealmSelectorAndCompleteCurrentTarget() throws Exc UnknownFieldSet.newBuilder() .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( - wireRequest.toBuilder().addSchemaVersion(1).build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + wireRequest.toBuilder().addSchemaVersion(1).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( - wireRequest.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + wireRequest.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( - wireRequest.toBuilder() - .setSelector( - 0, wireRequest.getSelector(0).toBuilder().setUnknownFields(unknown)) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + wireRequest.toBuilder() + .setSelector( + 0, wireRequest.getSelector(0).toBuilder().setUnknownFields(unknown)) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( - wireRequest.toBuilder().addSelector(wireRequest.getSelector(0)).build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + wireRequest.toBuilder().addSelector(wireRequest.getSelector(0)).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( - wireRequest.toBuilder() - .setSelector(0, wireRequest.getSelector(0).toBuilder().clearWorldSlug()) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + wireRequest.toBuilder() + .setSelector(0, wireRequest.getSelector(0).toBuilder().clearWorldSlug()) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( - wireRequest.toBuilder().clearSelector().build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + wireRequest.toBuilder().clearSelector().build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( - parsedRequest, response.toBuilder().addSchemaVersion(1).build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, response.toBuilder().addSchemaVersion(1).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( - parsedRequest, response.toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, response.toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( - parsedRequest, - response.toBuilder() - .setPublishedSource( - 0, response.getPublishedSource(0).toBuilder().setUnknownFields(unknown)) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, + response.toBuilder() + .setPublishedSource( + 0, response.getPublishedSource(0).toBuilder().setUnknownFields(unknown)) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( - parsedRequest, response.toBuilder().clearPublishedSource().build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, response.toBuilder().clearPublishedSource().build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( - parsedRequest, - response.toBuilder() - .setPublishedSource( - 0, response.getPublishedSource(0).toBuilder().clearRequest()) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, + response.toBuilder() + .setPublishedSource( + 0, response.getPublishedSource(0).toBuilder().clearRequest()) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( - parsedRequest, - response.toBuilder().addCurrentTarget(response.getCurrentTarget(0)).build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, + response.toBuilder().addCurrentTarget(response.getCurrentTarget(0)).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( - parsedRequest, - response.toBuilder() - .setCurrentTarget( - 0, response.getCurrentTarget(0).toBuilder().setUnknownFields(unknown)) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, + response.toBuilder() + .setCurrentTarget( + 0, response.getCurrentTarget(0).toBuilder().setUnknownFields(unknown)) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( - parsedRequest, - response.toBuilder() - .setCurrentTarget( - 0, response.getCurrentTarget(0).toBuilder().addPointerVersion("74")) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, + response.toBuilder() + .setCurrentTarget( + 0, response.getCurrentTarget(0).toBuilder().addPointerVersion("74")) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( - parsedRequest, - response.toBuilder() - .setPublishedSource( - 0, - response.getPublishedSource(0).toBuilder() - .setRequest( - response.getPublishedSource(0).getRequest().toBuilder() - .setCanonicalTenantUuid(OTHER.toString()))) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, + response.toBuilder() + .setPublishedSource( + 0, + response.getPublishedSource(0).toBuilder() + .setRequest( + response.getPublishedSource(0).getRequest().toBuilder() + .setCanonicalTenantUuid(OTHER.toString()))) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -886,10 +856,9 @@ void rejectsPublishedTargetSourceAndSelectorSubstitutions() throws Exception { targetEvidence.toBuilder().setAdmissionPointerSnapshotDigest(0, "f".repeat(64)).build(), targetEvidence.toBuilder().setOwnerProofDigest(0, "sha256:" + "f".repeat(64)).build(), targetEvidence.toBuilder().setCharacterCreationPolicy(0, "PLAYER_CREATED").build())) { - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( - request, response.toBuilder().setCurrentTarget(0, changed).build())) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + request, response.toBuilder().setCurrentTarget(0, changed).build())) .isInstanceOf(IllegalArgumentException.class); } @@ -900,10 +869,9 @@ void rejectsPublishedTargetSourceAndSelectorSubstitutions() throws Exception { CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmRequest( changedSelector)); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( - changedRequest, response)) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + changedRequest, response)) .isInstanceOf(IllegalArgumentException.class); } @@ -916,10 +884,9 @@ void enforcesPublishedRealmWireBoundsOnRequestAndResponse() throws Exception { request.toBuilder() .setSelector(0, request.getSelector(0).toBuilder().setWorldSlug("x".repeat(3_000))) .build(); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( - oversizedRequest)) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( + oversizedRequest)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("wire bound"); @@ -942,10 +909,9 @@ void enforcesPublishedRealmWireBoundsOnRequestAndResponse() throws Exception { [CanonicalGameplayAdmissionDecisionReadGrpcCodec .MAX_PUBLISHED_REALM_RESPONSE_WIRE_BYTES]))) .build(); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( - parsedRequest, oversizedResponse)) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.fromPublishedRealmResponse( + parsedRequest, oversizedResponse)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("wire bound"); } @@ -1138,18 +1104,17 @@ private static WorldCanonicalInstanceLifecycleEvidence worldLifecycle( null); var participants = content.participantDigests().stream() - .map( - p -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - p.participantKey(), - p.scopeValue(), - p.baseVersionId() != null, - p.baseVersionId(), - p.appliedCommitId(), - p.contentDigest(), - p.digestSchemaVersion(), - p.abilitySchemaDigest() != null, - p.abilitySchemaDigest())) + .map(p -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + p.participantKey(), + p.scopeValue(), + p.baseVersionId() != null, + p.baseVersionId(), + p.appliedCommitId(), + p.contentDigest(), + p.digestSchemaVersion(), + p.abilitySchemaDigest() != null, + p.abilitySchemaDigest())) .toList(); var release = AuthoredWorldReleaseAttestationEvidence.create( @@ -1344,25 +1309,19 @@ private static ReleaseContent publishedRelease( var request = operation.world().request(); var participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new Participant( - owner, - Long.toString( - operation - .account() - .input() - .selection() - .target() - .gameDesignVersionRowId()), - null, - request.appliedCommitId(), - owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - owner.equals("GAME_LOGIC") ? DIGEST : null, - null, - null)) + .map(owner -> + new Participant( + owner, + Long.toString( + operation.account().input().selection().target().gameDesignVersionRowId()), + null, + request.appliedCommitId(), + owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + owner.equals("GAME_LOGIC") ? DIGEST : null, + null, + null)) .toList(); return new ReleaseContent( request.canonicalTenantId(), diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationAcquisitionClientMtlsTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationAcquisitionClientMtlsTest.java index 3e33b645c7..43ac565aa1 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationAcquisitionClientMtlsTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/account/startsession/AccountStartSessionWorldParticipationAcquisitionClientMtlsTest.java @@ -204,10 +204,9 @@ void wrongAuthenticatedWorkloadsAndLocalNamespaceMismatchAreRejected() throws Ex client.init(); assertThatThrownBy(() -> client.acquire(wireRequest)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); client.close(); client = null; } @@ -233,10 +232,9 @@ void wrongAccountServerWorkloadIsRejectedBeforeSendingTheRequest() throws Except assertThatThrownBy(() -> client.acquire(request(NAMESPACE))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(handlers).hasValue(0); verifyNoInteractions(backend); } diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java index bcd03f253b..960bd070bf 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/GameplaySessionAttestationServiceTest.java @@ -26,10 +26,8 @@ void requireGameplaySessionMatchAcceptsCanonicalNonNilAccountUuid() { service.issueGameplaySessionAttestation( "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); - assertDoesNotThrow( - () -> - service.requireGameplaySessionMatch( - token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); + assertDoesNotThrow(() -> + service.requireGameplaySessionMatch(token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); } @Test @@ -119,10 +117,8 @@ void requireGameplaySessionMatchAllowsAlphanumericRoomInstanceId() { service.issueGameplaySessionAttestation( "22", "41", ACCOUNT_UUID, "123", "1", "R-1021", "demo", "production", "17", "SHARED"); - assertDoesNotThrow( - () -> - service.requireGameplaySessionMatch( - token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); + assertDoesNotThrow(() -> + service.requireGameplaySessionMatch(token, "22", "41", ACCOUNT_UUID, "123", "1", "R-1021")); } @Test diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/PublicationReadGuardTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/PublicationReadGuardTest.java index b8bd72c90d..a692a5b2e1 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/PublicationReadGuardTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/PublicationReadGuardTest.java @@ -51,40 +51,33 @@ void protectsExactlyTheGeneratedPublicationDigestMethods() { @Test void allowsAllFourExactPublicationReadsWithWorkloadOnlyContext() { - withPeer( - () -> { - SessionContext.setContext( - null, List.of(), Map.of(), true, "game-design-service", "game-design-instance"); - for (String method : PublicationReadGuard.PUBLICATION_READ_METHODS) { - guard.requirePublicationRead(method); - } - }); + withPeer(() -> { + SessionContext.setContext( + null, List.of(), Map.of(), true, "game-design-service", "game-design-instance"); + for (String method : PublicationReadGuard.PUBLICATION_READ_METHODS) { + guard.requirePublicationRead(method); + } + }); } @Test void deniesAuthenticatedUserContextEvenWithGameDesignPeer() { - withPeer( - () -> { - SessionContext.setContext("42", List.of(), Map.of()); - assertThatThrownBy( - () -> - guard.requirePublicationRead( - PublicationReadGuard.WORLD_MANAGEMENT_DIGEST_METHOD)) - .isInstanceOf(AdminAuthorizationException.class); - }); + withPeer(() -> { + SessionContext.setContext("42", List.of(), Map.of()); + assertThatThrownBy(() -> + guard.requirePublicationRead(PublicationReadGuard.WORLD_MANAGEMENT_DIGEST_METHOD)) + .isInstanceOf(AdminAuthorizationException.class); + }); } @Test void deniesAuthenticatedAdminContextEvenWithGameDesignPeer() { - withPeer( - () -> { - SessionContext.setContext("7", List.of("platformAdmin"), Map.of()); - assertThatThrownBy( - () -> - guard.requirePublicationRead( - PublicationReadGuard.AUTOMATION_SCRIPTING_DIGEST_METHOD)) - .isInstanceOf(AdminAuthorizationException.class); - }); + withPeer(() -> { + SessionContext.setContext("7", List.of("platformAdmin"), Map.of()); + assertThatThrownBy(() -> + guard.requirePublicationRead(PublicationReadGuard.AUTOMATION_SCRIPTING_DIGEST_METHOD)) + .isInstanceOf(AdminAuthorizationException.class); + }); } @Test @@ -118,10 +111,9 @@ void deniesGameDesignPeerFromWrongNamespace() { withPeer( wrongNamespacePeer, () -> - assertThatThrownBy( - () -> - guard.requirePublicationRead( - PublicationReadGuard.ENTITY_MANAGEMENT_DIGEST_METHOD)) + assertThatThrownBy(() -> + guard.requirePublicationRead( + PublicationReadGuard.ENTITY_MANAGEMENT_DIGEST_METHOD)) .isInstanceOf(AdminAuthorizationException.class)); } diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientMtlsTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientMtlsTest.java index 237e380ec9..9bc2c2df6d 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientMtlsTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientMtlsTest.java @@ -157,10 +157,9 @@ void loopbackMtlsReturnsExactReceiptAndPinsAutomationServerWithBoundedDeadline() client.init(); assertThatThrownBy(() -> client.retain(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(headers).hasValue(0); assertThat(bodies).hasValue(0); } diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientTest.java index c147e4bb4b..7bb5ccd048 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientTest.java @@ -36,10 +36,9 @@ void requiresReadableFileBackedMtlsAndCanonicalNamespace(@TempDir Path directory var channelFactory = mock(GrpcChannelFactory.class); var plaintext = tls(directory); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new GrpcAutomationSelectedSourceIntakeCommandClient( - new ServiceEndpointsProperties(), plaintext, channelFactory, "test")) + assertThatThrownBy(() -> + new GrpcAutomationSelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mTLS"); @@ -53,30 +52,26 @@ void requiresReadableFileBackedMtlsAndCanonicalNamespace(@TempDir Path directory }) { var invalidCertificate = tls(directory); invalidCertificate.setCertChain(invalidPath); - assertThatThrownBy( - () -> - new GrpcAutomationSelectedSourceIntakeCommandClient( - new ServiceEndpointsProperties(), invalidCertificate, channelFactory, "test")) + assertThatThrownBy(() -> + new GrpcAutomationSelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), invalidCertificate, channelFactory, "test")) .isInstanceOf(IllegalArgumentException.class); } var invalidKey = tls(directory); invalidKey.setPrivateKey(directory.resolve("missing-key.pem").toString()); - assertThatThrownBy( - () -> - new GrpcAutomationSelectedSourceIntakeCommandClient( - new ServiceEndpointsProperties(), invalidKey, channelFactory, "test")) + assertThatThrownBy(() -> + new GrpcAutomationSelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), invalidKey, channelFactory, "test")) .isInstanceOf(IllegalArgumentException.class); var invalidCa = tls(directory); invalidCa.setCaCert(directory.resolve("missing-ca.pem").toString()); - assertThatThrownBy( - () -> - new GrpcAutomationSelectedSourceIntakeCommandClient( - new ServiceEndpointsProperties(), invalidCa, channelFactory, "test")) + assertThatThrownBy(() -> + new GrpcAutomationSelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), invalidCa, channelFactory, "test")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GrpcAutomationSelectedSourceIntakeCommandClient( - new ServiceEndpointsProperties(), tls(directory), channelFactory, "Test")) + assertThatThrownBy(() -> + new GrpcAutomationSelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), tls(directory), channelFactory, "Test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("namespace"); diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClientMtlsTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClientMtlsTest.java index 516a564fa6..100625a566 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClientMtlsTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClientMtlsTest.java @@ -122,10 +122,9 @@ void loopbackMtlsReturnsExactReceiptAndPinsEntityServerWithBoundedDeadline() thr client.init(); assertThatThrownBy(() -> client.retain(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(headers).hasValue(0); assertThat(bodies).hasValue(0); } diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeCommandClientLifecycleTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeCommandClientLifecycleTest.java index 0d4d9bdacd..fe694a4861 100644 --- a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeCommandClientLifecycleTest.java +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeCommandClientLifecycleTest.java @@ -62,12 +62,11 @@ void closeReleasesClientMonitorBeforeDrainingCertificateCallback( GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); when(channelFactory.buildChannel( any(String.class), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) - .thenAnswer( - invocation -> { - ManagedChannel channel = mock(ManagedChannel.class); - channels.add(channel); - return channel; - }); + .thenAnswer(invocation -> { + ManagedChannel channel = mock(ManagedChannel.class); + channels.add(channel); + return channel; + }); ClientHandle handle = kind.create(endpoints, tls, channelFactory); client = handle.client(); handle.initialize().run(); diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java index cc932124fa..a037d4f16f 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/config/CommonSecurityAutoConfigurationTest.java @@ -47,13 +47,12 @@ void registersSharedGrpcAuthInterceptorWhenEnabled() { .withPropertyValues( "firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234", "firemud.auth.grpc.public-methods[0]=firemud.gateway.v1.GatewayManagementService/Ping") - .run( - ctx -> { - assertThat(ctx).hasSingleBean(AuthTokenInterceptor.class); - GrpcAuthProperties props = ctx.getBean(GrpcAuthProperties.class); - assertThat(props.getPublicMethods()) - .containsExactly("firemud.gateway.v1.GatewayManagementService/Ping"); - }); + .run(ctx -> { + assertThat(ctx).hasSingleBean(AuthTokenInterceptor.class); + GrpcAuthProperties props = ctx.getBean(GrpcAuthProperties.class); + assertThat(props.getPublicMethods()) + .containsExactly("firemud.gateway.v1.GatewayManagementService/Ping"); + }); } @Test @@ -69,14 +68,13 @@ void registersSharedHttpAuthWhenEnabled() { "firemud.auth.http.enabled=true", "firemud.auth.http.public-routes[0].method=GET", "firemud.auth.http.public-routes[0].path-pattern=/ping") - .run( - ctx -> { - assertThat(ctx).hasSingleBean(HttpJwtAuthInterceptor.class); - HttpAuthProperties props = ctx.getBean(HttpAuthProperties.class); - assertThat(props.getPublicRoutes()).hasSize(1); - assertThat(props.getPublicRoutes().get(0).getMethod()).isEqualTo("GET"); - assertThat(props.getPublicRoutes().get(0).getPathPattern()).isEqualTo("/ping"); - }); + .run(ctx -> { + assertThat(ctx).hasSingleBean(HttpJwtAuthInterceptor.class); + HttpAuthProperties props = ctx.getBean(HttpAuthProperties.class); + assertThat(props.getPublicRoutes()).hasSize(1); + assertThat(props.getPublicRoutes().get(0).getMethod()).isEqualTo("GET"); + assertThat(props.getPublicRoutes().get(0).getPathPattern()).isEqualTo("/ping"); + }); } @Test @@ -90,11 +88,10 @@ void reactiveAppsDoNotLoadServletHttpAuthAutoConfiguration() { .withPropertyValues( "firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234", "firemud.auth.http.enabled=true") - .run( - ctx -> { - assertThat(ctx).doesNotHaveBean(HttpJwtAuthInterceptor.class); - assertThat(ctx).hasSingleBean(JwtUtil.class); - }); + .run(ctx -> { + assertThat(ctx).doesNotHaveBean(HttpJwtAuthInterceptor.class); + assertThat(ctx).hasSingleBean(JwtUtil.class); + }); } @Test @@ -103,11 +100,10 @@ void sharedGrpcAuthInterceptorCanBeDisabledForCustomServerPolicy() { .withPropertyValues( "firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234", "firemud.auth.grpc.interceptor-enabled=false") - .run( - ctx -> { - assertThat(ctx).doesNotHaveBean(AuthTokenInterceptor.class); - assertThat(ctx).hasSingleBean(JwtUtil.class); - }); + .run(ctx -> { + assertThat(ctx).doesNotHaveBean(AuthTokenInterceptor.class); + assertThat(ctx).hasSingleBean(JwtUtil.class); + }); } @Test @@ -116,49 +112,46 @@ void configuredPublicMethodsBypassBearerRequirement() { .withPropertyValues( "firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234", "firemud.auth.grpc.public-methods[0]=demo.Service/Ping") - .run( - ctx -> { - AuthTokenInterceptor interceptor = ctx.getBean(AuthTokenInterceptor.class); - @SuppressWarnings({"rawtypes", "unchecked"}) - ServerCall call = Mockito.mock(ServerCall.class); - @SuppressWarnings({"rawtypes", "unchecked"}) - ServerCallHandler next = Mockito.mock(ServerCallHandler.class); - MethodDescriptor methodDescriptor = unaryMethod("demo.Service/Ping"); - Mockito.when(call.getMethodDescriptor()).thenReturn(methodDescriptor); - Mockito.when( - next.startCall(Mockito.any(ServerCall.class), Mockito.any(Metadata.class))) - .thenReturn(new ServerCall.Listener<>() {}); - - interceptor.interceptCall(call, new Metadata(), next); - - ArgumentCaptor forwardedCallCaptor = - ArgumentCaptor.forClass(ServerCall.class); - Mockito.verify(next) - .startCall(forwardedCallCaptor.capture(), Mockito.any(Metadata.class)); - ServerCall forwardedCall = forwardedCallCaptor.getValue(); - assertThat(forwardedCall).isNotSameAs(call); - assertThat(forwardedCall.getMethodDescriptor()).isSameAs(methodDescriptor); - - forwardedCall.close(Status.OK, new Metadata()); - Mockito.verify(call).close(Mockito.eq(Status.OK), Mockito.any(Metadata.class)); - }); + .run(ctx -> { + AuthTokenInterceptor interceptor = ctx.getBean(AuthTokenInterceptor.class); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = Mockito.mock(ServerCall.class); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCallHandler next = Mockito.mock(ServerCallHandler.class); + MethodDescriptor methodDescriptor = unaryMethod("demo.Service/Ping"); + Mockito.when(call.getMethodDescriptor()).thenReturn(methodDescriptor); + Mockito.when(next.startCall(Mockito.any(ServerCall.class), Mockito.any(Metadata.class))) + .thenReturn(new ServerCall.Listener<>() {}); + + interceptor.interceptCall(call, new Metadata(), next); + + ArgumentCaptor forwardedCallCaptor = + ArgumentCaptor.forClass(ServerCall.class); + Mockito.verify(next) + .startCall(forwardedCallCaptor.capture(), Mockito.any(Metadata.class)); + ServerCall forwardedCall = forwardedCallCaptor.getValue(); + assertThat(forwardedCall).isNotSameAs(call); + assertThat(forwardedCall.getMethodDescriptor()).isSameAs(methodDescriptor); + + forwardedCall.close(Status.OK, new Metadata()); + Mockito.verify(call).close(Mockito.eq(Status.OK), Mockito.any(Metadata.class)); + }); } @Test void jwtUtilStillCarriesRoleClaims() { contextRunner .withPropertyValues("firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234") - .run( - ctx -> { - JwtUtil jwtUtil = ctx.getBean(JwtUtil.class); - String token = - jwtUtil.generateToken( - "user", java.util.Map.of("globalRoles", List.of("platformAdmin"))); - Jws claims = jwtUtil.parseToken(token); - assertThat(claims.getPayload().getSubject()).isEqualTo("user"); - assertThat(claims.getPayload().get("globalRoles", List.class)) - .containsExactly("platformAdmin"); - }); + .run(ctx -> { + JwtUtil jwtUtil = ctx.getBean(JwtUtil.class); + String token = + jwtUtil.generateToken( + "user", java.util.Map.of("globalRoles", List.of("platformAdmin"))); + Jws claims = jwtUtil.parseToken(token); + assertThat(claims.getPayload().getSubject()).isEqualTo("user"); + assertThat(claims.getPayload().get("globalRoles", List.class)) + .containsExactly("platformAdmin"); + }); } @Test @@ -168,38 +161,34 @@ void jwtUtilCanInitializeFromSecretPathWithoutInlineSecret() throws Exception { contextRunner .withPropertyValues("firemud.auth.jwt-secret-path=" + secretFile) - .run( - ctx -> { - assertThat(ctx).hasSingleBean(JwtUtil.class); - JwtUtil jwtUtil = ctx.getBean(JwtUtil.class); - String token = jwtUtil.generateToken("user", java.util.Map.of()); - Jws claims = jwtUtil.parseToken(token); - assertThat(claims.getPayload().getSubject()).isEqualTo("user"); - }); + .run(ctx -> { + assertThat(ctx).hasSingleBean(JwtUtil.class); + JwtUtil jwtUtil = ctx.getBean(JwtUtil.class); + String token = jwtUtil.generateToken("user", java.util.Map.of()); + Jws claims = jwtUtil.parseToken(token); + assertThat(claims.getPayload().getSubject()).isEqualTo("user"); + }); } @Test void protectedMethodsStillRequireBearerToken() { contextRunner .withPropertyValues("firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234") - .run( - ctx -> { - AuthTokenInterceptor interceptor = ctx.getBean(AuthTokenInterceptor.class); - @SuppressWarnings({"rawtypes", "unchecked"}) - ServerCall call = Mockito.mock(ServerCall.class); - @SuppressWarnings({"rawtypes", "unchecked"}) - ServerCallHandler next = Mockito.mock(ServerCallHandler.class); - MethodDescriptor methodDescriptor = - unaryMethod("demo.Service/Protected"); - Mockito.when(call.getMethodDescriptor()).thenReturn(methodDescriptor); - - interceptor.interceptCall(call, new Metadata(), next); - - ArgumentCaptor statusCaptor = ArgumentCaptor.forClass(Status.class); - Mockito.verify(call).close(statusCaptor.capture(), Mockito.any(Metadata.class)); - assertThat(statusCaptor.getValue().getCode()) - .isEqualTo(Status.UNAUTHENTICATED.getCode()); - }); + .run(ctx -> { + AuthTokenInterceptor interceptor = ctx.getBean(AuthTokenInterceptor.class); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCall call = Mockito.mock(ServerCall.class); + @SuppressWarnings({"rawtypes", "unchecked"}) + ServerCallHandler next = Mockito.mock(ServerCallHandler.class); + MethodDescriptor methodDescriptor = unaryMethod("demo.Service/Protected"); + Mockito.when(call.getMethodDescriptor()).thenReturn(methodDescriptor); + + interceptor.interceptCall(call, new Metadata(), next); + + ArgumentCaptor statusCaptor = ArgumentCaptor.forClass(Status.class); + Mockito.verify(call).close(statusCaptor.capture(), Mockito.any(Metadata.class)); + assertThat(statusCaptor.getValue().getCode()).isEqualTo(Status.UNAUTHENTICATED.getCode()); + }); } @Test @@ -219,13 +208,12 @@ void outboundStubCustomizerCanForceInternalServiceIdentity() { .withPropertyValues( "firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234", "firemud.auth.grpc.force-internal-service-outbound=true") - .run( - ctx -> { - BlockingGrpcStubCustomizer customizer = ctx.getBean(BlockingGrpcStubCustomizer.class); - CapturingStub stub = new CapturingStub(); + .run(ctx -> { + BlockingGrpcStubCustomizer customizer = ctx.getBean(BlockingGrpcStubCustomizer.class); + CapturingStub stub = new CapturingStub(); - assertThat(customizer.customize(stub)).isNotSameAs(stub); - }); + assertThat(customizer.customize(stub)).isNotSameAs(stub); + }); } private MethodDescriptor unaryMethod(String fullMethodName) { diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/gamesession/CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodecTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/gamesession/CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodecTest.java index bb2e0a058f..520d9d5e92 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/gamesession/CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodecTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/gamesession/CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodecTest.java @@ -46,34 +46,28 @@ void requestAndActualFinalSessionMetadataRoundTripWithoutCredentialBytes() { void requestRequiresOneVersionAndOneCanonicalSelectorPayload() { var request = CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.toRequest(selector()); - assertThatThrownBy( - () -> - CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.parseRequest( - request.toBuilder().clearSchemaVersion().build())) + assertThatThrownBy(() -> + CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.parseRequest( + request.toBuilder().clearSchemaVersion().build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.parseRequest( - request.toBuilder().addSchemaVersion(1).build())) + assertThatThrownBy(() -> + CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.parseRequest( + request.toBuilder().addSchemaVersion(1).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.parseRequest( - request.toBuilder() - .addExpectedOriginalAdmissionJson( - request.getExpectedOriginalAdmissionJson(0)) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.parseRequest( + request.toBuilder() + .addExpectedOriginalAdmissionJson(request.getExpectedOriginalAdmissionJson(0)) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.parseRequest( - request.toBuilder() - .setUnknownFields( - UnknownFieldSet.newBuilder() - .addField( - 99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) - .build()) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.parseRequest( + request.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -87,30 +81,27 @@ void requestRejectsDuplicateUnknownAndNonCanonicalJson() { + UUID.randomUUID() + "\"}"; - assertThatThrownBy( - () -> - CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.parseRequest( - request.toBuilder() - .setExpectedOriginalAdmissionJson( - 0, ByteString.copyFrom(duplicate, StandardCharsets.UTF_8)) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.parseRequest( + request.toBuilder() + .setExpectedOriginalAdmissionJson( + 0, ByteString.copyFrom(duplicate, StandardCharsets.UTF_8)) + .build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.parseRequest( - request.toBuilder() - .setExpectedOriginalAdmissionJson( - 0, ByteString.copyFrom(canonical + " ", StandardCharsets.UTF_8)) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.parseRequest( + request.toBuilder() + .setExpectedOriginalAdmissionJson( + 0, ByteString.copyFrom(canonical + " ", StandardCharsets.UTF_8)) + .build())) .isInstanceOf(IllegalArgumentException.class); String unknown = canonical.substring(0, canonical.length() - 1) + ",\"unexpected\":\"x\"}"; - assertThatThrownBy( - () -> - CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.parseRequest( - request.toBuilder() - .setExpectedOriginalAdmissionJson( - 0, ByteString.copyFrom(unknown, StandardCharsets.UTF_8)) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.parseRequest( + request.toBuilder() + .setExpectedOriginalAdmissionJson( + 0, ByteString.copyFrom(unknown, StandardCharsets.UTF_8)) + .build())) .isInstanceOf(IllegalArgumentException.class); } @@ -123,14 +114,13 @@ void responseRequiresExactActualAnchorsAndValidContinuityArithmetic() { String original = response.getActualFinalAdmissionJson(0).toStringUtf8(); String changedHash = original.replace(HASH, OTHER_HASH); - assertThatThrownBy( - () -> - CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.fromResponse( - selector, - response.toBuilder() - .setActualFinalAdmissionJson( - 0, ByteString.copyFrom(changedHash, StandardCharsets.UTF_8)) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.fromResponse( + selector, + response.toBuilder() + .setActualFinalAdmissionJson( + 0, ByteString.copyFrom(changedHash, StandardCharsets.UTF_8)) + .build())) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> new FinalResult(selector, 1_000L, 60_999L, 60_000L, OTHER_HASH)) .isInstanceOf(IllegalArgumentException.class); @@ -149,28 +139,26 @@ void controlledResponseRejectsRebindHandleAndSessionHashMismatches() { "\"rebindHandleSha256\":\"" + HASH + "\"", "\"rebindHandleSha256\":\"" + OTHER_HASH + "\""); assertThat(changedHandle).isNotEqualTo(original); - assertThatThrownBy( - () -> - CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.fromResponse( - selector, - response.toBuilder() - .setActualFinalAdmissionJson( - 0, ByteString.copyFrom(changedHandle, StandardCharsets.UTF_8)) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.fromResponse( + selector, + response.toBuilder() + .setActualFinalAdmissionJson( + 0, ByteString.copyFrom(changedHandle, StandardCharsets.UTF_8)) + .build())) .isInstanceOf(IllegalArgumentException.class); String changedTokenHash = original.replace( "\"tokenSha256\":\"" + HASH + "\"", "\"tokenSha256\":\"" + OTHER_HASH + "\""); assertThat(changedTokenHash).isNotEqualTo(original); - assertThatThrownBy( - () -> - CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.fromResponse( - selector, - response.toBuilder() - .setActualFinalAdmissionJson( - 0, ByteString.copyFrom(changedTokenHash, StandardCharsets.UTF_8)) - .build())) + assertThatThrownBy(() -> + CanonicalGameplayOriginalNewFinalAdmissionReadGrpcCodec.fromResponse( + selector, + response.toBuilder() + .setActualFinalAdmissionJson( + 0, ByteString.copyFrom(changedTokenHash, StandardCharsets.UTF_8)) + .build())) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksCacheTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksCacheTest.java index ecdabb1343..2c99847fc1 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksCacheTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksCacheTest.java @@ -126,12 +126,11 @@ public long preparedDenyEpoch() { epoch.incrementAndGet(); denied.set(true); var invalidate = - executor.submit( - () -> { - assertThatThrownBy(() -> cache.keyFor("known")) - .isInstanceOf(AccountPublicJwksCache.SourcePreparedDenyException.class); - cache.invalidateKid("cut"); - }); + executor.submit(() -> { + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.SourcePreparedDenyException.class); + cache.invalidateKid("cut"); + }); invalidate.get(5, TimeUnit.SECONDS); // A full source recovery cannot authorize the older cache flight's pre-deny bytes. denied.set(false); @@ -241,16 +240,15 @@ void blockedProactiveLoadAllowsFreshBoundReadsAndImmediateInvalidation() throws try { assertThat(source.entered.await(5, TimeUnit.SECONDS)).isTrue(); var readAndInvalidate = - executor.submit( - () -> { - assertThat(cache.keyFor("known", PIN, sha256(first))).isEqualTo(key.getPublic()); - assertThatThrownBy(() -> cache.keyFor("known", PIN, sha256(second))) - .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); - cache.invalidateKid("known"); - assertThatThrownBy(() -> cache.keyFor("known")) - .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class); - return null; - }); + executor.submit(() -> { + assertThat(cache.keyFor("known", PIN, sha256(first))).isEqualTo(key.getPublic()); + assertThatThrownBy(() -> cache.keyFor("known", PIN, sha256(second))) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + cache.invalidateKid("known"); + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(AccountPublicJwksCache.UnknownKeyException.class); + return null; + }); readAndInvalidate.get(5, TimeUnit.SECONDS); } finally { source.release.countDown(); @@ -278,34 +276,30 @@ void proactiveUnknownAndStaleRequestsShareOneFlightInEitherOrder() throws Except cache.refresh(); try (var executor = Executors.newFixedThreadPool(3)) { var firstRequest = - executor.submit( - () -> { - if (demandFirst) { - assertThat(cache.keyFor("rotated", PIN, sha256(second))) - .isEqualTo(key.getPublic()); - } else { - cache.refresh(); - } - return null; - }); + executor.submit(() -> { + if (demandFirst) { + assertThat(cache.keyFor("rotated", PIN, sha256(second))).isEqualTo(key.getPublic()); + } else { + cache.refresh(); + } + return null; + }); try { assertThat(source.entered.await(5, TimeUnit.SECONDS)).isTrue(); AtomicReference proactiveThread = new AtomicReference<>(); var proactive = - executor.submit( - () -> { - proactiveThread.set(Thread.currentThread()); - cache.refresh(); - }); + executor.submit(() -> { + proactiveThread.set(Thread.currentThread()); + cache.refresh(); + }); awaitWaiting(proactiveThread); clock.advance(Duration.ofSeconds(11)); AtomicReference staleThread = new AtomicReference<>(); var stale = - executor.submit( - () -> { - staleThread.set(Thread.currentThread()); - return cache.keyFor("known", PIN, sha256(second)); - }); + executor.submit(() -> { + staleThread.set(Thread.currentThread()); + return cache.keyFor("known", PIN, sha256(second)); + }); awaitWaiting(staleThread); assertThat(source.loads).hasValue(2); source.release.countDown(); @@ -332,20 +326,18 @@ void proactiveJoinPermanentlyRejectsInvalidDemandFlight() throws Exception { cache.refresh(); try (var executor = Executors.newFixedThreadPool(2)) { var demand = - executor.submit( - () -> - assertThatThrownBy(() -> cache.keyFor("unknown")) - .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class)); + executor.submit(() -> + assertThatThrownBy(() -> cache.keyFor("unknown")) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class)); try { assertThat(source.entered.await(5, TimeUnit.SECONDS)).isTrue(); AtomicReference proactiveThread = new AtomicReference<>(); var proactive = - executor.submit( - () -> { - proactiveThread.set(Thread.currentThread()); - assertThatThrownBy(cache::refresh) - .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); - }); + executor.submit(() -> { + proactiveThread.set(Thread.currentThread()); + assertThatThrownBy(cache::refresh) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + }); awaitWaiting(proactiveThread); source.release.countDown(); demand.get(5, TimeUnit.SECONDS); @@ -376,10 +368,9 @@ void blockedRefreshOutageCannotUseSnapshotThatExpiredDuringLoad() throws Excepti cache.refresh(); try (var executor = Executors.newSingleThreadExecutor()) { var refresh = - executor.submit( - () -> - assertThatThrownBy(cache::refresh) - .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class)); + executor.submit(() -> + assertThatThrownBy(cache::refresh) + .isInstanceOf(AccountPublicJwksCache.SourceUnavailableException.class)); try { assertThat(source.entered.await(5, TimeUnit.SECONDS)).isTrue(); assertThat(cache.keyFor("known")).isEqualTo(key.getPublic()); @@ -475,20 +466,18 @@ void proactiveRefreshOutagesNeverExtendAgeAndDeniedKidsStayDenied() throws Excep KeyPair key = rsa3072(); MutableClock clock = new MutableClock(INITIAL); AtomicReference current = - new AtomicReference<>( - () -> - snapshot( - jwks( - jwk("known", (RSAPublicKey) key.getPublic()) - + "," - + jwk("denied", (RSAPublicKey) key.getPublic())))); + new AtomicReference<>(() -> + snapshot( + jwks( + jwk("known", (RSAPublicKey) key.getPublic()) + + "," + + jwk("denied", (RSAPublicKey) key.getPublic())))); var cache = cache(clock, () -> current.get().load()); cache.refresh(); cache.invalidateKid("denied"); - current.set( - () -> { - throw new AccountPublicJwksCache.SourceUnavailableException(); - }); + current.set(() -> { + throw new AccountPublicJwksCache.SourceUnavailableException(); + }); clock.advance(Duration.ofSeconds(3)); cache.refresh(); clock.advance(Duration.ofSeconds(3)); @@ -611,11 +600,10 @@ void concurrentRefreshCannotPairAKeyWithAnotherSnapshotsBinding() throws Excepti clock.advance(Duration.ofSeconds(11)); try (var executor = java.util.concurrent.Executors.newFixedThreadPool(2)) { var oldBinding = - executor.submit( - () -> { - assertThatThrownBy(() -> cache.keyFor("known", PIN, sha256(first))) - .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); - }); + executor.submit(() -> { + assertThatThrownBy(() -> cache.keyFor("known", PIN, sha256(first))) + .isInstanceOf(AccountPublicJwksCache.InvalidJwksException.class); + }); try { assertThat(refreshEntered.await(5, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); var newBinding = executor.submit(() -> cache.keyFor("known", PIN, sha256(second))); diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksReadCodecTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksReadCodecTest.java index 5ec076fe42..e36fd82775 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksReadCodecTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AccountPublicJwksReadCodecTest.java @@ -132,10 +132,9 @@ void localResultRejectsDenyWithBytesOrRecoveryClaimAndCopiesBytes() { new Object[][] { {new byte[] {1}, true, false}, {new byte[0], true, true}, {new byte[0], false, false} }) { - assertThatThrownBy( - () -> - new AccountPublicJwksReadCodec.ReadResult( - PIN, (byte[]) invalid[0], (boolean) invalid[1], (boolean) invalid[2])) + assertThatThrownBy(() -> + new AccountPublicJwksReadCodec.ReadResult( + PIN, (byte[]) invalid[0], (boolean) invalid[1], (boolean) invalid[2])) .isInstanceOf(AccountPublicJwksReadCodec.InvalidFrameException.class); } byte[] bytes = {1}; diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java index 8ccfd93c43..426b8871da 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java @@ -386,16 +386,15 @@ public Listener startCall(ServerCall serverCall, Metadata h assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); seedStaleCallerContext(); - assertThatThrownBy( - () -> - interceptor.interceptCall( - call, - new Metadata(), - (serverCall, headers) -> { - assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); - seedStaleCallerContext(); - throw new IllegalStateException("failed startCall"); - })) + assertThatThrownBy(() -> + interceptor.interceptCall( + call, + new Metadata(), + (serverCall, headers) -> { + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + seedStaleCallerContext(); + throw new IllegalStateException("failed startCall"); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("failed startCall"); assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationJwtProfileValidatorTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationJwtProfileValidatorTest.java index 253ba0c2dd..e6521f12f3 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationJwtProfileValidatorTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationJwtProfileValidatorTest.java @@ -26,10 +26,8 @@ void independentlyScopedAccountAndTenantUuidsMayEqualWithoutRelaxingExactMapKeys claims.put("tenantId", ACCOUNT); claims.put("authorityTuple", tuple); claims.put("membershipVersion", Map.of(ACCOUNT, "3")); - assertThatCode( - () -> - GameSessionAccountDelegationJwtProfileValidator.validatePublicTenantBoundClaims( - claims)) + assertThatCode(() -> + GameSessionAccountDelegationJwtProfileValidator.validatePublicTenantBoundClaims(claims)) .doesNotThrowAnyException(); assertThatThrownBy( () -> GameSessionAccountDelegationJwtProfileValidator.validateInitialClaims(claims)) diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfileTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfileTest.java index 6add388f56..44c4627f02 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfileTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationProfileTest.java @@ -68,37 +68,33 @@ void includesOnlyAnExplicitlyApplicableAccountCutoff() { @Test void rejectsMalformedCutoffCountersAndNonAccountStreamScopes() { - assertThatThrownBy( - () -> - new AccountSecurityCutoff( - "12", - "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", - "044")) + assertThatThrownBy(() -> + new AccountSecurityCutoff( + "12", + "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "044")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountSecurityCutoff( - "12", - "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", - "0")) + assertThatThrownBy(() -> + new AccountSecurityCutoff( + "12", + "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "0")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountSecurityCutoff( - "12", - "account:auth-authority:v1:tenant/11111111-1111-4111-8111-111111111111", - "44")) + assertThatThrownBy(() -> + new AccountSecurityCutoff( + "12", + "account:auth-authority:v1:tenant/11111111-1111-4111-8111-111111111111", + "44")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameSessionAccountDelegationProfile.authorityTuple( - 7L, - 12L, - Optional.of( - new AccountSecurityCutoff( - "11", - "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", - "44")))) + assertThatThrownBy(() -> + GameSessionAccountDelegationProfile.authorityTuple( + 7L, + 12L, + Optional.of( + new AccountSecurityCutoff( + "11", + "account:auth-authority:v1:account/11111111-1111-4111-8111-111111111111", + "44")))) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecordTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecordTest.java index 075f9731d5..488ff1e4d6 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecordTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GameSessionAccountDelegationRegistryRecordTest.java @@ -62,19 +62,18 @@ void boundRegistryRoundTripsEqualValuesInIndependentAccountAndTenantUuidDomains( assertThat(decoded.fields().get("membershipVersion")).isEqualTo(Map.of(ACCOUNT_ID, "3")); assertThatThrownBy(() -> record(compact)) .isInstanceOf(GameSessionAccountDelegationRegistryRecord.InvalidRecordException.class); - assertThatThrownBy( - () -> - GameSessionAccountDelegationRegistryRecord.fromAccountSignedBoundCompactJwt( - compact, - "5", - binding(), - snapshot(), - bundleReference(), - "22222222-2222-4222-8222-222222222222", - tuple, - Map.of(ACCOUNT_ID, "3"), - NOW, - MAX_RECORD_BYTES)) + assertThatThrownBy(() -> + GameSessionAccountDelegationRegistryRecord.fromAccountSignedBoundCompactJwt( + compact, + "5", + binding(), + snapshot(), + bundleReference(), + "22222222-2222-4222-8222-222222222222", + tuple, + Map.of(ACCOUNT_ID, "3"), + NOW, + MAX_RECORD_BYTES)) .isInstanceOf(AccountAsymmetricJwtVerifier.VerificationException.class); } @@ -201,16 +200,15 @@ void advancedAccountRequiresTheExactCurrentCutoffAndSequenceZeroOmitsIt() throws .forEach((key, value) -> fabricatedTuple.put((String) key, value)); fabricatedTuple.put("accountSecurityCutoff", cutoff(1L, 1L).toMap()); fabricatedBaseline.put("authorityTuple", fabricatedTuple); - assertThatThrownBy( - () -> - GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( - compact(fabricatedBaseline), - "5", - binding(), - baselineSnapshot(), - bundleReference(), - NOW, - MAX_RECORD_BYTES)) + assertThatThrownBy(() -> + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + compact(fabricatedBaseline), + "5", + binding(), + baselineSnapshot(), + bundleReference(), + NOW, + MAX_RECORD_BYTES)) .isInstanceOf(IllegalArgumentException.class); } @@ -221,25 +219,23 @@ void enforcesShortLifetimeCanonicalJwtAndExactRequestIdentity() throws Exception assertInvalid(tooLong); String compact = compact(claims()); - assertThatThrownBy( - () -> - GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( - compact + "=", - "5", - binding(), - snapshot(), - bundleReference(), - NOW, - MAX_RECORD_BYTES)) + assertThatThrownBy(() -> + GameSessionAccountDelegationRegistryRecord.fromAccountSignedCompactJwt( + compact + "=", + "5", + binding(), + snapshot(), + bundleReference(), + NOW, + MAX_RECORD_BYTES)) .isInstanceOf(IllegalArgumentException.class); GameSessionAccountDelegationRegistryRecord record = record(compact); byte[] bytes = record.toCanonicalJsonBytes(MAX_RECORD_BYTES); String nonCanonical = "{ \"state\": \"pending\" }"; - assertThatThrownBy( - () -> - GameSessionAccountDelegationRegistryRecord.decode( - nonCanonical.getBytes(StandardCharsets.UTF_8), MAX_RECORD_BYTES)) + assertThatThrownBy(() -> + GameSessionAccountDelegationRegistryRecord.decode( + nonCanonical.getBytes(StandardCharsets.UTF_8), MAX_RECORD_BYTES)) .isInstanceOf(IllegalArgumentException.class); assertThat(bytes).isNotEmpty(); } @@ -293,10 +289,8 @@ void requiresDecimalCountersAndCompleteFiveFieldBundleReference() throws Excepti incompleteFields.put("authEvidenceBundle", incompleteReference); byte[] incompleteBytes = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(incompleteFields)); - assertThatThrownBy( - () -> - GameSessionAccountDelegationRegistryRecord.decode( - incompleteBytes, MAX_RECORD_BYTES)) + assertThatThrownBy(() -> + GameSessionAccountDelegationRegistryRecord.decode(incompleteBytes, MAX_RECORD_BYTES)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java index 7c9c0e3a5a..82ccfb7ccc 100644 --- a/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java +++ b/services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java @@ -178,55 +178,53 @@ void rejectsMalformedCounterAliasesAndValuesAboveTheOwnerBigintMaximum() { @Test void rejectsMapKeyMismatchExtraTenantAndWrongNestedCounterType() { var tuple = authorityTuple("1", "1", "1", "1", false); - assertThatThrownBy( - () -> - new GatewayFirstPartyConnectContextEnvelope.GameplayConnectSource( - ACCOUNT_ID, - TENANT_ID, - REALM_ID, - "world", - "realm", - NAMESPACE_ID, - "SHARED", - GAME_INSTANCE_ID, - "1", - "1", - "scope-1", - "request-1", - tuple, - Map.of(UUID.randomUUID().toString(), "1"), - "jti-1", - "1", - null, - null, - NOW_MILLIS / 1_000L + 30L)) + assertThatThrownBy(() -> + new GatewayFirstPartyConnectContextEnvelope.GameplayConnectSource( + ACCOUNT_ID, + TENANT_ID, + REALM_ID, + "world", + "realm", + NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + "1", + "1", + "scope-1", + "request-1", + tuple, + Map.of(UUID.randomUUID().toString(), "1"), + "jti-1", + "1", + null, + null, + NOW_MILLIS / 1_000L + 30L)) .isInstanceOf(IllegalArgumentException.class); Map extraTenant = new LinkedHashMap<>(); extraTenant.put(TENANT_ID.toString(), "1"); extraTenant.put(UUID.randomUUID().toString(), "2"); - assertThatThrownBy( - () -> - new GatewayFirstPartyConnectContextEnvelope.GameplayConnectSource( - ACCOUNT_ID, - TENANT_ID, - REALM_ID, - "world", - "realm", - NAMESPACE_ID, - "SHARED", - GAME_INSTANCE_ID, - "1", - "1", - "scope-1", - "request-1", - tuple, - extraTenant, - "jti-1", - "1", - null, - null, - NOW_MILLIS / 1_000L + 30L)) + assertThatThrownBy(() -> + new GatewayFirstPartyConnectContextEnvelope.GameplayConnectSource( + ACCOUNT_ID, + TENANT_ID, + REALM_ID, + "world", + "realm", + NAMESPACE_ID, + "SHARED", + GAME_INSTANCE_ID, + "1", + "1", + "scope-1", + "request-1", + tuple, + extraTenant, + "jti-1", + "1", + null, + null, + NOW_MILLIS / 1_000L + 30L)) .isInstanceOf(IllegalArgumentException.class); Map unsafeAuthority = new LinkedHashMap<>(authorityTupleMap(tuple)); @@ -277,15 +275,13 @@ void validatesOptionalCutoffPresenceAndPositiveSequenceValues() { String compact = GatewayFirstPartyConnectContextEnvelope.sign(valid, metadata(), signingKey); assertThat(payload(compact).get("authorityTuple")).isEqualTo(authorityTupleMap(tuple)); - assertThatThrownBy( - () -> - new GatewayFirstPartyConnectContextEnvelope.AccountSecurityCutoff( - "2", "account:auth-authority:v1:account/" + ACCOUNT_ID, "0")) + assertThatThrownBy(() -> + new GatewayFirstPartyConnectContextEnvelope.AccountSecurityCutoff( + "2", "account:auth-authority:v1:account/" + ACCOUNT_ID, "0")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GatewayFirstPartyConnectContextEnvelope.AuthorityTuple( - "1", "2", Map.of(tenant, "1"), Map.of(tenant, "1"), List.of(), null, Map.of())) + assertThatThrownBy(() -> + new GatewayFirstPartyConnectContextEnvelope.AuthorityTuple( + "1", "2", Map.of(tenant, "1"), Map.of(tenant, "1"), List.of(), null, Map.of())) .isInstanceOf(IllegalArgumentException.class); } @@ -408,10 +404,8 @@ void enforcesSourceExpiryThirtySecondLifetimeSafeTimeIntegersAndClockSkew() { var metadataPastSource = new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( "203.0.113.8", "request-1", NOW_MILLIS, NOW_MILLIS, NOW_MILLIS + 31_000L); - assertThatThrownBy( - () -> - GatewayFirstPartyConnectContextEnvelope.sign( - source, metadataPastSource, signingKey)) + assertThatThrownBy(() -> + GatewayFirstPartyConnectContextEnvelope.sign(source, metadataPastSource, signingKey)) .isInstanceOf(GatewayFirstPartyConnectContextEnvelope.VerificationException.class) .extracting("reason") .isEqualTo(GatewayFirstPartyConnectContextEnvelope.FailureReason.INVALID_LIFETIME); @@ -437,10 +431,9 @@ void enforcesSourceExpiryThirtySecondLifetimeSafeTimeIntegersAndClockSkew() { source.playtestLifecycleId(), source.playtestStateGeneration(), NOW_MILLIS / 1_000L + 10L); - assertThatThrownBy( - () -> - GatewayFirstPartyConnectContextEnvelope.sign( - sourceExpiringInTenSeconds, metadata(), signingKey)) + assertThatThrownBy(() -> + GatewayFirstPartyConnectContextEnvelope.sign( + sourceExpiringInTenSeconds, metadata(), signingKey)) .isInstanceOf(GatewayFirstPartyConnectContextEnvelope.VerificationException.class) .extracting("reason") .isEqualTo(GatewayFirstPartyConnectContextEnvelope.FailureReason.INVALID_LIFETIME); @@ -469,9 +462,8 @@ sourceExpiringInTenSeconds, metadata(), signingKey)) var metadata31 = new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( "203.0.113.8", "request-1", NOW_MILLIS, NOW_MILLIS, NOW_MILLIS + 31_000L); - assertThatThrownBy( - () -> - GatewayFirstPartyConnectContextEnvelope.sign(tooLongSource, metadata31, signingKey)) + assertThatThrownBy(() -> + GatewayFirstPartyConnectContextEnvelope.sign(tooLongSource, metadata31, signingKey)) .isInstanceOf(GatewayFirstPartyConnectContextEnvelope.VerificationException.class); String valid = GatewayFirstPartyConnectContextEnvelope.sign(source, metadata(), signingKey); @@ -502,43 +494,38 @@ void failsClosedForUnavailableDedicatedKeySourceWithoutLeakingInput() throws Exc "missing-key", "typ", GatewayFirstPartyConnectContextEnvelope.PROTECTED_TYPE)); - assertThatThrownBy( - () -> - GatewayFirstPartyConnectContextEnvelope.verify( - token, - kid -> { - throw new GatewayFirstPartyConnectContextEnvelope - .KeySourceUnavailableException(); - }, - NOW_MILLIS, - 0)) + assertThatThrownBy(() -> + GatewayFirstPartyConnectContextEnvelope.verify( + token, + kid -> { + throw new GatewayFirstPartyConnectContextEnvelope.KeySourceUnavailableException(); + }, + NOW_MILLIS, + 0)) .isInstanceOf(GatewayFirstPartyConnectContextEnvelope.VerificationException.class) - .satisfies( - failure -> { - assertThat(failure.getMessage()).doesNotContain(secretMarker, "missing-key", token); - assertThat( - ((GatewayFirstPartyConnectContextEnvelope.VerificationException) failure) - .reason()) - .isEqualTo( - GatewayFirstPartyConnectContextEnvelope.FailureReason.KEY_SOURCE_UNAVAILABLE); - }); + .satisfies(failure -> { + assertThat(failure.getMessage()).doesNotContain(secretMarker, "missing-key", token); + assertThat( + ((GatewayFirstPartyConnectContextEnvelope.VerificationException) failure) + .reason()) + .isEqualTo( + GatewayFirstPartyConnectContextEnvelope.FailureReason.KEY_SOURCE_UNAVAILABLE); + }); } @Test void rejectsNoncanonicalClientAddressInsteadOfAcceptingHeaderLikeInput() { - assertThatThrownBy( - () -> - new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( - "203.000.113.8", "request-1", NOW_MILLIS, NOW_MILLIS, NOW_MILLIS + 30_000L)) + assertThatThrownBy(() -> + new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( + "203.000.113.8", "request-1", NOW_MILLIS, NOW_MILLIS, NOW_MILLIS + 30_000L)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( - "198.51.100.2, 203.0.113.8", - "request-1", - NOW_MILLIS, - NOW_MILLIS, - NOW_MILLIS + 30_000L)) + assertThatThrownBy(() -> + new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( + "198.51.100.2, 203.0.113.8", + "request-1", + NOW_MILLIS, + NOW_MILLIS, + NOW_MILLIS + 30_000L)) .isInstanceOf(IllegalArgumentException.class); } @@ -554,32 +541,21 @@ void acceptsOnlyJdkCanonicalUncompressedIpv6AddressSpelling() { var verified = GatewayFirstPartyConnectContextEnvelope.verify(signed, keySource, NOW_MILLIS, 0); assertThat(verified.claims().canonicalClientAddress()).isEqualTo("2001:db8:0:0:0:0:0:1"); - assertThatThrownBy( - () -> - new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( - "2001:db8::1", "request-1", NOW_MILLIS, NOW_MILLIS, NOW_MILLIS + 30_000L)) + assertThatThrownBy(() -> + new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( + "2001:db8::1", "request-1", NOW_MILLIS, NOW_MILLIS, NOW_MILLIS + 30_000L)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( - "2001:DB8:0:0:0:0:0:1", - "request-1", - NOW_MILLIS, - NOW_MILLIS, - NOW_MILLIS + 30_000L)) + assertThatThrownBy(() -> + new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( + "2001:DB8:0:0:0:0:0:1", "request-1", NOW_MILLIS, NOW_MILLIS, NOW_MILLIS + 30_000L)) .isInstanceOf(IllegalArgumentException.class); } @Test void rejectsNonAsciiCharactersInIpv6Address() { - assertThatThrownBy( - () -> - new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( - "2001:db8:0:0:0:0:0:1", - "request-1", - NOW_MILLIS, - NOW_MILLIS, - NOW_MILLIS + 30_000L)) + assertThatThrownBy(() -> + new GatewayFirstPartyConnectContextEnvelope.GatewayContextMetadata( + "2001:db8:0:0:0:0:0:1", "request-1", NOW_MILLIS, NOW_MILLIS, NOW_MILLIS + 30_000L)) .isInstanceOf(IllegalArgumentException.class); } @@ -676,14 +652,13 @@ private Map authorityTupleMap( map.put( "privateRealmGrantVersions", tuple.privateRealmGrantVersions().stream() - .map( - grant -> - Map.of( - "tenantId", grant.tenantId(), - "worldSlug", grant.worldSlug(), - "realmSlug", grant.realmSlug(), - "playtestLifecycleId", grant.playtestLifecycleId(), - "grantVersion", grant.grantVersion())) + .map(grant -> + Map.of( + "tenantId", grant.tenantId(), + "worldSlug", grant.worldSlug(), + "realmSlug", grant.realmSlug(), + "playtestLifecycleId", grant.playtestLifecycleId(), + "grantVersion", grant.grantVersion())) .toList()); if (tuple.accountSecurityCutoff() != null) { map.put( @@ -698,15 +673,14 @@ private Map authorityTupleMap( Map cutoffs = new LinkedHashMap<>(); tuple .tenantBillingCutoff() - .forEach( - (tenant, cutoff) -> - cutoffs.put( - tenant, - Map.of( - "tenantAuthorityGeneration", cutoff.tenantAuthorityGeneration(), - "tenantBillingSequence", cutoff.tenantBillingSequence(), - "outboxStreamKey", cutoff.outboxStreamKey(), - "outboxSequence", cutoff.outboxSequence()))); + .forEach((tenant, cutoff) -> + cutoffs.put( + tenant, + Map.of( + "tenantAuthorityGeneration", cutoff.tenantAuthorityGeneration(), + "tenantBillingSequence", cutoff.tenantBillingSequence(), + "outboxStreamKey", cutoff.outboxStreamKey(), + "outboxSequence", cutoff.outboxSequence()))); map.put("tenantBillingCutoff", cutoffs); } return map; @@ -771,12 +745,11 @@ private void assertRejected( assertThatThrownBy( () -> GatewayFirstPartyConnectContextEnvelope.verify(token, keySource, NOW_MILLIS, 0)) .isInstanceOf(GatewayFirstPartyConnectContextEnvelope.VerificationException.class) - .satisfies( - failure -> - assertThat( - ((GatewayFirstPartyConnectContextEnvelope.VerificationException) failure) - .reason()) - .isEqualTo(reason)); + .satisfies(failure -> + assertThat( + ((GatewayFirstPartyConnectContextEnvelope.VerificationException) failure) + .reason()) + .isEqualTo(reason)); } private void assertRejectedAt( @@ -787,11 +760,10 @@ private void assertRejectedAt( assertThatThrownBy( () -> GatewayFirstPartyConnectContextEnvelope.verify(token, keySource, nowMillis, skew)) .isInstanceOf(GatewayFirstPartyConnectContextEnvelope.VerificationException.class) - .satisfies( - failure -> - assertThat( - ((GatewayFirstPartyConnectContextEnvelope.VerificationException) failure) - .reason()) - .isEqualTo(reason)); + .satisfies(failure -> + assertThat( + ((GatewayFirstPartyConnectContextEnvelope.VerificationException) failure) + .reason()) + .isEqualTo(reason)); } } diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java index e7cbb9b5b3..052cef8630 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/AccountRuntimeStubServerCompatibilityTest.java @@ -80,10 +80,9 @@ void privateCapacityMutationRemainsUnimplementedOnSharedFakeRuntimeServer() thro ManagedChannelBuilder.forAddress("localhost", server.port()).usePlaintext().build(); try { var stub = AccountServiceGrpc.newBlockingStub(channel); - assertThatThrownBy( - () -> - stub.commitTenantCapacityAdmission( - CommitTenantCapacityAdmissionRequest.getDefaultInstance())) + assertThatThrownBy(() -> + stub.commitTenantCapacityAdmission( + CommitTenantCapacityAdmissionRequest.getDefaultInstance())) .isInstanceOfSatisfying( StatusRuntimeException.class, failure -> diff --git a/services/common-test-support/src/test/java/net/firedevops/firemud/test/HttpTestSupportTest.java b/services/common-test-support/src/test/java/net/firedevops/firemud/test/HttpTestSupportTest.java index 93eeaf4847..3aaf4cddc4 100644 --- a/services/common-test-support/src/test/java/net/firedevops/firemud/test/HttpTestSupportTest.java +++ b/services/common-test-support/src/test/java/net/firedevops/firemud/test/HttpTestSupportTest.java @@ -147,12 +147,11 @@ private TestHttpServer(HttpHandler handler) throws IOException { server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/actuator/health/readiness", handler); executor = - Executors.newCachedThreadPool( - runnable -> { - Thread thread = new Thread(runnable, "http-test-support-test-server"); - thread.setDaemon(true); - return thread; - }); + Executors.newCachedThreadPool(runnable -> { + Thread thread = new Thread(runnable, "http-test-support-test-server"); + thread.setDaemon(true); + return thread; + }); server.setExecutor(executor); server.start(); } @@ -162,30 +161,28 @@ private static TestHttpServer responding(String body) throws IOException { } private static TestHttpServer responding(int statusCode, String body) throws IOException { - return new TestHttpServer( - exchange -> { - byte[] response = body.getBytes(StandardCharsets.UTF_8); - exchange.sendResponseHeaders(statusCode, response.length); - try (OutputStream output = exchange.getResponseBody()) { - output.write(response); - } - }); + return new TestHttpServer(exchange -> { + byte[] response = body.getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(statusCode, response.length); + try (OutputStream output = exchange.getResponseBody()) { + output.write(response); + } + }); } private static TestHttpServer disconnectingOnceThenResponding( AtomicInteger requestCount, String body) throws IOException { - return new TestHttpServer( - exchange -> { - if (requestCount.getAndIncrement() == 0) { - exchange.close(); - return; - } - byte[] response = body.getBytes(StandardCharsets.UTF_8); - exchange.sendResponseHeaders(503, response.length); - try (OutputStream output = exchange.getResponseBody()) { - output.write(response); - } - }); + return new TestHttpServer(exchange -> { + if (requestCount.getAndIncrement() == 0) { + exchange.close(); + return; + } + byte[] response = body.getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(503, response.length); + try (OutputStream output = exchange.getResponseBody()) { + output.write(response); + } + }); } private static TestHttpServer hanging( @@ -194,19 +191,18 @@ private static TestHttpServer hanging( CountDownLatch requestFinished, AtomicInteger requestCount) throws IOException { - return new TestHttpServer( - exchange -> { - requestCount.incrementAndGet(); - requestStarted.countDown(); - try { - releaseRequest.await(); - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - } finally { - exchange.close(); - requestFinished.countDown(); - } - }); + return new TestHttpServer(exchange -> { + requestCount.incrementAndGet(); + requestStarted.countDown(); + try { + releaseRequest.await(); + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + } finally { + exchange.close(); + requestFinished.countDown(); + } + }); } private String url() { diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/IsolatedWorldPublicationInventoryFixtures.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/IsolatedWorldPublicationInventoryFixtures.java index d529ad025a..5a2da4aae9 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/IsolatedWorldPublicationInventoryFixtures.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/IsolatedWorldPublicationInventoryFixtures.java @@ -164,17 +164,14 @@ public static WorldSelectedPublicationArtifactInventoryEvidence stipulated( 0, 0, commit.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()) - .add(BigInteger.ONE) - .toString())) + .map(unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) .toList(), inboundClosure), List.of( diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java index 346bc15202..97b89680a9 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/PostgresBackedServiceTestSupport.java @@ -67,22 +67,21 @@ public static void awaitPostgresJdbcReady(PostgreSQLContainer postgres) { .alias("PostgreSQL mapped JDBC readiness at " + jdbcUrl) .pollInterval(Duration.ofMillis(100)) .atMost(Duration.ofSeconds(60)) - .until( - () -> { - try (Connection connection = - DriverManager.getConnection(jdbcUrl, connectionProperties); - Statement statement = connection.createStatement(); - ResultSet result = statement.executeQuery("SELECT 1")) { - if (result.next() && result.getInt(1) == 1) { - return true; - } - lastFailure.set(new SQLException("PostgreSQL readiness query did not return 1")); - return false; - } catch (SQLException failure) { - lastFailure.set(failure); - return false; - } - }); + .until(() -> { + try (Connection connection = + DriverManager.getConnection(jdbcUrl, connectionProperties); + Statement statement = connection.createStatement(); + ResultSet result = statement.executeQuery("SELECT 1")) { + if (result.next() && result.getInt(1) == 1) { + return true; + } + lastFailure.set(new SQLException("PostgreSQL readiness query did not return 1")); + return false; + } catch (SQLException failure) { + lastFailure.set(failure); + return false; + } + }); } catch (ConditionTimeoutException timeout) { SQLException failure = lastFailure.get(); if (failure == null) { diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/testsupport/entity/EntitySelectedSourceIntakeTerminalReadFixtures.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/testsupport/entity/EntitySelectedSourceIntakeTerminalReadFixtures.java index c352de61a5..5d3cc63d30 100644 --- a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/testsupport/entity/EntitySelectedSourceIntakeTerminalReadFixtures.java +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/testsupport/entity/EntitySelectedSourceIntakeTerminalReadFixtures.java @@ -130,10 +130,9 @@ private static TemplateConfigSourceSnapshot templateSnapshot(DraftCommitBinding var mutations = TemplateConfigSourceValues.mutations(authored); var declarations = mutations.stream() - .filter( - mutation -> - mutation.operation() - == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .filter(mutation -> + mutation.operation() + == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) .sorted(java.util.Comparator.comparing(declaration -> declaration.owner().name())) .toList(); @@ -380,15 +379,14 @@ private static PublicEvidence publicInventory( 0, 0, selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .map(unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) .toList(), emptyInboundClosure()); return new PublicEvidence( @@ -485,20 +483,19 @@ private static InboundSourceClosureDeclaration emptyInboundClosure() { "NPC_TEMPLATE_ROOTS", "OTHER_ACTOR_TEMPLATE_ROOTS"); return families.stream() - .map( - family -> - new EntityEmptySelectedSourceIntakeReceipt.FamilyCensus( - family, - EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY, - v1CensusFamily(family) - ? EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS - : EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind - .EMPTY_ONLY_OWNER_PROVIDER, - 0, - 0, - 0, - 0, - 0)) + .map(family -> + new EntityEmptySelectedSourceIntakeReceipt.FamilyCensus( + family, + EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY, + v1CensusFamily(family) + ? EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS + : EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind + .EMPTY_ONLY_OWNER_PROVIDER, + 0, + 0, + 0, + 0, + 0)) .toList(); } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java index 245d1c3885..ce1ad0ee3d 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadService.java @@ -45,11 +45,10 @@ public AccountBootstrapRosterReadResponse read(AccountBootstrapRosterReadRequest requireCurrent(request, target); var actors = Objects.requireNonNull( - reads.execute( - ignored -> - characters.readAccountBootstrapRoster( - AccountBootstrapRosterReadContract.uuid(request.getCanonicalAccountUuid()), - target))); + reads.execute(ignored -> + characters.readAccountBootstrapRoster( + AccountBootstrapRosterReadContract.uuid(request.getCanonicalAccountUuid()), + target))); // Source RPCs run outside SQL. This detects source movement over the local projection; // it does not claim a distributed hold or protect a later admission/selection. requireCurrent(request, target); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java index b7fb5a769e..4ff53e379b 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateRepository.java @@ -63,28 +63,27 @@ List readPlayerCreatedRoster( outsideTransaction(); Objects.requireNonNull(account, "account"); Objects.requireNonNull(published, "published"); - return dsl.transactionResult( - configuration -> { - DSLContext tx = DSL.using(configuration); - tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - var actors = - tx.fetch( - "SELECT character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason, name, creation_target_namespace, creation_operation_id, actor_entry_policy, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest FROM characters WHERE tenant_uuid = ? AND account_uuid = ? AND playable_state_namespace_id = ? AND playable_state_scope = 'PLAYABLE_STATE_SCOPE_SHARED' AND actor_entry_policy = 'PLAYER_CREATED' AND actor_identity_status = 'OWNER_RESOLVED' AND actor_identity_quarantine_reason IS NULL ORDER BY character_uuid", - published.tenantId(), - account.accountId(), - published.playableStateNamespaceId()); - if (actors.isEmpty()) { - requireNoPersistedPlayerCreatedRosterActors(tx, account, published); - } - var result = new java.util.ArrayList(actors.size()); - for (Record actor : actors) { - readStoredPlayerCreatedTerminal(tx, account, published, actor, false); - result.add( - new CanonicalGameplayRosterActor( - actor.get("character_uuid", UUID.class), actor.get("name", String.class))); - } - return List.copyOf(result); - }); + return dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + var actors = + tx.fetch( + "SELECT character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason, name, creation_target_namespace, creation_operation_id, actor_entry_policy, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest FROM characters WHERE tenant_uuid = ? AND account_uuid = ? AND playable_state_namespace_id = ? AND playable_state_scope = 'PLAYABLE_STATE_SCOPE_SHARED' AND actor_entry_policy = 'PLAYER_CREATED' AND actor_identity_status = 'OWNER_RESOLVED' AND actor_identity_quarantine_reason IS NULL ORDER BY character_uuid", + published.tenantId(), + account.accountId(), + published.playableStateNamespaceId()); + if (actors.isEmpty()) { + requireNoPersistedPlayerCreatedRosterActors(tx, account, published); + } + var result = new java.util.ArrayList(actors.size()); + for (Record actor : actors) { + readStoredPlayerCreatedTerminal(tx, account, published, actor, false); + result.add( + new CanonicalGameplayRosterActor( + actor.get("character_uuid", UUID.class), actor.get("name", String.class))); + } + return List.copyOf(result); + }); } EntityCharacterCreateTerminal readSelectedPlayerCreatedTerminal( @@ -95,20 +94,19 @@ EntityCharacterCreateTerminal readSelectedPlayerCreatedTerminal( Objects.requireNonNull(account, "account"); Objects.requireNonNull(published, "published"); requireCanonicalCharacterId(characterId); - return dsl.transactionResult( - configuration -> { - DSLContext tx = DSL.using(configuration); - tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - Record actor = - tx.fetchOne( - "SELECT character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason, name, creation_target_namespace, creation_operation_id, actor_entry_policy, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest FROM characters WHERE character_uuid = ? AND tenant_uuid = ? AND account_uuid = ? AND playable_state_namespace_id = ? AND playable_state_scope = 'PLAYABLE_STATE_SCOPE_SHARED' AND actor_entry_policy = 'PLAYER_CREATED' AND actor_identity_status = 'OWNER_RESOLVED' AND actor_identity_quarantine_reason IS NULL", - characterId, - published.tenantId(), - account.accountId(), - published.playableStateNamespaceId()); - if (actor == null) throw selectedPlayerCreatedActorUnavailable(); - return readStoredPlayerCreatedTerminal(tx, account, published, actor, true); - }); + return dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + Record actor = + tx.fetchOne( + "SELECT character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason, name, creation_target_namespace, creation_operation_id, actor_entry_policy, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest FROM characters WHERE character_uuid = ? AND tenant_uuid = ? AND account_uuid = ? AND playable_state_namespace_id = ? AND playable_state_scope = 'PLAYABLE_STATE_SCOPE_SHARED' AND actor_entry_policy = 'PLAYER_CREATED' AND actor_identity_status = 'OWNER_RESOLVED' AND actor_identity_quarantine_reason IS NULL", + characterId, + published.tenantId(), + account.accountId(), + published.playableStateNamespaceId()); + if (actor == null) throw selectedPlayerCreatedActorUnavailable(); + return readStoredPlayerCreatedTerminal(tx, account, published, actor, true); + }); } /** @@ -300,171 +298,168 @@ private static RuntimeException corruptRoster(Throwable cause) { EntityCharacterCreateTerminal settle(EntityCharacterCreateProofs proof, String abortRequestId) { outsideTransaction(); if (abortRequestId != null) EntityCharacterCreateBindings.id(abortRequestId); - return dsl.transactionResult( - configuration -> { - DSLContext tx = DSL.using(configuration); - tx.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); - var action = proof.action(); - UUID tenant = UUID.fromString(action.scope().tenantId()); - UUID namespace = UUID.fromString(action.scope().playableStateNamespaceId()); - UUID account = UUID.fromString(action.target().accountId()); - UUID operation = UUID.fromString(proof.original().getOperationId()); - UUID requestId = UUID.fromString(proof.original().getCreateCharacterRequestId()); - String workloadNamespace = proof.request().getOriginal().getTargetNamespace(); - String scope = action.scope().playableStateScope().name(); - // The selected intake association is actual Entity owner storage, not a numeric ID - // bridge. - var association = - tx.fetchOne( - "SELECT receipt_bytes FROM entity_empty_selected_source_receipt WHERE target_namespace = ? AND intake_request_id = ? FOR KEY SHARE", - workloadNamespace, - proof.entitySource().intakeRequestId()); - if (association == null - || !Arrays.equals( - association.get(0, byte[].class), proof.entitySource().canonicalBytes())) { - throw EntityCharacterCreateBindings.conflict(); - } - tx.execute( - "INSERT INTO entity_playable_state_namespace_scopes (tenant_uuid, playable_state_namespace_id, playable_state_scope) VALUES (?, ?, ?) ON CONFLICT DO NOTHING", + return dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); + var action = proof.action(); + UUID tenant = UUID.fromString(action.scope().tenantId()); + UUID namespace = UUID.fromString(action.scope().playableStateNamespaceId()); + UUID account = UUID.fromString(action.target().accountId()); + UUID operation = UUID.fromString(proof.original().getOperationId()); + UUID requestId = UUID.fromString(proof.original().getCreateCharacterRequestId()); + String workloadNamespace = proof.request().getOriginal().getTargetNamespace(); + String scope = action.scope().playableStateScope().name(); + // The selected intake association is actual Entity owner storage, not a numeric ID + // bridge. + var association = + tx.fetchOne( + "SELECT receipt_bytes FROM entity_empty_selected_source_receipt WHERE target_namespace = ? AND intake_request_id = ? FOR KEY SHARE", + workloadNamespace, + proof.entitySource().intakeRequestId()); + if (association == null + || !Arrays.equals( + association.get(0, byte[].class), proof.entitySource().canonicalBytes())) { + throw EntityCharacterCreateBindings.conflict(); + } + tx.execute( + "INSERT INTO entity_playable_state_namespace_scopes (tenant_uuid, playable_state_namespace_id, playable_state_scope) VALUES (?, ?, ?) ON CONFLICT DO NOTHING", + tenant, + namespace, + scope); + var enrolled = + tx.fetchOne( + "SELECT playable_state_scope FROM entity_playable_state_namespace_scopes WHERE tenant_uuid = ? AND playable_state_namespace_id = ? FOR UPDATE", tenant, - namespace, - scope); - var enrolled = - tx.fetchOne( - "SELECT playable_state_scope FROM entity_playable_state_namespace_scopes WHERE tenant_uuid = ? AND playable_state_namespace_id = ? FOR UPDATE", - tenant, - namespace); - if (enrolled == null || !scope.equals(enrolled.get(0, String.class))) - throw EntityCharacterCreateBindings.conflict(); - tx.execute( - "INSERT INTO entity_character_create_operations (target_namespace, operation_id, create_character_request_id, mutation_digest, tenant_uuid, playable_state_namespace_id, playable_state_scope, account_uuid, canonical_version_id, original_request, original_account, original_account_protection, original_game_session_protection, original_world_protection, entity_source_receipt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING", + namespace); + if (enrolled == null || !scope.equals(enrolled.get(0, String.class))) + throw EntityCharacterCreateBindings.conflict(); + tx.execute( + "INSERT INTO entity_character_create_operations (target_namespace, operation_id, create_character_request_id, mutation_digest, tenant_uuid, playable_state_namespace_id, playable_state_scope, account_uuid, canonical_version_id, original_request, original_account, original_account_protection, original_game_session_protection, original_world_protection, entity_source_receipt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING", + workloadNamespace, + operation, + requestId, + proof.original().getMutationDigest(), + tenant, + namespace, + scope, + account, + UUID.fromString(action.target().versionId()), + proof.request().toByteArray(), + proof.original().toByteArray(), + proof.account().toByteArray(), + proof.gameSession().originalOwnerReadback().toByteArray(), + proof.world().toByteArray(), + proof.entitySource().canonicalBytes()); + var candidates = + tx.fetch( + "SELECT * FROM entity_character_create_operations WHERE (target_namespace = ? AND operation_id = ?) OR (tenant_uuid = ? AND playable_state_namespace_id = ? AND account_uuid = ? AND create_character_request_id = ?) FOR UPDATE", workloadNamespace, operation, - requestId, - proof.original().getMutationDigest(), tenant, namespace, - scope, account, - UUID.fromString(action.target().versionId()), - proof.request().toByteArray(), - proof.original().toByteArray(), - proof.account().toByteArray(), - proof.gameSession().originalOwnerReadback().toByteArray(), - proof.world().toByteArray(), - proof.entitySource().canonicalBytes()); - var candidates = - tx.fetch( - "SELECT * FROM entity_character_create_operations WHERE (target_namespace = ? AND operation_id = ?) OR (tenant_uuid = ? AND playable_state_namespace_id = ? AND account_uuid = ? AND create_character_request_id = ?) FOR UPDATE", - workloadNamespace, - operation, - tenant, - namespace, - account, - requestId); - if (candidates.size() != 1) throw EntityCharacterCreateBindings.conflict(); - Record row = candidates.getFirst(); - requireSameProof(row, proof); - if (!"PENDING".equals(row.get("status", String.class))) return terminal(row); + requestId); + if (candidates.size() != 1) throw EntityCharacterCreateBindings.conflict(); + Record row = candidates.getFirst(); + requireSameProof(row, proof); + if (!"PENDING".equals(row.get("status", String.class))) return terminal(row); - // Match the existing canonical assignment writer's real tenant row lock before - // zero-roster - // observation, then lock the exact account/namespace roster scope. No identity is - // derived. - tx.execute( - "INSERT INTO entity_tenant_identities (canonical_tenant_uuid) VALUES (?) ON CONFLICT DO NOTHING", + // Match the existing canonical assignment writer's real tenant row lock before + // zero-roster + // observation, then lock the exact account/namespace roster scope. No identity is + // derived. + tx.execute( + "INSERT INTO entity_tenant_identities (canonical_tenant_uuid) VALUES (?) ON CONFLICT DO NOTHING", + tenant); + var tenantRow = + tx.fetchOne( + "SELECT entity_tenant_row_id FROM entity_tenant_identities WHERE canonical_tenant_uuid = ? FOR UPDATE", tenant); - var tenantRow = - tx.fetchOne( - "SELECT entity_tenant_row_id FROM entity_tenant_identities WHERE canonical_tenant_uuid = ? FOR UPDATE", - tenant); - if (tenantRow == null) - throw new IllegalStateException("Entity tenant identity unavailable"); + if (tenantRow == null) throw new IllegalStateException("Entity tenant identity unavailable"); + tx.execute( + "INSERT INTO entity_character_create_roster_guards (tenant_uuid, playable_state_namespace_id, account_uuid) VALUES (?, ?, ?) ON CONFLICT DO NOTHING", + tenant, + namespace, + account); + tx.fetchOne( + "SELECT account_uuid FROM entity_character_create_roster_guards WHERE tenant_uuid = ? AND playable_state_namespace_id = ? AND account_uuid = ? FOR UPDATE", + tenant, + namespace, + account); + UUID character = null; + if (abortRequestId == null) { + // Recheck expiry after every potentially blocking lock and immediately before + // allocation. + requireCurrentAuthority(action.expectedVersion().connectScopeExpiresAt()); + if (!tx.fetch( + "SELECT character_uuid FROM characters WHERE tenant_uuid = ? AND playable_state_namespace_id = ? AND account_uuid = ? FOR UPDATE", + tenant, + namespace, + account) + .isEmpty()) { + throw Status.FAILED_PRECONDITION + .withDescription("PLAYER_CREATED roster is not empty") + .asRuntimeException(); + } + requireCurrentAuthority(action.expectedVersion().connectScopeExpiresAt()); + character = UUID.randomUUID(); + String core = action.mutation().authoredSource().core().canonicalJson(); + int inserted = + tx.execute( + "INSERT INTO characters (character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason, tenant_id, account_id, playable_state_key, name, level, experience, strength, agility, intelligence, stamina, health, mana, body_layout_key, creation_target_namespace, creation_operation_id, actor_entry_policy, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest) VALUES (?, ?, ?, ?, ?, 'OWNER_RESOLVED', NULL, ?, NULL, NULL, ?, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, ?, ?, 'PLAYER_CREATED', ?, ?, ?) ON CONFLICT DO NOTHING", + character, + account, + tenant, + namespace, + scope, + tenantRow.get(0, Long.class), + new AuthoredCore(core).displayName(), + workloadNamespace, + operation, + core, + action.mutation().authoredSource().descriptor().canonicalJson(), + action.mutation().authoredSource().descriptor().digest()); + if (inserted != 1) + throw Status.FAILED_PRECONDITION + .withDescription("Canonical roster changed before creation") + .asRuntimeException(); + } + var builder = + EntityCharacterCreateTerminal.newBuilder() + .setOriginalRequest(proof.request()) + .setAccountOriginal(proof.original()) + .setOriginalAccountProtection(proof.account().toByteString()) + .setOriginalGameSessionProtection(proof.gameSession().originalOwnerReadback()) + .setOriginalWorldProtection(proof.world().toByteString()) + .setEntityIntakeRequestId(proof.entitySource().intakeRequestId().toString()) + .setEntitySourceReceiptDigest(proof.entitySource().receiptDigest()) + .setOutcome( + character == null + ? EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_ABORTED + : EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED) + .setTerminalId(UUID.randomUUID().toString()) + .setTerminalFence(1L) + .setCompletedAt(clock.instant().toString()); + if (character != null) builder.setCharacterId(character.toString()); + if (abortRequestId != null) builder.setAbortRequestId(abortRequestId); + var terminal = builder.build(); + EntityCharacterCreateBindings.requireBound( + terminal, EntityCharacterCreateBindings.MAX_TERMINAL_BYTES); + int updated = tx.execute( - "INSERT INTO entity_character_create_roster_guards (tenant_uuid, playable_state_namespace_id, account_uuid) VALUES (?, ?, ?) ON CONFLICT DO NOTHING", - tenant, - namespace, - account); - tx.fetchOne( - "SELECT account_uuid FROM entity_character_create_roster_guards WHERE tenant_uuid = ? AND playable_state_namespace_id = ? AND account_uuid = ? FOR UPDATE", - tenant, - namespace, - account); - UUID character = null; - if (abortRequestId == null) { - // Recheck expiry after every potentially blocking lock and immediately before - // allocation. - requireCurrentAuthority(action.expectedVersion().connectScopeExpiresAt()); - if (!tx.fetch( - "SELECT character_uuid FROM characters WHERE tenant_uuid = ? AND playable_state_namespace_id = ? AND account_uuid = ? FOR UPDATE", - tenant, - namespace, - account) - .isEmpty()) { - throw Status.FAILED_PRECONDITION - .withDescription("PLAYER_CREATED roster is not empty") - .asRuntimeException(); - } - requireCurrentAuthority(action.expectedVersion().connectScopeExpiresAt()); - character = UUID.randomUUID(); - String core = action.mutation().authoredSource().core().canonicalJson(); - int inserted = - tx.execute( - "INSERT INTO characters (character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason, tenant_id, account_id, playable_state_key, name, level, experience, strength, agility, intelligence, stamina, health, mana, body_layout_key, creation_target_namespace, creation_operation_id, actor_entry_policy, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest) VALUES (?, ?, ?, ?, ?, 'OWNER_RESOLVED', NULL, ?, NULL, NULL, ?, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, ?, ?, 'PLAYER_CREATED', ?, ?, ?) ON CONFLICT DO NOTHING", - character, - account, - tenant, - namespace, - scope, - tenantRow.get(0, Long.class), - new AuthoredCore(core).displayName(), - workloadNamespace, - operation, - core, - action.mutation().authoredSource().descriptor().canonicalJson(), - action.mutation().authoredSource().descriptor().digest()); - if (inserted != 1) - throw Status.FAILED_PRECONDITION - .withDescription("Canonical roster changed before creation") - .asRuntimeException(); - } - var builder = - EntityCharacterCreateTerminal.newBuilder() - .setOriginalRequest(proof.request()) - .setAccountOriginal(proof.original()) - .setOriginalAccountProtection(proof.account().toByteString()) - .setOriginalGameSessionProtection(proof.gameSession().originalOwnerReadback()) - .setOriginalWorldProtection(proof.world().toByteString()) - .setEntityIntakeRequestId(proof.entitySource().intakeRequestId().toString()) - .setEntitySourceReceiptDigest(proof.entitySource().receiptDigest()) - .setOutcome( - character == null - ? EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_ABORTED - : EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_COMMITTED) - .setTerminalId(UUID.randomUUID().toString()) - .setTerminalFence(1L) - .setCompletedAt(clock.instant().toString()); - if (character != null) builder.setCharacterId(character.toString()); - if (abortRequestId != null) builder.setAbortRequestId(abortRequestId); - var terminal = builder.build(); - EntityCharacterCreateBindings.requireBound( - terminal, EntityCharacterCreateBindings.MAX_TERMINAL_BYTES); - int updated = - tx.execute( - "UPDATE entity_character_create_operations SET status = ?, terminal_bytes = ?, character_uuid = ? WHERE target_namespace = ? AND operation_id = ? AND status = 'PENDING'", - character == null ? "ABORTED" : "COMMITTED", - terminal.toByteArray(), - character, - workloadNamespace, - operation); - if (updated != 1) - throw new IllegalStateException("Creation terminal serialization failed"); - if (character != null) { - new EntityPlayerCreatedRuntimeProjectionRepository() - .allocateFreshCreation(tx, terminal, action); - } - return terminal; - }); + "UPDATE entity_character_create_operations SET status = ?, terminal_bytes = ?, character_uuid = ? WHERE target_namespace = ? AND operation_id = ? AND status = 'PENDING'", + character == null ? "ABORTED" : "COMMITTED", + terminal.toByteArray(), + character, + workloadNamespace, + operation); + if (updated != 1) throw new IllegalStateException("Creation terminal serialization failed"); + if (character != null) { + new EntityPlayerCreatedRuntimeProjectionRepository() + .allocateFreshCreation(tx, terminal, action); + } + return terminal; + }); } private void requireCurrentAuthority(Instant connectScopeExpiresAt) { diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateService.java index 0b7490d110..9ddce73a0b 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateService.java @@ -61,10 +61,8 @@ public EntityCharacterCreateTerminal abort(AbortProtectedCharacterCreateRequest requireMutation(request.getCreation()); var existing = repository.replay(request.getCreation()); var terminal = - existing.orElseGet( - () -> - repository.settle( - readAllOwners(request.getCreation()), request.getAbortRequestId())); + existing.orElseGet(() -> + repository.settle(readAllOwners(request.getCreation()), request.getAbortRequestId())); if (terminal.getOutcome() == EntityCharacterCreateOutcome.ENTITY_CHARACTER_CREATE_OUTCOME_ABORTED && !request.getAbortRequestId().equals(terminal.getAbortRequestId())) @@ -83,11 +81,10 @@ public EntityCharacterCreateTerminal read(ReadEntityCharacterCreateTerminalReque throw Status.PERMISSION_DENIED.asRuntimeException(); return repository .read(request.getOriginal()) - .orElseThrow( - () -> - Status.NOT_FOUND - .withDescription("No definitive Entity creation terminal; absence is not abort") - .asRuntimeException()); + .orElseThrow(() -> + Status.NOT_FOUND + .withDescription("No definitive Entity creation terminal; absence is not abort") + .asRuntimeException()); } private void requireMutation(CommitProtectedCharacterCreateRequest request) { diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateSource.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateSource.java index 059aa42815..144a21a231 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateSource.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateSource.java @@ -39,11 +39,10 @@ public EntityEmptySelectedSourceIntakeReceipt read(CharacterCreateOperatorAction var receipt = intakes .read(action.scope().targetNamespace(), association.get(0, UUID.class)) - .orElseThrow( - () -> - Status.UNAVAILABLE - .withDescription("Entity selected source receipt is unavailable") - .asRuntimeException()); + .orElseThrow(() -> + Status.UNAVAILABLE + .withDescription("Entity selected source receipt is unavailable") + .asRuntimeException()); var owner = receipt.inputs().worldInventoryReadEvidence().inventory().publicEvidence().ownerScope(); if (!action.scope().targetNamespace().equals(receipt.targetNamespace()) diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java index d4e15824cf..7bc2ddea1d 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterService.java @@ -67,11 +67,10 @@ public CanonicalPlayerCreatedRosterResponse list(CanonicalPlayerCreatedRosterReq CanonicalGameplayRosterReferenceEvidence.requireDereference(checkedOriginal); var retained = requireTransactionResult( - transactions.execute( - status -> { - retentionRepository.requireAdmission(request, admission); - return retentionRepository.originalPlayerCreatedReceipt(checkedOriginal); - }), + transactions.execute(status -> { + retentionRepository.requireAdmission(request, admission); + return retentionRepository.originalPlayerCreatedReceipt(checkedOriginal); + }), "PLAYER_CREATED receipt lookup returned no result"); if (retained.isPresent()) { return CanonicalPlayerCreatedRosterEvidence.requireResponse(request, retained.orElseThrow()); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java index ebb249fa11..3dee01284c 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotRepository.java @@ -86,76 +86,72 @@ public CanonicalPlayerCreatedRosterResponse capture( new EntityPlayerCreatedRosterReadService.AuthenticatedAccountSelector( UUID.fromString(request.getCanonicalAccountUuid())); return Objects.requireNonNull( - transaction.execute( - ignored -> { - DSLContext tx = dsl; - var retention = new CanonicalGameplayRosterRetentionRepository(tx); + transaction.execute(ignored -> { + DSLContext tx = dsl; + var retention = new CanonicalGameplayRosterRetentionRepository(tx); - // Keep the retention family's established admission-before-snapshot lock order. - retention.requireAdmission(request, localAdmission); - Optional retained = - retention.originalPlayerCreatedReceipt(checkedOriginal); - if (retained.isPresent()) { - Record boundAdmission = - tx.fetchOne( - "SELECT snapshot_uuid FROM entity_canonical_roster_admissions WHERE operation_uuid = ? AND admission_uuid = ? AND admission_state = 'OPEN' FOR UPDATE", - UUID.fromString(request.getRequestUuid()), - localAdmission); - if (boundAdmission == null - || !UUID.fromString(retained.orElseThrow().getRoster().getSnapshotUuid()) - .equals(boundAdmission.get("snapshot_uuid", UUID.class))) { - throw new IllegalStateException("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); - } - if (!checkedOriginal.getCanonicalPlayerCreatedRosterReceipt().isEmpty() - && !checkedOriginal - .getCanonicalPlayerCreatedRosterReceipt() - .equals(retained.get().toByteString())) { - throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_RECEIPT_CONFLICT"); - } - return CanonicalPlayerCreatedRosterEvidence.requireResponse( - request, retained.orElseThrow()); - } - if (!checkedOriginal.getCanonicalPlayerCreatedRosterReceipt().isEmpty()) { - throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_RECEIPT_UNRETAINED"); - } + // Keep the retention family's established admission-before-snapshot lock order. + retention.requireAdmission(request, localAdmission); + Optional retained = + retention.originalPlayerCreatedReceipt(checkedOriginal); + if (retained.isPresent()) { + Record boundAdmission = + tx.fetchOne( + "SELECT snapshot_uuid FROM entity_canonical_roster_admissions WHERE operation_uuid = ? AND admission_uuid = ? AND admission_state = 'OPEN' FOR UPDATE", + UUID.fromString(request.getRequestUuid()), + localAdmission); + if (boundAdmission == null + || !UUID.fromString(retained.orElseThrow().getRoster().getSnapshotUuid()) + .equals(boundAdmission.get("snapshot_uuid", UUID.class))) { + throw new IllegalStateException("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); + } + if (!checkedOriginal.getCanonicalPlayerCreatedRosterReceipt().isEmpty() + && !checkedOriginal + .getCanonicalPlayerCreatedRosterReceipt() + .equals(retained.get().toByteString())) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_RECEIPT_CONFLICT"); + } + return CanonicalPlayerCreatedRosterEvidence.requireResponse( + request, retained.orElseThrow()); + } + if (!checkedOriginal.getCanonicalPlayerCreatedRosterReceipt().isEmpty()) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_RECEIPT_UNRETAINED"); + } - CanonicalGameplayRosterTarget currentTarget = - CanonicalGameplayRosterTarget.fromWire(target); - lockCreationRoster(tx, currentTarget, account.accountId()); + CanonicalGameplayRosterTarget currentTarget = + CanonicalGameplayRosterTarget.fromWire(target); + lockCreationRoster(tx, currentTarget, account.accountId()); - List actors = - EntityCharacterCreateRepository - .readFreshPlayerCreatedRosterWithinOwnerTransaction(tx, account, published); - List - wireActors = - actors.stream() - .map(EntityPlayerCreatedRosterSnapshotRepository::wireActor) - .toList(); - String snapshotDigest = - CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( - request.getCanonicalAccountUuid(), target, sourceIdentity, wireActors); + List actors = + EntityCharacterCreateRepository.readFreshPlayerCreatedRosterWithinOwnerTransaction( + tx, account, published); + List wireActors = + actors.stream().map(EntityPlayerCreatedRosterSnapshotRepository::wireActor).toList(); + String snapshotDigest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + request.getCanonicalAccountUuid(), target, sourceIdentity, wireActors); - CanonicalPlayerCreatedRosterResponse receipt = - persistOrReuseSnapshot( - tx, - request, - currentTarget, - sourceIdentity, - sourceIdentity.toByteArray(), - wireActors, - snapshotDigest); + CanonicalPlayerCreatedRosterResponse receipt = + persistOrReuseSnapshot( + tx, + request, + currentTarget, + sourceIdentity, + sourceIdentity.toByteArray(), + wireActors, + snapshotDigest); - UUID snapshotUuid = UUID.fromString(receipt.getRoster().getSnapshotUuid()); - retention.bindAdmission( - UUID.fromString(request.getRequestUuid()), localAdmission, snapshotUuid); - retention.bindPlayerCreatedOriginal(checkedOriginal, receipt); - CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( - checkedOriginal.getRequest(), - checkedOriginal.getOwnerFence(), - UUID.fromString(checkedOriginal.getTargetFenceUuid()), - receipt); - return CanonicalPlayerCreatedRosterEvidence.requireResponse(request, receipt); - }), + UUID snapshotUuid = UUID.fromString(receipt.getRoster().getSnapshotUuid()); + retention.bindAdmission( + UUID.fromString(request.getRequestUuid()), localAdmission, snapshotUuid); + retention.bindPlayerCreatedOriginal(checkedOriginal, receipt); + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + checkedOriginal.getRequest(), + checkedOriginal.getOwnerFence(), + UUID.fromString(checkedOriginal.getTargetFenceUuid()), + receipt); + return CanonicalPlayerCreatedRosterEvidence.requireResponse(request, receipt); + }), "PLAYER_CREATED capture transaction returned no receipt"); } @@ -226,108 +222,95 @@ public CanonicalSelectedPlayerCreatedCharacterResponse readSelected( new EntityPlayerCreatedRosterReadService.AuthenticatedAccountSelector( UUID.fromString(request.getCanonicalAccountUuid())); return Objects.requireNonNull( - transaction.execute( - ignored -> { - DSLContext tx = dsl; - var retention = new CanonicalGameplayRosterRetentionRepository(tx); - UUID operation = UUID.fromString(request.getRequestUuid()); - Record admission = - tx.fetchOne( - "SELECT admission_uuid, snapshot_uuid FROM entity_canonical_roster_admissions WHERE operation_uuid = ? FOR UPDATE", - operation); - if (admission == null) { - throw new IllegalStateException("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); - } - UUID nonce = admission.get("admission_uuid", UUID.class); - retention.requireAdmission(createdRequest, nonce); - if (!UUID.fromString(request.getExpectedSnapshot().getSnapshotUuid()) - .equals(admission.get("snapshot_uuid", UUID.class))) { - throw new IllegalStateException("CANONICAL_ROSTER_SNAPSHOT_STALE"); - } - CanonicalPlayerCreatedRosterResponse retained = - retention - .originalPlayerCreatedReceipt(checkedOriginal) - .orElseThrow( - () -> - new IllegalStateException( - "CANONICAL_ROSTER_ORIGINAL_RECEIPT_UNRETAINED")); - if (!retained.equals(originalRoster)) { - throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_RECEIPT_CONFLICT"); - } + transaction.execute(ignored -> { + DSLContext tx = dsl; + var retention = new CanonicalGameplayRosterRetentionRepository(tx); + UUID operation = UUID.fromString(request.getRequestUuid()); + Record admission = + tx.fetchOne( + "SELECT admission_uuid, snapshot_uuid FROM entity_canonical_roster_admissions WHERE operation_uuid = ? FOR UPDATE", + operation); + if (admission == null) { + throw new IllegalStateException("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); + } + UUID nonce = admission.get("admission_uuid", UUID.class); + retention.requireAdmission(createdRequest, nonce); + if (!UUID.fromString(request.getExpectedSnapshot().getSnapshotUuid()) + .equals(admission.get("snapshot_uuid", UUID.class))) { + throw new IllegalStateException("CANONICAL_ROSTER_SNAPSHOT_STALE"); + } + CanonicalPlayerCreatedRosterResponse retained = + retention + .originalPlayerCreatedReceipt(checkedOriginal) + .orElseThrow(() -> + new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_RECEIPT_UNRETAINED")); + if (!retained.equals(originalRoster)) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_RECEIPT_CONFLICT"); + } - CanonicalGameplayRosterTarget currentTarget = - CanonicalGameplayRosterTarget.fromWire(target); - lockCreationRoster(tx, currentTarget, account.accountId()); - List actors = - EntityCharacterCreateRepository.readPlayerCreatedRosterWithinOwnerTransaction( - tx, account, published); - List - wireActors = - actors.stream() - .map(EntityPlayerCreatedRosterSnapshotRepository::wireActor) - .toList(); - String digest = - CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( - request.getCanonicalAccountUuid(), target, sourceIdentity, wireActors); - if (!digest.equals(request.getExpectedSnapshot().getSnapshotDigest())) { - throw new IllegalStateException("CANONICAL_ROSTER_SNAPSHOT_STALE"); - } - CanonicalPlayerCreatedRosterResponse readback = - readBackSnapshot( - tx, - createdRequest, - UUID.fromString(request.getExpectedSnapshot().getSnapshotUuid()), - currentTarget, - sourceIdentity, - sourceIdentity.toByteArray(), - wireActors, - digest); - long selectedCount = - actors.stream() - .filter( - actor -> - actor - .characterUuid() - .toString() - .equals(request.getSelectedCharacterUuid())) - .count(); - if (selectedCount != 1L) { - throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_SELECTION_CHANGED"); - } + CanonicalGameplayRosterTarget currentTarget = + CanonicalGameplayRosterTarget.fromWire(target); + lockCreationRoster(tx, currentTarget, account.accountId()); + List actors = + EntityCharacterCreateRepository.readPlayerCreatedRosterWithinOwnerTransaction( + tx, account, published); + List wireActors = + actors.stream().map(EntityPlayerCreatedRosterSnapshotRepository::wireActor).toList(); + String digest = + CanonicalPlayerCreatedRosterEvidence.computeSnapshotDigest( + request.getCanonicalAccountUuid(), target, sourceIdentity, wireActors); + if (!digest.equals(request.getExpectedSnapshot().getSnapshotDigest())) { + throw new IllegalStateException("CANONICAL_ROSTER_SNAPSHOT_STALE"); + } + CanonicalPlayerCreatedRosterResponse readback = + readBackSnapshot( + tx, + createdRequest, + UUID.fromString(request.getExpectedSnapshot().getSnapshotUuid()), + currentTarget, + sourceIdentity, + sourceIdentity.toByteArray(), + wireActors, + digest); + long selectedCount = + actors.stream() + .filter(actor -> + actor.characterUuid().toString().equals(request.getSelectedCharacterUuid())) + .count(); + if (selectedCount != 1L) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_SELECTION_CHANGED"); + } - var terminal = - EntityCharacterCreateRepository - .readSelectedPlayerCreatedTerminalWithinOwnerTransaction( - tx, - account, - published, - UUID.fromString(request.getSelectedCharacterUuid())); - var originalCreateRequest = terminal.getOriginalRequest().getOriginal(); - var result = - CanonicalSelectedPlayerCreatedCharacterResponse.newBuilder() - .setRequestUuid(request.getRequestUuid()) - .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) - .setSelectedCharacterUuid(request.getSelectedCharacterUuid()) - .setTarget(target) - .setSnapshot( - CanonicalGameplayRosterSnapshotReference.newBuilder() - .setSnapshotUuid(readback.getRoster().getSnapshotUuid()) - .setSnapshotDigest(readback.getRoster().getSnapshotDigest())) - .setSourceIdentity(sourceIdentity) - .setCreationOperationUuid(originalCreateRequest.getOperationId()) - .setMutationDigest(originalCreateRequest.getMutationDigest()) - .setTerminal(terminal) - .build(); - var checkedResult = - CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse(request, result); - if (!checkedOriginal.getCanonicalSelectedPlayerCreatedCharacterReceipt().isEmpty() - && !CanonicalGameplayRosterReferenceEvidence - .selectedPlayerCreatedCharacterReceipt(checkedOriginal) - .equals(checkedResult)) { - throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_RECEIPT_CONFLICT"); - } - return checkedResult; - }), + var terminal = + EntityCharacterCreateRepository + .readSelectedPlayerCreatedTerminalWithinOwnerTransaction( + tx, account, published, UUID.fromString(request.getSelectedCharacterUuid())); + var originalCreateRequest = terminal.getOriginalRequest().getOriginal(); + var result = + CanonicalSelectedPlayerCreatedCharacterResponse.newBuilder() + .setRequestUuid(request.getRequestUuid()) + .setCanonicalAccountUuid(request.getCanonicalAccountUuid()) + .setSelectedCharacterUuid(request.getSelectedCharacterUuid()) + .setTarget(target) + .setSnapshot( + CanonicalGameplayRosterSnapshotReference.newBuilder() + .setSnapshotUuid(readback.getRoster().getSnapshotUuid()) + .setSnapshotDigest(readback.getRoster().getSnapshotDigest())) + .setSourceIdentity(sourceIdentity) + .setCreationOperationUuid(originalCreateRequest.getOperationId()) + .setMutationDigest(originalCreateRequest.getMutationDigest()) + .setTerminal(terminal) + .build(); + var checkedResult = + CanonicalPlayerCreatedRosterEvidence.requireSelectedResponse(request, result); + if (!checkedOriginal.getCanonicalSelectedPlayerCreatedCharacterReceipt().isEmpty() + && !CanonicalGameplayRosterReferenceEvidence.selectedPlayerCreatedCharacterReceipt( + checkedOriginal) + .equals(checkedResult)) { + throw new IllegalStateException("CANONICAL_ROSTER_ORIGINAL_RECEIPT_CONFLICT"); + } + return checkedResult; + }), "PLAYER_CREATED selected read returned no terminal"); } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClient.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClient.java index 152b059cb4..4f8f3583d6 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClient.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClient.java @@ -193,11 +193,10 @@ private AuthenticatedSource validateOwnerResponse( var json = tools.jackson.databind.json.JsonMapper.builder().build(); var selected = authored.projections().stream() - .filter( - projection -> - RealmEntryPolicy.parseCanonical(projection.policy().canonicalJson(), json) - .realmSlug() - .equals(request.getRealmSlug())) + .filter(projection -> + RealmEntryPolicy.parseCanonical(projection.policy().canonicalJson(), json) + .realmSlug() + .equals(request.getRealmSlug())) .toList(); if (selected.size() != 1) throw invalid(); var policy = @@ -251,18 +250,17 @@ private AuthenticatedSource validateOwnerResponse( || !expectedRelease.commandDefinitions().equals(release.commandDefinitions()) || !expectedRelease.generationConfigRevision().equals(release.generationConfigRevision()) || !expectedRelease.participantDigests().stream() - .map( - value -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - value.participantKey(), - value.scopeValue(), - value.baseVersionId() != null, - value.baseVersionId(), - value.appliedCommitId(), - value.contentDigest(), - value.digestSchemaVersion(), - value.abilitySchemaDigest() != null, - value.abilitySchemaDigest())) + .map(value -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + value.participantKey(), + value.scopeValue(), + value.baseVersionId() != null, + value.baseVersionId(), + value.appliedCommitId(), + value.contentDigest(), + value.digestSchemaVersion(), + value.abilitySchemaDigest() != null, + value.abilitySchemaDigest())) .toList() .equals(release.participantDigests()) || !expectedRelease.contentDigest().equals(set.publishedReleaseBundleDigest()) @@ -273,10 +271,9 @@ private AuthenticatedSource validateOwnerResponse( operation.world().canonicalBytes())) throw invalid(); var policies = set.policies().stream() - .filter( - candidate -> - candidate.policy().worldSlug().equals(request.getWorldSlug()) - && candidate.policy().realmSlug().equals(request.getRealmSlug())) + .filter(candidate -> + candidate.policy().worldSlug().equals(request.getWorldSlug()) + && candidate.policy().realmSlug().equals(request.getRealmSlug())) .toList(); if (policies.size() != 1) throw invalid(); var sealed = policies.getFirst().requireValidDigest(set); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRuntimeReferenceService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRuntimeReferenceService.java index 7cd3841c0d..a5f1d17eb6 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRuntimeReferenceService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRuntimeReferenceService.java @@ -87,12 +87,11 @@ private PlayerCreatedActorRuntimeReferenceResponse read( requireSelector(request, terminal, action); EntityPlayerCreatedRuntimeReference retained = - dsl.transactionResult( - configuration -> { - DSLContext tx = DSL.using(configuration); - tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - return projectionRepository.read(tx, terminal, action); - }); + dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + return projectionRepository.read(tx, terminal, action); + }); return CanonicalPlayerCreatedRuntimeReferenceEvidence.requireResponse( request, response(request, retained)); } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/CharacterController.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/CharacterController.java index d1e8acb43e..4ba708742c 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/CharacterController.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/CharacterController.java @@ -29,19 +29,14 @@ public ResponseEntity>> list( @RequestParam String gameInstanceId, @RequestParam PlayableStateScope playableStateScope, Pageable pageable) { - return EntityManagementRequestReaders.withBadRequest( - () -> { - EntityManagementRequestReaders.AccountScope scope = - EntityManagementRequestReaders.requireAccountScope(tenantId, accountId); - SessionContext.requireTenantAccess(scope.tenantId()); - Page list = - characterService.listForGameplayScope( - scope.tenantId(), - scope.accountId(), - gameInstanceId, - playableStateScope, - pageable); - return ResponseEntity.ok(ApiResponse.success(list)); - }); + return EntityManagementRequestReaders.withBadRequest(() -> { + EntityManagementRequestReaders.AccountScope scope = + EntityManagementRequestReaders.requireAccountScope(tenantId, accountId); + SessionContext.requireTenantAccess(scope.tenantId()); + Page list = + characterService.listForGameplayScope( + scope.tenantId(), scope.accountId(), gameInstanceId, playableStateScope, pageable); + return ResponseEntity.ok(ApiResponse.success(list)); + }); } } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java index c3d42526fb..f1c050b77b 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/EquipmentController.java @@ -31,20 +31,15 @@ public ResponseEntity>> list( @RequestParam String gameInstanceId, @RequestParam PlayableStateScope playableStateScope, Pageable pageable) { - return EntityManagementRequestReaders.withBadRequest( - () -> { - EntityManagementRequestReaders.CharacterScope scope = - EntityManagementRequestReaders.requireCharacterScope(tenantId, characterId); - SessionContext.requireTenantAccess(scope.tenantId()); - Page list = - equipmentService.listEquipment( - scope.tenantId(), - scope.characterId(), - gameInstanceId, - playableStateScope, - pageable); - return ResponseEntity.ok(ApiResponse.success(list)); - }); + return EntityManagementRequestReaders.withBadRequest(() -> { + EntityManagementRequestReaders.CharacterScope scope = + EntityManagementRequestReaders.requireCharacterScope(tenantId, characterId); + SessionContext.requireTenantAccess(scope.tenantId()); + Page list = + equipmentService.listEquipment( + scope.tenantId(), scope.characterId(), gameInstanceId, playableStateScope, pageable); + return ResponseEntity.ok(ApiResponse.success(list)); + }); } @PostMapping @@ -54,21 +49,20 @@ public ResponseEntity> wear( @RequestParam String gameInstanceId, @RequestParam PlayableStateScope playableStateScope, @Valid @RequestBody WearEquipmentItemRequest request) { - return EntityManagementRequestReaders.withBadRequest( - () -> { - EntityManagementRequestReaders.CharacterScope scope = - EntityManagementRequestReaders.requireCharacterScope(tenantId, characterId); - SessionContext.requireTenantAccess(scope.tenantId()); - CharacterEquipmentEntryDto dto = - equipmentService.wearItem( - scope.tenantId(), - scope.characterId(), - gameInstanceId, - playableStateScope, - request.itemId(), - null); - return ResponseEntity.ok(ApiResponse.success(dto)); - }); + return EntityManagementRequestReaders.withBadRequest(() -> { + EntityManagementRequestReaders.CharacterScope scope = + EntityManagementRequestReaders.requireCharacterScope(tenantId, characterId); + SessionContext.requireTenantAccess(scope.tenantId()); + CharacterEquipmentEntryDto dto = + equipmentService.wearItem( + scope.tenantId(), + scope.characterId(), + gameInstanceId, + playableStateScope, + request.itemId(), + null); + return ResponseEntity.ok(ApiResponse.success(dto)); + }); } @DeleteMapping("/{slot}") @@ -78,15 +72,14 @@ public ResponseEntity> remove( @PathVariable String slot, @RequestParam String gameInstanceId, @RequestParam PlayableStateScope playableStateScope) { - return EntityManagementRequestReaders.withBadRequest( - () -> { - EntityManagementRequestReaders.CharacterScope scope = - EntityManagementRequestReaders.requireCharacterScope(tenantId, characterId); - SessionContext.requireTenantAccess(scope.tenantId()); - CharacterEquipmentEntryDto dto = - equipmentService.removeWornItem( - scope.tenantId(), scope.characterId(), gameInstanceId, playableStateScope, slot); - return ResponseEntity.ok(ApiResponse.success(dto)); - }); + return EntityManagementRequestReaders.withBadRequest(() -> { + EntityManagementRequestReaders.CharacterScope scope = + EntityManagementRequestReaders.requireCharacterScope(tenantId, characterId); + SessionContext.requireTenantAccess(scope.tenantId()); + CharacterEquipmentEntryDto dto = + equipmentService.removeWornItem( + scope.tenantId(), scope.characterId(), gameInstanceId, playableStateScope, slot); + return ResponseEntity.ok(ApiResponse.success(dto)); + }); } } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/FriendController.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/FriendController.java index 6b36b3d57f..b2310a9282 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/FriendController.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/FriendController.java @@ -34,20 +34,15 @@ public ResponseEntity>> list( @RequestParam String gameInstanceId, @RequestParam PlayableStateScope playableStateScope, Pageable pageable) { - return EntityManagementRequestReaders.withBadRequest( - () -> { - EntityManagementRequestReaders.CharacterScope scope = - EntityManagementRequestReaders.requireCharacterScope(tenantId, characterId); - SessionContext.requireTenantAccess(scope.tenantId()); - Page list = - friendService.listFriends( - scope.tenantId(), - scope.characterId(), - gameInstanceId, - playableStateScope, - pageable); - return ResponseEntity.ok(ApiResponse.success(list)); - }); + return EntityManagementRequestReaders.withBadRequest(() -> { + EntityManagementRequestReaders.CharacterScope scope = + EntityManagementRequestReaders.requireCharacterScope(tenantId, characterId); + SessionContext.requireTenantAccess(scope.tenantId()); + Page list = + friendService.listFriends( + scope.tenantId(), scope.characterId(), gameInstanceId, playableStateScope, pageable); + return ResponseEntity.ok(ApiResponse.success(list)); + }); } @PostMapping @@ -57,22 +52,20 @@ public ResponseEntity> add( @RequestParam String gameInstanceId, @RequestParam PlayableStateScope playableStateScope, @Valid @RequestBody AddFriendRequest request) { - return EntityManagementRequestReaders.withBadRequest( - () -> { - EntityManagementRequestReaders.CharacterScope scope = - EntityManagementRequestReaders.requireCharacterScope(tenantId, characterId); - long parsedFriendId = - RequestIdValidation.requirePositiveLong(request.friendId(), "friendId"); - SessionContext.requireTenantAccess(scope.tenantId()); - CharacterFriendDto dto = - friendService.addFriend( - scope.tenantId(), - scope.characterId(), - gameInstanceId, - playableStateScope, - parsedFriendId); - return ResponseEntity.ok(ApiResponse.success(dto)); - }); + return EntityManagementRequestReaders.withBadRequest(() -> { + EntityManagementRequestReaders.CharacterScope scope = + EntityManagementRequestReaders.requireCharacterScope(tenantId, characterId); + long parsedFriendId = RequestIdValidation.requirePositiveLong(request.friendId(), "friendId"); + SessionContext.requireTenantAccess(scope.tenantId()); + CharacterFriendDto dto = + friendService.addFriend( + scope.tenantId(), + scope.characterId(), + gameInstanceId, + playableStateScope, + parsedFriendId); + return ResponseEntity.ok(ApiResponse.success(dto)); + }); } @DeleteMapping("/{friendId}") @@ -82,19 +75,18 @@ public ResponseEntity> remove( @PathVariable String friendId, @RequestParam String gameInstanceId, @RequestParam PlayableStateScope playableStateScope) { - return EntityManagementRequestReaders.withBadRequest( - () -> { - EntityManagementRequestReaders.CharacterScope scope = - EntityManagementRequestReaders.requireCharacterScope(tenantId, characterId); - long parsedFriendId = RequestIdValidation.requirePositiveLong(friendId, "friendId"); - SessionContext.requireTenantAccess(scope.tenantId()); - friendService.removeFriend( - scope.tenantId(), - scope.characterId(), - gameInstanceId, - playableStateScope, - parsedFriendId); - return ResponseEntity.ok(ApiResponse.success(null)); - }); + return EntityManagementRequestReaders.withBadRequest(() -> { + EntityManagementRequestReaders.CharacterScope scope = + EntityManagementRequestReaders.requireCharacterScope(tenantId, characterId); + long parsedFriendId = RequestIdValidation.requirePositiveLong(friendId, "friendId"); + SessionContext.requireTenantAccess(scope.tenantId()); + friendService.removeFriend( + scope.tenantId(), + scope.characterId(), + gameInstanceId, + playableStateScope, + parsedFriendId); + return ResponseEntity.ok(ApiResponse.success(null)); + }); } } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/InventoryController.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/InventoryController.java index f4496d4a4b..e004b1fa13 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/InventoryController.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/controller/InventoryController.java @@ -31,20 +31,15 @@ public ResponseEntity>> list( @RequestParam String gameInstanceId, @RequestParam PlayableStateScope playableStateScope, Pageable pageable) { - return EntityManagementRequestReaders.withBadRequest( - () -> { - EntityManagementRequestReaders.CharacterScope scope = - EntityManagementRequestReaders.requireCharacterScope(tenantId, characterId); - SessionContext.requireTenantAccess(scope.tenantId()); - Page list = - inventoryService.listInventory( - scope.tenantId(), - scope.characterId(), - gameInstanceId, - playableStateScope, - pageable); - return ResponseEntity.ok(ApiResponse.success(list)); - }); + return EntityManagementRequestReaders.withBadRequest(() -> { + EntityManagementRequestReaders.CharacterScope scope = + EntityManagementRequestReaders.requireCharacterScope(tenantId, characterId); + SessionContext.requireTenantAccess(scope.tenantId()); + Page list = + inventoryService.listInventory( + scope.tenantId(), scope.characterId(), gameInstanceId, playableStateScope, pageable); + return ResponseEntity.ok(ApiResponse.success(list)); + }); } @PostMapping @@ -54,21 +49,20 @@ public ResponseEntity> addItem( @RequestParam String gameInstanceId, @RequestParam PlayableStateScope playableStateScope, @Valid @RequestBody AddInventoryItemRequest request) { - return EntityManagementRequestReaders.withBadRequest( - () -> { - EntityManagementRequestReaders.CharacterScope scope = - EntityManagementRequestReaders.requireCharacterScope(tenantId, characterId); - SessionContext.requireTenantAccess(scope.tenantId()); - InventoryEntryDto dto = - inventoryService.addItem( - scope.tenantId(), - scope.characterId(), - gameInstanceId, - playableStateScope, - request.itemId(), - request.quantity()); - return ResponseEntity.ok(ApiResponse.success(dto)); - }); + return EntityManagementRequestReaders.withBadRequest(() -> { + EntityManagementRequestReaders.CharacterScope scope = + EntityManagementRequestReaders.requireCharacterScope(tenantId, characterId); + SessionContext.requireTenantAccess(scope.tenantId()); + InventoryEntryDto dto = + inventoryService.addItem( + scope.tenantId(), + scope.characterId(), + gameInstanceId, + playableStateScope, + request.itemId(), + request.quantity()); + return ResponseEntity.ok(ApiResponse.success(dto)); + }); } @DeleteMapping("/{itemId}") @@ -78,20 +72,14 @@ public ResponseEntity> remove( @PathVariable String itemId, @RequestParam String gameInstanceId, @RequestParam PlayableStateScope playableStateScope) { - return EntityManagementRequestReaders.withBadRequest( - () -> { - EntityManagementRequestReaders.CharacterScope scope = - EntityManagementRequestReaders.requireCharacterScope(tenantId, characterId); - long parsedItemId = - EntityManagementRequestReaders.requirePositivePathId(itemId, "itemId"); - SessionContext.requireTenantAccess(scope.tenantId()); - inventoryService.removeItem( - scope.tenantId(), - scope.characterId(), - gameInstanceId, - playableStateScope, - parsedItemId); - return ResponseEntity.ok(ApiResponse.success(null)); - }); + return EntityManagementRequestReaders.withBadRequest(() -> { + EntityManagementRequestReaders.CharacterScope scope = + EntityManagementRequestReaders.requireCharacterScope(tenantId, characterId); + long parsedItemId = EntityManagementRequestReaders.requirePositivePathId(itemId, "itemId"); + SessionContext.requireTenantAccess(scope.tenantId()); + inventoryService.removeItem( + scope.tenantId(), scope.characterId(), gameInstanceId, playableStateScope, parsedItemId); + return ResponseEntity.ok(ApiResponse.success(null)); + }); } } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/data/TestDataSeeder.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/data/TestDataSeeder.java index e83cae5435..bbdad670cb 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/data/TestDataSeeder.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/data/TestDataSeeder.java @@ -69,33 +69,31 @@ private Character ensureDemoCharacter(java.util.UUID accountUuid) { return characterRepository .findByTenantIdAndPlayableStateKeyAndNameIgnoreCase( DEMO_TENANT_ID, SHARED_LIVE_PLAYABLE_STATE, DEMO_CHARACTER_NAME) - .map( - character -> { - if (!accountUuid.equals(character.getAccountUuid())) { - throw new IllegalStateException( - "Retained demo character has unresolved or different Account ownership"); - } - character.setBodyLayoutKey("DEFAULT"); - return characterRepository.save(character); - }) - .orElseGet( - () -> { - Character character = new Character(); - character.setTenantId(DEMO_TENANT_ID); - character.setAccountUuid(accountUuid); - character.setPlayableStateKey(SHARED_LIVE_PLAYABLE_STATE); - character.setName(DEMO_CHARACTER_NAME); - character.setBodyLayoutKey("DEFAULT"); - character.setLevel(1); - character.setExperience(0); - character.setStrength(10); - character.setAgility(10); - character.setIntelligence(10); - character.setStamina(10); - character.setHealth(100); - character.setMana(50); - return characterRepository.save(character); - }); + .map(character -> { + if (!accountUuid.equals(character.getAccountUuid())) { + throw new IllegalStateException( + "Retained demo character has unresolved or different Account ownership"); + } + character.setBodyLayoutKey("DEFAULT"); + return characterRepository.save(character); + }) + .orElseGet(() -> { + Character character = new Character(); + character.setTenantId(DEMO_TENANT_ID); + character.setAccountUuid(accountUuid); + character.setPlayableStateKey(SHARED_LIVE_PLAYABLE_STATE); + character.setName(DEMO_CHARACTER_NAME); + character.setBodyLayoutKey("DEFAULT"); + character.setLevel(1); + character.setExperience(0); + character.setStrength(10); + character.setAgility(10); + character.setIntelligence(10); + character.setStamina(10); + character.setHealth(100); + character.setMana(50); + return characterRepository.save(character); + }); } private void ensureEquipmentSchema() { @@ -136,27 +134,25 @@ private void ensureBodyLayoutSlot(String bodyLayoutKey, String slotKey) { private Item ensureItem(String name, String description, String equipmentSlot) { return itemRepository .findByTenantIdAndNameIgnoreCase(DEMO_TENANT_ID, name) - .map( - item -> { - item.setVersionId(VERSION_ID); - item.setDescription(description); - item.setEquipmentSlot(equipmentSlot); - item.setContainer(false); - item.setStackable(false); - return itemRepository.save(item); - }) - .orElseGet( - () -> { - Item item = new Item(); - item.setTenantId(DEMO_TENANT_ID); - item.setVersionId(VERSION_ID); - item.setName(name); - item.setDescription(description); - item.setEquipmentSlot(equipmentSlot); - item.setContainer(false); - item.setStackable(false); - return itemRepository.save(item); - }); + .map(item -> { + item.setVersionId(VERSION_ID); + item.setDescription(description); + item.setEquipmentSlot(equipmentSlot); + item.setContainer(false); + item.setStackable(false); + return itemRepository.save(item); + }) + .orElseGet(() -> { + Item item = new Item(); + item.setTenantId(DEMO_TENANT_ID); + item.setVersionId(VERSION_ID); + item.setName(name); + item.setDescription(description); + item.setEquipmentSlot(equipmentSlot); + item.setContainer(false); + item.setStackable(false); + return itemRepository.save(item); + }); } private ContainerInstance ensureRoomContainer( @@ -167,16 +163,15 @@ private ContainerInstance ensureRoomContainer( .orElseGet(() -> createRoomItemInstance(item, token, sequence, visibleRef)); return containerInstanceRepository .findByItemInstance_Id(itemInstance.getId()) - .orElseGet( - () -> { - ContainerInstance container = new ContainerInstance(); - container.setTenantId(DEMO_TENANT_ID); - container.setGameInstanceId(DEMO_GAME_INSTANCE_ID); - container.setRoomInstanceId(STARTER_RUNTIME_ROOM_INSTANCE_ID); - container.setItem(item); - container.setItemInstance(itemInstance); - return containerInstanceRepository.save(container); - }); + .orElseGet(() -> { + ContainerInstance container = new ContainerInstance(); + container.setTenantId(DEMO_TENANT_ID); + container.setGameInstanceId(DEMO_GAME_INSTANCE_ID); + container.setRoomInstanceId(STARTER_RUNTIME_ROOM_INSTANCE_ID); + container.setItem(item); + container.setItemInstance(itemInstance); + return containerInstanceRepository.save(container); + }); } private void ensureContainedItem( diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java index 7f16301b01..18447e7951 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/effect/DefaultEffectEvaluationService.java @@ -33,17 +33,15 @@ public EffectEvaluationResult evaluate(EffectEvaluationInput input) { List grantedStates = modifiers.stream() - .filter( - modifier -> - modifier.operation() == EffectOperation.GRANT_FLAG - || modifier.operation() == EffectOperation.GRANT_CONDITION) - .map( - modifier -> - new GrantedActorState( - modifier.targetKey(), - modifier.operation(), - modifier.scope(), - modifier.source())) + .filter(modifier -> + modifier.operation() == EffectOperation.GRANT_FLAG + || modifier.operation() == EffectOperation.GRANT_CONDITION) + .map(modifier -> + new GrantedActorState( + modifier.targetKey(), + modifier.operation(), + modifier.scope(), + modifier.source())) .toList(); return new EffectEvaluationResult( resources.values().stream().map(MutableResource::toEvaluated).toList(), grantedStates); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java index 457224a624..c8730f6cff 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionRepository.java @@ -367,27 +367,26 @@ public java.util.List closedAdmissionCandidates(UUID a after, after, limit) - .map( - row -> { - try { - byte[] bytes = row.get("recovery_response", byte[].class); - if (bytes == null) - return ClosedAdmissionCandidate.invalid( - row.get("operation_uuid", UUID.class), row.get("admission_uuid", UUID.class)); - var response = CanonicalGameplayRosterRecoveryResponse.parseFrom(bytes); - CanonicalGameplayRosterRecoveryEvidence.requireResponse( - response.getRequest(), response); - return new ClosedAdmissionCandidate( - row.get("operation_uuid", UUID.class), - row.get("admission_uuid", UUID.class), - response); - } catch (com.google.protobuf.InvalidProtocolBufferException - | IllegalArgumentException - | IllegalStateException invalid) { - return ClosedAdmissionCandidate.invalid( - row.get("operation_uuid", UUID.class), row.get("admission_uuid", UUID.class)); - } - }); + .map(row -> { + try { + byte[] bytes = row.get("recovery_response", byte[].class); + if (bytes == null) + return ClosedAdmissionCandidate.invalid( + row.get("operation_uuid", UUID.class), row.get("admission_uuid", UUID.class)); + var response = CanonicalGameplayRosterRecoveryResponse.parseFrom(bytes); + CanonicalGameplayRosterRecoveryEvidence.requireResponse( + response.getRequest(), response); + return new ClosedAdmissionCandidate( + row.get("operation_uuid", UUID.class), + row.get("admission_uuid", UUID.class), + response); + } catch (com.google.protobuf.InvalidProtocolBufferException + | IllegalArgumentException + | IllegalStateException invalid) { + return ClosedAdmissionCandidate.invalid( + row.get("operation_uuid", UUID.class), row.get("admission_uuid", UUID.class)); + } + }); } /** @@ -716,38 +715,37 @@ public java.util.List candidates(UUID afterSnapshot, int limit) { afterSnapshot, afterSnapshot, limit) - .map( - row -> { - try { - byte[] bytes = row.get("owner_request", byte[].class); - if (bytes == null) return Candidate.invalid(row.get("snapshot_uuid", UUID.class)); - var request = - net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest - .parseFrom(bytes); - CanonicalGameplayRosterReferenceEvidence.requireRequest(request); - var target = - net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget - .fromWire(CanonicalGameplayRosterReferenceEvidence.target(request)); - var binding = - new CanonicalGameplayRosterRetentionBinding( - UUID.fromString(request.getCanonicalAccountUuid()), - new net.firedevops.firemud.entitymanagement.service - .CanonicalGameplayRosterSnapshotReference( - row.get("snapshot_uuid", UUID.class), - row.get("snapshot_digest", String.class)), - target); - return new Candidate( - binding, - request, - row.get("local_epoch", Long.class), - row.get("lifecycle_state", String.class), - row.get("owner_retirement_proof_digest", String.class)); - } catch (com.google.protobuf.InvalidProtocolBufferException - | IllegalArgumentException - | IllegalStateException invalid) { - return Candidate.invalid(row.get("snapshot_uuid", UUID.class)); - } - }); + .map(row -> { + try { + byte[] bytes = row.get("owner_request", byte[].class); + if (bytes == null) return Candidate.invalid(row.get("snapshot_uuid", UUID.class)); + var request = + net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest + .parseFrom(bytes); + CanonicalGameplayRosterReferenceEvidence.requireRequest(request); + var target = + net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterTarget + .fromWire(CanonicalGameplayRosterReferenceEvidence.target(request)); + var binding = + new CanonicalGameplayRosterRetentionBinding( + UUID.fromString(request.getCanonicalAccountUuid()), + new net.firedevops.firemud.entitymanagement.service + .CanonicalGameplayRosterSnapshotReference( + row.get("snapshot_uuid", UUID.class), + row.get("snapshot_digest", String.class)), + target); + return new Candidate( + binding, + request, + row.get("local_epoch", Long.class), + row.get("lifecycle_state", String.class), + row.get("owner_retirement_proof_digest", String.class)); + } catch (com.google.protobuf.InvalidProtocolBufferException + | IllegalArgumentException + | IllegalStateException invalid) { + return Candidate.invalid(row.get("snapshot_uuid", UUID.class)); + } + }); } /** Authenticated immutable GS target-seal evidence is observed on Entity's independent clock. */ @@ -1943,124 +1941,117 @@ public java.util.List retirementTransfers(UUID after, int li after, after, limit) - .map( - row -> { - try { - byte[] bytes = row.get("original_request", byte[].class); - if (bytes == null) - return RetirementTransfer.invalid( - row.get("observation_uuid", UUID.class), - row.get("transfer_state", String.class)); - var original = GetCanonicalGameplayRosterReferenceRequest.parseFrom(bytes); - CanonicalGameplayRosterReferenceEvidence.requireRequest(original); - if (!entryPolicy(original).equals(row.get("entry_policy", String.class))) - throw new IllegalArgumentException("Transfer policy mismatch"); - if (!original - .getOperationUuid() - .equals(row.get("operation_uuid", UUID.class).toString())) { - throw new IllegalStateException("CANONICAL_ROSTER_RETIREMENT_TRANSFER_CONFLICT"); - } - if (row.get("closed_admission_receipt", byte[].class) != null) { - var closed = - CanonicalGameplayRosterRecoveryResponse.parseFrom( - row.get("closed_admission_receipt", byte[].class)); - CanonicalGameplayRosterRecoveryEvidence.requireResponse( - closed.getRequest(), closed); - if (!closed.getRequest().getOriginalSelection().equals(original) - || !closed - .getAdmissionUuid() - .equals(row.get("admission_uuid", UUID.class).toString()) - || !closed.getCanonicalRosterReceipt().isEmpty() - || !closed.getCanonicalPlayerCreatedRosterReceipt().isEmpty() - || closed.getOwnerFence() != row.get("owner_fence", Long.class) - || !closed - .getTargetFenceUuid() - .equals(row.get("target_fence_uuid", UUID.class).toString())) { - throw new IllegalStateException( - "CANONICAL_ROSTER_RETIREMENT_TRANSFER_CONFLICT"); - } - } - var request = - row.get("acknowledgement_request", byte[].class) == null - ? null - : CanonicalGameplayRosterRetirementAcknowledgementRequest.parseFrom( - row.get("acknowledgement_request", byte[].class)); - var acknowledgement = - row.get("acknowledgement_response", byte[].class) == null - ? null - : CanonicalGameplayRosterRetirementAcknowledgementResponse.parseFrom( - row.get("acknowledgement_response", byte[].class)); - if ((acknowledgement != null && request == null) - || (request == null - && !"WAITING_RETIREMENT".equals(row.get("transfer_state", String.class))) - || (acknowledgement == null - && "ACKNOWLEDGED".equals(row.get("transfer_state", String.class)))) { - throw new IllegalStateException("CANONICAL_ROSTER_RETIREMENT_TRANSFER_INVALID"); - } - if (request != null) { - // Each fresh retained row is fully validated once. The guarded response - // validator also computes and binds this same immutable request digest. - String requestDigest = - acknowledgement == null - ? CanonicalGameplayRosterRetirementEvidence.requestDigest(request) - : CanonicalGameplayRosterRetirementEvidence - .requireAcknowledgementResponse(request, acknowledgement) - .getRequestDigest(); - if (!request.getOriginalSelection().equals(original) - || !request - .getObservationUuid() - .equals(row.get("observation_uuid", UUID.class).toString()) - || !request - .getAdmissionUuid() - .equals(row.get("admission_uuid", UUID.class).toString()) - || !Objects.equals( - request.getSnapshotUuid(), - row.get("snapshot_uuid", UUID.class) == null - ? "" - : row.get("snapshot_uuid", UUID.class).toString()) - || !Objects.equals( - request.getSnapshotDigest(), - row.get("snapshot_digest", String.class) == null - ? "" - : row.get("snapshot_digest", String.class)) - || request.getMinimumRetentionMillis() - != row.get("minimum_retention_millis", Long.class) - || request.getObservedRetirement().getOwnerFence() - != row.get("owner_fence", Long.class) - || !request - .getObservedRetirement() - .getTargetFenceUuid() - .equals(row.get("target_fence_uuid", UUID.class).toString()) - || !Arrays.equals( - request.getObservedRetirement().toByteArray(), - row.get("observed_retirement", byte[].class)) - || !requestDigest.equals(row.get("request_digest", String.class))) { - throw new IllegalStateException( - "CANONICAL_ROSTER_RETIREMENT_TRANSFER_CONFLICT"); - } - } - if (acknowledgement != null) { - Long effectiveMinimum = row.get("effective_minimum_retention_millis", Long.class); - if (effectiveMinimum == null - || acknowledgement.getMinimumRetentionMillis() != effectiveMinimum) { - throw new IllegalStateException( - "CANONICAL_ROSTER_RETIREMENT_TRANSFER_CONFLICT"); - } - } - return new RetirementTransfer( - row.get("observation_uuid", UUID.class), - row.get("transfer_state", String.class), - original, - request, - acknowledgement); - } catch (com.google.protobuf.InvalidProtocolBufferException - | IllegalArgumentException - | IllegalStateException invalid) { - return RetirementTransfer.invalid( - row.get("observation_uuid", UUID.class), - row.get("transfer_state", String.class)); + .map(row -> { + try { + byte[] bytes = row.get("original_request", byte[].class); + if (bytes == null) + return RetirementTransfer.invalid( + row.get("observation_uuid", UUID.class), row.get("transfer_state", String.class)); + var original = GetCanonicalGameplayRosterReferenceRequest.parseFrom(bytes); + CanonicalGameplayRosterReferenceEvidence.requireRequest(original); + if (!entryPolicy(original).equals(row.get("entry_policy", String.class))) + throw new IllegalArgumentException("Transfer policy mismatch"); + if (!original + .getOperationUuid() + .equals(row.get("operation_uuid", UUID.class).toString())) { + throw new IllegalStateException("CANONICAL_ROSTER_RETIREMENT_TRANSFER_CONFLICT"); + } + if (row.get("closed_admission_receipt", byte[].class) != null) { + var closed = + CanonicalGameplayRosterRecoveryResponse.parseFrom( + row.get("closed_admission_receipt", byte[].class)); + CanonicalGameplayRosterRecoveryEvidence.requireResponse(closed.getRequest(), closed); + if (!closed.getRequest().getOriginalSelection().equals(original) + || !closed + .getAdmissionUuid() + .equals(row.get("admission_uuid", UUID.class).toString()) + || !closed.getCanonicalRosterReceipt().isEmpty() + || !closed.getCanonicalPlayerCreatedRosterReceipt().isEmpty() + || closed.getOwnerFence() != row.get("owner_fence", Long.class) + || !closed + .getTargetFenceUuid() + .equals(row.get("target_fence_uuid", UUID.class).toString())) { + throw new IllegalStateException("CANONICAL_ROSTER_RETIREMENT_TRANSFER_CONFLICT"); } - }); + } + var request = + row.get("acknowledgement_request", byte[].class) == null + ? null + : CanonicalGameplayRosterRetirementAcknowledgementRequest.parseFrom( + row.get("acknowledgement_request", byte[].class)); + var acknowledgement = + row.get("acknowledgement_response", byte[].class) == null + ? null + : CanonicalGameplayRosterRetirementAcknowledgementResponse.parseFrom( + row.get("acknowledgement_response", byte[].class)); + if ((acknowledgement != null && request == null) + || (request == null + && !"WAITING_RETIREMENT".equals(row.get("transfer_state", String.class))) + || (acknowledgement == null + && "ACKNOWLEDGED".equals(row.get("transfer_state", String.class)))) { + throw new IllegalStateException("CANONICAL_ROSTER_RETIREMENT_TRANSFER_INVALID"); + } + if (request != null) { + // Each fresh retained row is fully validated once. The guarded response + // validator also computes and binds this same immutable request digest. + String requestDigest = + acknowledgement == null + ? CanonicalGameplayRosterRetirementEvidence.requestDigest(request) + : CanonicalGameplayRosterRetirementEvidence.requireAcknowledgementResponse( + request, acknowledgement) + .getRequestDigest(); + if (!request.getOriginalSelection().equals(original) + || !request + .getObservationUuid() + .equals(row.get("observation_uuid", UUID.class).toString()) + || !request + .getAdmissionUuid() + .equals(row.get("admission_uuid", UUID.class).toString()) + || !Objects.equals( + request.getSnapshotUuid(), + row.get("snapshot_uuid", UUID.class) == null + ? "" + : row.get("snapshot_uuid", UUID.class).toString()) + || !Objects.equals( + request.getSnapshotDigest(), + row.get("snapshot_digest", String.class) == null + ? "" + : row.get("snapshot_digest", String.class)) + || request.getMinimumRetentionMillis() + != row.get("minimum_retention_millis", Long.class) + || request.getObservedRetirement().getOwnerFence() + != row.get("owner_fence", Long.class) + || !request + .getObservedRetirement() + .getTargetFenceUuid() + .equals(row.get("target_fence_uuid", UUID.class).toString()) + || !Arrays.equals( + request.getObservedRetirement().toByteArray(), + row.get("observed_retirement", byte[].class)) + || !requestDigest.equals(row.get("request_digest", String.class))) { + throw new IllegalStateException("CANONICAL_ROSTER_RETIREMENT_TRANSFER_CONFLICT"); + } + } + if (acknowledgement != null) { + Long effectiveMinimum = row.get("effective_minimum_retention_millis", Long.class); + if (effectiveMinimum == null + || acknowledgement.getMinimumRetentionMillis() != effectiveMinimum) { + throw new IllegalStateException("CANONICAL_ROSTER_RETIREMENT_TRANSFER_CONFLICT"); + } + } + return new RetirementTransfer( + row.get("observation_uuid", UUID.class), + row.get("transfer_state", String.class), + original, + request, + acknowledgement); + } catch (com.google.protobuf.InvalidProtocolBufferException + | IllegalArgumentException + | IllegalStateException invalid) { + return RetirementTransfer.invalid( + row.get("observation_uuid", UUID.class), row.get("transfer_state", String.class)); + } + }); } public boolean observeWaitingRetirement( diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java index 7cc00fe148..066d70b3a4 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/CharacterRepository.java @@ -1282,10 +1282,9 @@ private List readCurrentCanonicalRoster( List actors = query .forShare() - .fetch( - row -> - new CanonicalGameplayRosterActor( - row.get(CHARACTERS.CHARACTER_UUID), row.get(CHARACTERS.NAME))); + .fetch(row -> + new CanonicalGameplayRosterActor( + row.get(CHARACTERS.CHARACTER_UUID), row.get(CHARACTERS.NAME))); if (actors.size() > CanonicalGameplayRosterSnapshotDigest.MAX_ROSTER_SIZE) { throw new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_LIMIT_EXCEEDED"); } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogRepository.java index 38692604ac..1120421033 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogRepository.java @@ -44,29 +44,28 @@ public EntityRuntimeFamilyCatalogRepository( public Evidence read(Request request) { requireIndependent(request); byte[] committed = - capture.execute( - status -> { - var catalog = currentCatalog(); - byte[] requestBytes = EntityRuntimeFamilyCatalogCodec.requestBytes(request); - var proposed = new Evidence(request, UUID.randomUUID(), catalog); - byte[] evidenceBytes = EntityRuntimeFamilyCatalogCodec.evidenceBytes(proposed); - dsl.execute( - "INSERT INTO " - + table("entity_runtime_family_catalog_snapshot") - + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," - + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)" - + " ON CONFLICT (read_request_id) DO NOTHING", - request.readRequestId(), - request.targetNamespace(), - requestBytes, - EntityRuntimeFamilyCatalog.sha256(requestBytes), - proposed.snapshotId(), - catalog.catalogEpoch(), - catalog.digest(), - evidenceBytes, - proposed.digest()); - return retained(request, catalog); - }); + capture.execute(status -> { + var catalog = currentCatalog(); + byte[] requestBytes = EntityRuntimeFamilyCatalogCodec.requestBytes(request); + var proposed = new Evidence(request, UUID.randomUUID(), catalog); + byte[] evidenceBytes = EntityRuntimeFamilyCatalogCodec.evidenceBytes(proposed); + dsl.execute( + "INSERT INTO " + + table("entity_runtime_family_catalog_snapshot") + + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," + + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)" + + " ON CONFLICT (read_request_id) DO NOTHING", + request.readRequestId(), + request.targetNamespace(), + requestBytes, + EntityRuntimeFamilyCatalog.sha256(requestBytes), + proposed.snapshotId(), + catalog.catalogEpoch(), + catalog.digest(), + evidenceBytes, + proposed.digest()); + return retained(request, catalog); + }); Evidence result = readExact(request); if (!Arrays.equals(committed, EntityRuntimeFamilyCatalogCodec.evidenceBytes(result))) throw new CatalogConflictException("Committed catalog readback changed"); @@ -76,10 +75,8 @@ public Evidence read(Request request) { /** Independent committed readback; drift or missing evidence never becomes an empty success. */ public Evidence readExact(Request request) { requireIndependent(request); - return readback.execute( - status -> - EntityRuntimeFamilyCatalogCodec.evidenceFromStored( - retained(request, currentCatalog()))); + return readback.execute(status -> + EntityRuntimeFamilyCatalogCodec.evidenceFromStored(retained(request, currentCatalog()))); } private EntityRuntimeFamilyCatalog currentCatalog() { diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/PreseededActorRuntimeProjectionRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/PreseededActorRuntimeProjectionRepository.java index af20c54965..9796b72b2f 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/PreseededActorRuntimeProjectionRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/repository/PreseededActorRuntimeProjectionRepository.java @@ -22,15 +22,15 @@ void allocateFreshAssignment(PreseededActorAssignmentReceipt receipt) { int inserted = dsl.execute( """ - INSERT INTO entity_preseeded_actor_runtime_projections - (tenant_uuid, playable_state_namespace_id, game_instance_id, character_uuid, - assignment_uuid, intent_digest, published_owner_proof_digest) - SELECT tenant_uuid, playable_state_namespace_id, game_instance_id, character_uuid, - assignment_uuid, intent_digest, published_owner_proof_digest - FROM entity_preseeded_actor_assignment_operations - WHERE assignment_uuid = ? AND character_uuid = ? AND intent_digest = ? - AND status = 'ASSIGNED' AND publication_evidence_format = 'CANONICAL_UUID' - """, + INSERT INTO entity_preseeded_actor_runtime_projections + (tenant_uuid, playable_state_namespace_id, game_instance_id, character_uuid, + assignment_uuid, intent_digest, published_owner_proof_digest) + SELECT tenant_uuid, playable_state_namespace_id, game_instance_id, character_uuid, + assignment_uuid, intent_digest, published_owner_proof_digest + FROM entity_preseeded_actor_assignment_operations + WHERE assignment_uuid = ? AND character_uuid = ? AND intent_digest = ? + AND status = 'ASSIGNED' AND publication_evidence_format = 'CANONICAL_UUID' + """, receipt.assignmentUuid(), receipt.characterUuid(), receipt.intentDigest()); @@ -44,12 +44,12 @@ Optional read(PreseededActorAssignmentReceipt re var row = dsl.fetchOne( """ - SELECT runtime_entity_id, projection_generation, projection_fence - FROM entity_preseeded_actor_runtime_projections - WHERE tenant_uuid = ? AND playable_state_namespace_id = ? AND game_instance_id = ? - AND character_uuid = ? AND assignment_uuid = ? AND intent_digest = ? - AND published_owner_proof_digest = ? AND projection_state = 'CURRENT' - """, + SELECT runtime_entity_id, projection_generation, projection_fence + FROM entity_preseeded_actor_runtime_projections + WHERE tenant_uuid = ? AND playable_state_namespace_id = ? AND game_instance_id = ? + AND character_uuid = ? AND assignment_uuid = ? AND intent_digest = ? + AND published_owner_proof_digest = ? AND projection_state = 'CURRENT' + """, target.canonicalTenantUuid(), target.playableStateNamespaceId(), target.gameInstanceId(), diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionService.java index e7ef20ef16..96974244fa 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionService.java @@ -58,33 +58,27 @@ public synchronized void sweep() { || TransactionSynchronizationManager.isSynchronizationActive()) { throw new IllegalStateException("CANONICAL_ROSTER_SWEEP_REQUIRES_NO_AMBIENT_TRANSACTION"); } - runCleanupStage( - () -> - transactions.executeWithoutResult( - ignored -> repository.classifyRetainedDependencies(policy.batchSize()))); + runCleanupStage(() -> + transactions.executeWithoutResult( + ignored -> repository.classifyRetainedDependencies(policy.batchSize()))); runCleanupStage(this::sweepSnapshots); runCleanupStage(this::sweepClosedAdmissions); runCleanupStage(this::sweepRetirementTransfers); - runCleanupStage( - () -> - transactions.executeWithoutResult( - ignored -> repository.purgeOrphanOpenAdmissions(policy, policy.batchSize()))); - runCleanupStage( - () -> - transactions.executeWithoutResult( - ignored -> repository.purgeDisposedTombstones(policy.batchSize()))); - runCleanupStage( - () -> - transactions.executeWithoutResult( - ignored -> repository.purgeConfirmedRetirementTransfers(policy.batchSize()))); - runCleanupStage( - () -> - transactions.executeWithoutResult( - ignored -> repository.purgeRetiredTargets(policy.batchSize()))); - runCleanupStage( - () -> - transactions.executeWithoutResult( - ignored -> repository.purgeTargetClassifications(policy.batchSize()))); + runCleanupStage(() -> + transactions.executeWithoutResult( + ignored -> repository.purgeOrphanOpenAdmissions(policy, policy.batchSize()))); + runCleanupStage(() -> + transactions.executeWithoutResult( + ignored -> repository.purgeDisposedTombstones(policy.batchSize()))); + runCleanupStage(() -> + transactions.executeWithoutResult( + ignored -> repository.purgeConfirmedRetirementTransfers(policy.batchSize()))); + runCleanupStage(() -> + transactions.executeWithoutResult( + ignored -> repository.purgeRetiredTargets(policy.batchSize()))); + runCleanupStage(() -> + transactions.executeWithoutResult( + ignored -> repository.purgeTargetClassifications(policy.batchSize()))); refreshHealth(); } @@ -230,9 +224,8 @@ private void sweepRetirementTransfers() { transfer.acknowledgementRequest())); boolean acknowledged = Boolean.TRUE.equals( - transactions.execute( - ignored -> - repository.recordRetirementAcknowledgement(transfer, acknowledgement))); + transactions.execute(ignored -> + repository.recordRetirementAcknowledgement(transfer, acknowledgement))); if (acknowledged) { metrics .counter("firemud.canonical.roster.cleanup", "result", "acknowledged") diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshot.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshot.java index 39c9b7f047..7df7e0fc27 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshot.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSnapshot.java @@ -51,16 +51,15 @@ public static CanonicalGameplayRosterSnapshot fromWire( } var actors = receipt.getActorsList().stream() - .map( - actor -> { - if (actor.getActorKind() - != net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind - .CANONICAL_ROSTER_ACTOR_KIND_PLAYER) { - throw new IllegalArgumentException("Retained roster actor kind is invalid"); - } - return new CanonicalGameplayRosterActor( - UUID.fromString(actor.getCharacterUuid()), actor.getDisplayName()); - }) + .map(actor -> { + if (actor.getActorKind() + != net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind + .CANONICAL_ROSTER_ACTOR_KIND_PLAYER) { + throw new IllegalArgumentException("Retained roster actor kind is invalid"); + } + return new CanonicalGameplayRosterActor( + UUID.fromString(actor.getCharacterUuid()), actor.getDisplayName()); + }) .toList(); var snapshot = new CanonicalGameplayRosterSnapshot( diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java index 26283287d5..3baa6ee0f6 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java @@ -20,11 +20,10 @@ public Character requireScopedCharacter( String playableStateKey = playableStateKeyResolver.resolve(gameInstanceId, playableStateScope); return characterRepository .findByIdAndTenantIdAndPlayableStateKey(characterId, tenantId, playableStateKey) - .or( - () -> - characterRepository - .findByIdAndTenantId(characterId, tenantId) - .filter(character -> playableStateKey.equals(character.getPlayableStateKey()))) + .or(() -> + characterRepository + .findByIdAndTenantId(characterId, tenantId) + .filter(character -> playableStateKey.equals(character.getPlayableStateKey()))) .orElseThrow( () -> new IllegalArgumentException("Character does not belong to gameplay scope")); } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java index 54cc7fed53..17de724829 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ActorStateServiceImpl.java @@ -157,12 +157,11 @@ private List evaluateEffects( private List conditionModifiers( long characterId, List activeConditions) { return activeConditions.stream() - .flatMap( - condition -> - effectPayloadParser - .parseModifiers( - condition.effectPayloadJson(), toEffectSource(characterId, condition)) - .stream()) + .flatMap(condition -> + effectPayloadParser + .parseModifiers( + condition.effectPayloadJson(), toEffectSource(characterId, condition)) + .stream()) .toList(); } @@ -174,13 +173,12 @@ private List equipmentModifiers(long tenantId, long characterId) .findByTenantIdAndCharacter_IdAndEquipmentSlotIsNotNullAndGameInstanceIdIsNullAndRoomInstanceIdIsNullOrderByEquipmentSlotAscIdAsc( tenantId, characterId) .stream() - .flatMap( - itemInstance -> - effectPayloadParser - .parseModifiers( - itemInstance.getItem().getEffectPayloadJson(), - toEffectSource(characterId, itemInstance)) - .stream()) + .flatMap(itemInstance -> + effectPayloadParser + .parseModifiers( + itemInstance.getItem().getEffectPayloadJson(), + toEffectSource(characterId, itemInstance)) + .stream()) .toList(); } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java index 3cc6a23e6b..ea1375bcfa 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/ContainerServiceImpl.java @@ -420,17 +420,16 @@ private String moveInventoryStackToContainer( itemStackRepository .findByTenantIdAndContainerInstance_IdAndItem_IdAndCompatibilityFingerprint( tenantId, containerInstance.getId(), item.getId(), compatibilityFingerprint) - .orElseGet( - () -> { - ItemStack created = new ItemStack(); - created.setTenantId(tenantId); - created.setContainerInstance(containerInstance); - created.setItem(item); - created.setStackFamilyKey(source.getStackFamilyKey()); - created.setCompatibilityFingerprint(compatibilityFingerprint); - created.setQuantity(0); - return created; - }); + .orElseGet(() -> { + ItemStack created = new ItemStack(); + created.setTenantId(tenantId); + created.setContainerInstance(containerInstance); + created.setItem(item); + created.setStackFamilyKey(source.getStackFamilyKey()); + created.setCompatibilityFingerprint(compatibilityFingerprint); + created.setQuantity(0); + return created; + }); destination.setQuantity(destination.getQuantity() + quantity); itemStackRepository.save(destination); itemTransferAuditWriter.recordStackTransfer( @@ -467,17 +466,16 @@ private String moveContainerStackToInventory( itemStackRepository .findByTenantIdAndCharacter_IdAndEquipmentSlotIsNullAndGameInstanceIdIsNullAndRoomInstanceIdIsNullAndContainerInstanceIsNullAndItem_IdAndCompatibilityFingerprint( tenantId, character.getId(), item.getId(), compatibilityFingerprint) - .orElseGet( - () -> { - ItemStack created = new ItemStack(); - created.setTenantId(tenantId); - created.setCharacter(character); - created.setItem(item); - created.setStackFamilyKey(source.getStackFamilyKey()); - created.setCompatibilityFingerprint(compatibilityFingerprint); - created.setQuantity(0); - return created; - }); + .orElseGet(() -> { + ItemStack created = new ItemStack(); + created.setTenantId(tenantId); + created.setCharacter(character); + created.setItem(item); + created.setStackFamilyKey(source.getStackFamilyKey()); + created.setCompatibilityFingerprint(compatibilityFingerprint); + created.setQuantity(0); + return created; + }); destination.setQuantity(destination.getQuantity() + quantity); itemStackRepository.save(destination); itemTransferAuditWriter.recordStackTransfer( @@ -519,10 +517,9 @@ private ItemStack requireSingleStackSource( } if (stackFamilyKey != null) { return stacks.stream() - .filter( - stack -> - stackFamilyKey.equals( - stackableItemSupport.normalizeStackFamilyKey(stack.getStackFamilyKey()))) + .filter(stack -> + stackFamilyKey.equals( + stackableItemSupport.normalizeStackFamilyKey(stack.getStackFamilyKey()))) .findFirst() .orElseThrow(() -> new IllegalArgumentException(notFoundMessage)); } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java index 29256aa92c..4e85f81c92 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityDraftDesignDigestServiceImpl.java @@ -54,59 +54,54 @@ public EntityDraftDesignDigest getDraftDesignDigest(String tenantId, String vers itemRepository .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) .stream() - .map( - item -> - Map.of( - "id", item.getId(), - "name", item.getName(), - "description", value(item.getDescription()), - "equipmentSlot", value(item.getEquipmentSlot()), - "container", item.isContainer(), - "stackable", item.isStackable(), - "stackCompatibilityMode", item.getStackCompatibilityMode().name(), - "stackVariantKey", value(item.getStackVariantKey()), - "effectPayloadJson", value(item.getEffectPayloadJson()))) + .map(item -> + Map.of( + "id", item.getId(), + "name", item.getName(), + "description", value(item.getDescription()), + "equipmentSlot", value(item.getEquipmentSlot()), + "container", item.isContainer(), + "stackable", item.isStackable(), + "stackCompatibilityMode", item.getStackCompatibilityMode().name(), + "stackVariantKey", value(item.getStackVariantKey()), + "effectPayloadJson", value(item.getEffectPayloadJson()))) .toList(), "npcs", npcRepository .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) .stream() - .map( - npc -> - Map.of( - "id", npc.getId(), - "name", npc.getName(), - "behavior", value(npc.getBehavior()), - "respawnDelaySeconds", npc.getRespawnDelaySeconds())) + .map(npc -> + Map.of( + "id", npc.getId(), + "name", npc.getName(), + "behavior", value(npc.getBehavior()), + "respawnDelaySeconds", npc.getRespawnDelaySeconds())) .toList(), "craftingRecipes", craftingRecipeRepository .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) .stream() - .map( - recipe -> - Map.of( - "id", - recipe.getId(), - "name", - recipe.getName(), - "resultItemId", - recipe.getResultItem().getId(), - "resultQuantity", - recipe.getResultQuantity(), - "ingredients", - recipe.getIngredients().stream() - .sorted( - Comparator.comparing( - (CraftingIngredient ingredient) -> - ingredient.getItem().getId()) - .thenComparingInt(CraftingIngredient::getQuantity)) - .map( - ingredient -> - Map.of( - "itemId", ingredient.getItem().getId(), - "quantity", ingredient.getQuantity())) - .toList())) + .map(recipe -> + Map.of( + "id", + recipe.getId(), + "name", + recipe.getName(), + "resultItemId", + recipe.getResultItem().getId(), + "resultQuantity", + recipe.getResultQuantity(), + "ingredients", + recipe.getIngredients().stream() + .sorted( + Comparator.comparing((CraftingIngredient ingredient) -> + ingredient.getItem().getId()) + .thenComparingInt(CraftingIngredient::getQuantity)) + .map(ingredient -> + Map.of( + "itemId", ingredient.getItem().getId(), + "quantity", ingredient.getQuantity())) + .toList())) .toList())); return new EntityDraftDesignDigest( tenantId, diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayService.java index 3d2e458488..c45ca6b35c 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayService.java @@ -58,10 +58,9 @@ public T execute( EntityMutationEffect raced = repository .findByTenantIdAndEffectId(tenantId, normalizedEffectId) - .orElseThrow( - () -> - new ResponseStatusException( - HttpStatus.CONFLICT, "Mutation effect is already being applied")); + .orElseThrow(() -> + new ResponseStatusException( + HttpStatus.CONFLICT, "Mutation effect is already being applied")); return replay(raced, normalizedOperationName, parser); } return executeFirstApplication(tenantId, normalizedEffectId, normalizedOperationName, mutation); @@ -86,10 +85,9 @@ private T executeFirstApplication( EntityMutationEffect effect = repository .findByTenantIdAndEffectId(tenantId, effectId) - .orElseThrow( - () -> - new ResponseStatusException( - HttpStatus.CONFLICT, "Mutation effect marker was not created")); + .orElseThrow(() -> + new ResponseStatusException( + HttpStatus.CONFLICT, "Mutation effect marker was not created")); T response = mutation.get(); effect.setStatus(STATUS_APPLIED); effect.setResponseType(response.getClass().getName()); diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.java index 422512e04d..83a5bc9a34 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/GameSessionCanonicalGameplayRosterOwnerEvidenceAdapter.java @@ -157,10 +157,9 @@ private CanonicalGameplayRosterOwnerEvidence mapCompleteEvidence( List exactPolicies = policySet.policies().stream() - .filter( - candidate -> - candidate.policy().worldSlug().equals(holdRequest.worldSlug()) - && candidate.policy().realmSlug().equals(ownerReadRequest.realmSlug())) + .filter(candidate -> + candidate.policy().worldSlug().equals(holdRequest.worldSlug()) + && candidate.policy().realmSlug().equals(ownerReadRequest.realmSlug())) .toList(); if (exactPolicies.size() != 1) { throw new IllegalArgumentException( diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java index 088df7facb..1246fe5258 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/InventoryServiceImpl.java @@ -355,18 +355,17 @@ private void incrementInventoryStack( itemStackRepository .findByTenantIdAndCharacter_IdAndEquipmentSlotIsNullAndGameInstanceIdIsNullAndRoomInstanceIdIsNullAndContainerInstanceIsNullAndItem_IdAndCompatibilityFingerprint( character.getTenantId(), character.getId(), item.getId(), compatibilityFingerprint) - .orElseGet( - () -> { - ItemStack created = new ItemStack(); - created.setTenantId(character.getTenantId()); - created.setCharacter(character); - created.setItem(item); - created.setStackFamilyKey( - stackableItemSupport.normalizeStackFamilyKey(stackFamilyKey)); - created.setCompatibilityFingerprint(compatibilityFingerprint); - created.setQuantity(0); - return created; - }); + .orElseGet(() -> { + ItemStack created = new ItemStack(); + created.setTenantId(character.getTenantId()); + created.setCharacter(character); + created.setItem(item); + created.setStackFamilyKey( + stackableItemSupport.normalizeStackFamilyKey(stackFamilyKey)); + created.setCompatibilityFingerprint(compatibilityFingerprint); + created.setQuantity(0); + return created; + }); stack.setQuantity(stack.getQuantity() + quantity); itemStackRepository.save(stack); } @@ -391,18 +390,17 @@ private String moveInventoryStackToRoom( itemStackRepository .findByTenantIdAndGameInstanceIdAndRoomInstanceIdAndCharacterIsNullAndEquipmentSlotIsNullAndContainerInstanceIsNullAndItem_IdAndCompatibilityFingerprint( tenantId, gameInstanceId, roomInstanceId, item.getId(), compatibilityFingerprint) - .orElseGet( - () -> { - ItemStack created = new ItemStack(); - created.setTenantId(tenantId); - created.setGameInstanceId(gameInstanceId); - created.setRoomInstanceId(roomInstanceId); - created.setItem(item); - created.setStackFamilyKey(source.getStackFamilyKey()); - created.setCompatibilityFingerprint(compatibilityFingerprint); - created.setQuantity(0); - return created; - }); + .orElseGet(() -> { + ItemStack created = new ItemStack(); + created.setTenantId(tenantId); + created.setGameInstanceId(gameInstanceId); + created.setRoomInstanceId(roomInstanceId); + created.setItem(item); + created.setStackFamilyKey(source.getStackFamilyKey()); + created.setCompatibilityFingerprint(compatibilityFingerprint); + created.setQuantity(0); + return created; + }); destination.setQuantity(destination.getQuantity() + quantity); itemStackRepository.save(destination); itemTransferAuditWriter.recordStackTransfer( @@ -478,10 +476,9 @@ private ItemStack requireSingleStackSource( } if (stackFamilyKey != null) { return stacks.stream() - .filter( - stack -> - stackFamilyKey.equals( - stackableItemSupport.normalizeStackFamilyKey(stack.getStackFamilyKey()))) + .filter(stack -> + stackFamilyKey.equals( + stackableItemSupport.normalizeStackFamilyKey(stack.getStackFamilyKey()))) .findFirst() .orElseThrow(() -> new IllegalArgumentException(notFoundMessage)); } diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RoomEntityServiceImpl.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RoomEntityServiceImpl.java index 715997a41d..6ad123e092 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RoomEntityServiceImpl.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RoomEntityServiceImpl.java @@ -52,18 +52,17 @@ public List listEntities(long tenantId, String gameInstanceId, St room == null ? List.of() : room.getEntities().stream() - .map( - entity -> - new RoomEntityDto( - entity.getEntityId(), - entity.getDisplayName(), - entity.getEntityType(), - entity.getRole(), - entity.getStateFlags(), - entity.getVisionPriority(), - entity.getReloadHint(), - entity.isVisible(), - null)) + .map(entity -> + new RoomEntityDto( + entity.getEntityId(), + entity.getDisplayName(), + entity.getEntityType(), + entity.getRole(), + entity.getStateFlags(), + entity.getVisionPriority(), + entity.getReloadHint(), + entity.isVisible(), + null)) .toList(); Page roomGroundPage = itemInstanceRepository diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java index 44ee512dee..dc08613464 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java @@ -111,55 +111,51 @@ public EntityEmptySelectedSourceIntakeReceipt readPublicationScope( requireNoAmbientOwnerSql("Entity publication receipt read"); requirePublicationScopeKey(targetNamespace, canonicalTenantId, gameDesignVersionRowId); - return dsl.transactionResult( - configuration -> { - DSLContext tx = DSL.using(configuration); - tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - var associations = - tx.fetch( - "SELECT canonical_version_id, intake_request_id FROM " - + ASSOCIATION - + " WHERE target_namespace = ? AND canonical_tenant_id = ? " - + "ORDER BY canonical_version_id", - targetNamespace, - canonicalTenantId); - if (associations.isEmpty()) { - throw new IllegalStateException( - "Entity selected-empty publication receipt is unavailable"); - } + return dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + var associations = + tx.fetch( + "SELECT canonical_version_id, intake_request_id FROM " + + ASSOCIATION + + " WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "ORDER BY canonical_version_id", + targetNamespace, + canonicalTenantId); + if (associations.isEmpty()) { + throw new IllegalStateException("Entity selected-empty publication receipt is unavailable"); + } - var matches = new ArrayList(); - for (Record association : associations) { - UUID associatedCanonicalVersionId = association.get(0, UUID.class); - UUID intakeRequestId = association.get(1, UUID.class); - if (associatedCanonicalVersionId == null || intakeRequestId == null) { - throw new CorruptReceiptException( - "Entity publication association identity is corrupt"); - } - EntityEmptySelectedSourceIntakeReceipt receipt = - readValidated(tx, targetNamespace, intakeRequestId) - .orElseThrow( - () -> - new CorruptReceiptException( - "Entity publication association has no committed receipt")); - var target = receipt.authorizationBinding().selected().target(); - if (!canonicalTenantId.equals(receipt.canonicalTenantId()) - || !associatedCanonicalVersionId.equals(receipt.canonicalVersionId()) - || !canonicalTenantId.equals(target.canonicalTenantId()) - || !associatedCanonicalVersionId.equals(target.canonicalVersionId())) { - throw new CorruptReceiptException( - "Entity publication association differs from the retained selected target"); - } - if (target.gameDesignVersionRowId() == gameDesignVersionRowId) { - matches.add(receipt); - } - } - if (matches.size() != 1) { - throw new IllegalStateException( - "Entity selected-empty publication scope is missing or ambiguous"); - } - return matches.get(0); - }); + var matches = new ArrayList(); + for (Record association : associations) { + UUID associatedCanonicalVersionId = association.get(0, UUID.class); + UUID intakeRequestId = association.get(1, UUID.class); + if (associatedCanonicalVersionId == null || intakeRequestId == null) { + throw new CorruptReceiptException("Entity publication association identity is corrupt"); + } + EntityEmptySelectedSourceIntakeReceipt receipt = + readValidated(tx, targetNamespace, intakeRequestId) + .orElseThrow(() -> + new CorruptReceiptException( + "Entity publication association has no committed receipt")); + var target = receipt.authorizationBinding().selected().target(); + if (!canonicalTenantId.equals(receipt.canonicalTenantId()) + || !associatedCanonicalVersionId.equals(receipt.canonicalVersionId()) + || !canonicalTenantId.equals(target.canonicalTenantId()) + || !associatedCanonicalVersionId.equals(target.canonicalVersionId())) { + throw new CorruptReceiptException( + "Entity publication association differs from the retained selected target"); + } + if (target.gameDesignVersionRowId() == gameDesignVersionRowId) { + matches.add(receipt); + } + } + if (matches.size() != 1) { + throw new IllegalStateException( + "Entity selected-empty publication scope is missing or ambiguous"); + } + return matches.get(0); + }); } /** @@ -184,55 +180,53 @@ public EntityEmptySelectedSourceIntakeReceipt retainFresh( UUID genesisId = UUID.randomUUID(); EntityEmptySelectedSourceIntakeReceipt committed = - dsl.transactionResult( - configuration -> { - DSLContext tx = DSL.using(configuration); - tx.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); - lockOwnerRecords(tx); - lockSourceAndInboundTables(tx); - - Optional previous = - readValidated(tx, binding.targetNamespace(), binding.intakeRequestId()); - if (previous.isPresent()) { - EntityEmptySelectedSourceIntakeReceipt receipt = previous.orElseThrow(); - receipt.requireSameInputs(inputs); - return receipt; - } - requireNoPriorScopeOrOperation(tx, binding); - - long maximumOccupiedKey = maximumOccupiedSourceKey(tx); - long localTenantKey = Math.addExact(maximumOccupiedKey, 1L); - long localVersionKey = Math.addExact(maximumOccupiedKey, 2L); - List familyStates = - censusEveryDeclaredFamily(tx, inputs, localTenantKey, localVersionKey); - - reserveCanonicalKey(tx, "TENANT", localTenantKey); - reserveCanonicalKey(tx, "VERSION", localVersionKey); - OffsetDateTime retainedAt = - requiredScalar(tx, "SELECT CURRENT_TIMESTAMP", OffsetDateTime.class) - .withOffsetSameInstant(ZoneOffset.UTC); - EntityEmptySelectedSourceIntakeReceipt receipt = - EntityEmptySelectedSourceIntakeReceipt.create( - inputs, - genesisId, - localTenantKey, - localVersionKey, - requestDigest, - familyStates, - retainedAt); - insertAssociation(tx, receipt); - insertEmptyOnlyProviderStates(tx, receipt); - insertFamilyStates(tx, receipt); - insertReceipt(tx, receipt); - return receipt; - }); + dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); + lockOwnerRecords(tx); + lockSourceAndInboundTables(tx); + + Optional previous = + readValidated(tx, binding.targetNamespace(), binding.intakeRequestId()); + if (previous.isPresent()) { + EntityEmptySelectedSourceIntakeReceipt receipt = previous.orElseThrow(); + receipt.requireSameInputs(inputs); + return receipt; + } + requireNoPriorScopeOrOperation(tx, binding); + + long maximumOccupiedKey = maximumOccupiedSourceKey(tx); + long localTenantKey = Math.addExact(maximumOccupiedKey, 1L); + long localVersionKey = Math.addExact(maximumOccupiedKey, 2L); + List familyStates = + censusEveryDeclaredFamily(tx, inputs, localTenantKey, localVersionKey); + + reserveCanonicalKey(tx, "TENANT", localTenantKey); + reserveCanonicalKey(tx, "VERSION", localVersionKey); + OffsetDateTime retainedAt = + requiredScalar(tx, "SELECT CURRENT_TIMESTAMP", OffsetDateTime.class) + .withOffsetSameInstant(ZoneOffset.UTC); + EntityEmptySelectedSourceIntakeReceipt receipt = + EntityEmptySelectedSourceIntakeReceipt.create( + inputs, + genesisId, + localTenantKey, + localVersionKey, + requestDigest, + familyStates, + retainedAt); + insertAssociation(tx, receipt); + insertEmptyOnlyProviderStates(tx, receipt); + insertFamilyStates(tx, receipt); + insertReceipt(tx, receipt); + return receipt; + }); EntityEmptySelectedSourceIntakeReceipt readBack = read(committed.targetNamespace(), committed.intakeRequestId()) - .orElseThrow( - () -> - new CorruptReceiptException( - "Committed Entity source catalogue receipt is unavailable")); + .orElseThrow(() -> + new CorruptReceiptException( + "Committed Entity source catalogue receipt is unavailable")); if (!Arrays.equals(committed.canonicalBytes(), readBack.canonicalBytes()) || !committed.receiptDigest().equals(readBack.receiptDigest()) || !committed.requestDigest().equals(readBack.requestDigest()) diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java index e4d1e9e78e..17b55f2fb9 100644 --- a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java @@ -103,14 +103,13 @@ static String contentDigest( private static void requireEmptyReceipt(EntityEmptySelectedSourceIntakeReceipt receipt) { if (receipt.familyStates().size() != 23 || receipt.familyStates().stream() - .anyMatch( - state -> - state.state() != EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY - || state.rowCount() != 0L - || state.unqualifiedRowCount() != 0L - || state.retainedRowCount() != 0L - || state.selectedScopeRowCount() != 0L - || state.referenceCount() != 0L)) { + .anyMatch(state -> + state.state() != EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY + || state.rowCount() != 0L + || state.unqualifiedRowCount() != 0L + || state.retainedRowCount() != 0L + || state.selectedScopeRowCount() != 0L + || state.referenceCount() != 0L)) { throw new IllegalStateException("Entity selected-empty receipt is incomplete or nonempty"); } } diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java index 55f382a27d..3f28e1e806 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/CanonicalGameplayRosterIntegrationTest.java @@ -172,10 +172,9 @@ void originalSelectionBindsAtomicallyAndReplaysItsExactHistoricalSnapshot() { 1L, java.util.UUID.fromString("12121212-1212-4212-8212-121212121212"), null); - assertThatThrownBy( - () -> - characterRepository.captureAndBindCanonicalGameplayRosterSnapshot( - request, evidence, changedSource, localAdmission)) + assertThatThrownBy(() -> + characterRepository.captureAndBindCanonicalGameplayRosterSnapshot( + request, evidence, changedSource, localAdmission)) .isInstanceOf(IllegalArgumentException.class); } @@ -213,19 +212,17 @@ void originalSelectionReferenceAndNewSnapshotRollBackTogether() { Long snapshotsBefore = jdbcTemplate.queryForObject( "SELECT count(*) FROM entity_canonical_gameplay_roster_snapshots", Long.class); - assertThatThrownBy( - () -> - new TransactionTemplate(transactionManager) - .executeWithoutResult( - ignored -> { - characterRepository.captureAndBindCanonicalGameplayRosterSnapshot( - request, - new CanonicalGameplayRosterOwnerEvidence( - operation, accountUuid, target, Instant.now()), - source, - localAdmission); - throw new IllegalStateException("controlled original bind rollback"); - })) + assertThatThrownBy(() -> + new TransactionTemplate(transactionManager) + .executeWithoutResult(ignored -> { + characterRepository.captureAndBindCanonicalGameplayRosterSnapshot( + request, + new CanonicalGameplayRosterOwnerEvidence( + operation, accountUuid, target, Instant.now()), + source, + localAdmission); + throw new IllegalStateException("controlled original bind rollback"); + })) .hasMessage("controlled original bind rollback"); assertThat( jdbcTemplate.queryForObject( @@ -299,21 +296,20 @@ void exactOwnerRetirementHoldsEpochDisposalRollbackAndDelayedDuplicateRemainCoup 8); UUID recovery = UUID.randomUUID(); UUID hold = UUID.randomUUID(); - transactions.executeWithoutResult( - ignored -> { - repository.acquire( - binding, - UUID.randomUUID(), - recovery, - net.firedevops.firemud.entitymanagement.repository - .CanonicalGameplayRosterRetentionRepository.ReferenceKind.RECOVERY); - repository.acquire( - binding, - UUID.randomUUID(), - hold, - net.firedevops.firemud.entitymanagement.repository - .CanonicalGameplayRosterRetentionRepository.ReferenceKind.HOLD); - }); + transactions.executeWithoutResult(ignored -> { + repository.acquire( + binding, + UUID.randomUUID(), + recovery, + net.firedevops.firemud.entitymanagement.repository + .CanonicalGameplayRosterRetentionRepository.ReferenceKind.RECOVERY); + repository.acquire( + binding, + UUID.randomUUID(), + hold, + net.firedevops.firemud.entitymanagement.repository + .CanonicalGameplayRosterRetentionRepository.ReferenceKind.HOLD); + }); var proof = net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence.sealRetirement( net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence.response( @@ -347,13 +343,12 @@ void exactOwnerRetirementHoldsEpochDisposalRollbackAndDelayedDuplicateRemainCoup // Preparation advances the local epoch; final-disposal checks use the reloaded candidate. var retired = retentionCandidate(snapshot, ownerRequest); assertThat(transactions.execute(ignored -> repository.dispose(retired))).isFalse(); - transactions.executeWithoutResult( - ignored -> { - assertThat(repository.protection(binding).liveReferences()).isEqualTo(1L); - assertThat(repository.protection(binding).holds()).isEqualTo(1L); - repository.release(binding, UUID.randomUUID(), recovery); - repository.release(binding, UUID.randomUUID(), hold); - }); + transactions.executeWithoutResult(ignored -> { + assertThat(repository.protection(binding).liveReferences()).isEqualTo(1L); + assertThat(repository.protection(binding).holds()).isEqualTo(1L); + repository.release(binding, UUID.randomUUID(), recovery); + repository.release(binding, UUID.randomUUID(), hold); + }); assertThat(transactions.execute(ignored -> repository.dispose(retired))).isFalse(); Thread.sleep(5L); var ready = retentionCandidate(snapshot, ownerRequest); @@ -364,13 +359,11 @@ void exactOwnerRetirementHoldsEpochDisposalRollbackAndDelayedDuplicateRemainCoup var assignmentsBefore = jdbcTemplate.queryForList( "SELECT to_jsonb(a)::text AS bytes, xmin::text AS xmin FROM entity_preseeded_actor_assignment_operations a ORDER BY assignment_uuid"); - assertThatThrownBy( - () -> - transactions.executeWithoutResult( - ignored -> { - assertThat(repository.dispose(ready)).isTrue(); - throw new IllegalStateException("controlled disposal rollback"); - })) + assertThatThrownBy(() -> + transactions.executeWithoutResult(ignored -> { + assertThat(repository.dispose(ready)).isTrue(); + throw new IllegalStateException("controlled disposal rollback"); + })) .hasMessage("controlled disposal rollback"); assertThat( jdbcTemplate.queryForObject( @@ -394,10 +387,9 @@ void exactOwnerRetirementHoldsEpochDisposalRollbackAndDelayedDuplicateRemainCoup jdbcTemplate.queryForList( "SELECT to_jsonb(a)::text AS bytes, xmin::text AS xmin FROM entity_preseeded_actor_assignment_operations a ORDER BY assignment_uuid")) .isEqualTo(assignmentsBefore); - assertThatThrownBy( - () -> - characterRepository.captureAndBindCanonicalGameplayRosterSnapshot( - request, evidence, reserved, admission)) + assertThatThrownBy(() -> + characterRepository.captureAndBindCanonicalGameplayRosterSnapshot( + request, evidence, reserved, admission)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("LOCAL_ADMISSION_FENCE_CLOSED"); Thread.sleep(5L); @@ -427,16 +419,14 @@ void exactOwnerRetirementHoldsEpochDisposalRollbackAndDelayedDuplicateRemainCoup Long.class, accountUuid)) .isZero(); - assertThatThrownBy( - () -> - characterRepository.captureAndBindCanonicalGameplayRosterSnapshot( - request, evidence, reserved, admission)) + assertThatThrownBy(() -> + characterRepository.captureAndBindCanonicalGameplayRosterSnapshot( + request, evidence, reserved, admission)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("LOCAL_ADMISSION_FENCE_CLOSED"); - assertThatThrownBy( - () -> - net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence - .requireDereference(proof)) + assertThatThrownBy(() -> + net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence + .requireDereference(proof)) .isInstanceOf(IllegalStateException.class); } @@ -534,14 +524,13 @@ void independentlyRetiresSameTargetSiblingSnapshotsAndRejectsLateCapture() throw second.snapshot().snapshotUuid(), second.snapshot().snapshotDigest()), exactTarget); UUID secondHold = UUID.randomUUID(); - transactions.executeWithoutResult( - ignored -> - repository.acquire( - secondBinding, - UUID.randomUUID(), - secondHold, - net.firedevops.firemud.entitymanagement.repository - .CanonicalGameplayRosterRetentionRepository.ReferenceKind.HOLD)); + transactions.executeWithoutResult(ignored -> + repository.acquire( + secondBinding, + UUID.randomUUID(), + secondHold, + net.firedevops.firemud.entitymanagement.repository + .CanonicalGameplayRosterRetentionRepository.ReferenceKind.HOLD)); var firstProof = retirementProof(first, targetFence, retirementId); var secondProof = retirementProof(second, targetFence, retirementId); @@ -552,53 +541,47 @@ void independentlyRetiresSameTargetSiblingSnapshotsAndRejectsLateCapture() throw AtomicInteger secondSealPid = new AtomicInteger(); try (ExecutorService executor = Executors.newFixedThreadPool(2)) { Future firstSeal = - executor.submit( - () -> - transactions.execute( - ignored -> { - firstSealPid.set( - java.util.Objects.requireNonNull( - jdbcTemplate.queryForObject( - "SELECT pg_backend_pid()", Integer.class))); - assertThat( - repository.observeRetirement( - retentionCandidate(first.snapshot(), first.ownerRequest()), - firstProof, - policy)) - .isTrue(); - assertThat( - jdbcTemplate.queryForObject( - "SELECT retirement_observed_at + minimum_retention_millis * interval '1 millisecond' > clock_timestamp() " - + "FROM entity_canonical_roster_retention_lifecycle WHERE snapshot_uuid = ?", - Boolean.class, - first.snapshot().snapshotUuid())) - .as("the stored sibling seal horizon has not elapsed") - .isTrue(); - assertThat( - repository.dispose( - retentionCandidate(first.snapshot(), first.ownerRequest()))) - .as("a current epoch cannot bypass the persisted seal horizon") - .isFalse(); - firstSealed.countDown(); - awaitSiblingLatch(allowFirstCommit, "first sibling seal commit"); - return true; - })); + executor.submit(() -> + transactions.execute(ignored -> { + firstSealPid.set( + java.util.Objects.requireNonNull( + jdbcTemplate.queryForObject("SELECT pg_backend_pid()", Integer.class))); + assertThat( + repository.observeRetirement( + retentionCandidate(first.snapshot(), first.ownerRequest()), + firstProof, + policy)) + .isTrue(); + assertThat( + jdbcTemplate.queryForObject( + "SELECT retirement_observed_at + minimum_retention_millis * interval '1 millisecond' > clock_timestamp() " + + "FROM entity_canonical_roster_retention_lifecycle WHERE snapshot_uuid = ?", + Boolean.class, + first.snapshot().snapshotUuid())) + .as("the stored sibling seal horizon has not elapsed") + .isTrue(); + assertThat( + repository.dispose( + retentionCandidate(first.snapshot(), first.ownerRequest()))) + .as("a current epoch cannot bypass the persisted seal horizon") + .isFalse(); + firstSealed.countDown(); + awaitSiblingLatch(allowFirstCommit, "first sibling seal commit"); + return true; + })); assertThat(firstSealed.await(10, TimeUnit.SECONDS)).isTrue(); Future secondSeal = - executor.submit( - () -> - transactions.execute( - ignored -> { - secondSealPid.set( - java.util.Objects.requireNonNull( - jdbcTemplate.queryForObject( - "SELECT pg_backend_pid()", Integer.class))); - secondStarted.countDown(); - return repository.observeRetirement( - retentionCandidate(second.snapshot(), second.ownerRequest()), - secondProof, - policy); - })); + executor.submit(() -> + transactions.execute(ignored -> { + secondSealPid.set( + java.util.Objects.requireNonNull( + jdbcTemplate.queryForObject("SELECT pg_backend_pid()", Integer.class))); + secondStarted.countDown(); + return repository.observeRetirement( + retentionCandidate(second.snapshot(), second.ownerRequest()), + secondProof, + policy); + })); assertThat(secondStarted.await(10, TimeUnit.SECONDS)).isTrue(); awaitBackendBlockedBy(secondSealPid.get(), firstSealPid.get()); allowFirstCommit.countDown(); @@ -611,73 +594,60 @@ void independentlyRetiresSameTargetSiblingSnapshotsAndRejectsLateCapture() throw } assertThat( - transactions.execute( - ignored -> - repository.observeRetirement( - retentionCandidate(first.snapshot(), first.ownerRequest()), - firstProof, - policy))) + transactions.execute(ignored -> + repository.observeRetirement( + retentionCandidate(first.snapshot(), first.ownerRequest()), + firstProof, + policy))) .as("exact replay preserves the first snapshot's persisted seal") .isTrue(); assertThat( - transactions.execute( - ignored -> - repository.observeRetirement( - retentionCandidate(second.snapshot(), second.ownerRequest()), - secondProof, - policy))) + transactions.execute(ignored -> + repository.observeRetirement( + retentionCandidate(second.snapshot(), second.ownerRequest()), + secondProof, + policy))) .as("exact replay preserves the sibling snapshot's independent seal") .isTrue(); assertThat( - transactions.execute( - ignored -> - repository.observeRetirement( - retentionCandidate(first.snapshot(), first.ownerRequest()), - retirementProof(first, targetFence, UUID.randomUUID()), - policy))) + transactions.execute(ignored -> + repository.observeRetirement( + retentionCandidate(first.snapshot(), first.ownerRequest()), + retirementProof(first, targetFence, UUID.randomUUID()), + policy))) .as("a changed retirement proof cannot replace an existing snapshot seal") .isFalse(); jdbcTemplate.update( "UPDATE characters SET name = ? WHERE character_uuid = ?", "Changed After Seal", actor); CanonicalGameplayRosterReadRequest changedDirectRequest = originalRosterRequest(exactTarget); - assertThatThrownBy( - () -> - characterRepository.captureCanonicalGameplayRosterSnapshot( - changedDirectRequest, - new CanonicalGameplayRosterOwnerEvidence( - changedDirectRequest.requestUuid(), - accountUuid, - exactTarget, - Instant.now()))) + assertThatThrownBy(() -> + characterRepository.captureCanonicalGameplayRosterSnapshot( + changedDirectRequest, + new CanonicalGameplayRosterOwnerEvidence( + changedDirectRequest.requestUuid(), accountUuid, exactTarget, Instant.now()))) .as("direct capture cannot create or reuse an alternate snapshot after the target seal") .isInstanceOf(IllegalStateException.class) .hasMessageContaining("LOCAL_ADMISSION_FENCE_CLOSED"); - assertThatThrownBy( - () -> - transactions.executeWithoutResult( - ignored -> - repository.acquire( - secondBinding, - UUID.randomUUID(), - UUID.randomUUID(), - net.firedevops.firemud.entitymanagement.repository - .CanonicalGameplayRosterRetentionRepository.ReferenceKind - .RECOVERY))) + assertThatThrownBy(() -> + transactions.executeWithoutResult(ignored -> + repository.acquire( + secondBinding, + UUID.randomUUID(), + UUID.randomUUID(), + net.firedevops.firemud.entitymanagement.repository + .CanonicalGameplayRosterRetentionRepository.ReferenceKind.RECOVERY))) .as("recovery acquisition is covered by the same target fence") .isInstanceOf(IllegalStateException.class) .hasMessageContaining("LOCAL_ADMISSION_FENCE_CLOSED"); - assertThatThrownBy( - () -> - characterRepository.captureAndBindCanonicalGameplayRosterSnapshot( - delayedRequest, delayedEvidence, delayedOwnerResponse, delayedAdmission)) + assertThatThrownBy(() -> + characterRepository.captureAndBindCanonicalGameplayRosterSnapshot( + delayedRequest, delayedEvidence, delayedOwnerResponse, delayedAdmission)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("LOCAL_ADMISSION_FENCE_CLOSED"); - assertThatThrownBy( - () -> - characterRepository.reserveOriginalRosterAdmission( - originalRosterRequest(exactTarget))) + assertThatThrownBy(() -> + characterRepository.reserveOriginalRosterAdmission(originalRosterRequest(exactTarget))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("LOCAL_ADMISSION_FENCE_CLOSED"); @@ -713,10 +683,8 @@ void independentlyRetiresSameTargetSiblingSnapshotsAndRejectsLateCapture() throw String.class, first.localRequest().requestUuid())) .isEqualTo("PENDING_ACK"); - assertThatThrownBy( - () -> - characterRepository.reserveOriginalRosterAdmission( - originalRosterRequest(exactTarget))) + assertThatThrownBy(() -> + characterRepository.reserveOriginalRosterAdmission(originalRosterRequest(exactTarget))) .as("disposing one sibling leaves the shared target fence closed") .isInstanceOf(IllegalStateException.class) .hasMessageContaining("LOCAL_ADMISSION_FENCE_CLOSED"); @@ -885,13 +853,12 @@ void reusesExactSnapshotAndChangesIdentityForRosterOrTargetChanges() { characterRepository.readCurrentCanonicalGameplayRosterSnapshot( accountUuid, exactTarget, expectedReference)) .isEqualTo(first); - assertThatThrownBy( - () -> - characterRepository.readCurrentCanonicalGameplayRosterSnapshot( - accountUuid, - exactTarget, - new CanonicalGameplayRosterSnapshotReference( - UUID.randomUUID(), first.snapshotDigest()))) + assertThatThrownBy(() -> + characterRepository.readCurrentCanonicalGameplayRosterSnapshot( + accountUuid, + exactTarget, + new CanonicalGameplayRosterSnapshotReference( + UUID.randomUUID(), first.snapshotDigest()))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_GAMEPLAY_ROSTER_SNAPSHOT_READBACK_UNAVAILABLE"); assertThat( @@ -922,29 +889,26 @@ void reusesExactSnapshotAndChangesIdentityForRosterOrTargetChanges() { Long.class, first.snapshotUuid())) .isEqualTo(exactTarget.activeWorldEpoch()); - assertThatThrownBy( - () -> - jdbcTemplate.update( - "UPDATE entity_canonical_gameplay_roster_snapshots " - + "SET canonical_version_uuid = ? WHERE snapshot_uuid = ?", - UUID.randomUUID(), - first.snapshotUuid())) + assertThatThrownBy(() -> + jdbcTemplate.update( + "UPDATE entity_canonical_gameplay_roster_snapshots " + + "SET canonical_version_uuid = ? WHERE snapshot_uuid = ?", + UUID.randomUUID(), + first.snapshotUuid())) .isInstanceOf(RuntimeException.class); - assertThatThrownBy( - () -> - jdbcTemplate.update( - "UPDATE entity_canonical_gameplay_roster_snapshots " - + "SET pointer_version = ? WHERE snapshot_uuid = ?", - exactTarget.pointerVersion() + 1, - first.snapshotUuid())) + assertThatThrownBy(() -> + jdbcTemplate.update( + "UPDATE entity_canonical_gameplay_roster_snapshots " + + "SET pointer_version = ? WHERE snapshot_uuid = ?", + exactTarget.pointerVersion() + 1, + first.snapshotUuid())) .isInstanceOf(RuntimeException.class); - assertThatThrownBy( - () -> - jdbcTemplate.update( - "UPDATE entity_canonical_gameplay_roster_snapshots " - + "SET active_world_epoch = ? WHERE snapshot_uuid = ?", - exactTarget.activeWorldEpoch() + 1, - first.snapshotUuid())) + assertThatThrownBy(() -> + jdbcTemplate.update( + "UPDATE entity_canonical_gameplay_roster_snapshots " + + "SET active_world_epoch = ? WHERE snapshot_uuid = ?", + exactTarget.activeWorldEpoch() + 1, + first.snapshotUuid())) .isInstanceOf(RuntimeException.class); jdbcTemplate.update( @@ -954,10 +918,9 @@ void reusesExactSnapshotAndChangesIdentityForRosterOrTargetChanges() { assertThat(changedRoster.snapshotDigest()).isNotEqualTo(first.snapshotDigest()); assertThat(changedRoster.actors()) .containsExactly(new CanonicalGameplayRosterActor(actor, "After Rename")); - assertThatThrownBy( - () -> - characterRepository.readCurrentCanonicalGameplayRosterSnapshot( - accountUuid, exactTarget, expectedReference)) + assertThatThrownBy(() -> + characterRepository.readCurrentCanonicalGameplayRosterSnapshot( + accountUuid, exactTarget, expectedReference)) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_GAMEPLAY_ROSTER_SNAPSHOT_STALE"); @@ -983,21 +946,19 @@ void reusesExactSnapshotAndChangesIdentityForRosterOrTargetChanges() { assertThat(changedEpochSnapshot.target().activeWorldEpoch()) .isEqualTo(changedEpoch.activeWorldEpoch()); - assertThatThrownBy( - () -> - jdbcTemplate.update( - "UPDATE entity_canonical_gameplay_roster_snapshots " - + "SET world_slug = 'changed' WHERE snapshot_uuid = ?", - first.snapshotUuid())) + assertThatThrownBy(() -> + jdbcTemplate.update( + "UPDATE entity_canonical_gameplay_roster_snapshots " + + "SET world_slug = 'changed' WHERE snapshot_uuid = ?", + first.snapshotUuid())) .isInstanceOf(RuntimeException.class); - assertThatThrownBy( - () -> - jdbcTemplate.update( - "UPDATE entity_canonical_gameplay_roster_snapshot_actors " - + "SET display_name = 'tampered' " - + "WHERE snapshot_uuid = ? AND character_uuid = ?", - first.snapshotUuid(), - actor)) + assertThatThrownBy(() -> + jdbcTemplate.update( + "UPDATE entity_canonical_gameplay_roster_snapshot_actors " + + "SET display_name = 'tampered' " + + "WHERE snapshot_uuid = ? AND character_uuid = ?", + first.snapshotUuid(), + actor)) .isInstanceOf(RuntimeException.class); } @@ -1013,20 +974,19 @@ void concurrentDifferentOriginalOperationsBindTheSameExistingSealedSnapshotWitho UUID targetFence = UUID.randomUUID(); var sources = requests.stream() - .map( - request -> - net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence - .response( - net.firedevops.firemud.common.world - .CanonicalGameplayRosterReferenceEvidence.request( + .map(request -> + net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence + .response( + net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence + .request( request.requestUuid(), request.canonicalAccountUuid(), request.playerExecutionContext().sessionUuid(), "gameplay", target.toWire()), - 1L, - targetFence, - null)) + 1L, + targetFence, + null)) .toList(); var retention = new net.firedevops.firemud.entitymanagement.repository @@ -1039,63 +999,54 @@ void concurrentDifferentOriginalOperationsBindTheSameExistingSealedSnapshotWitho ExecutorService executor = Executors.newFixedThreadPool(2); try { Future first = - executor.submit( - () -> - new TransactionTemplate(transactionManager) - .execute( - ignored -> { - firstPid.set( - java.util.Objects.requireNonNull( - jdbcTemplate.queryForObject( - "SELECT pg_backend_pid()", Integer.class))); - var request = requests.getFirst(); - retention.requireAdmission(request, admissions.getFirst()); - assertThat(retention.originalReceipt(sources.getFirst())).isEmpty(); - // Pause the actual capture/bind sequence after capture, while all its - // locks remain held. - var snapshot = - characterRepository.captureCanonicalGameplayRosterSnapshot( - request, - new CanonicalGameplayRosterOwnerEvidence( - request.requestUuid(), accountUuid, target, Instant.now())); - firstCaptured.countDown(); - try { - if (!releaseFirst.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException( - "First existing snapshot capture was not released"); - } - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(interrupted); - } - retention.bindOriginal(sources.getFirst(), snapshot); - retention.bindAdmission( - request.requestUuid(), - admissions.getFirst(), - snapshot.snapshotUuid()); - return snapshot; - })); + executor.submit(() -> + new TransactionTemplate(transactionManager) + .execute(ignored -> { + firstPid.set( + java.util.Objects.requireNonNull( + jdbcTemplate.queryForObject("SELECT pg_backend_pid()", Integer.class))); + var request = requests.getFirst(); + retention.requireAdmission(request, admissions.getFirst()); + assertThat(retention.originalReceipt(sources.getFirst())).isEmpty(); + // Pause the actual capture/bind sequence after capture, while all its + // locks remain held. + var snapshot = + characterRepository.captureCanonicalGameplayRosterSnapshot( + request, + new CanonicalGameplayRosterOwnerEvidence( + request.requestUuid(), accountUuid, target, Instant.now())); + firstCaptured.countDown(); + try { + if (!releaseFirst.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException( + "First existing snapshot capture was not released"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + retention.bindOriginal(sources.getFirst(), snapshot); + retention.bindAdmission( + request.requestUuid(), admissions.getFirst(), snapshot.snapshotUuid()); + return snapshot; + })); assertThat(firstCaptured.await(10, TimeUnit.SECONDS)).isTrue(); Future second = - executor.submit( - () -> - new TransactionTemplate(transactionManager) - .execute( - ignored -> { - secondPid.set( - java.util.Objects.requireNonNull( - jdbcTemplate.queryForObject( - "SELECT pg_backend_pid()", Integer.class))); - secondStarted.countDown(); - var request = requests.get(1); - return characterRepository - .captureAndBindCanonicalGameplayRosterSnapshot( - request, - new CanonicalGameplayRosterOwnerEvidence( - request.requestUuid(), accountUuid, target, Instant.now()), - sources.get(1), - admissions.get(1)); - })); + executor.submit(() -> + new TransactionTemplate(transactionManager) + .execute(ignored -> { + secondPid.set( + java.util.Objects.requireNonNull( + jdbcTemplate.queryForObject("SELECT pg_backend_pid()", Integer.class))); + secondStarted.countDown(); + var request = requests.get(1); + return characterRepository.captureAndBindCanonicalGameplayRosterSnapshot( + request, + new CanonicalGameplayRosterOwnerEvidence( + request.requestUuid(), accountUuid, target, Instant.now()), + sources.get(1), + admissions.get(1)); + })); assertThat(secondStarted.await(10, TimeUnit.SECONDS)).isTrue(); awaitBackendBlockedBy(secondPid.get(), firstPid.get()); assertActorWriterBlocked(actor); @@ -1170,32 +1121,29 @@ void currentSnapshotReadersStillShareTheirRowsAndExcludeActorWriters() throws Ex ExecutorService executor = Executors.newFixedThreadPool(2); try { Future first = - executor.submit( - () -> - new TransactionTemplate(transactionManager) - .execute( - ignored -> { - var result = - characterRepository.readCurrentCanonicalGameplayRosterSnapshot( - accountUuid, target, reference); - firstRead.countDown(); - try { - if (!releaseFirst.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException( - "First current snapshot reader was not released"); - } - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(interrupted); - } - return result; - })); + executor.submit(() -> + new TransactionTemplate(transactionManager) + .execute(ignored -> { + var result = + characterRepository.readCurrentCanonicalGameplayRosterSnapshot( + accountUuid, target, reference); + firstRead.countDown(); + try { + if (!releaseFirst.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException( + "First current snapshot reader was not released"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return result; + })); assertThat(firstRead.await(10, TimeUnit.SECONDS)).isTrue(); Future second = - executor.submit( - () -> - characterRepository.readCurrentCanonicalGameplayRosterSnapshot( - accountUuid, target, reference)); + executor.submit(() -> + characterRepository.readCurrentCanonicalGameplayRosterSnapshot( + accountUuid, target, reference)); assertThat(second.get(5, TimeUnit.SECONDS)).isEqualTo(snapshot); assertActorWriterBlocked(actor); releaseFirst.countDown(); @@ -1253,16 +1201,14 @@ private void awaitBackendBlockedBy(int waitingPid, int holderPid) throws Interru } private void assertActorWriterBlocked(UUID actor) { - assertThatThrownBy( - () -> - new TransactionTemplate(transactionManager) - .executeWithoutResult( - ignored -> { - jdbcTemplate.execute("SET LOCAL lock_timeout = '250ms'"); - jdbcTemplate.update( - "UPDATE characters SET name = 'Blocked Actor Rename' WHERE character_uuid = ?", - actor); - })) + assertThatThrownBy(() -> + new TransactionTemplate(transactionManager) + .executeWithoutResult(ignored -> { + jdbcTemplate.execute("SET LOCAL lock_timeout = '250ms'"); + jdbcTemplate.update( + "UPDATE characters SET name = 'Blocked Actor Rename' WHERE character_uuid = ?", + actor); + })) .isInstanceOf(RuntimeException.class) .hasMessageContaining("lock timeout"); } @@ -1275,17 +1221,15 @@ void concurrentIdenticalReadsReuseOnePersistedSnapshotIdentity() throws Exceptio ExecutorService executor = Executors.newFixedThreadPool(2); try { Future first = - executor.submit( - () -> { - start.await(); - return readRoster(accountUuid, exactTarget); - }); + executor.submit(() -> { + start.await(); + return readRoster(accountUuid, exactTarget); + }); Future second = - executor.submit( - () -> { - start.await(); - return readRoster(accountUuid, exactTarget); - }); + executor.submit(() -> { + start.await(); + return readRoster(accountUuid, exactTarget); + }); start.countDown(); CanonicalGameplayRosterSnapshot firstResult = first.get(15, TimeUnit.SECONDS); @@ -1317,25 +1261,22 @@ void differentAccountRosterCaptureCanFinishWhileAnotherReaderHoldsItsTransaction ExecutorService executor = Executors.newFixedThreadPool(2); try { Future first = - executor.submit( - () -> - new TransactionTemplate(transactionManager) - .execute( - ignored -> { - CanonicalGameplayRosterSnapshot snapshot = - readRoster(accountUuid, exactTarget); - firstRead.countDown(); - try { - if (!releaseFirst.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException( - "First roster transaction was not released"); - } - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(interrupted); - } - return snapshot; - })); + executor.submit(() -> + new TransactionTemplate(transactionManager) + .execute(ignored -> { + CanonicalGameplayRosterSnapshot snapshot = readRoster(accountUuid, exactTarget); + firstRead.countDown(); + try { + if (!releaseFirst.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException( + "First roster transaction was not released"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return snapshot; + })); assertThat(firstRead.await(10, TimeUnit.SECONDS)).isTrue(); Future second = diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/OrdinaryAccountUuidOwnerPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/OrdinaryAccountUuidOwnerPostgresIntegrationTest.java index abb4d98886..0a5ea9fade 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/OrdinaryAccountUuidOwnerPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/OrdinaryAccountUuidOwnerPostgresIntegrationTest.java @@ -205,10 +205,9 @@ void upgradePreservesNumericSourcesAndQueriesOnlyExactOrdinaryUuidWithoutPromoti "authored_initial_core_json = '{}'", "creation_descriptor_json = '{}'", "creation_descriptor_digest = 'sha256:" + "a".repeat(64) + "'")) { - assertThatThrownBy( - () -> - jdbc.update( - "UPDATE characters SET " + invalidChange + " WHERE id = ?", saved.getId())) + assertThatThrownBy(() -> + jdbc.update( + "UPDATE characters SET " + invalidChange + " WHERE id = ?", saved.getId())) .as(invalidChange) .isInstanceOf(org.springframework.dao.DataAccessException.class); assertThat( @@ -229,11 +228,10 @@ void upgradePreservesNumericSourcesAndQueriesOnlyExactOrdinaryUuidWithoutPromoti "health", "mana", "body_layout_key")) { - assertThatThrownBy( - () -> - jdbc.update( - "UPDATE characters SET " + requiredColumn + " = NULL WHERE id = ?", - saved.getId())) + assertThatThrownBy(() -> + jdbc.update( + "UPDATE characters SET " + requiredColumn + " = NULL WHERE id = ?", + saved.getId())) .as(requiredColumn) .isInstanceOf(org.springframework.dao.DataAccessException.class); } diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java index 43d047cf1c..adae6d96ce 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java @@ -136,28 +136,24 @@ void createIsolatedOwnerProofIdentities() { @Test void receiptLockRequiresCallerOwnedWritableTransactionThroughRepositoryProxy() { UUID absentActor = UUID.randomUUID(); - assertThatThrownBy( - () -> - characterRepository.lockCurrentPreseededActorAssignmentReceipt( - assignmentUuid, accountUuid, absentActor, "a".repeat(64))) + assertThatThrownBy(() -> + characterRepository.lockCurrentPreseededActorAssignmentReceipt( + assignmentUuid, accountUuid, absentActor, "a".repeat(64))) .isInstanceOf(IllegalTransactionStateException.class); TransactionTemplate writable = new TransactionTemplate(transactionManager); Optional absentReceipt = - writable.execute( - ignored -> - characterRepository.lockCurrentPreseededActorAssignmentReceipt( - assignmentUuid, accountUuid, absentActor, "a".repeat(64))); + writable.execute(ignored -> + characterRepository.lockCurrentPreseededActorAssignmentReceipt( + assignmentUuid, accountUuid, absentActor, "a".repeat(64))); assertThat(absentReceipt).isEmpty(); TransactionTemplate readOnly = new TransactionTemplate(transactionManager); readOnly.setReadOnly(true); - assertThatThrownBy( - () -> - readOnly.execute( - ignored -> - characterRepository.lockCurrentPreseededActorAssignmentReceipt( - assignmentUuid, accountUuid, absentActor, "a".repeat(64)))) + assertThatThrownBy(() -> + readOnly.execute(ignored -> + characterRepository.lockCurrentPreseededActorAssignmentReceipt( + assignmentUuid, accountUuid, absentActor, "a".repeat(64)))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("writable hold transaction"); } @@ -173,38 +169,37 @@ void postgresMigrationInstallsAndEnforcesDeferredAssignmentForeignKeys() { UUID missingCharacterUuid = UUID.randomUUID(); UUID invalidOperationUuid = UUID.randomUUID(); - assertThatThrownBy( - () -> - jdbcTemplate.update( - "INSERT INTO entity_preseeded_actor_assignment_operations (" - + "assignment_uuid, intent_digest, account_uuid, account_uuid_provenance, " - + "account_identity_schema_version, account_identity_target_namespace, " - + "source_account_row_id, eligibility, " - + "eligibility_evaluated_at, membership_authority_generation, " - + "eligibility_evidence_digest, tenant_uuid, realm_uuid, world_slug, " - + "realm_slug, game_instance_id, catalog_revision, canonical_version_uuid, " - + "publication_evidence_format, frozen_policy_digest, " - + "playable_state_namespace_id, playable_state_scope, entry_policy, " - + "actor_kind, display_name, status, character_uuid, completed_at, " - + "account_authority_snapshot_digest, account_purpose, account_currentness, " - + "published_owner_proof_digest, published_release_bundle_ref) " - + "SELECT ?, intent_digest, account_uuid, account_uuid_provenance, " - + "account_identity_schema_version, account_identity_target_namespace, " - + "source_account_row_id, eligibility, " - + "eligibility_evaluated_at, membership_authority_generation, " - + "eligibility_evidence_digest, tenant_uuid, realm_uuid, world_slug, " - + "realm_slug, game_instance_id, catalog_revision, canonical_version_uuid, " - + "publication_evidence_format, frozen_policy_digest, " - + "playable_state_namespace_id, playable_state_scope, entry_policy, " - + "actor_kind, display_name, 'ASSIGNED', ?, CURRENT_TIMESTAMP " - + ", account_authority_snapshot_digest, account_purpose, " - + "account_currentness, published_owner_proof_digest, " - + "published_release_bundle_ref " - + "FROM entity_preseeded_actor_assignment_operations " - + "WHERE assignment_uuid = ?", - invalidOperationUuid, - missingCharacterUuid, - assignmentUuid)) + assertThatThrownBy(() -> + jdbcTemplate.update( + "INSERT INTO entity_preseeded_actor_assignment_operations (" + + "assignment_uuid, intent_digest, account_uuid, account_uuid_provenance, " + + "account_identity_schema_version, account_identity_target_namespace, " + + "source_account_row_id, eligibility, " + + "eligibility_evaluated_at, membership_authority_generation, " + + "eligibility_evidence_digest, tenant_uuid, realm_uuid, world_slug, " + + "realm_slug, game_instance_id, catalog_revision, canonical_version_uuid, " + + "publication_evidence_format, frozen_policy_digest, " + + "playable_state_namespace_id, playable_state_scope, entry_policy, " + + "actor_kind, display_name, status, character_uuid, completed_at, " + + "account_authority_snapshot_digest, account_purpose, account_currentness, " + + "published_owner_proof_digest, published_release_bundle_ref) " + + "SELECT ?, intent_digest, account_uuid, account_uuid_provenance, " + + "account_identity_schema_version, account_identity_target_namespace, " + + "source_account_row_id, eligibility, " + + "eligibility_evaluated_at, membership_authority_generation, " + + "eligibility_evidence_digest, tenant_uuid, realm_uuid, world_slug, " + + "realm_slug, game_instance_id, catalog_revision, canonical_version_uuid, " + + "publication_evidence_format, frozen_policy_digest, " + + "playable_state_namespace_id, playable_state_scope, entry_policy, " + + "actor_kind, display_name, 'ASSIGNED', ?, CURRENT_TIMESTAMP " + + ", account_authority_snapshot_digest, account_purpose, " + + "account_currentness, published_owner_proof_digest, " + + "published_release_bundle_ref " + + "FROM entity_preseeded_actor_assignment_operations " + + "WHERE assignment_uuid = ?", + invalidOperationUuid, + missingCharacterUuid, + assignmentUuid)) .isInstanceOf(DataAccessException.class); assertThat( @@ -419,10 +414,9 @@ void migrationRetainsOlderRosterEvidenceWithoutBackfillingOwnerCounters() throws validTarget.realmUuid(), newOperation, validTarget.playableStateScope())); - assertThatThrownBy( - () -> - retentionTransaction.execute( - ignored -> retentionRepository.reserveAdmission(otherwiseValidRequest))) + assertThatThrownBy(() -> + retentionTransaction.execute( + ignored -> retentionRepository.reserveAdmission(otherwiseValidRequest))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); assertThat( @@ -767,13 +761,12 @@ void committedReceiptIsExactReplayStableAndDeniedForChangedOrQuarantinedActor() String.class, assignmentUuid)) .isEqualTo("CANONICAL_UUID"); - assertThatThrownBy( - () -> - jdbcTemplate.update( - "UPDATE entity_preseeded_actor_assignment_operations " - + "SET canonical_version_uuid = ? WHERE assignment_uuid = ?", - UUID.randomUUID(), - assignmentUuid)) + assertThatThrownBy(() -> + jdbcTemplate.update( + "UPDATE entity_preseeded_actor_assignment_operations " + + "SET canonical_version_uuid = ? WHERE assignment_uuid = ?", + UUID.randomUUID(), + assignmentUuid)) .isInstanceOf(DataAccessException.class); assertThat( @@ -887,34 +880,31 @@ void reservedAuthoredTenantKeyDoesNotBlockOwnerResolvedCharacterAssignment() thr PreseededActorAssignmentRequest request = assignmentRequest(owner, "Reserved-Key Actor"); PreseededActorAssignmentResult assigned = - isolatedDsl.transactionResult( - configuration -> - new CharacterRepository(DSL.using(configuration)) - .assignPreseededActor( - request, - owner, - accountIdentity(assignmentUuid, accountUuid), - request.mutationIntentDigest())); + isolatedDsl.transactionResult(configuration -> + new CharacterRepository(DSL.using(configuration)) + .assignPreseededActor( + request, + owner, + accountIdentity(assignmentUuid, accountUuid), + request.mutationIntentDigest())); assertThat(assigned.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); assertThat(assigned.characterUuid()).isNotNull(); - assertThatThrownBy( - () -> - isolatedDsl.execute( - "INSERT INTO characters (account_id, name, tenant_id) " - + "VALUES (23, 'Legacy Reserved-Key Actor', ?)", - sourceReceipt.localTenantKey())) + assertThatThrownBy(() -> + isolatedDsl.execute( + "INSERT INTO characters (account_id, name, tenant_id) " + + "VALUES (23, 'Legacy Reserved-Key Actor', ?)", + sourceReceipt.localTenantKey())) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("reserved by an immutable empty-source receipt"); - assertThatThrownBy( - () -> - isolatedDsl.execute( - "UPDATE characters SET account_uuid = NULL, tenant_uuid = NULL, " - + "playable_state_namespace_id = NULL, playable_state_scope = NULL, " - + "actor_identity_status = 'QUARANTINED', " - + "actor_identity_quarantine_reason = 'OWNER_PROVENANCE_MISSING' " - + "WHERE character_uuid = ?", - assigned.characterUuid())) + assertThatThrownBy(() -> + isolatedDsl.execute( + "UPDATE characters SET account_uuid = NULL, tenant_uuid = NULL, " + + "playable_state_namespace_id = NULL, playable_state_scope = NULL, " + + "actor_identity_status = 'QUARANTINED', " + + "actor_identity_quarantine_reason = 'OWNER_PROVENANCE_MISSING' " + + "WHERE character_uuid = ?", + assigned.characterUuid())) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("reserved by an immutable empty-source receipt"); @@ -1716,17 +1706,15 @@ void runtimeProjectionSurvivesLostReplyRepositoryRestartAndRejectsChangedSelecto .isEqualTo(1); assertThat(characterRepository.readPreseededActorAssignmentReceipt(selector)) .contains(originalReceipt); - assertThatThrownBy( - () -> - jdbcTemplate.update( - "UPDATE entity_preseeded_actor_runtime_projections SET projection_fence = projection_fence + 1 WHERE assignment_uuid = ?", - assignmentUuid)) + assertThatThrownBy(() -> + jdbcTemplate.update( + "UPDATE entity_preseeded_actor_runtime_projections SET projection_fence = projection_fence + 1 WHERE assignment_uuid = ?", + assignmentUuid)) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - jdbcTemplate.update( - "DELETE FROM entity_preseeded_actor_runtime_projections WHERE assignment_uuid = ?", - assignmentUuid)) + assertThatThrownBy(() -> + jdbcTemplate.update( + "DELETE FROM entity_preseeded_actor_runtime_projections WHERE assignment_uuid = ?", + assignmentUuid)) .isInstanceOf(DataAccessException.class); // Stale durable character authority must invalidate the retained runtime projection read. jdbcTemplate.update( @@ -1750,14 +1738,13 @@ void concurrentFreshAssignmentAllocationsAreUniqueAndDuplicateOperationsAllocate UUID operation = index < 2 ? assignmentUuid : UUID.randomUUID(); UUID account = index < 2 ? accountUuid : UUID.randomUUID(); futures.add( - executor.submit( - () -> { - ready.countDown(); - if (!start.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException("Runtime projection race did not start"); - } - return assign(operation, account, 4L, scope, "Assigned Actor"); - })); + executor.submit(() -> { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Runtime projection race did not start"); + } + return assign(operation, account, 4L, scope, "Assigned Actor"); + })); } assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); start.countDown(); @@ -1789,33 +1776,31 @@ void distinctConcurrentAssignmentsPersistOneWinnerAndOneReplayableConflict() thr ExecutorService executor = Executors.newFixedThreadPool(2); try { Future first = - executor.submit( - () -> { - ready.countDown(); - if (!start.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException("Assignment race did not start"); - } - return assign( - assignmentUuid, - accountUuid, - 4L, - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Concurrent Actor"); - }); + executor.submit(() -> { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Assignment race did not start"); + } + return assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Concurrent Actor"); + }); Future second = - executor.submit( - () -> { - ready.countDown(); - if (!start.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException("Assignment race did not start"); - } - return assign( - secondAssignmentUuid, - accountUuid, - 4L, - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Concurrent Actor"); - }); + executor.submit(() -> { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Assignment race did not start"); + } + return assign( + secondAssignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Concurrent Actor"); + }); assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); start.countDown(); @@ -1828,10 +1813,8 @@ void distinctConcurrentAssignmentsPersistOneWinnerAndOneReplayableConflict() thr .orElseThrow(); PreseededActorAssignmentResult loser = results.stream() - .filter( - result -> - result.outcome() - == PreseededActorAssignmentResult.Outcome.IDEMPOTENCY_CONFLICT) + .filter(result -> + result.outcome() == PreseededActorAssignmentResult.Outcome.IDEMPOTENCY_CONFLICT) .findFirst() .orElseThrow(); @@ -1880,14 +1863,13 @@ void conflictingNamespaceScopeProofRollsBackGuardAndDoesNotPromoteOrAllocateActo namespaceUuid, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED.name()); - assertThatThrownBy( - () -> - assign( - assignmentUuid, - accountUuid, - 4L, - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - "Assigned Actor")) + assertThatThrownBy(() -> + assign( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + "Assigned Actor")) .isInstanceOf(RuntimeException.class); assertThat( @@ -1913,24 +1895,20 @@ void assignmentReplayAndOwnerMappingsRejectDeleteAndTruncate() { PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, "Assigned Actor"); - assertThatThrownBy( - () -> - jdbcTemplate.update( - "DELETE FROM entity_preseeded_actor_assignment_operations " - + "WHERE assignment_uuid = ?", - assignmentUuid)) + assertThatThrownBy(() -> + jdbcTemplate.update( + "DELETE FROM entity_preseeded_actor_assignment_operations " + + "WHERE assignment_uuid = ?", + assignmentUuid)) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - jdbcTemplate.update( - "DELETE FROM entity_tenant_identities WHERE canonical_tenant_uuid = ?", - tenantUuid)) + assertThatThrownBy(() -> + jdbcTemplate.update( + "DELETE FROM entity_tenant_identities WHERE canonical_tenant_uuid = ?", tenantUuid)) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - jdbcTemplate.execute( - "TRUNCATE TABLE entity_preseeded_actor_assignment_operations CASCADE")) + assertThatThrownBy(() -> + jdbcTemplate.execute( + "TRUNCATE TABLE entity_preseeded_actor_assignment_operations CASCADE")) .isInstanceOf(DataAccessException.class); assertThatThrownBy(() -> jdbcTemplate.execute("TRUNCATE TABLE entity_tenant_identities")) .isInstanceOf(DataAccessException.class); @@ -2008,13 +1986,12 @@ private void assertEmptyCanonicalRosterCreatedTenantMapping( new TransactionTemplate( new org.springframework.jdbc.datasource.DataSourceTransactionManager(ownerDataSource)); var snapshot = - ownerTransaction.execute( - ignored -> - new CharacterRepository(ownerDsl) - .captureCanonicalGameplayRosterSnapshot( - request, - new CanonicalGameplayRosterOwnerEvidence( - requestUuid, owner.canonicalAccountUuid(), target, Instant.now()))); + ownerTransaction.execute(ignored -> + new CharacterRepository(ownerDsl) + .captureCanonicalGameplayRosterSnapshot( + request, + new CanonicalGameplayRosterOwnerEvidence( + requestUuid, owner.canonicalAccountUuid(), target, Instant.now()))); assertThat(snapshot.actors()).isEmpty(); Long mappedTenantRowId = isolatedDsl diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java index 4389710eb7..2e16d1841d 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentOwnerCompositionPostgresIntegrationTest.java @@ -315,10 +315,9 @@ void composesExactMtlsOwnerReadsCapabilityAndActualPostgresAssignmentWriterAndRe // Invalidate the capability only after all three independent source RPCs have returned. // The service's second read is the last authorization step before the proxied SQL writer. - gameSessionOwner.afterNextRead.set( - () -> - writeCapabilityUnchecked( - capabilityFile, assignment, "changed-during-source-read", PROJECT)); + gameSessionOwner.afterNextRead.set(() -> + writeCapabilityUnchecked( + capabilityFile, assignment, "changed-during-source-read", PROJECT)); assertCallDenied( entityServer, "game-session-client", wireRequest, Status.Code.PERMISSION_DENIED); assertNoMutation(baseline, assignment); @@ -452,10 +451,9 @@ void composesExactMtlsOwnerReadsCapabilityAndActualPostgresAssignmentWriterAndRe List.of("world-client", "account-client", "foreign-game-session-client")) { assertThatThrownBy(() -> callRuntimeRead(entityServer, wrongPeer, runtimeSelector)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } assertThat(runtimeReadEntryCount.get()).isEqualTo(1); var changedRuntimeSelector = @@ -463,10 +461,9 @@ void composesExactMtlsOwnerReadsCapabilityAndActualPostgresAssignmentWriterAndRe assertThatThrownBy( () -> callRuntimeRead(entityServer, "game-session-client", changedRuntimeSelector)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.NOT_FOUND)); + .satisfies(failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.NOT_FOUND)); // A replacement target cannot borrow the original assignment's projection. var changedRuntimeTarget = runtimeSelector.toBuilder() @@ -477,10 +474,9 @@ void composesExactMtlsOwnerReadsCapabilityAndActualPostgresAssignmentWriterAndRe assertThatThrownBy( () -> callRuntimeRead(entityServer, "game-session-client", changedRuntimeTarget)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.NOT_FOUND)); + .satisfies(failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.NOT_FOUND)); var foreignRuntimeTarget = runtimeSelector.toBuilder() .setExpectedTarget( @@ -490,19 +486,17 @@ void composesExactMtlsOwnerReadsCapabilityAndActualPostgresAssignmentWriterAndRe assertThatThrownBy( () -> callRuntimeRead(entityServer, "game-session-client", foreignRuntimeTarget)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.NOT_FOUND)); + .satisfies(failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.NOT_FOUND)); var wrongAssignment = runtimeSelector.toBuilder().setAssignmentUuid(UUID.randomUUID().toString()).build(); assertThatThrownBy( () -> callRuntimeRead(entityServer, "game-session-client", wrongAssignment)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.NOT_FOUND)); + .satisfies(failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.NOT_FOUND)); assertThat( callRuntimeRead(entityServer, "game-session-client", runtimeSelector).toByteArray()) .containsExactly(runtimeRead.toByteArray()); @@ -889,36 +883,36 @@ private static String capabilityJson( String trustRootFingerprint) { var target = request.expectedTarget(); return """ - {\ - "schema": "firemud.run-owned-preseeded-actor-assignment.v3",%n\ - "runId": "%s",%n\ - "composeProjectName": "%s",%n\ - "action": "PRESEEDED_ACTOR_ASSIGNMENT",%n\ - "trustedGameSessionUriSan": "%s",%n\ - "trustedGameSessionNamespace": "%s",%n\ - "assignmentUuid": "%s",%n\ - "canonicalAccountUuid": "%s",%n\ - "expectedTarget": {%n\ - "canonicalTenantUuid": "%s",%n\ - "realmUuid": "%s",%n\ - "worldSlug": "%s",%n\ - "realmSlug": "%s",%n\ - "gameInstanceId": "%s",%n\ - "catalogRevision": %d,%n\ - "canonicalVersionUuid": "%s",%n\ - "frozenPolicyDigest": "%s",%n\ - "playableStateNamespaceUuid": "%s",%n\ - "publishedReleaseBundleRef": "%s",%n\ - "playableStateScope": "%s"%n\ - },%n\ - "corePayload": {%n\ - "actorKind": "PLAYER",%n\ - "displayName": "%s"%n\ - },%n\ - "intentDigest": "%s",%n\ - "entityServerTrustRootSha256": "%s"%n\ - }%n\ - """ + {\ + "schema": "firemud.run-owned-preseeded-actor-assignment.v3",%n\ + "runId": "%s",%n\ + "composeProjectName": "%s",%n\ + "action": "PRESEEDED_ACTOR_ASSIGNMENT",%n\ + "trustedGameSessionUriSan": "%s",%n\ + "trustedGameSessionNamespace": "%s",%n\ + "assignmentUuid": "%s",%n\ + "canonicalAccountUuid": "%s",%n\ + "expectedTarget": {%n\ + "canonicalTenantUuid": "%s",%n\ + "realmUuid": "%s",%n\ + "worldSlug": "%s",%n\ + "realmSlug": "%s",%n\ + "gameInstanceId": "%s",%n\ + "catalogRevision": %d,%n\ + "canonicalVersionUuid": "%s",%n\ + "frozenPolicyDigest": "%s",%n\ + "playableStateNamespaceUuid": "%s",%n\ + "publishedReleaseBundleRef": "%s",%n\ + "playableStateScope": "%s"%n\ + },%n\ + "corePayload": {%n\ + "actorKind": "PLAYER",%n\ + "displayName": "%s"%n\ + },%n\ + "intentDigest": "%s",%n\ + "entityServerTrustRootSha256": "%s"%n\ + }%n\ + """ .formatted( runId, project, diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index 5c8df7ca95..6b57a55c32 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -342,26 +342,24 @@ void storedCanonicalIdentityRequiresExactTupleWithoutPromotingLegacyRows() { assertThat( characterRepository.findById(legacyId).orElseThrow().getActorIdentity().status().name()) .isEqualTo("QUARANTINED"); - assertThatThrownBy( - () -> - insertActor( - "duplicate UUID", - resolvedActorUuid, - null, - null, - null, - null, - "shared-live", - "QUARANTINED", - "OWNER_PROVENANCE_MISSING", - accountId, - tenantId)) + assertThatThrownBy(() -> + insertActor( + "duplicate UUID", + resolvedActorUuid, + null, + null, + null, + null, + "shared-live", + "QUARANTINED", + "OWNER_PROVENANCE_MISSING", + accountId, + tenantId)) .isInstanceOf(org.springframework.dao.DuplicateKeyException.class) .hasMessageContaining("ux_characters_character_uuid"); - assertThatThrownBy( - () -> - insertNamespace( - tenantUuid, namespaceUuid, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + assertThatThrownBy(() -> + insertNamespace( + tenantUuid, namespaceUuid, PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) .isInstanceOf(org.springframework.dao.DuplicateKeyException.class) .hasMessageContaining("pk_entity_playable_state_namespace_scopes"); } @@ -499,15 +497,14 @@ void canonicalOwnerRepositoryReadsExactScopedActorsAndExcludesQuarantine() { shared, targetActor.toString())) .get() - .satisfies( - identity -> { - assertThat(identity.characterUuid()).isEqualTo(targetActor); - assertThat(identity.accountUuid()).isEqualTo(accountUuid); - assertThat(identity.tenantUuid()).isEqualTo(tenantUuid); - assertThat(identity.playableStateNamespaceId()).isEqualTo(namespaceUuid); - assertThat(identity.playableStateScope()).isEqualTo(shared); - assertThat(identity.status().name()).isEqualTo("OWNER_RESOLVED"); - }); + .satisfies(identity -> { + assertThat(identity.characterUuid()).isEqualTo(targetActor); + assertThat(identity.accountUuid()).isEqualTo(accountUuid); + assertThat(identity.tenantUuid()).isEqualTo(tenantUuid); + assertThat(identity.playableStateNamespaceId()).isEqualTo(namespaceUuid); + assertThat(identity.playableStateScope()).isEqualTo(shared); + assertThat(identity.status().name()).isEqualTo("OWNER_RESOLVED"); + }); for (UUID excluded : List.of(accountActor, tenantActor, namespaceActor, quarantinedActor)) { assertThat( actorIdentityRepository.findOwnerResolvedActor( @@ -697,11 +694,10 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro "saga/V1001__saga_instance_table.sql", "saga/V1002__saga_step_table.sql"); assertThat(parentHistory) - .allSatisfy( - entry -> { - assertThat(entry.success()).isTrue(); - assertThat(entry.checksum()).isNotNull(); - }); + .allSatisfy(entry -> { + assertThat(entry.success()).isTrue(); + assertThat(entry.checksum()).isNotNull(); + }); try (Connection connection = connectToMigrationSchema()) { var statement = connection.createStatement(); statement.executeUpdate( diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java index 02b847b8b9..6f6b0f315e 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPostgresMtlsIntegrationTest.java @@ -419,14 +419,13 @@ UUID assign(UUID account, CanonicalGameplayRosterTarget target, long rowId, Stri target.playableStateScope())); var result = new TransactionTemplate(manager) - .execute( - ignored -> - characters.assignPreseededActor( - request, - evidence, - new RuntimeAccountIdentityEvidence( - 1, "test", operation, account, rowId, "ACCOUNT_DATABASE_INSERT"), - request.mutationIntentDigest())); + .execute(ignored -> + characters.assignPreseededActor( + request, + evidence, + new RuntimeAccountIdentityEvidence( + 1, "test", operation, account, rowId, "ACCOUNT_DATABASE_INSERT"), + request.mutationIntentDigest())); assertThat(result.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); return result.characterUuid(); } diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java index bde5e9b6cc..276be96c30 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreatePostgresIntegrationTest.java @@ -189,10 +189,9 @@ void binaryGuardUpgradePreservesCreatedRowsHistoryAndTerminalReplay() throws Exc assertThat(retainedRepository.settle(retainedProof, null)).isEqualTo(terminal); assertThat(retainedDsl.fetchCount(DSL.table("entity_player_created_runtime_projections"))) .isZero(); - assertThatThrownBy( - () -> - new EntityPlayerCreatedRuntimeProjectionRepository() - .read(retainedDsl, terminal, retainedProof.action())) + assertThatThrownBy(() -> + new EntityPlayerCreatedRuntimeProjectionRepository() + .read(retainedDsl, terminal, retainedProof.action())) .isInstanceOf(io.grpc.StatusRuntimeException.class) .hasMessageContaining("FAILED_PRECONDITION"); assertThat(retainedRepository.replay(retainedProof.request()).orElseThrow()) @@ -202,14 +201,13 @@ void binaryGuardUpgradePreservesCreatedRowsHistoryAndTerminalReplay() throws Exc "original_request = decode('01', 'hex')", "terminal_bytes = decode('02', 'hex')", "status = 'PENDING'")) { - assertThatThrownBy( - () -> - retainedDsl.execute( - "UPDATE entity_character_create_operations SET " - + change - + " WHERE target_namespace = ? AND operation_id = ?", - operationNamespace, - operation)) + assertThatThrownBy(() -> + retainedDsl.execute( + "UPDATE entity_character_create_operations SET " + + change + + " WHERE target_namespace = ? AND operation_id = ?", + operationNamespace, + operation)) .isInstanceOf(org.jooq.exception.DataAccessException.class); } assertThat(retainedOperationRow(retainedDsl, operationNamespace, operation)) @@ -316,17 +314,14 @@ void atomicallyPersistsAuthoredGenericActorAssociationAndExactReplay() throws Ex assertThat(actor.get("actor_entry_policy", String.class)).isEqualTo("PLAYER_CREATED"); assertThat(terminal.getEntityIntakeRequestId()).isEqualTo(source.intakeRequestId().toString()); assertThat(terminal.getEntitySourceReceiptDigest()).isEqualTo(source.receiptDigest()); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE entity_character_create_operations SET terminal_bytes = ?", - new byte[] {1})) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE entity_character_create_operations SET terminal_bytes = ?", new byte[] {1})) .isInstanceOf(org.jooq.exception.DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE characters SET name = 'substituted' WHERE character_uuid = ?", - UUID.fromString(terminal.getCharacterId()))) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE characters SET name = 'substituted' WHERE character_uuid = ?", + UUID.fromString(terminal.getCharacterId()))) .isInstanceOf(org.jooq.exception.DataAccessException.class); } @@ -340,12 +335,11 @@ void freshRuntimeProjectionSurvivesReplayAndRepositoryRecreation() throws Except assertThat(reference.projectionGeneration()).isOne(); assertThat(reference.projectionFence()).isOne(); assertThat(reference.creationTerminal()).isEqualTo(terminal); - assertRuntimeSelectorUnavailable( - () -> - projections.read( - dsl, - terminal.toBuilder().setTerminalId(UUID.randomUUID().toString()).build(), - proof.action())); + assertRuntimeSelectorUnavailable(() -> + projections.read( + dsl, + terminal.toBuilder().setTerminalId(UUID.randomUUID().toString()).build(), + proof.action())); assertThat(reference.terminalDigest()) .isEqualTo(CommandSource.sha256(terminal.toByteArray()).substring("sha256:".length())); var restarted = new EntityCharacterCreateRepository(dsl, Clock.fixed(NOW, ZoneOffset.UTC)); @@ -484,17 +478,15 @@ void actualCreatedRuntimeOwnerServesBothRolesWithoutReadAllocation(@TempDir Path selector.getOrigin().toBuilder() .setCreationOperationUuid(UUID.randomUUID().toString())) .build(); - assertThatThrownBy( - () -> - restartedRepository.read( - proof.request().getOriginal().toBuilder() - .setMutationDigest(changedDigest.getOrigin().getMutationDigest()) - .build())) + assertThatThrownBy(() -> + restartedRepository.read( + proof.request().getOriginal().toBuilder() + .setMutationDigest(changedDigest.getOrigin().getMutationDigest()) + .build())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.ALREADY_EXISTS)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.ALREADY_EXISTS)); for (var changed : List.of( changedOrigin, changedCharacter, changedTarget, changedDigest, missingOperation)) { @@ -592,50 +584,47 @@ void rawProjectionMismatchAndAllHistoryMutationFailClosed() throws Exception { // Valid self-assignments bypass CHECK(projection_fence = 1); only the retained-history // trigger may reject these, so removal of that guard must fail the test. for (String immutableColumn : List.of("game_instance_id", "terminal_digest")) { - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE entity_player_created_runtime_projections SET " - + immutableColumn - + " = " - + immutableColumn)) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE entity_player_created_runtime_projections SET " + + immutableColumn + + " = " + + immutableColumn)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("Entity assignment evidence cannot be removed"); } for (String mismatch : List.of("account_uuid", "tenant_uuid", "canonical_version_id", "character_uuid")) { - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO entity_player_created_runtime_projections " - + "(tenant_uuid, playable_state_namespace_id, game_instance_id, character_uuid, account_uuid, canonical_version_id, realm_uuid, target_namespace, creation_operation_id, mutation_digest, terminal_id, terminal_digest) " - + "SELECT " - + (mismatch.equals("tenant_uuid") ? "?::uuid" : "tenant_uuid") - + ", playable_state_namespace_id, game_instance_id, " - + (mismatch.equals("character_uuid") ? "?::uuid" : "character_uuid") - + ", " - + (mismatch.equals("account_uuid") ? "?::uuid" : "account_uuid") - + ", " - + (mismatch.equals("canonical_version_id") - ? "?::uuid" - : "canonical_version_id") - + ", realm_uuid, target_namespace, creation_operation_id, mutation_digest, terminal_id, terminal_digest FROM entity_player_created_runtime_projections", - UUID.randomUUID())) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO entity_player_created_runtime_projections " + + "(tenant_uuid, playable_state_namespace_id, game_instance_id, character_uuid, account_uuid, canonical_version_id, realm_uuid, target_namespace, creation_operation_id, mutation_digest, terminal_id, terminal_digest) " + + "SELECT " + + (mismatch.equals("tenant_uuid") ? "?::uuid" : "tenant_uuid") + + ", playable_state_namespace_id, game_instance_id, " + + (mismatch.equals("character_uuid") ? "?::uuid" : "character_uuid") + + ", " + + (mismatch.equals("account_uuid") ? "?::uuid" : "account_uuid") + + ", " + + (mismatch.equals("canonical_version_id") + ? "?::uuid" + : "canonical_version_id") + + ", realm_uuid, target_namespace, creation_operation_id, mutation_digest, terminal_id, terminal_digest FROM entity_player_created_runtime_projections", + UUID.randomUUID())) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining("exact committed PLAYER_CREATED provenance"); } for (String mismatch : List.of("mutation_digest", "terminal_digest")) { - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO entity_player_created_runtime_projections " - + "(tenant_uuid, playable_state_namespace_id, game_instance_id, character_uuid, account_uuid, canonical_version_id, realm_uuid, target_namespace, creation_operation_id, mutation_digest, terminal_id, terminal_digest) " - + "SELECT tenant_uuid, playable_state_namespace_id, game_instance_id, character_uuid, account_uuid, canonical_version_id, realm_uuid, target_namespace, creation_operation_id, " - + (mismatch.equals("mutation_digest") ? "?" : "mutation_digest") - + ", terminal_id, " - + (mismatch.equals("terminal_digest") ? "?" : "terminal_digest") - + " FROM entity_player_created_runtime_projections", - "f".repeat(64))) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO entity_player_created_runtime_projections " + + "(tenant_uuid, playable_state_namespace_id, game_instance_id, character_uuid, account_uuid, canonical_version_id, realm_uuid, target_namespace, creation_operation_id, mutation_digest, terminal_id, terminal_digest) " + + "SELECT tenant_uuid, playable_state_namespace_id, game_instance_id, character_uuid, account_uuid, canonical_version_id, realm_uuid, target_namespace, creation_operation_id, " + + (mismatch.equals("mutation_digest") ? "?" : "mutation_digest") + + ", terminal_id, " + + (mismatch.equals("terminal_digest") ? "?" : "terminal_digest") + + " FROM entity_player_created_runtime_projections", + "f".repeat(64))) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining("exact committed PLAYER_CREATED provenance"); } @@ -740,21 +729,19 @@ void storedSourceMismatchReturnsDataLossWithCauseAndNoReadEffects() throws Excep UUID.fromString(proof.original().getOperationId()))); int actorCountBefore = dsl.fetchCount(DSL.table("characters")); - assertThatThrownBy( - () -> - repository.readSelectedPlayerCreatedTerminal( - new AuthenticatedAccountSelector(accountId), published(proof), characterId)) + assertThatThrownBy(() -> + repository.readSelectedPlayerCreatedTerminal( + new AuthenticatedAccountSelector(accountId), published(proof), characterId)) .isInstanceOf(io.grpc.StatusRuntimeException.class) - .satisfies( - failure -> { - var status = (io.grpc.StatusRuntimeException) failure; - assertThat(status.getStatus().getCode()).isEqualTo(io.grpc.Status.Code.DATA_LOSS); - assertThat(status.getStatus().getDescription()) - .isEqualTo("Stored creation terminal is invalid"); - assertThat(status.getCause()) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Corrupt creation source identity"); - }); + .satisfies(failure -> { + var status = (io.grpc.StatusRuntimeException) failure; + assertThat(status.getStatus().getCode()).isEqualTo(io.grpc.Status.Code.DATA_LOSS); + assertThat(status.getStatus().getDescription()) + .isEqualTo("Stored creation terminal is invalid"); + assertThat(status.getCause()) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Corrupt creation source identity"); + }); var actorAfter = Objects.requireNonNull( @@ -861,11 +848,10 @@ void standaloneCreatedRosterCannotExceedTheOwnerResolvedScopeUniqueIndex() throw UUID characterId = UUID.fromString(terminal.getCharacterId()); String before = retainedRow(dsl, "characters", "character_uuid", characterId); // Even a direct duplicate with retained terminal metadata cannot exceed the scope bound. - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO characters (character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason, tenant_id, account_id, playable_state_key, name, level, experience, strength, agility, intelligence, stamina, health, mana, body_layout_key, creation_target_namespace, creation_operation_id, actor_entry_policy, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest) SELECT gen_random_uuid(), account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason, tenant_id, account_id, playable_state_key, name, level, experience, strength, agility, intelligence, stamina, health, mana, body_layout_key, creation_target_namespace, creation_operation_id, actor_entry_policy, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest FROM characters WHERE character_uuid = ?", - characterId)) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO characters (character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason, tenant_id, account_id, playable_state_key, name, level, experience, strength, agility, intelligence, stamina, health, mana, body_layout_key, creation_target_namespace, creation_operation_id, actor_entry_policy, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest) SELECT gen_random_uuid(), account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason, tenant_id, account_id, playable_state_key, name, level, experience, strength, agility, intelligence, stamina, health, mana, body_layout_key, creation_target_namespace, creation_operation_id, actor_entry_policy, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest FROM characters WHERE character_uuid = ?", + characterId)) .isInstanceOf(org.jooq.exception.IntegrityConstraintViolationException.class) .hasMessageContaining("ux_characters_owner_resolved_account_namespace"); assertThat(dsl.fetchCount(DSL.table("characters"))).isOne(); @@ -1043,22 +1029,19 @@ void changedPublishedProjectionFailsClosedAndStoredProvenanceCorruptionIsDataLos proof.action().scope().targetNamespace(), UUID.fromString(proof.original().getOperationId()))); int actorCountBefore = dsl.fetchCount(DSL.table("characters")); - assertThatThrownBy( - () -> - repository.readPlayerCreatedRoster( - new AuthenticatedAccountSelector(account), changedPublishedSource)) + assertThatThrownBy(() -> + repository.readPlayerCreatedRoster( + new AuthenticatedAccountSelector(account), changedPublishedSource)) .isInstanceOf(io.grpc.StatusRuntimeException.class) .hasMessageContaining("FAILED_PRECONDITION"); - assertThatThrownBy( - () -> - repository.readSelectedPlayerCreatedTerminal( - new AuthenticatedAccountSelector(account), changedPublishedSource, characterId)) + assertThatThrownBy(() -> + repository.readSelectedPlayerCreatedTerminal( + new AuthenticatedAccountSelector(account), changedPublishedSource, characterId)) .isInstanceOf(io.grpc.StatusRuntimeException.class) .hasMessageContaining("FAILED_PRECONDITION"); - assertThatThrownBy( - () -> - repository.readPlayerCreatedRoster( - new AuthenticatedAccountSelector(account), changedRealm)) + assertThatThrownBy(() -> + repository.readPlayerCreatedRoster( + new AuthenticatedAccountSelector(account), changedRealm)) .isInstanceOf(io.grpc.StatusRuntimeException.class) .hasMessageContaining("FAILED_PRECONDITION"); var actorAfter = @@ -1087,18 +1070,16 @@ void changedPublishedProjectionFailsClosedAndStoredProvenanceCorruptionIsDataLos dsl.execute( "UPDATE characters SET creation_descriptor_json = '{}' WHERE character_uuid = ?", characterId); - assertThatThrownBy( - () -> - repository.readPlayerCreatedRoster( - new AuthenticatedAccountSelector(account), published)) + assertThatThrownBy(() -> + repository.readPlayerCreatedRoster( + new AuthenticatedAccountSelector(account), published)) .isInstanceOf(io.grpc.StatusRuntimeException.class) .hasMessageContaining("DATA_LOSS"); - assertThatThrownBy( - () -> - repository.readSelectedPlayerCreatedTerminal( - new AuthenticatedAccountSelector(account), - published, - UUID.fromString(terminal.getCharacterId()))) + assertThatThrownBy(() -> + repository.readSelectedPlayerCreatedTerminal( + new AuthenticatedAccountSelector(account), + published, + UUID.fromString(terminal.getCharacterId()))) .isInstanceOf(io.grpc.StatusRuntimeException.class) .hasMessageContaining("DATA_LOSS"); } finally { @@ -1126,12 +1107,11 @@ void explicitAbortPermanentlyWinsAgainstFutureCommitAndChangedDigestConflicts() .containsExactly(terminal.toByteArray()); assertThat(dsl.fetchCount(DSL.table("characters"))).isZero(); assertThat(dsl.fetchCount(DSL.table("entity_player_created_runtime_projections"))).isZero(); - assertThatThrownBy( - () -> - repository.read( - proof.request().getOriginal().toBuilder() - .setMutationDigest("f".repeat(64)) - .build())) + assertThatThrownBy(() -> + repository.read( + proof.request().getOriginal().toBuilder() + .setMutationDigest("f".repeat(64)) + .build())) .isInstanceOf(io.grpc.StatusRuntimeException.class) .hasMessageContaining("ALREADY_EXISTS"); assertThatThrownBy(() -> dsl.execute("DELETE FROM entity_character_create_operations")) @@ -1200,15 +1180,13 @@ void commitAndAbortSerializeToOneImmutableTerminal() throws Exception { void legacyRowsKeepTheirConstraintsAndCannotBeRelabelled() { dsl.execute( "INSERT INTO characters (account_id, tenant_id, name) VALUES (76543, 87654, 'legacy')"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE characters SET actor_entry_policy = 'PLAYER_CREATED' WHERE name = 'legacy'")) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE characters SET actor_entry_policy = 'PLAYER_CREATED' WHERE name = 'legacy'")) .isInstanceOf(org.jooq.exception.DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO characters (account_id, tenant_id, name, level) VALUES (76544, 87654, 'invalid', NULL)")) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO characters (account_id, tenant_id, name, level) VALUES (76544, 87654, 'invalid', NULL)")) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat( Objects.requireNonNull( @@ -1556,13 +1534,11 @@ private static void assertCreatedActorQuarantineBoundary( proof.action().scope().targetNamespace(), UUID.fromString(proof.original().getOperationId()))) .isEqualTo(operationBefore); - assertThatThrownBy( - () -> - ownerDsl.execute( - "UPDATE characters SET creation_descriptor_digest=? " - + "WHERE character_uuid=?", - "sha256:" + "f".repeat(64), - characterId)) + assertThatThrownBy(() -> + ownerDsl.execute( + "UPDATE characters SET creation_descriptor_digest=? " + "WHERE character_uuid=?", + "sha256:" + "f".repeat(64), + characterId)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining("CHARACTER_CREATE authored identity/provenance is immutable"); var published = published(proof); @@ -1592,18 +1568,17 @@ private static void assertCreatedActorQuarantineBoundary( .and(DSL.field("character_uuid").eq(characterId)))) .isZero(); assertThat(new CharacterRepository(ownerDsl).findById(privateCharacterId)).isEmpty(); - assertThatThrownBy( - () -> - ownerDsl.execute( - "INSERT INTO characters (character_uuid, account_uuid, tenant_uuid, " - + "playable_state_namespace_id, playable_state_scope, account_id, " - + "tenant_id, name) VALUES (?, ?, ?, ?, " - + "'PLAYABLE_STATE_SCOPE_SHARED', 45, ?, 'unqualified quarantine')", - UUID.randomUUID(), - accountId, - UUID.fromString(proof.action().scope().tenantId()), - UUID.randomUUID(), - privateTenantId)) + assertThatThrownBy(() -> + ownerDsl.execute( + "INSERT INTO characters (character_uuid, account_uuid, tenant_uuid, " + + "playable_state_namespace_id, playable_state_scope, account_id, " + + "tenant_id, name) VALUES (?, ?, ?, ?, " + + "'PLAYABLE_STATE_SCOPE_SHARED', 45, ?, 'unqualified quarantine')", + UUID.randomUUID(), + accountId, + UUID.fromString(proof.action().scope().tenantId()), + UUID.randomUUID(), + privateTenantId)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining( "Entity numeric source key is reserved by an immutable empty-source receipt"); @@ -1614,9 +1589,8 @@ private static void assertSelectedActorUnavailable( AuthenticatedAccountSelector account, PublishedIdentity published, UUID characterId) { - assertThatThrownBy( - () -> - ownerRepository.readSelectedPlayerCreatedTerminal(account, published, characterId)) + assertThatThrownBy(() -> + ownerRepository.readSelectedPlayerCreatedTerminal(account, published, characterId)) .isInstanceOf(io.grpc.StatusRuntimeException.class) .hasMessageContaining("FAILED_PRECONDITION") .hasMessageContaining("Selected PLAYER_CREATED character is unavailable"); @@ -1705,13 +1679,12 @@ private static ManagedChannel runtimeChannel(int port, LoopbackMtlsTestPki.Pki p private static void assertRuntimeSelectorUnavailable(Runnable call) { assertThatThrownBy(call::run) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - var status = Status.fromThrowable(failure); - assertThat(status.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); - assertThat(status.getDescription()) - .isEqualTo("Original PLAYER_CREATED runtime evidence is unavailable"); - }); + .satisfies(failure -> { + var status = Status.fromThrowable(failure); + assertThat(status.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(status.getDescription()) + .isEqualTo("Original PLAYER_CREATED runtime evidence is unavailable"); + }); } /** Controlled historical pre-V1023 storage cohort; this is not the current creation writer. */ @@ -1734,68 +1707,67 @@ private static EntityCharacterCreateTerminal retainHistoricalCreatedActor( .setTerminalFence(1L) .setCompletedAt(NOW.toString()) .build(); - ownerDsl.transaction( - configuration -> { - var tx = DSL.using(configuration); - UUID tenant = UUID.fromString(action.scope().tenantId()); - UUID namespace = UUID.fromString(action.scope().playableStateNamespaceId()); - UUID account = UUID.fromString(action.target().accountId()); - UUID operation = UUID.fromString(proof.original().getOperationId()); - String scope = action.scope().playableStateScope().name(); - tx.execute( - "INSERT INTO entity_tenant_identities (canonical_tenant_uuid) VALUES (?) ON CONFLICT DO NOTHING", - tenant); - Long tenantRow = - tx.fetchSingle( - "SELECT entity_tenant_row_id FROM entity_tenant_identities WHERE canonical_tenant_uuid = ?", - tenant) - .get(0, Long.class); - tx.execute( - "INSERT INTO entity_playable_state_namespace_scopes (tenant_uuid, playable_state_namespace_id, playable_state_scope) VALUES (?, ?, ?) ON CONFLICT DO NOTHING", - tenant, - namespace, - scope); - tx.execute( - "INSERT INTO entity_character_create_roster_guards (tenant_uuid, playable_state_namespace_id, account_uuid) VALUES (?, ?, ?)", - tenant, - namespace, - account); - tx.execute( - "INSERT INTO entity_character_create_operations (target_namespace, operation_id, create_character_request_id, mutation_digest, tenant_uuid, playable_state_namespace_id, playable_state_scope, account_uuid, canonical_version_id, original_request, original_account, original_account_protection, original_game_session_protection, original_world_protection, entity_source_receipt, status, terminal_bytes, character_uuid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'COMMITTED', ?, ?)", - action.scope().targetNamespace(), - operation, - UUID.fromString(proof.original().getCreateCharacterRequestId()), - proof.original().getMutationDigest(), - tenant, - namespace, - scope, - account, - UUID.fromString(action.target().versionId()), - proof.request().toByteArray(), - proof.original().toByteArray(), - proof.account().toByteArray(), - proof.gameSession().originalOwnerReadback().toByteArray(), - proof.world().toByteArray(), - proof.entitySource().canonicalBytes(), - terminal.toByteArray(), - character); - tx.execute( - "INSERT INTO characters (character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason, tenant_id, account_id, playable_state_key, name, level, experience, strength, agility, intelligence, stamina, health, mana, body_layout_key, creation_target_namespace, creation_operation_id, actor_entry_policy, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest) VALUES (?, ?, ?, ?, ?, 'OWNER_RESOLVED', NULL, ?, NULL, NULL, ?, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, ?, ?, 'PLAYER_CREATED', ?, ?, ?)", - character, - account, - tenant, - namespace, - scope, - tenantRow, - new AuthoredInitialActorCoreProjection.AuthoredCore( - action.mutation().authoredSource().core().canonicalJson()) - .displayName(), - action.scope().targetNamespace(), - operation, - action.mutation().authoredSource().core().canonicalJson(), - action.mutation().authoredSource().descriptor().canonicalJson(), - action.mutation().authoredSource().descriptor().digest()); - }); + ownerDsl.transaction(configuration -> { + var tx = DSL.using(configuration); + UUID tenant = UUID.fromString(action.scope().tenantId()); + UUID namespace = UUID.fromString(action.scope().playableStateNamespaceId()); + UUID account = UUID.fromString(action.target().accountId()); + UUID operation = UUID.fromString(proof.original().getOperationId()); + String scope = action.scope().playableStateScope().name(); + tx.execute( + "INSERT INTO entity_tenant_identities (canonical_tenant_uuid) VALUES (?) ON CONFLICT DO NOTHING", + tenant); + Long tenantRow = + tx.fetchSingle( + "SELECT entity_tenant_row_id FROM entity_tenant_identities WHERE canonical_tenant_uuid = ?", + tenant) + .get(0, Long.class); + tx.execute( + "INSERT INTO entity_playable_state_namespace_scopes (tenant_uuid, playable_state_namespace_id, playable_state_scope) VALUES (?, ?, ?) ON CONFLICT DO NOTHING", + tenant, + namespace, + scope); + tx.execute( + "INSERT INTO entity_character_create_roster_guards (tenant_uuid, playable_state_namespace_id, account_uuid) VALUES (?, ?, ?)", + tenant, + namespace, + account); + tx.execute( + "INSERT INTO entity_character_create_operations (target_namespace, operation_id, create_character_request_id, mutation_digest, tenant_uuid, playable_state_namespace_id, playable_state_scope, account_uuid, canonical_version_id, original_request, original_account, original_account_protection, original_game_session_protection, original_world_protection, entity_source_receipt, status, terminal_bytes, character_uuid) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'COMMITTED', ?, ?)", + action.scope().targetNamespace(), + operation, + UUID.fromString(proof.original().getCreateCharacterRequestId()), + proof.original().getMutationDigest(), + tenant, + namespace, + scope, + account, + UUID.fromString(action.target().versionId()), + proof.request().toByteArray(), + proof.original().toByteArray(), + proof.account().toByteArray(), + proof.gameSession().originalOwnerReadback().toByteArray(), + proof.world().toByteArray(), + proof.entitySource().canonicalBytes(), + terminal.toByteArray(), + character); + tx.execute( + "INSERT INTO characters (character_uuid, account_uuid, tenant_uuid, playable_state_namespace_id, playable_state_scope, actor_identity_status, actor_identity_quarantine_reason, tenant_id, account_id, playable_state_key, name, level, experience, strength, agility, intelligence, stamina, health, mana, body_layout_key, creation_target_namespace, creation_operation_id, actor_entry_policy, authored_initial_core_json, creation_descriptor_json, creation_descriptor_digest) VALUES (?, ?, ?, ?, ?, 'OWNER_RESOLVED', NULL, ?, NULL, NULL, ?, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, ?, ?, 'PLAYER_CREATED', ?, ?, ?)", + character, + account, + tenant, + namespace, + scope, + tenantRow, + new AuthoredInitialActorCoreProjection.AuthoredCore( + action.mutation().authoredSource().core().canonicalJson()) + .displayName(), + action.scope().targetNamespace(), + operation, + action.mutation().authoredSource().core().canonicalJson(), + action.mutation().authoredSource().descriptor().canonicalJson(), + action.mutation().authoredSource().descriptor().digest()); + }); return terminal; } diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java index 23f1b6781a..2b1fef8739 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSnapshotPostgresIntegrationTest.java @@ -120,15 +120,14 @@ void sealedEmptyCreatedSnapshotRetainsImmutableSourceIdentity() { assertThat(dsl.fetchCount(DSL.table("entity_canonical_gameplay_roster_snapshot_actors"))) .isZero(); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE entity_canonical_gameplay_roster_snapshots SET canonical_player_created_source_identity = ? WHERE snapshot_uuid = ?", - sourceIdentity().toBuilder() - .setDescriptorRevisionUuid(UUID.randomUUID().toString()) - .build() - .toByteArray(), - snapshot)) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE entity_canonical_gameplay_roster_snapshots SET canonical_player_created_source_identity = ? WHERE snapshot_uuid = ?", + sourceIdentity().toBuilder() + .setDescriptorRevisionUuid(UUID.randomUUID().toString()) + .build() + .toByteArray(), + snapshot)) .isInstanceOf(DataAccessException.class); } @@ -165,10 +164,9 @@ void actualCreatedActorProducesIndependentlyRetiredEmptyAndPopulatedSiblingSnaps .setDescriptorUuid(UUID.randomUUID().toString())) .build(); var beforeMismatch = rosterRowCounts(); - assertThatThrownBy( - () -> - snapshotRepository.capture( - changedSourceRequest, source, empty.original(), emptyAdmission)) + assertThatThrownBy(() -> + snapshotRepository.capture( + changedSourceRequest, source, empty.original(), emptyAdmission)) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_PLAYER_CREATED_SOURCE_CHANGED"); assertThat(rosterRowCounts()).isEqualTo(beforeMismatch); @@ -214,36 +212,33 @@ void actualCreatedActorProducesIndependentlyRetiredEmptyAndPopulatedSiblingSnaps assertThat(lateCandidateRows).hasSize(2); var emptyCandidate = lateCandidateRows.stream() - .filter( - candidate -> - candidate - .binding() - .snapshot() - .snapshotUuid() - .toString() - .equals(emptyReceipt.getRoster().getSnapshotUuid())) + .filter(candidate -> + candidate + .binding() + .snapshot() + .snapshotUuid() + .toString() + .equals(emptyReceipt.getRoster().getSnapshotUuid())) .findFirst() .orElseThrow(); var initialPopulatedCandidate = lateCandidateRows.stream() - .filter( - candidate -> - candidate - .binding() - .snapshot() - .snapshotUuid() - .toString() - .equals(populatedReceipt.getRoster().getSnapshotUuid())) + .filter(candidate -> + candidate + .binding() + .snapshot() + .snapshotUuid() + .toString() + .equals(populatedReceipt.getRoster().getSnapshotUuid())) .findFirst() .orElseThrow(); UUID siblingHold = UUID.randomUUID(); - transaction.executeWithoutResult( - ignored -> - delayedBinding.acquire( - initialPopulatedCandidate.binding(), - UUID.randomUUID(), - siblingHold, - CanonicalGameplayRosterRetentionRepository.ReferenceKind.HOLD)); + transaction.executeWithoutResult(ignored -> + delayedBinding.acquire( + initialPopulatedCandidate.binding(), + UUID.randomUUID(), + siblingHold, + CanonicalGameplayRosterRetentionRepository.ReferenceKind.HOLD)); UUID populatedSnapshotUuid = initialPopulatedCandidate.snapshotUuid(); var populatedCandidate = transaction.execute(ignored -> delayedBinding.candidates(null, 10)).stream() @@ -268,34 +263,24 @@ void actualCreatedActorProducesIndependentlyRetiredEmptyAndPopulatedSiblingSnaps AtomicInteger secondSealPid = new AtomicInteger(); try (ExecutorService executor = Executors.newFixedThreadPool(2)) { Future firstSeal = - executor.submit( - () -> - transaction.execute( - ignored -> { - firstSealPid.set( - dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); - assertThat( - delayedBinding.observeRetirement( - emptyCandidate, emptyProof, policy)) - .as("the empty created sibling persists its own seal") - .isTrue(); - firstSealAcquired.countDown(); - awaitSiblingLatch( - allowFirstSealCommit, "first created sibling seal commit"); - return true; - })); + executor.submit(() -> + transaction.execute(ignored -> { + firstSealPid.set(dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + assertThat(delayedBinding.observeRetirement(emptyCandidate, emptyProof, policy)) + .as("the empty created sibling persists its own seal") + .isTrue(); + firstSealAcquired.countDown(); + awaitSiblingLatch(allowFirstSealCommit, "first created sibling seal commit"); + return true; + })); assertThat(firstSealAcquired.await(10, TimeUnit.SECONDS)).isTrue(); Future secondSeal = - executor.submit( - () -> - transaction.execute( - ignored -> { - secondSealPid.set( - dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); - secondSealStarted.countDown(); - return delayedBinding.observeRetirement( - populatedCandidate, populatedProof, policy); - })); + executor.submit(() -> + transaction.execute(ignored -> { + secondSealPid.set(dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + secondSealStarted.countDown(); + return delayedBinding.observeRetirement(populatedCandidate, populatedProof, policy); + })); assertThat(secondSealStarted.await(10, TimeUnit.SECONDS)).isTrue(); awaitBackendBlockedBy(secondSealPid.get(), firstSealPid.get()); allowFirstSealCommit.countDown(); @@ -312,49 +297,41 @@ void actualCreatedActorProducesIndependentlyRetiredEmptyAndPopulatedSiblingSnaps .findFirst() .orElseThrow(); assertThat( - transaction.execute( - ignored -> - delayedBinding.observeRetirement(sealedEmptyCandidate, emptyProof, policy))) + transaction.execute(ignored -> + delayedBinding.observeRetirement(sealedEmptyCandidate, emptyProof, policy))) .as("exact retirement replay keeps the empty sibling's persisted proof") .isTrue(); var changedProof = createdRetirementProof(empty, emptyReceipt, targetFence, UUID.randomUUID()); assertThat( - transaction.execute( - ignored -> - delayedBinding.observeRetirement(sealedEmptyCandidate, changedProof, policy))) + transaction.execute(ignored -> + delayedBinding.observeRetirement(sealedEmptyCandidate, changedProof, policy))) .as("a different proof cannot replace a retained sibling seal") .isFalse(); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - delayedBinding.acquire( - populatedCandidate.binding(), - UUID.randomUUID(), - UUID.randomUUID(), - CanonicalGameplayRosterRetentionRepository.ReferenceKind.RECOVERY))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + delayedBinding.acquire( + populatedCandidate.binding(), + UUID.randomUUID(), + UUID.randomUUID(), + CanonicalGameplayRosterRetentionRepository.ReferenceKind.RECOVERY))) .as("the live created snapshot's recovery path is fenced by its shared target seal") .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); var currentEmpty = transaction.execute(ignored -> delayedBinding.candidates(null, 10)).stream() - .filter( - candidate -> - candidate - .snapshotUuid() - .equals(emptyCandidate.binding().snapshot().snapshotUuid())) + .filter(candidate -> + candidate.snapshotUuid().equals(emptyCandidate.binding().snapshot().snapshotUuid())) .findFirst() .orElseThrow(); var currentPopulated = transaction.execute(ignored -> delayedBinding.candidates(null, 10)).stream() - .filter( - candidate -> - candidate - .snapshotUuid() - .equals(populatedCandidate.binding().snapshot().snapshotUuid())) + .filter(candidate -> + candidate + .snapshotUuid() + .equals(populatedCandidate.binding().snapshot().snapshotUuid())) .findFirst() .orElseThrow(); assertThat( @@ -380,12 +357,11 @@ void actualCreatedActorProducesIndependentlyRetiredEmptyAndPopulatedSiblingSnaps var confirmation = net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence .confirmation(transfer.acknowledgementRequest(), transfer.acknowledgement()); - transaction.executeWithoutResult( - ignored -> - delayedBinding.recordRetirementConfirmation( - transfer, - net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence - .confirmationResponse(confirmation))); + transaction.executeWithoutResult(ignored -> + delayedBinding.recordRetirementConfirmation( + transfer, + net.firedevops.firemud.common.world.CanonicalGameplayRosterRetirementEvidence + .confirmationResponse(confirmation))); } dsl.fetch("SELECT pg_sleep(0.05)"); @@ -409,9 +385,8 @@ void actualCreatedActorProducesIndependentlyRetiredEmptyAndPopulatedSiblingSnaps .as("the shared target fence remains while a sibling and delayed nonce remain") .isZero(); - transaction.executeWithoutResult( - ignored -> - delayedBinding.release(populatedCandidate.binding(), UUID.randomUUID(), siblingHold)); + transaction.executeWithoutResult(ignored -> + delayedBinding.release(populatedCandidate.binding(), UUID.randomUUID(), siblingHold)); dsl.fetch("SELECT pg_sleep(0.05)"); var unheldPopulated = transaction.execute(ignored -> delayedBinding.candidates(null, 10)).stream() @@ -432,10 +407,9 @@ void actualCreatedActorProducesIndependentlyRetiredEmptyAndPopulatedSiblingSnaps assertThat(transaction.execute(ignored -> delayedBinding.purgeRetiredTargets(8))) .as("the pre-seal delayed nonce still holds the shared target fence after siblings dispose") .isZero(); - assertThatThrownBy( - () -> - snapshotRepository.capture( - delayed.request(), source, delayed.original(), delayedAdmission)) + assertThatThrownBy(() -> + snapshotRepository.capture( + delayed.request(), source, delayed.original(), delayedAdmission)) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); assertThatThrownBy(() -> reserveAdmission(inputs(source, accountId, targetFence).request())) @@ -554,12 +528,11 @@ void actualConfiguredMtlsSourceCapturesAndReplaysAnEmptyRosterAtomically() throw .get(0, UUID.class)) .isEqualTo(UUID.fromString(first.getRoster().getSnapshotUuid())); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE entity_canonical_gameplay_roster_snapshots SET canonical_player_created_source_identity = ? WHERE snapshot_uuid = ?", - sourceIdentity().toByteArray(), - UUID.fromString(first.getRoster().getSnapshotUuid()))) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE entity_canonical_gameplay_roster_snapshots SET canonical_player_created_source_identity = ? WHERE snapshot_uuid = ?", + sourceIdentity().toByteArray(), + UUID.fromString(first.getRoster().getSnapshotUuid()))) .isInstanceOf(DataAccessException.class); } @@ -685,10 +658,8 @@ void actualCreatedActorWriterFeedsAuthenticatedBoundedSnapshotCapture() throws E .setDescriptorUuid(UUID.randomUUID().toString())) .build(); var beforeSelectedSourceMismatch = rosterRowCounts(); - assertThatThrownBy( - () -> - snapshotRepository.readSelected( - substitutedSource, inputs.source(), selectedOriginal)) + assertThatThrownBy(() -> + snapshotRepository.readSelected(substitutedSource, inputs.source(), selectedOriginal)) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_PLAYER_CREATED_SOURCE_CHANGED"); assertThat(rosterRowCounts()).isEqualTo(beforeSelectedSourceMismatch); @@ -700,10 +671,8 @@ void actualCreatedActorWriterFeedsAuthenticatedBoundedSnapshotCapture() throws E selectedRequest.getPlayerExecutionContext().toBuilder() .setAccountId(otherAccount.toString())) .build(); - assertThatThrownBy( - () -> - snapshotRepository.readSelected( - substitutedAccount, inputs.source(), selectedOriginal)) + assertThatThrownBy(() -> + snapshotRepository.readSelected(substitutedAccount, inputs.source(), selectedOriginal)) .isInstanceOf(IllegalArgumentException.class); var wrongNamespaceRequest = CanonicalGameplayRosterReferenceEvidence.playerCreatedRequest( @@ -719,10 +688,9 @@ void actualCreatedActorWriterFeedsAuthenticatedBoundedSnapshotCapture() throws E selectedOriginal.getOwnerFence(), UUID.fromString(selectedOriginal.getTargetFenceUuid()), snapshot); - assertThatThrownBy( - () -> - snapshotRepository.readSelected( - selectedRequest, inputs.source(), wrongNamespaceOriginal)) + assertThatThrownBy(() -> + snapshotRepository.readSelected( + selectedRequest, inputs.source(), wrongNamespaceOriginal)) .isInstanceOf(IllegalArgumentException.class); var beforeQuarantineSnapshot = @@ -735,9 +703,8 @@ void actualCreatedActorWriterFeedsAuthenticatedBoundedSnapshotCapture() throws E "UPDATE characters SET actor_identity_status='QUARANTINED', actor_identity_quarantine_reason='OWNER_PROVENANCE_REVOKED' WHERE character_uuid=? AND actor_identity_status='OWNER_RESOLVED'", actorId)) .isOne(); - assertThatThrownBy( - () -> - snapshotRepository.readSelected(selectedRequest, inputs.source(), selectedOriginal)) + assertThatThrownBy(() -> + snapshotRepository.readSelected(selectedRequest, inputs.source(), selectedOriginal)) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_SNAPSHOT_STALE"); assertThat(rosterRowCounts()).isEqualTo(beforeQuarantineCounts); @@ -761,13 +728,12 @@ void actualCreatedActorWriterFeedsAuthenticatedBoundedSnapshotCapture() throws E "SELECT xmin::text AS row_version, original_request, terminal_bytes, entity_source_receipt FROM entity_character_create_operations WHERE target_namespace = ? AND operation_id = ?", proof.action().scope().targetNamespace(), UUID.fromString(proof.original().getOperationId())); - assertThatThrownBy( - () -> - snapshotRepository.capture( - freshInputs.request(), - freshInputs.source(), - freshInputs.original(), - freshAdmission)) + assertThatThrownBy(() -> + snapshotRepository.capture( + freshInputs.request(), + freshInputs.source(), + freshInputs.original(), + freshAdmission)) .isInstanceOf(io.grpc.StatusRuntimeException.class) .hasMessageContaining("FAILED_PRECONDITION") .hasMessageContaining("Fresh PLAYER_CREATED roster is unavailable"); @@ -814,20 +780,18 @@ void actualCreatedActorWriterFeedsAuthenticatedBoundedSnapshotCapture() throws E .build(); var recoveryOwner = selectedOriginal.toBuilder().setRecoveryUuid(recoveryId.toString()).build(); var retentionRepository = new CanonicalGameplayRosterRetentionRepository(dsl); - transaction.executeWithoutResult( - ignored -> - retentionRepository.closeAdmission( - recoveryRequest, - recoveryOwner, - new CanonicalGameplayRosterRetentionPolicy( - Duration.ofHours(1), - Duration.ofHours(1), - Duration.ofHours(1), - Duration.ofMinutes(1), - 2))); - assertThatThrownBy( - () -> - snapshotRepository.readSelected(selectedRequest, inputs.source(), selectedOriginal)) + transaction.executeWithoutResult(ignored -> + retentionRepository.closeAdmission( + recoveryRequest, + recoveryOwner, + new CanonicalGameplayRosterRetentionPolicy( + Duration.ofHours(1), + Duration.ofHours(1), + Duration.ofHours(1), + Duration.ofMinutes(1), + 2))); + assertThatThrownBy(() -> + snapshotRepository.readSelected(selectedRequest, inputs.source(), selectedOriginal)) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); @@ -931,10 +895,8 @@ void substitutedSourceAccountSessionAndOriginalNamespaceRefuseBeforeSnapshotWrit UUID.fromString(inputs.request().getPlayerExecutionContext().getSessionId()), changedSource); var beforeSourceSubstitution = rosterRowCounts(); - assertThatThrownBy( - () -> - repository.capture( - sourceSubstitution, inputs.source(), inputs.original(), admission)) + assertThatThrownBy(() -> + repository.capture(sourceSubstitution, inputs.source(), inputs.original(), admission)) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_PLAYER_CREATED_SOURCE_CHANGED"); assertThat(rosterRowCounts()).isEqualTo(beforeSourceSubstitution); @@ -947,10 +909,8 @@ void substitutedSourceAccountSessionAndOriginalNamespaceRefuseBeforeSnapshotWrit otherAccount, UUID.fromString(inputs.request().getPlayerExecutionContext().getSessionId()), inputs.request().getExpectedSource()); - assertThatThrownBy( - () -> - repository.capture( - accountSubstitution, inputs.source(), inputs.original(), admission)) + assertThatThrownBy(() -> + repository.capture(accountSubstitution, inputs.source(), inputs.original(), admission)) .isInstanceOf(IllegalArgumentException.class); UUID otherSession = UUID.randomUUID(); @@ -961,10 +921,8 @@ void substitutedSourceAccountSessionAndOriginalNamespaceRefuseBeforeSnapshotWrit UUID.fromString(inputs.request().getCanonicalAccountUuid()), otherSession, inputs.request().getExpectedSource()); - assertThatThrownBy( - () -> - repository.capture( - sessionSubstitution, inputs.source(), inputs.original(), admission)) + assertThatThrownBy(() -> + repository.capture(sessionSubstitution, inputs.source(), inputs.original(), admission)) .isInstanceOf(IllegalArgumentException.class); var wrongNamespaceRequest = @@ -981,10 +939,9 @@ void substitutedSourceAccountSessionAndOriginalNamespaceRefuseBeforeSnapshotWrit inputs.original().getOwnerFence(), UUID.fromString(inputs.original().getTargetFenceUuid()), null); - assertThatThrownBy( - () -> - repository.capture( - inputs.request(), inputs.source(), wrongNamespaceOriginal, admission)) + assertThatThrownBy(() -> + repository.capture( + inputs.request(), inputs.source(), wrongNamespaceOriginal, admission)) .isInstanceOf(IllegalArgumentException.class); var isolatedTarget = @@ -1000,9 +957,8 @@ void substitutedSourceAccountSessionAndOriginalNamespaceRefuseBeforeSnapshotWrit inputs.request().getPlayerExecutionContext().toBuilder() .setPlayableStateScope("ISOLATED")) .build(); - assertThatThrownBy( - () -> - repository.capture(isolatedRequest, inputs.source(), inputs.original(), admission)) + assertThatThrownBy(() -> + repository.capture(isolatedRequest, inputs.source(), inputs.original(), admission)) .isInstanceOf(IllegalArgumentException.class); assertThat(dsl.fetchCount(DSL.table("entity_canonical_gameplay_roster_snapshots"))).isZero(); @@ -1025,9 +981,8 @@ void failedOriginalBindRollsBackTheSnapshotAndAdmissionBinding() throws Exceptio "CREATE TRIGGER fail_player_created_original_bind BEFORE INSERT ON entity_canonical_roster_original_selections FOR EACH ROW EXECUTE FUNCTION fail_player_created_original_bind()"); var repository = new EntityPlayerCreatedRosterSnapshotRepository(dsl, transactionManager); - assertThatThrownBy( - () -> - repository.capture(inputs.request(), inputs.source(), inputs.original(), admission)) + assertThatThrownBy(() -> + repository.capture(inputs.request(), inputs.source(), inputs.original(), admission)) .isInstanceOf(DataAccessException.class); assertThat(dsl.fetchCount(DSL.table("entity_canonical_gameplay_roster_snapshots"))).isZero(); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java index 1494dcbb89..de5c3d935c 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/CanonicalGameplayRosterRetentionPostgresIntegrationTest.java @@ -90,10 +90,9 @@ void upgradeRetainedV1011ActorReceiptAndSealedSnapshot() { migrate(dataSource, "latest"); assertThat(retainedRows()).containsExactlyElementsOf(retained); assertInheritedNullableFieldsRemainNull(); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> repository.requireUnsealedTarget(localRequest()))) + assertThatThrownBy(() -> + transaction.executeWithoutResult( + ignored -> repository.requireUnsealedTarget(localRequest()))) .as("retained snapshot classification must be initialized before acquisition") .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); @@ -118,65 +117,63 @@ void oldProtectedSnapshotDoesNotContributeToOldestBlockingRetirement() { @Test void latestMigrationsRetainClassificationShapeAndSeparateProofBudgets() { - transaction.executeWithoutResult( - ignored -> { - var liveChecks = - dsl.fetch( - "SELECT t.relname AS table_name, pg_get_constraintdef(c.oid) AS definition " - + "FROM pg_constraint c JOIN pg_class t ON t.oid = c.conrelid " - + "JOIN pg_namespace n ON n.oid = t.relnamespace " - + "WHERE c.contype = 'c' AND n.nspname = current_schema() " - + "AND t.relname IN ('entity_canonical_roster_target_classifications', " - + "'entity_canonical_roster_snapshot_targets', 'entity_canonical_roster_retired_targets')"); - assertThat(liveChecks.getValues("table_name", String.class)) - .contains( - "entity_canonical_roster_target_classifications", - "entity_canonical_roster_snapshot_targets", - "entity_canonical_roster_retired_targets"); - assertThat(liveChecks.getValues("definition", String.class)) - .anySatisfy( - definition -> - assertThat(definition) - .contains("classification_state", "target_binding", "retirement_proof") - .doesNotContain("octet_length(retirement_proof)")); - assertProofBudget( - liveChecks, + transaction.executeWithoutResult(ignored -> { + var liveChecks = + dsl.fetch( + "SELECT t.relname AS table_name, pg_get_constraintdef(c.oid) AS definition " + + "FROM pg_constraint c JOIN pg_class t ON t.oid = c.conrelid " + + "JOIN pg_namespace n ON n.oid = t.relnamespace " + + "WHERE c.contype = 'c' AND n.nspname = current_schema() " + + "AND t.relname IN ('entity_canonical_roster_target_classifications', " + + "'entity_canonical_roster_snapshot_targets', 'entity_canonical_roster_retired_targets')"); + assertThat(liveChecks.getValues("table_name", String.class)) + .contains( "entity_canonical_roster_target_classifications", - "octet_length(retirement_proof)", - "203423744", - "131072"); - assertProofBudget( - liveChecks, "entity_canonical_roster_snapshot_targets", - "octet_length(source_retirement_proof)", - "203423744", - "131072"); - assertProofBudget( - liveChecks, - "entity_canonical_roster_retired_targets", - "octet_length(owner_retirement_proof)", - "203423744"); - - // This clone inherits the actual latest-migration CHECKs. It contains synthetic bytes - // only: no source triggers or owner evidence are copied, so these probes prove storage - // shape constraints and do not qualify an authenticated source or retirement authority. - dsl.execute( - "CREATE TEMP TABLE roster_classification_constraint_probe " - + "(LIKE entity_canonical_roster_target_classifications INCLUDING CONSTRAINTS INCLUDING DEFAULTS) " - + "ON COMMIT DROP"); - byte[] target = "target-binding".getBytes(java.nio.charset.StandardCharsets.UTF_8); - byte[] proof = "synthetic-proof".getBytes(java.nio.charset.StandardCharsets.UTF_8); - insertClassificationProbe("ADMISSION", "UNKNOWN", null, null, null); - insertClassificationProbe("ADMISSION", "KNOWN", target, digest(target), null); - - assertRejectedClassificationProbe("ADMISSION", "UNKNOWN", target, digest(target), null); - assertRejectedClassificationProbe("ADMISSION", "KNOWN", target, null, null); - assertRejectedClassificationProbe("ADMISSION", "KNOWN", target, "0".repeat(64), null); - assertRejectedClassificationProbe("ADMISSION", "KNOWN", target, digest(target), proof); - assertRejectedClassificationProbe("TRANSFER", "KNOWN", target, digest(target), proof); - assertRejectedClassificationProbe( - "TRANSFER_RETIREMENT", "KNOWN", target, digest(target), null); - }); + "entity_canonical_roster_retired_targets"); + assertThat(liveChecks.getValues("definition", String.class)) + .anySatisfy(definition -> + assertThat(definition) + .contains("classification_state", "target_binding", "retirement_proof") + .doesNotContain("octet_length(retirement_proof)")); + assertProofBudget( + liveChecks, + "entity_canonical_roster_target_classifications", + "octet_length(retirement_proof)", + "203423744", + "131072"); + assertProofBudget( + liveChecks, + "entity_canonical_roster_snapshot_targets", + "octet_length(source_retirement_proof)", + "203423744", + "131072"); + assertProofBudget( + liveChecks, + "entity_canonical_roster_retired_targets", + "octet_length(owner_retirement_proof)", + "203423744"); + + // This clone inherits the actual latest-migration CHECKs. It contains synthetic bytes + // only: no source triggers or owner evidence are copied, so these probes prove storage + // shape constraints and do not qualify an authenticated source or retirement authority. + dsl.execute( + "CREATE TEMP TABLE roster_classification_constraint_probe " + + "(LIKE entity_canonical_roster_target_classifications INCLUDING CONSTRAINTS INCLUDING DEFAULTS) " + + "ON COMMIT DROP"); + byte[] target = "target-binding".getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] proof = "synthetic-proof".getBytes(java.nio.charset.StandardCharsets.UTF_8); + insertClassificationProbe("ADMISSION", "UNKNOWN", null, null, null); + insertClassificationProbe("ADMISSION", "KNOWN", target, digest(target), null); + + assertRejectedClassificationProbe("ADMISSION", "UNKNOWN", target, digest(target), null); + assertRejectedClassificationProbe("ADMISSION", "KNOWN", target, null, null); + assertRejectedClassificationProbe("ADMISSION", "KNOWN", target, "0".repeat(64), null); + assertRejectedClassificationProbe("ADMISSION", "KNOWN", target, digest(target), proof); + assertRejectedClassificationProbe("TRANSFER", "KNOWN", target, digest(target), proof); + assertRejectedClassificationProbe( + "TRANSFER_RETIREMENT", "KNOWN", target, digest(target), null); + }); } private void assertProofBudget( @@ -185,12 +182,11 @@ private void assertProofBudget( String columnExpression, String... bounds) { assertThat(checks) - .anySatisfy( - row -> { - assertThat(row.get("table_name", String.class)).isEqualTo(tableName); - String definition = row.get("definition", String.class); - assertThat(definition).contains(columnExpression).contains(bounds); - }); + .anySatisfy(row -> { + assertThat(row.get("table_name", String.class)).isEqualTo(tableName); + String definition = row.get("definition", String.class); + assertThat(definition).contains(columnExpression).contains(bounds); + }); } private void assertRejectedClassificationProbe( @@ -236,12 +232,11 @@ void retirementHealthStartsAfterStoredHorizonAndKeepsPayloadAndCleanupLag() { var snapshot = retainedSnapshot(); bindSnapshot(local, owner, snapshot); var candidate = transaction.execute(ignored -> repository.candidates(null, 1)).getFirst(); - transaction.executeWithoutResult( - ignored -> - assertThat( - repository.observeRetirement( - candidate, retirement(owner, snapshot), policy(Duration.ofSeconds(2)))) - .isTrue()); + transaction.executeWithoutResult(ignored -> + assertThat( + repository.observeRetirement( + candidate, retirement(owner, snapshot), policy(Duration.ofSeconds(2)))) + .isTrue()); assertThat( dsl.fetchSingle( @@ -303,10 +298,9 @@ void observedRetirementCommitsStableActualNoncesAndHeldSnapshotsCannotRemintTran retirement( candidate.ownerRequest().equals(firstOwner.getRequest()) ? firstOwner : secondOwner, snapshot); - transaction.executeWithoutResult( - ignored -> - assertThat(repository.observeRetirement(candidate, proof, policy(Duration.ofMillis(1)))) - .isTrue()); + transaction.executeWithoutResult(ignored -> + assertThat(repository.observeRetirement(candidate, proof, policy(Duration.ofMillis(1)))) + .isTrue()); var sealed = transaction.execute(ignored -> repository.candidates(null, 2)).getFirst(); assertThat(transaction.execute(ignored -> repository.prepareRetirement(sealed, 2))) @@ -317,42 +311,39 @@ void observedRetirementCommitsStableActualNoncesAndHeldSnapshotsCannotRemintTran var transfers = transaction.execute(ignored -> repository.retirementTransfers(null, 2)); assertThat(transfers).hasSize(2); assertThat(transfers) - .allSatisfy( - transfer -> { - assertThat(transfer.state()).isEqualTo("PENDING_ACK"); - var request = transfer.acknowledgementRequest(); - assertThat(request.getObservedRetirement()).isEqualTo(proof); - assertThat(request.getSnapshotUuid()).isEqualTo(snapshot.snapshotUuid().toString()); - assertThat(request.getSnapshotDigest()).isEqualTo(snapshot.snapshotDigest()); - UUID expectedNonce = - request - .getOriginalSelection() - .getOperationUuid() - .equals(first.requestUuid().toString()) - ? firstNonce - : secondNonce; - assertThat(request.getAdmissionUuid()).isEqualTo(expectedNonce.toString()); - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM entity_canonical_roster_retirement_transfers WHERE observation_uuid = ?", - transfer.observationUuid())) - .isInstanceOf(DataAccessException.class); - var acknowledgement = - CanonicalGameplayRosterRetirementEvidence.response(request, UUID.randomUUID(), 1); - transaction.executeWithoutResult( - ignored -> repository.recordRetirementAcknowledgement(transfer, acknowledgement)); - }); + .allSatisfy(transfer -> { + assertThat(transfer.state()).isEqualTo("PENDING_ACK"); + var request = transfer.acknowledgementRequest(); + assertThat(request.getObservedRetirement()).isEqualTo(proof); + assertThat(request.getSnapshotUuid()).isEqualTo(snapshot.snapshotUuid().toString()); + assertThat(request.getSnapshotDigest()).isEqualTo(snapshot.snapshotDigest()); + UUID expectedNonce = + request + .getOriginalSelection() + .getOperationUuid() + .equals(first.requestUuid().toString()) + ? firstNonce + : secondNonce; + assertThat(request.getAdmissionUuid()).isEqualTo(expectedNonce.toString()); + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM entity_canonical_roster_retirement_transfers WHERE observation_uuid = ?", + transfer.observationUuid())) + .isInstanceOf(DataAccessException.class); + var acknowledgement = + CanonicalGameplayRosterRetirementEvidence.response(request, UUID.randomUUID(), 1); + transaction.executeWithoutResult( + ignored -> repository.recordRetirementAcknowledgement(transfer, acknowledgement)); + }); for (var acknowledged : transaction.execute(ignored -> repository.retirementTransfers(null, 2))) { var confirmation = CanonicalGameplayRosterRetirementEvidence.confirmation( acknowledged.acknowledgementRequest(), acknowledged.acknowledgement()); - transaction.executeWithoutResult( - ignored -> - repository.recordRetirementConfirmation( - acknowledged, - CanonicalGameplayRosterRetirementEvidence.confirmationResponse(confirmation))); + transaction.executeWithoutResult(ignored -> + repository.recordRetirementConfirmation( + acknowledged, + CanonicalGameplayRosterRetirementEvidence.confirmationResponse(confirmation))); } dsl.fetch("SELECT pg_sleep(0.02)"); assertThat( @@ -361,10 +352,9 @@ void observedRetirementCommitsStableActualNoncesAndHeldSnapshotsCannotRemintTran .isZero(); var retired = transaction.execute(ignored -> repository.candidates(null, 2)).getFirst(); assertThat(transaction.execute(ignored -> repository.dispose(retired))).isFalse(); - transaction.executeWithoutResult( - ignored -> - assertThat(repository.observeRetirement(retired, proof, policy(Duration.ofHours(1)))) - .isTrue()); + transaction.executeWithoutResult(ignored -> + assertThat(repository.observeRetirement(retired, proof, policy(Duration.ofHours(1)))) + .isTrue()); assertThat( dsl.fetch("SELECT observation_uuid FROM entity_canonical_roster_retirement_transfers") .getValues(0, UUID.class)) @@ -373,17 +363,15 @@ void observedRetirementCommitsStableActualNoncesAndHeldSnapshotsCannotRemintTran assertThatThrownBy(() -> transaction.execute(ignored -> repository.reserveAdmission(first))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> repository.requireAdmission(second, secondNonce))) + assertThatThrownBy(() -> + transaction.executeWithoutResult( + ignored -> repository.requireAdmission(second, secondNonce))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE entity_canonical_roster_admissions SET snapshot_uuid = snapshot_uuid WHERE operation_uuid = ?", - first.requestUuid())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE entity_canonical_roster_admissions SET snapshot_uuid = snapshot_uuid WHERE operation_uuid = ?", + first.requestUuid())) .isInstanceOf(DataAccessException.class); } @@ -439,18 +427,16 @@ void forward1015To1016PreservesInstalledHistoryRetainedRowsAndOldSnapshotGuards( binding.snapshot().snapshotUuid()) .get(0, String.class)) .isEqualTo("PRESEEDED_ONLY"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE entity_canonical_gameplay_roster_snapshots SET canonical_player_created_source_identity = ? WHERE snapshot_uuid = ?", - new byte[] {1}, - binding.snapshot().snapshotUuid())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE entity_canonical_gameplay_roster_snapshots SET canonical_player_created_source_identity = ? WHERE snapshot_uuid = ?", + new byte[] {1}, + binding.snapshot().snapshotUuid())) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM entity_canonical_gameplay_roster_snapshots WHERE snapshot_uuid = ?", - binding.snapshot().snapshotUuid())) + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM entity_canonical_gameplay_roster_snapshots WHERE snapshot_uuid = ?", + binding.snapshot().snapshotUuid())) .isInstanceOf(DataAccessException.class); assertThatThrownBy( () -> dsl.execute("TRUNCATE entity_canonical_gameplay_roster_snapshots CASCADE")) @@ -481,10 +467,9 @@ void createdAdmissionAndOriginalRecoveryKeepExactSourceAndDistinctReceiptBranch( assertThatThrownBy(() -> transaction.execute(ignored -> repository.reserveAdmission(changed))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_REQUEST_CONFLICT"); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> repository.requireAdmission(changed, nonce))) + assertThatThrownBy(() -> + transaction.executeWithoutResult( + ignored -> repository.requireAdmission(changed, nonce))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); var invalidPolicy = request.toBuilder().setExpectedTarget(binding.target().toWire()).build(); @@ -496,27 +481,25 @@ void createdAdmissionAndOriginalRecoveryKeepExactSourceAndDistinctReceiptBranch( CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( original, 1, UUID.randomUUID(), null); var receipt = createdReceipt(request); - transaction.executeWithoutResult( - ignored -> { - assertThat(repository.originalPlayerCreatedReceipt(owner)).isEmpty(); - repository.requireAdmission(request, nonce); - seedCreatedSnapshot(receipt, 0); - repository.bindPlayerCreatedOriginal(owner, receipt); - repository.bindAdmission( - UUID.fromString(request.getRequestUuid()), - nonce, - UUID.fromString(receipt.getRoster().getSnapshotUuid())); - assertThat(repository.originalPlayerCreatedReceipt(owner)).contains(receipt); - }); + transaction.executeWithoutResult(ignored -> { + assertThat(repository.originalPlayerCreatedReceipt(owner)).isEmpty(); + repository.requireAdmission(request, nonce); + seedCreatedSnapshot(receipt, 0); + repository.bindPlayerCreatedOriginal(owner, receipt); + repository.bindAdmission( + UUID.fromString(request.getRequestUuid()), + nonce, + UUID.fromString(receipt.getRoster().getSnapshotUuid())); + assertThat(repository.originalPlayerCreatedReceipt(owner)).contains(receipt); + }); assertThatThrownBy(() -> transaction.execute(ignored -> repository.originalReceipt(owner))) .isInstanceOf(IllegalArgumentException.class); var wrongSourceOwner = CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( createdOriginal(changed), 1, UUID.fromString(owner.getTargetFenceUuid()), null); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> repository.originalPlayerCreatedReceipt(wrongSourceOwner))) + assertThatThrownBy(() -> + transaction.execute( + ignored -> repository.originalPlayerCreatedReceipt(wrongSourceOwner))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_ORIGINAL_REQUEST_CONFLICT"); var recovery = @@ -527,16 +510,14 @@ void createdAdmissionAndOriginalRecoveryKeepExactSourceAndDistinctReceiptBranch( .build(); var recovering = owner.toBuilder().setRecoveryUuid(recovery.getRecoveryUuid()).build(); var closed = - transaction.execute( - ignored -> - repository.closeAdmission(recovery, recovering, policy(Duration.ofHours(1)))); + transaction.execute(ignored -> + repository.closeAdmission(recovery, recovering, policy(Duration.ofHours(1)))); assertThat(closed.getAdmissionUuid()).isEqualTo(nonce.toString()); assertThat(closed.getCanonicalRosterReceipt()).isEmpty(); assertThat(closed.getCanonicalPlayerCreatedRosterReceipt()).isEqualTo(receipt.toByteString()); var replay = - transaction.execute( - ignored -> - repository.closeAdmission(recovery, recovering, policy(Duration.ofHours(2)))); + transaction.execute(ignored -> + repository.closeAdmission(recovery, recovering, policy(Duration.ofHours(2)))); assertThat(replay).isEqualTo(closed); var stored = dsl.fetchSingle( @@ -546,25 +527,22 @@ void createdAdmissionAndOriginalRecoveryKeepExactSourceAndDistinctReceiptBranch( assertThat(stored.get("canonical_roster_receipt", byte[].class)).isNull(); assertThat(stored.get("canonical_player_created_roster_receipt", byte[].class)) .isEqualTo(receipt.toByteArray()); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE entity_canonical_gameplay_roster_snapshots SET canonical_player_created_source_identity = ? WHERE snapshot_uuid = ?", - changed.getExpectedSource().toByteArray(), - UUID.fromString(receipt.getRoster().getSnapshotUuid()))) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE entity_canonical_gameplay_roster_snapshots SET canonical_player_created_source_identity = ? WHERE snapshot_uuid = ?", + changed.getExpectedSource().toByteArray(), + UUID.fromString(receipt.getRoster().getSnapshotUuid()))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE entity_canonical_roster_admissions SET entry_policy = 'PRESEEDED_ONLY' WHERE operation_uuid = ?", - UUID.fromString(request.getRequestUuid()))) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE entity_canonical_roster_admissions SET entry_policy = 'PRESEEDED_ONLY' WHERE operation_uuid = ?", + UUID.fromString(request.getRequestUuid()))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE entity_canonical_roster_original_selections SET canonical_roster_receipt = ? WHERE operation_uuid = ?", - receipt.getRoster().toByteArray(), - UUID.fromString(request.getRequestUuid()))) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE entity_canonical_roster_original_selections SET canonical_roster_receipt = ? WHERE operation_uuid = ?", + receipt.getRoster().toByteArray(), + UUID.fromString(request.getRequestUuid()))) .isInstanceOf(DataAccessException.class); } @@ -572,11 +550,9 @@ void createdAdmissionAndOriginalRecoveryKeepExactSourceAndDistinctReceiptBranch( void createdSnapshotRequiresSharedSourceAndRejectsPreseededActorSubstitution() { var request = createdRequest(); var receipt = createdReceipt(request); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - seedCreatedSnapshot(receipt.toBuilder().clearSourceIdentity().build(), 0))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + seedCreatedSnapshot(receipt.toBuilder().clearSourceIdentity().build(), 0))) .isInstanceOf(DataAccessException.class); var oversized = receipt.toBuilder() @@ -604,18 +580,16 @@ void createdSnapshotRequiresSharedSourceAndRejectsPreseededActorSubstitution() { "SELECT character_uuid FROM entity_canonical_gameplay_roster_snapshot_actors WHERE snapshot_uuid = ?", binding.snapshot().snapshotUuid()) .get(0, UUID.class); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO entity_canonical_gameplay_roster_snapshot_actors (snapshot_uuid, ordinal_position, character_uuid, display_name, actor_kind) VALUES (?, 0, ?, 'Retained Actor', 'PLAYER')", - UUID.fromString(receipt.getRoster().getSnapshotUuid()), - actor)) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO entity_canonical_gameplay_roster_snapshot_actors (snapshot_uuid, ordinal_position, character_uuid, display_name, actor_kind) VALUES (?, 0, ?, 'Retained Actor', 'PLAYER')", + UUID.fromString(receipt.getRoster().getSnapshotUuid()), + actor)) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE entity_canonical_gameplay_roster_snapshots SET construction_state = 'SEALED' WHERE snapshot_uuid = ?", - UUID.fromString(receipt.getRoster().getSnapshotUuid()))) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE entity_canonical_gameplay_roster_snapshots SET construction_state = 'SEALED' WHERE snapshot_uuid = ?", + UUID.fromString(receipt.getRoster().getSnapshotUuid()))) .isInstanceOf(DataAccessException.class); } @@ -628,25 +602,23 @@ void createdRetirementPreservesFullSourceThroughOutboxAndKeepsPreseededFamilyPro original, 1, UUID.randomUUID(), null); var receipt = createdReceipt(request); UUID nonce = transaction.execute(ignored -> repository.reserveAdmission(request)); - transaction.executeWithoutResult( - ignored -> { - repository.requireAdmission(request, nonce); - seedCreatedSnapshot(receipt, 0); - repository.bindPlayerCreatedOriginal(owner, receipt); - repository.bindAdmission( - UUID.fromString(request.getRequestUuid()), - nonce, - UUID.fromString(receipt.getRoster().getSnapshotUuid())); - }); + transaction.executeWithoutResult(ignored -> { + repository.requireAdmission(request, nonce); + seedCreatedSnapshot(receipt, 0); + repository.bindPlayerCreatedOriginal(owner, receipt); + repository.bindAdmission( + UUID.fromString(request.getRequestUuid()), + nonce, + UUID.fromString(receipt.getRoster().getSnapshotUuid())); + }); var recorded = CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( original, 1, UUID.fromString(owner.getTargetFenceUuid()), receipt); var proof = retirement(recorded, null); var candidate = transaction.execute(ignored -> repository.candidates(null, 1)).getFirst(); - transaction.executeWithoutResult( - ignored -> - assertThat(repository.observeRetirement(candidate, proof, policy(Duration.ofMillis(1)))) - .isTrue()); + transaction.executeWithoutResult(ignored -> + assertThat(repository.observeRetirement(candidate, proof, policy(Duration.ofMillis(1)))) + .isTrue()); var beforePreparation = transaction.execute(ignored -> repository.retirementTransfers(null, 1)); assertThat(beforePreparation).isEmpty(); assertThat(preparePage(1)).isEqualTo(1); @@ -717,57 +689,45 @@ void createdOutboxStorageBudgetDoesNotWidenPreseededOrAuthenticateOpaqueBytes() .toBuilder() .setRecoveryUuid(createdRecovery.getRecoveryUuid()) .build(); - transaction.executeWithoutResult( - ignored -> - repository.closeAdmission(createdRecovery, createdOwner, policy(Duration.ofHours(1)))); + transaction.executeWithoutResult(ignored -> + repository.closeAdmission(createdRecovery, createdOwner, policy(Duration.ofHours(1)))); var preseeded = localRequest(); var preseededRecovery = recovery(preseeded); var preseededOwner = recoveryOwner(preseededRecovery); - transaction.executeWithoutResult( - ignored -> - repository.closeAdmission( - preseededRecovery, preseededOwner, policy(Duration.ofHours(1)))); + transaction.executeWithoutResult(ignored -> + repository.closeAdmission(preseededRecovery, preseededOwner, policy(Duration.ofHours(1)))); byte[] rawRequest = new byte[128 * 1024 + 1]; - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - insertRawTransferForBudget( - preseeded.requestUuid(), retirement(preseededOwner, null), rawRequest))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + insertRawTransferForBudget( + preseeded.requestUuid(), retirement(preseededOwner, null), rawRequest))) .isInstanceOf(DataAccessException.class) .hasMessageContaining("ck_entity_roster_transfer_policy_request"); // Raw SQL tests only the policy-specific byte budget. Opaque request bytes remain invalid // to the repository's value parser and never become authenticated acknowledgement authority. - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> { - insertRawTransferForBudget( - UUID.fromString(created.getRequestUuid()), - retirement(createdOwner, null), - rawRequest); - assertThat( - dsl.fetchCount( - DSL.table("entity_canonical_roster_retirement_transfers"))) - .isEqualTo(1); - UUID malformedObservation = - dsl.fetchSingle( - "SELECT observation_uuid FROM entity_canonical_roster_retirement_transfers") - .get(0, UUID.class); - var malformed = repository.retirementTransfers(null, 1); - assertThat(malformed).hasSize(1); - assertThat(malformed.getFirst().observationUuid()) - .isEqualTo(malformedObservation); - assertThat(malformed.getFirst().valid()).isFalse(); - assertThat(malformed.getFirst().original()).isNull(); - assertThat(malformed.getFirst().acknowledgementRequest()).isNull(); - assertThat(malformed.getFirst().acknowledgement()).isNull(); - assertThat( - dsl.fetchCount( - DSL.table("entity_canonical_roster_retirement_transfers"))) - .isEqualTo(1); - throw new IllegalStateException("controlled byte-budget rollback"); - })) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> { + insertRawTransferForBudget( + UUID.fromString(created.getRequestUuid()), + retirement(createdOwner, null), + rawRequest); + assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_retirement_transfers"))) + .isEqualTo(1); + UUID malformedObservation = + dsl.fetchSingle( + "SELECT observation_uuid FROM entity_canonical_roster_retirement_transfers") + .get(0, UUID.class); + var malformed = repository.retirementTransfers(null, 1); + assertThat(malformed).hasSize(1); + assertThat(malformed.getFirst().observationUuid()).isEqualTo(malformedObservation); + assertThat(malformed.getFirst().valid()).isFalse(); + assertThat(malformed.getFirst().original()).isNull(); + assertThat(malformed.getFirst().acknowledgementRequest()).isNull(); + assertThat(malformed.getFirst().acknowledgement()).isNull(); + assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_retirement_transfers"))) + .isEqualTo(1); + throw new IllegalStateException("controlled byte-budget rollback"); + })) .hasMessage("controlled byte-budget rollback"); assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_retirement_transfers"))).isZero(); } @@ -820,10 +780,9 @@ void malformedOriginalPageKeepsItsKeyAndPassesLaterSnapshotWithoutChangingSource void malformedRecoveryAndTransferPagesPassLaterRowsAndKeepInvalidSources() { for (int index = 0; index < 2; index++) { var recovery = recovery(localRequest()); - transaction.executeWithoutResult( - ignored -> - repository.closeAdmission( - recovery, recoveryOwner(recovery), policy(Duration.ofMillis(1)))); + transaction.executeWithoutResult(ignored -> + repository.closeAdmission( + recovery, recoveryOwner(recovery), policy(Duration.ofMillis(1)))); } var closures = transaction.execute(ignored -> repository.closedAdmissionCandidates(null, 2)); var bad = closures.getFirst(); @@ -837,33 +796,29 @@ void malformedRecoveryAndTransferPagesPassLaterRowsAndKeepInvalidSources() { assertThat(firstClosure.operationUuid()).isEqualTo(bad.operationUuid()); assertThat( transaction - .execute( - ignored -> - repository.closedAdmissionCandidates(firstClosure.operationUuid(), 1)) + .execute(ignored -> + repository.closedAdmissionCandidates(firstClosure.operationUuid(), 1)) .getFirst() .valid()) .isTrue(); // Explicit inconsistent-restore fixtures: production never disables immutable source guards. - transaction.executeWithoutResult( - ignored -> { - dsl.execute( - "ALTER TABLE entity_canonical_roster_retirement_transfers DISABLE TRIGGER USER"); - for (int index = 0; index < closures.size(); index++) { - var closure = closures.get(index); - var response = closure.response(); - dsl.execute( - "INSERT INTO entity_canonical_roster_retirement_transfers (observation_uuid, operation_uuid, original_request, admission_uuid, closed_admission_receipt, owner_fence, target_fence_uuid, minimum_retention_millis, transfer_state) VALUES (?, ?, ?, ?, ?, ?, ?, 1, 'WAITING_RETIREMENT')", - new UUID(0, index + 1), - closure.operationUuid(), - response.getRequest().getOriginalSelection().toByteArray(), - closure.admissionUuid(), - response.toByteArray(), - response.getOwnerFence(), - UUID.fromString(response.getTargetFenceUuid())); - } - dsl.execute( - "ALTER TABLE entity_canonical_roster_retirement_transfers ENABLE TRIGGER USER"); - }); + transaction.executeWithoutResult(ignored -> { + dsl.execute("ALTER TABLE entity_canonical_roster_retirement_transfers DISABLE TRIGGER USER"); + for (int index = 0; index < closures.size(); index++) { + var closure = closures.get(index); + var response = closure.response(); + dsl.execute( + "INSERT INTO entity_canonical_roster_retirement_transfers (observation_uuid, operation_uuid, original_request, admission_uuid, closed_admission_receipt, owner_fence, target_fence_uuid, minimum_retention_millis, transfer_state) VALUES (?, ?, ?, ?, ?, ?, ?, 1, 'WAITING_RETIREMENT')", + new UUID(0, index + 1), + closure.operationUuid(), + response.getRequest().getOriginalSelection().toByteArray(), + closure.admissionUuid(), + response.toByteArray(), + response.getOwnerFence(), + UUID.fromString(response.getTargetFenceUuid())); + } + dsl.execute("ALTER TABLE entity_canonical_roster_retirement_transfers ENABLE TRIGGER USER"); + }); corruptRestoredBytes( "entity_canonical_roster_retirement_transfers", "original_request", bad.operationUuid()); String retainedTransfer = @@ -914,87 +869,79 @@ void conflictingTransferRemainsProtectedWhileDurablePreparationCursorPassesIt() .findFirst() .orElseThrow(); var sealedProof = retirement(anchor, snapshot); - transaction.executeWithoutResult( - ignored -> - repository.observeRetirement(candidate, sealedProof, policy(Duration.ofMillis(1)))); + transaction.executeWithoutResult(ignored -> + repository.observeRetirement(candidate, sealedProof, policy(Duration.ofMillis(1)))); UUID bad = UUID.fromString(candidate.ownerRequest().getOperationUuid()); var operations = dsl.fetch( "SELECT operation_uuid FROM entity_canonical_roster_original_selections ORDER BY operation_uuid") .getValues(0, UUID.class); // Explicit inconsistent restore: nonce, positive proof and ACK intent conflicts stay protected. - transaction.executeWithoutResult( - ignored -> { + transaction.executeWithoutResult(ignored -> { + dsl.execute("ALTER TABLE entity_canonical_roster_retirement_transfers DISABLE TRIGGER USER"); + for (int index = 0; index < 4; index++) { + UUID operation = operations.get(index); + var original = + owners.stream() + .filter(owner -> owner.getRequest().getOperationUuid().equals(operation.toString())) + .findFirst() + .orElseThrow() + .getRequest(); + UUID actualNonce = + dsl.fetchSingle( + "SELECT admission_uuid FROM entity_canonical_roster_admissions WHERE operation_uuid = ?", + operation) + .get(0, UUID.class); + UUID observation = new UUID(0, index + 1); + if (index == 0 || index == 3) { + // The fourth original is a qualified WAITING carrier and must promote before release. dsl.execute( - "ALTER TABLE entity_canonical_roster_retirement_transfers DISABLE TRIGGER USER"); - for (int index = 0; index < 4; index++) { - UUID operation = operations.get(index); - var original = - owners.stream() - .filter( - owner -> owner.getRequest().getOperationUuid().equals(operation.toString())) - .findFirst() - .orElseThrow() - .getRequest(); - UUID actualNonce = - dsl.fetchSingle( - "SELECT admission_uuid FROM entity_canonical_roster_admissions WHERE operation_uuid = ?", - operation) - .get(0, UUID.class); - UUID observation = new UUID(0, index + 1); - if (index == 0 || index == 3) { - // The fourth original is a qualified WAITING carrier and must promote before release. - dsl.execute( - "INSERT INTO entity_canonical_roster_retirement_transfers (observation_uuid, operation_uuid, original_request, admission_uuid, snapshot_uuid, snapshot_digest, owner_fence, target_fence_uuid, minimum_retention_millis, transfer_state) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, 'WAITING_RETIREMENT')", - observation, - operation, - original.toByteArray(), - index == 0 ? UUID.randomUUID() : actualNonce, - snapshot.snapshotUuid(), - snapshot.snapshotDigest(), - sealedProof.getOwnerFence(), - UUID.fromString(sealedProof.getTargetFenceUuid())); - } else { - var observed = index == 1 ? retirement(anchor, snapshot) : sealedProof; - var intent = - net.firedevops.firemud.gamesession.v1 - .CanonicalGameplayRosterRetirementAcknowledgementRequest.newBuilder() - .setSchemaVersion(1) - .setOriginalSelection(original) - .setObservedRetirement(observed) - .setObservationUuid(observation.toString()) - .setAdmissionUuid((index == 2 ? UUID.randomUUID() : actualNonce).toString()) - .setSnapshotUuid(snapshot.snapshotUuid().toString()) - .setSnapshotDigest(snapshot.snapshotDigest()) - .setMinimumRetentionMillis(1) - .build(); - CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement(intent); - dsl.execute( - "INSERT INTO entity_canonical_roster_retirement_transfers (observation_uuid, operation_uuid, original_request, admission_uuid, snapshot_uuid, snapshot_digest, owner_fence, target_fence_uuid, minimum_retention_millis, transfer_state, observed_retirement, acknowledgement_request, request_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, 'PENDING_ACK', ?, ?, ?)", - observation, - operation, - original.toByteArray(), - actualNonce, - snapshot.snapshotUuid(), - snapshot.snapshotDigest(), - sealedProof.getOwnerFence(), - UUID.fromString(sealedProof.getTargetFenceUuid()), - observed.toByteArray(), - intent.toByteArray(), - CanonicalGameplayRosterRetirementEvidence.requestDigest(intent)); - } - } + "INSERT INTO entity_canonical_roster_retirement_transfers (observation_uuid, operation_uuid, original_request, admission_uuid, snapshot_uuid, snapshot_digest, owner_fence, target_fence_uuid, minimum_retention_millis, transfer_state) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, 'WAITING_RETIREMENT')", + observation, + operation, + original.toByteArray(), + index == 0 ? UUID.randomUUID() : actualNonce, + snapshot.snapshotUuid(), + snapshot.snapshotDigest(), + sealedProof.getOwnerFence(), + UUID.fromString(sealedProof.getTargetFenceUuid())); + } else { + var observed = index == 1 ? retirement(anchor, snapshot) : sealedProof; + var intent = + net.firedevops.firemud.gamesession.v1 + .CanonicalGameplayRosterRetirementAcknowledgementRequest.newBuilder() + .setSchemaVersion(1) + .setOriginalSelection(original) + .setObservedRetirement(observed) + .setObservationUuid(observation.toString()) + .setAdmissionUuid((index == 2 ? UUID.randomUUID() : actualNonce).toString()) + .setSnapshotUuid(snapshot.snapshotUuid().toString()) + .setSnapshotDigest(snapshot.snapshotDigest()) + .setMinimumRetentionMillis(1) + .build(); + CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement(intent); dsl.execute( - "ALTER TABLE entity_canonical_roster_retirement_transfers ENABLE TRIGGER USER"); - }); + "INSERT INTO entity_canonical_roster_retirement_transfers (observation_uuid, operation_uuid, original_request, admission_uuid, snapshot_uuid, snapshot_digest, owner_fence, target_fence_uuid, minimum_retention_millis, transfer_state, observed_retirement, acknowledgement_request, request_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, 'PENDING_ACK', ?, ?, ?)", + observation, + operation, + original.toByteArray(), + actualNonce, + snapshot.snapshotUuid(), + snapshot.snapshotDigest(), + sealedProof.getOwnerFence(), + UUID.fromString(sealedProof.getTargetFenceUuid()), + observed.toByteArray(), + intent.toByteArray(), + CanonicalGameplayRosterRetirementEvidence.requestDigest(intent)); + } + } + dsl.execute("ALTER TABLE entity_canonical_roster_retirement_transfers ENABLE TRIGGER USER"); + }); var protectedSources = operations.subList(0, 3).stream() - .map( - operation -> - pageSourceRow( - "entity_canonical_roster_retirement_transfers", - "operation_uuid", - operation)) + .map(operation -> + pageSourceRow( + "entity_canonical_roster_retirement_transfers", "operation_uuid", operation)) .toList(); String source = pageSourceRow("entity_canonical_roster_original_selections", "operation_uuid", bad); @@ -1033,12 +980,11 @@ void conflictingTransferRemainsProtectedWhileDurablePreparationCursorPassesIt() .isEqualTo(transfer); assertThat( operations.subList(0, 3).stream() - .map( - operation -> - pageSourceRow( - "entity_canonical_roster_retirement_transfers", - "operation_uuid", - operation)) + .map(operation -> + pageSourceRow( + "entity_canonical_roster_retirement_transfers", + "operation_uuid", + operation)) .toList()) .containsExactlyElementsOf(protectedSources); assertThat( @@ -1051,15 +997,14 @@ void conflictingTransferRemainsProtectedWhileDurablePreparationCursorPassesIt() private void corruptRestoredBytes(String table, String column, UUID operation) { // Explicit inconsistent-restore fixture; source immutability remains enabled in production. - transaction.executeWithoutResult( - ignored -> { - dsl.execute("ALTER TABLE " + table + " DISABLE TRIGGER USER"); - dsl.execute( - "UPDATE " + table + " SET " + column + " = ? WHERE operation_uuid = ?", - new byte[] {(byte) 0x80}, - operation); - dsl.execute("ALTER TABLE " + table + " ENABLE TRIGGER USER"); - }); + transaction.executeWithoutResult(ignored -> { + dsl.execute("ALTER TABLE " + table + " DISABLE TRIGGER USER"); + dsl.execute( + "UPDATE " + table + " SET " + column + " = ? WHERE operation_uuid = ?", + new byte[] {(byte) 0x80}, + operation); + dsl.execute("ALTER TABLE " + table + " ENABLE TRIGGER USER"); + }); } private String pageSourceRow(String table, String key, UUID value) { @@ -1077,12 +1022,11 @@ private String pageSourceRow(String table, String key, UUID value) { void typedOnlySnapshotRecognitionReportsEveryBoundedPageBeforeDrainingToZero() { int pageSize = 2; int snapshotCount = 5; - transaction.executeWithoutResult( - ignored -> { - for (int index = 0; index < snapshotCount; index++) { - seedCreatedSnapshot(createdReceipt(createdRequest()), 0); - } - }); + transaction.executeWithoutResult(ignored -> { + for (int index = 0; index < snapshotCount; index++) { + seedCreatedSnapshot(createdReceipt(createdRequest()), 0); + } + }); // Sealing captures V1 inventory through the existing SQL trigger; only typed recognition is // pending. assertThat( @@ -1151,22 +1095,19 @@ void boundedTargetClassificationPassesTrueUnknownAndKeepsEveryAdmissionBoundaryC laterKnownAccount, target(), UUID.fromString("00000000-0000-4000-8000-000000000002")); UUID unknownNonce = transaction.execute(ignored -> repository.reserveAdmission(unknownLocal)); UUID knownNonce = transaction.execute(ignored -> repository.reserveAdmission(laterKnownLocal)); - transaction.executeWithoutResult( - ignored -> - dsl.execute( - "ALTER TABLE entity_canonical_roster_target_classifications DISABLE TRIGGER USER")); + transaction.executeWithoutResult(ignored -> + dsl.execute( + "ALTER TABLE entity_canonical_roster_target_classifications DISABLE TRIGGER USER")); try { - transaction.executeWithoutResult( - ignored -> - dsl.execute( - "DELETE FROM entity_canonical_roster_target_classifications WHERE source_kind = 'ADMISSION' AND operation_uuid IN (?, ?)", - unknownLocal.requestUuid(), - laterKnownLocal.requestUuid())); + transaction.executeWithoutResult(ignored -> + dsl.execute( + "DELETE FROM entity_canonical_roster_target_classifications WHERE source_kind = 'ADMISSION' AND operation_uuid IN (?, ?)", + unknownLocal.requestUuid(), + laterKnownLocal.requestUuid())); } finally { - transaction.executeWithoutResult( - ignored -> - dsl.execute( - "ALTER TABLE entity_canonical_roster_target_classifications ENABLE TRIGGER USER")); + transaction.executeWithoutResult(ignored -> + dsl.execute( + "ALTER TABLE entity_canonical_roster_target_classifications ENABLE TRIGGER USER")); } corruptRestoredBytes( "entity_canonical_roster_admissions", "request_binding", unknownLocal.requestUuid()); @@ -1234,10 +1175,9 @@ void sameTargetSiblingSealsReplayIndependentlyAfterRepositoryReconstruction() { binding.snapshot().snapshotUuid()) .get(0, Long.class)) .isEqualTo(1L); - transaction.executeWithoutResult( - ignored -> - repository.acquire( - binding, classificationOperation, classificationHold, ReferenceKind.RECOVERY)); + transaction.executeWithoutResult(ignored -> + repository.acquire( + binding, classificationOperation, classificationHold, ReferenceKind.RECOVERY)); transaction.executeWithoutResult( ignored -> repository.release(binding, UUID.randomUUID(), classificationHold)); @@ -1292,17 +1232,15 @@ void sameTargetSiblingSealsReplayIndependentlyAfterRepositoryReconstruction() { .isEqualTo(secondSnapshot.toWire().toByteString()); assertThat( - transaction.execute( - ignored -> - repository.observeRetirement( - firstCandidate, firstProof, policy(Duration.ofMillis(1))))) + transaction.execute(ignored -> + repository.observeRetirement( + firstCandidate, firstProof, policy(Duration.ofMillis(1))))) .isTrue(); repository = new CanonicalGameplayRosterRetentionRepository(dsl); assertThat( - transaction.execute( - ignored -> - repository.observeRetirement( - secondCandidate, secondProof, policy(Duration.ofMillis(1))))) + transaction.execute(ignored -> + repository.observeRetirement( + secondCandidate, secondProof, policy(Duration.ofMillis(1))))) .as("a reconstructed owner repository accepts the sibling's separate exact seal") .isTrue(); repository = new CanonicalGameplayRosterRetentionRepository(dsl); @@ -1318,17 +1256,15 @@ secondCandidate, secondProof, policy(Duration.ofMillis(1))))) .findFirst() .orElseThrow(); assertThat( - transaction.execute( - ignored -> - repository.observeRetirement( - replayFirst, firstProof, policy(Duration.ofMillis(1))))) + transaction.execute(ignored -> + repository.observeRetirement( + replayFirst, firstProof, policy(Duration.ofMillis(1))))) .as("lost-reply replay at the current epoch returns the first sibling's persisted result") .isTrue(); assertThat( - transaction.execute( - ignored -> - repository.observeRetirement( - replaySecond, secondProof, policy(Duration.ofMillis(1))))) + transaction.execute(ignored -> + repository.observeRetirement( + replaySecond, secondProof, policy(Duration.ofMillis(1))))) .as("lost-reply replay at the current epoch returns the second sibling's persisted result") .isTrue(); assertThat( @@ -1364,12 +1300,10 @@ void retainedProtectedInventoryAndImmutableRowsSurviveUpgradeThenRetireNormally( classifyAllRetainedSources(); assertThat(immutableRetentionRows()).containsExactlyElementsOf(legacy); var candidate = transaction.execute(ignored -> repository.candidates(null, 1)).getFirst(); - transaction.executeWithoutResult( - ignored -> - assertThat( - repository.observeRetirement( - candidate, legacyProof, policy(Duration.ofMillis(1)))) - .isTrue()); + transaction.executeWithoutResult(ignored -> + assertThat( + repository.observeRetirement(candidate, legacyProof, policy(Duration.ofMillis(1)))) + .isTrue()); assertThat(preparePage(1)).isEqualTo(1); assertThat(preparePage(1)).isEqualTo(1); } @@ -1384,14 +1318,11 @@ void retainedRetiredProofAndPartialIntentInitializeAtomicallyWithoutOwnerRead() .isEqualTo(1L); classifyAllRetainedSources(); var candidate = transaction.execute(ignored -> repository.candidates(null, 1)).getFirst(); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> { - assertThat(repository.initializeRetainedRetirement(candidate)).isTrue(); - throw new IllegalStateException( - "controlled retained initialization rollback"); - })) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> { + assertThat(repository.initializeRetainedRetirement(candidate)).isTrue(); + throw new IllegalStateException("controlled retained initialization rollback"); + })) .isInstanceOf(IllegalStateException.class); assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_retired_targets"))).isZero(); assertThat(immutableRetentionRows()).containsExactlyElementsOf(legacy); @@ -1474,11 +1405,10 @@ private void assertRetainedDisposedLineage(boolean alreadyPurged) { var confirmation = CanonicalGameplayRosterRetirementEvidence.confirmation( acknowledged.acknowledgementRequest(), acknowledged.acknowledgement()); - transaction.executeWithoutResult( - ignored -> - repository.recordRetirementConfirmation( - acknowledged, - CanonicalGameplayRosterRetirementEvidence.confirmationResponse(confirmation))); + transaction.executeWithoutResult(ignored -> + repository.recordRetirementConfirmation( + acknowledged, + CanonicalGameplayRosterRetirementEvidence.confirmationResponse(confirmation))); dsl.fetch("SELECT pg_sleep(0.02)"); assertThat( transaction.execute( @@ -1488,11 +1418,9 @@ private void assertRetainedDisposedLineage(boolean alreadyPurged) { assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_target_classifications"))) .isZero(); var old = legacyRequests.getFirst(); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.requireAdmission(old, legacyNonces.get(old.requestUuid())))) + assertThatThrownBy(() -> + transaction.executeWithoutResult( + ignored -> repository.requireAdmission(old, legacyNonces.get(old.requestUuid())))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); } @@ -1514,13 +1442,11 @@ void malformedRetainedBindingIsDurableUnknownAndCannotStarveLaterClassification( legacyAdmissionBinding(local)); } var before = immutableRetentionRows(); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> { - assertThat(repository.classifyRetainedDependencies(2)).isEqualTo(2); - throw new IllegalStateException("controlled classification rollback"); - })) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> { + assertThat(repository.classifyRetainedDependencies(2)).isEqualTo(2); + throw new IllegalStateException("controlled classification rollback"); + })) .isInstanceOf(IllegalStateException.class); assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_target_classifications"))) .isZero(); @@ -1544,18 +1470,16 @@ void malformedRetainedBindingIsDurableUnknownAndCannotStarveLaterClassification( () -> transaction.execute(ignored -> repository.reserveAdmission(localRequest()))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM entity_canonical_roster_target_classifications WHERE operation_uuid = ?", - bad)) + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM entity_canonical_roster_target_classifications WHERE operation_uuid = ?", + bad)) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE entity_canonical_roster_target_classifications SET source_binding = ? WHERE operation_uuid = ?", - new byte[] {2}, - bad)) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE entity_canonical_roster_target_classifications SET source_binding = ? WHERE operation_uuid = ?", + new byte[] {2}, + bad)) .isInstanceOf(DataAccessException.class); } @@ -1565,28 +1489,24 @@ void immutableAcquireReleaseAndHoldOutcomesNeverGrantTerminality() { UUID reference = UUID.randomUUID(); UUID hold = UUID.randomUUID(); UUID releaseOperation = UUID.randomUUID(); - transaction.executeWithoutResult( - ignored -> { - repository.acquire( - binding, acquireOperation, reference, ReferenceKind.ORIGINAL_SELECTION); - repository.acquire( - binding, acquireOperation, reference, ReferenceKind.ORIGINAL_SELECTION); - repository.acquire(binding, UUID.randomUUID(), hold, ReferenceKind.HOLD); - assertThat(repository.protection(binding).liveReferences()).isEqualTo(1); - assertThat(repository.protection(binding).holds()).isEqualTo(1); - repository.release(binding, releaseOperation, reference); - repository.release(binding, releaseOperation, reference); - assertThat(repository.protection(binding).liveReferences()).isZero(); - assertThat(repository.protection(binding).holds()).isEqualTo(1); - assertThat(repository.protection(binding).disposalEligible()).isFalse(); - repository.release(binding, UUID.randomUUID(), hold); - var zeroReferences = repository.protection(binding); - assertThat(zeroReferences.liveReferences()).isZero(); - assertThat(zeroReferences.holds()).isZero(); - assertThat(zeroReferences.terminality()) - .isEqualTo("AUTHENTICATED_SUPERSESSION_UNAVAILABLE"); - assertThat(zeroReferences.disposalEligible()).isFalse(); - }); + transaction.executeWithoutResult(ignored -> { + repository.acquire(binding, acquireOperation, reference, ReferenceKind.ORIGINAL_SELECTION); + repository.acquire(binding, acquireOperation, reference, ReferenceKind.ORIGINAL_SELECTION); + repository.acquire(binding, UUID.randomUUID(), hold, ReferenceKind.HOLD); + assertThat(repository.protection(binding).liveReferences()).isEqualTo(1); + assertThat(repository.protection(binding).holds()).isEqualTo(1); + repository.release(binding, releaseOperation, reference); + repository.release(binding, releaseOperation, reference); + assertThat(repository.protection(binding).liveReferences()).isZero(); + assertThat(repository.protection(binding).holds()).isEqualTo(1); + assertThat(repository.protection(binding).disposalEligible()).isFalse(); + repository.release(binding, UUID.randomUUID(), hold); + var zeroReferences = repository.protection(binding); + assertThat(zeroReferences.liveReferences()).isZero(); + assertThat(zeroReferences.holds()).isZero(); + assertThat(zeroReferences.terminality()).isEqualTo("AUTHENTICATED_SUPERSESSION_UNAVAILABLE"); + assertThat(zeroReferences.disposalEligible()).isFalse(); + }); List retained = retainedRows(); for (String table : List.of( @@ -1600,11 +1520,10 @@ void immutableAcquireReleaseAndHoldOutcomesNeverGrantTerminality() { assertThatThrownBy(() -> dsl.execute("TRUNCATE " + table + " CASCADE")) .isInstanceOf(DataAccessException.class); } - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE entity_canonical_roster_retention_lifecycle " - + "SET lifecycle_state = 'RETIRED'")) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE entity_canonical_roster_retention_lifecycle " + + "SET lifecycle_state = 'RETIRED'")) .isInstanceOf(DataAccessException.class); assertThat(retainedRows()).containsExactlyElementsOf(retained); } @@ -1613,21 +1532,16 @@ void immutableAcquireReleaseAndHoldOutcomesNeverGrantTerminality() { void staleTargetFenceUnknownReferenceAndIdentityReuseFailClosed() { UUID acquireOperation = UUID.randomUUID(); UUID reference = UUID.randomUUID(); - transaction.executeWithoutResult( - ignored -> - repository.acquire(binding, acquireOperation, reference, ReferenceKind.RECOVERY)); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.acquire( - binding, UUID.randomUUID(), reference, ReferenceKind.RECOVERY))) + transaction.executeWithoutResult(ignored -> + repository.acquire(binding, acquireOperation, reference, ReferenceKind.RECOVERY)); + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + repository.acquire(binding, UUID.randomUUID(), reference, ReferenceKind.RECOVERY))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_REFERENCE_IDEMPOTENCY_CONFLICT"); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> repository.release(binding, UUID.randomUUID(), UUID.randomUUID()))) + assertThatThrownBy(() -> + transaction.executeWithoutResult( + ignored -> repository.release(binding, UUID.randomUUID(), UUID.randomUUID()))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_REFERENCE_UNAVAILABLE"); var old = binding.target(); @@ -1649,13 +1563,11 @@ void staleTargetFenceUnknownReferenceAndIdentityReuseFailClosed() { old.playableStateNamespaceId(), old.playableStateScope(), old.entryPolicy()); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.protection( - new CanonicalGameplayRosterRetentionBinding( - binding.canonicalAccountUuid(), binding.snapshot(), stale)))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + repository.protection( + new CanonicalGameplayRosterRetentionBinding( + binding.canonicalAccountUuid(), binding.snapshot(), stale)))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_RETENTION_TARGET_MISMATCH"); assertThatThrownBy(() -> repository.protection(binding)) @@ -1666,18 +1578,15 @@ void staleTargetFenceUnknownReferenceAndIdentityReuseFailClosed() { @Test void rollbackPreservesActorReceiptSnapshotAndDoesNotReleaseAReference() { UUID reference = UUID.randomUUID(); - transaction.executeWithoutResult( - ignored -> - repository.acquire( - binding, UUID.randomUUID(), reference, ReferenceKind.ORIGINAL_SELECTION)); + transaction.executeWithoutResult(ignored -> + repository.acquire( + binding, UUID.randomUUID(), reference, ReferenceKind.ORIGINAL_SELECTION)); List retained = retainedRows(); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> { - repository.release(binding, UUID.randomUUID(), reference); - throw new IllegalStateException("controlled rollback"); - })) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> { + repository.release(binding, UUID.randomUUID(), reference); + throw new IllegalStateException("controlled rollback"); + })) .isInstanceOf(IllegalStateException.class); transaction.executeWithoutResult( ignored -> assertThat(repository.protection(binding).liveReferences()).isEqualTo(1)); @@ -1694,48 +1603,41 @@ void concurrentAcquisitionRemainsAtomicWhileDirectDisposalIsRefused() throws Exc CountDownLatch inspected = new CountDownLatch(1); try (var executor = Executors.newFixedThreadPool(2)) { var acquire = - executor.submit( - () -> - transaction.executeWithoutResult( - ignored -> { - repository.acquire( - binding, UUID.randomUUID(), UUID.randomUUID(), ReferenceKind.RECOVERY); - acquired.countDown(); - await(inspected); - })); + executor.submit(() -> + transaction.executeWithoutResult(ignored -> { + repository.acquire( + binding, UUID.randomUUID(), UUID.randomUUID(), ReferenceKind.RECOVERY); + acquired.countDown(); + await(inspected); + })); var dispose = - executor.submit( - () -> { - await(acquired); - try { - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> { - dsl.execute("SET LOCAL lock_timeout = '500ms'"); - dsl.execute( - "DELETE FROM entity_canonical_gameplay_roster_snapshots " - + "WHERE snapshot_uuid = ?", - binding.snapshot().snapshotUuid()); - })) - .isInstanceOf(DataAccessException.class); - } finally { - inspected.countDown(); - } - }); + executor.submit(() -> { + await(acquired); + try { + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> { + dsl.execute("SET LOCAL lock_timeout = '500ms'"); + dsl.execute( + "DELETE FROM entity_canonical_gameplay_roster_snapshots " + + "WHERE snapshot_uuid = ?", + binding.snapshot().snapshotUuid()); + })) + .isInstanceOf(DataAccessException.class); + } finally { + inspected.countDown(); + } + }); acquire.get(15, TimeUnit.SECONDS); dispose.get(15, TimeUnit.SECONDS); } - transaction.executeWithoutResult( - ignored -> { - assertThat(repository.protection(binding).liveReferences()).isEqualTo(1); - assertThat(repository.protection(binding).disposalEligible()).isFalse(); - }); - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM entity_canonical_gameplay_roster_snapshots WHERE snapshot_uuid = ?", - binding.snapshot().snapshotUuid())) + transaction.executeWithoutResult(ignored -> { + assertThat(repository.protection(binding).liveReferences()).isEqualTo(1); + assertThat(repository.protection(binding).disposalEligible()).isFalse(); + }); + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM entity_canonical_gameplay_roster_snapshots WHERE snapshot_uuid = ?", + binding.snapshot().snapshotUuid())) .isInstanceOf(DataAccessException.class); } @@ -1754,46 +1656,36 @@ void closedNonceRejectsDelayedBindingAndExactRecoveryReplayIsImmutable() { transaction . - execute( - ignored -> - repository.closeAdmission( - recovery, owner, policy(Duration.ofHours(2))))) + execute(ignored -> + repository.closeAdmission(recovery, owner, policy(Duration.ofHours(2))))) .isEqualTo(response); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> repository.requireAdmission(local, nonce))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> repository.requireAdmission(local, nonce))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.bindAdmission( - local.requestUuid(), nonce, binding.snapshot().snapshotUuid()))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + repository.bindAdmission( + local.requestUuid(), nonce, binding.snapshot().snapshotUuid()))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); assertThatThrownBy(() -> transaction.execute(ignored -> repository.reserveAdmission(local))) .isInstanceOf(IllegalStateException.class); var conflict = recovery.toBuilder().setRecoveryUuid(UUID.randomUUID().toString()).build(); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> - repository.closeAdmission( - conflict, recoveryOwner(conflict), policy(Duration.ofHours(1))))) + assertThatThrownBy(() -> + transaction.execute(ignored -> + repository.closeAdmission( + conflict, recoveryOwner(conflict), policy(Duration.ofHours(1))))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_RECOVERY_CONFLICT"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE entity_canonical_roster_admissions SET admission_state = 'OPEN', closed_at = NULL, minimum_retention_millis = NULL")) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE entity_canonical_roster_admissions SET admission_state = 'OPEN', closed_at = NULL, minimum_retention_millis = NULL")) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE entity_canonical_roster_admissions SET recovery_response = ?", - new byte[] {1})) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE entity_canonical_roster_admissions SET recovery_response = ?", + new byte[] {1})) .isInstanceOf(DataAccessException.class); assertThatThrownBy(() -> dsl.execute("DELETE FROM entity_canonical_roster_admissions")) .isInstanceOf(DataAccessException.class); @@ -1811,11 +1703,9 @@ void openAdmissionRejectsOwnerReceiptWithoutLocalOriginalAndPreservesAdmissionBy .contains("\"admission_state\":\"OPEN\"") .contains("\"recovery_response\":null"); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> - repository.closeAdmission(recovery, owner, policy(Duration.ofHours(1))))) + assertThatThrownBy(() -> + transaction.execute( + ignored -> repository.closeAdmission(recovery, owner, policy(Duration.ofHours(1))))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_ORIGINAL_LOCAL_RECEIPT_UNAVAILABLE"); @@ -1830,11 +1720,9 @@ void provisionalAdmissionInsertRollsBackWhenOwnerReceiptHasNoLocalOriginal() { assertThat(owner.getCanonicalRosterReceipt()).isNotEmpty(); assertThat(admissionCount(local.requestUuid())).isZero(); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> - repository.closeAdmission(recovery, owner, policy(Duration.ofHours(1))))) + assertThatThrownBy(() -> + transaction.execute( + ignored -> repository.closeAdmission(recovery, owner, policy(Duration.ofHours(1))))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_ORIGINAL_LOCAL_RECEIPT_UNAVAILABLE"); @@ -1871,11 +1759,9 @@ void createdOpenAdmissionPreservesBytesAndXminWhenOwnerReceiptIsUnavailableLocal .contains("\"admission_state\":\"OPEN\"") .contains("\"recovery_response\":null"); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> - repository.closeAdmission(recovery, owner, policy(Duration.ofHours(1))))) + assertThatThrownBy(() -> + transaction.execute( + ignored -> repository.closeAdmission(recovery, owner, policy(Duration.ofHours(1))))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_ORIGINAL_LOCAL_RECEIPT_UNAVAILABLE"); @@ -1909,11 +1795,9 @@ void createdProvisionalAdmissionInsertRollsBackWhenOwnerReceiptHasNoLocalOrigina UUID operation = UUID.fromString(request.getRequestUuid()); assertThat(admissionCount(operation)).isZero(); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> - repository.closeAdmission(recovery, owner, policy(Duration.ofHours(1))))) + assertThatThrownBy(() -> + transaction.execute( + ignored -> repository.closeAdmission(recovery, owner, policy(Duration.ofHours(1))))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_ORIGINAL_LOCAL_RECEIPT_UNAVAILABLE"); @@ -1937,33 +1821,25 @@ void closedUnboundAdmissionRequiresExactPositiveOwnerAcknowledgementAndLocalHori .isFalse(); assertThatThrownBy(() -> dsl.execute("DELETE FROM entity_canonical_roster_admissions")) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> - repository.purgeClosedAdmission( - candidate, - owner.toBuilder() - .setRecoveryUuid(UUID.randomUUID().toString()) - .setTerminalOutcome("DENIED") - .build()))) + assertThatThrownBy(() -> + transaction.execute(ignored -> + repository.purgeClosedAdmission( + candidate, + owner.toBuilder() + .setRecoveryUuid(UUID.randomUUID().toString()) + .setTerminalOutcome("DENIED") + .build()))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> - repository.purgeClosedAdmission( - candidate, - owner.toBuilder() - .setOwnerFence(2) - .setTerminalOutcome("DENIED") - .build()))) + assertThatThrownBy(() -> + transaction.execute(ignored -> + repository.purgeClosedAdmission( + candidate, + owner.toBuilder().setOwnerFence(2).setTerminalOutcome("DENIED").build()))) .isInstanceOf(IllegalStateException.class); assertThat( - transaction.execute( - ignored -> - repository.purgeClosedAdmission( - candidate, owner.toBuilder().setTerminalOutcome("DENIED").build()))) + transaction.execute(ignored -> + repository.purgeClosedAdmission( + candidate, owner.toBuilder().setTerminalOutcome("DENIED").build()))) .isTrue(); assertThat( transaction @@ -1973,10 +1849,9 @@ void closedUnboundAdmissionRequiresExactPositiveOwnerAcknowledgementAndLocalHori assertThatThrownBy(() -> transaction.execute(ignored -> repository.reserveAdmission(local))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> repository.requireAdmission(local, candidate.admissionUuid()))) + assertThatThrownBy(() -> + transaction.executeWithoutResult( + ignored -> repository.requireAdmission(local, candidate.admissionUuid()))) .isInstanceOf(IllegalStateException.class); assertThat(retainedRows()).hasSize(4); @@ -1988,10 +1863,9 @@ void closedUnboundAdmissionRequiresExactPositiveOwnerAcknowledgementAndLocalHori var held = transaction.execute(ignored -> repository.closedAdmissionCandidates(null, 1)).getFirst(); assertThat( - transaction.execute( - ignored -> - repository.purgeClosedAdmission( - held, heldOwner.toBuilder().setTerminalOutcome("DENIED").build()))) + transaction.execute(ignored -> + repository.purgeClosedAdmission( + held, heldOwner.toBuilder().setTerminalOutcome("DENIED").build()))) .isFalse(); } @@ -2031,16 +1905,13 @@ void longerEntityClosureHorizonPreventsEarlyTransferEvenWhenOwnerAlreadyRetired( .isInstanceOf(DataAccessException.class); dsl.fetch("SELECT pg_sleep(3.1)"); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> { - assertThat(repository.purgeClosedAdmission(candidate, retired)).isTrue(); - assertThat(repository.retirementTransfers(null, 1)).hasSize(1); - assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_admissions"))) - .isZero(); - throw new IllegalStateException("controlled transfer/purge rollback"); - })) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> { + assertThat(repository.purgeClosedAdmission(candidate, retired)).isTrue(); + assertThat(repository.retirementTransfers(null, 1)).hasSize(1); + assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_admissions"))).isZero(); + throw new IllegalStateException("controlled transfer/purge rollback"); + })) .hasMessage("controlled transfer/purge rollback"); assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_admissions"))).isEqualTo(1); assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_retirement_transfers"))).isZero(); @@ -2078,20 +1949,18 @@ void qualifiedDisposalExtendsClosedAdmissionRetentionWhenRetirementHorizonIncrea binding.snapshot().snapshotDigest(), binding.target(), List.of(new CanonicalGameplayRosterActor(actor, "Retained Actor"))); - transaction.executeWithoutResult( - ignored -> { - repository.requireAdmission(local, nonce); - repository.bindOriginal(owner, snapshot); - repository.bindAdmission(local.requestUuid(), nonce, snapshot.snapshotUuid()); - }); + transaction.executeWithoutResult(ignored -> { + repository.requireAdmission(local, nonce); + repository.bindOriginal(owner, snapshot); + repository.bindAdmission(local.requestUuid(), nonce, snapshot.snapshotUuid()); + }); var closed = transaction.execute( ignored -> repository.closeAdmission(recovery, owner, policy(Duration.ofMillis(1)))); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE entity_canonical_roster_admissions SET minimum_retention_millis = 2 WHERE operation_uuid = ?", - local.requestUuid())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE entity_canonical_roster_admissions SET minimum_retention_millis = 2 WHERE operation_uuid = ?", + local.requestUuid())) .isInstanceOf(DataAccessException.class); var proof = CanonicalGameplayRosterReferenceEvidence.sealRetirement( @@ -2110,10 +1979,9 @@ void qualifiedDisposalExtendsClosedAdmissionRetentionWhenRetirementHorizonIncrea var protectedCandidate = transaction.execute(ignored -> repository.candidates(null, 1)).getFirst(); assertThat( - transaction.execute( - ignored -> - repository.observeRetirement( - protectedCandidate, proof, policy(Duration.ofMillis(20))))) + transaction.execute(ignored -> + repository.observeRetirement( + protectedCandidate, proof, policy(Duration.ofMillis(20))))) .isTrue(); assertThat(preparePage(2)).isEqualTo(1); dsl.fetch("SELECT pg_sleep(0.03)"); @@ -2161,11 +2029,10 @@ void retirementSealPreparesMoreThanOnePageWhileHoldProtectsPayloadAndReplayKeeps var late = localRequest(); UUID lateNonce = transaction.execute(ignored -> repository.reserveAdmission(late)); UUID hold = UUID.randomUUID(); - transaction.executeWithoutResult( - ignored -> { - repository.acquire(binding, UUID.randomUUID(), hold, ReferenceKind.HOLD); - repository.acquire(binding, UUID.randomUUID(), UUID.randomUUID(), ReferenceKind.RECOVERY); - }); + transaction.executeWithoutResult(ignored -> { + repository.acquire(binding, UUID.randomUUID(), hold, ReferenceKind.HOLD); + repository.acquire(binding, UUID.randomUUID(), UUID.randomUUID(), ReferenceKind.RECOVERY); + }); var candidate = transaction.execute(ignored -> repository.candidates(null, 1)).getFirst(); var anchor = owners.stream() @@ -2173,41 +2040,35 @@ void retirementSealPreparesMoreThanOnePageWhileHoldProtectsPayloadAndReplayKeeps .findFirst() .orElseThrow(); var proof = retirement(anchor, snapshot); - transaction.executeWithoutResult( - ignored -> - assertThat(repository.observeRetirement(candidate, proof, policy(Duration.ofMillis(1)))) - .isTrue()); + transaction.executeWithoutResult(ignored -> + assertThat(repository.observeRetirement(candidate, proof, policy(Duration.ofMillis(1)))) + .isTrue()); assertThat( transaction .>execute( ignored -> repository.retirementTransfers(null, 10))) .isEmpty(); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> repository.requireAdmission(late, lateNonce))) + assertThatThrownBy(() -> + transaction.executeWithoutResult( + ignored -> repository.requireAdmission(late, lateNonce))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); assertThatThrownBy( () -> transaction.execute(ignored -> repository.reserveAdmission(localRequest()))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.acquire( - binding, UUID.randomUUID(), UUID.randomUUID(), ReferenceKind.RECOVERY))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + repository.acquire( + binding, UUID.randomUUID(), UUID.randomUUID(), ReferenceKind.RECOVERY))) .isInstanceOf(IllegalStateException.class); var sealedCandidate = transaction.execute(ignored -> repository.candidates(null, 1)).getFirst(); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> { - assertThat(repository.prepareRetirement(sealedCandidate, 2)).isEqualTo(2); - throw new IllegalStateException("controlled page rollback"); - })) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> { + assertThat(repository.prepareRetirement(sealedCandidate, 2)).isEqualTo(2); + throw new IllegalStateException("controlled page rollback"); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("controlled page rollback"); assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_retirement_transfers"))).isZero(); @@ -2218,24 +2079,21 @@ void retirementSealPreparesMoreThanOnePageWhileHoldProtectsPayloadAndReplayKeeps new CanonicalGameplayRosterSnapshotReference( UUID.randomUUID(), binding.snapshot().snapshotDigest()), binding.target()); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.acquire( - alternate, - UUID.randomUUID(), - UUID.randomUUID(), - ReferenceKind.ORIGINAL_SELECTION))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + repository.acquire( + alternate, + UUID.randomUUID(), + UUID.randomUUID(), + ReferenceKind.ORIGINAL_SELECTION))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); assertThat(preparePage(2)).isEqualTo(2); var firstPage = transaction.execute(ignored -> repository.retirementTransfers(null, 10)); assertThat(firstPage).hasSize(2); var stale = transaction.execute(ignored -> repository.candidates(null, 1)).getFirst(); - transaction.executeWithoutResult( - ignored -> - repository.acquire(binding, UUID.randomUUID(), UUID.randomUUID(), ReferenceKind.HOLD)); + transaction.executeWithoutResult(ignored -> + repository.acquire(binding, UUID.randomUUID(), UUID.randomUUID(), ReferenceKind.HOLD)); assertThat(transaction.execute(ignored -> repository.prepareRetirement(stale, 2))) .isZero(); assertThat(transaction.execute(ignored -> repository.dispose(stale))).isFalse(); @@ -2245,16 +2103,14 @@ void retirementSealPreparesMoreThanOnePageWhileHoldProtectsPayloadAndReplayKeeps var transfers = transaction.execute(ignored -> repository.retirementTransfers(null, 10)); assertThat(transfers) .hasSize(5) - .allSatisfy( - transfer -> { - var request = transfer.acknowledgementRequest(); - assertThat(request.getObservedRetirement()).isEqualTo(proof); - assertThat(request.getAdmissionUuid()) - .isEqualTo( - nonces.get(request.getOriginalSelection().getOperationUuid()).toString()); - assertThat(request.getSnapshotUuid()).isEqualTo(snapshot.snapshotUuid().toString()); - assertThat(request.getSnapshotDigest()).isEqualTo(snapshot.snapshotDigest()); - }); + .allSatisfy(transfer -> { + var request = transfer.acknowledgementRequest(); + assertThat(request.getObservedRetirement()).isEqualTo(proof); + assertThat(request.getAdmissionUuid()) + .isEqualTo(nonces.get(request.getOriginalSelection().getOperationUuid()).toString()); + assertThat(request.getSnapshotUuid()).isEqualTo(snapshot.snapshotUuid().toString()); + assertThat(request.getSnapshotDigest()).isEqualTo(snapshot.snapshotDigest()); + }); assertThat(preparePage(2)).isZero(); assertThat(preparePage(2)).isZero(); assertThat( @@ -2274,11 +2130,10 @@ void retirementSealPreparesMoreThanOnePageWhileHoldProtectsPayloadAndReplayKeeps var confirmation = CanonicalGameplayRosterRetirementEvidence.confirmation( transfer.acknowledgementRequest(), transfer.acknowledgement()); - transaction.executeWithoutResult( - ignored -> - repository.recordRetirementConfirmation( - transfer, - CanonicalGameplayRosterRetirementEvidence.confirmationResponse(confirmation))); + transaction.executeWithoutResult(ignored -> + repository.recordRetirementConfirmation( + transfer, + CanonicalGameplayRosterRetirementEvidence.confirmationResponse(confirmation))); } dsl.fetch("SELECT pg_sleep(0.02)"); assertThat( @@ -2302,10 +2157,9 @@ void concurrentHoldWaitsForPreparationThenInvalidatesItsEpochAndProtectsFinalDis var snapshot = retainedSnapshot(); bindSnapshot(local, owner, snapshot); var candidate = transaction.execute(ignored -> repository.candidates(null, 1)).getFirst(); - transaction.executeWithoutResult( - ignored -> - repository.observeRetirement( - candidate, retirement(owner, snapshot), policy(Duration.ofMillis(1)))); + transaction.executeWithoutResult(ignored -> + repository.observeRetirement( + candidate, retirement(owner, snapshot), policy(Duration.ofMillis(1)))); var sealed = transaction.execute(ignored -> repository.candidates(null, 1)).getFirst(); var preparationPid = new java.util.concurrent.atomic.AtomicInteger(); var holdPid = new java.util.concurrent.atomic.AtomicInteger(); @@ -2314,28 +2168,23 @@ void concurrentHoldWaitsForPreparationThenInvalidatesItsEpochAndProtectsFinalDis CountDownLatch allowCommit = new CountDownLatch(1); try (var executor = Executors.newFixedThreadPool(2)) { var preparation = - executor.submit( - () -> - transaction.executeWithoutResult( - ignored -> { - preparationPid.set( - dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); - assertThat(repository.prepareRetirement(sealed, 2)).isEqualTo(1); - prepared.countDown(); - await(allowCommit); - })); + executor.submit(() -> + transaction.executeWithoutResult(ignored -> { + preparationPid.set( + dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + assertThat(repository.prepareRetirement(sealed, 2)).isEqualTo(1); + prepared.countDown(); + await(allowCommit); + })); await(prepared); var hold = - executor.submit( - () -> - transaction.executeWithoutResult( - ignored -> { - holdPid.set( - dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); - holdStarted.countDown(); - repository.acquire( - binding, UUID.randomUUID(), UUID.randomUUID(), ReferenceKind.HOLD); - })); + executor.submit(() -> + transaction.executeWithoutResult(ignored -> { + holdPid.set(dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + holdStarted.countDown(); + repository.acquire( + binding, UUID.randomUUID(), UUID.randomUUID(), ReferenceKind.HOLD); + })); await(holdStarted); try { awaitBackendBlockedBy(holdPid.get(), preparationPid.get()); @@ -2380,19 +2229,17 @@ void missingAdmissionCannotCompleteAndDoesNotStarveLaterOriginalPages() { .filter(owner -> owner.getRequest().equals(candidate.ownerRequest())) .findFirst() .orElseThrow(); - transaction.executeWithoutResult( - ignored -> - repository.observeRetirement( - candidate, retirement(anchor, snapshot), policy(Duration.ofMillis(1)))); + transaction.executeWithoutResult(ignored -> + repository.observeRetirement( + candidate, retirement(anchor, snapshot), policy(Duration.ofMillis(1)))); UUID missing = UUID.fromString(candidate.ownerRequest().getOperationUuid()); // Controlled restore inconsistency: missing rows are not positive completion evidence. - transaction.executeWithoutResult( - ignored -> { - dsl.execute("ALTER TABLE entity_canonical_roster_admissions DISABLE TRIGGER USER"); - dsl.execute( - "DELETE FROM entity_canonical_roster_admissions WHERE operation_uuid = ?", missing); - dsl.execute("ALTER TABLE entity_canonical_roster_admissions ENABLE TRIGGER USER"); - }); + transaction.executeWithoutResult(ignored -> { + dsl.execute("ALTER TABLE entity_canonical_roster_admissions DISABLE TRIGGER USER"); + dsl.execute( + "DELETE FROM entity_canonical_roster_admissions WHERE operation_uuid = ?", missing); + dsl.execute("ALTER TABLE entity_canonical_roster_admissions ENABLE TRIGGER USER"); + }); assertThat(preparePage(2)).isEqualTo(1); repository = new CanonicalGameplayRosterRetentionRepository(dsl); assertThat(preparePage(2)).isEqualTo(2); @@ -2406,28 +2253,23 @@ void missingAdmissionCannotCompleteAndDoesNotStarveLaterOriginalPages() { assertThat(transaction.execute(ignored -> repository.dispose(incomplete))).isFalse(); // Even after losing that original and releasing its orphaned local reference, the stored // positive inventory count prevents absence from becoming completion. - transaction.executeWithoutResult( - ignored -> { - dsl.execute( - "ALTER TABLE entity_canonical_roster_original_selections DISABLE TRIGGER USER"); - dsl.execute( - "DELETE FROM entity_canonical_roster_original_selections WHERE operation_uuid = ?", - missing); - dsl.execute( - "ALTER TABLE entity_canonical_roster_original_selections ENABLE TRIGGER USER"); - repository.release(binding, UUID.randomUUID(), missing); - }); + transaction.executeWithoutResult(ignored -> { + dsl.execute("ALTER TABLE entity_canonical_roster_original_selections DISABLE TRIGGER USER"); + dsl.execute( + "DELETE FROM entity_canonical_roster_original_selections WHERE operation_uuid = ?", + missing); + dsl.execute("ALTER TABLE entity_canonical_roster_original_selections ENABLE TRIGGER USER"); + repository.release(binding, UUID.randomUUID(), missing); + }); dsl.fetch("SELECT pg_sleep(0.02)"); var missingOriginal = transaction.execute(ignored -> repository.candidates(null, 1)).getFirst(); assertThat(transaction.execute(ignored -> repository.dispose(missingOriginal))) .isFalse(); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - dsl.execute( - "UPDATE entity_canonical_roster_retention_lifecycle SET lifecycle_state = 'DISPOSING', local_epoch = local_epoch + 1 WHERE snapshot_uuid = ?", - snapshot.snapshotUuid()))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + dsl.execute( + "UPDATE entity_canonical_roster_retention_lifecycle SET lifecycle_state = 'DISPOSING', local_epoch = local_epoch + 1 WHERE snapshot_uuid = ?", + snapshot.snapshotUuid()))) .isInstanceOf(DataAccessException.class); } @@ -2477,23 +2319,17 @@ void missingAdmissionCannotCompleteAndDoesNotStarveLaterOriginalPages() { var acknowledgement = CanonicalGameplayRosterRetirementEvidence.response( retried.acknowledgementRequest(), UUID.randomUUID(), 2000); - transaction.executeWithoutResult( - ignored -> - assertThat(repository.recordRetirementAcknowledgement(retried, acknowledgement)) - .isTrue()); + transaction.executeWithoutResult(ignored -> + assertThat(repository.recordRetirementAcknowledgement(retried, acknowledgement)).isTrue()); // A lost ACK reply reuses the exact persisted request and response; a changed ACK conflicts. - transaction.executeWithoutResult( - ignored -> - assertThat(repository.recordRetirementAcknowledgement(retried, acknowledgement)) - .isFalse()); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.recordRetirementAcknowledgement( - retried, - CanonicalGameplayRosterRetirementEvidence.response( - retried.acknowledgementRequest(), UUID.randomUUID(), 2000)))) + transaction.executeWithoutResult(ignored -> + assertThat(repository.recordRetirementAcknowledgement(retried, acknowledgement)).isFalse()); + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + repository.recordRetirementAcknowledgement( + retried, + CanonicalGameplayRosterRetirementEvidence.response( + retried.acknowledgementRequest(), UUID.randomUUID(), 2000)))) .isInstanceOf(IllegalStateException.class); repository = new CanonicalGameplayRosterRetentionRepository(dsl); var acknowledged = @@ -2512,13 +2348,10 @@ void missingAdmissionCannotCompleteAndDoesNotStarveLaterOriginalPages() { "entity_canonical_roster_retirement_transfers", "observation_uuid", acknowledged.observationUuid()); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.recordRetirementConfirmation( - acknowledged, - confirmed.toBuilder().setRequestDigest("0".repeat(64)).build()))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + repository.recordRetirementConfirmation( + acknowledged, confirmed.toBuilder().setRequestDigest("0".repeat(64)).build()))) .isInstanceOf(IllegalArgumentException.class); var changedRequest = acknowledged.acknowledgementRequest().toBuilder().setSnapshotDigest("0".repeat(64)).build(); @@ -2529,11 +2362,9 @@ void missingAdmissionCannotCompleteAndDoesNotStarveLaterOriginalPages() { acknowledged.original(), changedRequest, acknowledged.acknowledgement()); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.recordRetirementConfirmation(changedCandidate, confirmed))) + assertThatThrownBy(() -> + transaction.executeWithoutResult( + ignored -> repository.recordRetirementConfirmation(changedCandidate, confirmed))) .isInstanceOf(IllegalArgumentException.class); assertThat( pageSourceRow( @@ -2541,12 +2372,10 @@ void missingAdmissionCannotCompleteAndDoesNotStarveLaterOriginalPages() { "observation_uuid", acknowledged.observationUuid())) .isEqualTo(retainedTransfer); - transaction.executeWithoutResult( - ignored -> - assertThat(repository.recordRetirementConfirmation(acknowledged, confirmed)).isTrue()); - transaction.executeWithoutResult( - ignored -> - assertThat(repository.recordRetirementConfirmation(acknowledged, confirmed)).isFalse()); + transaction.executeWithoutResult(ignored -> + assertThat(repository.recordRetirementConfirmation(acknowledged, confirmed)).isTrue()); + transaction.executeWithoutResult(ignored -> + assertThat(repository.recordRetirementConfirmation(acknowledged, confirmed)).isFalse()); assertThat( transaction.execute( ignored -> repository.purgeConfirmedRetirementTransfers(1))) @@ -2561,10 +2390,8 @@ void missingAdmissionCannotCompleteAndDoesNotStarveLaterOriginalPages() { .isEqualTo(1); assertThat(transaction.execute(ignored -> repository.purgeRetiredTargets(1))) .isEqualTo(1); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> repository.requireAdmission(local, nonce))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> repository.requireAdmission(local, nonce))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); } @@ -2595,10 +2422,9 @@ void deniedUnboundNonceLeavesExactWaitingIntentUntilIndependentPositiveRetiremen transaction.execute(ignored -> repository.retirementTransfers(null, 1)).getFirst(); assertThat(waiting.state()).isEqualTo("WAITING_RETIREMENT"); assertThat(waiting.acknowledgementRequest()).isNull(); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> repository.observeWaitingRetirement(waiting, denied))) + assertThatThrownBy(() -> + transaction.executeWithoutResult( + ignored -> repository.observeWaitingRetirement(waiting, denied))) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> transaction.execute(ignored -> repository.reserveAdmission(local))) .isInstanceOf(IllegalStateException.class); @@ -2639,38 +2465,31 @@ void committedObservationSerializesTheDelayedNonceAndDeniesCaptureAfterItsLockRe CountDownLatch allowCommit = new CountDownLatch(1); try (var executor = Executors.newFixedThreadPool(2)) { var observation = - executor.submit( - () -> - transaction.executeWithoutResult( - ignored -> { - observationPid.set( - dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); - assertThat( - repository.observeRetirement( - candidate, proof, policy(Duration.ofHours(1)))) - .isTrue(); - observed.countDown(); - await(allowCommit); - })); + executor.submit(() -> + transaction.executeWithoutResult(ignored -> { + observationPid.set( + dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + assertThat( + repository.observeRetirement(candidate, proof, policy(Duration.ofHours(1)))) + .isTrue(); + observed.countDown(); + await(allowCommit); + })); await(observed); var delayed = - executor.submit( - () -> - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> { - delayedPid.set( - dsl.fetchSingle("SELECT pg_backend_pid()") - .get(0, Integer.class)); - delayedStarted.countDown(); - repository.requireAdmission(local, nonce); - repository.bindOriginal(owner, snapshot); - repository.bindAdmission( - local.requestUuid(), nonce, snapshot.snapshotUuid()); - })) - .isInstanceOf(IllegalStateException.class) - .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED")); + executor.submit(() -> + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> { + delayedPid.set( + dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + delayedStarted.countDown(); + repository.requireAdmission(local, nonce); + repository.bindOriginal(owner, snapshot); + repository.bindAdmission( + local.requestUuid(), nonce, snapshot.snapshotUuid()); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED")); await(delayedStarted); try { awaitBackendBlockedBy(delayedPid.get(), observationPid.get()); @@ -2847,14 +2666,13 @@ private UUID bindSnapshot( CanonicalGameplayRosterReadRequest local, GetCanonicalGameplayRosterReferenceResponse owner, CanonicalGameplayRosterSnapshot snapshot) { - return transaction.execute( - ignored -> { - UUID nonce = repository.reserveAdmission(local); - repository.requireAdmission(local, nonce); - repository.bindOriginal(owner, snapshot); - repository.bindAdmission(local.requestUuid(), nonce, snapshot.snapshotUuid()); - return nonce; - }); + return transaction.execute(ignored -> { + UUID nonce = repository.reserveAdmission(local); + repository.requireAdmission(local, nonce); + repository.bindOriginal(owner, snapshot); + repository.bindAdmission(local.requestUuid(), nonce, snapshot.snapshotUuid()); + return nonce; + }); } private GetCanonicalGameplayRosterReferenceResponse retirement( @@ -2889,41 +2707,33 @@ void orphanCleanupRevokesOnlyExpiredUnboundOpenNonces() { UUID expiredNonce = insertAgedAdmission(expired, Duration.ofHours(2)); UUID boundNonce = insertAgedAdmission(bound, Duration.ofHours(2)); UUID freshNonce = transaction.execute(ignored -> repository.reserveAdmission(fresh)); - transaction.executeWithoutResult( - ignored -> - repository.bindAdmission( - bound.requestUuid(), boundNonce, binding.snapshot().snapshotUuid())); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE entity_canonical_roster_admissions SET admission_state = 'EXPIRED', minimum_retention_millis = 3600000 WHERE operation_uuid = ?", - fresh.requestUuid())) + transaction.executeWithoutResult(ignored -> + repository.bindAdmission( + bound.requestUuid(), boundNonce, binding.snapshot().snapshotUuid())); + assertThatThrownBy(() -> + dsl.execute( + "UPDATE entity_canonical_roster_admissions SET admission_state = 'EXPIRED', minimum_retention_millis = 3600000 WHERE operation_uuid = ?", + fresh.requestUuid())) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE entity_canonical_roster_admissions SET admission_state = 'EXPIRED', minimum_retention_millis = 3600000 WHERE operation_uuid = ?", - bound.requestUuid())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE entity_canonical_roster_admissions SET admission_state = 'EXPIRED', minimum_retention_millis = 3600000 WHERE operation_uuid = ?", + bound.requestUuid())) .isInstanceOf(DataAccessException.class); assertThat( transaction.execute( ignored -> repository.purgeOrphanOpenAdmissions(policy(Duration.ofHours(1)), 1))) .isEqualTo(1); - transaction.executeWithoutResult( - ignored -> { - repository.requireAdmission(fresh, freshNonce); - repository.requireAdmission(bound, boundNonce); - }); + transaction.executeWithoutResult(ignored -> { + repository.requireAdmission(fresh, freshNonce); + repository.requireAdmission(bound, boundNonce); + }); UUID newNonce = transaction.execute(ignored -> repository.reserveAdmission(expired)); assertThat(newNonce).isNotEqualTo(expiredNonce); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.bindAdmission( - expired.requestUuid(), - expiredNonce, - binding.snapshot().snapshotUuid()))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + repository.bindAdmission( + expired.requestUuid(), expiredNonce, binding.snapshot().snapshotUuid()))) .isInstanceOf(IllegalStateException.class); assertThat(retainedRows()).hasSize(4); } @@ -2956,42 +2766,39 @@ private void raceOrphanCleanupAndBind(boolean cleanupFirst) throws Exception { CountDownLatch allowCommit = new CountDownLatch(1); Runnable bind = () -> - transaction.executeWithoutResult( - ignored -> { - repository.requireAdmission(local, nonce); - repository.bindAdmission( - local.requestUuid(), nonce, binding.snapshot().snapshotUuid()); - if (!cleanupFirst) { - firstLocked.countDown(); - await(allowCommit); - } - }); + transaction.executeWithoutResult(ignored -> { + repository.requireAdmission(local, nonce); + repository.bindAdmission( + local.requestUuid(), nonce, binding.snapshot().snapshotUuid()); + if (!cleanupFirst) { + firstLocked.countDown(); + await(allowCommit); + } + }); Runnable cleanup = () -> - transaction.executeWithoutResult( - ignored -> { - assertThat(repository.purgeOrphanOpenAdmissions(policy(Duration.ofHours(1)), 1)) - .isEqualTo(cleanupFirst ? 1 : 0); - if (cleanupFirst) { - firstLocked.countDown(); - await(allowCommit); - } - }); + transaction.executeWithoutResult(ignored -> { + assertThat(repository.purgeOrphanOpenAdmissions(policy(Duration.ofHours(1)), 1)) + .isEqualTo(cleanupFirst ? 1 : 0); + if (cleanupFirst) { + firstLocked.countDown(); + await(allowCommit); + } + }); try (var executor = Executors.newFixedThreadPool(2)) { var first = executor.submit(cleanupFirst ? cleanup : bind); await(firstLocked); var second = - executor.submit( - () -> { - secondStarted.countDown(); - if (cleanupFirst) { - assertThatThrownBy(bind::run) - .isInstanceOf(IllegalStateException.class) - .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); - } else { - cleanup.run(); - } - }); + executor.submit(() -> { + secondStarted.countDown(); + if (cleanupFirst) { + assertThatThrownBy(bind::run) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); + } else { + cleanup.run(); + } + }); await(secondStarted); allowCommit.countDown(); first.get(15, TimeUnit.SECONDS); @@ -3034,42 +2841,38 @@ private void raceClosureAndBind(boolean closeFirst) throws Exception { CountDownLatch allowCommit = new CountDownLatch(1); Runnable bind = () -> - transaction.executeWithoutResult( - ignored -> { - repository.requireAdmission(local, nonce); - repository.bindOriginal(owner, snapshot); - repository.bindAdmission(local.requestUuid(), nonce, snapshot.snapshotUuid()); - if (!closeFirst) { - firstLocked.countDown(); - await(allowCommit); - } - }); + transaction.executeWithoutResult(ignored -> { + repository.requireAdmission(local, nonce); + repository.bindOriginal(owner, snapshot); + repository.bindAdmission(local.requestUuid(), nonce, snapshot.snapshotUuid()); + if (!closeFirst) { + firstLocked.countDown(); + await(allowCommit); + } + }); Runnable close = () -> - transaction.executeWithoutResult( - ignored -> { - response.set( - repository.closeAdmission(recovery, owner, policy(Duration.ofHours(1)))); - if (closeFirst) { - firstLocked.countDown(); - await(allowCommit); - } - }); + transaction.executeWithoutResult(ignored -> { + response.set(repository.closeAdmission(recovery, owner, policy(Duration.ofHours(1)))); + if (closeFirst) { + firstLocked.countDown(); + await(allowCommit); + } + }); try (var executor = Executors.newFixedThreadPool(2)) { var first = executor.submit(closeFirst ? close : bind); await(firstLocked); var second = - executor.submit( - () -> { - secondStarted.countDown(); - if (closeFirst) { - assertThatThrownBy(bind::run) - .isInstanceOf(IllegalStateException.class) - .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); - } else { - close.run(); - } - }); + executor.submit(() -> { + secondStarted.countDown(); + if (closeFirst) { + assertThatThrownBy(bind::run) + .isInstanceOf(IllegalStateException.class) + .hasMessage("CANONICAL_ROSTER_LOCAL_ADMISSION_FENCE_CLOSED"); + } else { + close.run(); + } + }); await(secondStarted); allowCommit.countDown(); first.get(15, TimeUnit.SECONDS); @@ -3083,12 +2886,11 @@ private void raceClosureAndBind(boolean closeFirst) throws Exception { assertThat(dsl.fetchCount(DSL.table("entity_canonical_roster_original_selections"))).isZero(); } else { assertThat(response.get().getCanonicalRosterReceipt()).isEqualTo(expected.toByteString()); - transaction.executeWithoutResult( - ignored -> { - assertThat(repository.originalReceipt(owner)).contains(expected); - assertThat(repository.protection(binding).liveReferences()).isEqualTo(1); - assertThat(repository.protection(binding).disposalEligible()).isFalse(); - }); + transaction.executeWithoutResult(ignored -> { + assertThat(repository.originalReceipt(owner)).contains(expected); + assertThat(repository.protection(binding).liveReferences()).isEqualTo(1); + assertThat(repository.protection(binding).disposalEligible()).isFalse(); + }); assertThat( transaction .> @@ -3424,19 +3226,18 @@ private List retainedRows() { "entity_canonical_gameplay_roster_snapshots", "entity_canonical_gameplay_roster_snapshot_actors") .stream() - .flatMap( - table -> - dsl - .fetch( - "SELECT (" - + predecessorRowProjection(table) - + ")::TEXT || ':' || t.xmin::TEXT FROM " - + table - + " t ORDER BY (" - + predecessorRowProjection(table) - + ")::TEXT") - .getValues(0, String.class) - .stream()) + .flatMap(table -> + dsl + .fetch( + "SELECT (" + + predecessorRowProjection(table) + + ")::TEXT || ':' || t.xmin::TEXT FROM " + + table + + " t ORDER BY (" + + predecessorRowProjection(table) + + ")::TEXT") + .getValues(0, String.class) + .stream()) .toList(); } @@ -3489,144 +3290,142 @@ private List rebuildLegacyCohort( var owners = new java.util.ArrayList(); UUID fence = UUID.randomUUID(); var snapshot = retainedSnapshot(); - transaction.executeWithoutResult( - ignored -> { + transaction.executeWithoutResult(ignored -> { + dsl.execute( + "INSERT INTO entity_canonical_roster_retention_lifecycle (snapshot_uuid, snapshot_digest) VALUES (?, ?)", + snapshot.snapshotUuid(), + snapshot.snapshotDigest()); + for (int index = 0; index < (disposed ? 1 : 2); index++) { + var local = localRequest(); + UUID nonce = UUID.randomUUID(); + var owner = + CanonicalGameplayRosterReferenceEvidence.response( + recovery(local).getOriginalSelection(), 1, fence, null); + legacyRequests.add(local); + legacyNonces.put(local.requestUuid(), nonce); + owners.add(owner); + dsl.execute( + "INSERT INTO entity_canonical_roster_admissions (operation_uuid, admission_uuid, request_binding, snapshot_uuid) VALUES (?, ?, ?, ?)", + local.requestUuid(), + nonce, + legacyAdmissionBinding(local), + snapshot.snapshotUuid()); + dsl.execute( + "INSERT INTO entity_canonical_roster_retention_references (reference_uuid, acquire_operation_uuid, snapshot_uuid, snapshot_digest, reference_kind) VALUES (?, ?, ?, ?, 'ORIGINAL_SELECTION')", + local.requestUuid(), + local.requestUuid(), + snapshot.snapshotUuid(), + snapshot.snapshotDigest()); + dsl.execute( + "INSERT INTO entity_canonical_roster_original_selections (operation_uuid, owner_request, owner_fence, owner_target_fence_uuid, snapshot_uuid, snapshot_digest, canonical_roster_receipt) VALUES (?, ?, ?, ?, ?, ?, ?)", + local.requestUuid(), + owner.getRequest().toByteArray(), + 1, + fence, + snapshot.snapshotUuid(), + snapshot.snapshotDigest(), + snapshot.toWire().toByteArray()); + } + UUID anchor = + dsl.fetchSingle( + "SELECT operation_uuid FROM entity_canonical_roster_original_selections ORDER BY operation_uuid LIMIT 1") + .get(0, UUID.class); + var owner = + owners.stream() + .filter(value -> value.getRequest().getOperationUuid().equals(anchor.toString())) + .findFirst() + .orElseThrow(); + legacyProof = retirement(owner, snapshot); + if (retired) { + for (var local : legacyRequests) { + UUID release = + UUID.nameUUIDFromBytes( + (legacyProof.getRetirementUuid() + ":" + local.requestUuid()) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); dsl.execute( - "INSERT INTO entity_canonical_roster_retention_lifecycle (snapshot_uuid, snapshot_digest) VALUES (?, ?)", + "INSERT INTO entity_canonical_roster_retention_releases (release_operation_uuid, reference_uuid, snapshot_uuid, snapshot_digest) VALUES (?, ?, ?, ?)", + release, + local.requestUuid(), snapshot.snapshotUuid(), snapshot.snapshotDigest()); - for (int index = 0; index < (disposed ? 1 : 2); index++) { - var local = localRequest(); - UUID nonce = UUID.randomUUID(); - var owner = - CanonicalGameplayRosterReferenceEvidence.response( - recovery(local).getOriginalSelection(), 1, fence, null); - legacyRequests.add(local); - legacyNonces.put(local.requestUuid(), nonce); - owners.add(owner); - dsl.execute( - "INSERT INTO entity_canonical_roster_admissions (operation_uuid, admission_uuid, request_binding, snapshot_uuid) VALUES (?, ?, ?, ?)", - local.requestUuid(), - nonce, - legacyAdmissionBinding(local), - snapshot.snapshotUuid()); - dsl.execute( - "INSERT INTO entity_canonical_roster_retention_references (reference_uuid, acquire_operation_uuid, snapshot_uuid, snapshot_digest, reference_kind) VALUES (?, ?, ?, ?, 'ORIGINAL_SELECTION')", - local.requestUuid(), - local.requestUuid(), - snapshot.snapshotUuid(), - snapshot.snapshotDigest()); - dsl.execute( - "INSERT INTO entity_canonical_roster_original_selections (operation_uuid, owner_request, owner_fence, owner_target_fence_uuid, snapshot_uuid, snapshot_digest, canonical_roster_receipt) VALUES (?, ?, ?, ?, ?, ?, ?)", - local.requestUuid(), - owner.getRequest().toByteArray(), - 1, - fence, - snapshot.snapshotUuid(), - snapshot.snapshotDigest(), - snapshot.toWire().toByteArray()); - } - UUID anchor = - dsl.fetchSingle( - "SELECT operation_uuid FROM entity_canonical_roster_original_selections ORDER BY operation_uuid LIMIT 1") - .get(0, UUID.class); - var owner = - owners.stream() - .filter(value -> value.getRequest().getOperationUuid().equals(anchor.toString())) - .findFirst() - .orElseThrow(); - legacyProof = retirement(owner, snapshot); - if (retired) { - for (var local : legacyRequests) { - UUID release = - UUID.nameUUIDFromBytes( - (legacyProof.getRetirementUuid() + ":" + local.requestUuid()) - .getBytes(java.nio.charset.StandardCharsets.UTF_8)); - dsl.execute( - "INSERT INTO entity_canonical_roster_retention_releases (release_operation_uuid, reference_uuid, snapshot_uuid, snapshot_digest) VALUES (?, ?, ?, ?)", - release, - local.requestUuid(), - snapshot.snapshotUuid(), - snapshot.snapshotDigest()); - } - dsl.execute( - "UPDATE entity_canonical_roster_retention_lifecycle SET lifecycle_state = 'RETIRED', local_epoch = local_epoch + 1, owner_target_fence_uuid = ?, owner_retirement_uuid = ?, owner_retirement_proof_digest = ?, owner_retirement_proof = ?, retirement_observed_at = clock_timestamp(), minimum_retention_millis = 1 WHERE snapshot_uuid = ?", - fence, - UUID.fromString(legacyProof.getRetirementUuid()), - legacyProof.getRetirementProofDigest(), - legacyProof.toByteArray(), - snapshot.snapshotUuid()); - for (int index = 0; index < intents; index++) { - var local = legacyRequests.get(index); - var original = owners.get(index).getRequest(); - UUID observation = UUID.randomUUID(); - var request = - net.firedevops.firemud.gamesession.v1 - .CanonicalGameplayRosterRetirementAcknowledgementRequest.newBuilder() - .setSchemaVersion(1) - .setOriginalSelection(original) - .setObservedRetirement(legacyProof) - .setObservationUuid(observation.toString()) - .setAdmissionUuid(legacyNonces.get(local.requestUuid()).toString()) - .setSnapshotUuid(snapshot.snapshotUuid().toString()) - .setSnapshotDigest(snapshot.snapshotDigest()) - .setMinimumRetentionMillis(1) - .build(); - CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement(request); - dsl.execute( - "INSERT INTO entity_canonical_roster_retirement_transfers (observation_uuid, operation_uuid, original_request, admission_uuid, snapshot_uuid, snapshot_digest, owner_fence, target_fence_uuid, minimum_retention_millis, transfer_state, observed_retirement, acknowledgement_request, request_digest) VALUES (?, ?, ?, ?, ?, ?, 1, ?, 1, 'PENDING_ACK', ?, ?, ?)", - observation, - local.requestUuid(), - original.toByteArray(), - legacyNonces.get(local.requestUuid()), - snapshot.snapshotUuid(), - snapshot.snapshotDigest(), - fence, - legacyProof.toByteArray(), - request.toByteArray(), - CanonicalGameplayRosterRetirementEvidence.requestDigest(request)); - } - } - }); + } + dsl.execute( + "UPDATE entity_canonical_roster_retention_lifecycle SET lifecycle_state = 'RETIRED', local_epoch = local_epoch + 1, owner_target_fence_uuid = ?, owner_retirement_uuid = ?, owner_retirement_proof_digest = ?, owner_retirement_proof = ?, retirement_observed_at = clock_timestamp(), minimum_retention_millis = 1 WHERE snapshot_uuid = ?", + fence, + UUID.fromString(legacyProof.getRetirementUuid()), + legacyProof.getRetirementProofDigest(), + legacyProof.toByteArray(), + snapshot.snapshotUuid()); + for (int index = 0; index < intents; index++) { + var local = legacyRequests.get(index); + var original = owners.get(index).getRequest(); + UUID observation = UUID.randomUUID(); + var request = + net.firedevops.firemud.gamesession.v1 + .CanonicalGameplayRosterRetirementAcknowledgementRequest.newBuilder() + .setSchemaVersion(1) + .setOriginalSelection(original) + .setObservedRetirement(legacyProof) + .setObservationUuid(observation.toString()) + .setAdmissionUuid(legacyNonces.get(local.requestUuid()).toString()) + .setSnapshotUuid(snapshot.snapshotUuid().toString()) + .setSnapshotDigest(snapshot.snapshotDigest()) + .setMinimumRetentionMillis(1) + .build(); + CanonicalGameplayRosterRetirementEvidence.requireAcknowledgement(request); + dsl.execute( + "INSERT INTO entity_canonical_roster_retirement_transfers (observation_uuid, operation_uuid, original_request, admission_uuid, snapshot_uuid, snapshot_digest, owner_fence, target_fence_uuid, minimum_retention_millis, transfer_state, observed_retirement, acknowledgement_request, request_digest) VALUES (?, ?, ?, ?, ?, ?, 1, ?, 1, 'PENDING_ACK', ?, ?, ?)", + observation, + local.requestUuid(), + original.toByteArray(), + legacyNonces.get(local.requestUuid()), + snapshot.snapshotUuid(), + snapshot.snapshotDigest(), + fence, + legacyProof.toByteArray(), + request.toByteArray(), + CanonicalGameplayRosterRetirementEvidence.requestDigest(request)); + } + } + }); if (disposed) { dsl.fetch("SELECT pg_sleep(0.02)"); - transaction.executeWithoutResult( - ignored -> { - long epoch = - dsl.fetchSingle( - "UPDATE entity_canonical_roster_retention_lifecycle SET lifecycle_state = 'DISPOSING', local_epoch = local_epoch + 1 WHERE snapshot_uuid = ? RETURNING local_epoch", - snapshot.snapshotUuid()) - .get(0, Long.class); - dsl.execute( - "INSERT INTO entity_canonical_roster_disposal_receipts (snapshot_uuid, snapshot_digest, owner_target_fence_uuid, owner_retirement_uuid, owner_retirement_proof_digest, local_epoch, minimum_retention_millis) VALUES (?, ?, ?, ?, ?, ?, 1)", - snapshot.snapshotUuid(), - snapshot.snapshotDigest(), - fence, - UUID.fromString(legacyProof.getRetirementUuid()), - legacyProof.getRetirementProofDigest(), - epoch); - dsl.execute( - "UPDATE entity_canonical_roster_admissions SET admission_state = 'DISPOSED', disposed_at = clock_timestamp(), minimum_retention_millis = 1 WHERE snapshot_uuid = ?", - snapshot.snapshotUuid()); - dsl.execute( - "DELETE FROM entity_canonical_gameplay_roster_snapshot_actors WHERE snapshot_uuid = ?", - snapshot.snapshotUuid()); - dsl.execute( - "DELETE FROM entity_canonical_roster_original_selections WHERE snapshot_uuid = ?", - snapshot.snapshotUuid()); - dsl.execute( - "DELETE FROM entity_canonical_roster_retention_references WHERE snapshot_uuid = ?", - snapshot.snapshotUuid()); - dsl.execute( - "DELETE FROM entity_canonical_roster_retention_releases WHERE snapshot_uuid = ?", - snapshot.snapshotUuid()); - dsl.execute( - "DELETE FROM entity_canonical_gameplay_roster_snapshots WHERE snapshot_uuid = ?", - snapshot.snapshotUuid()); - dsl.execute( - "DELETE FROM entity_canonical_roster_retention_lifecycle WHERE snapshot_uuid = ?", - snapshot.snapshotUuid()); - }); + transaction.executeWithoutResult(ignored -> { + long epoch = + dsl.fetchSingle( + "UPDATE entity_canonical_roster_retention_lifecycle SET lifecycle_state = 'DISPOSING', local_epoch = local_epoch + 1 WHERE snapshot_uuid = ? RETURNING local_epoch", + snapshot.snapshotUuid()) + .get(0, Long.class); + dsl.execute( + "INSERT INTO entity_canonical_roster_disposal_receipts (snapshot_uuid, snapshot_digest, owner_target_fence_uuid, owner_retirement_uuid, owner_retirement_proof_digest, local_epoch, minimum_retention_millis) VALUES (?, ?, ?, ?, ?, ?, 1)", + snapshot.snapshotUuid(), + snapshot.snapshotDigest(), + fence, + UUID.fromString(legacyProof.getRetirementUuid()), + legacyProof.getRetirementProofDigest(), + epoch); + dsl.execute( + "UPDATE entity_canonical_roster_admissions SET admission_state = 'DISPOSED', disposed_at = clock_timestamp(), minimum_retention_millis = 1 WHERE snapshot_uuid = ?", + snapshot.snapshotUuid()); + dsl.execute( + "DELETE FROM entity_canonical_gameplay_roster_snapshot_actors WHERE snapshot_uuid = ?", + snapshot.snapshotUuid()); + dsl.execute( + "DELETE FROM entity_canonical_roster_original_selections WHERE snapshot_uuid = ?", + snapshot.snapshotUuid()); + dsl.execute( + "DELETE FROM entity_canonical_roster_retention_references WHERE snapshot_uuid = ?", + snapshot.snapshotUuid()); + dsl.execute( + "DELETE FROM entity_canonical_roster_retention_releases WHERE snapshot_uuid = ?", + snapshot.snapshotUuid()); + dsl.execute( + "DELETE FROM entity_canonical_gameplay_roster_snapshots WHERE snapshot_uuid = ?", + snapshot.snapshotUuid()); + dsl.execute( + "DELETE FROM entity_canonical_roster_retention_lifecycle WHERE snapshot_uuid = ?", + snapshot.snapshotUuid()); + }); if (purgeTombstones) { dsl.fetch("SELECT pg_sleep(0.02)"); dsl.execute("DELETE FROM entity_canonical_roster_admissions"); @@ -3635,16 +3434,13 @@ private List rebuildLegacyCohort( } if (inconsistentRestore) { // Explicit inconsistent-restore fixture only: production migration never disables guards. - transaction.executeWithoutResult( - ignored -> { - dsl.execute( - "ALTER TABLE entity_canonical_roster_original_selections DISABLE TRIGGER USER"); - dsl.execute( - "DELETE FROM entity_canonical_roster_original_selections WHERE operation_uuid = ?", - UUID.fromString(legacyProof.getRequest().getOperationUuid())); - dsl.execute( - "ALTER TABLE entity_canonical_roster_original_selections ENABLE TRIGGER USER"); - }); + transaction.executeWithoutResult(ignored -> { + dsl.execute("ALTER TABLE entity_canonical_roster_original_selections DISABLE TRIGGER USER"); + dsl.execute( + "DELETE FROM entity_canonical_roster_original_selections WHERE operation_uuid = ?", + UUID.fromString(legacyProof.getRequest().getOperationUuid())); + dsl.execute("ALTER TABLE entity_canonical_roster_original_selections ENABLE TRIGGER USER"); + }); } var rows = immutableRetentionRows(); var authority = retainedLifecycleAuthority(); @@ -3758,26 +3554,25 @@ private List retainedBeforeCreatedExtension() { "entity_canonical_gameplay_roster_snapshot_actors", "entity_canonical_roster_retention_lifecycle") .stream() - .flatMap( - table -> { - String projection = - table.equals("entity_canonical_gameplay_roster_snapshots") - ? "to_jsonb(t) - 'canonical_player_created_source_identity'" - : table.equals("entity_canonical_roster_retention_lifecycle") - ? "to_jsonb(t) - 'entry_policy'" - : "to_jsonb(t)"; - return dsl - .fetch( - "SELECT (" - + projection - + ")::TEXT || ':' || xmin::TEXT FROM " - + table - + " t ORDER BY (" - + projection - + ")::TEXT") - .getValues(0, String.class) - .stream(); - }) + .flatMap(table -> { + String projection = + table.equals("entity_canonical_gameplay_roster_snapshots") + ? "to_jsonb(t) - 'canonical_player_created_source_identity'" + : table.equals("entity_canonical_roster_retention_lifecycle") + ? "to_jsonb(t) - 'entry_policy'" + : "to_jsonb(t)"; + return dsl + .fetch( + "SELECT (" + + projection + + ")::TEXT || ':' || xmin::TEXT FROM " + + table + + " t ORDER BY (" + + projection + + ")::TEXT") + .getValues(0, String.class) + .stream(); + }) .toList(); } diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java index d52d0043f7..213ebb2711 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java @@ -126,12 +126,9 @@ void migrationSeedsActualLegacySourceAndAuditTenantVersionKeys() { "SELECT key_kind, numeric_key, claim_kind " + "FROM entity_empty_source_numeric_key_reservation " + "WHERE claim_kind = 'LEGACY_NUMERIC' ORDER BY key_kind, numeric_key") - .map( - row -> - new ReservedNumericKey( - row.get(0, String.class), - row.get(1, Long.class), - row.get(2, String.class))); + .map(row -> + new ReservedNumericKey( + row.get(0, String.class), row.get(1, Long.class), row.get(2, String.class))); assertThat(legacyKeys) .containsExactly( new ReservedNumericKey("TENANT", 31001L, "LEGACY_NUMERIC"), @@ -195,12 +192,11 @@ void staleRepeatableReadWritersCannotMissACommittedCanonicalReservation() throws try (Connection staleRowWriter = repeatableReadSnapshot()) { commitCanonicalReservation(99001L); try { - assertThatThrownBy( - () -> - execute( - staleRowWriter, - "INSERT INTO characters (account_id, name, tenant_id) " - + "VALUES (99001, 'stale-snapshot-character', 99001)")) + assertThatThrownBy(() -> + execute( + staleRowWriter, + "INSERT INTO characters (account_id, name, tenant_id) " + + "VALUES (99001, 'stale-snapshot-character', 99001)")) .isInstanceOf(SQLException.class) .hasMessageContaining( "Entity authored-source row writes require READ COMMITTED isolation"); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java index 2dcabe3a54..4ad4cbcef0 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java @@ -128,25 +128,22 @@ void persistsAllTwentyThreeExplicitEmptyStatesAndReplaysOriginalReceiptBytes() { } assertThat(first.familyStates()) .hasSize(23) - .allSatisfy( - state -> { - assertThat(state.state()) - .isEqualTo(EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY); - assertThat(state.rowCount()).isZero(); - assertThat(state.referenceCount()).isZero(); - }); + .allSatisfy(state -> { + assertThat(state.state()) + .isEqualTo(EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY); + assertThat(state.rowCount()).isZero(); + assertThat(state.referenceCount()).isZero(); + }); assertThat(first.familyStates()) - .filteredOn( - state -> - state.evidenceKind() - == EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind - .EMPTY_ONLY_OWNER_PROVIDER) + .filteredOn(state -> + state.evidenceKind() + == EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind + .EMPTY_ONLY_OWNER_PROVIDER) .hasSize(14); assertThat(first.familyStates()) - .filteredOn( - state -> - state.evidenceKind() - == EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS) + .filteredOn(state -> + state.evidenceKind() + == EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS) .hasSize(9); assertThat(first.localTenantKey()).isPositive(); assertThat(first.localVersionKey()).isPositive().isNotEqualTo(first.localTenantKey()); @@ -176,12 +173,11 @@ void persistsAllTwentyThreeExplicitEmptyStatesAndReplaysOriginalReceiptBytes() { assertThat(readBack.receiptDigest()).isEqualTo(first.receiptDigest()); assertThat(readBack.retainedAt().toInstant()).isEqualTo(first.retainedAt().toInstant()); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO items (name, tenant_id, version_id) VALUES ('blocked', ?, ?)", - first.localTenantKey(), - first.localVersionKey())) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO items (name, tenant_id, version_id) VALUES ('blocked', ?, ?)", + first.localTenantKey(), + first.localVersionKey())) .isInstanceOf(DataAccessException.class); dsl.execute( "INSERT INTO items (name, tenant_id, version_id) VALUES ('unassociated', 81001, 81002)"); @@ -272,12 +268,11 @@ void selectedEmptyPublicationReaderResolvesOnlyTheValidatedReceiptForTenantAndGa gameDesignVersionRowId) .canonicalBytes()) .containsExactly(receipt.canonicalBytes()); - assertThatThrownBy( - () -> - repository.readPublicationScope( - EntityEmptySelectedSourceIntakePostgresFixture.NAMESPACE, - EntityEmptySelectedSourceIntakePostgresFixture.TENANT, - gameDesignVersionRowId + 1L)) + assertThatThrownBy(() -> + repository.readPublicationScope( + EntityEmptySelectedSourceIntakePostgresFixture.NAMESPACE, + EntityEmptySelectedSourceIntakePostgresFixture.TENANT, + gameDesignVersionRowId + 1L)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("missing or ambiguous"); @@ -315,15 +310,14 @@ void selectedEmptyPublicationReaderResolvesOnlyTheValidatedReceiptForTenantAndGa receipt.targetNamespace(), receipt.intakeRequestId()) .get(0, String.class); - assertThatThrownBy( - () -> - new EntitySelectedEmptyPublicationDigestService( - EntityEmptySelectedSourceIntakePostgresFixture.NAMESPACE, repository) - .getDraftDesignDigest( - PublicationDigestRequestBinding.full( - EntityEmptySelectedSourceIntakePostgresFixture.TENANT.toString(), - Long.toString(gameDesignVersionRowId), - "publish-request-2"))) + assertThatThrownBy(() -> + new EntitySelectedEmptyPublicationDigestService( + EntityEmptySelectedSourceIntakePostgresFixture.NAMESPACE, repository) + .getDraftDesignDigest( + PublicationDigestRequestBinding.full( + EntityEmptySelectedSourceIntakePostgresFixture.TENANT.toString(), + Long.toString(gameDesignVersionRowId), + "publish-request-2"))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("original retained World freeze"); String rowAfterMismatchedPublicationRead = @@ -427,12 +421,11 @@ void corruptStoredReceiptBytesHaveADistinctRepositoryFailure() { assertThatThrownBy(() -> repository.read(receipt.targetNamespace(), receipt.intakeRequestId())) .isInstanceOf(EntityEmptySelectedSourceIntakeRepository.CorruptReceiptException.class) .hasMessageContaining("Entity stored source receipt is corrupt"); - assertThatThrownBy( - () -> - repository.readPublicationScope( - receipt.targetNamespace(), - receipt.canonicalTenantId(), - fixture.authorization().selected().target().gameDesignVersionRowId())) + assertThatThrownBy(() -> + repository.readPublicationScope( + receipt.targetNamespace(), + receipt.canonicalTenantId(), + fixture.authorization().selected().target().gameDesignVersionRowId())) .isInstanceOf(EntityEmptySelectedSourceIntakeRepository.CorruptReceiptException.class); } @@ -552,17 +545,15 @@ void providerConstraintsAndImmutableReadbackRejectUnknownNonemptyOrChangedState( dsl.execute("ALTER TABLE " + table + " DISABLE TRIGGER USER"); try { - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE " + table + " SET row_count = 1 WHERE target_namespace = ?", - receipt.targetNamespace())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE " + table + " SET row_count = 1 WHERE target_namespace = ?", + receipt.targetNamespace())) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE " + table + " SET owner_state = 'UNKNOWN' WHERE target_namespace = ?", - receipt.targetNamespace())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE " + table + " SET owner_state = 'UNKNOWN' WHERE target_namespace = ?", + receipt.targetNamespace())) .isInstanceOf(DataAccessException.class); dsl.execute( "DELETE FROM " + table + " WHERE target_namespace = ? AND intake_request_id = ?", @@ -574,12 +565,11 @@ void providerConstraintsAndImmutableReadbackRejectUnknownNonemptyOrChangedState( assertThatThrownBy(() -> repository.read(receipt.targetNamespace(), receipt.intakeRequestId())) .isInstanceOf(EntityEmptySelectedSourceIntakeRepository.CorruptReceiptException.class) .hasMessageContaining("provider readback is missing or differs"); - assertThatThrownBy( - () -> - repository.readPublicationScope( - receipt.targetNamespace(), - receipt.canonicalTenantId(), - fixture.authorization().selected().target().gameDesignVersionRowId())) + assertThatThrownBy(() -> + repository.readPublicationScope( + receipt.targetNamespace(), + receipt.canonicalTenantId(), + fixture.authorization().selected().target().gameDesignVersionRowId())) .isInstanceOf(EntityEmptySelectedSourceIntakeRepository.CorruptReceiptException.class); } diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java index 6cb1dac97b..7436b7542c 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -100,15 +100,13 @@ void actualCombinedMigrationsYieldExactCompleteCensusIncludingOwnInfrastructure( assertThat(catalog.schemaFacts()) .anyMatch(fact -> fact.kind() == FactKind.ROUTINE) .anyMatch(fact -> fact.kind() == FactKind.COLUMN) - .anyMatch( - fact -> - fact.kind() == FactKind.SEQUENCE - && fact.identity().equals("entity_runtime_entity_id_sequence")) + .anyMatch(fact -> + fact.kind() == FactKind.SEQUENCE + && fact.identity().equals("entity_runtime_entity_id_sequence")) .anyMatch(fact -> fact.kind() == FactKind.MIGRATION && fact.identity().contains("1004")) - .anyMatch( - fact -> - fact.kind() == FactKind.MIGRATION - && fact.identity().equals("catalog-installation:1025")); + .anyMatch(fact -> + fact.kind() == FactKind.MIGRATION + && fact.identity().equals("catalog-installation:1025")); assertThat( f.dsl .fetchSingle( @@ -240,10 +238,9 @@ void conditionalAndMixedFamiliesAreExplicitBlockingFactsEvenWithZeroRows() { StateClass.NOT_PAYLOAD, FreshDisposition.SELECTED_EMPTY_SOURCE_ONLY); assertThat(catalog.families()) - .noneMatch( - family -> - family.familyId().equals("entity_tick_state") - || family.familyId().equals("character")); + .noneMatch(family -> + family.familyId().equals("entity_tick_state") + || family.familyId().equals("character")); } } @@ -585,10 +582,9 @@ void forwardFrameGuardUpgradeRetainsOldEpochSnapshotAndHistoryWithoutResampling( assertThat(current.catalog().catalogEpoch()).isEqualTo(2); assertThat(current.catalog().digest()).isNotEqualTo(original.catalog().digest()); assertThat(current.catalog().schemaFacts()) - .anyMatch( - fact -> - fact.kind() == FactKind.MIGRATION - && fact.identity().equals("catalog-installation:1026")); + .anyMatch(fact -> + fact.kind() == FactKind.MIGRATION + && fact.identity().equals("catalog-installation:1026")); migration(f.source, f.schema, HISTORY, null).load().validate(); } } @@ -659,19 +655,18 @@ void directSqlPoisonFramesRefuseWithoutConsumingRequestIdentity() { byte[] insertedEvidence = evidenceBytes; String insertedNamespace = namespace; long before = f.count("entity_runtime_family_catalog_snapshot"); - assertThatThrownBy( - () -> - f.dsl.execute( - "INSERT INTO entity_runtime_family_catalog_snapshot(read_request_id,target_namespace,request_bytes,request_digest,snapshot_id,catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)", - read.readRequestId(), - insertedNamespace, - insertedRequest, - EntityRuntimeFamilyCatalog.sha256(insertedRequest), - snapshot, - original.catalog().catalogEpoch(), - original.catalog().digest(), - insertedEvidence, - EntityRuntimeFamilyCatalog.sha256(insertedEvidence))) + assertThatThrownBy(() -> + f.dsl.execute( + "INSERT INTO entity_runtime_family_catalog_snapshot(read_request_id,target_namespace,request_bytes,request_digest,snapshot_id,catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)", + read.readRequestId(), + insertedNamespace, + insertedRequest, + EntityRuntimeFamilyCatalog.sha256(insertedRequest), + snapshot, + original.catalog().catalogEpoch(), + original.catalog().digest(), + insertedEvidence, + EntityRuntimeFamilyCatalog.sha256(insertedEvidence))) .as(vector) .hasMessageContaining("complete exact request and evidence"); assertThat(f.count("entity_runtime_family_catalog_snapshot")).isEqualTo(before); @@ -698,16 +693,14 @@ void metadataEpochAndSnapshotsRemainImmutableAndWrongSealCannotBeInserted() { assertThatThrownBy(() -> f.dsl.execute("TRUNCATE " + table + " CASCADE")) .hasMessageContaining("immutable"); } - assertThatThrownBy( - () -> - f.dsl.execute( - "UPDATE entity_runtime_family_classification SET state_class='S3' WHERE family_id='item_instances'")) + assertThatThrownBy(() -> + f.dsl.execute( + "UPDATE entity_runtime_family_classification SET state_class='S3' WHERE family_id='item_instances'")) .hasMessageContaining("immutable"); - assertThatThrownBy( - () -> - f.dsl.execute( - "INSERT INTO entity_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 3,catalog_bytes,catalog_digest FROM entity_runtime_family_catalog_epoch WHERE catalog_epoch=2")) + assertThatThrownBy(() -> + f.dsl.execute( + "INSERT INTO entity_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" + + " SELECT 3,catalog_bytes,catalog_digest FROM entity_runtime_family_catalog_epoch WHERE catalog_epoch=2")) .hasMessageContaining("exact classified installed schema"); } } @@ -723,10 +716,9 @@ void actualHandlerReturnsCommittedExactEvidenceWithoutCreatingActorsOrRuntime() .orElseThrow(); Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .run( - () -> - service.readEntityRuntimeFamilyCatalog( - EntityRuntimeFamilyCatalogCodec.toRequest(read), collector)); + .run(() -> + service.readEntityRuntimeFamilyCatalog( + EntityRuntimeFamilyCatalogCodec.toRequest(read), collector)); assertThat(collector.error).isNull(); assertThat(collector.completed).isTrue(); assertThat(EntityRuntimeFamilyCatalogCodec.fromResponse(read, collector.value)) @@ -794,13 +786,12 @@ private static void assertFamily( StateClass state, FreshDisposition disposition) { assertThat(catalog.families()) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo(name); - assertThat(family.role()).isEqualTo(role); - assertThat(family.stateClass()).isEqualTo(state); - assertThat(family.freshDisposition()).isEqualTo(disposition); - }); + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo(name); + assertThat(family.role()).isEqualTo(role); + assertThat(family.stateClass()).isEqualTo(state); + assertThat(family.freshDisposition()).isEqualTo(disposition); + }); } private static Request request() { diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptorTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptorTest.java index deac9277d9..a73c3632a9 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptorTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterPeerInterceptorTest.java @@ -34,12 +34,11 @@ void exactAccountCertificateIsAvailableBeforeMessageHandling() throws Exception var call = call("spiffe://firemud/ns/test/sa/account-service"); ServerCallHandler next = mock(ServerCallHandler.class); when(next.startCall(any(), any())) - .thenAnswer( - ignored -> { - assertThat(GrpcPeerIdentity.current().isService("account-service")).isTrue(); - assertThat(GrpcPeerIdentity.current().isInNamespace("test")).isTrue(); - return new ServerCall.Listener() {}; - }); + .thenAnswer(ignored -> { + assertThat(GrpcPeerIdentity.current().isService("account-service")).isTrue(); + assertThat(GrpcPeerIdentity.current().isInNamespace("test")).isTrue(); + return new ServerCall.Listener() {}; + }); new AccountBootstrapRosterPeerInterceptor("test").interceptCall(call, new Metadata(), next); verify(next).startCall(any(), any()); } @@ -58,12 +57,11 @@ void absentWrongNamespaceAndGameSessionPeersNeverStartMessageDecoding() throws E verify(next, never()).startCall(any(), any()); verify(call) .close( - argThat( - status -> - status.getCode() - == (identity == null - ? Status.Code.UNAUTHENTICATED - : Status.Code.PERMISSION_DENIED)), + argThat(status -> + status.getCode() + == (identity == null + ? Status.Code.UNAUTHENTICATED + : Status.Code.PERMISSION_DENIED)), any()); } } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java index 7a170ef426..1cfe9e5ef1 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterReadServiceTest.java @@ -53,25 +53,21 @@ void realAdapterReadsCurrentSourceBeforeAndAfterShortLocalProjectionIncludingEmp var client = mock(GameSessionCanonicalGameplayRosterOwnerReadClient.class); var repository = mock(CharacterRepository.class); when(client.getCanonicalGameplayRosterOwnerRead(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - assertThat( - invocation.getArgument( - 0, CanonicalGameplayRosterOwnerReadEvidence.Request.class)) - .isEqualTo(f.evidence().request()); - return f.evidence(); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat( + invocation.getArgument(0, CanonicalGameplayRosterOwnerReadEvidence.Request.class)) + .isEqualTo(f.evidence().request()); + return f.evidence(); + }); UUID actor = UUID.randomUUID(); when(repository.readAccountBootstrapRoster(any(), eq(f.target()))) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); - return List.of( - new AccountBootstrapRosterActorProjection(actor, "Persisted Actor", 7)); - }) + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isTrue(); + return List.of(new AccountBootstrapRosterActorProjection(actor, "Persisted Actor", 7)); + }) .thenReturn(List.of()); var service = service(client, repository); assertThat(service.read(f.request()).getActorsList()) @@ -147,15 +143,14 @@ void malformedUnsupportedAndAmbientTransactionRefuseBeforeAnySourceOrSql() throw assertThatThrownBy( () -> service.read(f.request().toBuilder().setCanonicalAccountUuid("12").build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - service.read( - f.request().toBuilder() - .setExpectedTarget( - f.request().getExpectedTarget().toBuilder() - .setPlayableStateScope( - PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) - .build())) + assertThatThrownBy(() -> + service.read( + f.request().toBuilder() + .setExpectedTarget( + f.request().getExpectedTarget().toBuilder() + .setPlayableStateScope( + PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) + .build())) .isInstanceOf(UnsupportedOperationException.class); var unknown = UnknownFieldSet.newBuilder() @@ -165,14 +160,13 @@ void malformedUnsupportedAndAmbientTransactionRefuseBeforeAnySourceOrSql() throw () -> service.read(f.request().toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class); new TransactionTemplate(new LocalTransactions()) - .executeWithoutResult( - ignored -> { - assertThatThrownBy(() -> service.read(f.request())) - .isExactlyInstanceOf(IllegalStateException.class) - .hasMessage( - "Account bootstrap roster read requires no ambient transaction or synchronization") - .hasNoCause(); - }); + .executeWithoutResult(ignored -> { + assertThatThrownBy(() -> service.read(f.request())) + .isExactlyInstanceOf(IllegalStateException.class) + .hasMessage( + "Account bootstrap roster read requires no ambient transaction or synchronization") + .hasNoCause(); + }); verifyNoInteractions(client, repository); } @@ -258,10 +252,9 @@ void receiverKeepsMalformedRequestsInvalidWithoutCallingService() throws Excepti new AccountBootstrapRosterReadGrpcService(service, AccountBootstrapRosterFixture.NAMESPACE); StreamObserver observer = mock(StreamObserver.class); - withControlledAccountPeer( - () -> - receiver.readAccountBootstrapRoster( - f.request().toBuilder().setCanonicalAccountUuid("malformed").build(), observer)); + withControlledAccountPeer(() -> + receiver.readAccountBootstrapRoster( + f.request().toBuilder().setCanonicalAccountUuid("malformed").build(), observer)); assertReceiverFailure(observer, Status.Code.INVALID_ARGUMENT); verifyNoInteractions(service); @@ -281,11 +274,10 @@ void receiverClassifiesStoredProjectionAndResponseValidationFailuresAsInternal() .thenThrow(new IllegalStateException("CANONICAL_ROSTER_LEVEL_NULL")); } else if ("negative-level".equals(invalidProjection)) { when(repository.readAccountBootstrapRoster(any(), any())) - .thenAnswer( - ignored -> - List.of( - new AccountBootstrapRosterActorProjection( - UUID.randomUUID(), "Persisted Actor", -1))); + .thenAnswer(ignored -> + List.of( + new AccountBootstrapRosterActorProjection( + UUID.randomUUID(), "Persisted Actor", -1))); } else { var actor = new AccountBootstrapRosterActorProjection(UUID.randomUUID(), "Persisted Actor", 0); @@ -342,11 +334,10 @@ private static void withControlledAccountPeer(Runnable action) throws Exception ServerCallHandler next = mock(ServerCallHandler.class); when(next.startCall(any(), any())) - .thenAnswer( - ignored -> { - action.run(); - return new ServerCall.Listener() {}; - }); + .thenAnswer(ignored -> { + action.run(); + return new ServerCall.Listener() {}; + }); new AccountBootstrapRosterPeerInterceptor(AccountBootstrapRosterFixture.NAMESPACE) .interceptCall(call, new Metadata(), next); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateBindingsTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateBindingsTest.java index fbb4b93ad9..6f2161247a 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateBindingsTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateBindingsTest.java @@ -23,19 +23,17 @@ void strictOriginalPreservesEmptyInputAndAuthoredGenericCore() throws Exception var action = EntityCharacterCreateBindings.requireOriginal(reference(original), original); assertThat(action.mutation().canonicalCreationInput()).isEqualTo("{}"); assertThat(action.mutation().authoredSource().core().canonicalJson()).contains("Wayfarer"); - assertThatThrownBy( - () -> - EntityCharacterCreateBindings.requireOriginal( - reference(original), - original.toBuilder() - .setAuthenticatedAccountId(UUID.randomUUID().toString()) - .build())) + assertThatThrownBy(() -> + EntityCharacterCreateBindings.requireOriginal( + reference(original), + original.toBuilder() + .setAuthenticatedAccountId(UUID.randomUUID().toString()) + .build())) .isInstanceOf(io.grpc.StatusRuntimeException.class); - assertThatThrownBy( - () -> - EntityCharacterCreateBindings.requireOriginal( - reference(original), - original.toBuilder().setOriginalSourceReadback(ByteString.EMPTY).build())) + assertThatThrownBy(() -> + EntityCharacterCreateBindings.requireOriginal( + reference(original), + original.toBuilder().setOriginalSourceReadback(ByteString.EMPTY).build())) .isInstanceOf(io.grpc.StatusRuntimeException.class); } @@ -60,33 +58,29 @@ void protectionRequiresExactOriginalOperationSourceAndFence() throws Exception { .setOriginalEntitlementSnapshot(ByteString.copyFromUtf8("fixture-entitlement")) .build(); EntityCharacterCreateBindings.requireAccountProtection(request, original, proof); - assertThatThrownBy( - () -> - EntityCharacterCreateBindings.requireAccountProtection( - request, - original, - proof.toBuilder() - .setOriginal( - original.toBuilder() - .setOriginalSourceReadback( - ByteString.copyFromUtf8("different-source"))) - .build())) + assertThatThrownBy(() -> + EntityCharacterCreateBindings.requireAccountProtection( + request, + original, + proof.toBuilder() + .setOriginal( + original.toBuilder() + .setOriginalSourceReadback(ByteString.copyFromUtf8("different-source"))) + .build())) .isInstanceOf(io.grpc.StatusRuntimeException.class); - assertThatThrownBy( - () -> - EntityCharacterCreateBindings.requireAccountProtection( - request, original, proof.toBuilder().setAccountProtectionFence(2L).build())) + assertThatThrownBy(() -> + EntityCharacterCreateBindings.requireAccountProtection( + request, original, proof.toBuilder().setAccountProtectionFence(2L).build())) .isInstanceOf(io.grpc.StatusRuntimeException.class); } @Test void unavailableGameSessionCreationAuthorityCannotBecomePositiveRosterEvidence() { - assertThatThrownBy( - () -> - GameSessionCharacterCreateProtectionReader.unavailable() - .readOriginal( - ReadOriginalCharacterCreateProtectionResponse.getDefaultInstance(), - protection())) + assertThatThrownBy(() -> + GameSessionCharacterCreateProtectionReader.unavailable() + .readOriginal( + ReadOriginalCharacterCreateProtectionResponse.getDefaultInstance(), + protection())) .isInstanceOf(io.grpc.StatusRuntimeException.class) .hasMessageContaining("UNAVAILABLE"); } @@ -101,18 +95,16 @@ void allThreePositiveCanonicalReferencesAreRequired() throws Exception { .setWorldProtection(protection()) .build(); EntityCharacterCreateBindings.requireRequest(request); - assertThatThrownBy( - () -> - EntityCharacterCreateBindings.requireRequest( - request.toBuilder().clearWorldProtection().build())) + assertThatThrownBy(() -> + EntityCharacterCreateBindings.requireRequest( + request.toBuilder().clearWorldProtection().build())) .isInstanceOf(io.grpc.StatusRuntimeException.class); - assertThatThrownBy( - () -> - EntityCharacterCreateBindings.requireRequest( - request.toBuilder() - .setGameSessionProtection( - request.getGameSessionProtection().toBuilder().setProtectionFence(0L)) - .build())) + assertThatThrownBy(() -> + EntityCharacterCreateBindings.requireRequest( + request.toBuilder() + .setGameSessionProtection( + request.getGameSessionProtection().toBuilder().setProtectionFence(0L)) + .build())) .isInstanceOf(io.grpc.StatusRuntimeException.class); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateMtlsTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateMtlsTest.java index 383dfe1ac5..08252e38ba 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateMtlsTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateMtlsTest.java @@ -139,11 +139,10 @@ void ownerCertificatesHaveDistinctReadAndMutationPermissions() throws Exception .sslContext(GrpcSslContexts.forClient().trustManager(pki.caCertificate()).build()) .build(); try { - assertThatThrownBy( - () -> - EntityCharacterCreateServiceGrpc.newBlockingStub(noCertificate) - .withDeadlineAfter(5, TimeUnit.SECONDS) - .readEntityCharacterCreateTerminal(read)) + assertThatThrownBy(() -> + EntityCharacterCreateServiceGrpc.newBlockingStub(noCertificate) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .readEntityCharacterCreateTerminal(read)) .isInstanceOf(io.grpc.StatusRuntimeException.class); } finally { noCertificate.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateProtectionBoundsTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateProtectionBoundsTest.java index 58ae5c4303..01c03b9b87 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateProtectionBoundsTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityCharacterCreateProtectionBoundsTest.java @@ -43,10 +43,8 @@ class EntityCharacterCreateProtectionBoundsTest { @Test void eachExactOneMebibyteSnapshotIsAccepted() { - assertThatCode( - () -> - EntityCharacterCreateBindings.requireAccountProtection( - REQUEST, ORIGINAL, protection())) + assertThatCode(() -> + EntityCharacterCreateBindings.requireAccountProtection(REQUEST, ORIGINAL, protection())) .doesNotThrowAnyException(); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterReadServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterReadServiceTest.java index e5f6c9fb29..9e8c46f3f6 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterReadServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterReadServiceTest.java @@ -38,11 +38,10 @@ void refusesAmbientSqlBeforeCallingTheSourceOwner() { var service = new EntityPlayerCreatedRosterReadService(repository, source); TransactionSynchronizationManager.initSynchronization(); - assertThatThrownBy( - () -> - service.read( - new AuthenticatedAccountSelector(UUID.randomUUID()), - ReadPlayerCreatedRosterSourceRequest.getDefaultInstance())) + assertThatThrownBy(() -> + service.read( + new AuthenticatedAccountSelector(UUID.randomUUID()), + ReadPlayerCreatedRosterSourceRequest.getDefaultInstance())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("short Entity transactions"); verifyNoInteractions(source, repository); @@ -101,17 +100,15 @@ void selectedReadRejectsNilCharacterBeforeCallingSource() { var source = mock(EntityPlayerCreatedRosterSourceClient.class); var service = new EntityPlayerCreatedRosterReadService(repository, source); - assertThatThrownBy( - () -> - service.readSelectedTerminal( - new AuthenticatedAccountSelector(UUID.randomUUID()), - new UUID(0L, 0L), - ReadPlayerCreatedRosterSourceRequest.getDefaultInstance())) + assertThatThrownBy(() -> + service.readSelectedTerminal( + new AuthenticatedAccountSelector(UUID.randomUUID()), + new UUID(0L, 0L), + ReadPlayerCreatedRosterSourceRequest.getDefaultInstance())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.INVALID_ARGUMENT)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT)); verifyNoInteractions(source, repository); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterServiceTest.java index bd0109a365..8cdd7af07b 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterServiceTest.java @@ -53,10 +53,8 @@ void rejectsMalformedSelectedRequestBeforeEitherOwnerTransport() { new EntityPlayerCreatedRosterService( "gameplay", source, owner, snapshots, retention, transactions); - assertThatThrownBy( - () -> - service.selected( - CanonicalSelectedPlayerCreatedCharacterRequest.getDefaultInstance())) + assertThatThrownBy(() -> + service.selected(CanonicalSelectedPlayerCreatedCharacterRequest.getDefaultInstance())) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(source, owner, snapshots, retention, transactions); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java index 34b132d0b6..486cda5d62 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRosterSourceClientMtlsTest.java @@ -113,19 +113,18 @@ void actualClientSourceComposesBeforeTheLocalRosterRead() throws Exception { client.init(); var repository = mock(EntityCharacterCreateRepository.class); when(repository.readPlayerCreatedRoster(any(), any())) - .thenAnswer( - invocation -> { - assertThat(owner.receivedRequests()).containsExactly(fixture.request()); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - var published = - invocation.getArgument( - 1, EntityPlayerCreatedRosterReadService.PublishedIdentity.class); - assertThat(published.tenantId()) - .isEqualTo(fixture.world().request().canonicalTenantId()); - assertThat(published.projection().canonicalBytes()) - .containsExactly(fixture.authored().projections().getFirst().canonicalBytes()); - return List.of(); - }); + .thenAnswer(invocation -> { + assertThat(owner.receivedRequests()).containsExactly(fixture.request()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var published = + invocation.getArgument( + 1, EntityPlayerCreatedRosterReadService.PublishedIdentity.class); + assertThat(published.tenantId()) + .isEqualTo(fixture.world().request().canonicalTenantId()); + assertThat(published.projection().canonicalBytes()) + .containsExactly(fixture.authored().projections().getFirst().canonicalBytes()); + return List.of(); + }); var service = new EntityPlayerCreatedRosterReadService(repository, client); assertThat( @@ -141,22 +140,18 @@ void actualClientSourceComposesBeforeTheLocalRosterRead() throws Exception { void constructionRequiresFileBackedMtlsAndCanonicalNamespace() throws Exception { var endpoints = new ServiceEndpointsProperties(); var channels = new GrpcChannelFactory(); - assertThatThrownBy( - () -> - new EntityPlayerCreatedRosterSourceClient( - endpoints, new CommonGrpcClientProperties(), channels, NAMESPACE)) + assertThatThrownBy(() -> + new EntityPlayerCreatedRosterSourceClient( + endpoints, new CommonGrpcClientProperties(), channels, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); var plaintext = controlled.clientProperties("entity"); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new EntityPlayerCreatedRosterSourceClient( - endpoints, plaintext, channels, NAMESPACE)) + assertThatThrownBy(() -> + new EntityPlayerCreatedRosterSourceClient(endpoints, plaintext, channels, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new EntityPlayerCreatedRosterSourceClient( - endpoints, controlled.clientProperties("entity"), channels, "Other")) + assertThatThrownBy(() -> + new EntityPlayerCreatedRosterSourceClient( + endpoints, controlled.clientProperties("entity"), channels, "Other")) .isInstanceOfSatisfying( StatusRuntimeException.class, failure -> diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRuntimeReferenceIngressTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRuntimeReferenceIngressTest.java index f901015922..a1bc6246e9 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRuntimeReferenceIngressTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/charactercreate/EntityPlayerCreatedRuntimeReferenceIngressTest.java @@ -170,13 +170,12 @@ void pendingCreationAndStorageFailuresRemainDistinctAcrossBothOwnerMethods() thr () -> game.readPlayerCreatedActorRuntimeReference(request))) { assertThatThrownBy(read::run) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - var status = Status.fromThrowable(failure); - assertThat(status.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); - assertThat(status.getDescription()) - .isEqualTo("Original PLAYER_CREATED runtime evidence is unavailable"); - }); + .satisfies(failure -> { + var status = Status.fromThrowable(failure); + assertThat(status.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(status.getDescription()) + .isEqualTo("Original PLAYER_CREATED runtime evidence is unavailable"); + }); } org.mockito.Mockito.doThrow(new org.jooq.exception.DataAccessException("private detail")) .when(creation) @@ -228,10 +227,9 @@ void completedCallbackFailureDoesNotSendASecondTerminalSignal() { mock(StreamObserver.class); var failure = new IllegalStateException("controlled completion callback failure"); doThrow(failure).when(observer).onCompleted(); - assertThatThrownBy( - () -> - new EntityPlayerCreatedRuntimeReferenceGrpcService(owner) - .readPlayerCreatedActorRuntimeReference(validRequest(), observer)) + assertThatThrownBy(() -> + new EntityPlayerCreatedRuntimeReferenceGrpcService(owner) + .readPlayerCreatedActorRuntimeReference(validRequest(), observer)) .isSameAs(failure); verify(observer, never()).onError(any()); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java index a0018357a1..ee5b39ed15 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountPreseededActorStagingEligibilityClientTest.java @@ -135,10 +135,8 @@ void rejectsMalformedInputsBeforeStubOrChannelUse() { }); for (String[] invalid : invalidRequests) { - assertThatThrownBy( - () -> - client.resolvePreseededActorStagingEligibility( - invalid[0], invalid[1], invalid[2])) + assertThatThrownBy(() -> + client.resolvePreseededActorStagingEligibility(invalid[0], invalid[1], invalid[2])) .isInstanceOf(IllegalArgumentException.class); } verifyNoInteractions(channelFactory); @@ -149,10 +147,9 @@ void rejectsUninitializedClientAndAbsentResponseWithoutActivation() throws Excep GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); AccountPreseededActorStagingEligibilityClient uninitialized = newClientWithoutStub(channelFactory); - assertThatThrownBy( - () -> - uninitialized.resolvePreseededActorStagingEligibility( - ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString())) + assertThatThrownBy(() -> + uninitialized.resolvePreseededActorStagingEligibility( + ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not initialized"); verifyNoInteractions(channelFactory); @@ -161,10 +158,9 @@ void rejectsUninitializedClientAndAbsentResponseWithoutActivation() throws Excep stub = mockStub(); when(stub.resolvePreseededActorStagingEligibility(any())).thenReturn(null); AccountPreseededActorStagingEligibilityClient client = newClient(stub); - assertThatThrownBy( - () -> - client.resolvePreseededActorStagingEligibility( - ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString())) + assertThatThrownBy(() -> + client.resolvePreseededActorStagingEligibility( + ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("absent"); } @@ -281,15 +277,13 @@ void propagatesProviderFailuresWithFiniteDeadline() throws Exception { .thenThrow(unavailable); AccountPreseededActorStagingEligibilityClient client = newClient(stub); - assertThatThrownBy( - () -> - client.resolvePreseededActorStagingEligibility( - ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString())) + assertThatThrownBy(() -> + client.resolvePreseededActorStagingEligibility( + ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString())) .isSameAs(timeout); - assertThatThrownBy( - () -> - client.resolvePreseededActorStagingEligibility( - ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString())) + assertThatThrownBy(() -> + client.resolvePreseededActorStagingEligibility( + ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString())) .isSameAs(unavailable); verify(stub, times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); @@ -301,16 +295,14 @@ void rejectsPlaintextMissingClasspathTlsAndInvalidNamespaceBeforeChannelCreation CommonGrpcClientProperties plaintext = mtlsProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new AccountPreseededActorStagingEligibilityClient( - new ServiceEndpointsProperties(), plaintext, channelFactory, NAMESPACE)) + assertThatThrownBy(() -> + new AccountPreseededActorStagingEligibilityClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mTLS"); - assertThatThrownBy( - () -> - new AccountPreseededActorStagingEligibilityClient( - new ServiceEndpointsProperties(), null, channelFactory, NAMESPACE)) + assertThatThrownBy(() -> + new AccountPreseededActorStagingEligibilityClient( + new ServiceEndpointsProperties(), null, channelFactory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("TLS configuration is required"); @@ -319,10 +311,9 @@ void rejectsPlaintextMissingClasspathTlsAndInvalidNamespaceBeforeChannelCreation incompleteMtlsProperties(null, "entity.key", "account-ca.crt"), incompleteMtlsProperties("entity.crt", null, "account-ca.crt"), incompleteMtlsProperties("entity.crt", "entity.key", null))) { - assertThatThrownBy( - () -> - new AccountPreseededActorStagingEligibilityClient( - new ServiceEndpointsProperties(), incomplete, channelFactory, NAMESPACE)) + assertThatThrownBy(() -> + new AccountPreseededActorStagingEligibilityClient( + new ServiceEndpointsProperties(), incomplete, channelFactory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("certificate, key, and CA"); } @@ -332,18 +323,16 @@ void rejectsPlaintextMissingClasspathTlsAndInvalidNamespaceBeforeChannelCreation incompleteMtlsProperties("classpath:entity.crt", "entity.key", "account-ca.crt"), incompleteMtlsProperties("entity.crt", "classpath:entity.key", "account-ca.crt"), incompleteMtlsProperties("entity.crt", "entity.key", "classpath:account-ca.crt"))) { - assertThatThrownBy( - () -> - new AccountPreseededActorStagingEligibilityClient( - new ServiceEndpointsProperties(), classpath, channelFactory, NAMESPACE)) + assertThatThrownBy(() -> + new AccountPreseededActorStagingEligibilityClient( + new ServiceEndpointsProperties(), classpath, channelFactory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("file-backed"); } - assertThatThrownBy( - () -> - new AccountPreseededActorStagingEligibilityClient( - new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, "bad.ns")) + assertThatThrownBy(() -> + new AccountPreseededActorStagingEligibilityClient( + new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, "bad.ns")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("one DNS label"); verifyNoInteractions(channelFactory); @@ -395,10 +384,9 @@ void refusesCallsAfterCloseWithoutUsingTheStaleStub(@TempDir Path directory) thr setStub(client, staleStub); client.close(); - assertThatThrownBy( - () -> - client.resolvePreseededActorStagingEligibility( - ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString())) + assertThatThrownBy(() -> + client.resolvePreseededActorStagingEligibility( + ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not initialized"); verifyNoInteractions(staleStub); @@ -414,10 +402,9 @@ private static void assertRejected(ResolvePreseededActorStagingEligibilityRespon when(stub.resolvePreseededActorStagingEligibility(any())).thenReturn(response); AccountPreseededActorStagingEligibilityClient client = newClient(stub); - assertThatThrownBy( - () -> - client.resolvePreseededActorStagingEligibility( - ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString())) + assertThatThrownBy(() -> + client.resolvePreseededActorStagingEligibility( + ACCOUNT_ID.toString(), TENANT_ID.toString(), REQUEST_ID.toString())) .isInstanceOf(IllegalStateException.class); } @@ -429,10 +416,9 @@ private static void assertPreconditionRejected( when(stub.resolvePreseededActorStagingEligibility(any())).thenReturn(validResponse()); AccountPreseededActorStagingEligibilityClient client = newClient(stub); - assertThatThrownBy( - () -> - client.resolvePreseededActorStagingEligibility( - requestedAccountId, requestedTenantId, requestedRequestId)) + assertThatThrownBy(() -> + client.resolvePreseededActorStagingEligibility( + requestedAccountId, requestedTenantId, requestedRequestId)) .isInstanceOf(PreseededActorAssignmentService.PreconditionException.class) .hasMessage("Account actor-staging eligibility response does not match the exact request"); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java index bdc1135edd..89090e6faf 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/AccountRuntimeIdentityClientTest.java @@ -85,10 +85,9 @@ void rejectsMalformedInputsBeforeStubOrChannelUse() { assertThatThrownBy(() -> client.resolveRuntimeAccountIdentity(invalid[0], invalid[1])) .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - client.resolveRuntimeAccountIdentity( - "AB426BB3-A733-43F0-9C8E-2E379CBDF7EC", REQUEST_ID.toString())) + assertThatThrownBy(() -> + client.resolveRuntimeAccountIdentity( + "AB426BB3-A733-43F0-9C8E-2E379CBDF7EC", REQUEST_ID.toString())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Canonical nonnil canonical account ID is required") .hasCauseInstanceOf(IllegalArgumentException.class); @@ -99,10 +98,9 @@ void rejectsMalformedInputsBeforeStubOrChannelUse() { void rejectsUninitializedClientAndAbsentOwnerResponseWithoutActivation() throws Exception { GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); AccountRuntimeIdentityClient uninitialized = newClientWithoutStub(channelFactory); - assertThatThrownBy( - () -> - uninitialized.resolveRuntimeAccountIdentity( - ACCOUNT_ID.toString(), REQUEST_ID.toString())) + assertThatThrownBy(() -> + uninitialized.resolveRuntimeAccountIdentity( + ACCOUNT_ID.toString(), REQUEST_ID.toString())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not initialized"); verifyNoInteractions(channelFactory); @@ -110,9 +108,8 @@ void rejectsUninitializedClientAndAbsentOwnerResponseWithoutActivation() throws RuntimeAccountIdentityServiceGrpc.RuntimeAccountIdentityServiceBlockingStub stub = mockStub(); when(stub.resolveRuntimeAccountIdentity(any())).thenReturn(null); AccountRuntimeIdentityClient client = newClient(stub); - assertThatThrownBy( - () -> - client.resolveRuntimeAccountIdentity(ACCOUNT_ID.toString(), REQUEST_ID.toString())) + assertThatThrownBy(() -> + client.resolveRuntimeAccountIdentity(ACCOUNT_ID.toString(), REQUEST_ID.toString())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("absent"); } @@ -155,13 +152,11 @@ void propagatesTimeoutAndProviderFailuresWithFiniteDeadline() throws Exception { when(stub.resolveRuntimeAccountIdentity(any())).thenThrow(timeout).thenThrow(unavailable); AccountRuntimeIdentityClient client = newClient(stub); - assertThatThrownBy( - () -> - client.resolveRuntimeAccountIdentity(ACCOUNT_ID.toString(), REQUEST_ID.toString())) + assertThatThrownBy(() -> + client.resolveRuntimeAccountIdentity(ACCOUNT_ID.toString(), REQUEST_ID.toString())) .isSameAs(timeout); - assertThatThrownBy( - () -> - client.resolveRuntimeAccountIdentity(ACCOUNT_ID.toString(), REQUEST_ID.toString())) + assertThatThrownBy(() -> + client.resolveRuntimeAccountIdentity(ACCOUNT_ID.toString(), REQUEST_ID.toString())) .isSameAs(unavailable); verify(stub, times(2)).withDeadlineAfter(5L, TimeUnit.SECONDS); @@ -173,16 +168,14 @@ void rejectsPlaintextMissingClasspathTlsAndInvalidNamespaceBeforeChannelCreation CommonGrpcClientProperties plaintext = mtlsProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new AccountRuntimeIdentityClient( - new ServiceEndpointsProperties(), plaintext, channelFactory, NAMESPACE)) + assertThatThrownBy(() -> + new AccountRuntimeIdentityClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mTLS"); - assertThatThrownBy( - () -> - new AccountRuntimeIdentityClient( - new ServiceEndpointsProperties(), null, channelFactory, NAMESPACE)) + assertThatThrownBy(() -> + new AccountRuntimeIdentityClient( + new ServiceEndpointsProperties(), null, channelFactory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("TLS configuration is required"); @@ -191,10 +184,9 @@ void rejectsPlaintextMissingClasspathTlsAndInvalidNamespaceBeforeChannelCreation incompleteMtlsProperties(null, "entity.key", "account-ca.crt"), incompleteMtlsProperties("entity.crt", null, "account-ca.crt"), incompleteMtlsProperties("entity.crt", "entity.key", null))) { - assertThatThrownBy( - () -> - new AccountRuntimeIdentityClient( - new ServiceEndpointsProperties(), incomplete, channelFactory, NAMESPACE)) + assertThatThrownBy(() -> + new AccountRuntimeIdentityClient( + new ServiceEndpointsProperties(), incomplete, channelFactory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("certificate, key, and CA"); } @@ -204,18 +196,16 @@ void rejectsPlaintextMissingClasspathTlsAndInvalidNamespaceBeforeChannelCreation incompleteMtlsProperties("classpath:entity.crt", "entity.key", "account-ca.crt"), incompleteMtlsProperties("entity.crt", "classpath:entity.key", "account-ca.crt"), incompleteMtlsProperties("entity.crt", "entity.key", "classpath:account-ca.crt"))) { - assertThatThrownBy( - () -> - new AccountRuntimeIdentityClient( - new ServiceEndpointsProperties(), classpath, channelFactory, NAMESPACE)) + assertThatThrownBy(() -> + new AccountRuntimeIdentityClient( + new ServiceEndpointsProperties(), classpath, channelFactory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("file-backed"); } - assertThatThrownBy( - () -> - new AccountRuntimeIdentityClient( - new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, "bad.ns")) + assertThatThrownBy(() -> + new AccountRuntimeIdentityClient( + new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, "bad.ns")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("one DNS label"); verifyNoInteractions(channelFactory); @@ -266,9 +256,8 @@ void refusesCallsAfterCloseWithoutUsingTheStaleStub(@TempDir Path directory) thr setStub(client, staleStub); client.close(); - assertThatThrownBy( - () -> - client.resolveRuntimeAccountIdentity(ACCOUNT_ID.toString(), REQUEST_ID.toString())) + assertThatThrownBy(() -> + client.resolveRuntimeAccountIdentity(ACCOUNT_ID.toString(), REQUEST_ID.toString())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not initialized"); verifyNoInteractions(staleStub); @@ -283,9 +272,8 @@ private static void assertRejected(ResolveRuntimeAccountIdentityResponse respons when(stub.resolveRuntimeAccountIdentity(any())).thenReturn(response); AccountRuntimeIdentityClient client = newClient(stub); - assertThatThrownBy( - () -> - client.resolveRuntimeAccountIdentity(ACCOUNT_ID.toString(), REQUEST_ID.toString())) + assertThatThrownBy(() -> + client.resolveRuntimeAccountIdentity(ACCOUNT_ID.toString(), REQUEST_ID.toString())) .isInstanceOf(IllegalStateException.class); } @@ -295,9 +283,8 @@ private static void assertPreconditionRejected(ResolveRuntimeAccountIdentityResp when(stub.resolveRuntimeAccountIdentity(any())).thenReturn(response); AccountRuntimeIdentityClient client = newClient(stub); - assertThatThrownBy( - () -> - client.resolveRuntimeAccountIdentity(ACCOUNT_ID.toString(), REQUEST_ID.toString())) + assertThatThrownBy(() -> + client.resolveRuntimeAccountIdentity(ACCOUNT_ID.toString(), REQUEST_ID.toString())) .isInstanceOf(PreseededActorAssignmentService.PreconditionException.class) .hasMessage("Account runtime identity response does not match the exact request"); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java index 167ce139ea..ed380c8440 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/DemoAccountAuthenticationClientTest.java @@ -47,10 +47,9 @@ void usesCredentialAuthenticationAndExactReturnedUuidWithoutNumericIdentity() th assertThat(client.authenticateDemoOwner()).isEqualTo(actual); verify(stub) .authenticate( - argThat( - request -> - request.getEmail().equals("demo@example.com") - && request.getPassword().equals("swordfish"))); + argThat(request -> + request.getEmail().equals("demo@example.com") + && request.getPassword().equals("swordfish"))); } @Test @@ -73,12 +72,11 @@ void retriesOnlyTransientTransportFailuresWithTheSameCredentialRequest() throws verify(stub, times(3)).authenticate(requests.capture()); verify(stub, times(3)).withDeadlineAfter(5, TimeUnit.SECONDS); assertThat(requests.getAllValues()) - .allSatisfy( - request -> { - assertThat(request).isSameAs(requests.getValue()); - assertThat(request.getEmail()).isEqualTo("demo@example.com"); - assertThat(request.getPassword()).isEqualTo("swordfish"); - }); + .allSatisfy(request -> { + assertThat(request).isSameAs(requests.getValue()); + assertThat(request.getEmail()).isEqualTo("demo@example.com"); + assertThat(request.getPassword()).isEqualTo("swordfish"); + }); } @Test @@ -138,11 +136,10 @@ void interruptionStopsRetryAndPreservesInterruptWithoutReturningAnOwner() throws var stub = mock(AccountServiceGrpc.AccountServiceBlockingStub.class); when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); when(stub.authenticate(any())) - .thenAnswer( - invocation -> { - Thread.currentThread().interrupt(); - throw Status.UNAVAILABLE.asRuntimeException(); - }); + .thenAnswer(invocation -> { + Thread.currentThread().interrupt(); + throw Status.UNAVAILABLE.asRuntimeException(); + }); var client = client(stub); try { assertThatThrownBy(client::authenticateDemoOwner) @@ -231,15 +228,14 @@ void refusesUnavailableMalformedNilAndNoncanonicalOwners() throws Exception { void enabledUnusedClientDoesNotValidatePlaintextConfigurationUntilRequested() { contextRunner .withPropertyValues("firemud.grpc.plaintext=true") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThatThrownBy(() -> context.getBean(DemoAccountAuthenticationClient.class)) - .hasRootCauseInstanceOf(IllegalArgumentException.class) - .hasRootCauseMessage( - "Demo Account authentication require Entity Management workload mTLS"); - verifyNoInteractions(context.getBean(GrpcChannelFactory.class)); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThatThrownBy(() -> context.getBean(DemoAccountAuthenticationClient.class)) + .hasRootCauseInstanceOf(IllegalArgumentException.class) + .hasRootCauseMessage( + "Demo Account authentication require Entity Management workload mTLS"); + verifyNoInteractions(context.getBean(GrpcChannelFactory.class)); + }); } @Test @@ -250,15 +246,14 @@ void enabledUnusedClientDoesNotValidateMissingNamespaceUntilRequested() { "firemud.grpc.cert-chain=/fixture/client.crt", "firemud.grpc.private-key=/fixture/client.key", "firemud.grpc.ca-cert=/fixture/ca.crt") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThatThrownBy(() -> context.getBean(DemoAccountAuthenticationClient.class)) - .hasRootCauseInstanceOf(IllegalArgumentException.class) - .hasRootCauseMessage( - "Demo authentication requires the configured workload namespace"); - verifyNoInteractions(context.getBean(GrpcChannelFactory.class)); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThatThrownBy(() -> context.getBean(DemoAccountAuthenticationClient.class)) + .hasRootCauseInstanceOf(IllegalArgumentException.class) + .hasRootCauseMessage( + "Demo authentication requires the configured workload namespace"); + verifyNoInteractions(context.getBean(GrpcChannelFactory.class)); + }); } @Configuration(proxyBeanMethods = false) diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientMtlsTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientMtlsTest.java index e2eae8cc88..4257d427eb 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientMtlsTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientMtlsTest.java @@ -141,16 +141,14 @@ private void assertWrongServerCannotReceive(String alias) throws Exception { client.init(); assertThatThrownBy(() -> client.getCanonicalGameplayRosterReference(referenceRequest())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThatThrownBy(() -> client.getCanonicalGameplayRosterOwnerRead(ownerRequest())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); var retirement = retirementRequest(referenceRequest()); var confirmation = CanonicalGameplayRosterRetirementEvidence.confirmation( @@ -159,17 +157,15 @@ private void assertWrongServerCannotReceive(String alias) throws Exception { retirement, UUID.randomUUID(), 1000)); assertThatThrownBy(() -> client.acknowledgeCanonicalGameplayRosterRetirement(retirement)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThatThrownBy( () -> client.confirmCanonicalGameplayRosterRetirementAcknowledgement(confirmation)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(observedAcknowledgement.get()).isNull(); assertThat(observedConfirmation.get()).isNull(); assertThat(handlerReads.get()).isZero(); @@ -214,10 +210,8 @@ void authenticatedRetirementTransferUsesExactBytesAndNoAmbientClaims() throws Ex CanonicalGameplayRosterRetirementEvidence.confirmation( foreign, CanonicalGameplayRosterRetirementEvidence.response(foreign, UUID.randomUUID(), 1000)); - assertThatThrownBy( - () -> - client.confirmCanonicalGameplayRosterRetirementAcknowledgement( - foreignConfirmation)) + assertThatThrownBy(() -> + client.confirmCanonicalGameplayRosterRetirementAcknowledgement(foreignConfirmation)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("namespace"); assertThat(receivedCalls.get()).isEqualTo(2); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java index b7ec182fab..5586e0cc3e 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionCanonicalGameplayRosterOwnerReadClientTest.java @@ -160,10 +160,9 @@ void requiresFileBackedMtlsAndPinsExactSameNamespaceGameSessionPeer(@TempDir Pat var channelFactory = mock(GrpcChannelFactory.class); var invalidTls = mtlsProperties(); invalidTls.setPlaintext(true); - assertThatThrownBy( - () -> - new GameSessionCanonicalGameplayRosterOwnerReadClient( - new ServiceEndpointsProperties(), invalidTls, channelFactory, NAMESPACE)) + assertThatThrownBy(() -> + new GameSessionCanonicalGameplayRosterOwnerReadClient( + new ServiceEndpointsProperties(), invalidTls, channelFactory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mTLS"); @@ -253,15 +252,13 @@ void malformedReferenceOwnerResponseIsUnavailableWhileCallerGuardsStayInvalid() verify(stub).getCanonicalGameplayRosterReference(request); var guardedStub = mockStub(); var guardedClient = newClient(guardedStub); - assertThatThrownBy( - () -> - guardedClient.getCanonicalGameplayRosterReference( - request.toBuilder().setSchemaVersion(0).build())) + assertThatThrownBy(() -> + guardedClient.getCanonicalGameplayRosterReference( + request.toBuilder().setSchemaVersion(0).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - guardedClient.getCanonicalGameplayRosterReference( - retirementRequest("other").getOriginalSelection())) + assertThatThrownBy(() -> + guardedClient.getCanonicalGameplayRosterReference( + retirementRequest("other").getOriginalSelection())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("namespace"); verifyNoInteractions(guardedStub); @@ -377,16 +374,14 @@ void retirementRejectsNamespaceMalformedInputAndAmbientTransactionsBeforeTranspo assertThatThrownBy(() -> client.acknowledgeCanonicalGameplayRosterRetirement(foreign)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("namespace"); - assertThatThrownBy( - () -> - client.confirmCanonicalGameplayRosterRetirementAcknowledgement(foreignConfirmation)) + assertThatThrownBy(() -> + client.confirmCanonicalGameplayRosterRetirementAcknowledgement(foreignConfirmation)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("namespace"); var request = retirementRequest(NAMESPACE); - assertThatThrownBy( - () -> - client.acknowledgeCanonicalGameplayRosterRetirement( - request.toBuilder().setSchemaVersion(0).build())) + assertThatThrownBy(() -> + client.acknowledgeCanonicalGameplayRosterRetirement( + request.toBuilder().setSchemaVersion(0).build())) .isInstanceOf(IllegalArgumentException.class); var confirmation = CanonicalGameplayRosterRetirementEvidence.confirmation( @@ -416,9 +411,8 @@ void retirementRejectsNamespaceMalformedInputAndAmbientTransactionsBeforeTranspo assertThatThrownBy(() -> uninitialized.acknowledgeCanonicalGameplayRosterRetirement(request)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not initialized"); - assertThatThrownBy( - () -> - uninitialized.confirmCanonicalGameplayRosterRetirementAcknowledgement(confirmation)) + assertThatThrownBy(() -> + uninitialized.confirmCanonicalGameplayRosterRetirementAcknowledgement(confirmation)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("not initialized"); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java index 94241c19ce..e3da4c8437 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/client/GameSessionPreseededActorAssignmentOwnerReadClientTest.java @@ -49,16 +49,14 @@ void requiresStrictFileBackedMtlsAndValidWorkloadNamespace() { CommonGrpcClientProperties plaintext = mtlsProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new GameSessionPreseededActorAssignmentOwnerReadClient( - new ServiceEndpointsProperties(), plaintext, channelFactory, NAMESPACE)) + assertThatThrownBy(() -> + new GameSessionPreseededActorAssignmentOwnerReadClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mTLS"); - assertThatThrownBy( - () -> - new GameSessionPreseededActorAssignmentOwnerReadClient( - new ServiceEndpointsProperties(), null, channelFactory, NAMESPACE)) + assertThatThrownBy(() -> + new GameSessionPreseededActorAssignmentOwnerReadClient( + new ServiceEndpointsProperties(), null, channelFactory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("TLS configuration is required"); @@ -67,10 +65,9 @@ void requiresStrictFileBackedMtlsAndValidWorkloadNamespace() { incompleteMtlsProperties(null, "entity.key", "gs-ca.crt"), incompleteMtlsProperties("entity.crt", null, "gs-ca.crt"), incompleteMtlsProperties("entity.crt", "entity.key", null))) { - assertThatThrownBy( - () -> - new GameSessionPreseededActorAssignmentOwnerReadClient( - new ServiceEndpointsProperties(), incomplete, channelFactory, NAMESPACE)) + assertThatThrownBy(() -> + new GameSessionPreseededActorAssignmentOwnerReadClient( + new ServiceEndpointsProperties(), incomplete, channelFactory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("certificate, key, and CA"); } @@ -80,18 +77,16 @@ void requiresStrictFileBackedMtlsAndValidWorkloadNamespace() { incompleteMtlsProperties("classpath:entity.crt", "entity.key", "gs-ca.crt"), incompleteMtlsProperties("entity.crt", "classpath:entity.key", "gs-ca.crt"), incompleteMtlsProperties("entity.crt", "entity.key", "classpath:gs-ca.crt"))) { - assertThatThrownBy( - () -> - new GameSessionPreseededActorAssignmentOwnerReadClient( - new ServiceEndpointsProperties(), classpath, channelFactory, NAMESPACE)) + assertThatThrownBy(() -> + new GameSessionPreseededActorAssignmentOwnerReadClient( + new ServiceEndpointsProperties(), classpath, channelFactory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("file-backed"); } - assertThatThrownBy( - () -> - new GameSessionPreseededActorAssignmentOwnerReadClient( - new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, "bad.ns")) + assertThatThrownBy(() -> + new GameSessionPreseededActorAssignmentOwnerReadClient( + new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, "bad.ns")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("one DNS label"); verifyNoInteractions(channelFactory); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java index df3dc5964e..4d82bfedbf 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/CanonicalGameplayRosterConfigurationTest.java @@ -116,15 +116,14 @@ private static void processConfigurationClasses(AnnotationConfigApplicationConte private static Set registeredTypeNames(AnnotationConfigApplicationContext context) { var beanFactory = context.getBeanFactory(); return Arrays.stream(beanFactory.getBeanDefinitionNames()) - .flatMap( - name -> { - var definition = beanFactory.getBeanDefinition(name); - var beanType = beanFactory.getType(name, false); - return Arrays.stream( - new String[] { - definition.getBeanClassName(), beanType == null ? null : beanType.getName() - }); - }) + .flatMap(name -> { + var definition = beanFactory.getBeanDefinition(name); + var beanType = beanFactory.getType(name, false); + return Arrays.stream( + new String[] { + definition.getBeanClassName(), beanType == null ? null : beanType.getName() + }); + }) .filter(typeName -> typeName != null) .collect(Collectors.toSet()); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java index f9ff74c6e4..da0c23a867 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/config/PreseededActorAssignmentConfigurationTest.java @@ -45,19 +45,17 @@ void manualCompositionDeniesByDefaultBeforeReadsOrPersistence() { assertThatThrownBy(() -> service.assign(request)) .isInstanceOf(AdminAuthorizationException.class) .hasMessage("PRESEEDED_ASSIGNMENT_RUN_OWNED_ACTION_GRANT_UNAVAILABLE"); - assertThatThrownBy( - () -> - accountIdentityPort.resolveRuntimeAccountIdentity( - request.canonicalAccountUuid().toString(), request.assignmentUuid().toString())) + assertThatThrownBy(() -> + accountIdentityPort.resolveRuntimeAccountIdentity( + request.canonicalAccountUuid().toString(), request.assignmentUuid().toString())) .isInstanceOf( PreseededActorAssignmentOwnerEvidencePort.OwnerEvidenceUnavailableException.class) .hasMessage("PRESEEDED_ASSIGNMENT_OWNER_EVIDENCE_UNAVAILABLE"); - assertThatThrownBy( - () -> - stagingEligibilityPort.resolvePreseededActorStagingEligibility( - request.canonicalAccountUuid().toString(), - request.expectedTarget().canonicalTenantUuid().toString(), - request.assignmentUuid().toString())) + assertThatThrownBy(() -> + stagingEligibilityPort.resolvePreseededActorStagingEligibility( + request.canonicalAccountUuid().toString(), + request.expectedTarget().canonicalTenantUuid().toString(), + request.assignmentUuid().toString())) .isInstanceOf( PreseededActorAssignmentOwnerEvidencePort.OwnerEvidenceUnavailableException.class) .hasMessage("PRESEEDED_ASSIGNMENT_OWNER_EVIDENCE_UNAVAILABLE"); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java index ca7568a1b6..568829a695 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java @@ -57,17 +57,15 @@ void acceptsOnlyExactSameNamespaceGameSessionCertificate() { ServerCallHandler next = mock(ServerCallHandler.class); ServerCall.Listener listener = new ServerCall.Listener<>() {}; when(next.startCall(any(), any())) - .thenAnswer( - invocation -> { - assertThat(CanonicalGameplayRosterPeerInterceptor.currentVerifiedPeer()) - .isNotNull() - .satisfies( - peer -> { - assertThat(peer.isService("game-session-service")).isTrue(); - assertThat(peer.isInNamespace(WORKLOAD_NAMESPACE)).isTrue(); - }); - return listener; - }); + .thenAnswer(invocation -> { + assertThat(CanonicalGameplayRosterPeerInterceptor.currentVerifiedPeer()) + .isNotNull() + .satisfies(peer -> { + assertThat(peer.isService("game-session-service")).isTrue(); + assertThat(peer.isInNamespace(WORKLOAD_NAMESPACE)).isTrue(); + }); + return listener; + }); interceptor.interceptCall(call, new Metadata(), next); @@ -84,11 +82,10 @@ void selectedAssignmentMethodUsesTheSameNamespaceAndEndUserContextGuard() { peerSession("spiffe://firemud/ns/gameplay/sa/game-session-service")); ServerCallHandler trustedNext = mock(ServerCallHandler.class); when(trustedNext.startCall(any(), any())) - .thenAnswer( - invocation -> { - assertThat(CanonicalGameplayRosterPeerInterceptor.currentVerifiedPeer()).isNotNull(); - return new ServerCall.Listener<>() {}; - }); + .thenAnswer(invocation -> { + assertThat(CanonicalGameplayRosterPeerInterceptor.currentVerifiedPeer()).isNotNull(); + return new ServerCall.Listener<>() {}; + }); interceptor.interceptCall(trustedCall, new Metadata(), trustedNext); @@ -133,12 +130,10 @@ void bothCreatedRosterMethodsUseTheSameCertificateNamespaceAndEndUserGuard() { callFor(method, peerSession("spiffe://firemud/ns/gameplay/sa/game-session-service")); ServerCallHandler trustedNext = mock(ServerCallHandler.class); when(trustedNext.startCall(any(), any())) - .thenAnswer( - invocation -> { - assertThat(CanonicalGameplayRosterPeerInterceptor.currentVerifiedPeer()) - .isNotNull(); - return new ServerCall.Listener<>() {}; - }); + .thenAnswer(invocation -> { + assertThat(CanonicalGameplayRosterPeerInterceptor.currentVerifiedPeer()).isNotNull(); + return new ServerCall.Listener<>() {}; + }); interceptor.interceptCall(trusted, new Metadata(), trustedNext); verify(trustedNext).startCall(any(), any()); @@ -251,10 +246,9 @@ void rejectsAbsentWrongNamespaceAndNonGameSessionCertificates() { verify(call) .close( - org.mockito.ArgumentMatchers.argThat( - status -> - status.getCode() == Status.Code.PERMISSION_DENIED - && "Trusted Game Session peer required".equals(status.getDescription())), + org.mockito.ArgumentMatchers.argThat(status -> + status.getCode() == Status.Code.PERMISSION_DENIED + && "Trusted Game Session peer required".equals(status.getDescription())), any(Metadata.class)); verify(next, never()).startCall(any(), any()); } @@ -275,10 +269,9 @@ void rejectsBearerPlayerContextEvenWhenCertificateIsTrusted() { verify(call) .close( - org.mockito.ArgumentMatchers.argThat( - status -> - status.getCode() == Status.Code.PERMISSION_DENIED - && "Trusted Game Session peer required".equals(status.getDescription())), + org.mockito.ArgumentMatchers.argThat(status -> + status.getCode() == Status.Code.PERMISSION_DENIED + && "Trusted Game Session peer required".equals(status.getDescription())), any(Metadata.class)); verify(next, never()).startCall(any(), any()); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptorTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptorTest.java index e10e4ff515..74d8dda1f2 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptorTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalPreseededActorAssignmentPeerInterceptorTest.java @@ -52,15 +52,14 @@ void acceptsOnlyTheExactSameNamespaceGameSessionCertificateForTheWriteMethod() { CanonicalPreseededActorAssignmentPeerInterceptor.METHOD_NAME, peerSession(EXACT_PEER)); ServerCallHandler next = mock(ServerCallHandler.class); when(next.startCall(any(), any())) - .thenAnswer( - invocation -> { - var peer = CanonicalPreseededActorAssignmentPeerInterceptor.currentVerifiedPeer(); - assertThat(peer).isNotNull(); - assertThat(peer.uri()).isEqualTo(EXACT_PEER); - assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); - assertThat(SessionContext.isInternalService()).isFalse(); - return new ServerCall.Listener<>() {}; - }); + .thenAnswer(invocation -> { + var peer = CanonicalPreseededActorAssignmentPeerInterceptor.currentVerifiedPeer(); + assertThat(peer).isNotNull(); + assertThat(peer.uri()).isEqualTo(EXACT_PEER); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + assertThat(SessionContext.isInternalService()).isFalse(); + return new ServerCall.Listener<>() {}; + }); interceptor.interceptCall(call, new Metadata(), next); @@ -76,16 +75,14 @@ void acceptsOnlyTheExactSameNamespaceWorldCertificateForTheReceiptReadMethod() { peerSession(EXACT_WORLD_PEER)); ServerCallHandler next = mock(ServerCallHandler.class); when(next.startCall(any(), any())) - .thenAnswer( - invocation -> { - var peer = - CanonicalPreseededActorAssignmentPeerInterceptor.currentVerifiedWorldPeer(); - assertThat(peer).isNotNull(); - assertThat(peer.uri()).isEqualTo(EXACT_WORLD_PEER); - assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); - assertThat(SessionContext.isInternalService()).isFalse(); - return new ServerCall.Listener<>() {}; - }); + .thenAnswer(invocation -> { + var peer = CanonicalPreseededActorAssignmentPeerInterceptor.currentVerifiedWorldPeer(); + assertThat(peer).isNotNull(); + assertThat(peer.uri()).isEqualTo(EXACT_WORLD_PEER); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + assertThat(SessionContext.isInternalService()).isFalse(); + return new ServerCall.Listener<>() {}; + }); interceptor.interceptCall(call, new Metadata(), next); @@ -101,22 +98,18 @@ void runtimeReadHasItsOwnExactGameSessionPurposeAndNeverWorldOrAssignmentAuthori peerSession(EXACT_PEER)); ServerCallHandler next = mock(ServerCallHandler.class); when(next.startCall(any(), any())) - .thenAnswer( - invocation -> { - CanonicalPreseededActorAssignmentPeerInterceptor.requireVerifiedRuntimeReferencePeer( - NAMESPACE); - assertThatThrownBy( - () -> - CanonicalPreseededActorAssignmentPeerInterceptor.requireVerifiedWorldPeer( - NAMESPACE)) - .isInstanceOf(io.grpc.StatusRuntimeException.class); - assertThatThrownBy( - () -> - CanonicalPreseededActorAssignmentPeerInterceptor.requireVerifiedPeer( - NAMESPACE)) - .isInstanceOf(io.grpc.StatusRuntimeException.class); - return new ServerCall.Listener<>() {}; - }); + .thenAnswer(invocation -> { + CanonicalPreseededActorAssignmentPeerInterceptor.requireVerifiedRuntimeReferencePeer( + NAMESPACE); + assertThatThrownBy(() -> + CanonicalPreseededActorAssignmentPeerInterceptor.requireVerifiedWorldPeer( + NAMESPACE)) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + assertThatThrownBy(() -> + CanonicalPreseededActorAssignmentPeerInterceptor.requireVerifiedPeer(NAMESPACE)) + .isInstanceOf(io.grpc.StatusRuntimeException.class); + return new ServerCall.Listener<>() {}; + }); interceptor.interceptCall(readCall, new Metadata(), next); verify(next).startCall(any(), any()); for (String uri : diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryServiceTest.java index 33e3ef1565..d52ea0c32e 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRecoveryServiceTest.java @@ -52,19 +52,17 @@ void independentlyReadsExactOwnerOutsideSqlThenClosesInOneLocalTransaction() { UUID.fromString(owner.getTargetFenceUuid()), null); when(ownerClient.getCanonicalGameplayRosterReference(request.getOriginalSelection())) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - return owner; - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return owner; + }); when(repository.closeAdmission(request, owner, policy)) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); - return response; - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + return response; + }); var service = new CanonicalGameplayRosterRecoveryService( repository, ownerClient, localTransactions(), policy); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionServiceTest.java index d0e355f24c..c416d1d099 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterRetentionServiceTest.java @@ -51,11 +51,10 @@ class CanonicalGameplayRosterRetentionServiceTest { @BeforeEach void currentRetiredFixturesAlreadyHaveQualifiedSeals() { when(repository.initializeRetainedRetirement(any())) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return true; - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return true; + }); } @Test @@ -121,17 +120,15 @@ void boundedPreparationFailureDoesNotBlockNextSnapshotOrRequireOwnerAvailability when(repository.candidates(null, 2)).thenReturn(List.of(failing, advancing)); when(repository.health()).thenReturn(new Health(0, 0)); when(repository.prepareRetirement(failing, 2)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - throw new IllegalStateException("original page unavailable"); - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + throw new IllegalStateException("original page unavailable"); + }); when(repository.prepareRetirement(advancing, 2)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return 2; - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return 2; + }); service.sweep(); verify(repository).prepareRetirement(failing, 2); verify(repository).prepareRetirement(advancing, 2); @@ -148,66 +145,54 @@ void boundedPagesPassUnavailableAndUnknownOwnersThenDisposeOnlyRetiredCandidates var eligible = candidate(3, "RETIRED"); var held = candidate(4, "RETIRED"); when(repository.candidates(null, 2)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return List.of(unavailable, unknown); - }) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return List.of(); - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return List.of(unavailable, unknown); + }) + .thenAnswer(ignored -> { + assertSqlTransaction(); + return List.of(); + }); when(repository.candidates(unknown.binding().snapshot().snapshotUuid(), 2)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return List.of(eligible, held); - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return List.of(eligible, held); + }); when(repository.candidates(held.binding().snapshot().snapshotUuid(), 2)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return List.of(); - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return List.of(); + }); when(ownerClient.getCanonicalGameplayRosterReference(unavailable.ownerRequest())) - .thenAnswer( - ignored -> { - assertOutsideTransaction(); - throw new IllegalStateException("Owner unavailable"); - }); + .thenAnswer(ignored -> { + assertOutsideTransaction(); + throw new IllegalStateException("Owner unavailable"); + }); when(ownerClient.getCanonicalGameplayRosterReference(unknown.ownerRequest())) - .thenAnswer( - ignored -> { - assertOutsideTransaction(); - return GetCanonicalGameplayRosterReferenceResponse.newBuilder() - .setStateValue(77) - .build(); - }); + .thenAnswer(ignored -> { + assertOutsideTransaction(); + return GetCanonicalGameplayRosterReferenceResponse.newBuilder().setStateValue(77).build(); + }); when(repository.dispose(eligible)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return true; - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return true; + }); when(repository.dispose(held)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return false; - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return false; + }); when(repository.purgeDisposedTombstones(2)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return 1; - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return 1; + }); when(repository.health()) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return new Health(91, 17); - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return new Health(91, 17); + }); service.sweep(); verify(repository, never()).dispose(any()); @@ -262,35 +247,30 @@ void positiveRetirementIsObservedLocallyAndDisposalWaitsForARetiredCandidatePage when(repository.candidates(refusedSnapshot.binding().snapshot().snapshotUuid(), 2)) .thenReturn(List.of(retiredSnapshot)); when(ownerClient.getCanonicalGameplayRosterReference(protectedSnapshot.ownerRequest())) - .thenAnswer( - ignored -> { - assertOutsideTransaction(); - return proof; - }); + .thenAnswer(ignored -> { + assertOutsideTransaction(); + return proof; + }); when(ownerClient.getCanonicalGameplayRosterReference(refusedSnapshot.ownerRequest())) - .thenAnswer( - ignored -> { - assertOutsideTransaction(); - return refusedProof; - }); + .thenAnswer(ignored -> { + assertOutsideTransaction(); + return refusedProof; + }); when(repository.observeRetirement(protectedSnapshot, proof, policy)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return true; - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return true; + }); when(repository.observeRetirement(refusedSnapshot, refusedProof, policy)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return false; - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return false; + }); when(repository.dispose(retiredSnapshot)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return true; - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return true; + }); when(repository.health()).thenReturn(new Health(0, 0)); service.sweep(); @@ -382,23 +362,20 @@ void closedAdmissionsUseIndependentOwnerReadsOutsideSqlAndABoundedSeparateCursor when(repository.closedAdmissionCandidates(null, 2)).thenReturn(List.of(closure)); when(repository.closedAdmissionCandidates(closure.operationUuid(), 2)).thenReturn(List.of()); when(ownerClient.getCanonicalGameplayRosterReference(original)) - .thenAnswer( - ignored -> { - assertOutsideTransaction(); - return owner; - }); + .thenAnswer(ignored -> { + assertOutsideTransaction(); + return owner; + }); when(repository.purgeClosedAdmission(closure, owner)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return false; - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return false; + }); when(repository.purgeOrphanOpenAdmissions(policy, 2)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return 0; - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return 0; + }); when(repository.health()).thenReturn(new Health(0, 0)); service.sweep(); service.sweep(); @@ -420,11 +397,10 @@ void failedSnapshotPageStillProcessesClosedAdmissionsPurgesAndHealth() { .thenThrow(new org.jooq.exception.DataAccessException("snapshot mapping failed")); when(repository.closedAdmissionCandidates(null, 2)).thenReturn(List.of(closure)); when(ownerClient.getCanonicalGameplayRosterReference(owner.getRequest())) - .thenAnswer( - ignored -> { - assertOutsideTransaction(); - return owner; - }); + .thenAnswer(ignored -> { + assertOutsideTransaction(); + return owner; + }); when(repository.purgeClosedAdmission(closure, owner)).thenReturn(true); when(repository.health()).thenReturn(new Health(11, 3)); @@ -460,11 +436,10 @@ void failedClosedAdmissionPageStillRunsPurgesAndHealthAndPreservesCandidateCount @Test void failedOrphanPurgeStillRunsDisposedPurgeAndHealth() { when(repository.purgeOrphanOpenAdmissions(policy, 2)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - throw new org.jooq.exception.DataAccessException("orphan purge unavailable"); - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + throw new org.jooq.exception.DataAccessException("orphan purge unavailable"); + }); when(repository.health()).thenReturn(new Health(0, 0)); service.sweep(); @@ -476,11 +451,10 @@ void failedOrphanPurgeStillRunsDisposedPurgeAndHealth() { @Test void failedDisposedPurgeStillRefreshesHealth() { when(repository.purgeDisposedTombstones(2)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - throw new org.jooq.exception.DataAccessException("disposed purge unavailable"); - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + throw new org.jooq.exception.DataAccessException("disposed purge unavailable"); + }); when(repository.health()).thenReturn(new Health(4, 2)); service.sweep(); @@ -592,27 +566,23 @@ void waitingTransferUsesIndependentPositiveOwnerReadOutsideSqlAndNeverAcknowledg CanonicalGameplayRosterReferenceEvidence.response( candidate.ownerRequest(), 1, new UUID(3, 1), null); when(ownerClient.getCanonicalGameplayRosterReference(candidate.ownerRequest())) - .thenAnswer( - ignored -> { - assertOutsideTransaction(); - return nonterminal; - }) - .thenAnswer( - ignored -> { - assertOutsideTransaction(); - throw new IllegalStateException("unavailable"); - }) - .thenAnswer( - ignored -> { - assertOutsideTransaction(); - return retirement(candidate); - }); + .thenAnswer(ignored -> { + assertOutsideTransaction(); + return nonterminal; + }) + .thenAnswer(ignored -> { + assertOutsideTransaction(); + throw new IllegalStateException("unavailable"); + }) + .thenAnswer(ignored -> { + assertOutsideTransaction(); + return retirement(candidate); + }); when(repository.observeWaitingRetirement(waiting, retirement(candidate))) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return true; - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return true; + }); when(repository.health()).thenReturn(new Health(0, 0)); service.sweep(); @@ -650,49 +620,42 @@ void lostAcknowledgementRetriesStableRequestAndConfirmationUsesCommittedActualRe when(repository.retirementTransfers(null, 2)).thenReturn(List.of(pending)); when(repository.retirementTransfers(pending.observationUuid(), 2)) .thenReturn(List.of(pending)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - assertThat(committed.get()).isTrue(); - return List.of(acknowledged); - }) + .thenAnswer(ignored -> { + assertSqlTransaction(); + assertThat(committed.get()).isTrue(); + return List.of(acknowledged); + }) .thenReturn(List.of(acknowledged)); when(ownerClient.acknowledgeCanonicalGameplayRosterRetirement(request)) - .thenAnswer( - ignored -> { - assertOutsideTransaction(); - throw new IllegalStateException("ACK reply lost"); - }) - .thenAnswer( - ignored -> { - assertOutsideTransaction(); - return acknowledgement; - }); + .thenAnswer(ignored -> { + assertOutsideTransaction(); + throw new IllegalStateException("ACK reply lost"); + }) + .thenAnswer(ignored -> { + assertOutsideTransaction(); + return acknowledgement; + }); when(repository.recordRetirementAcknowledgement(pending, acknowledgement)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - committed.set(true); - return true; - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + committed.set(true); + return true; + }); when(ownerClient.confirmCanonicalGameplayRosterRetirementAcknowledgement(confirmation)) - .thenAnswer( - ignored -> { - assertOutsideTransaction(); - assertThat(committed.get()).isTrue(); - throw new IllegalStateException("confirmation reply lost"); - }) - .thenAnswer( - ignored -> { - assertOutsideTransaction(); - return confirmationResponse; - }); + .thenAnswer(ignored -> { + assertOutsideTransaction(); + assertThat(committed.get()).isTrue(); + throw new IllegalStateException("confirmation reply lost"); + }) + .thenAnswer(ignored -> { + assertOutsideTransaction(); + return confirmationResponse; + }); when(repository.recordRetirementConfirmation(acknowledged, confirmationResponse)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return true; - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return true; + }); when(repository.health()).thenReturn(new Health(0, 0)); service.sweep(); @@ -748,29 +711,25 @@ void idempotentTransferNoOpsDoNotRecordAcknowledgedOrConfirmedOutcomes() { CanonicalGameplayRosterRetirementEvidence.confirmationResponse(confirmation); when(repository.retirementTransfers(null, 2)).thenReturn(List.of(pending, acknowledged)); when(ownerClient.acknowledgeCanonicalGameplayRosterRetirement(pending.acknowledgementRequest())) - .thenAnswer( - ignored -> { - assertOutsideTransaction(); - return acknowledgement; - }); + .thenAnswer(ignored -> { + assertOutsideTransaction(); + return acknowledgement; + }); when(repository.recordRetirementAcknowledgement(pending, acknowledgement)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return false; - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return false; + }); when(ownerClient.confirmCanonicalGameplayRosterRetirementAcknowledgement(confirmation)) - .thenAnswer( - ignored -> { - assertOutsideTransaction(); - return confirmationResponse; - }); + .thenAnswer(ignored -> { + assertOutsideTransaction(); + return confirmationResponse; + }); when(repository.recordRetirementConfirmation(acknowledged, confirmationResponse)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return false; - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return false; + }); when(repository.health()).thenReturn(new Health(0, 0)); service.sweep(); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java index 05c96e5bdf..f333808ba9 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterSelectedAssignmentServiceTest.java @@ -273,11 +273,9 @@ void unsupportedCallerPolicyFailsBeforeOwnerResolution() { CanonicalGameplayRosterSelectedAssignmentService service = new CanonicalGameplayRosterSelectedAssignmentService(ownerPort, repository); - assertThatThrownBy( - () -> - service.read( - request( - withPolicy(target(), CanonicalGameplayRosterEntryPolicy.AUTO_PROVISIONED)))) + assertThatThrownBy(() -> + service.read( + request(withPolicy(target(), CanonicalGameplayRosterEntryPolicy.AUTO_PROVISIONED)))) .isInstanceOf(UnsupportedOperationException.class); verifyNoInteractions(ownerPort, repository); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterServiceTest.java index 9041f2a58e..ab4bde49f5 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/CanonicalGameplayRosterServiceTest.java @@ -83,23 +83,18 @@ void unsupportedEntryPoliciesFailBeforeOwnerReadsOrRosterLookup() { CanonicalGameplayRosterService service = new CanonicalGameplayRosterService(ownerPort, repository); - assertThatThrownBy( - () -> - service.read( - request( - withPolicy(target(), CanonicalGameplayRosterEntryPolicy.PLAYER_CREATED)))) + assertThatThrownBy(() -> + service.read( + request(withPolicy(target(), CanonicalGameplayRosterEntryPolicy.PLAYER_CREATED)))) .isInstanceOf(UnsupportedOperationException.class) .hasMessage("CANONICAL_GAMEPLAY_ROSTER_ENTRY_POLICY_UNSUPPORTED"); - assertThatThrownBy( - () -> - service.read( - request( - withPolicy(target(), CanonicalGameplayRosterEntryPolicy.AUTO_PROVISIONED)))) + assertThatThrownBy(() -> + service.read( + request(withPolicy(target(), CanonicalGameplayRosterEntryPolicy.AUTO_PROVISIONED)))) .isInstanceOf(UnsupportedOperationException.class); - assertThatThrownBy( - () -> - service.read( - request(withPolicy(target(), CanonicalGameplayRosterEntryPolicy.UNSPECIFIED)))) + assertThatThrownBy(() -> + service.read( + request(withPolicy(target(), CanonicalGameplayRosterEntryPolicy.UNSPECIFIED)))) .isInstanceOf(UnsupportedOperationException.class); verifyNoInteractions(ownerPort, repository); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayloadTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayloadTest.java index e9145597ea..216678fe58 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayloadTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/PreseededActorCorePayloadTest.java @@ -13,29 +13,24 @@ void rejectsMissingBlankOverlongOrControlCharacterDisplayNames() { assertThatThrownBy( () -> new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, " ")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new PreseededActorCorePayload( - PreseededActorCorePayload.ActorKind.PLAYER, "x".repeat(101))) + assertThatThrownBy(() -> + new PreseededActorCorePayload( + PreseededActorCorePayload.ActorKind.PLAYER, "x".repeat(101))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new PreseededActorCorePayload( - PreseededActorCorePayload.ActorKind.PLAYER, "Bad\nName")) + assertThatThrownBy(() -> + new PreseededActorCorePayload(PreseededActorCorePayload.ActorKind.PLAYER, "Bad\nName")) .isInstanceOf(IllegalArgumentException.class); } @Test void rejectsUnpairedUtf16Surrogates() { - assertThatThrownBy( - () -> - new PreseededActorCorePayload( - PreseededActorCorePayload.ActorKind.PLAYER, "Bad\uD800Name")) + assertThatThrownBy(() -> + new PreseededActorCorePayload( + PreseededActorCorePayload.ActorKind.PLAYER, "Bad\uD800Name")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new PreseededActorCorePayload( - PreseededActorCorePayload.ActorKind.PLAYER, "Bad\uDC00Name")) + assertThatThrownBy(() -> + new PreseededActorCorePayload( + PreseededActorCorePayload.ActorKind.PLAYER, "Bad\uDC00Name")) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapterTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapterTest.java index 0edcc33177..e3ab9750b3 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapterTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentAuthorityAdapterTest.java @@ -59,30 +59,26 @@ void validatesExactGrantThenRechecksItAgainstIndependentOwnerTarget(@TempDir Pat RunOwnedPreseededActorAssignmentAuthorityAdapter authority = authority(capabilityFile.toString()); - withGameSessionPeer( - () -> { - assertThatCode( - () -> - authority.requireAuthorized( - request(), - RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) - .doesNotThrowAnyException(); - assertThatCode( - () -> - authority.requireTargetBoundAuthorized( - request(), - ownerEvidence(), - RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) - .doesNotThrowAnyException(); - assertThatThrownBy( - () -> - authority.requireTargetBoundAuthorized( - request(), - ownerEvidenceWithNamespace( - UUID.fromString("60000000-0000-4000-8000-000000000006")), - RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) - .isInstanceOf(AdminAuthorizationException.class); - }); + withGameSessionPeer(() -> { + assertThatCode(() -> + authority.requireAuthorized( + request(), + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + .doesNotThrowAnyException(); + assertThatCode(() -> + authority.requireTargetBoundAuthorized( + request(), + ownerEvidence(), + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + .doesNotThrowAnyException(); + assertThatThrownBy(() -> + authority.requireTargetBoundAuthorized( + request(), + ownerEvidenceWithNamespace( + UUID.fromString("60000000-0000-4000-8000-000000000006")), + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + .isInstanceOf(AdminAuthorizationException.class); + }); } @Test @@ -107,21 +103,18 @@ void changedOrAbsentGrantDeniesBeforeOwnerReadsAndRepositoryMutation(@TempDir Pa new PreseededActorAssignmentService( authority, accountIdentityPort, stagingPort(), ownerEvidencePort, characterRepository); - withGameSessionPeer( - () -> - assertThatThrownBy(() -> service.assign(request)) - .isInstanceOf(AdminAuthorizationException.class)); + withGameSessionPeer(() -> + assertThatThrownBy(() -> service.assign(request)) + .isInstanceOf(AdminAuthorizationException.class)); verifyNoInteractions(accountIdentityPort, ownerEvidencePort, characterRepository); RunOwnedPreseededActorAssignmentAuthorityAdapter missingCapability = authority(""); - withGameSessionPeer( - () -> - assertThatThrownBy( - () -> - missingCapability.requireAuthorized( - request, - RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) - .isInstanceOf(AdminAuthorizationException.class)); + withGameSessionPeer(() -> + assertThatThrownBy(() -> + missingCapability.requireAuthorized( + request, + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + .isInstanceOf(AdminAuthorizationException.class)); } @Test @@ -131,11 +124,9 @@ void authenticatedUriMustBeExactAndUserContextRemainsDenied(@TempDir Path direct RunOwnedPreseededActorAssignmentAuthorityAdapter authority = authority(capabilityFile.toString()); - assertThatThrownBy( - () -> - authority.requireAuthorized( - request(), - RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + assertThatThrownBy(() -> + authority.requireAuthorized( + request(), RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) .isInstanceOf(AdminAuthorizationException.class); Context.current() .withValue( @@ -144,27 +135,21 @@ void authenticatedUriMustBeExactAndUserContextRemainsDenied(@TempDir Path direct "spiffe://firemud/ns/other/sa/game-session-service", "other", "game-session-service")) - .run( - () -> - assertThatThrownBy( - () -> - authority.requireAuthorized( - request(), - RunOwnedPreseededAssignmentAuthority.Action - .PRESEEDED_ACTOR_ASSIGNMENT)) - .isInstanceOf(AdminAuthorizationException.class)); + .run(() -> + assertThatThrownBy(() -> + authority.requireAuthorized( + request(), + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + .isInstanceOf(AdminAuthorizationException.class)); SessionContext.setContext(ACCOUNT_UUID.toString(), List.of(), java.util.Map.of()); try { - withGameSessionPeer( - () -> - assertThatThrownBy( - () -> - authority.requireAuthorized( - request(), - RunOwnedPreseededAssignmentAuthority.Action - .PRESEEDED_ACTOR_ASSIGNMENT)) - .isInstanceOf(AdminAuthorizationException.class)); + withGameSessionPeer(() -> + assertThatThrownBy(() -> + authority.requireAuthorized( + request(), + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + .isInstanceOf(AdminAuthorizationException.class)); } finally { SessionContext.clear(); } @@ -190,25 +175,23 @@ void grantReplacementBetweenOwnerReadsAndPersistenceFailsClosed(@TempDir Path di authority, accountIdentityPort, stagingPort(), ownerEvidencePort, characterRepository); when(accountIdentityPort.resolveRuntimeAccountIdentity( ACCOUNT_UUID.toString(), ASSIGNMENT_UUID.toString())) - .thenAnswer( - invocation -> { - PreseededActorAssignmentRequest replacement = - new PreseededActorAssignmentRequest( - ASSIGNMENT_UUID, - ACCOUNT_UUID, - new PreseededActorCorePayload( - PreseededActorCorePayload.ActorKind.PLAYER, "Changed Actor"), - request.expectedTarget()); - replaceGrant(capabilityFile, replacement); - return accountProof; - }); + .thenAnswer(invocation -> { + PreseededActorAssignmentRequest replacement = + new PreseededActorAssignmentRequest( + ASSIGNMENT_UUID, + ACCOUNT_UUID, + new PreseededActorCorePayload( + PreseededActorCorePayload.ActorKind.PLAYER, "Changed Actor"), + request.expectedTarget()); + replaceGrant(capabilityFile, replacement); + return accountProof; + }); when(ownerEvidencePort.resolveCurrentEligibleTarget(request, accountProof, stagingEvidence())) .thenReturn(ownerEvidence()); - withGameSessionPeer( - () -> - assertThatThrownBy(() -> service.assign(request)) - .isInstanceOf(AdminAuthorizationException.class)); + withGameSessionPeer(() -> + assertThatThrownBy(() -> service.assign(request)) + .isInstanceOf(AdminAuthorizationException.class)); verifyNoInteractions(characterRepository); } @@ -222,19 +205,17 @@ void activeServerTrustRootPinIsReevaluatedAtTheOwnerBoundBoundary(@TempDir Path new RunOwnedPreseededActorAssignmentAuthorityAdapter( capabilityFile.toString(), RUN_ID, PROJECT_NAME, NAMESPACE, activeTrustRoot::get); - withGameSessionPeer( - () -> { - authority.requireAuthorized( - request(), RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT); - activeTrustRoot.set("c".repeat(64)); - assertThatThrownBy( - () -> - authority.requireTargetBoundAuthorized( - request(), - ownerEvidence(), - RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) - .isInstanceOf(AdminAuthorizationException.class); - }); + withGameSessionPeer(() -> { + authority.requireAuthorized( + request(), RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT); + activeTrustRoot.set("c".repeat(64)); + assertThatThrownBy(() -> + authority.requireTargetBoundAuthorized( + request(), + ownerEvidence(), + RunOwnedPreseededAssignmentAuthority.Action.PRESEEDED_ACTOR_ASSIGNMENT)) + .isInstanceOf(AdminAuthorizationException.class); + }); } private static RunOwnedPreseededActorAssignmentAuthorityAdapter authority(String path) { diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java index 77f822a23f..b6dab13fdd 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/RunOwnedPreseededActorAssignmentCapabilityTest.java @@ -185,30 +185,26 @@ void trustRootPinRequiresOneValidCaAndUsesExactLoadedCertificateFingerprint() th RunOwnedPreseededActorAssignmentCapability.activeTrustRootFingerprint( new TrustManager[] {loadedTrustManager}, configuredFingerprint)) .isEqualTo(configuredFingerprint); - assertThatThrownBy( - () -> - RunOwnedPreseededActorAssignmentCapability.activeTrustRootFingerprint( - new TrustManager[] {loadedTrustManager}, "c".repeat(64))) + assertThatThrownBy(() -> + RunOwnedPreseededActorAssignmentCapability.activeTrustRootFingerprint( + new TrustManager[] {loadedTrustManager}, "c".repeat(64))) .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); when(loadedTrustManager.getAcceptedIssuers()) .thenReturn(new X509Certificate[] {trustedRoot, trustedRoot}); - assertThatThrownBy( - () -> - RunOwnedPreseededActorAssignmentCapability.activeTrustRootFingerprint( - new TrustManager[] {loadedTrustManager}, configuredFingerprint)) + assertThatThrownBy(() -> + RunOwnedPreseededActorAssignmentCapability.activeTrustRootFingerprint( + new TrustManager[] {loadedTrustManager}, configuredFingerprint)) .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); - assertThatThrownBy( - () -> - RunOwnedPreseededActorAssignmentCapability.fingerprintValidatedTrustRoot( - List.of(trustedRoot, trustedRoot))) + assertThatThrownBy(() -> + RunOwnedPreseededActorAssignmentCapability.fingerprintValidatedTrustRoot( + List.of(trustedRoot, trustedRoot))) .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); doThrow(new CertificateExpiredException()).when(trustedRoot).checkValidity(); - assertThatThrownBy( - () -> - RunOwnedPreseededActorAssignmentCapability.fingerprintValidatedTrustRoot( - List.of(trustedRoot))) + assertThatThrownBy(() -> + RunOwnedPreseededActorAssignmentCapability.fingerprintValidatedTrustRoot( + List.of(trustedRoot))) .isInstanceOf(RunOwnedPreseededActorAssignmentCapability.InvalidCapabilityException.class); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java index 3df1920192..0c56fa619e 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterGrpcAdapterTest.java @@ -245,10 +245,9 @@ void selectedAssignmentRejectsUnknownFieldsAndMalformedActorIdentityBeforeLookup CanonicalGameplayRosterTarget unknownTarget = target().toBuilder().setUnknownFields(unknownField()).build(); - assertThatThrownBy( - () -> - CanonicalGameplayRosterGrpcAdapter.parseSelectedAssignmentRequest( - selectedAssignmentRequest(unknownTarget))) + assertThatThrownBy(() -> + CanonicalGameplayRosterGrpcAdapter.parseSelectedAssignmentRequest( + selectedAssignmentRequest(unknownTarget))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Complete expected target is required"); @@ -256,10 +255,8 @@ void selectedAssignmentRejectsUnknownFieldsAndMalformedActorIdentityBeforeLookup selectedAssignmentRequest(target()).toBuilder() .setSelectedCharacterUuid("not-a-uuid") .build(); - assertThatThrownBy( - () -> - CanonicalGameplayRosterGrpcAdapter.parseSelectedAssignmentRequest( - malformedCharacter)) + assertThatThrownBy(() -> + CanonicalGameplayRosterGrpcAdapter.parseSelectedAssignmentRequest(malformedCharacter)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("selected_character_uuid"); @@ -278,10 +275,9 @@ void selectedAssignmentRejectsUnknownFieldsAndMalformedActorIdentityBeforeLookup .setCharacterId(UUID.randomUUID().toString()) .build()) .build(); - assertThatThrownBy( - () -> - CanonicalGameplayRosterGrpcAdapter.parseSelectedAssignmentRequest( - mismatchedContextActor)) + assertThatThrownBy(() -> + CanonicalGameplayRosterGrpcAdapter.parseSelectedAssignmentRequest( + mismatchedContextActor)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("playerExecutionContext.character_id must equal selectedCharacterUuid"); } @@ -340,53 +336,51 @@ void rpcErrorsUseCanonicalStatusesWithoutPartialResponses() { .thenThrow(new IllegalStateException("CANONICAL_GAMEPLAY_ROSTER_SNAPSHOT_STALE")); var selectedOwner = mock(CanonicalGameplayRosterOwnerEvidencePort.class); when(selectedOwner.resolveCurrentTarget(any())) - .thenAnswer( - call -> { - CanonicalGameplayRosterReadRequest request = call.getArgument(0); - return new CanonicalGameplayRosterOwnerEvidence( + .thenAnswer(call -> { + CanonicalGameplayRosterReadRequest request = call.getArgument(0); + return new CanonicalGameplayRosterOwnerEvidence( + request.requestUuid(), + request.canonicalAccountUuid(), + request.expectedTarget(), + Instant.parse("2026-10-01T00:00:00Z")); + }); + when(selectedOwner.readOriginalSelection(any())) + .thenAnswer(call -> { + CanonicalGameplayRosterReadRequest request = call.getArgument(0); + var original = + CanonicalGameplayRosterReferenceEvidence.request( request.requestUuid(), request.canonicalAccountUuid(), - request.expectedTarget(), - Instant.parse("2026-10-01T00:00:00Z")); - }); - when(selectedOwner.readOriginalSelection(any())) - .thenAnswer( - call -> { - CanonicalGameplayRosterReadRequest request = call.getArgument(0); - var original = - CanonicalGameplayRosterReferenceEvidence.request( - request.requestUuid(), - request.canonicalAccountUuid(), - request.playerExecutionContext().sessionUuid(), - "gameplay", - request.expectedTarget().toWire()); - var receipt = - net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse - .newBuilder() - .setCanonicalAccountUuid(request.canonicalAccountUuid().toString()) - .setTarget(request.expectedTarget().toWire()) - .setSnapshotUuid(selectedRequest.getExpectedSnapshot().getSnapshotUuid()) - .setSnapshotDigest(selectedRequest.getExpectedSnapshot().getSnapshotDigest()) - .addActors( - net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor - .newBuilder() - .setCharacterUuid(selectedRequest.getSelectedCharacterUuid()) - .setDisplayName("Fixture Actor") - .setActorKind( - net.firedevops.firemud.entitymanagement.v1 - .CanonicalGameplayRosterActorKind - .CANONICAL_ROSTER_ACTOR_KIND_PLAYER)) - .build(); - return CanonicalGameplayRosterReferenceEvidence.response( - original, 1L, UUID.randomUUID(), receipt) - .toBuilder() - .setSelectionInput( - net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput + request.playerExecutionContext().sessionUuid(), + "gameplay", + request.expectedTarget().toWire()); + var receipt = + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterResponse + .newBuilder() + .setCanonicalAccountUuid(request.canonicalAccountUuid().toString()) + .setTarget(request.expectedTarget().toWire()) + .setSnapshotUuid(selectedRequest.getExpectedSnapshot().getSnapshotUuid()) + .setSnapshotDigest(selectedRequest.getExpectedSnapshot().getSnapshotDigest()) + .addActors( + net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActor .newBuilder() - .setSchemaVersion(1)) - .setSelectedCharacterUuid(selectedRequest.getSelectedCharacterUuid()) + .setCharacterUuid(selectedRequest.getSelectedCharacterUuid()) + .setDisplayName("Fixture Actor") + .setActorKind( + net.firedevops.firemud.entitymanagement.v1 + .CanonicalGameplayRosterActorKind + .CANONICAL_ROSTER_ACTOR_KIND_PLAYER)) .build(); - }); + return CanonicalGameplayRosterReferenceEvidence.response( + original, 1L, UUID.randomUUID(), receipt) + .toBuilder() + .setSelectionInput( + net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput + .newBuilder() + .setSchemaVersion(1)) + .setSelectedCharacterUuid(selectedRequest.getSelectedCharacterUuid()) + .build(); + }); CanonicalGameplayRosterGrpcAdapter staleSnapshotAdapter = new CanonicalGameplayRosterGrpcAdapter( new CanonicalGameplayRosterService( @@ -654,25 +648,23 @@ void unexpectedIllegalStateExceptionReturnsInternalAndRecordsInternalMetric() { when(repository.reserveOriginalRosterAdmission(any())).thenReturn(UUID.randomUUID()); var owner = mock(CanonicalGameplayRosterOwnerEvidencePort.class); when(owner.readOriginalSelection(any())) - .thenAnswer( - call -> { - CanonicalGameplayRosterReadRequest request = call.getArgument(0); - var original = - CanonicalGameplayRosterReferenceEvidence.request( - request.requestUuid(), - request.canonicalAccountUuid(), - request.playerExecutionContext().sessionUuid(), - "gameplay", - request.expectedTarget().toWire()); - return CanonicalGameplayRosterReferenceEvidence.response( - original, 1L, UUID.randomUUID(), null); - }); + .thenAnswer(call -> { + CanonicalGameplayRosterReadRequest request = call.getArgument(0); + var original = + CanonicalGameplayRosterReferenceEvidence.request( + request.requestUuid(), + request.canonicalAccountUuid(), + request.playerExecutionContext().sessionUuid(), + "gameplay", + request.expectedTarget().toWire()); + return CanonicalGameplayRosterReferenceEvidence.response( + original, 1L, UUID.randomUUID(), null); + }); when(owner.resolveCurrentTarget(any())) - .thenAnswer( - call -> { - throw new IllegalStateException( - failures.getAndIncrement() == 0 ? null : "unexpected invariant"); - }); + .thenAnswer(call -> { + throw new IllegalStateException( + failures.getAndIncrement() == 0 ? null : "unexpected invariant"); + }); CanonicalGameplayRosterGrpcAdapter adapter = new CanonicalGameplayRosterGrpcAdapter( new CanonicalGameplayRosterService(owner, repository), @@ -742,11 +734,10 @@ private static void withTrustedPeer(String methodName, Runnable action) { Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_SSL_SESSION, trustedSession).build()); ServerCallHandler next = mock(ServerCallHandler.class); when(next.startCall(any(), any())) - .thenAnswer( - invocation -> { - action.run(); - return new ServerCall.Listener<>() {}; - }); + .thenAnswer(invocation -> { + action.run(); + return new ServerCall.Listener<>() {}; + }); new CanonicalGameplayRosterPeerInterceptor("gameplay") .interceptCall(call, new Metadata(), next); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterRecoveryGrpcAdapterMtlsTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterRecoveryGrpcAdapterMtlsTest.java index 718c00a172..0cf5251600 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterRecoveryGrpcAdapterMtlsTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalGameplayRosterRecoveryGrpcAdapterMtlsTest.java @@ -108,16 +108,15 @@ void exactGameSessionCertificateCarriesExactRecoveryRequestAndOriginalResponse() CanonicalGameplayRosterRecoveryEvidence.response( request, UUID.randomUUID(), 1, UUID.randomUUID(), null); when(recovery.recover(request)) - .thenAnswer( - ignored -> { - assertThat(CanonicalGameplayRosterPeerInterceptor.currentVerifiedPeer()).isNotNull(); - assertThat( - CanonicalGameplayRosterPeerInterceptor.currentVerifiedPeer() - .isService("game-session-service")) - .isTrue(); - assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); - return expected; - }); + .thenAnswer(ignored -> { + assertThat(CanonicalGameplayRosterPeerInterceptor.currentVerifiedPeer()).isNotNull(); + assertThat( + CanonicalGameplayRosterPeerInterceptor.currentVerifiedPeer() + .isService("game-session-service")) + .isTrue(); + assertThat(SessionContext.hasAuthenticatedCallerContext()).isFalse(); + return expected; + }); start(); var channel = channel("gs"); try { @@ -137,16 +136,14 @@ void wrongNamespaceAndServiceCannotReachRecoveryHandler() throws Exception { for (String alias : new String[] {"foreign", "account"}) { var channel = channel(alias); try { - assertThatThrownBy( - () -> - CanonicalGameplayRosterRecoveryServiceGrpc.newBlockingStub(channel) - .withDeadlineAfter(5, TimeUnit.SECONDS) - .recoverOriginalSelection(request())) + assertThatThrownBy(() -> + CanonicalGameplayRosterRecoveryServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .recoverOriginalSelection(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } finally { close(channel); } @@ -161,16 +158,14 @@ void localConflictReturnsBoundedFailureWithoutTransportSuccess() throws Exceptio start(); var channel = channel("gs"); try { - assertThatThrownBy( - () -> - CanonicalGameplayRosterRecoveryServiceGrpc.newBlockingStub(channel) - .withDeadlineAfter(5, TimeUnit.SECONDS) - .recoverOriginalSelection(request())) + assertThatThrownBy(() -> + CanonicalGameplayRosterRecoveryServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .recoverOriginalSelection(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); } finally { close(channel); } @@ -187,19 +182,16 @@ void invalidPersistedRecoveryStateReturnsUnavailableToAuthenticatedGameSession() start(); var channel = channel("gs"); try { - assertThatThrownBy( - () -> - CanonicalGameplayRosterRecoveryServiceGrpc.newBlockingStub(channel) - .withDeadlineAfter(5, TimeUnit.SECONDS) - .recoverOriginalSelection(request())) + assertThatThrownBy(() -> + CanonicalGameplayRosterRecoveryServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .recoverOriginalSelection(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE); - assertThat(Status.fromThrowable(failure).getDescription()) - .isEqualTo("Original selection recovery unavailable"); - }); + .satisfies(failure -> { + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(Status.fromThrowable(failure).getDescription()) + .isEqualTo("Original selection recovery unavailable"); + }); } finally { close(channel); } @@ -214,16 +206,14 @@ void malformedCallerRequestStillReturnsInvalidArgumentOverAuthenticatedTransport start(); var channel = channel("gs"); try { - assertThatThrownBy( - () -> - CanonicalGameplayRosterRecoveryServiceGrpc.newBlockingStub(channel) - .withDeadlineAfter(5, TimeUnit.SECONDS) - .recoverOriginalSelection(malformed)) + assertThatThrownBy(() -> + CanonicalGameplayRosterRecoveryServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .recoverOriginalSelection(malformed)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.INVALID_ARGUMENT)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT)); } finally { close(channel); } @@ -251,9 +241,8 @@ void malformedAuthenticatedOwnerUsesActualClientAndReturnsUnavailableBeforeSql() void authenticatedOwnerRecoveryMismatchUsesActualClientAndReturnsConflictBeforeSql() throws Exception { var request = request(); - startOwner( - original -> - owner(request).toBuilder().setRecoveryUuid(UUID.randomUUID().toString()).build()); + startOwner(original -> + owner(request).toBuilder().setRecoveryUuid(UUID.randomUUID().toString()).build()); var repository = mock(CanonicalGameplayRosterRetentionRepository.class); var transactions = mock(TransactionOperations.class); try (var ownerClient = ownerClient()) { @@ -277,12 +266,11 @@ void postValidationPersistedArgumentFailureReturnsUnavailableThroughActualOwnerC // real. var repository = mock(CanonicalGameplayRosterRetentionRepository.class); when(repository.closeAdmission(request, owner, policy())) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); - throw new IllegalArgumentException("Invalid retained original roster receipt"); - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + throw new IllegalArgumentException("Invalid retained original roster receipt"); + }); try (var ownerClient = ownerClient()) { ownerClient.init(); start( @@ -323,11 +311,10 @@ private void assertRecoveryStatus( CanonicalGameplayRosterRecoveryRequest request, Status.Code expected) throws Exception { var channel = channel("gs"); try { - assertThatThrownBy( - () -> - CanonicalGameplayRosterRecoveryServiceGrpc.newBlockingStub(channel) - .withDeadlineAfter(5, TimeUnit.SECONDS) - .recoverOriginalSelection(request)) + assertThatThrownBy(() -> + CanonicalGameplayRosterRecoveryServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .recoverOriginalSelection(request)) .isInstanceOf(StatusRuntimeException.class) .satisfies( failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcServiceTest.java index cb39dfefa4..8f400ae16e 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CanonicalPreseededActorAssignmentGrpcServiceTest.java @@ -570,19 +570,18 @@ void runtimeReferenceReturnsExactTypedProjectionOrOneBoundedFailure() { var malformed = invokeRuntimeRead(handler, wire.toBuilder().setSchemaVersion(2).build()); assertThat(malformed.errorCode).isEqualTo(Status.Code.INVALID_ARGUMENT); assertThat(malformed.terminalCount).isEqualTo(1); - assertThatThrownBy( - () -> - PreseededActorAssignmentGrpcCodec.fromRuntimeReferenceRequest( - wire.toBuilder() - .setUnknownFields( - com.google.protobuf.UnknownFieldSet.newBuilder() - .addField( - 99, - com.google.protobuf.UnknownFieldSet.Field.newBuilder() - .addVarint(1) - .build()) - .build()) - .build())) + assertThatThrownBy(() -> + PreseededActorAssignmentGrpcCodec.fromRuntimeReferenceRequest( + wire.toBuilder() + .setUnknownFields( + com.google.protobuf.UnknownFieldSet.newBuilder() + .addField( + 99, + com.google.protobuf.UnknownFieldSet.Field.newBuilder() + .addVarint(1) + .build()) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java index 46d37fbe00..2594457198 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityManagementGrpcServiceTest.java @@ -319,15 +319,14 @@ private EntityMutationEffectReplayService effectReplayService() { Mockito.anyString(), Mockito.any(), Mockito.any())) - .thenAnswer( - invocation -> { - String effectId = invocation.getArgument(1); - if (effectId == null || effectId.isBlank()) { - throw new ResponseStatusException( - HttpStatus.BAD_REQUEST, "Effect id is required for replay-guarded mutations"); - } - return ((java.util.function.Supplier) invocation.getArgument(3)).get(); - }); + .thenAnswer(invocation -> { + String effectId = invocation.getArgument(1); + if (effectId == null || effectId.isBlank()) { + throw new ResponseStatusException( + HttpStatus.BAD_REQUEST, "Effect id is required for replay-guarded mutations"); + } + return ((java.util.function.Supplier) invocation.getArgument(3)).get(); + }); return service; } @@ -441,22 +440,21 @@ void getDraftDesignDigestReturnsVersionScopedDigest() { publicationReadGuard()); AtomicReference ref = new AtomicReference<>(); - runAsGameDesign( - () -> - service.getDraftDesignDigest( - fullDigestRequest("1", "7"), - new StreamObserver<>() { - @Override - public void onNext(GetDraftDesignDigestResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - })); + runAsGameDesign(() -> + service.getDraftDesignDigest( + fullDigestRequest("1", "7"), + new StreamObserver<>() { + @Override + public void onNext(GetDraftDesignDigestResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + })); assertEquals("7", ref.get().getVersionId()); assertEquals("version:7", ref.get().getAppliedCommitId()); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java index 2f51dd30bc..dae93f9fe7 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/EntityMutationEffectReplayServiceTest.java @@ -34,14 +34,13 @@ void executeRejectsMissingOrBlankEffectIdBeforeMutation() { }; for (String effectId : new String[] {null, "", " \t "}) { - assertThatThrownBy( - () -> - service.execute( - 1L, - effectId, - "PickupItemFromRoom", - mutation, - PickupItemFromRoomResponse::parseFrom)) + assertThatThrownBy(() -> + service.execute( + 1L, + effectId, + "PickupItemFromRoom", + mutation, + PickupItemFromRoomResponse::parseFrom)) .isInstanceOf(org.springframework.web.server.ResponseStatusException.class) .hasMessageContaining("Effect id is required"); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java index 1ed41a7315..c072e7092c 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java @@ -126,16 +126,13 @@ void rejectsValidSourceResponseBoundToDifferentAssignmentBeforeReturningEligible PreseededActorAssignmentOwnerReadEvidence.Request.class))) .thenReturn(fixture.evidence()); - assertThatThrownBy( - () -> - new GameSessionPreseededActorAssignmentOwnerEvidenceAdapter(client, sourceNamespace) - .resolveCurrentEligibleTarget( - request, - identity( - sourceNamespace, - request.assignmentUuid(), - request.canonicalAccountUuid()), - staging)) + assertThatThrownBy(() -> + new GameSessionPreseededActorAssignmentOwnerEvidenceAdapter(client, sourceNamespace) + .resolveCurrentEligibleTarget( + request, + identity( + sourceNamespace, request.assignmentUuid(), request.canonicalAccountUuid()), + staging)) .isInstanceOf( PreseededActorAssignmentOwnerEvidencePort.OwnerEvidenceUnavailableException.class); } @@ -145,10 +142,9 @@ void accountSnapshotMustBindExactAssignmentAccountTenantAndCurrentStagingPurpose GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); var adapter = adapter(channelFactory); - assertThatThrownBy( - () -> - adapter.resolveCurrentEligibleTarget( - request(INSTANCE.toString()), identity(), staging(OTHER_TENANT))) + assertThatThrownBy(() -> + adapter.resolveCurrentEligibleTarget( + request(INSTANCE.toString()), identity(), staging(OTHER_TENANT))) .isInstanceOf( PreseededActorAssignmentOwnerEvidencePort.OwnerEvidenceUnavailableException.class); diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodecTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodecTest.java index a99ea7a990..ec4cf1aa4c 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodecTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/PreseededActorAssignmentGrpcCodecTest.java @@ -50,33 +50,29 @@ void decodesExactIntentAndPreservesOpaqueGameInstanceText() { @Test void rejectsUnsupportedSchemaUnknownFieldsAndMissingNestedValues() { - assertThatThrownBy( - () -> - PreseededActorAssignmentGrpcCodec.fromRequest( - request().toBuilder().setSchemaVersion(2).build())) + assertThatThrownBy(() -> + PreseededActorAssignmentGrpcCodec.fromRequest( + request().toBuilder().setSchemaVersion(2).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported schema_version"); - assertThatThrownBy( - () -> - PreseededActorAssignmentGrpcCodec.fromRequest( - request().toBuilder().setUnknownFields(unknownField()).build())) + assertThatThrownBy(() -> + PreseededActorAssignmentGrpcCodec.fromRequest( + request().toBuilder().setUnknownFields(unknownField()).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unknown fields"); - assertThatThrownBy( - () -> - PreseededActorAssignmentGrpcCodec.fromRequest( - request().toBuilder() - .setExpectedTarget( - request().getExpectedTarget().toBuilder() - .setUnknownFields(unknownField()) - .build()) - .build())) + assertThatThrownBy(() -> + PreseededActorAssignmentGrpcCodec.fromRequest( + request().toBuilder() + .setExpectedTarget( + request().getExpectedTarget().toBuilder() + .setUnknownFields(unknownField()) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unknown fields"); - assertThatThrownBy( - () -> - PreseededActorAssignmentGrpcCodec.fromRequest( - request().toBuilder().clearCorePayload().build())) + assertThatThrownBy(() -> + PreseededActorAssignmentGrpcCodec.fromRequest( + request().toBuilder().clearCorePayload().build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("complete assignment intent"); } @@ -163,15 +159,14 @@ void encodesOnlyThePersistedAssignmentOutcomeAndActorIdentity() { void refusesToExposeAResultForAnotherOperationOrDigest() { PreseededActorAssignmentRequest request = PreseededActorAssignmentGrpcCodec.fromRequest(request()); - assertThatThrownBy( - () -> - PreseededActorAssignmentGrpcCodec.toResponse( - request, - new PreseededActorAssignmentResult( - uuid("80000000-0000-4000-8000-000000000008"), - PreseededActorAssignmentResult.Outcome.ASSIGNED, - CHARACTER_UUID, - request.mutationIntentDigest()))) + assertThatThrownBy(() -> + PreseededActorAssignmentGrpcCodec.toResponse( + request, + new PreseededActorAssignmentResult( + uuid("80000000-0000-4000-8000-000000000008"), + PreseededActorAssignmentResult.Outcome.ASSIGNED, + CHARACTER_UUID, + request.mutationIntentDigest()))) .isInstanceOf(IllegalStateException.class); } @@ -192,33 +187,29 @@ void decodesReceiptSelectorAndPreservesPlacementCorrelationAndOpaqueTargetBytes( @Test void rejectsOpenMalformedReceiptSelectorsBeforeStorageRead() { - assertThatThrownBy( - () -> - PreseededActorAssignmentGrpcCodec.fromReceiptReadRequest( - receiptReadRequest().toBuilder().setSchemaVersion(2).build())) + assertThatThrownBy(() -> + PreseededActorAssignmentGrpcCodec.fromReceiptReadRequest( + receiptReadRequest().toBuilder().setSchemaVersion(2).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unsupported schema_version"); - assertThatThrownBy( - () -> - PreseededActorAssignmentGrpcCodec.fromReceiptReadRequest( - receiptReadRequest().toBuilder().setUnknownFields(unknownField()).build())) + assertThatThrownBy(() -> + PreseededActorAssignmentGrpcCodec.fromReceiptReadRequest( + receiptReadRequest().toBuilder().setUnknownFields(unknownField()).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unknown fields"); - assertThatThrownBy( - () -> - PreseededActorAssignmentGrpcCodec.fromReceiptReadRequest( - receiptReadRequest().toBuilder().clearExpectedTarget().build())) + assertThatThrownBy(() -> + PreseededActorAssignmentGrpcCodec.fromReceiptReadRequest( + receiptReadRequest().toBuilder().clearExpectedTarget().build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("complete receipt selector"); - assertThatThrownBy( - () -> - PreseededActorAssignmentGrpcCodec.fromReceiptReadRequest( - receiptReadRequest().toBuilder() - .setExpectedTarget( - receiptReadRequest().getExpectedTarget().toBuilder() - .setUnknownFields(unknownField()) - .build()) - .build())) + assertThatThrownBy(() -> + PreseededActorAssignmentGrpcCodec.fromReceiptReadRequest( + receiptReadRequest().toBuilder() + .setExpectedTarget( + receiptReadRequest().getExpectedTarget().toBuilder() + .setUnknownFields(unknownField()) + .build()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unknown fields"); assertReceiptReadInvalid( diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepositoryTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepositoryTest.java index 725aced55d..5251cc2d71 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepositoryTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepositoryTest.java @@ -72,17 +72,16 @@ void anEmptyFamilyStateCannotCarryRowsOrReferences() { @Test void rejectsEvidenceKindThatDoesNotMatchFamilyProvider() { - assertThatThrownBy( - () -> - new EntityEmptySelectedSourceIntakeReceipt.FamilyCensus( - "ARCHETYPE_ROOTS", - EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY, - EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS, - 0L, - 0L, - 0L, - 0L, - 0L)) + assertThatThrownBy(() -> + new EntityEmptySelectedSourceIntakeReceipt.FamilyCensus( + "ARCHETYPE_ROOTS", + EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY, + EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS, + 0L, + 0L, + 0L, + 0L, + 0L)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("evidence kind differs"); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeServiceTest.java index 8e95b351e4..3257712957 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeServiceTest.java @@ -34,13 +34,12 @@ void rejectsCallerSelectedNamespaceBeforeReceiptReplayOrRemoteReads() { @Test void rejectsInvalidConfiguredNamespaceAtConstruction() { DSLContext dsl = mock(DSLContext.class); - assertThatThrownBy( - () -> - new EntityEmptySelectedSourceIntakeService( - "Invalid_Namespace", - new EntityEmptySelectedSourceIntakeRepository(dsl), - mock(SelectedOwnerIntakeAuthorizationReadClient.class), - mock(SelectedOwnerWorldInventoryReadClient.class))) + assertThatThrownBy(() -> + new EntityEmptySelectedSourceIntakeService( + "Invalid_Namespace", + new EntityEmptySelectedSourceIntakeRepository(dsl), + mock(SelectedOwnerIntakeAuthorizationReadClient.class), + mock(SelectedOwnerWorldInventoryReadClient.class))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Configured Entity namespace"); } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java index 9959bc29fa..caf62d7178 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java @@ -148,24 +148,23 @@ private static GetDraftDesignDigestResponse invokeAsGameDesign( "spiffe://firemud/ns/test/sa/game-design-service", NAMESPACE, "game-design-service")) - .run( - () -> - receiver.getDraftDesignDigest( - request, - new StreamObserver<>() { - @Override - public void onNext(GetDraftDesignDigestResponse value) { - response.set(value); - } - - @Override - public void onError(Throwable error) { - throw new AssertionError(error); - } - - @Override - public void onCompleted() {} - })); + .run(() -> + receiver.getDraftDesignDigest( + request, + new StreamObserver<>() { + @Override + public void onNext(GetDraftDesignDigestResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable error) { + throw new AssertionError(error); + } + + @Override + public void onCompleted() {} + })); return response.get(); } } diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadServiceTest.java index a3e59f65ab..75642119b0 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadServiceTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadServiceTest.java @@ -167,17 +167,15 @@ void databaseOutagesAreSanitizedAsUnavailable() { assertThatThrownBy(() -> service.read(terminalRequest)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> { - var status = Status.fromThrowable(error); - assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); - assertThat(status.getDescription()) - .isEqualTo("Entity terminal receipt storage is unavailable"); - assertThat(status.getDescription()) - .doesNotContain("private jOOQ", "private Spring"); - assertThat(((StatusRuntimeException) error).getCause()).isNull(); - assertThat(((StatusRuntimeException) error).getTrailers()).isNull(); - }); + .satisfies(error -> { + var status = Status.fromThrowable(error); + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status.getDescription()) + .isEqualTo("Entity terminal receipt storage is unavailable"); + assertThat(status.getDescription()).doesNotContain("private jOOQ", "private Spring"); + assertThat(((StatusRuntimeException) error).getCause()).isNull(); + assertThat(((StatusRuntimeException) error).getTrailers()).isNull(); + }); var recovered = service.read(terminalRequest); assertThat(recovered.request()).isSameAs(terminalRequest); @@ -223,10 +221,9 @@ void rejectsWrongPeerNamespaceOwnerEndUserAndAmbientSqlBeforeRepositoryRead() { otherAccount.detach(previous); } - assertThatThrownBy( - () -> - EntitySelectedSourceIntakeTerminalReadEvidence.Request.create( - NAMESPACE, fixture.wrongOwnerAuthorization())) + assertThatThrownBy(() -> + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create( + NAMESPACE, fixture.wrongOwnerAuthorization())) .isInstanceOf(IllegalArgumentException.class); var accountContext = accountPeer(NAMESPACE); diff --git a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java index febbbd1d8d..ecd1b38212 100644 --- a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java +++ b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/bootstrap/AccountBootstrapRosterFixture.java @@ -65,19 +65,18 @@ public static Fixture create() throws Exception { var world = prepared.world().request(); var participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new GameDesignPublicationTerminalEvidence.Participant( - owner, - Long.toString(draft.target().gameDesignVersionRowId()), - null, - world.appliedCommitId(), - owner.equals("WORLD_MANAGEMENT") ? world.contentDigest() : "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - owner.equals("GAME_LOGIC") ? "sha256:" + "a".repeat(64) : null, - null, - null)) + .map(owner -> + new GameDesignPublicationTerminalEvidence.Participant( + owner, + Long.toString(draft.target().gameDesignVersionRowId()), + null, + world.appliedCommitId(), + owner.equals("WORLD_MANAGEMENT") ? world.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + owner.equals("GAME_LOGIC") ? "sha256:" + "a".repeat(64) : null, + null, + null)) .toList(); var release = new GameDesignPublicationTerminalEvidence.ReleaseContent( @@ -104,10 +103,10 @@ public static Fixture create() throws Exception { var policy = RealmEntryPolicy.parse( """ - {"schemaVersion":1,"worldSlug":"earth","worldDisplayName":"Earth", - "realmSlug":"main","realmDisplayName":"Main","visible":true, - "publicProduction":true,"stateScope":"SHARED","entryPolicy":"PRESEEDED_ONLY"} - """, + {"schemaVersion":1,"worldSlug":"earth","worldDisplayName":"Earth", + "realmSlug":"main","realmDisplayName":"Main","visible":true, + "publicProduction":true,"stateScope":"SHARED","entryPolicy":"PRESEEDED_ONLY"} + """, JSON); UUID policyId = UUID.randomUUID(); UUID revisionId = UUID.randomUUID(); diff --git a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledPlayerCreatedRosterSourceFixture.java b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledPlayerCreatedRosterSourceFixture.java index 2906a10d89..94adc17856 100644 --- a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledPlayerCreatedRosterSourceFixture.java +++ b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledPlayerCreatedRosterSourceFixture.java @@ -790,15 +790,14 @@ private static String gameplaySnapshot( snapshot.put( "entries", entries.stream() - .map( - entry -> - Map.of( - "family", entry.family().name(), - "definitionJson", GameplayRuleManifest.canonical(entry.definition()), - "sourceBindingJson", entry.sourceBinding().canonicalJson(), - "sourceBindingDigest", entry.sourceBinding().digest(), - "revisionOrder", entry.revisionOrder(), - "revisionId", entry.revisionId().toString())) + .map(entry -> + Map.of( + "family", entry.family().name(), + "definitionJson", GameplayRuleManifest.canonical(entry.definition()), + "sourceBindingJson", entry.sourceBinding().canonicalJson(), + "sourceBindingDigest", entry.sourceBinding().digest(), + "revisionOrder", entry.revisionOrder(), + "revisionId", entry.revisionId().toString())) .toList()); return CommandSource.canonical(snapshot); } diff --git a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledSelectedSourceIntakeFixtureBuilder.java b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledSelectedSourceIntakeFixtureBuilder.java index cabab2cbc1..583f774e49 100644 --- a/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledSelectedSourceIntakeFixtureBuilder.java +++ b/services/entity-management-service/src/testFixtures/java/net/firedevops/firemud/entitymanagement/testing/ControlledSelectedSourceIntakeFixtureBuilder.java @@ -112,10 +112,9 @@ private static TemplateConfigSourceSnapshot templateSnapshot( DraftCommitBinding authored = authoredBinding(declarationPayload, selected.target()); TemplateConfigOwnerSourceInventoryDeclaration ownerDeclaration = TemplateConfigSourceValues.mutations(authored).stream() - .filter( - mutation -> - mutation.operation() - == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .filter(mutation -> + mutation.operation() + == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) .findFirst() .orElseThrow(); @@ -330,15 +329,14 @@ private static PublicEvidence publicInventory( 0, 0, selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .map(unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) .toList(), emptyInboundClosure()); var ownerScope = diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/controller/AssetController.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/controller/AssetController.java index 0d814fcb4e..dee9ad8e8e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/controller/AssetController.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/controller/AssetController.java @@ -22,11 +22,10 @@ public class AssetController { @PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity> upload( @RequestParam String tenantId, @RequestParam("file") @NotNull MultipartFile file) { - return GameDesignRequestReaders.withBadRequest( - () -> { - GameDesignRequestReaders.requireTenantAccess(tenantId); - GameAssetDto dto = assetService.uploadAsset(tenantId, file); - return ResponseEntity.ok(ApiResponse.success(dto)); - }); + return GameDesignRequestReaders.withBadRequest(() -> { + GameDesignRequestReaders.requireTenantAccess(tenantId); + GameAssetDto dto = assetService.uploadAsset(tenantId, file); + return ResponseEntity.ok(ApiResponse.success(dto)); + }); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/controller/GameTemplateController.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/controller/GameTemplateController.java index e987ce1c32..7ad18f566f 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/controller/GameTemplateController.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/controller/GameTemplateController.java @@ -24,22 +24,20 @@ public class GameTemplateController { @PostMapping public ResponseEntity> create( @Valid @RequestBody GameTemplateDto dto) { - return GameDesignRequestReaders.withBadRequest( - () -> { - GameDesignRequestReaders.requireTenantAccess(dto.tenantId()); - GameTemplateDto created = templateService.createTemplate(dto); - return ResponseEntity.ok(ApiResponse.success(created)); - }); + return GameDesignRequestReaders.withBadRequest(() -> { + GameDesignRequestReaders.requireTenantAccess(dto.tenantId()); + GameTemplateDto created = templateService.createTemplate(dto); + return ResponseEntity.ok(ApiResponse.success(created)); + }); } @GetMapping public ResponseEntity>> list( @RequestParam String tenantId, Pageable pageable) { - return GameDesignRequestReaders.withBadRequest( - () -> { - GameDesignRequestReaders.requireTenantAccess(tenantId); - Page templates = templateService.listTemplates(tenantId, pageable); - return ResponseEntity.ok(ApiResponse.success(templates)); - }); + return GameDesignRequestReaders.withBadRequest(() -> { + GameDesignRequestReaders.requireTenantAccess(tenantId); + Page templates = templateService.listTemplates(tenantId, pageable); + return ResponseEntity.ok(ApiResponse.success(templates)); + }); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java index 35f5984754..1ab9648f47 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureLaunchReadback.java @@ -102,10 +102,9 @@ public Snapshot readCommittedOutcome(Snapshot captured) { registered.canonicalTenantId(), registered.worldSlug(), registered.targetNamespace()) - .orElseThrow( - () -> - new IllegalStateException( - "Committed authored-world source registration cannot be read back")); + .orElseThrow(() -> + new IllegalStateException( + "Committed authored-world source registration cannot be read back")); if (!registered.equals(committed)) { throw new IllegalStateException( "Committed authored-world source readback differs from the registration result"); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixturePolicyProducer.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixturePolicyProducer.java index 80fcd3303b..f895848671 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixturePolicyProducer.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/RunOwnedFixturePolicyProducer.java @@ -62,43 +62,41 @@ RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal sealAndRead( String requestDigest = frame.requestDigest(); String bindingJson = frame.bindingJson(); String policyJson = frame.policyJson(); - write.executeWithoutResult( - ignored -> { - dsl.fetchSingle( - "SELECT id FROM game WHERE id=? AND tenant_id=? FOR UPDATE", - creation.sourceGameRowId(), - creation.sourceGameTenantKey()); - dsl.fetchSingle( - "SELECT id FROM version WHERE id=? AND tenant_id=? FOR UPDATE", - snapshot.version().id(), - creation.sourceGameTenantKey()); - UUID operationId = trusted.operationId(); - String evidenceDigest = - RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( - operationId, requestDigest); - dsl.execute( - "INSERT INTO game_design_published_realm_policy_set " - + "(canonical_tenant_id, canonical_version_id, game_design_version_row_id, version_number, sealed, " - + "fixture_operation_id, fixture_request_bytes, fixture_request_digest, fixture_evidence_digest, " - + "fixture_binding_json, fixture_policy_json) VALUES (?, ?, ?, ?, TRUE, ?, ?, ?, ?, ?::jsonb, ?::jsonb) " - + "ON CONFLICT (canonical_tenant_id, canonical_version_id) DO NOTHING", - source.canonicalTenantId(), - snapshot.version().canonicalVersionId(), - snapshot.version().id(), - snapshot.version().versionNumber(), - operationId, - request, - requestDigest, - evidenceDigest, - bindingJson, - policyJson); - requireExactRow(snapshot, request, requestDigest, bindingJson, policyJson); - }); + write.executeWithoutResult(ignored -> { + dsl.fetchSingle( + "SELECT id FROM game WHERE id=? AND tenant_id=? FOR UPDATE", + creation.sourceGameRowId(), + creation.sourceGameTenantKey()); + dsl.fetchSingle( + "SELECT id FROM version WHERE id=? AND tenant_id=? FOR UPDATE", + snapshot.version().id(), + creation.sourceGameTenantKey()); + UUID operationId = trusted.operationId(); + String evidenceDigest = + RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( + operationId, requestDigest); + dsl.execute( + "INSERT INTO game_design_published_realm_policy_set " + + "(canonical_tenant_id, canonical_version_id, game_design_version_row_id, version_number, sealed, " + + "fixture_operation_id, fixture_request_bytes, fixture_request_digest, fixture_evidence_digest, " + + "fixture_binding_json, fixture_policy_json) VALUES (?, ?, ?, ?, TRUE, ?, ?, ?, ?, ?::jsonb, ?::jsonb) " + + "ON CONFLICT (canonical_tenant_id, canonical_version_id) DO NOTHING", + source.canonicalTenantId(), + snapshot.version().canonicalVersionId(), + snapshot.version().id(), + snapshot.version().versionNumber(), + operationId, + request, + requestDigest, + evidenceDigest, + bindingJson, + policyJson); + requireExactRow(snapshot, request, requestDigest, bindingJson, policyJson); + }); var seal = Objects.requireNonNull( - read.execute( - ignored -> - requireExactRow(snapshot, request, requestDigest, bindingJson, policyJson))); + read.execute(ignored -> + requireExactRow(snapshot, request, requestDigest, bindingJson, policyJson))); // Independent owner read after seal commit; changing upstream rows cannot publish a receipt. readback.readCommittedCreation(creation); var committedSnapshot = readback.readCommittedOutcome(snapshot); @@ -120,14 +118,13 @@ RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal readExisting( ResolvedLaunchDescriptorDto descriptor) { PolicyFrame frame = frame(trusted, creation, snapshot, descriptor); return Objects.requireNonNull( - read.execute( - ignored -> - requireExactRow( - snapshot, - frame.request(), - frame.requestDigest(), - frame.bindingJson(), - frame.policyJson()))); + read.execute(ignored -> + requireExactRow( + snapshot, + frame.request(), + frame.requestDigest(), + frame.bindingJson(), + frame.policyJson()))); } private PolicyFrame frame( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java index ca3c7408bd..2212faa879 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/data/TestDataSeeder.java @@ -131,13 +131,12 @@ public void run(ApplicationArguments args) { if (!initialAdmissionFixtureEnabled && versionRepository .findByTenantIdAndVersionNumber(DEMO_TENANT_ID, DEMO_VERSION_NUMBER) - .filter( - version -> - version.getCanonicalVersionId() == null - && version.getCanonicalTenantId() == null - && version.getIdentitySourceGameRowId() == null - && version.getIdentitySourceGameTenantKey() == null - && version.getIdentitySourceProvenanceKind() == null) + .filter(version -> + version.getCanonicalVersionId() == null + && version.getCanonicalTenantId() == null + && version.getIdentitySourceGameRowId() == null + && version.getIdentitySourceGameTenantKey() == null + && version.getIdentitySourceProvenanceKind() == null) .isPresent()) { seedRetainedBaselineRuntime(); return; @@ -187,10 +186,8 @@ public void run(ApplicationArguments args) { GameTenantIdentity gameIdentity = gameRepository .findRuntimeTenantIdentityByTenantKey(game.getTenantId()) - .orElseThrow( - () -> - new IllegalStateException( - "Existing demo game tenant identity cannot be read")); + .orElseThrow(() -> + new IllegalStateException("Existing demo game tenant identity cannot be read")); if (!matchesDemoVersion(version, game, gameIdentity)) { throw new IllegalStateException( "Existing published version does not exactly match the demo seed; refusing to reuse it"); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java index 3b5ad18ced..1807af9216 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/DraftCommitCoordinatorRepository.java @@ -493,10 +493,9 @@ PublicationEvidence requireSynchronizedPublicationEvidence( } VisibilityFence current = readVisibilityFence(target) - .orElseThrow( - () -> - new DraftCommitStateConflictException( - "Selected authored Draft commit is not the current synchronized fence")); + .orElseThrow(() -> + new DraftCommitStateConflictException( + "Selected authored Draft commit is not the current synchronized fence")); if (!current.requestId().equals(requestId) || !current.commitId().equals(commitId) || !current.inputDigest().equals(inputDigest) @@ -544,17 +543,14 @@ public void releaseApplicationSlot(DraftCommitBinding binding) { boolean anyApplied = outcomes.stream().anyMatch(state -> state.status() == OwnerStatus.APPLIED); boolean unresolved = outcomes.stream() - .anyMatch( - state -> - state.status() == OwnerStatus.UNKNOWN - || state.status() == OwnerStatus.IN_PROGRESS); + .anyMatch(state -> + state.status() == OwnerStatus.UNKNOWN || state.status() == OwnerStatus.IN_PROGRESS); boolean allApplied = outcomes.stream().allMatch(state -> state.status() == OwnerStatus.APPLIED); boolean definiteNoApply = outcomes.stream() - .allMatch( - state -> - state.status() == OwnerStatus.NOT_ATTEMPTED - || state.status() == OwnerStatus.REJECTED) + .allMatch(state -> + state.status() == OwnerStatus.NOT_ATTEMPTED + || state.status() == OwnerStatus.REJECTED) && outcomes.stream().anyMatch(state -> state.status() == OwnerStatus.REJECTED); if (unresolved || (anyApplied && !allApplied) || (!allApplied && !definiteNoApply)) { throw new DraftCommitStateConflictException( @@ -729,10 +725,9 @@ private void requireCompleteTerminalAbortVector( ownerStates.stream() .filter(candidate -> candidate.owner() == owner) .findFirst() - .orElseThrow( - () -> - new DraftCommitStateConflictException( - "Definitive final-abort evidence cannot omit a required owner result")); + .orElseThrow(() -> + new DraftCommitStateConflictException( + "Definitive final-abort evidence cannot omit a required owner result")); if (state.status() != OwnerStatus.APPLIED && state.status() != OwnerStatus.REJECTED) { throw new DraftCommitStateConflictException( "Definitive final-abort evidence requires only exact terminal APPLIED or REJECTED owners"); @@ -740,10 +735,9 @@ private void requireCompleteTerminalAbortVector( OwnerOutcome outcome = state .outcome() - .orElseThrow( - () -> - new DraftCommitStateConflictException( - "Definitive final-abort evidence requires durable owner result bytes")); + .orElseThrow(() -> + new DraftCommitStateConflictException( + "Definitive final-abort evidence requires durable owner result bytes")); requireOutcomeMatches(binding, outcome); } } @@ -757,10 +751,9 @@ private String exactTerminalAbortResultVector( ownerStates.stream() .filter(candidate -> candidate.owner() == owner) .findFirst() - .orElseThrow( - () -> - new DraftCommitStateConflictException( - "Definitive final-abort evidence cannot omit a required owner result")); + .orElseThrow(() -> + new DraftCommitStateConflictException( + "Definitive final-abort evidence cannot omit a required owner result")); resultVector.add(ownerResultJson(state.outcome().orElseThrow())); } return canonicalJson(resultVector); @@ -1090,10 +1083,8 @@ private String exactAppliedResultVector( ownerStates.stream() .filter(candidate -> candidate.owner() == owner) .findFirst() - .orElseThrow( - () -> - new DraftCommitStateConflictException( - "Required Draft owner result is missing")); + .orElseThrow(() -> + new DraftCommitStateConflictException("Required Draft owner result is missing")); OwnerOutcome outcome = state.outcome().orElse(null); if (state.status() != OwnerStatus.APPLIED || outcome == null) { throw new DraftCommitStateConflictException( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidence.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidence.java index 3377efb694..841061c778 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidence.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidence.java @@ -86,16 +86,14 @@ public static GameDesignReviewedBaseEvidence authored( || !binding.digest().equals(outcome.bindingDigest()) || outcome.appliedEpochs().size() != binding.affectedUnits(owner).size() || binding.affectedUnits(owner).stream() - .anyMatch( - unit -> - outcome.appliedEpochs().stream() - .noneMatch( - epoch -> - epoch.aggregateType().equals(unit.aggregateType()) - && epoch.aggregateId().equals(unit.aggregateId()) - && epoch.scopeType().equals(unit.scopeType()) - && epoch.scopeId().equals(unit.scopeId()) - && epoch.expectedEpoch().equals(unit.expectedEpoch())))) { + .anyMatch(unit -> + outcome.appliedEpochs().stream() + .noneMatch(epoch -> + epoch.aggregateType().equals(unit.aggregateType()) + && epoch.aggregateId().equals(unit.aggregateId()) + && epoch.scopeType().equals(unit.scopeType()) + && epoch.scopeId().equals(unit.scopeId()) + && epoch.expectedEpoch().equals(unit.expectedEpoch())))) { throw new IllegalArgumentException("Complete exact APPLIED base owner evidence required"); } frame(out, owner.name()); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignWorldSourceCommitService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignWorldSourceCommitService.java index 404065d7f5..7289ae5ec5 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignWorldSourceCommitService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignWorldSourceCommitService.java @@ -90,15 +90,14 @@ public GameDesignDraftTerminalOutcome commit( sources.validateInput(binding); retained = Objects.requireNonNull( - write.execute( - ignored -> { - coordinator.lockVersionTarget(binding.target()); - var existing = terminal(operation); - if (existing.isPresent()) return existing; - coordinator.claim(binding, original); - coordinator.claimApplicationSlot(binding); - return Optional.empty(); - })); + write.execute(ignored -> { + coordinator.lockVersionTarget(binding.target()); + var existing = terminal(operation); + if (existing.isPresent()) return existing; + coordinator.claim(binding, original); + coordinator.claimApplicationSlot(binding); + return Optional.empty(); + })); if (retained.isPresent()) return retained.orElseThrow(); outsideSql(); var orderRequest = @@ -110,111 +109,103 @@ public GameDesignDraftTerminalOutcome commit( outsideSql(); var staged = Objects.requireNonNull( - write.execute( - ignored -> { - coordinator.lockVersionTarget(binding.target()); - var existing = terminal(operation); - if (existing.isPresent()) return new Staged(existing, Optional.empty()); - var claimed = coordinator.claim(binding, original); - coordinator.claimApplicationSlot(binding); - var local = claimed.ownerStates().get(Owner.GAME_DESIGN_CONTROL_PLANE); - if (local == null) - throw new IllegalStateException("Complete GD owner state required"); - if (local.status() == OwnerStatus.NOT_ATTEMPTED) { - coordinator.markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); - requireApplied( - binding, - sources.apply(binding).ownerOutcome(), - Owner.GAME_DESIGN_CONTROL_PLANE); - } else if (local.status() == OwnerStatus.APPLIED) { - requireApplied( - binding, local.outcome().orElseThrow(), Owner.GAME_DESIGN_CONTROL_PLANE); - } else { - throw new IllegalStateException("Unresolved GD source requires exact recovery"); - } - var remote = claimed.ownerStates().get(Owner.WORLD_MANAGEMENT); - if (remote == null) - throw new IllegalStateException("Complete World owner state required"); - if (remote.status() == OwnerStatus.APPLIED) { - var outcome = remote.outcome().orElseThrow(); - requireApplied(binding, outcome, Owner.WORLD_MANAGEMENT); - return new Staged(Optional.empty(), Optional.of(outcome)); - } - if (remote.status() == OwnerStatus.NOT_ATTEMPTED) - coordinator.markOwnerInProgress(binding, Owner.WORLD_MANAGEMENT); - else if (remote.status() != OwnerStatus.IN_PROGRESS - && remote.status() != OwnerStatus.UNKNOWN) - throw new IllegalStateException( - "World owner has no successful recoverable result"); - return new Staged(Optional.empty(), Optional.empty()); - })); + write.execute(ignored -> { + coordinator.lockVersionTarget(binding.target()); + var existing = terminal(operation); + if (existing.isPresent()) return new Staged(existing, Optional.empty()); + var claimed = coordinator.claim(binding, original); + coordinator.claimApplicationSlot(binding); + var local = claimed.ownerStates().get(Owner.GAME_DESIGN_CONTROL_PLANE); + if (local == null) + throw new IllegalStateException("Complete GD owner state required"); + if (local.status() == OwnerStatus.NOT_ATTEMPTED) { + coordinator.markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + requireApplied( + binding, + sources.apply(binding).ownerOutcome(), + Owner.GAME_DESIGN_CONTROL_PLANE); + } else if (local.status() == OwnerStatus.APPLIED) { + requireApplied( + binding, local.outcome().orElseThrow(), Owner.GAME_DESIGN_CONTROL_PLANE); + } else { + throw new IllegalStateException("Unresolved GD source requires exact recovery"); + } + var remote = claimed.ownerStates().get(Owner.WORLD_MANAGEMENT); + if (remote == null) + throw new IllegalStateException("Complete World owner state required"); + if (remote.status() == OwnerStatus.APPLIED) { + var outcome = remote.outcome().orElseThrow(); + requireApplied(binding, outcome, Owner.WORLD_MANAGEMENT); + return new Staged(Optional.empty(), Optional.of(outcome)); + } + if (remote.status() == OwnerStatus.NOT_ATTEMPTED) + coordinator.markOwnerInProgress(binding, Owner.WORLD_MANAGEMENT); + else if (remote.status() != OwnerStatus.IN_PROGRESS + && remote.status() != OwnerStatus.UNKNOWN) + throw new IllegalStateException("World owner has no successful recoverable result"); + return new Staged(Optional.empty(), Optional.empty()); + })); if (staged.terminal().isPresent()) return staged.terminal().orElseThrow(); outsideSql(); OwnerOutcome worldOutcome = staged .worldOutcome() - .orElseGet( - () -> { - var response = - Objects.requireNonNull( - world.apply(request), "Authenticated World result required"); - if (!request.equals(response.request())) - throw new IllegalArgumentException( - "World result changed the complete original request"); - // Revalidate even an injected client's returned value; the strict carrier checks - // the complete - // original binding, APPLIED bytes and every World expected/resulting epoch. - var verified = - new WorldOriginalDraftGraphApplyEvidence.Result( - request, response.ownerReadback()); - return new OwnerOutcome( - Owner.WORLD_MANAGEMENT, - OwnerStatus.APPLIED, - binding.commitId(), - binding.digest(), - verified.resultIdentity(), - verified.ownerReadback().result(), - verified.appliedEpochs().stream() - .map( - epoch -> - new AppliedEpoch( - epoch.aggregateType(), - epoch.aggregateId(), - epoch.scopeType(), - epoch.scopeId(), - epoch.expectedEpoch(), - epoch.resultingEpoch())) - .toList()); - }); + .orElseGet(() -> { + var response = + Objects.requireNonNull( + world.apply(request), "Authenticated World result required"); + if (!request.equals(response.request())) + throw new IllegalArgumentException( + "World result changed the complete original request"); + // Revalidate even an injected client's returned value; the strict carrier checks + // the complete + // original binding, APPLIED bytes and every World expected/resulting epoch. + var verified = + new WorldOriginalDraftGraphApplyEvidence.Result( + request, response.ownerReadback()); + return new OwnerOutcome( + Owner.WORLD_MANAGEMENT, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + verified.resultIdentity(), + verified.ownerReadback().result(), + verified.appliedEpochs().stream() + .map(epoch -> + new AppliedEpoch( + epoch.aggregateType(), + epoch.aggregateId(), + epoch.scopeType(), + epoch.scopeId(), + epoch.expectedEpoch(), + epoch.resultingEpoch())) + .toList()); + }); outsideSql(); - write.executeWithoutResult( - ignored -> { - coordinator.lockVersionTarget(binding.target()); - if (terminal(operation).isPresent()) return; - requireApplied(binding, worldOutcome, Owner.WORLD_MANAGEMENT); - coordinator.recordOwnerOutcome(binding, worldOutcome); - var actual = coordinator.read(binding.target(), binding.requestId()).orElseThrow(); - if (!binding.equals(actual.binding())) - throw new IllegalStateException("Complete retained coordinator binding required"); - var outcomes = - binding.requiredOwners().stream() - .map( - owner -> { - var state = actual.ownerStates().get(owner); - if (state == null || state.status() != OwnerStatus.APPLIED) - throw new IllegalStateException( - "Every exact owner must be durably APPLIED"); - var outcome = state.outcome().orElseThrow(); - requireApplied(binding, outcome, owner); - return outcome; - }) - .toList(); - coordinator.advanceSourceVisibilityFence( - binding, new CoordinatorProof(binding, outcomes)); - coordinator.releaseApplicationSlot(binding); - terminal(operation) - .orElseThrow(() -> new IllegalStateException("Terminal source readback unavailable")); - }); + write.executeWithoutResult(ignored -> { + coordinator.lockVersionTarget(binding.target()); + if (terminal(operation).isPresent()) return; + requireApplied(binding, worldOutcome, Owner.WORLD_MANAGEMENT); + coordinator.recordOwnerOutcome(binding, worldOutcome); + var actual = coordinator.read(binding.target(), binding.requestId()).orElseThrow(); + if (!binding.equals(actual.binding())) + throw new IllegalStateException("Complete retained coordinator binding required"); + var outcomes = + binding.requiredOwners().stream() + .map(owner -> { + var state = actual.ownerStates().get(owner); + if (state == null || state.status() != OwnerStatus.APPLIED) + throw new IllegalStateException("Every exact owner must be durably APPLIED"); + var outcome = state.outcome().orElseThrow(); + requireApplied(binding, outcome, owner); + return outcome; + }) + .toList(); + coordinator.advanceSourceVisibilityFence(binding, new CoordinatorProof(binding, outcomes)); + coordinator.releaseApplicationSlot(binding); + terminal(operation) + .orElseThrow(() -> new IllegalStateException("Terminal source readback unavailable")); + }); outsideSql(); return Objects.requireNonNull(read.execute(ignored -> terminal(operation).orElseThrow())); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java index 5cba3d29af..bf02e40aa6 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java @@ -145,14 +145,13 @@ public Optional apply(DraftCommitBinding binding) { .map(m -> Long.parseLong(m.assetRowId())) .distinct() .sorted() - .forEach( - id -> { - if (dsl.fetchOne( - "SELECT id FROM game_assets WHERE tenant_id = ? AND id = ? FOR UPDATE", - binding.target().gameDesignVersionTenantKey(), - id) - == null) throw new IllegalStateException("ASSET_SOURCE_ROW_UNAVAILABLE"); - }); + .forEach(id -> { + if (dsl.fetchOne( + "SELECT id FROM game_assets WHERE tenant_id = ? AND id = ? FOR UPDATE", + binding.target().gameDesignVersionTenantKey(), + id) + == null) throw new IllegalStateException("ASSET_SOURCE_ROW_UNAVAILABLE"); + }); for (var mutation : mutations) { net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item item = mutation.operation() == AssetSource.OperationKind.UPSERT @@ -315,19 +314,16 @@ public Optional readSnapshot(TargetProof target, UUID commitId) { target.gameDesignVersionRowId()); if (mappings.size() != snapshot.items().size() || mappings.stream() - .anyMatch( - mapping -> - mapping.get("usage_type") != null - || snapshot.items().stream() - .noneMatch( - item -> - item.reference() - .assetRowId() - .equals( - mapping.get("asset_id", Long.class).toString()) - && item.reference() - .usageKey() - .equals(mapping.get("usage_key", String.class))))) { + .anyMatch(mapping -> + mapping.get("usage_type") != null + || snapshot.items().stream() + .noneMatch(item -> + item.reference() + .assetRowId() + .equals(mapping.get("asset_id", Long.class).toString()) + && item.reference() + .usageKey() + .equals(mapping.get("usage_key", String.class))))) { throw new IllegalStateException("ASSET_SOURCE_PROJECTION_READBACK_CONFLICT"); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceRepository.java index 354e7ffbee..9e406c3852 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceRepository.java @@ -150,14 +150,13 @@ public Optional apply(DraftCommitBinding binding) { .map(m -> Long.parseLong(m.assetRowId())) .distinct() .sorted() - .forEach( - id -> { - if (dsl.fetchOne( - "SELECT id FROM game_assets WHERE tenant_id = ? AND id = ? FOR UPDATE", - binding.target().gameDesignVersionTenantKey(), - id) - == null) throw new IllegalStateException("BRANDING_SOURCE_ROW_UNAVAILABLE"); - }); + .forEach(id -> { + if (dsl.fetchOne( + "SELECT id FROM game_assets WHERE tenant_id = ? AND id = ? FOR UPDATE", + binding.target().gameDesignVersionTenantKey(), + id) + == null) throw new IllegalStateException("BRANDING_SOURCE_ROW_UNAVAILABLE"); + }); for (var mutation : mutations) { net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot.Item item = mutation.operation() == BrandingSource.OperationKind.UPSERT diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java index 26bd6ab1d4..f10ff0d331 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java @@ -320,9 +320,8 @@ public CommandSnapshot.Capture freeze(GameDesignPublicationOperation operation) var retainedOperation = new GameDesignPublicationOperationRepository(dsl) .read(operation.workflowId()) - .orElseThrow( - () -> - new IllegalStateException("COMMAND_SOURCE_PUBLICATION_OPERATION_UNAVAILABLE")); + .orElseThrow(() -> + new IllegalStateException("COMMAND_SOURCE_PUBLICATION_OPERATION_UNAVAILABLE")); GameDesignPublicationOperationRepository.exact(retainedOperation.operation(), operation); if (!"PENDING".equals(retainedOperation.outcome())) { throw new IllegalStateException("COMMAND_SOURCE_PUBLICATION_OPERATION_SEALED"); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java index bde5647a7e..bdb3fe10fb 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadService.java @@ -60,24 +60,23 @@ public GameplayRuleSourceReadEvidence read(GameplayRuleSourceReadEvidence.Reques throw Status.FAILED_PRECONDITION .withDescription("Exact Account source permission required") .asRuntimeException(); - return transaction.execute( - ignored -> { - var snapshot = - repository.requireCompleteForGameLogic( - request.binding().target(), request.binding().commitId()); - if (!snapshot.binding().equals(request.binding())) - throw Status.FAILED_PRECONDITION - .withDescription("Selected rule binding differs") - .asRuntimeException(); - if (request.proof() instanceof GameplayRuleSourceReadEvidence.Finalized finalized - && !java.util.Arrays.equals( - snapshot.canonicalBytes(), finalized.authorization().source().canonicalBytes())) - throw Status.FAILED_PRECONDITION - .withDescription("Finalized source differs") - .asRuntimeException(); - return new GameplayRuleSourceReadEvidence( - request, new GameplayRuleSelectedSource(snapshot.canonicalJson())); - }); + return transaction.execute(ignored -> { + var snapshot = + repository.requireCompleteForGameLogic( + request.binding().target(), request.binding().commitId()); + if (!snapshot.binding().equals(request.binding())) + throw Status.FAILED_PRECONDITION + .withDescription("Selected rule binding differs") + .asRuntimeException(); + if (request.proof() instanceof GameplayRuleSourceReadEvidence.Finalized finalized + && !java.util.Arrays.equals( + snapshot.canonicalBytes(), finalized.authorization().source().canonicalBytes())) + throw Status.FAILED_PRECONDITION + .withDescription("Finalized source differs") + .asRuntimeException(); + return new GameplayRuleSourceReadEvidence( + request, new GameplayRuleSelectedSource(snapshot.canonicalJson())); + }); } static void requirePeer(String namespace) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationService.java index 85eae34210..ddbb350c66 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationService.java @@ -35,12 +35,11 @@ public GameDesignPublicationOperationRepository.Readback retainVerifiedOperation if (retained.isPresent()) { var original = retained.orElseThrow(); if ("PENDING".equals(original.outcome())) { - read.executeWithoutResult( - status -> - repository - .readSourceCapture(operation) - .orElseThrow( - () -> new IllegalStateException("PUBLICATION_SOURCE_CAPTURE_UNAVAILABLE"))); + read.executeWithoutResult(status -> + repository + .readSourceCapture(operation) + .orElseThrow( + () -> new IllegalStateException("PUBLICATION_SOURCE_CAPTURE_UNAVAILABLE"))); } return original; } @@ -52,15 +51,13 @@ public GameDesignPublicationOperationRepository.Readback retainVerifiedOperation public Optional readExact( GameDesignPublicationOperation operation) { requireIndependent(); - return read.execute( - status -> - repository - .read(operation.workflowId()) - .map( - result -> { - GameDesignPublicationOperationRepository.exact(result.operation(), operation); - return result; - })); + return read.execute(status -> + repository + .read(operation.workflowId()) + .map(result -> { + GameDesignPublicationOperationRepository.exact(result.operation(), operation); + return result; + })); } /** Independently resolves the complete retained owner identity, never a workflow-only result. */ @@ -76,22 +73,19 @@ public Optional readExact( || !selectionDigest.matches("sha256:[0-9a-f]{64}")) { throw new IllegalArgumentException("Complete publication owner scope required"); } - return read.execute( - status -> - repository - .read(workflow) - .map( - result -> { - var operation = result.operation(); - if (!tenant.equals(operation.tenantKey()) - || !workflow.equals(operation.workflowId()) - || version != operation.versionId() - || !selectionDigest.equals(operation.selectionDigest())) { - throw new IllegalArgumentException( - "PUBLICATION_OPERATION_IDENTITY_CONFLICT"); - } - return result; - })); + return read.execute(status -> + repository + .read(workflow) + .map(result -> { + var operation = result.operation(); + if (!tenant.equals(operation.tenantKey()) + || !workflow.equals(operation.workflowId()) + || version != operation.versionId() + || !selectionDigest.equals(operation.selectionDigest())) { + throw new IllegalArgumentException("PUBLICATION_OPERATION_IDENTITY_CONFLICT"); + } + return result; + })); } private static void requireIndependent() { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadService.java index 4624f10a27..ec79359534 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceReadService.java @@ -70,23 +70,22 @@ public SelectedOwnerIntakeSourceExport readSource(SelectedOwnerIntakeSourceReadS .asRuntimeException(); } - return transaction.execute( - ignored -> { - var exported = repository.requireSelectedOwnerIntakeSource(scope); - if (exported == null - || !Arrays.equals(scope.canonicalBytes(), exported.scope().canonicalBytes()) - || !scope.digest().equals(exported.scope().digest())) { - throw Status.FAILED_PRECONDITION - .withDescription("Selected owner source scope differs") - .asRuntimeException(); - } - byte[] canonicalBytes = exported.canonicalBytes(); - if (!DraftAuthorizationFenceBinding.digest(canonicalBytes).equals(exported.digest())) { - throw Status.FAILED_PRECONDITION - .withDescription("Selected owner source export digest differs") - .asRuntimeException(); - } - return exported; - }); + return transaction.execute(ignored -> { + var exported = repository.requireSelectedOwnerIntakeSource(scope); + if (exported == null + || !Arrays.equals(scope.canonicalBytes(), exported.scope().canonicalBytes()) + || !scope.digest().equals(exported.scope().digest())) { + throw Status.FAILED_PRECONDITION + .withDescription("Selected owner source scope differs") + .asRuntimeException(); + } + byte[] canonicalBytes = exported.canonicalBytes(); + if (!DraftAuthorizationFenceBinding.digest(canonicalBytes).equals(exported.digest())) { + throw Status.FAILED_PRECONDITION + .withDescription("Selected owner source export digest differs") + .asRuntimeException(); + } + return exported; + }); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java index 705f1cfbb3..187d13d5e8 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java @@ -90,10 +90,8 @@ public Genesis enrollFreshDraft(TargetProof target) { Optional.of(templateConfig)); if (!result.equals( readGenesis(target) - .orElseThrow( - () -> - new IllegalStateException( - "GAME_DESIGN_SOURCE_GENESIS_READBACK_UNAVAILABLE")))) { + .orElseThrow(() -> + new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_READBACK_UNAVAILABLE")))) { throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_READBACK_CONFLICT"); } return result; @@ -461,9 +459,8 @@ public SelectedOwnerIntakeSourceExport requireSelectedOwnerIntakeSource( private void requireGenesis(TargetProof target) { if (readGenesis(target) - .filter( - genesis -> - genesis.assetEvidence().isPresent() && genesis.brandingEvidence().isPresent()) + .filter(genesis -> + genesis.assetEvidence().isPresent() && genesis.brandingEvidence().isPresent()) .isEmpty()) { throw new IllegalStateException("GAME_DESIGN_SOURCE_GENESIS_UNAVAILABLE"); } @@ -525,19 +522,17 @@ private static void requireCompleteScopes( List units = binding.affectedUnits(Owner.GAME_DESIGN_CONTROL_PLANE); List commands = units.stream() - .filter( - unit -> - CommandSource.SCOPE.equals(unit.aggregateType()) - && CommandSource.SCOPE.equals(unit.scopeType()) - && CommandSource.SCOPE_ID.equals(unit.scopeId())) + .filter(unit -> + CommandSource.SCOPE.equals(unit.aggregateType()) + && CommandSource.SCOPE.equals(unit.scopeType()) + && CommandSource.SCOPE_ID.equals(unit.scopeId())) .toList(); List policies = units.stream() - .filter( - unit -> - RealmPolicySource.SCOPE.equals(unit.aggregateType()) - && RealmPolicySource.SCOPE.equals(unit.scopeType()) - && "effective".equals(unit.scopeId())) + .filter(unit -> + RealmPolicySource.SCOPE.equals(unit.aggregateType()) + && RealmPolicySource.SCOPE.equals(unit.scopeType()) + && "effective".equals(unit.scopeId())) .toList(); List assets = units.stream().filter(AssetSourceRepository::isScope).toList(); List branding = units.stream().filter(BrandingSourceRepository::isScope).toList(); @@ -557,9 +552,8 @@ private static void requireCompleteScopes( + templateConfigs.size() != units.size() || units.stream() - .anyMatch( - unit -> - !binding.target().canonicalVersionId().toString().equals(unit.aggregateId()))) { + .anyMatch(unit -> + !binding.target().canonicalVersionId().toString().equals(unit.aggregateId()))) { throw new IllegalArgumentException("Complete supported Game Design source scopes required"); } if (hasPolicy) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepository.java index 149c8b2674..a6d3f56f39 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepository.java @@ -376,10 +376,8 @@ public GameplayRuleSnapshot requireCompleteForGameLogic(TargetProof target, UUID var commands = new CommandSourceRepository(dsl) .readSnapshot(target, commitId) - .orElseThrow( - () -> - new IllegalStateException( - "GAMEPLAY_RULE_LEGACY_COMMAND_INVENTORY_UNAVAILABLE")); + .orElseThrow(() -> + new IllegalStateException("GAMEPLAY_RULE_LEGACY_COMMAND_INVENTORY_UNAVAILABLE")); if (!commands.binding().equals(snapshot.binding()) || !commands.definitions().isEmpty()) throw new IllegalStateException("GAMEPLAY_RULE_LEGACY_COMMAND_SOURCE_NOT_CONVERGED"); return snapshot; diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublicationReleaseContent.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublicationReleaseContent.java index e330e02684..70452284dc 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublicationReleaseContent.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublicationReleaseContent.java @@ -41,18 +41,17 @@ static GameDesignPublicationTerminalEvidence.ReleaseContent fromRow(Record row) row.get("required_manifest_asset_keys_json", String.class), new TypeReference>() {}), participants.stream() - .map( - p -> - new GameDesignPublicationTerminalEvidence.Participant( - p.participantKey(), - p.scopeValue(), - p.baseVersionId(), - p.appliedCommitId(), - p.contentDigest(), - p.digestSchemaVersion(), - p.abilitySchemaDigest(), - p.errorCode(), - p.errorMessage())) + .map(p -> + new GameDesignPublicationTerminalEvidence.Participant( + p.participantKey(), + p.scopeValue(), + p.baseVersionId(), + p.appliedCommitId(), + p.contentDigest(), + p.digestSchemaVersion(), + p.abilitySchemaDigest(), + p.errorCode(), + p.errorMessage())) .toList(), mapper.readValue( row.get("command_definitions_json", String.class), diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublishedReleaseEvidenceEncoding.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublishedReleaseEvidenceEncoding.java index 1a8f7beaee..187669c6bd 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublishedReleaseEvidenceEncoding.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/PublishedReleaseEvidenceEncoding.java @@ -73,30 +73,28 @@ static GameDesignPublicationTerminalEvidence.ReleaseContent releaseContent( } List participants = dto.participantDigests().stream() - .map( - value -> - new GameDesignPublicationTerminalEvidence.Participant( - value.participantKey(), - value.scopeValue(), - value.baseVersionId(), - value.appliedCommitId(), - value.contentDigest(), - Objects.requireNonNull(value.digestSchemaVersion()), - value.abilitySchemaDigest(), - value.errorCode(), - value.errorMessage())) + .map(value -> + new GameDesignPublicationTerminalEvidence.Participant( + value.participantKey(), + value.scopeValue(), + value.baseVersionId(), + value.appliedCommitId(), + value.contentDigest(), + Objects.requireNonNull(value.digestSchemaVersion()), + value.abilitySchemaDigest(), + value.errorCode(), + value.errorMessage())) .toList(); List artifacts = dto.artifactDigests().stream() - .map( - value -> - new AuthoredWorldReleaseAttestationEvidence.Artifact( - value.usageKey(), - value.artifactKind(), - value.immutableObjectKey(), - value.contentDigest(), - value.contentType(), - value.artifactSchemaVersion())) + .map(value -> + new AuthoredWorldReleaseAttestationEvidence.Artifact( + value.usageKey(), + value.artifactKind(), + value.immutableObjectKey(), + value.contentDigest(), + value.contentType(), + value.artifactSchemaVersion())) .toList(); return new GameDesignPublicationTerminalEvidence.ReleaseContent( dto.canonicalTenantId(), diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java index 9749791c25..4555583f04 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java @@ -178,10 +178,9 @@ private boolean requireGameSessionPeer(StreamObserver observer) { private static boolean containsSelector( PublishedRealmEntryPolicySetEvidence evidence, String worldSlug, String realmSlug) { return evidence.policies().stream() - .anyMatch( - policy -> - policy.policy().worldSlug().equals(worldSlug) - && policy.policy().realmSlug().equals(realmSlug)); + .anyMatch(policy -> + policy.policy().worldSlug().equals(worldSlug) + && policy.policy().realmSlug().equals(realmSlug)); } private static void requireExactTarget( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationService.java index 1af6a81893..008dfdd09c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationService.java @@ -54,14 +54,12 @@ public Optional readPublishedPolicy( throw new IllegalArgumentException("Canonical realm policy selectors required"); } return readPublishedSet(target) - .flatMap( - set -> - set.policies().stream() - .filter( - policy -> - policy.source().policy().worldSlug().equals(worldSlug) - && policy.source().policy().realmSlug().equals(realmSlug)) - .findFirst()); + .flatMap(set -> + set.policies().stream() + .filter(policy -> + policy.source().policy().worldSlug().equals(worldSlug) + && policy.source().policy().realmSlug().equals(realmSlug)) + .findFirst()); } private static void requireIndependentRead() { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java index e0432cb2f3..d181b80edf 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidence.java @@ -234,15 +234,14 @@ public static String computePolicySetDigest( RealmPolicySource.ordered(policies.stream().map(Policy::source).toList()); var shared = policies.stream() - .map( - policy -> - new PublishedRealmEntryPolicyEvidence( - policy.policyId(), - policy.source().commitId(), - policy.source().revisionId(), - policy.source().logicalRevisionId(), - policy.source().policy(), - policy.policyDigest())) + .map(policy -> + new PublishedRealmEntryPolicyEvidence( + policy.policyId(), + policy.source().commitId(), + policy.source().revisionId(), + policy.source().logicalRevisionId(), + policy.source().policy(), + policy.policyDigest())) .toList(); return PublishedRealmEntryPolicySetEvidence.calculatePolicySetDigest( target, diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidenceMapper.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidenceMapper.java index ac368131db..7671c83a23 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidenceMapper.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublishedEvidenceMapper.java @@ -13,15 +13,14 @@ static PublishedRealmEntryPolicySetEvidence toShared( Objects.requireNonNull(source, "source"); var policies = source.policies().stream() - .map( - policy -> - new PublishedRealmEntryPolicyEvidence( - policy.policyId(), - policy.source().commitId(), - policy.source().revisionId(), - policy.source().logicalRevisionId(), - policy.source().policy(), - policy.policyDigest())) + .map(policy -> + new PublishedRealmEntryPolicyEvidence( + policy.policyId(), + policy.source().commitId(), + policy.source().revisionId(), + policy.source().logicalRevisionId(), + policy.source().policy(), + policy.policyDigest())) .toList(); var candidate = new PublishedRealmEntryPolicySetEvidence( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java index 5634d95c5e..0df056a725 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySource.java @@ -186,17 +186,16 @@ public static List draftOrdered(List policies) { static String policiesJson(List policies) { return canonical( draftOrdered(policies).stream() - .map( - policy -> - Map.of( - "commitId", - policy.commitId().toString(), - "revisionId", - policy.revisionId().toString(), - "logicalRevisionId", - policy.logicalRevisionId(), - "policy", - tree(policy.policy().canonicalJson()))) + .map(policy -> + Map.of( + "commitId", + policy.commitId().toString(), + "revisionId", + policy.revisionId().toString(), + "logicalRevisionId", + policy.logicalRevisionId(), + "policy", + tree(policy.policy().canonicalJson()))) .toList()); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java index a7ffd4492d..d76c67d0af 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java @@ -316,10 +316,9 @@ public RealmPolicySnapshot captureSynchronized(DraftCommitBinding binding) { var applied = application(binding); RealmPolicySnapshot snapshot; if (binding.revisions().stream() - .anyMatch( - r -> - r.owner() == Owner.GAME_DESIGN_CONTROL_PLANE - && RealmPolicySource.isPolicyRevision(r))) { + .anyMatch(r -> + r.owner() == Owner.GAME_DESIGN_CONTROL_PLANE + && RealmPolicySource.isPolicyRevision(r))) { var result = applied.orElseThrow(() -> new IllegalStateException("POLICY_OWNER_RESULT_UNAVAILABLE")); requireCoordinatorResult(result); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigest.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigest.java index 77d9cc1e30..a0b9750392 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigest.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftControlPlaneDigest.java @@ -45,10 +45,8 @@ public static SelectedDraftControlPlaneDigest compute( TemplateConfigSourceSnapshot templateConfig = sources .templateConfig() - .orElseThrow( - () -> - new IllegalStateException( - "Selected template-config source snapshot unavailable")); + .orElseThrow(() -> + new IllegalStateException("Selected template-config source snapshot unavailable")); List snapshots = List.of( new Snapshot( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java index f92a8c58d1..54800149ca 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java @@ -185,15 +185,14 @@ public SelectedDraftPublicationOwner.Reservation admitAndReserve( .selectedCommit() .affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT) .stream() - .map( - unit -> - new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) + .map(unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) .toList()); WorldPublishedStartLocationEvidence worldEvidence = worldClient.read(worldRequest); requireExactWorldReadback(worldRequest, worldEvidence); @@ -203,14 +202,13 @@ public SelectedDraftPublicationOwner.Reservation admitAndReserve( readAndVerifyWorldSource(worldEvidence, selection.target()); return Objects.requireNonNull( - reservationTransaction.execute( - status -> - owner.reserve( - intent, - accountEvidence.request().binding(), - worldEvidence, - inventory, - worldSourceRead)), + reservationTransaction.execute(status -> + owner.reserve( + intent, + accountEvidence.request().binding(), + worldEvidence, + inventory, + worldSourceRead)), "Selected Draft publication reservation returned no result"); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java index 4cf1d8c1ef..23090b1b78 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadService.java @@ -120,11 +120,10 @@ private ReadResult readSnapshot( GameDesignPublicationOperationRepository.Readback readback = owner .read(publicationRequest.derivedWorkflowIdentity()) - .orElseThrow( - () -> - Status.NOT_FOUND - .withDescription("Selected publication operation unavailable") - .asRuntimeException()); + .orElseThrow(() -> + Status.NOT_FOUND + .withDescription("Selected publication operation unavailable") + .asRuntimeException()); GameDesignPublicationOperation operation = readback.operation(); requireOperationCorrelation(operation, publicationRequest); @@ -133,22 +132,20 @@ private ReadResult readSnapshot( GameDesignSourceRepository.Capture frozen = owner .readSourceCapture(operation) - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription("Complete selected source capture unavailable") - .asRuntimeException()); + .orElseThrow(() -> + Status.FAILED_PRECONDITION + .withDescription("Complete selected source capture unavailable") + .asRuntimeException()); requireCapture(operation, frozen); DraftCommitBinding selected = operation.account().input().selection().selectedCommit(); GameDesignSourceRepository.SynchronizedSources synchronizedSources = owner .readSynchronized(selected.target(), selected.commitId()) - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription("Complete synchronized selected sources unavailable") - .asRuntimeException()); + .orElseThrow(() -> + Status.FAILED_PRECONDITION + .withDescription("Complete synchronized selected sources unavailable") + .asRuntimeException()); requireFrozenSources(selected, frozen, synchronizedSources); if (receipt.isPresent() && !SelectedGameplayRuleSourceJoin.matches( @@ -233,33 +230,27 @@ private static void requireCapture( capture.policy().operation().canonicalBytes(), capture .asset() - .orElseThrow( - () -> - new IllegalStateException("Complete frozen asset source capture unavailable")) + .orElseThrow(() -> + new IllegalStateException("Complete frozen asset source capture unavailable")) .operation() .canonicalBytes(), capture .branding() - .orElseThrow( - () -> - new IllegalStateException( - "Complete frozen branding source capture unavailable")) + .orElseThrow(() -> + new IllegalStateException("Complete frozen branding source capture unavailable")) .operation() .canonicalBytes(), capture .templateConfig() - .orElseThrow( - () -> - new IllegalStateException( - "Complete frozen templateConfig source capture unavailable")) + .orElseThrow(() -> + new IllegalStateException( + "Complete frozen templateConfig source capture unavailable")) .operation() .canonicalBytes(), capture .gameplay() - .orElseThrow( - () -> - new IllegalStateException( - "Complete frozen gameplay source capture unavailable")) + .orElseThrow(() -> + new IllegalStateException("Complete frozen gameplay source capture unavailable")) .operation() .canonicalBytes() }) { @@ -281,10 +272,8 @@ private static void requireFrozenSources( TemplateConfigSourceSnapshot templateConfig = synchronizedSources .templateConfig() - .orElseThrow( - () -> - new IllegalStateException( - "Selected template-config source snapshot unavailable")); + .orElseThrow(() -> + new IllegalStateException("Selected template-config source snapshot unavailable")); GameplayRuleSnapshot gameplay = synchronizedSources .gameplayEvidence() @@ -304,40 +293,35 @@ private static void requireFrozenSources( || !Arrays.equals( frozen .asset() - .orElseThrow( - () -> - new IllegalStateException( - "Complete frozen asset source capture unavailable")) + .orElseThrow(() -> + new IllegalStateException("Complete frozen asset source capture unavailable")) .snapshot() .canonicalBytes(), synchronizedSources.asset().canonicalBytes()) || !Arrays.equals( frozen .branding() - .orElseThrow( - () -> - new IllegalStateException( - "Complete frozen branding source capture unavailable")) + .orElseThrow(() -> + new IllegalStateException( + "Complete frozen branding source capture unavailable")) .snapshot() .canonicalBytes(), branding.canonicalBytes()) || !Arrays.equals( frozen .templateConfig() - .orElseThrow( - () -> - new IllegalStateException( - "Complete frozen templateConfig source capture unavailable")) + .orElseThrow(() -> + new IllegalStateException( + "Complete frozen templateConfig source capture unavailable")) .snapshot() .canonicalBytes(), templateConfig.canonicalBytes()) || !Arrays.equals( frozen .gameplay() - .orElseThrow( - () -> - new IllegalStateException( - "Complete frozen gameplay source capture unavailable")) + .orElseThrow(() -> + new IllegalStateException( + "Complete frozen gameplay source capture unavailable")) .snapshot() .canonicalBytes(), gameplay.canonicalBytes())) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java index 3b774a371a..82aa20bee0 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationOwner.java @@ -150,17 +150,15 @@ public Reservation reserve( var gameplayCapture = capture .gameplay() - .orElseThrow( - () -> - new IllegalStateException( - "SELECTED_PUBLICATION_GAMEPLAY_SOURCE_CAPTURE_UNAVAILABLE")); + .orElseThrow(() -> + new IllegalStateException( + "SELECTED_PUBLICATION_GAMEPLAY_SOURCE_CAPTURE_UNAVAILABLE")); var templateCapture = capture .templateConfig() - .orElseThrow( - () -> - new IllegalStateException( - "SELECTED_PUBLICATION_TEMPLATE_SOURCE_CAPTURE_UNAVAILABLE")); + .orElseThrow(() -> + new IllegalStateException( + "SELECTED_PUBLICATION_TEMPLATE_SOURCE_CAPTURE_UNAVAILABLE")); templateWorldSources.retainOrRead( operation, templateCapture, worldSourceRead, priorOperation.isEmpty()); var retained = @@ -172,10 +170,8 @@ public Reservation reserve( selections .read( intent.canonicalTenantId(), intent.canonicalVersionId(), intent.publishRequestId()) - .orElseThrow( - () -> - new IllegalStateException( - "SELECTED_PUBLICATION_SELECTION_READBACK_UNAVAILABLE")) + .orElseThrow(() -> + new IllegalStateException("SELECTED_PUBLICATION_SELECTION_READBACK_UNAVAILABLE")) .selection(); if (!Arrays.equals(operation.canonicalBytes(), retained.operation().canonicalBytes()) || !"PENDING".equals(retained.outcome()) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociationRepository.java index fff0ef7fff..93fc686c66 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftTemplateWorldSourceAssociationRepository.java @@ -90,10 +90,9 @@ public List readExact( rows.stream() .filter(value -> Objects.equals(value.get("template_id", Long.class), templateId)) .findFirst() - .orElseThrow( - () -> - new IllegalStateException( - "SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_ENTRY_MISSING")); + .orElseThrow(() -> + new IllegalStateException( + "SELECTED_TEMPLATE_WORLD_SOURCE_ASSOCIATION_ENTRY_MISSING")); Association retained = decode(operation, capture, entry, row); requireRowMatches(retained, row); result.add(retained); @@ -108,10 +107,9 @@ private List associations( Objects.requireNonNull(operation, "operation"); Objects.requireNonNull(capture, "capture"); return capture.snapshot().entries().stream() - .map( - entry -> - SelectedDraftTemplateWorldSourceAssociation.create( - operation, capture, entry, sourceRead)) + .map(entry -> + SelectedDraftTemplateWorldSourceAssociation.create( + operation, capture, entry, sourceRead)) .toList(); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java index 35c8cc11d8..a959d3e7ff 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducer.java @@ -145,12 +145,11 @@ public ResolvedBinding resolve(Request request) { canonicalTenantId, association.worldSlug(), request.targetNamespace()) - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription( - "Exact registered Game Design source for the association is unavailable") - .asRuntimeException()); + .orElseThrow(() -> + Status.FAILED_PRECONDITION + .withDescription( + "Exact registered Game Design source for the association is unavailable") + .asRuntimeException()); requireSourceMatches(association, source); AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest = descriptorRequest(tuple, association); @@ -159,17 +158,16 @@ public ResolvedBinding resolve(Request request) { OwnerOutcome outcome = Objects.requireNonNull( - writeTransaction.execute( - ignored -> - writeOrRead( - request, - exact, - descriptorRequest, - requestJson, - source, - sourceJson, - canonicalTenantId, - templateId)), + writeTransaction.execute(ignored -> + writeOrRead( + request, + exact, + descriptorRequest, + requestJson, + source, + sourceJson, + canonicalTenantId, + templateId)), "StartSession launch descriptor transaction returned no binding"); if (outcome.failure() != null) { throw new StoredBusinessDenial(exact, outcome.failure()); @@ -1017,32 +1015,30 @@ private GameDesignPublicationTerminalEvidence.ReleaseContent releaseContent(Resu } List participants = bundle.getParticipantDigestsList().stream() - .map( - value -> - new GameDesignPublicationTerminalEvidence.Participant( - value.getParticipantKey(), - value.getScopeValue(), - null, - value.getAppliedCommitId(), - value.getContentDigest(), - value.getDigestSchemaVersion(), - value.hasAbilitySchemaDigest() ? value.getAbilitySchemaDigest() : null, - null, - null)) + .map(value -> + new GameDesignPublicationTerminalEvidence.Participant( + value.getParticipantKey(), + value.getScopeValue(), + null, + value.getAppliedCommitId(), + value.getContentDigest(), + value.getDigestSchemaVersion(), + value.hasAbilitySchemaDigest() ? value.getAbilitySchemaDigest() : null, + null, + null)) .toList(); List artifacts = bundle.getArtifactDigestsList().stream() - .map( - value -> - new net.firedevops.firemud.common.gamedesign - .AuthoredWorldReleaseAttestationEvidence.Artifact( - value.getUsageKey(), - value.getArtifactKind(), - value.getImmutableObjectKey(), - value.getContentDigest(), - value.getContentType(), - value.getArtifactSchemaVersion())) + .map(value -> + new net.firedevops.firemud.common.gamedesign + .AuthoredWorldReleaseAttestationEvidence.Artifact( + value.getUsageKey(), + value.getArtifactKind(), + value.getImmutableObjectKey(), + value.getContentDigest(), + value.getContentType(), + value.getArtifactSchemaVersion())) .toList(); return new GameDesignPublicationTerminalEvidence.ReleaseContent( UUID.fromString(bundle.getCanonicalTenantId()), diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java index 5ce6182007..c59c2fb892 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadService.java @@ -193,15 +193,13 @@ private Result readSnapshot(Request request, StartSessionPostAuthorizationExecut .readPhase(canonicalTenantId) .filter(value -> value.phase() == TemplateReferenceRepository.Phase.ENFORCED) .filter(value -> value.phaseEpoch() > 0L) - .filter( - value -> - value.inventoryTemplateCount() != null && value.inventoryTemplateCount() > 0L) + .filter(value -> + value.inventoryTemplateCount() != null && value.inventoryTemplateCount() > 0L) .filter(value -> value.inventoryDigest() != null) - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription("Explicit enforced template reference phase unavailable") - .asRuntimeException()); + .orElseThrow(() -> + Status.FAILED_PRECONDITION + .withDescription("Explicit enforced template reference phase unavailable") + .asRuntimeException()); UUID canonicalVersionId; UUID selectedCommitId = null; @@ -211,11 +209,10 @@ private Result readSnapshot(Request request, StartSessionPostAuthorizationExecut configuredReference = templateReferences .readExactBaseReference(canonicalTenantId, templateId) - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription("Current normalized template reference unavailable") - .asRuntimeException()); + .orElseThrow(() -> + Status.FAILED_PRECONDITION + .withDescription("Current normalized template reference unavailable") + .asRuntimeException()); canonicalVersionId = configuredReference.canonicalVersionId(); if (!canonicalTenantId.equals(configuredReference.canonicalTenantId()) || templateId != configuredReference.templateId()) { @@ -233,11 +230,10 @@ private Result readSnapshot(Request request, StartSessionPostAuthorizationExecut Version version = versions .findByCanonicalTenantIdAndCanonicalVersionId(canonicalTenantId, canonicalVersionId) - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription("Exact canonical published Version unavailable") - .asRuntimeException()); + .orElseThrow(() -> + Status.FAILED_PRECONDITION + .withDescription("Exact canonical published Version unavailable") + .asRuntimeException()); requireLaunchableVersion(version, canonicalTenantId, canonicalVersionId, phase); if (configuredReference != null) { configuredEntry = @@ -253,11 +249,10 @@ private Result readSnapshot(Request request, StartSessionPostAuthorizationExecut PublishedReleaseBundleDto configuredRelease = releases .findPublishedReleaseBundle(version.getTenantId(), version.getId()) - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription("Exact published release bundle unavailable") - .asRuntimeException()); + .orElseThrow(() -> + Status.FAILED_PRECONDITION + .withDescription("Exact published release bundle unavailable") + .asRuntimeException()); if (!canonicalTenantId.equals(configuredRelease.canonicalTenantId()) || !canonicalVersionId.equals(configuredRelease.canonicalVersionId()) || !PublishedReleaseBundleDto.isSelectedAttestationSchema( @@ -293,11 +288,10 @@ private Result readExactPublication( GameDesignPublicationOperationRepository.Readback operationReadback = publicationOperations .read(workflowId) - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription("Exact original publication operation unavailable") - .asRuntimeException()); + .orElseThrow(() -> + Status.FAILED_PRECONDITION + .withDescription("Exact original publication operation unavailable") + .asRuntimeException()); GameDesignPublicationOperation operation = operationReadback.operation(); if (!"PUBLISHED".equals(operationReadback.outcome()) || operationReadback.terminalEvidenceBytes() == null @@ -346,19 +340,17 @@ private Result readExactPublication( GameDesignSourceRepository.Capture capture = sourceRepository .readCapture(operation) - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription("Complete original selected source capture unavailable") - .asRuntimeException()); + .orElseThrow(() -> + Status.FAILED_PRECONDITION + .withDescription("Complete original selected source capture unavailable") + .asRuntimeException()); TemplateConfigSourceSnapshot.Capture templateCapture = capture .templateConfig() - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription("Exact template source capture unavailable") - .asRuntimeException()); + .orElseThrow(() -> + Status.FAILED_PRECONDITION + .withDescription("Exact template source capture unavailable") + .asRuntimeException()); if (!templateCapture.snapshot().binding().equals(selected.selectedCommit())) { throw new IllegalStateException("START_SESSION_CAPTURE_SOURCE_ENTRY_CONFLICT"); } @@ -431,11 +423,10 @@ private Result readExactPublication( PublishedReleaseBundleDto release = releases .findPublishedReleaseBundle(version.getTenantId(), version.getId()) - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription("Exact published release bundle unavailable") - .asRuntimeException()); + .orElseThrow(() -> + Status.FAILED_PRECONDITION + .withDescription("Exact published release bundle unavailable") + .asRuntimeException()); if (!workflowId.equals(release.publishWorkflowId()) || !canonicalTenantId.equals(release.canonicalTenantId()) || !canonicalVersionId.equals(release.canonicalVersionId()) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java index fe1a8d202e..e6057bb76c 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceRepository.java @@ -471,11 +471,10 @@ private void requireSelectedReferences(TemplateConfigSourceSnapshot snapshot) { for (var entry : snapshot.entries()) for (var input : entry.config().gameplayInputs()) if (gameplay.entries().stream() - .noneMatch( - e -> - e.family() == input.family() - && e.definition().key().equals(input.key()) - && e.revisionId().equals(input.revisionId()))) + .noneMatch(e -> + e.family() == input.family() + && e.definition().key().equals(input.key()) + && e.revisionId().equals(input.revisionId()))) throw new IllegalStateException("TEMPLATE_CONFIG_GAMEPLAY_INPUT_CHANGED"); } @@ -519,10 +518,9 @@ private Optional application( private void verifyOwnerInventoryApplication(DraftCommitBinding binding) { var expected = TemplateConfigSource.mutations(binding).stream() - .filter( - mutation -> - mutation.operation() - == TemplateConfigSource.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .filter(mutation -> + mutation.operation() + == TemplateConfigSource.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) .toList(); var rows = dsl.fetch( @@ -574,19 +572,14 @@ private void verifyOwnerInventoryDeclarations(TemplateConfigSourceSnapshot snaps var mutation = TemplateConfigSource.mutations(sourceBinding).stream() .filter(m -> m.revisionId().equals(row.get("revision_id", UUID.class))) - .filter( - m -> - Integer.parseInt(m.revisionOrder()) - == row.get("revision_order", Integer.class)) - .filter( - m -> - m.operation() - == TemplateConfigSource.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .filter(m -> + Integer.parseInt(m.revisionOrder()) == row.get("revision_order", Integer.class)) + .filter(m -> + m.operation() + == TemplateConfigSource.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) .findFirst() - .orElseThrow( - () -> - new IllegalStateException( - "TEMPLATE_CONFIG_OWNER_INVENTORY_SOURCE_UNAVAILABLE")); + .orElseThrow(() -> + new IllegalStateException("TEMPLATE_CONFIG_OWNER_INVENTORY_SOURCE_UNAVAILABLE")); if (!sourceBinding.requestId().equals(row.get("request_id", UUID.class)) || !sourceBinding.commitId().equals(row.get("commit_id", UUID.class)) || !mutation.declaredOwner().name().equals(row.get("owner", String.class)) @@ -604,15 +597,12 @@ private void verifyOwnerInventoryDeclarations(TemplateConfigSourceSnapshot snaps TemplateConfigSource.mutations(declaration.sourceBinding()).stream() .filter(m -> m.revisionId().equals(declaration.revisionId())) .filter(m -> m.revisionOrder().equals(declaration.revisionOrder())) - .filter( - m -> - m.operation() - == TemplateConfigSource.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .filter(m -> + m.operation() + == TemplateConfigSource.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) .findFirst() - .orElseThrow( - () -> - new IllegalStateException( - "TEMPLATE_CONFIG_OWNER_INVENTORY_SOURCE_UNAVAILABLE")); + .orElseThrow(() -> + new IllegalStateException("TEMPLATE_CONFIG_OWNER_INVENTORY_SOURCE_UNAVAILABLE")); var row = dsl.fetchOne( "SELECT request_id, commit_id, owner, inventory_json, payload_json " @@ -757,11 +747,10 @@ private void requireGameplayInputs( var rules = GameplayRuleSnapshot.fromStored(json); for (var input : config.gameplayInputs()) if (rules.entries().stream() - .noneMatch( - e -> - e.family() == input.family() - && e.definition().key().equals(input.key()) - && e.revisionId().equals(input.revisionId()))) + .noneMatch(e -> + e.family() == input.family() + && e.definition().key().equals(input.key()) + && e.revisionId().equals(input.revisionId()))) throw new IllegalStateException("TEMPLATE_CONFIG_GAMEPLAY_INPUT_UNAVAILABLE"); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateReferenceRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateReferenceRepository.java index 537443fa54..ec2fd3bed6 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateReferenceRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/TemplateReferenceRepository.java @@ -370,9 +370,8 @@ private InventoryEvidence readCompleteInventory(GameOwner owner) { TemplateConfigSourceSnapshot snapshot = sourceRepository .readSnapshot(scope.target(), visibleCommitId) - .orElseThrow( - () -> - new IllegalStateException("TEMPLATE_REFERENCE_SOURCE_SNAPSHOT_UNAVAILABLE")); + .orElseThrow(() -> + new IllegalStateException("TEMPLATE_REFERENCE_SOURCE_SNAPSHOT_UNAVAILABLE")); Map versionTemplates = templatesByVersion.get(canonicalVersionId); if (snapshot.entries().size() != versionTemplates.size()) { throw new IllegalStateException("TEMPLATE_REFERENCE_INVENTORY_SOURCE_SET_CONFLICT"); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTemplateRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTemplateRepository.java index 5d1f848f5a..2886db8863 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTemplateRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTemplateRepository.java @@ -92,15 +92,14 @@ public Optional findLaunchConfigByTenantIdAndId( .from(TABLE_REF) .where(TENANT_ID.eq(tenantId).and(ID.eq(id))) .limit(1) - .fetchOne( - record -> - new GameTemplateLaunchConfigViewRecord( - record.get(ID), - record.get(TENANT_ID), - record.get(DEFAULT_VERSION_ID), - record.get(DEFAULT_SCRIPT_PATCH_VERSION), - record.get(DEFAULT_RUNTIME_FLAGS_JSON), - TemplateReferencePhase.valueOf(record.get(TEMPLATE_REFERENCE_PHASE))))); + .fetchOne(record -> + new GameTemplateLaunchConfigViewRecord( + record.get(ID), + record.get(TENANT_ID), + record.get(DEFAULT_VERSION_ID), + record.get(DEFAULT_SCRIPT_PATCH_VERSION), + record.get(DEFAULT_RUNTIME_FLAGS_JSON), + TemplateReferencePhase.valueOf(record.get(TEMPLATE_REFERENCE_PHASE))))); } public GameTemplate save(GameTemplate template) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java index 0e9d012343..6698bb87cf 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepository.java @@ -244,10 +244,9 @@ private void requireNewGameSource(Game saved, String sourceGameTenantKey) { source = gameRepository .findRuntimeTenantIdentityByTenantKey(sourceGameTenantKey) - .orElseThrow( - () -> - new IllegalStateException( - "New game source identity did not read back after insert")); + .orElseThrow(() -> + new IllegalStateException( + "New game source identity did not read back after insert")); } catch (IllegalStateException exception) { throw new IllegalStateException("New game source identity did not read back", exception); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java index d450711f7f..72c334751b 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java @@ -168,13 +168,12 @@ public PublishedReleaseBundle save(PublishedReleaseBundle bundle) { throw new IllegalStateException( "Published release bundle is immutable; read the stored row instead of saving it again"); } - return dsl.transactionResult( - configuration -> { - DSLContext tx = DSL.using(configuration); - LocalDateTime publishedAt = - bundle.getPublishedAt() == null ? LocalDateTime.now() : bundle.getPublishedAt(); - return insertNewBundle(tx, bundle, publishedAt); - }); + return dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + LocalDateTime publishedAt = + bundle.getPublishedAt() == null ? LocalDateTime.now() : bundle.getPublishedAt(); + return insertNewBundle(tx, bundle, publishedAt); + }); } private PublishedReleaseBundle insertNewBundle( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java index 57c46fd3eb..ff1b31fc66 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java @@ -52,17 +52,16 @@ public ExportSnapshot freezeOrReadSnapshot(String tenantId, int versionNumber) { if (versionNumber <= 0) { throw new IllegalArgumentException("Version number must be positive"); } - return dsl.connectionResult( - connection -> { - if (connection.getAutoCommit()) { - throw new IllegalStateException( - "Version asset snapshot requires an enclosing owner transaction"); - } - // Preserve caller configuration while keeping every query on the checked connection. - DSLContext ownerDsl = DSL.using(dsl.configuration().derive(connection)); - return new VersionAssetPublicationRepository(ownerDsl) - .freezeOrReadSnapshotInTransaction(tenantId, versionNumber); - }); + return dsl.connectionResult(connection -> { + if (connection.getAutoCommit()) { + throw new IllegalStateException( + "Version asset snapshot requires an enclosing owner transaction"); + } + // Preserve caller configuration while keeping every query on the checked connection. + DSLContext ownerDsl = DSL.using(dsl.configuration().derive(connection)); + return new VersionAssetPublicationRepository(ownerDsl) + .freezeOrReadSnapshotInTransaction(tenantId, versionNumber); + }); } private ExportSnapshot freezeOrReadSnapshotInTransaction(String tenantId, int versionNumber) { @@ -419,15 +418,14 @@ private List lockMappedSourceAssets(String tenantId, long versionId + "ORDER BY va.asset_id FOR UPDATE OF ga", tenantId, versionId) - .map( - row -> - new SourceAsset( - row.get("usage_key", String.class), - row.get("asset_id", Long.class), - row.get("file_name", String.class), - row.get("content_type", String.class), - row.get("content_digest", String.class), - row.get("byte_size", Long.class))); + .map(row -> + new SourceAsset( + row.get("usage_key", String.class), + row.get("asset_id", Long.class), + row.get("file_name", String.class), + row.get("content_type", String.class), + row.get("content_digest", String.class), + row.get("byte_size", Long.class))); } private Optional lockVersionByTenantAndVersionNumber( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionTemplateRemapSetRepository.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionTemplateRemapSetRepository.java index b847164946..25dbd31326 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionTemplateRemapSetRepository.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionTemplateRemapSetRepository.java @@ -207,18 +207,17 @@ private List loadEntries(VersionTemplateRemapSet rema return dsl.selectFrom(ENTRY_TABLE) .where(ENTRY_REMAP_SET_PK.eq(remapSet.getId())) .orderBy(ENTRY_ID.asc()) - .fetch( - record -> { - VersionTemplateRemapEntry entry = new VersionTemplateRemapEntry(); - entry.setId(record.get(ENTRY_ID)); - entry.setRemapSet(remapSet); - entry.setMappingDomain(record.get(ENTRY_MAPPING_DOMAIN)); - entry.setMappingType(record.get(ENTRY_MAPPING_TYPE)); - entry.setSourceTemplateKey(record.get(ENTRY_SOURCE_TEMPLATE_KEY)); - entry.setTargetTemplateKey(record.get(ENTRY_TARGET_TEMPLATE_KEY)); - entry.setCreatedAt(readLocalDateTime(record, ENTRY_CREATED_AT)); - return entry; - }); + .fetch(record -> { + VersionTemplateRemapEntry entry = new VersionTemplateRemapEntry(); + entry.setId(record.get(ENTRY_ID)); + entry.setRemapSet(remapSet); + entry.setMappingDomain(record.get(ENTRY_MAPPING_DOMAIN)); + entry.setMappingType(record.get(ENTRY_MAPPING_TYPE)); + entry.setSourceTemplateKey(record.get(ENTRY_SOURCE_TEMPLATE_KEY)); + entry.setTargetTemplateKey(record.get(ENTRY_TARGET_TEMPLATE_KEY)); + entry.setCreatedAt(readLocalDateTime(record, ENTRY_CREATED_AT)); + return entry; + }); } private static LocalDateTime readLocalDateTime(Record record, Field field) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AccountAuthorizedTenantCreationService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AccountAuthorizedTenantCreationService.java index f7e6e03633..06ae06270e 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AccountAuthorizedTenantCreationService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AccountAuthorizedTenantCreationService.java @@ -117,36 +117,34 @@ public FreshTenantCreationEvidence create(CandidateRequest request) { } WriteDisposition disposition = - ownerWrite.execute( - transaction -> { - dispatchRepository.applyLocalWriteTimeouts(); - if (!dispatchRepository.isAuthorizationCurrent( - authorization.validBeforeEpochMillis())) { - throw new IllegalStateException( - "Current Account tenant-creation authorization expired before owner writes"); - } + ownerWrite.execute(transaction -> { + dispatchRepository.applyLocalWriteTimeouts(); + if (!dispatchRepository.isAuthorizationCurrent(authorization.validBeforeEpochMillis())) { + throw new IllegalStateException( + "Current Account tenant-creation authorization expired before owner writes"); + } - OriginalOutcomeSnapshot claimed = outcomeRepository.claimLocked(binding); - if (claimed.status() == OutcomeStatus.CREATED) { - return WriteDisposition.REPLAY; - } - if (claimed.status() == OutcomeStatus.NOT_CREATED) { - throw new IllegalStateException( - "A definitively closed fresh tenant original cannot be reopened"); - } + OriginalOutcomeSnapshot claimed = outcomeRepository.claimLocked(binding); + if (claimed.status() == OutcomeStatus.CREATED) { + return WriteDisposition.REPLAY; + } + if (claimed.status() == OutcomeStatus.NOT_CREATED) { + throw new IllegalStateException( + "A definitively closed fresh tenant original cannot be reopened"); + } - FreshTenantCreationEvidence receipt = - creationRepository.createCandidate( - binding.targetNamespace(), - binding.creationRequestId(), - request.sourceGameTenantKey(), - request.name(), - request.description()); - outcomeRepository.markCreatedLocked(binding, receipt); - dispatchRepository.recordAuthorizedDispatch( - binding, authorization.readRequestId(), authorization.validBeforeEpochMillis()); - return WriteDisposition.CREATED; - }); + FreshTenantCreationEvidence receipt = + creationRepository.createCandidate( + binding.targetNamespace(), + binding.creationRequestId(), + request.sourceGameTenantKey(), + request.name(), + request.description()); + outcomeRepository.markCreatedLocked(binding, receipt); + dispatchRepository.recordAuthorizedDispatch( + binding, authorization.readRequestId(), authorization.validBeforeEpochMillis()); + return WriteDisposition.CREATED; + }); if (disposition == null) { throw new IllegalStateException("Game Design creation transaction returned no disposition"); } @@ -155,10 +153,9 @@ public FreshTenantCreationEvidence create(CandidateRequest request) { AuthorizedDispatch dispatch = dispatchRepository .readCommitted(binding) - .orElseThrow( - () -> - new IllegalStateException( - "Committed Game Design creation lacks its authorization deadline fence")); + .orElseThrow(() -> + new IllegalStateException( + "Committed Game Design creation lacks its authorization deadline fence")); if (!dispatch.authorizationReadRequestId().equals(authorization.readRequestId()) || dispatch.validBeforeEpochMillis() != authorization.validBeforeEpochMillis()) { throw new IllegalStateException( @@ -168,9 +165,8 @@ public FreshTenantCreationEvidence create(CandidateRequest request) { OriginalOutcomeSnapshot terminal = outcomeRepository .readCommitted(binding) - .orElseThrow( - () -> - new IllegalStateException("Committed Game Design original outcome is absent")); + .orElseThrow(() -> + new IllegalStateException("Committed Game Design original outcome is absent")); if (!terminal.binding().equals(binding) || terminal.status() != OutcomeStatus.CREATED) { throw new IllegalStateException("Committed Game Design original outcome is not CREATED"); } @@ -229,11 +225,10 @@ private static boolean pauseAuthorizationRetry(long delayMillis) { public void closeOriginal(Binding binding) { requireOutsideSql(); Objects.requireNonNull(binding, "binding"); - ownerWrite.executeWithoutResult( - transaction -> { - dispatchRepository.applyLocalWriteTimeouts(); - outcomeRepository.closeNotCreatedLocked(binding); - }); + ownerWrite.executeWithoutResult(transaction -> { + dispatchRepository.applyLocalWriteTimeouts(); + outcomeRepository.closeNotCreatedLocked(binding); + }); } private FreshTenantCreationEvidence replayTerminal( @@ -255,10 +250,9 @@ private FreshTenantCreationEvidence readAndVerifyReceipt( FreshTenantCreationEvidence receipt = creationRepository .read(binding.creationRequestId(), binding.targetNamespace()) - .orElseThrow( - () -> - new IllegalStateException( - "CREATED Game Design original lacks its committed V30 receipt")); + .orElseThrow(() -> + new IllegalStateException( + "CREATED Game Design original lacks its committed V30 receipt")); if (!receipt.targetNamespace().equals(binding.targetNamespace()) || !receipt.creationRequestId().equals(binding.creationRequestId()) || !receipt.requestDigest().equals(binding.creationRequestDigest()) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateService.java index 82ce26c230..3eb8ef569f 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AuthoredWorldVersionStateService.java @@ -31,16 +31,15 @@ public AuthoredWorldVersionStateService( public AuthoredWorldVersionStateEvidence read(AuthoredWorldVersionStateEvidence.Request request) { Objects.requireNonNull(request, "request"); Optional snapshot = - ownerSnapshot.execute( - status -> - sourceRepository.readVersionStateSnapshot( - request.targetNamespace(), - request.readRequestId(), - request.canonicalTenantId(), - request.worldSlug(), - request.sourceOperationId(), - request.expectedSourceEvidenceDigest(), - request.versionId())); + ownerSnapshot.execute(status -> + sourceRepository.readVersionStateSnapshot( + request.targetNamespace(), + request.readRequestId(), + request.canonicalTenantId(), + request.worldSlug(), + request.sourceOperationId(), + request.expectedSourceEvidenceDigest(), + request.versionId())); if (snapshot == null || snapshot.isEmpty()) { throw new NotFoundException( "No authored-world source or version exists for the exact requested owner tuple"); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java index 261d04ae77..2527dcd036 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImpl.java @@ -99,11 +99,10 @@ public CompleteLaunchBindingDto getCompleteLaunchBinding( descriptor.authoredWorldSourceOperationId(), descriptor.authoredWorldSourceEvidenceDigest(), descriptor.versionId()) - .orElseThrow( - () -> - deny( - "AUTHORED_WORLD_SOURCE_NOT_FOUND", - "exact committed source or descriptor version is missing")); + .orElseThrow(() -> + deny( + "AUTHORED_WORLD_SOURCE_NOT_FOUND", + "exact committed source or descriptor version is missing")); AuthoredWorldSourceEvidence source = sourceSnapshot.sourceEvidence(); requireSourceMatchesDescriptor(source, descriptor, canonicalTenantId, worldSlug); if (sourceSnapshot.versionState() == null @@ -324,11 +323,10 @@ private Version requireCanonicalVersion( versionRepository .findByCanonicalTenantIdAndCanonicalVersionId( bundle.canonicalTenantId(), bundle.canonicalVersionId()) - .orElseThrow( - () -> - deny( - "CANONICAL_VERSION_NOT_FOUND", - "release canonical Version identity has no exact persisted owner source")); + .orElseThrow(() -> + deny( + "CANONICAL_VERSION_NOT_FOUND", + "release canonical Version identity has no exact persisted owner source")); if (!Objects.equals(version.getId(), descriptor.versionId()) || !Objects.equals(version.getTenantId(), source.sourceGameTenantKey()) || !Objects.equals(version.getCanonicalTenantId(), source.canonicalTenantId()) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImpl.java index 5378ab75a9..928392535b 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImpl.java @@ -68,38 +68,34 @@ private String computeDigest(VersionDto version) { List> templates = gameTemplateRepository.findByTenantId(version.tenantId(), Pageable.unpaged()).stream() .sorted(Comparator.comparing(entity -> entity.getName().toLowerCase())) - .map( - entity -> - Map.of( - "name", entity.getName(), - "description", - entity.getDescription() == null ? "" : entity.getDescription(), - "config", entity.getConfig())) + .map(entity -> + Map.of( + "name", entity.getName(), + "description", entity.getDescription() == null ? "" : entity.getDescription(), + "config", entity.getConfig())) .toList(); List> assets = gameAssetRepository.findByTenantId(version.tenantId()).stream() .sorted(Comparator.comparing(entity -> entity.getFileName().toLowerCase())) - .map( - entity -> - Map.of( - "fileName", entity.getFileName(), - "contentType", entity.getContentType(), - "byteLength", entity.getData() == null ? 0 : entity.getData().length)) + .map(entity -> + Map.of( + "fileName", entity.getFileName(), + "contentType", entity.getContentType(), + "byteLength", entity.getData() == null ? 0 : entity.getData().length)) .toList(); List> commandDefinitions = revisionRepository .findByTenantIdAndVersionIdAndRevisionKindOrderByIdAsc( version.tenantId(), version.id(), "COMMAND_DEFINITION") .stream() - .map( - revision -> - Map.of( - "logicalRevisionId", - revision.getLogicalRevisionId() == null - ? "" - : revision.getLogicalRevisionId(), - "data", - revision.getData())) + .map(revision -> + Map.of( + "logicalRevisionId", + revision.getLogicalRevisionId() == null + ? "" + : revision.getLogicalRevisionId(), + "data", + revision.getData())) .toList(); String canonicalJson = objectMapper.writeValueAsString( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAssetServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAssetServiceImpl.java index 1fc5a36fe3..eae42574a0 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAssetServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAssetServiceImpl.java @@ -21,10 +21,9 @@ public class GameAssetServiceImpl implements GameAssetService { @Transactional @Timed(value = "gamedesign.asset.upload") public GameAssetDto uploadAsset(String tenantId, MultipartFile file) { - return CreatorMutationOwnerProofGuard.denyUntilAccountCommitBoundProof( - () -> - new MutationOwnerProofUnavailableException( - "CREATOR_MUTATION_OWNER_PROOF_UNAVAILABLE", - "Account commit-bound authority is unavailable for asset upload")); + return CreatorMutationOwnerProofGuard.denyUntilAccountCommitBoundProof(() -> + new MutationOwnerProofUnavailableException( + "CREATOR_MUTATION_OWNER_PROOF_UNAVAILABLE", + "Account commit-bound authority is unavailable for asset upload")); } } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImpl.java index ab5c991de2..9cfa1a66b6 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImpl.java @@ -37,10 +37,9 @@ public Optional resolvePublishedTopic( String normalizedTopic = normalizeKey(topic, "topic"); return repository .findPublishedByCanonicalKey(scope.tenantId(), scope.gameTemplateId(), normalizedTopic) - .or( - () -> - repository.findPublishedByAliasKey( - scope.tenantId(), scope.gameTemplateId(), normalizedTopic)) + .or(() -> + repository.findPublishedByAliasKey( + scope.tenantId(), scope.gameTemplateId(), normalizedTopic)) .map(this::toDto); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java index 952e81d7de..a6b5c40301 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignGrpcService.java @@ -661,17 +661,16 @@ public void listVersions( try { AdminRoleGuard.requireAdminRole(); var versions = versionService.listVersions(request.getTenantId()); - versions.forEach( - v -> - builder.addVersions( - net.firedevops.firemud.gamedesign.v1.Version.newBuilder() - .setId(v.id()) - .setVersionNumber(v.versionNumber()) - .setScriptPatchVersion( - v.scriptPatchVersion() == null ? "" : v.scriptPatchVersion()) - .setIsScriptOnly(v.scriptOnly()) - .setNotes(v.notes() == null ? "" : v.notes()) - .build())); + versions.forEach(v -> + builder.addVersions( + net.firedevops.firemud.gamedesign.v1.Version.newBuilder() + .setId(v.id()) + .setVersionNumber(v.versionNumber()) + .setScriptPatchVersion( + v.scriptPatchVersion() == null ? "" : v.scriptPatchVersion()) + .setIsScriptOnly(v.scriptOnly()) + .setNotes(v.notes() == null ? "" : v.notes()) + .build())); } catch (AdminAuthorizationException ex) { builder.setError( GrpcAppErrors.error( @@ -2019,43 +2018,39 @@ private net.firedevops.firemud.gamedesign.dto.WorldDesignMutationRevisionDto toD return new net.firedevops.firemud.gamedesign.dto.WorldDesignMutationRevisionDto .WorldGenerationSubtreeMutationDto( request.getGenerationRulesList().stream() - .map( - rule -> - new net.firedevops.firemud.gamedesign.dto.WorldDesignMutationRevisionDto - .GenerationRuleMutationDto(rule.getName(), rule.getValue())) + .map(rule -> + new net.firedevops.firemud.gamedesign.dto.WorldDesignMutationRevisionDto + .GenerationRuleMutationDto(rule.getName(), rule.getValue())) .toList(), request.getRoomsList().stream() - .map( - room -> - new net.firedevops.firemud.gamedesign.dto.WorldDesignMutationRevisionDto - .GeneratedRoomMutationDto( - room.getClientRef(), - room.getName(), - room.getDescription(), - room.getZoneId(), - room.getNameLocalizedVariantsJson(), - room.getDescriptionLocalizedVariantsJson())) + .map(room -> + new net.firedevops.firemud.gamedesign.dto.WorldDesignMutationRevisionDto + .GeneratedRoomMutationDto( + room.getClientRef(), + room.getName(), + room.getDescription(), + room.getZoneId(), + room.getNameLocalizedVariantsJson(), + room.getDescriptionLocalizedVariantsJson())) .toList(), request.getRoomExitsList().stream() - .map( - exit -> - new net.firedevops.firemud.gamedesign.dto.WorldDesignMutationRevisionDto - .GeneratedRoomExitMutationDto( - exit.getFromRoomRef(), - exit.getToRoomRef(), - exit.getDirection(), - exit.getCost())) + .map(exit -> + new net.firedevops.firemud.gamedesign.dto.WorldDesignMutationRevisionDto + .GeneratedRoomExitMutationDto( + exit.getFromRoomRef(), + exit.getToRoomRef(), + exit.getDirection(), + exit.getCost())) .toList(), request.getWorldEntitySpawnBindingsList().stream() - .map( - binding -> - new net.firedevops.firemud.gamedesign.dto.WorldDesignMutationRevisionDto - .GeneratedWorldEntitySpawnBindingMutationDto( - binding.getRoomRef(), - binding.getEntityTemplateType().name(), - binding.getEntityTemplateId(), - binding.getSpawnCount(), - binding.getRespawnDelaySeconds())) + .map(binding -> + new net.firedevops.firemud.gamedesign.dto.WorldDesignMutationRevisionDto + .GeneratedWorldEntitySpawnBindingMutationDto( + binding.getRoomRef(), + binding.getEntityTemplateType().name(), + binding.getEntityTemplateId(), + binding.getSpawnCount(), + binding.getRespawnDelaySeconds())) .toList()); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignLaunchReadProjectionMapper.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignLaunchReadProjectionMapper.java index 87aafc645b..e5ca123627 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignLaunchReadProjectionMapper.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/GameDesignLaunchReadProjectionMapper.java @@ -29,27 +29,24 @@ public static PublishedReleaseBundle toProto(PublishedReleaseBundleDto bundle) { .addAllCommandDefinitions(bundle.commandDefinitions()) .addAllParticipantDigests( bundle.participantDigests().stream() - .map( - digest -> { - ParticipantDigest.Builder participant = - ParticipantDigest.newBuilder() - .setParticipantKey(digest.participantKey()) - .setScopeValue(digest.scopeValue()) - .setAppliedCommitId( - digest.appliedCommitId() == null - ? "" - : digest.appliedCommitId()) - .setContentDigest( - digest.contentDigest() == null ? "" : digest.contentDigest()) - .setDigestSchemaVersion( - digest.digestSchemaVersion() == null - ? 0 - : digest.digestSchemaVersion()); - if (digest.abilitySchemaDigest() != null) { - participant.setAbilitySchemaDigest(digest.abilitySchemaDigest()); - } - return participant.build(); - }) + .map(digest -> { + ParticipantDigest.Builder participant = + ParticipantDigest.newBuilder() + .setParticipantKey(digest.participantKey()) + .setScopeValue(digest.scopeValue()) + .setAppliedCommitId( + digest.appliedCommitId() == null ? "" : digest.appliedCommitId()) + .setContentDigest( + digest.contentDigest() == null ? "" : digest.contentDigest()) + .setDigestSchemaVersion( + digest.digestSchemaVersion() == null + ? 0 + : digest.digestSchemaVersion()); + if (digest.abilitySchemaDigest() != null) { + participant.setAbilitySchemaDigest(digest.abilitySchemaDigest()); + } + return participant.build(); + }) .toList()) .setGenerationConfigRevision(bundle.generationConfigRevision()) .setIsScriptOnly(bundle.scriptOnly()) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java index aca63dc4c2..bd659cd3a0 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImpl.java @@ -105,11 +105,9 @@ private ResolvedLaunchDescriptorDto resolveNewLaunchDescriptor( .findLaunchConfigByTenantIdAndId(source.sourceGameTenantKey(), request.gameTemplateId()) .filter(row -> row.getId() == request.gameTemplateId()) .filter(row -> source.sourceGameTenantKey().equals(row.getTenantId())) - .orElseThrow( - () -> - denial( - "INVALID_TEMPLATE_CONFIGURATION", - "template is not owned by the source game")); + .orElseThrow(() -> + denial( + "INVALID_TEMPLATE_CONFIGURATION", "template is not owned by the source game")); if (template.getTemplateReferencePhase() != TemplateReferencePhase.ENFORCED) { throw denial( "TEMPLATE_REFERENCE_PHASE_NOT_ENFORCED", "template reference phase is not enforced"); @@ -126,25 +124,23 @@ private ResolvedLaunchDescriptorDto resolveNewLaunchDescriptor( .findById(versionId) .filter(row -> row.getId().equals(versionId)) .filter(row -> source.sourceGameTenantKey().equals(row.getTenantId())) - .map( - row -> - new VersionDto( - row.getId(), - row.getTenantId(), - row.getVersionNumber(), - row.getVersionState(), - row.getVersionStateEpoch(), - row.getScriptPatchVersion(), - row.getBaseVersionId(), - row.isScriptOnly(), - row.getNotes(), - row.getCreatedAt(), - row.getUpdatedAt())) - .orElseThrow( - () -> - denial( - "INVALID_TEMPLATE_CONFIGURATION", - "target version is not owned by the source game")); + .map(row -> + new VersionDto( + row.getId(), + row.getTenantId(), + row.getVersionNumber(), + row.getVersionState(), + row.getVersionStateEpoch(), + row.getScriptPatchVersion(), + row.getBaseVersionId(), + row.isScriptOnly(), + row.getNotes(), + row.getCreatedAt(), + row.getUpdatedAt())) + .orElseThrow(() -> + denial( + "INVALID_TEMPLATE_CONFIGURATION", + "target version is not owned by the source game")); if (version.versionState() != VersionLifecycleState.PUBLISHED && version.versionState() != VersionLifecycleState.ACTIVE) { throw denial("VERSION_STATE_EPOCH_STALE", "resolved version is not activation-eligible"); @@ -164,11 +160,10 @@ private ResolvedLaunchDescriptorDto resolveNewLaunchDescriptor( templateRemapSetService .findApprovedTemplateRemapSet( source.sourceGameTenantKey(), request.sourceVersionId(), versionId) - .orElseThrow( - () -> - denial( - "LAUNCH_REMAP_REQUIRED", - "replacement-instance launch requires an approved remapSetId")); + .orElseThrow(() -> + denial( + "LAUNCH_REMAP_REQUIRED", + "replacement-instance launch requires an approved remapSetId")); remapSetId = remap.remapSetId(); } PublishedReleaseBundleDto bundle = @@ -315,10 +310,9 @@ public ResolvedLaunchDescriptorDto getLaunchDescriptorInOwnerSnapshot( storedRequest.authoredWorldSourceOperationId(), storedRequest.authoredWorldSourceEvidenceDigest(), Objects.requireNonNull(descriptor.getVersionId(), "descriptor versionId")) - .orElseThrow( - () -> - new IllegalArgumentException( - "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source or version is missing")); + .orElseThrow(() -> + new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source or version is missing")); AuthoredWorldSourceEvidence source = sourceSnapshot.sourceEvidence(); requireExactSource(storedRequest, source); String sourceJson = writeJson(source); @@ -356,10 +350,9 @@ private DescriptorReadContext findExactSuccessfulDescriptor( LaunchDescriptor descriptor = launchDescriptorRepository .findBoundByRequest(workloadNamespace, canonicalTenantId, controlPlaneRequestId) - .orElseThrow( - () -> - new IllegalArgumentException( - "LAUNCH_DESCRIPTOR_NOT_FOUND: no descriptor exists for the exact request")); + .orElseThrow(() -> + new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_NOT_FOUND: no descriptor exists for the exact request")); if (!LaunchDescriptor.OUTCOME_SUCCESS.equals(descriptor.getOutcomeStatus())) { throw new IllegalArgumentException( "LAUNCH_DESCRIPTOR_CONFLICT: request outcome is not a successful descriptor"); @@ -389,10 +382,9 @@ private AuthoredWorldSourceEvidence readExactSource( request.canonicalTenantId(), request.worldSlug(), workloadNamespace) - .orElseThrow( - () -> - new IllegalArgumentException( - "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source evidence is missing")); + .orElseThrow(() -> + new IllegalArgumentException( + "AUTHORED_WORLD_SOURCE_NOT_FOUND: exact committed source evidence is missing")); requireExactSource(request, source); return source; } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java index ce68b6dc2a..0cefd5c195 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java @@ -218,13 +218,12 @@ private String canonicalBundleDigest(Map files) { files.entrySet().stream() .filter(entry -> !"signatures.json".equals(entry.getKey())) .sorted(Comparator.comparing(Map.Entry::getKey)) - .forEach( - entry -> { - digest.update(entry.getKey().getBytes(StandardCharsets.UTF_8)); - digest.update((byte) 0); - digest.update(entry.getValue()); - digest.update((byte) 0); - }); + .forEach(entry -> { + digest.update(entry.getKey().getBytes(StandardCharsets.UTF_8)); + digest.update((byte) 0); + digest.update(entry.getValue()); + digest.update((byte) 0); + }); byte[] hash = digest.digest(); StringBuilder builder = new StringBuilder(hash.length * 2); for (byte current : hash) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java index 7971bc5934..831d4f90b6 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java @@ -193,33 +193,31 @@ public List collectSelectedFullVersionParticipantDi var snapshot = selected; String snapshotFailureCode = failureCode; return FULL_VERSION_PARTICIPANTS.stream() - .map( - participant -> { - if (participant == PublishParticipantKey.WORLD_MANAGEMENT - || participant == PublishParticipantKey.GAME_DESIGN_CONTROL_PLANE) { - if (snapshot == null) { - return failedObservation( - participant, - canonicalBinding.versionId(), - null, - snapshotFailureCode, - "Exact selected publication source evidence unavailable"); - } - return participant == PublishParticipantKey.WORLD_MANAGEMENT - ? snapshot.worldManagementDigest() - : toParticipantDigest(participant, version, snapshot.gameDesignDigest()); - } - return observeFullVersionParticipant(version, canonicalBinding, participant, true); - }) + .map(participant -> { + if (participant == PublishParticipantKey.WORLD_MANAGEMENT + || participant == PublishParticipantKey.GAME_DESIGN_CONTROL_PLANE) { + if (snapshot == null) { + return failedObservation( + participant, + canonicalBinding.versionId(), + null, + snapshotFailureCode, + "Exact selected publication source evidence unavailable"); + } + return participant == PublishParticipantKey.WORLD_MANAGEMENT + ? snapshot.worldManagementDigest() + : toParticipantDigest(participant, version, snapshot.gameDesignDigest()); + } + return observeFullVersionParticipant(version, canonicalBinding, participant, true); + }) .toList(); } private List collectFullVersionParticipantDigests( VersionDto version, PublicationDigestRequestBinding binding, boolean selectedPublication) { return FULL_VERSION_PARTICIPANTS.stream() - .map( - participant -> - observeFullVersionParticipant(version, binding, participant, selectedPublication)) + .map(participant -> + observeFullVersionParticipant(version, binding, participant, selectedPublication)) .toList(); } @@ -333,43 +331,40 @@ private void assertParticipantEvidence( String expectedScope = version.scriptOnly() ? version.scriptPatchVersion() : String.valueOf(version.id()); Long expectedBaseVersionId = version.scriptOnly() ? version.baseVersionId() : null; - participantDigests.forEach( - digest -> { - if (!expectedScope.equals(digest.scopeValue()) - || !Objects.equals(expectedBaseVersionId, digest.baseVersionId())) { - throw new PublishGateFailureException( - PublishGateFailureCode.PARTICIPANT_SCOPE_MISMATCH, - "publish gate failed: wrong scope from " + digest.participantKey()); - } - String participantKey = digest.participantKey(); - Integer supportedSchemaVersion; - if (selectedAttestationSchema != null) { - supportedSchemaVersion = - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - participantKey, selectedAttestationSchema); - } else { - supportedSchemaVersion = - participantKey == null - ? null - : SUPPORTED_DIGEST_SCHEMA_VERSIONS.get(participantKey); - } - if (digest.digestSchemaVersion() == null - || !digest.digestSchemaVersion().equals(supportedSchemaVersion)) { - throw new PublishGateFailureException( - PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA, - "publish gate failed: unsupported digest schema from " + digest.participantKey()); - } - if (digest.contentDigest() == null || digest.contentDigest().isBlank()) { - throw new PublishGateFailureException( - PublishGateFailureCode.MISSING_CONTENT_DIGEST, - "publish gate failed: missing content digest from " + digest.participantKey()); - } - if (digest.appliedCommitId() == null || digest.appliedCommitId().isBlank()) { - throw new PublishGateFailureException( - PublishGateFailureCode.MISSING_APPLIED_COMMIT, - "publish gate failed: missing applied commit from " + digest.participantKey()); - } - }); + participantDigests.forEach(digest -> { + if (!expectedScope.equals(digest.scopeValue()) + || !Objects.equals(expectedBaseVersionId, digest.baseVersionId())) { + throw new PublishGateFailureException( + PublishGateFailureCode.PARTICIPANT_SCOPE_MISMATCH, + "publish gate failed: wrong scope from " + digest.participantKey()); + } + String participantKey = digest.participantKey(); + Integer supportedSchemaVersion; + if (selectedAttestationSchema != null) { + supportedSchemaVersion = + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participantKey, selectedAttestationSchema); + } else { + supportedSchemaVersion = + participantKey == null ? null : SUPPORTED_DIGEST_SCHEMA_VERSIONS.get(participantKey); + } + if (digest.digestSchemaVersion() == null + || !digest.digestSchemaVersion().equals(supportedSchemaVersion)) { + throw new PublishGateFailureException( + PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA, + "publish gate failed: unsupported digest schema from " + digest.participantKey()); + } + if (digest.contentDigest() == null || digest.contentDigest().isBlank()) { + throw new PublishGateFailureException( + PublishGateFailureCode.MISSING_CONTENT_DIGEST, + "publish gate failed: missing content digest from " + digest.participantKey()); + } + if (digest.appliedCommitId() == null || digest.appliedCommitId().isBlank()) { + throw new PublishGateFailureException( + PublishGateFailureCode.MISSING_APPLIED_COMMIT, + "publish gate failed: missing applied commit from " + digest.participantKey()); + } + }); long distinctAppliedCommitIds = participantDigests.stream() .map(PublishParticipantDigestDto::appliedCommitId) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java index cf00f2ea3e..6bb70edb02 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java @@ -116,10 +116,8 @@ private PublishedReleaseBundleDto createBundle( var identitySource = versionRepository .findByTenantIdAndId(version.tenantId(), version.id()) - .orElseThrow( - () -> - new IllegalStateException( - "published release canonical identity source missing")); + .orElseThrow(() -> + new IllegalStateException("published release canonical identity source missing")); UUID canonicalTenantId = identitySource.getCanonicalTenantId(); UUID canonicalVersionId = identitySource.getCanonicalVersionId(); if (!version.id().equals(identitySource.getId()) diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImpl.java index 09c679403b..8a199c52de 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImpl.java @@ -28,17 +28,16 @@ public void assertMatchesRecordedDigests( String tenantId, PublishType publishType, List participantDigests) { - participantDigests.forEach( - digest -> - repository - .findByTenantIdAndPublishTypeAndParticipantKeyAndAppliedCommitId( - tenantId, - publishType, - PublishParticipantKey.valueOf(digest.participantKey()), - digest.baseVersionId(), - digest.scopeValue(), - digest.appliedCommitId()) - .ifPresent(recorded -> assertMatchesRecordedDigest(recorded, digest))); + participantDigests.forEach(digest -> + repository + .findByTenantIdAndPublishTypeAndParticipantKeyAndAppliedCommitId( + tenantId, + publishType, + PublishParticipantKey.valueOf(digest.participantKey()), + digest.baseVersionId(), + digest.scopeValue(), + digest.appliedCommitId()) + .ifPresent(recorded -> assertMatchesRecordedDigest(recorded, digest))); } @Override @@ -49,36 +48,34 @@ public void recordVerifiedDigests( String publishWorkflowId, List participantDigests) { LocalDateTime now = LocalDateTime.now(); - participantDigests.forEach( - digest -> { - PublishParticipantKey participantKey = - PublishParticipantKey.valueOf(digest.participantKey()); - RecordedParticipantDigest recorded = - repository - .findByTenantIdAndPublishTypeAndParticipantKeyAndAppliedCommitId( - tenantId, - publishType, - participantKey, - digest.baseVersionId(), - digest.scopeValue(), - digest.appliedCommitId()) - .orElseGet(RecordedParticipantDigest::new); - recorded.setTenantId(tenantId); - recorded.setPublishType(publishType); - recorded.setParticipantKey(participantKey); - recorded.setScopeValue(digest.scopeValue()); - recorded.setBaseVersionId(digest.baseVersionId()); - recorded.setAppliedCommitId(digest.appliedCommitId()); - recorded.setContentDigest(digest.contentDigest()); - recorded.setDigestSchemaVersion(digest.digestSchemaVersion()); - if (recorded.getRecordedFromPublishWorkflowId() == null) { - recorded.setRecordedFromPublishWorkflowId(publishWorkflowId); - recorded.setRecordedAt(now); - } - recorded.setLastVerifiedPublishWorkflowId(publishWorkflowId); - recorded.setLastVerifiedAt(now); - repository.save(recorded); - }); + participantDigests.forEach(digest -> { + PublishParticipantKey participantKey = PublishParticipantKey.valueOf(digest.participantKey()); + RecordedParticipantDigest recorded = + repository + .findByTenantIdAndPublishTypeAndParticipantKeyAndAppliedCommitId( + tenantId, + publishType, + participantKey, + digest.baseVersionId(), + digest.scopeValue(), + digest.appliedCommitId()) + .orElseGet(RecordedParticipantDigest::new); + recorded.setTenantId(tenantId); + recorded.setPublishType(publishType); + recorded.setParticipantKey(participantKey); + recorded.setScopeValue(digest.scopeValue()); + recorded.setBaseVersionId(digest.baseVersionId()); + recorded.setAppliedCommitId(digest.appliedCommitId()); + recorded.setContentDigest(digest.contentDigest()); + recorded.setDigestSchemaVersion(digest.digestSchemaVersion()); + if (recorded.getRecordedFromPublishWorkflowId() == null) { + recorded.setRecordedFromPublishWorkflowId(publishWorkflowId); + recorded.setRecordedAt(now); + } + recorded.setLastVerifiedPublishWorkflowId(publishWorkflowId); + recorded.setLastVerifiedAt(now); + repository.save(recorded); + }); } private void assertMatchesRecordedDigest( diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemplateRemapSetServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemplateRemapSetServiceImpl.java index ca32e3784f..ae064d38c7 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemplateRemapSetServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemplateRemapSetServiceImpl.java @@ -151,13 +151,12 @@ private TemplateRemapSetDto toDto(VersionTemplateRemapSet remapSet) { remapSet.getCreatedAt(), remapSet.getApprovedAt(), remapSet.getRemapEntries().stream() - .map( - entry -> - new TemplateRemapEntryDto( - entry.getMappingDomain(), - entry.getMappingType(), - entry.getSourceTemplateKey(), - entry.getTargetTemplateKey())) + .map(entry -> + new TemplateRemapEntryDto( + entry.getMappingDomain(), + entry.getMappingType(), + entry.getSourceTemplateKey(), + entry.getTargetTemplateKey())) .toList()); } diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java index 380af58610..ad44a341de 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java @@ -516,16 +516,15 @@ private VersionAssetArtifact requireArtifact(String tenantId, long versionId) { private VersionAssetArtifact findOrCreate(String tenantId, long versionId) { return repository .findByTenantIdAndVersionId(tenantId, versionId) - .orElseGet( - () -> { - VersionAssetArtifact created = new VersionAssetArtifact(); - created.setTenantId(tenantId); - created.setVersionId(versionId); - created.setExportedVersionNumber(0); - created.setArtifactState(VersionAssetArtifactState.STAGED); - created.setStateEpoch(0); - return created; - }); + .orElseGet(() -> { + VersionAssetArtifact created = new VersionAssetArtifact(); + created.setTenantId(tenantId); + created.setVersionId(versionId); + created.setExportedVersionNumber(0); + created.setArtifactState(VersionAssetArtifactState.STAGED); + created.setStateEpoch(0); + return created; + }); } private void requireEpoch(VersionAssetArtifact artifact, long expectedStateEpoch) { diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java index fe5dfbb52d..276819f883 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java @@ -104,18 +104,16 @@ public VersionPublishCommandServiceImpl( /** Internal plumbing only: a durable selection does not establish creator authorization. */ PublishWorkflowRequest reserveSelection(PublishIntent intent) { try { - return publishAttemptService.executeFullVersionTransaction( - () -> { - AuthoredDraftPublishSelection selection = - authoredSelections.reserve(intent).selection(); - return new PublishWorkflowRequest( - selection.target().gameDesignVersionTenantKey(), - intent.notes(), - intent.publishRequestId(), - TemporalVersionPublishOrchestrator.workflowId( - intent.canonicalTenantId().toString(), intent.publishRequestId()), - selection.intent()); - }); + return publishAttemptService.executeFullVersionTransaction(() -> { + AuthoredDraftPublishSelection selection = authoredSelections.reserve(intent).selection(); + return new PublishWorkflowRequest( + selection.target().gameDesignVersionTenantKey(), + intent.notes(), + intent.publishRequestId(), + TemporalVersionPublishOrchestrator.workflowId( + intent.canonicalTenantId().toString(), intent.publishRequestId()), + selection.intent()); + }); } catch (PublishAttemptService.FullVersionTransactionException exception) { throw exception.causeException(); } @@ -593,47 +591,45 @@ private PublishWorkflowSnapshot replaySucceededAttempt( private void recordVerifiedAndSucceed( PublishWorkflowRequest request, PublishedReleaseBundleDto bundle) { try { - publishAttemptService.executeFullVersionTransaction( - () -> { - if (gameRepository.findByTenantIdForUpdate(request.tenantId()) == null) { - throw new IllegalArgumentException("game not found"); - } - PublishAttempt current = - publishAttemptRepository - .findByPublishWorkflowIdForUpdate(request.publishWorkflowId()) - .orElseThrow( - () -> new PendingReconciliationException("publish attempt not found")); - validateFullVersionAttempt(current, request); - if (current.getStatus() != PublishAttemptStatus.PENDING - && current.getStatus() != PublishAttemptStatus.SUCCEEDED) { - throw pendingReconciliation("full-version attempt is no longer pending"); - } - if (current.getStatus() == PublishAttemptStatus.PENDING) { - publishAttemptRepository.requirePublicationPending(current); - } else { - publishAttemptRepository.requirePublishedOperation(current); - } - requireAttemptVersionForUpdate(current, request); - PublicationReadback currentReadback = readPublication(request, current); - if (!currentReadback.isComplete()) { - throw pendingReconciliation( - "published release evidence is incomplete; readback/reconciliation is required"); - } - if (!Objects.equals(bundle, currentReadback.bundle())) { - throw pendingReconciliation("published release bundle changed during reconciliation"); - } - assertCommittedBundleEvidence(request, currentReadback); - recordedParticipantDigestService.recordVerifiedDigests( - request.tenantId(), - PublishType.FULL_VERSION, - request.publishWorkflowId(), - currentReadback.bundle().participantDigests()); - if (current.getStatus() == PublishAttemptStatus.PENDING) { - publishAttemptService.markFullVersionSucceeded(request.publishWorkflowId()); - publishAttemptRepository.sealPublication(current, true); - } - return null; - }); + publishAttemptService.executeFullVersionTransaction(() -> { + if (gameRepository.findByTenantIdForUpdate(request.tenantId()) == null) { + throw new IllegalArgumentException("game not found"); + } + PublishAttempt current = + publishAttemptRepository + .findByPublishWorkflowIdForUpdate(request.publishWorkflowId()) + .orElseThrow(() -> new PendingReconciliationException("publish attempt not found")); + validateFullVersionAttempt(current, request); + if (current.getStatus() != PublishAttemptStatus.PENDING + && current.getStatus() != PublishAttemptStatus.SUCCEEDED) { + throw pendingReconciliation("full-version attempt is no longer pending"); + } + if (current.getStatus() == PublishAttemptStatus.PENDING) { + publishAttemptRepository.requirePublicationPending(current); + } else { + publishAttemptRepository.requirePublishedOperation(current); + } + requireAttemptVersionForUpdate(current, request); + PublicationReadback currentReadback = readPublication(request, current); + if (!currentReadback.isComplete()) { + throw pendingReconciliation( + "published release evidence is incomplete; readback/reconciliation is required"); + } + if (!Objects.equals(bundle, currentReadback.bundle())) { + throw pendingReconciliation("published release bundle changed during reconciliation"); + } + assertCommittedBundleEvidence(request, currentReadback); + recordedParticipantDigestService.recordVerifiedDigests( + request.tenantId(), + PublishType.FULL_VERSION, + request.publishWorkflowId(), + currentReadback.bundle().participantDigests()); + if (current.getStatus() == PublishAttemptStatus.PENDING) { + publishAttemptService.markFullVersionSucceeded(request.publishWorkflowId()); + publishAttemptRepository.sealPublication(current, true); + } + return null; + }); } catch (PublishAttemptService.FullVersionTransactionException ex) { throw pendingReconciliation( "committed publication readback could not be reconciled", ex.causeException()); @@ -691,35 +687,33 @@ private PublishWorkflowSnapshot failDefinitively( String failureCode = publishFailureCode(failure); String failureMessage = publishFailureMessage(failure); try { - publishAttemptService.executeFullVersionTransaction( - () -> { - if (gameRepository.findByTenantIdForUpdate(request.tenantId()) == null) { - throw new IllegalArgumentException("game not found"); - } - PublishAttempt current = - publishAttemptRepository - .findByPublishWorkflowIdForUpdate(request.publishWorkflowId()) - .orElseThrow( - () -> new PendingReconciliationException("publish attempt not found")); - validateFullVersionAttempt(current, request); - if (current.getStatus() != PublishAttemptStatus.PENDING) { - throw pendingReconciliation("full-version attempt is no longer pending"); - } - publishAttemptRepository.requirePublicationPending(current); - requireAttemptVersionForUpdate(current, request); - PublicationReadback readback = readPublication(request, current); - if (!readback.isAbsent()) { - if (!readback.isStagedNoRelease() || readback.candidate() != null) { - throw pendingReconciliation( - "publication failure has committed or partial release evidence; reconciliation is required"); - } - } - publishAttemptService.markFullVersionFailed( - request.publishWorkflowId(), failureCode, failureMessage); - publishAttemptRepository.sealPublication(current, false); - // Approved launch remap sets may reference this failed candidate, so retain the row. - return Boolean.TRUE; - }); + publishAttemptService.executeFullVersionTransaction(() -> { + if (gameRepository.findByTenantIdForUpdate(request.tenantId()) == null) { + throw new IllegalArgumentException("game not found"); + } + PublishAttempt current = + publishAttemptRepository + .findByPublishWorkflowIdForUpdate(request.publishWorkflowId()) + .orElseThrow(() -> new PendingReconciliationException("publish attempt not found")); + validateFullVersionAttempt(current, request); + if (current.getStatus() != PublishAttemptStatus.PENDING) { + throw pendingReconciliation("full-version attempt is no longer pending"); + } + publishAttemptRepository.requirePublicationPending(current); + requireAttemptVersionForUpdate(current, request); + PublicationReadback readback = readPublication(request, current); + if (!readback.isAbsent()) { + if (!readback.isStagedNoRelease() || readback.candidate() != null) { + throw pendingReconciliation( + "publication failure has committed or partial release evidence; reconciliation is required"); + } + } + publishAttemptService.markFullVersionFailed( + request.publishWorkflowId(), failureCode, failureMessage); + publishAttemptRepository.sealPublication(current, false); + // Approved launch remap sets may reference this failed candidate, so retain the row. + return Boolean.TRUE; + }); } catch (PublishAttemptService.FullVersionTransactionException ex) { PublicationReadback winningPublication; try { @@ -1128,10 +1122,9 @@ private AuthoredDraftPublishSelection requireSelectedIntent(PublishWorkflowReque AuthoredDraftPublishSelection selection = authoredSelections .readByPublishRequest(request.intent().canonicalTenantId(), request.publishRequestId()) - .orElseThrow( - () -> - new IllegalStateException( - "PUBLISH_SELECTION_REQUIRED: exact durable selection is absent")) + .orElseThrow(() -> + new IllegalStateException( + "PUBLISH_SELECTION_REQUIRED: exact durable selection is absent")) .selection(); if (!selection.intent().equals(request.intent()) || !selection.target().gameDesignVersionTenantKey().equals(request.tenantId()) @@ -1168,14 +1161,13 @@ private void assertSelectedCommit( AuthoredDraftPublishSelection selection = requireSelectedIntent(request); if (digests == null || digests.stream() - .anyMatch( - digest -> - digest == null - || !selection - .selectedCommit() - .commitId() - .toString() - .equals(digest.appliedCommitId()))) { + .anyMatch(digest -> + digest == null + || !selection + .selectedCommit() + .commitId() + .toString() + .equals(digest.appliedCommitId()))) { throw new PublishGateFailureException( PublishGateFailureCode.APPLIED_COMMIT_MISMATCH, "Every participant must report the exact selected authored Draft commit"); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java index 3080772d3a..1cdec44a85 100644 --- a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionServiceImpl.java @@ -162,10 +162,8 @@ public VersionDto publishScriptPatchVersion( ScriptPatchReservation reservation; try { reservation = - publishAttemptService.executeScriptPatchTransaction( - () -> - reserveScriptPatch( - patchBinding, tenantId, baseVersionId, scriptPatchVersion, notes)); + publishAttemptService.executeScriptPatchTransaction(() -> + reserveScriptPatch(patchBinding, tenantId, baseVersionId, scriptPatchVersion, notes)); } catch (PublishAttemptService.ScriptPatchTransactionException ex) { throw ex.causeException(); } @@ -363,10 +361,9 @@ private ScriptPatchFinalization failScriptPatch( Version draft = versionRepository .findByTenantIdAndIdForUpdate(patchBinding.tenantId(), attempt.getVersionId()) - .orElseThrow( - () -> - new IllegalStateException( - "PUBLISH_ATTEMPT_INCONSISTENT: pending attempt references a missing version")); + .orElseThrow(() -> + new IllegalStateException( + "PUBLISH_ATTEMPT_INCONSISTENT: pending attempt references a missing version")); if (draft.getVersionState() != VersionLifecycleState.DRAFT) { throw new IllegalStateException( "PUBLISH_ATTEMPT_INCONSISTENT: pending attempt references a non-draft version"); @@ -419,10 +416,9 @@ private Version requireAttemptVersion( Version version = versionRepository .findByTenantIdAndId(patchBinding.tenantId(), attempt.getVersionId()) - .orElseThrow( - () -> - new IllegalStateException( - "PUBLISH_ATTEMPT_INCOMPLETE: referenced version is not available")); + .orElseThrow(() -> + new IllegalStateException( + "PUBLISH_ATTEMPT_INCOMPLETE: referenced version is not available")); if (!Objects.equals(version.getTenantId(), patchBinding.tenantId()) || version.getVersionNumber() != attempt.getVersionNumber() || !version.isScriptOnly() @@ -651,11 +647,10 @@ public PublishedPluginVersionDto getPublishedPluginVersion( requireText(pluginVersionId, "pluginVersionId"); return publishedPluginVersionRepository .findByTenantIdAndPluginIdAndPluginVersionId(tenantId, pluginId, pluginVersionId) - .filter( - entity -> - entity.getPublicationState() == VersionLifecycleState.PUBLISHED - || entity.getPublicationState() == VersionLifecycleState.SUPERSEDED - || entity.getPublicationState() == VersionLifecycleState.REVOKED_DESIGN) + .filter(entity -> + entity.getPublicationState() == VersionLifecycleState.PUBLISHED + || entity.getPublicationState() == VersionLifecycleState.SUPERSEDED + || entity.getPublicationState() == VersionLifecycleState.REVOKED_DESIGN) .map(this::toPublishedPluginVersionDto) .orElseThrow(() -> new IllegalArgumentException("NOT_FOUND: plugin version not found")); } @@ -815,11 +810,10 @@ public VersionStateDto compareAndSetVersionState( if (version.getVersionState() == newState) { return toVersionStateDto(version); } - return CreatorMutationOwnerProofGuard.denyUntilAccountCommitBoundProof( - () -> - new MutationOwnerProofUnavailableException( - "VERSION_STATE_MUTATION_UNAVAILABLE", - "Canonical lifecycle transition and owner proof are unavailable")); + return CreatorMutationOwnerProofGuard.denyUntilAccountCommitBoundProof(() -> + new MutationOwnerProofUnavailableException( + "VERSION_STATE_MUTATION_UNAVAILABLE", + "Canonical lifecycle transition and owner proof are unavailable")); } private int calculateNextNumber(String tenantId) { @@ -943,16 +937,14 @@ private void requireRequestedUploadMatchesStoredBundle( private String requiredAutomationAbilitySchemaDigest(PublishedReleaseBundleDto bundle) { return bundle.participantDigests().stream() - .filter( - digest -> - PublishParticipantKey.AUTOMATION_SCRIPTING.name().equals(digest.participantKey())) + .filter(digest -> + PublishParticipantKey.AUTOMATION_SCRIPTING.name().equals(digest.participantKey())) .map(PublishParticipantDigestDto::contentDigest) .filter(digest -> digest != null && !digest.isBlank()) .findFirst() - .orElseThrow( - () -> - new IllegalArgumentException( - "INVALID_ARGUMENT: published release bundle is missing the Automation ability-schema digest")); + .orElseThrow(() -> + new IllegalArgumentException( + "INVALID_ARGUMENT: published release bundle is missing the Automation ability-schema digest")); } private void markValidationFailed(PublishedPluginVersion entity, String statusReason) { diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationSupport.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationSupport.java index dfd63e52e0..d59397afd0 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationSupport.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationSupport.java @@ -294,16 +294,15 @@ protected byte[] readPublishedReleaseBundleBytes() { protected void writeVersionStateEpoch( TransactionTemplate transaction, String tenantId, Long versionId, long epoch) { - transaction.executeWithoutResult( - status -> { - int updated = - dsl.execute( - "update version set version_state_epoch = ? where tenant_id = ? and id = ?", - epoch, - tenantId, - versionId); - assertThat(updated).isOne(); - }); + transaction.executeWithoutResult(status -> { + int updated = + dsl.execute( + "update version set version_state_epoch = ? where tenant_id = ? and id = ?", + epoch, + tenantId, + versionId); + assertThat(updated).isOne(); + }); } protected Fixture prepareFixture(Path testDirectory) throws Exception { @@ -524,10 +523,9 @@ protected Fixture prepareFixture(Path testDirectory, boolean prepareExistingOwne flyway.migrate(); if (prepareExistingOwner) { new TransactionTemplate(transactionManager) - .executeWithoutResult( - status -> - creationRepository.createCandidate( - NAMESPACE, operationId, "1", "Demo Game", "Seed game")); + .executeWithoutResult(status -> + creationRepository.createCandidate( + NAMESPACE, operationId, "1", "Demo Game", "Seed game")); ReflectionTestUtils.setField(seeder, "initialAdmissionFixtureEnabled", false); seeder.run(new DefaultApplicationArguments(new String[] {})); } diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java index f564110d45..d4db5a33fc 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/draft/IsolatedPublicationOwnerSetup.java @@ -241,15 +241,14 @@ private static GameDesignPublicationOperation retain( coordinator.claimApplicationSlot(draft); var epochs = draft.affectedUnits().stream() - .map( - unit -> - new DraftCommitCoordinatorRepository.AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .map(unit -> + new DraftCommitCoordinatorRepository.AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) .toList(); var outcome = new DraftCommitCoordinatorRepository.OwnerOutcome( diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java index 7d7a91f3ee..0307f7d644 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/publication/IsolatedPublicationOperationFixtures.java @@ -68,21 +68,20 @@ private static GameDesignPublicationOperation fresh( originalDraftAccount.inputDigest()); var appliedEpochs = draft.affectedUnits().stream() - .map( - unit -> - Map.of( - "aggregateType", - unit.aggregateType(), - "aggregateId", - unit.aggregateId(), - "scopeType", - unit.scopeType(), - "scopeId", - unit.scopeId(), - "expectedEpoch", - unit.expectedEpoch(), - "resultingEpoch", - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .map(unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) .toList(); String vector = new String( @@ -172,32 +171,31 @@ private static GameDesignPublicationOperation selection( new AccountPublicationAuthorizationBinding.PreallocationInput( originalDraftAccount.actorAccountId(), selected), java.util.Arrays.stream(DraftAuthorizationFenceBinding.SourceKind.values()) - .flatMap( - kind -> { - if (kind == DraftAuthorizationFenceBinding.SourceKind.RECENT_REAUTH_POLICY) { - return java.util.stream.Stream.of( - recentReauthenticationPolicyEvidence("PLATFORM", 300L, 30L), - recentReauthenticationPolicyEvidence("DEPLOYMENT", 240L, 30L)); - } - return java.util.stream.Stream.of( - new DraftAuthorizationFenceBinding.SourceEvidence( - kind, - switch (kind) { - case ACCOUNT, GLOBAL_ROLES -> - originalDraftAccount.actorAccountId().toString(); - case TENANT -> target.canonicalTenantId().toString(); - case MEMBERSHIP -> - originalDraftAccount.actorAccountId() - + "/" - + target.canonicalTenantId(); - default -> "ISOLATED-" + kind; - }, - "1", - "1", - null, - null, - ("ISOLATED-stipulated-" + kind).getBytes(StandardCharsets.UTF_8))); - }) + .flatMap(kind -> { + if (kind == DraftAuthorizationFenceBinding.SourceKind.RECENT_REAUTH_POLICY) { + return java.util.stream.Stream.of( + recentReauthenticationPolicyEvidence("PLATFORM", 300L, 30L), + recentReauthenticationPolicyEvidence("DEPLOYMENT", 240L, 30L)); + } + return java.util.stream.Stream.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + kind, + switch (kind) { + case ACCOUNT, GLOBAL_ROLES -> + originalDraftAccount.actorAccountId().toString(); + case TENANT -> target.canonicalTenantId().toString(); + case MEMBERSHIP -> + originalDraftAccount.actorAccountId() + + "/" + + target.canonicalTenantId(); + default -> "ISOLATED-" + kind; + }, + "1", + "1", + null, + null, + ("ISOLATED-stipulated-" + kind).getBytes(StandardCharsets.UTF_8))); + }) .toList()); var world = new WorldPublishedStartLocationEvidence( diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java index e6326497ff..da4a3d0c0a 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/service/impl/PublishedWorldSelectorFixtures.java @@ -133,21 +133,20 @@ public static WorldPublishedStartLocationEvidence evidence( .AuthoredWorldReleaseAttestationEvidence .requiredParticipantOrder() .stream() - .map( - owner -> - new net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto( - owner, - Long.toString(versionId), - null, - evidence.request().appliedCommitId(), - "WORLD_MANAGEMENT".equals(owner) - ? evidence.request().contentDigest() - : "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, attestationSchemaVersion), - "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, - null, - null)) + .map(owner -> + new net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto( + owner, + Long.toString(versionId), + null, + evidence.request().appliedCommitId(), + "WORLD_MANAGEMENT".equals(owner) + ? evidence.request().contentDigest() + : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, attestationSchemaVersion), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, + null, + null)) .toList(); } @@ -173,15 +172,14 @@ private WorldPublishedStartLocationEvidence build( .thenComparing(AffectedUnit::scopeType) .thenComparing(AffectedUnit::scopeId) .thenComparing(AffectedUnit::expectedEpoch)) - .map( - u -> - new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( - u.owner().name(), - u.aggregateType(), - u.aggregateId(), - u.scopeType(), - u.scopeId(), - u.expectedEpoch())) + .map(u -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + u.owner().name(), + u.aggregateType(), + u.aggregateId(), + u.scopeType(), + u.scopeId(), + u.expectedEpoch())) .toList(); var request = new WorldPublishedStartLocationEvidence.Request( @@ -284,23 +282,22 @@ private DraftAuthorizationFenceBinding.OwnerReadback committedReadback( result.put( "appliedEpochs", draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - Map.of( - "aggregateType", - unit.aggregateType(), - "aggregateId", - unit.aggregateId(), - "scopeType", - unit.scopeType(), - "scopeId", - unit.scopeId(), - "expectedEpoch", - unit.expectedEpoch(), - "resultingEpoch", - new java.math.BigInteger(unit.expectedEpoch()) - .add(java.math.BigInteger.ONE) - .toString())) + .map(unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new java.math.BigInteger(unit.expectedEpoch()) + .add(java.math.BigInteger.ONE) + .toString())) .toList()); return new DraftAuthorizationFenceBinding.OwnerReadback( Owner.WORLD, diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java index 17025e58cd..a0729f7f09 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/account/GenuineGameDesignWorldSourceCommitPostgresIntegrationTest.java @@ -248,15 +248,14 @@ private void compose(Failure failure) throws Exception { var source = Objects.requireNonNull( transaction(gd.store()) - .execute( - ignored -> - sourceRepository.register( - NAMESPACE, - UUID.randomUUID(), - gd.target().canonicalTenantId(), - "genuine-tenant", - "genuine-world", - "Genuine authored World"))); + .execute(ignored -> + sourceRepository.register( + NAMESPACE, + UUID.randomUUID(), + gd.target().canonicalTenantId(), + "genuine-tenant", + "genuine-world", + "Genuine authored World"))); var intakes = new WorldAuthoredSourceIntakeRepository(world.dsl()); var identities = new WorldAuthoredVersionIdentityRepository(world.dsl()); try (var sourceClient = @@ -363,18 +362,16 @@ public void sendMessage(RespT message) { // This controlled review retains exact current policy/command/asset genesis owner evidence; // it proves source lineage only, not reviewer identity or Account authorization. transaction(gd.store()) - .execute( - ignored -> { - var reviewedBase = - reviewedBaseOwner.resolve( - gd.target(), DraftBaseReference.parse(binding.baseCommitId())); - draftSources.claimReviewed(binding, reviewedBase); - var retained = reviewedBaseOwner.requireCurrentRetained(binding); - assertThat(retained.canonicalBytes()) - .containsExactly(reviewedBase.canonicalBytes()); - assertThat(retained.digest()).isEqualTo(reviewedBase.digest()); - return null; - }); + .execute(ignored -> { + var reviewedBase = + reviewedBaseOwner.resolve( + gd.target(), DraftBaseReference.parse(binding.baseCommitId())); + draftSources.claimReviewed(binding, reviewedBase); + var retained = reviewedBaseOwner.requireCurrentRetained(binding); + assertThat(retained.canonicalBytes()).containsExactly(reviewedBase.canonicalBytes()); + assertThat(retained.digest()).isEqualTo(reviewedBase.digest()); + return null; + }); var request = account.prepareOriginalDraftOrder(binding, NAMESPACE); var original = request.original(); register( @@ -432,11 +429,10 @@ public void sendMessage(RespT message) { assertThatThrownBy( () -> composer.commit(original, "invalid-test-only-creator-credential")) .isInstanceOf(io.grpc.StatusRuntimeException.class); - assertThatThrownBy( - () -> - heldClient.read( - DraftCommitOrderReadEvidence.Request.create( - NAMESPACE, original.canonicalBytes()))) + assertThatThrownBy(() -> + heldClient.read( + DraftCommitOrderReadEvidence.Request.create( + NAMESPACE, original.canonicalBytes()))) .isInstanceOf(io.grpc.StatusRuntimeException.class); assertThat(coordinator.readApplicationSlot(gd.target())).isPresent(); assertThat(coordinator.readVisibilityFence(gd.target())).isEmpty(); @@ -447,9 +443,8 @@ public void sendMessage(RespT message) { .isZero(); var refused = coordinator.read(gd.target(), binding.requestId()).orElseThrow(); assertThat(refused.ownerStates().values()) - .allMatch( - owner -> - owner.status() == DraftCommitCoordinatorRepository.OwnerStatus.NOT_ATTEMPTED); + .allMatch(owner -> + owner.status() == DraftCommitCoordinatorRepository.OwnerStatus.NOT_ATTEMPTED); } else if (failure != Failure.NONE) { assertThatThrownBy(() -> composer.commit(original, request.originalCreatorCredential())) .isInstanceOf(io.grpc.StatusRuntimeException.class); @@ -578,15 +573,14 @@ public void sendMessage(RespT message) { assertThat(worldOwner.appliedEpochs()) .isEqualTo( actualWorld.appliedEpochs().stream() - .map( - epoch -> - new DraftCommitCoordinatorRepository.AppliedEpoch( - epoch.aggregateType(), - epoch.aggregateId(), - epoch.scopeType(), - epoch.scopeId(), - epoch.expectedEpoch(), - epoch.resultingEpoch())) + .map(epoch -> + new DraftCommitCoordinatorRepository.AppliedEpoch( + epoch.aggregateType(), + epoch.aggregateId(), + epoch.scopeType(), + epoch.scopeId(), + epoch.expectedEpoch(), + epoch.resultingEpoch())) .toList()); } } finally { diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java index d050148d04..0d3775c9b9 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GenuineSelectedGameLogicIntakePostgresIntegrationTest.java @@ -247,18 +247,16 @@ void controlledCreatorAndWorldFixturesDriveActualOwnersThroughExactIntakeAndRece var binding = binding(local, "genuine-admission"); var reviewedBaseOwner = new GameDesignReviewedBaseRepository(local.dsl()); transaction(local) - .execute( - ignored -> { - var reviewedBase = - reviewedBaseOwner.resolve( - local.target(), DraftBaseReference.parse(binding.baseCommitId())); - new GameDesignSourceRepository(local.dsl()).claimReviewed(binding, reviewedBase); - var retained = reviewedBaseOwner.requireCurrentRetained(binding); - assertThat(retained.canonicalBytes()) - .containsExactly(reviewedBase.canonicalBytes()); - assertThat(retained.digest()).isEqualTo(reviewedBase.digest()); - return null; - }); + .execute(ignored -> { + var reviewedBase = + reviewedBaseOwner.resolve( + local.target(), DraftBaseReference.parse(binding.baseCommitId())); + new GameDesignSourceRepository(local.dsl()).claimReviewed(binding, reviewedBase); + var retained = reviewedBaseOwner.requireCurrentRetained(binding); + assertThat(retained.canonicalBytes()).containsExactly(reviewedBase.canonicalBytes()); + assertThat(retained.digest()).isEqualTo(reviewedBase.digest()); + return null; + }); var originalRequest = account.prepareOriginalDraftOrder(binding, NAMESPACE); var original = originalRequest.original(); var credential = originalRequest.originalCreatorCredential(); @@ -608,21 +606,20 @@ private AuthoredDraftPublishSelection reserveSelection( Local local, DraftAuthorizationFenceBinding original) { var tx = transaction(local); var selected = new GameDesignDraftTerminalOperation(original).gameDesignBinding(); - return tx.execute( - ignored -> - new AuthoredDraftPublishSelectionRepository( - local.dsl(), new DraftCommitCoordinatorRepository(local.dsl())) - .reserve( - new AuthoredDraftPublishSelection.PublishIntent( - local.target().canonicalTenantId(), - local.target().canonicalVersionId(), - UUID.randomUUID().toString(), - "1", - "controlled owner source receipt proof", - selected.requestId(), - selected.commitId(), - selected.digest())) - .selection()); + return tx.execute(ignored -> + new AuthoredDraftPublishSelectionRepository( + local.dsl(), new DraftCommitCoordinatorRepository(local.dsl())) + .reserve( + new AuthoredDraftPublishSelection.PublishIntent( + local.target().canonicalTenantId(), + local.target().canonicalVersionId(), + UUID.randomUUID().toString(), + "1", + "controlled owner source receipt proof", + selected.requestId(), + selected.commitId(), + selected.digest())) + .selection()); } private static void assertSynchronizedSource( @@ -658,15 +655,14 @@ private void registerWorldSourceIdentity( NAMESPACE)); var source = transaction(local) - .execute( - ignored -> - gameSourceRepository.register( - NAMESPACE, - UUID.randomUUID(), - local.target().canonicalTenantId(), - "controlled-tenant", - "controlled-world", - "Controlled authored World source")); + .execute(ignored -> + gameSourceRepository.register( + NAMESPACE, + UUID.randomUUID(), + local.target().canonicalTenantId(), + "controlled-tenant", + "controlled-world", + "Controlled authored World source")); var intakes = new WorldAuthoredSourceIntakeRepository(world.dsl()); var identities = new WorldAuthoredVersionIdentityRepository(world.dsl()); try (var sourceClient = @@ -1041,10 +1037,9 @@ private static ServerInterceptor countingInterceptor(Map public ServerCall.Listener interceptCall( ServerCall call, Metadata headers, ServerCallHandler next) { String method = call.getMethodDescriptor().getFullMethodName().toLowerCase(Locale.ROOT); - methodCounts.forEach( - (fragment, count) -> { - if (method.contains(fragment)) count.incrementAndGet(); - }); + methodCounts.forEach((fragment, count) -> { + if (method.contains(fragment)) count.incrementAndGet(); + }); return next.startCall(call, headers); } }; diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index 21c96348e1..0afbe2b2f3 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -270,12 +270,11 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema commit.digest()); var selection = gds.write() - .execute( - ignored -> - new AuthoredDraftPublishSelectionRepository( - gds.dsl(), new DraftCommitCoordinatorRepository(gds.dsl())) - .reserve(intent) - .selection()); + .execute(ignored -> + new AuthoredDraftPublishSelectionRepository( + gds.dsl(), new DraftCommitCoordinatorRepository(gds.dsl())) + .reserve(intent) + .selection()); try (var accountFixture = new AccountControlUiOriginalOrderFixture( ACCOUNT_POSTGRES.getJdbcUrl(), @@ -405,12 +404,11 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema var glOwner = new GameLogicGameplayRuleIntakeRepository(gameLogic.dsl()); gameLogic .write() - .execute( - ignored -> { - glOwner.lockOperation(glAuthorization.operationId()); - glOwner.insertTerminal(glTerminal); - return null; - }); + .execute(ignored -> { + glOwner.lockOperation(glAuthorization.operationId()); + glOwner.insertTerminal(glTerminal); + return null; + }); var committedGlTerminal = glOwner.findTerminal(glAuthorization.operationId()).orElseThrow(); assertThat(committedGlTerminal.canonicalBytes()).containsExactly(glTerminal.canonicalBytes()); @@ -625,10 +623,9 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema assertThat(participantDigests) .filteredOn(digest -> "WORLD_MANAGEMENT".equals(digest.participantKey())) .singleElement() - .satisfies( - digest -> - assertThat(digest.contentDigest()) - .isEqualTo(worldOwners.selectedWorldDigest().contentDigest())); + .satisfies(digest -> + assertThat(digest.contentDigest()) + .isEqualTo(worldOwners.selectedWorldDigest().contentDigest())); assertThat(participantDigests) .filteredOn(digest -> "GAME_LOGIC".equals(digest.participantKey())) .singleElement() @@ -652,10 +649,9 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema validAutomation.errorMessage())); assertThatThrownBy(() -> gate.assertSelectedGatePassed(versionDto, altered)) .isInstanceOf(PublishGateFailureException.class) - .satisfies( - failure -> - assertThat(((PublishGateFailureException) failure).failureCode()) - .isEqualTo(PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA)); + .satisfies(failure -> + assertThat(((PublishGateFailureException) failure).failureCode()) + .isEqualTo(PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA)); var releaseService = new PublishedReleaseBundleServiceImpl( @@ -683,19 +679,17 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema gds.dsl()); var exportSnapshot = gds.write() - .execute( - ignored -> - assetPublication.freezeOrReadSnapshot( - versionDto.tenantId(), versionDto.versionNumber())); + .execute(ignored -> + assetPublication.freezeOrReadSnapshot( + versionDto.tenantId(), versionDto.versionNumber())); assertThat(exportSnapshot.items()).isEmpty(); gds.write() - .execute( - ignored -> - artifactService.stageExport( - versionDto.tenantId(), - versionDto.id(), - versionDto.versionNumber(), - publicationRequest.derivedWorkflowIdentity())); + .execute(ignored -> + artifactService.stageExport( + versionDto.tenantId(), + versionDto.id(), + versionDto.versionNumber(), + publicationRequest.derivedWorkflowIdentity())); var candidateService = new net.firedevops.firemud.gamedesign.service.impl .VersionAssetExportCandidateServiceImpl( @@ -720,18 +714,16 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema candidateService.readExportCandidate( versionDto.tenantId(), versionDto.versionNumber())) .isEqualTo(candidate); - assertThatThrownBy( - () -> - gds.write() - .execute( - ignored -> - releaseService.createFullVersionBundle( - versionDto, - publicationRequest.derivedWorkflowIdentity(), - controlledEmptyManifest, - "controlled-generation-input", - altered, - worldOwners.startLocationEvidence()))) + assertThatThrownBy(() -> + gds.write() + .execute(ignored -> + releaseService.createFullVersionBundle( + versionDto, + publicationRequest.derivedWorkflowIdentity(), + controlledEmptyManifest, + "controlled-generation-input", + altered, + worldOwners.startLocationEvidence()))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Selected-full release requires the exact 4/3/1/6/2"); assertThat( @@ -746,58 +738,54 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema PublishedReleaseBundleService releaseOwner = releaseService; var written = gds.write() - .execute( - ignored -> { - String workflow = publicationRequest.derivedWorkflowIdentity(); - var exported = - artifactService.markExportedUnattested( - versionDto.tenantId(), - versionDto.id(), - versionDto.versionNumber(), - workflow, - controlledEmptyManifest); - var result = - releaseOwner.createFullVersionBundle( - versionDto, - workflow, - controlledEmptyManifest, - "controlled-generation-input", - participantDigests, - worldOwners.startLocationEvidence()); - var version = - versions - .findByTenantIdAndIdForUpdate( - versionDto.tenantId(), versionDto.id()) - .orElseThrow(); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch( - Math.addExact(version.getVersionStateEpoch(), 1L)); - versions.save(version); - artifactService.markPublished( + .execute(ignored -> { + String workflow = publicationRequest.derivedWorkflowIdentity(); + var exported = + artifactService.markExportedUnattested( versionDto.tenantId(), versionDto.id(), - exported.stateEpoch(), + versionDto.versionNumber(), workflow, - controlledEmptyManifest.manifestHash()); - var attempts = - new net.firedevops.firemud.gamedesign.repository - .PublishAttemptRepository(gds.dsl()); - var attempt = - attempts.findByPublishWorkflowIdForUpdate(workflow).orElseThrow(); - attempt.setStatus( - net.firedevops.firemud.gamedesign.model.PublishAttemptStatus.SUCCEEDED); - attempts.save(attempt); - var operation = selectedOwnerReservation.operation(); - new net.firedevops.firemud.gamedesign.publication - .GameDesignPublicationOperationRepository(gds.dsl()) - .seal( - operation.tenantKey(), - workflow, - operation.versionId(), - operation.selectionDigest(), - true); - return result; - }); + controlledEmptyManifest); + var result = + releaseOwner.createFullVersionBundle( + versionDto, + workflow, + controlledEmptyManifest, + "controlled-generation-input", + participantDigests, + worldOwners.startLocationEvidence()); + var version = + versions + .findByTenantIdAndIdForUpdate(versionDto.tenantId(), versionDto.id()) + .orElseThrow(); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(Math.addExact(version.getVersionStateEpoch(), 1L)); + versions.save(version); + artifactService.markPublished( + versionDto.tenantId(), + versionDto.id(), + exported.stateEpoch(), + workflow, + controlledEmptyManifest.manifestHash()); + var attempts = + new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository( + gds.dsl()); + var attempt = attempts.findByPublishWorkflowIdForUpdate(workflow).orElseThrow(); + attempt.setStatus( + net.firedevops.firemud.gamedesign.model.PublishAttemptStatus.SUCCEEDED); + attempts.save(attempt); + var operation = selectedOwnerReservation.operation(); + new net.firedevops.firemud.gamedesign.publication + .GameDesignPublicationOperationRepository(gds.dsl()) + .seal( + operation.tenantKey(), + workflow, + operation.versionId(), + operation.selectionDigest(), + true); + return result; + }); assertThat(written.attestationSchemaVersion()).isEqualTo("v4"); assertThat(written.participantDigests()).containsExactlyElementsOf(participantDigests); assertThat(written.worldPublishedStartLocationEvidence().canonicalBytes()) @@ -817,15 +805,14 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema var replay = gds.write() - .execute( - ignored -> - releaseOwner.createFullVersionBundle( - versionDto, - publicationRequest.derivedWorkflowIdentity(), - controlledEmptyManifest, - "controlled-generation-input", - participantDigests, - worldOwners.startLocationEvidence())); + .execute(ignored -> + releaseOwner.createFullVersionBundle( + versionDto, + publicationRequest.derivedWorkflowIdentity(), + controlledEmptyManifest, + "controlled-generation-input", + participantDigests, + worldOwners.startLocationEvidence())); assertThat(replay).isEqualTo(written); assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); completeActualWorldAndAccountTerminals( @@ -871,18 +858,17 @@ void ownerServerCleanupAttemptsEveryServerAndSuppressesFailuresOnBodyFailure() when(thirdServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(false); Throwable thrown = - catchThrowable( - () -> { - Throwable primaryFailure = null; - try { - throw bodyFailure; - } catch (RuntimeException failure) { - primaryFailure = failure; - throw failure; - } finally { - stopServers(primaryFailure, firstServer, secondServer, thirdServer); - } - }); + catchThrowable(() -> { + Throwable primaryFailure = null; + try { + throw bodyFailure; + } catch (RuntimeException failure) { + primaryFailure = failure; + throw failure; + } finally { + stopServers(primaryFailure, firstServer, secondServer, thirdServer); + } + }); assertThat(thrown).isSameAs(bodyFailure); assertThat(bodyFailure.getSuppressed()).hasSize(3); @@ -911,11 +897,10 @@ void ownerServerCleanupFailureFailsWhenPublicationBodySucceeded() throws Interru assertThatThrownBy(() -> stopServers(null, firstServer, secondServer, thirdServer)) .isInstanceOf(AssertionError.class) - .satisfies( - failure -> { - assertThat(failure.getSuppressed()).hasSize(1); - assertThat(failure.getSuppressed()[0].getCause()).isSameAs(waitFailure); - }); + .satisfies(failure -> { + assertThat(failure.getSuppressed()).hasSize(1); + assertThat(failure.getSuppressed()[0].getCause()).isSameAs(waitFailure); + }); verify(firstServer).shutdownNow(); verify(secondServer).shutdownNow(); @@ -939,11 +924,10 @@ void ownerServerCleanupRestoresInterruptAfterAttemptingAllTerminationWaits() try { assertThatThrownBy(() -> stopServers(null, firstServer, secondServer, thirdServer)) .isInstanceOf(AssertionError.class) - .satisfies( - failure -> { - assertThat(failure.getSuppressed()).hasSize(1); - assertThat(failure.getSuppressed()[0].getCause()).isSameAs(interruption); - }); + .satisfies(failure -> { + assertThat(failure.getSuppressed()).hasSize(1); + assertThat(failure.getSuppressed()[0].getCause()).isSameAs(interruption); + }); assertThat(Thread.currentThread().isInterrupted()).isTrue(); verify(firstServer).awaitTermination(5, TimeUnit.SECONDS); verify(secondServer).awaitTermination(5, TimeUnit.SECONDS); @@ -1006,10 +990,9 @@ void ownerServerCleanupRestoresInterruptAfterAttemptingAllTerminationWaits() assertThat(before.get("account_selected_publication_sources")).isEmpty(); assertThatThrownBy(() -> client.authorize(request)) .isInstanceOf(io.grpc.StatusRuntimeException.class) - .satisfies( - error -> - assertThat(io.grpc.Status.fromThrowable(error).getCode()) - .isEqualTo(io.grpc.Status.Code.UNAVAILABLE)); + .satisfies(error -> + assertThat(io.grpc.Status.fromThrowable(error).getCode()) + .isEqualTo(io.grpc.Status.Code.UNAVAILABLE)); assertThat(publicationOrderRows(sources.dsl)).isEqualTo(before); assertThat(reads.get()).isEqualTo(1); unavailable.set(false); @@ -1186,10 +1169,9 @@ private static WorldSelectedFullPublicationEvidenceFixture.Result freshAuthentic .isEqualTo("OPEN"); assertThatThrownBy(() -> freeze.begin(request)) .isInstanceOf(io.grpc.StatusRuntimeException.class) - .satisfies( - error -> - assertThat(io.grpc.Status.fromThrowable(error).getCode()) - .isEqualTo(io.grpc.Status.Code.UNAVAILABLE)); + .satisfies(error -> + assertThat(io.grpc.Status.fromThrowable(error).getCode()) + .isEqualTo(io.grpc.Status.Code.UNAVAILABLE)); assertThat(freezeOwnerRows(world.dsl())).isEqualTo(before); assertThat(selectionCalls.get()).isEqualTo(1); assertThat(versionCalls.get()).isEqualTo(1); @@ -1384,25 +1366,22 @@ private static void completeActualWorldAndAccountTerminals( wrongCaller.init(); assertThatThrownBy(() -> wrongCaller.settle(settlementRequest)) .isInstanceOf(io.grpc.StatusRuntimeException.class) - .satisfies( - error -> - assertThat(io.grpc.Status.fromThrowable(error).getCode()) - .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); + .satisfies(error -> + assertThat(io.grpc.Status.fromThrowable(error).getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); } diagnostics.phase( "account-settlement-before-world-terminal", () -> { - assertThatThrownBy( - () -> - settlementClient.settle( - net.firedevops.firemud.common.publication - .AccountSelectedPublicationSettlementGrpcCodec.Request.create( - NAMESPACE, operation.canonicalBytes()))) + assertThatThrownBy(() -> + settlementClient.settle( + net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, operation.canonicalBytes()))) .isInstanceOf(io.grpc.StatusRuntimeException.class) - .satisfies( - error -> - assertThat(io.grpc.Status.fromThrowable(error).getCode()) - .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + .satisfies(error -> + assertThat(io.grpc.Status.fromThrowable(error).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); return null; }); assertThat( @@ -1559,20 +1538,17 @@ private static void requireAccountClosureInventoryRefusals( "sha256:" + java.util.HexFormat.of() .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(inventory))); - assertThatThrownBy( - () -> - dsl.fetch( - "SELECT require_selected_inventory_operation_v2(?::bytea)", - raw.toByteArray())) + assertThatThrownBy(() -> + dsl.fetch( + "SELECT require_selected_inventory_operation_v2(?::bytea)", raw.toByteArray())) .isInstanceOf(org.jooq.exception.DataAccessException.class) - .satisfies( - failure -> { - var cause = failure; - while (cause != null && !(cause instanceof java.sql.SQLException)) - cause = cause.getCause(); - assertThat(cause).isInstanceOf(java.sql.SQLException.class); - assertThat(((java.sql.SQLException) cause).getSQLState()).isEqualTo("23514"); - }); + .satisfies(failure -> { + var cause = failure; + while (cause != null && !(cause instanceof java.sql.SQLException)) + cause = cause.getCause(); + assertThat(cause).isInstanceOf(java.sql.SQLException.class); + assertThat(((java.sql.SQLException) cause).getSQLState()).isEqualTo("23514"); + }); } assertThat( dsl.fetch( @@ -1584,19 +1560,18 @@ private static void requireAccountClosureInventoryRefusals( private static Draft createDraft(Store gds) { Version savedVersion = gds.write() - .execute( - ignored -> { - Game game = new Game(); - game.setTenantId(UUID.randomUUID().toString()); - game.setName("Controlled selected full owner proof"); - Game savedGame = new GameRepository(gds.dsl()).save(game); - Version version = new Version(); - version.setTenantId(savedGame.getTenantId()); - version.setVersionNumber(1); - version.setVersionState(VersionLifecycleState.DRAFT); - version.setVersionStateEpoch(1L); - return new VersionRepository(gds.dsl()).save(version); - }); + .execute(ignored -> { + Game game = new Game(); + game.setTenantId(UUID.randomUUID().toString()); + game.setName("Controlled selected full owner proof"); + Game savedGame = new GameRepository(gds.dsl()).save(game); + Version version = new Version(); + version.setTenantId(savedGame.getTenantId()); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.DRAFT); + version.setVersionStateEpoch(1L); + return new VersionRepository(gds.dsl()).save(version); + }); var target = new TargetProof( savedVersion.getCanonicalTenantId(), @@ -1613,15 +1588,14 @@ private static AuthoredWorldSourceEvidence registerControlledWorldSource( Store gds, TargetProof target) { var repository = new GameAuthoredWorldSourceRepository(gds.dsl()); return gds.write() - .execute( - ignored -> - repository.register( - NAMESPACE, - UUID.randomUUID(), - target.canonicalTenantId(), - "controlled-selected-tenant", - "controlled-selected-world", - "Controlled selected World source")); + .execute(ignored -> + repository.register( + NAMESPACE, + UUID.randomUUID(), + target.canonicalTenantId(), + "controlled-selected-tenant", + "controlled-selected-world", + "Controlled selected World source")); } private static DraftCommitBinding selectedCommit(Store gds, TargetProof target) @@ -1864,17 +1838,16 @@ private static void applyGameDesignCommit(Store gds, DraftCommitBinding binding) var coordinator = new DraftCommitCoordinatorRepository(gds.dsl()); var sources = new GameDesignSourceRepository(gds.dsl()); gds.write() - .execute( - ignored -> { - var reviewed = - new GameDesignReviewedBaseRepository(gds.dsl()) - .resolve(binding.target(), DraftBaseReference.parse(binding.baseCommitId())); - sources.claimReviewed(binding, reviewed); - coordinator.claimApplicationSlot(binding); - for (Owner owner : binding.requiredOwners()) - coordinator.markOwnerInProgress(binding, owner); - return null; - }); + .execute(ignored -> { + var reviewed = + new GameDesignReviewedBaseRepository(gds.dsl()) + .resolve(binding.target(), DraftBaseReference.parse(binding.baseCommitId())); + sources.claimReviewed(binding, reviewed); + coordinator.claimApplicationSlot(binding); + for (Owner owner : binding.requiredOwners()) + coordinator.markOwnerInProgress(binding, owner); + return null; + }); } private static void completeGameDesignCommit( @@ -1893,34 +1866,31 @@ private static void completeGameDesignCommit( worldApplied.resultIdentity(), worldApplied.canonicalBytes(), worldApplied.appliedEpochs().stream() - .map( - epoch -> - new DraftCommitCoordinatorRepository.AppliedEpoch( - epoch.aggregateType(), - epoch.aggregateId(), - epoch.scopeType(), - epoch.scopeId(), - epoch.expectedEpoch(), - epoch.resultingEpoch())) + .map(epoch -> + new DraftCommitCoordinatorRepository.AppliedEpoch( + epoch.aggregateType(), + epoch.aggregateId(), + epoch.scopeType(), + epoch.scopeId(), + epoch.expectedEpoch(), + epoch.resultingEpoch())) .toList()); gds.write() - .execute( - ignored -> { - coordinator.recordOwnerOutcome(binding, gameDesignApplied.ownerOutcome()); - coordinator.recordOwnerOutcome(binding, worldOutcome); - List outcomes = - binding.requiredOwners().stream() - .map( - owner -> - owner == Owner.WORLD_MANAGEMENT - ? worldOutcome - : gameDesignApplied.ownerOutcome()) - .toList(); - net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup - .advanceIsolatedSourceVisibility(gds.dsl(), binding, outcomes); - coordinator.releaseApplicationSlot(binding); - return null; - }); + .execute(ignored -> { + coordinator.recordOwnerOutcome(binding, gameDesignApplied.ownerOutcome()); + coordinator.recordOwnerOutcome(binding, worldOutcome); + List outcomes = + binding.requiredOwners().stream() + .map(owner -> + owner == Owner.WORLD_MANAGEMENT + ? worldOutcome + : gameDesignApplied.ownerOutcome()) + .toList(); + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .advanceIsolatedSourceVisibility(gds.dsl(), binding, outcomes); + coordinator.releaseApplicationSlot(binding); + return null; + }); } private static SelectedOwnerIntakeAuthorizationBinding selectedOwnerAuthorization( diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java index 1c9cc36e40..37361aa260 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java @@ -214,24 +214,22 @@ void actualPreliminaryPermissionDisclosesExactSixFamiliesAndAbortPermanentlyRefu for (var owner : List.of(Owner.ENTITY_MANAGEMENT, Owner.AUTOMATION_SCRIPTING)) { UUID requestId = UUID.randomUUID(); var scope = - asGameDesign( - () -> - reservations.reserveSourceRead( - issued.compact(), - requestId, - owner, - local.binding(), - issued.environment())); + asGameDesign(() -> + reservations.reserveSourceRead( + issued.compact(), + requestId, + owner, + local.binding(), + issued.environment())); var retained = retainedReservation(f, scope); var request = SelectedOwnerIntakeSourceReadEvidence.Request.create(NAMESPACE, scope); var content = sources.read(request); var expected = local .tx() - .execute( - ignored -> - new GameDesignSourceRepository(local.dsl()) - .requireSelectedOwnerIntakeSource(scope)); + .execute(ignored -> + new GameDesignSourceRepository(local.dsl()) + .requireSelectedOwnerIntakeSource(scope)); assertThat(content.canonicalBytes()).isEqualTo(expected.canonicalBytes()); assertThat(content.digest()).isEqualTo(expected.digest()); for (String family : @@ -250,14 +248,13 @@ void actualPreliminaryPermissionDisclosesExactSixFamiliesAndAbortPermanentlyRefu .canonicalBytes()) .isEqualTo(content.canonicalBytes()); assertThat( - asGameDesign( - () -> - reservations.reserveSourceRead( - issued.compact(), - requestId, - owner, - local.binding(), - issued.environment())) + asGameDesign(() -> + reservations.reserveSourceRead( + issued.compact(), + requestId, + owner, + local.binding(), + issued.environment())) .canonicalBytes()) .isEqualTo(scope.canonicalBytes()); assertThat(retainedReservation(f, scope)).isEqualTo(retained); @@ -274,11 +271,10 @@ void actualPreliminaryPermissionDisclosesExactSixFamiliesAndAbortPermanentlyRefu scope.intakeRequestId(), scope.actorAccountId(), scope.selected()); - assertThatThrownBy( - () -> - sources.read( - SelectedOwnerIntakeSourceReadEvidence.Request.create( - NAMESPACE, substituted))) + assertThatThrownBy(() -> + sources.read( + SelectedOwnerIntakeSourceReadEvidence.Request.create( + NAMESPACE, substituted))) .isInstanceOf(io.grpc.StatusRuntimeException.class); assertThat(retainedReservation(f, scope)).isEqualTo(retained); var capturedSources = @@ -297,38 +293,34 @@ void actualPreliminaryPermissionDisclosesExactSixFamiliesAndAbortPermanentlyRefu .isEqualTo("ABORTED"); assertThat(f.tx(() -> f.fences.sourceMutationPermitted(blockedWriter))) .isTrue(); - f.tx( - () -> { - f.fences.markSourceAborted( - blockedWriter, - net.firedevops.firemud.accountservice.authordraft - .DraftAuthorizationFenceRepository.SourceChangeAbortReason - .DEFINITIVE_ABORT); - return null; - }); + f.tx(() -> { + f.fences.markSourceAborted( + blockedWriter, + net.firedevops.firemud.accountservice.authordraft + .DraftAuthorizationFenceRepository.SourceChangeAbortReason + .DEFINITIVE_ABORT); + return null; + }); var aborted = retainedReservation(f, scope); assertThatThrownBy(() -> sources.read(request)) .isInstanceOf(io.grpc.StatusRuntimeException.class); - assertThatThrownBy( - () -> - asGameDesign( - () -> - reservations.reserveSourceRead( - issued.compact(), - requestId, - owner, - local.binding(), - issued.environment()))) + assertThatThrownBy(() -> + asGameDesign(() -> + reservations.reserveSourceRead( + issued.compact(), + requestId, + owner, + local.binding(), + issued.environment()))) .isInstanceOf(io.grpc.StatusRuntimeException.class); asGameDesign(() -> reservations.abortSourceRead(scope)); assertThat(retainedReservation(f, scope)).isEqualTo(aborted); assertThat( local .tx() - .execute( - ignored -> - new GameDesignSourceRepository(local.dsl()) - .requireSelectedOwnerIntakeSource(scope)) + .execute(ignored -> + new GameDesignSourceRepository(local.dsl()) + .requireSelectedOwnerIntakeSource(scope)) .canonicalBytes()) .isEqualTo(content.canonicalBytes()); } @@ -374,22 +366,21 @@ private static void retainControlledSelectedAuthorAdmission( captured.sources()) .withRequiredOwners(); issued.actors().claimOriginalDraft(issued.compact(), original, issued.environment()); - f.tx( - () -> { - for (var owner : original.requiredOwners()) - f.fences.recordOwnerReadback( - original, - new DraftAuthorizationFenceBinding.OwnerReadback( - owner, - DraftAuthorizationFenceBinding.Outcome.COMMITTED, - original.operationId(), - original.commitId(), - original.fenceId(), - original.inputDigest(), - original.canonicalBytes(), - new byte[] {1})); - return null; - }); + f.tx(() -> { + for (var owner : original.requiredOwners()) + f.fences.recordOwnerReadback( + original, + new DraftAuthorizationFenceBinding.OwnerReadback( + owner, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.canonicalBytes(), + new byte[] {1})); + return null; + }); } private static Local sourceStore() { @@ -454,22 +445,21 @@ private static Local sourceStore() { CommandSource.SCOPE, "effective", "0"))); - tx.executeWithoutResult( - ignored -> { - var source = new GameDesignSourceRepository(dsl); - var reviewed = - new GameDesignReviewedBaseRepository(dsl) - .resolve(target, DraftBaseReference.parse(binding.baseCommitId())); - source.claimReviewed(binding, reviewed); - var coordinator = new DraftCommitCoordinatorRepository(dsl); - coordinator.claimApplicationSlot(binding); - coordinator.markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); - var applied = source.apply(binding); - IsolatedPublicationOwnerSetup.advanceIsolatedSourceVisibility( - dsl, binding, List.of(applied.ownerOutcome())); - source.captureSynchronized(binding); - coordinator.releaseApplicationSlot(binding); - }); + tx.executeWithoutResult(ignored -> { + var source = new GameDesignSourceRepository(dsl); + var reviewed = + new GameDesignReviewedBaseRepository(dsl) + .resolve(target, DraftBaseReference.parse(binding.baseCommitId())); + source.claimReviewed(binding, reviewed); + var coordinator = new DraftCommitCoordinatorRepository(dsl); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + var applied = source.apply(binding); + IsolatedPublicationOwnerSetup.advanceIsolatedSourceVisibility( + dsl, binding, List.of(applied.ownerOutcome())); + source.captureSynchronized(binding); + coordinator.releaseApplicationSlot(binding); + }); return new Local(dsl, manager, tx, binding); } diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java index bef6b7876e..31cab59add 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java @@ -111,10 +111,9 @@ void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads(@TempDir Pat var applicationNameOrigin = environment.getPropertySources().stream() .filter(source -> source.containsProperty("spring.application.name")) - .map( - source -> - org.springframework.boot.origin.OriginLookup.getOrigin( - source, "spring.application.name")) + .map(source -> + org.springframework.boot.origin.OriginLookup.getOrigin( + source, "spring.application.name")) .filter(java.util.Objects::nonNull) .findFirst() .orElseThrow( @@ -337,19 +336,18 @@ void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads(@TempDir Pat org.mockito.Mockito.doReturn(java.util.Optional.of(changedSource)) .when(authoredWorldSourceRepository) .read(any(UUID.class), any(UUID.class), any(String.class), any(String.class)); - org.assertj.core.api.Assertions.assertThatThrownBy( - () -> - withControlledGameSessionPeer( - fixture, - () -> - controlledInstallation.withLaunchOwners( - starting.gameInstanceUuid(), - () -> - ReflectionTestUtils.invokeMethod( - initialCommands, - PREPARE_RUN_OWNED_FIXTURE, - request, - worldEvidence)))) + org.assertj.core.api.Assertions.assertThatThrownBy(() -> + withControlledGameSessionPeer( + fixture, + () -> + controlledInstallation.withLaunchOwners( + starting.gameInstanceUuid(), + () -> + ReflectionTestUtils.invokeMethod( + initialCommands, + PREPARE_RUN_OWNED_FIXTURE, + request, + worldEvidence)))) .isInstanceOf(RuntimeException.class); assertThat(allComposedOwnerRows(worldDatabase.dsl())).isEqualTo(emptyWorldRows); org.mockito.Mockito.verify(authoredWorldSourceRepository) @@ -512,19 +510,18 @@ void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads(@TempDir Pat request.publishedReleaseBundleRef(), request.versionStateEpoch(), request.remapSetId()); - org.assertj.core.api.Assertions.assertThatThrownBy( - () -> - withControlledGameSessionPeer( - fixture, - () -> - controlledInstallation.withLaunchOwners( - starting.gameInstanceUuid(), - () -> - ReflectionTestUtils.invokeMethod( - initialCommands, - PREPARE_RUN_OWNED_FIXTURE, - mismatchedRequest, - worldEvidence)))) + org.assertj.core.api.Assertions.assertThatThrownBy(() -> + withControlledGameSessionPeer( + fixture, + () -> + controlledInstallation.withLaunchOwners( + starting.gameInstanceUuid(), + () -> + ReflectionTestUtils.invokeMethod( + initialCommands, + PREPARE_RUN_OWNED_FIXTURE, + mismatchedRequest, + worldEvidence)))) .isInstanceOf(IllegalArgumentException.class); assertThat(allComposedOwnerRows(worldDatabase.dsl())).isEqualTo(worldRows); org.mockito.Mockito.verifyNoInteractions(entityClient); @@ -597,10 +594,9 @@ void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads(@TempDir Pat var otherGsLeaf = issueFixedReadLeaf(fixture, "different-game-session-client", SESSION_URI_SAN, false); var wrongSessionCertificate = readCertificate(otherGsLeaf.certificate()); - org.assertj.core.api.Assertions.assertThatThrownBy( - () -> - withControlledPeer( - wrongSessionCertificate, replayProvider::requireAuthenticatedEvidence)) + org.assertj.core.api.Assertions.assertThatThrownBy(() -> + withControlledPeer( + wrongSessionCertificate, replayProvider::requireAuthenticatedEvidence)) .isInstanceOf( RunOwnedCanonicalWorldLaunchEvidenceProvider .InvalidRunOwnedCanonicalWorldLaunchEvidenceException.class); diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java index 1cb78ad66c..0935d46fd6 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationPostgresIntegrationTest.java @@ -174,10 +174,8 @@ class GameDesignPublicationOperationPostgresIntegrationTest { // The real handler and owner read finish; the first outbound result is deliberately lost. assertThatThrownBy(() -> client.read(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - e -> - assertThat(Status.fromThrowable(e).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); + .satisfies(e -> + assertThat(Status.fromThrowable(e).getCode()).isEqualTo(Status.Code.UNAVAILABLE)); var recovered = client.read(request).terminalEvidence().orElseThrow(); assertThat(recovered.canonicalBytes()).isEqualTo(retained); assertThat(recovered.operationBytes()).isEqualTo(fixture.operation().canonicalBytes()); @@ -205,12 +203,11 @@ class GameDesignPublicationOperationPostgresIntegrationTest { client.init(); assertThatThrownBy(() -> client.read(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - e -> { - assertThat(Status.fromThrowable(e).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED); - assertThat(TlsTestSupport.isTlsHandshakeRejection(e)).isFalse(); - }); + .satisfies(e -> { + assertThat(Status.fromThrowable(e).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(TlsTestSupport.isTlsHandshakeRejection(e)).isFalse(); + }); } } assertThat(headers).hasValue(5); @@ -233,12 +230,11 @@ class GameDesignPublicationOperationPostgresIntegrationTest { client.init(); assertThatThrownBy(() -> client.read(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - e -> { - assertThat(Status.fromThrowable(e).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED); - assertThat(TlsTestSupport.isTlsHandshakeRejection(e)).isFalse(); - }); + .satisfies(e -> { + assertThat(Status.fromThrowable(e).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(TlsTestSupport.isTlsHandshakeRejection(e)).isFalse(); + }); assertThat(deniedHeaders).hasValue(0); } finally { deniedServer.shutdownNow(); @@ -316,37 +312,33 @@ void actualProducerComposesRequiredMtlsWorldVerifierWithControlledStoreAndReplay pki.server(), pki.ca(), directory.resolve("producer-gds-" + ownerIndex)), new GrpcChannelFactory(), "test")) { - assertThatThrownBy( - () -> - fixture - .write() - .executeWithoutResult( - status -> { - producer.reconcile( - fixture.operation().tenantKey(), - fixture.operation().workflowId(), - fixture.operation().versionId(), - fixture.operation().selectionDigest(), - outcome); - })) + assertThatThrownBy(() -> + fixture + .write() + .executeWithoutResult(status -> { + producer.reconcile( + fixture.operation().tenantKey(), + fixture.operation().workflowId(), + fixture.operation().versionId(), + fixture.operation().selectionDigest(), + outcome); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("Independent World publication handoff required"); assertThat(completionProbe.calls).isEmpty(); assertThat(terminalOwnerSnapshot(fixture)).isEqualTo(ownerBefore); - assertThatThrownBy( - () -> - producer.reconcile( - fixture.operation().tenantKey(), - fixture.operation().workflowId(), - fixture.operation().versionId(), - fixture.operation().selectionDigest(), - outcome)) + assertThatThrownBy(() -> + producer.reconcile( + fixture.operation().tenantKey(), + fixture.operation().workflowId(), + fixture.operation().versionId(), + fixture.operation().selectionDigest(), + outcome)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); assertThat(completionProbe.calls).hasSize(1); assertThat(completionStore.calls()).hasSize(1); @@ -371,27 +363,25 @@ void actualProducerComposesRequiredMtlsWorldVerifierWithControlledStoreAndReplay assertThat(completionProbe.calls.get(0).requestId()) .isNotEqualTo(completionProbe.calls.get(1).requestId()); assertThat(completionProbe.calls) - .allSatisfy( - call -> { - assertThat(call.targetNamespace()).isEqualTo("test"); - assertThat(call.operationBytes()).isEqualTo(originalOperationBytes); - assertThat(call.terminalBytes()).isEqualTo(originalTerminalBytes); - assertThat(call.ownerTransactionActive()).isFalse(); - assertThat(call.ownerSynchronizationActive()).isFalse(); - }); + .allSatisfy(call -> { + assertThat(call.targetNamespace()).isEqualTo("test"); + assertThat(call.operationBytes()).isEqualTo(originalOperationBytes); + assertThat(call.terminalBytes()).isEqualTo(originalTerminalBytes); + assertThat(call.ownerTransactionActive()).isFalse(); + assertThat(call.ownerSynchronizationActive()).isFalse(); + }); assertThat(completionStore.calls()) - .allSatisfy( - call -> { - assertThat(call.operationBytes()).isEqualTo(originalOperationBytes); - assertThat(call.terminalBytes()).isEqualTo(originalTerminalBytes); - assertThat(call.publicationFence()).isEqualTo(originalWorld.publicationFence()); - assertThat(call.publicationRequestId()) - .isEqualTo(originalWorld.publicationRequestId()); - assertThat(call.workflowId()).isEqualTo(fixture.operation().workflowId()); - assertThat(call.ownerTransactionActive()).isFalse(); - assertThat(call.ownerSynchronizationActive()).isFalse(); - assertThat(call.completedGdsReads()).isGreaterThan(0); - }); + .allSatisfy(call -> { + assertThat(call.operationBytes()).isEqualTo(originalOperationBytes); + assertThat(call.terminalBytes()).isEqualTo(originalTerminalBytes); + assertThat(call.publicationFence()).isEqualTo(originalWorld.publicationFence()); + assertThat(call.publicationRequestId()) + .isEqualTo(originalWorld.publicationRequestId()); + assertThat(call.workflowId()).isEqualTo(fixture.operation().workflowId()); + assertThat(call.ownerTransactionActive()).isFalse(); + assertThat(call.ownerSynchronizationActive()).isFalse(); + assertThat(call.completedGdsReads()).isGreaterThan(0); + }); assertThat(readHeaders).hasValue(2); assertThat(readResponses).hasValue(2); assertThat(completionProbe.responses).hasValue(1); @@ -408,14 +398,13 @@ void actualProducerComposesRequiredMtlsWorldVerifierWithControlledStoreAndReplay outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED ? GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION : GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED; - assertThatThrownBy( - () -> - producer.reconcile( - fixture.operation().tenantKey(), - fixture.operation().workflowId(), - fixture.operation().versionId(), - fixture.operation().selectionDigest(), - oppositeOutcome)) + assertThatThrownBy(() -> + producer.reconcile( + fixture.operation().tenantKey(), + fixture.operation().workflowId(), + fixture.operation().versionId(), + fixture.operation().selectionDigest(), + oppositeOutcome)) .isInstanceOf(IllegalStateException.class) .hasMessage("PUBLICATION_TERMINAL_UNRESOLVED"); assertThat(completionProbe.calls).hasSize(2); @@ -454,24 +443,22 @@ void producerDoesNotCallWorldForAbsentPendingOrHistoricalMissingTerminal(@TempDi publicationClientTls(pki.server(), pki.ca(), directory.resolve("pending-producer")), new GrpcChannelFactory(), "test")) { - assertThatThrownBy( - () -> - producer.reconcile( - pendingFixture.operation().tenantKey(), - pendingFixture.operation().workflowId() + "-absent", - pendingFixture.operation().versionId(), - pendingFixture.operation().selectionDigest(), - GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED)) + assertThatThrownBy(() -> + producer.reconcile( + pendingFixture.operation().tenantKey(), + pendingFixture.operation().workflowId() + "-absent", + pendingFixture.operation().versionId(), + pendingFixture.operation().selectionDigest(), + GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED)) .isInstanceOf(IllegalStateException.class) .hasMessage("PUBLICATION_TERMINAL_PENDING"); - assertThatThrownBy( - () -> - producer.reconcile( - pendingFixture.operation().tenantKey(), - pendingFixture.operation().workflowId(), - pendingFixture.operation().versionId(), - pendingFixture.operation().selectionDigest(), - GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED)) + assertThatThrownBy(() -> + producer.reconcile( + pendingFixture.operation().tenantKey(), + pendingFixture.operation().workflowId(), + pendingFixture.operation().versionId(), + pendingFixture.operation().selectionDigest(), + GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED)) .isInstanceOf(IllegalStateException.class) .hasMessage("PUBLICATION_TERMINAL_UNRESOLVED"); assertThat(terminalOwnerSnapshot(pendingFixture)).isEqualTo(pendingBefore); @@ -488,14 +475,13 @@ void producerDoesNotCallWorldForAbsentPendingOrHistoricalMissingTerminal(@TempDi pki.server(), pki.ca(), directory.resolve("historical-producer")), new GrpcChannelFactory(), "test")) { - assertThatThrownBy( - () -> - producer.reconcile( - historical.operation().tenantKey(), - historical.operation().workflowId(), - historical.operation().versionId(), - historical.operation().selectionDigest(), - GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION)) + assertThatThrownBy(() -> + producer.reconcile( + historical.operation().tenantKey(), + historical.operation().workflowId(), + historical.operation().versionId(), + historical.operation().selectionDigest(), + GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION)) .isInstanceOf(IllegalStateException.class) .hasMessage("PUBLICATION_TERMINAL_UNRESOLVED"); assertThat(terminalOwnerSnapshot(historical)).isEqualTo(historicalBefore); @@ -544,19 +530,17 @@ void wrongPublicationWorkloadOrCallerContextIsDeniedBeforeEitherOwnerEffect( directory.resolve("wrong-gds-" + invalidIdentity.label())), new GrpcChannelFactory(), "test")) { - assertThatThrownBy( - () -> - producer.reconcile( - fixture.operation().tenantKey(), - fixture.operation().workflowId(), - fixture.operation().versionId(), - fixture.operation().selectionDigest(), - GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED)) + assertThatThrownBy(() -> + producer.reconcile( + fixture.operation().tenantKey(), + fixture.operation().workflowId(), + fixture.operation().versionId(), + fixture.operation().selectionDigest(), + GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } } probe.injectCallerContext.set(true); @@ -568,19 +552,17 @@ void wrongPublicationWorkloadOrCallerContextIsDeniedBeforeEitherOwnerEffect( pki.server(), pki.ca(), directory.resolve("caller-context-producer")), new GrpcChannelFactory(), "test")) { - assertThatThrownBy( - () -> - producer.reconcile( - fixture.operation().tenantKey(), - fixture.operation().workflowId(), - fixture.operation().versionId(), - fixture.operation().selectionDigest(), - GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED)) + assertThatThrownBy(() -> + producer.reconcile( + fixture.operation().tenantKey(), + fixture.operation().workflowId(), + fixture.operation().versionId(), + fixture.operation().selectionDigest(), + GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } probe.injectCallerContext.set(false); assertThat(probe.calls).hasSize(3); @@ -630,19 +612,17 @@ void wrongPublicationWorkloadOrCallerContextIsDeniedBeforeEitherOwnerEffect( pki.server(), pki.ca(), directory.resolve("wrong-world-verifier-producer")), new GrpcChannelFactory(), "test")) { - assertThatThrownBy( - () -> - producer.reconcile( - fixture.operation().tenantKey(), - fixture.operation().workflowId(), - fixture.operation().versionId(), - fixture.operation().selectionDigest(), - GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED)) + assertThatThrownBy(() -> + producer.reconcile( + fixture.operation().tenantKey(), + fixture.operation().workflowId(), + fixture.operation().versionId(), + fixture.operation().selectionDigest(), + GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); assertThat(wrongWorldProbe.calls).hasSize(1); assertThat(wrongWorldReadHeaders).hasValue(1); assertThat(wrongWorldReadResponses).hasValue(0); @@ -1174,10 +1154,9 @@ void authenticatedTerminalReadMapsResponseEncodingFailuresWithoutPartialResponse GameDesignPublicationTerminalReadGrpcCodec.class, org.mockito.Mockito.CALLS_REAL_METHODS)) { codec - .when( - () -> - GameDesignPublicationTerminalReadGrpcCodec.toResponse( - org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) + .when(() -> + GameDesignPublicationTerminalReadGrpcCodec.toResponse( + org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any())) .thenThrow(encodingFailure); var result = readThroughHandler(fixture, request, "account-service"); @@ -1237,22 +1216,18 @@ void retainedV50_6TerminalReadFailsPreconditionWithoutBackfillingEvidenceOrEpoch DraftAuthorizationFenceBinding.frame(old, new byte[0]); fixture .write() - .executeWithoutResult( - status -> { - var attempt = - fixture - .attempts() - .findByPublishWorkflowIdForUpdate(op.workflowId()) - .orElseThrow(); - attempt.setStatus(PublishAttemptStatus.FAILED); - fixture.attempts().save(attempt); - fixture - .dsl() - .execute( - "UPDATE game_design_publication_operation SET outcome = 'NO_PUBLICATION', revision = revision + 1, result_bytes = ? WHERE publish_workflow_id = ?", - old.toByteArray(), - op.workflowId()); - }); + .executeWithoutResult(status -> { + var attempt = + fixture.attempts().findByPublishWorkflowIdForUpdate(op.workflowId()).orElseThrow(); + attempt.setStatus(PublishAttemptStatus.FAILED); + fixture.attempts().save(attempt); + fixture + .dsl() + .execute( + "UPDATE game_design_publication_operation SET outcome = 'NO_PUBLICATION', revision = revision + 1, result_bytes = ? WHERE publish_workflow_id = ?", + old.toByteArray(), + op.workflowId()); + }); fixture.completeMigration().run(); var request = GameDesignPublicationTerminalReadEvidence.ReadRequest.create("test", op.canonicalBytes()); @@ -1298,47 +1273,44 @@ void retainedPreV56V1OperationStaysByteExactReadableAndReadOnlyAfterV56AndV70() assertThat(retained.operation().canonicalBytes()).isEqualTo(originalRequest); assertThat(retained.outcome()).isEqualTo("PENDING"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "INSERT INTO game_design_publication_operation " - + "(publish_workflow_id, tenant_id, version_id, selection_digest, request_bytes) " - + "VALUES (?, ?, ?, ?, ?)", - operation.workflowId(), - operation.tenantKey(), - operation.versionId(), - operation.selectionDigest(), - originalRequest)) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "INSERT INTO game_design_publication_operation " + + "(publish_workflow_id, tenant_id, version_id, selection_digest, request_bytes) " + + "VALUES (?, ?, ?, ?, ?)", + operation.workflowId(), + operation.tenantKey(), + operation.versionId(), + operation.selectionDigest(), + originalRequest)) .hasMessageContaining("Truncated publication inventory frame"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "UPDATE game_design_publication_operation SET outcome = 'NO_PUBLICATION', " - + "revision = revision + 1, result_bytes = ? WHERE publish_workflow_id = ?", - new byte[] {1}, - operation.workflowId())) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "UPDATE game_design_publication_operation SET outcome = 'NO_PUBLICATION', " + + "revision = revision + 1, result_bytes = ? WHERE publish_workflow_id = ?", + new byte[] {1}, + operation.workflowId())) .hasMessageContaining("Truncated publication inventory frame"); var selection = operation.account().input().selection(); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "INSERT INTO game_design_realm_policy_capture " - + "(canonical_tenant_id, canonical_version_id, publish_workflow_id, " - + "commit_id, operation_bytes, capture_bytes) VALUES (?, ?, ?, ?, ?, ?)", - operation.account().tenantId(), - operation.world().request().canonicalVersionId(), - operation.workflowId(), - selection.selectedCommit().commitId(), - originalRequest, - new byte[] {1})) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "INSERT INTO game_design_realm_policy_capture " + + "(canonical_tenant_id, canonical_version_id, publish_workflow_id, " + + "commit_id, operation_bytes, capture_bytes) VALUES (?, ?, ?, ?, ?, ?)", + operation.account().tenantId(), + operation.world().request().canonicalVersionId(), + operation.workflowId(), + selection.selectedCommit().commitId(), + originalRequest, + new byte[] {1})) .hasMessageContaining("Truncated publication inventory frame"); assertThat( @@ -1387,12 +1359,11 @@ void retainedPublicationReceiptSurvivesAdditiveReleaseColumnAndV1SealIsDeniedAft retained.completeMigration().run(); retained .write() - .executeWithoutResult( - status -> - retained - .dsl() - .execute( - "ALTER TABLE published_release_bundle ADD COLUMN future_optional_evidence TEXT")); + .executeWithoutResult(status -> + retained + .dsl() + .execute( + "ALTER TABLE published_release_bundle ADD COLUMN future_optional_evidence TEXT")); String expandedWholeRow = java.util.Objects.requireNonNull( retained @@ -1407,18 +1378,16 @@ void retainedPublicationReceiptSurvivesAdditiveReleaseColumnAndV1SealIsDeniedAft var replay = retained.service().readExact(retained.operation()).orElseThrow(); assertThat(replay.receiptBytes()).isEqualTo(original.receiptBytes()); assertThat(replay.terminalEvidenceBytes()).isEqualTo(original.terminalEvidenceBytes()); - assertThatThrownBy( - () -> - retained - .write() - .executeWithoutResult( - status -> - retained - .dsl() - .execute( - "UPDATE published_release_bundle SET generation_config_revision = 'changed' WHERE tenant_id = ? AND version_id = ?", - retained.operation().tenantKey(), - retained.operation().versionId()))) + assertThatThrownBy(() -> + retained + .write() + .executeWithoutResult(status -> + retained + .dsl() + .execute( + "UPDATE published_release_bundle SET generation_config_revision = 'changed' WHERE tenant_id = ? AND version_id = ?", + retained.operation().tenantKey(), + retained.operation().versionId()))) .isInstanceOf(RuntimeException.class); assertThat(retained.service().readExact(retained.operation()).orElseThrow().receiptBytes()) .isEqualTo(original.receiptBytes()); @@ -1426,15 +1395,14 @@ void retainedPublicationReceiptSurvivesAdditiveReleaseColumnAndV1SealIsDeniedAft var retainedPending = historicalFixture("50.7"); var originalOperationBytes = retainedPending.operation().canonicalBytes(); retainedPending.completeMigration().run(); - assertThatThrownBy( - () -> - retainedPending - .dsl() - .execute( - "UPDATE game_design_publication_operation SET outcome = 'NO_PUBLICATION', " - + "revision = revision + 1, result_bytes = ? WHERE publish_workflow_id = ?", - new byte[] {1}, - retainedPending.operation().workflowId())) + assertThatThrownBy(() -> + retainedPending + .dsl() + .execute( + "UPDATE game_design_publication_operation SET outcome = 'NO_PUBLICATION', " + + "revision = revision + 1, result_bytes = ? WHERE publish_workflow_id = ?", + new byte[] {1}, + retainedPending.operation().workflowId())) .hasMessageContaining("Truncated publication inventory frame"); var stillPending = retainedPending.service().readExact(retainedPending.operation()).orElseThrow(); @@ -1445,12 +1413,11 @@ void retainedPublicationReceiptSurvivesAdditiveReleaseColumnAndV1SealIsDeniedAft fresh.completeMigration().run(); fresh .write() - .executeWithoutResult( - status -> - fresh - .dsl() - .execute( - "ALTER TABLE published_release_bundle ADD COLUMN future_optional_evidence TEXT")); + .executeWithoutResult(status -> + fresh + .dsl() + .execute( + "ALTER TABLE published_release_bundle ADD COLUMN future_optional_evidence TEXT")); publish(fresh); var freshRead = fresh.service().readExact(fresh.operation()).orElseThrow(); assertThat(freshRead.outcome()).isEqualTo("PUBLISHED"); @@ -1549,19 +1516,17 @@ void noPublicationReceiptReplaysAfterLostResponseAndExcludesDelayedFinalizerAndR .isInstanceOf(IllegalStateException.class); assertThat(fixture.service().retainVerifiedOperation(fixture.operation()).receiptBytes()) .isEqualTo(original.receiptBytes()); - assertThatThrownBy( - () -> - fixture - .write() - .executeWithoutResult( - status -> - fixture - .operations() - .requirePending( - fixture.operation().tenantKey(), - fixture.operation().workflowId(), - fixture.operation().versionId(), - fixture.operation().selectionDigest()))) + assertThatThrownBy(() -> + fixture + .write() + .executeWithoutResult(status -> + fixture + .operations() + .requirePending( + fixture.operation().tenantKey(), + fixture.operation().workflowId(), + fixture.operation().versionId(), + fixture.operation().selectionDigest()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("SEALED_OR_CHANGED"); assertThatThrownBy( @@ -1589,18 +1554,17 @@ void terminalEvidenceKeepsOriginalCommittedEpochAfterLaterVersionTransition() th assertThat(terminal.operationBytes()).isEqualTo(fixture.operation().canonicalBytes()); fixture .write() - .executeWithoutResult( - status -> { - var version = - fixture - .versions() - .findByTenantIdAndIdForUpdate( - fixture.operation().tenantKey(), fixture.operation().versionId()) - .orElseThrow(); - version.setVersionState(VersionLifecycleState.RETIRED); - version.setVersionStateEpoch(captured + 1); - fixture.versions().save(version); - }); + .executeWithoutResult(status -> { + var version = + fixture + .versions() + .findByTenantIdAndIdForUpdate( + fixture.operation().tenantKey(), fixture.operation().versionId()) + .orElseThrow(); + version.setVersionState(VersionLifecycleState.RETIRED); + version.setVersionStateEpoch(captured + 1); + fixture.versions().save(version); + }); var replay = fixture.service().readExact(fixture.operation()).orElseThrow(); assertThat(replay.terminalEvidenceBytes()).isEqualTo(original.terminalEvidenceBytes()); assertThat( @@ -1620,33 +1584,29 @@ void terminalExtensionRefusesRawEpochDigestBytesAndReleaseContentSubstitution() "published_release_bundle_digest = 'sha256:' || repeat('f', 64)", "terminal_evidence_bytes = terminal_evidence_bytes || decode('00', 'hex')", "release_content_bytes = release_content_bytes || decode('00', 'hex')")) { - assertThatThrownBy( - () -> - fixture - .write() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "UPDATE game_design_publication_operation SET " - + assignment - + " WHERE publish_workflow_id = ?", - fixture.operation().workflowId()))) + assertThatThrownBy(() -> + fixture + .write() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "UPDATE game_design_publication_operation SET " + + assignment + + " WHERE publish_workflow_id = ?", + fixture.operation().workflowId()))) .hasMessageContaining("publication operation identity or terminal outcome is immutable"); } - assertThatThrownBy( - () -> - fixture - .write() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "UPDATE published_release_bundle SET generation_config_revision = 'changed' WHERE tenant_id = ? AND version_id = ?", - fixture.operation().tenantKey(), - fixture.operation().versionId()))) + assertThatThrownBy(() -> + fixture + .write() + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "UPDATE published_release_bundle SET generation_config_revision = 'changed' WHERE tenant_id = ? AND version_id = ?", + fixture.operation().tenantKey(), + fixture.operation().versionId()))) .isInstanceOf(RuntimeException.class); assertThat( fixture.service().readExact(fixture.operation()).orElseThrow().terminalEvidenceBytes()) @@ -1661,15 +1621,13 @@ void originalSealRejectsForgedCommittedEpochAndPreservesPendingOwnerRows() throw ? "publication terminal bytes differ from original owner result" : "publication terminal content or committed epoch differs from owner seal"; var fixture = fixture(); - assertThatThrownBy( - () -> - fixture - .write() - .executeWithoutResult( - status -> { - publishInTransaction(fixture, false); - rawTerminalSeal(fixture, forgedField); - })) + assertThatThrownBy(() -> + fixture + .write() + .executeWithoutResult(status -> { + publishInTransaction(fixture, false); + rawTerminalSeal(fixture, forgedField); + })) .hasMessageContaining(expectedGuardMessage); var pending = fixture.service().readExact(fixture.operation()).orElseThrow(); assertThat(pending.outcome()).isEqualTo("PENDING"); @@ -1688,20 +1646,18 @@ void originalSealRejectsForgedCommittedEpochAndPreservesPendingOwnerRows() throw @Test void publicationSealEpochMustRemainTheActualVersionEpochThroughCommit() throws Exception { var fixture = fixture(); - assertThatThrownBy( - () -> - fixture - .write() - .executeWithoutResult( - status -> { - publishInTransaction(fixture); - fixture - .dsl() - .execute( - "UPDATE version SET version_state_epoch = version_state_epoch + 1 WHERE tenant_id = ? AND id = ?", - fixture.operation().tenantKey(), - fixture.operation().versionId()); - })) + assertThatThrownBy(() -> + fixture + .write() + .executeWithoutResult(status -> { + publishInTransaction(fixture); + fixture + .dsl() + .execute( + "UPDATE version SET version_state_epoch = version_state_epoch + 1 WHERE tenant_id = ? AND id = ?", + fixture.operation().tenantKey(), + fixture.operation().versionId()); + })) .isInstanceOf(RuntimeException.class); assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()) .isEqualTo("PENDING"); @@ -1727,11 +1683,8 @@ void publishedReceiptCannotBeDemotedByStaleFailureAndRetainsOriginalFreezeEpoch( .getVersionStateEpoch()) .isEqualTo(fixture.operation().world().request().versionStateEpoch() + 1); staleFailure.setStatus(PublishAttemptStatus.FAILED); - assertThatThrownBy( - () -> - fixture - .write() - .executeWithoutResult(status -> fixture.attempts().save(staleFailure))) + assertThatThrownBy(() -> + fixture.write().executeWithoutResult(status -> fixture.attempts().save(staleFailure))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("CAS_CONFLICT"); assertThatThrownBy(() -> noPublication(fixture)).isInstanceOf(IllegalStateException.class); @@ -1743,16 +1696,13 @@ void publishedReceiptCannotBeDemotedByStaleFailureAndRetainsOriginalFreezeEpoch( void failedAtomicCommitLeavesAttemptOperationVersionAndReleasePendingForExactRetry() throws Exception { var fixture = fixture(); - assertThatThrownBy( - () -> - fixture - .write() - .executeWithoutResult( - status -> { - publishInTransaction(fixture); - throw new IllegalStateException( - "ISOLATED rollback after all owner writes"); - })) + assertThatThrownBy(() -> + fixture + .write() + .executeWithoutResult(status -> { + publishInTransaction(fixture); + throw new IllegalStateException("ISOLATED rollback after all owner writes"); + })) .hasMessageContaining("rollback after all owner writes"); assertThat(fixture.service().readExact(fixture.operation()).orElseThrow().outcome()) .isEqualTo("PENDING"); @@ -1792,39 +1742,35 @@ void noPublicationSerializesAgainstAnAlreadyScheduledLatePublisher() throws Exce var loserPid = new AtomicInteger(); try (var executor = Executors.newFixedThreadPool(2)) { var winner = - executor.submit( - () -> - fixture - .write() - .executeWithoutResult( - status -> { - noPublicationInTransaction(fixture); - winnerPid.set( - java.util.Objects.requireNonNull( - fixture.dsl().fetchOne("SELECT pg_backend_pid()"), - "no-publication transaction must expose its PostgreSQL backend") - .get(0, Integer.class)); - sealed.countDown(); - await(releaseSeal); - })); + executor.submit(() -> + fixture + .write() + .executeWithoutResult(status -> { + noPublicationInTransaction(fixture); + winnerPid.set( + java.util.Objects.requireNonNull( + fixture.dsl().fetchOne("SELECT pg_backend_pid()"), + "no-publication transaction must expose its PostgreSQL backend") + .get(0, Integer.class)); + sealed.countDown(); + await(releaseSeal); + })); assertThat(sealed.await(10, TimeUnit.SECONDS)).isTrue(); var loser = - executor.submit( - () -> { - fixture - .write() - .executeWithoutResult( - status -> { - loserPid.set( - java.util.Objects.requireNonNull( - fixture.dsl().fetchOne("SELECT pg_backend_pid()"), - "late publisher transaction must expose its PostgreSQL backend") - .get(0, Integer.class)); - attempting.countDown(); - assertThatThrownBy(() -> publishInTransaction(fixture)) - .isInstanceOf(IllegalStateException.class); - }); - }); + executor.submit(() -> { + fixture + .write() + .executeWithoutResult(status -> { + loserPid.set( + java.util.Objects.requireNonNull( + fixture.dsl().fetchOne("SELECT pg_backend_pid()"), + "late publisher transaction must expose its PostgreSQL backend") + .get(0, Integer.class)); + attempting.countDown(); + assertThatThrownBy(() -> publishInTransaction(fixture)) + .isInstanceOf(IllegalStateException.class); + }); + }); assertThat(attempting.await(10, TimeUnit.SECONDS)).isTrue(); boolean observedBlock = false; long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); @@ -1871,24 +1817,23 @@ private void retainHistoricalNoPublicationWithoutCurrentTerminal(Fixture fixture DraftAuthorizationFenceBinding.frame(historicalReceipt, new byte[0]); fixture .write() - .executeWithoutResult( - status -> { - var attempt = - fixture - .attempts() - .findByPublishWorkflowIdForUpdate(operation.workflowId()) - .orElseThrow(); - attempt.setStatus(PublishAttemptStatus.FAILED); - fixture.attempts().save(attempt); + .executeWithoutResult(status -> { + var attempt = fixture - .dsl() - .execute( - "UPDATE game_design_publication_operation SET outcome = 'NO_PUBLICATION', " - + "revision = revision + 1, result_bytes = ? " - + "WHERE publish_workflow_id = ?", - historicalReceipt.toByteArray(), - operation.workflowId()); - }); + .attempts() + .findByPublishWorkflowIdForUpdate(operation.workflowId()) + .orElseThrow(); + attempt.setStatus(PublishAttemptStatus.FAILED); + fixture.attempts().save(attempt); + fixture + .dsl() + .execute( + "UPDATE game_design_publication_operation SET outcome = 'NO_PUBLICATION', " + + "revision = revision + 1, result_bytes = ? " + + "WHERE publish_workflow_id = ?", + historicalReceipt.toByteArray(), + operation.workflowId()); + }); fixture.completeMigration().run(); var retained = fixture.service().readExact(operation).orElseThrow(); assertThat(retained.outcome()).isEqualTo("NO_PUBLICATION"); @@ -2141,13 +2086,12 @@ private Fixture fixture( properties.setSchema(schema); var versions = new VersionRepository(dsl); Game game = - write.execute( - status -> { - var requested = new Game(); - requested.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); - requested.setName("ISOLATED publication owner"); - return games.save(requested); - }); + write.execute(status -> { + var requested = new Game(); + requested.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + requested.setName("ISOLATED publication owner"); + return games.save(requested); + }); Version version; if (historicalV1) { // Retained pre-V56 rows use the original Version shape and operation framing. @@ -2171,36 +2115,34 @@ private Fixture fixture( if (includeAssetCandidate && !"50.6".equals(migrationTarget)) { var gameAssets = new GameAssetRepository(dsl); asset = - write.execute( - status -> { - var requested = new GameAsset(); - requested.setTenantId(game.getTenantId()); - requested.setFileName(ASSET_FILE_NAME); - requested.setContentType(ASSET_CONTENT_TYPE); - requested.setData(ASSET_BYTES); - return gameAssets.save(requested); - }); + write.execute(status -> { + var requested = new GameAsset(); + requested.setTenantId(game.getTenantId()); + requested.setFileName(ASSET_FILE_NAME); + requested.setContentType(ASSET_CONTENT_TYPE); + requested.setData(ASSET_BYTES); + return gameAssets.save(requested); + }); } GameAsset fixtureAsset = asset; var operation = - write.execute( - status -> { - try { - return historicalV1 - ? IsolatedPublicationOwnerSetup.retainHistoricalV1PreV56( - dsl, target, version.getVersionStateEpoch()) - : IsolatedPublicationOwnerSetup.retainFrozenSourceBacked( - dsl, - target, - version.getVersionStateEpoch(), - "ISOLATED selected source and publication fixture", - List.of( - new IsolatedPublicationOwnerSetup.OrdinaryAsset( - Objects.requireNonNull(fixtureAsset).getId(), ASSET_FILE_NAME))); - } catch (Exception failure) { - throw new IllegalStateException(failure); - } - }); + write.execute(status -> { + try { + return historicalV1 + ? IsolatedPublicationOwnerSetup.retainHistoricalV1PreV56( + dsl, target, version.getVersionStateEpoch()) + : IsolatedPublicationOwnerSetup.retainFrozenSourceBacked( + dsl, + target, + version.getVersionStateEpoch(), + "ISOLATED selected source and publication fixture", + List.of( + new IsolatedPublicationOwnerSetup.OrdinaryAsset( + Objects.requireNonNull(fixtureAsset).getId(), ASSET_FILE_NAME))); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); var operations = new GameDesignPublicationOperationRepository(dsl); var artifacts = new VersionAssetArtifactRepository(dsl); FrozenAssetExportCandidate readCandidate = null; @@ -2214,20 +2156,18 @@ private Fixture fixture( } else { var publicationRepository = new VersionAssetPublicationRepository(dsl); var snapshot = - write.execute( - status -> - publicationRepository.freezeOrReadSnapshot( - game.getTenantId(), version.getVersionNumber())); + write.execute(status -> + publicationRepository.freezeOrReadSnapshot( + game.getTenantId(), version.getVersionNumber())); var artifactService = new VersionAssetArtifactServiceImpl( artifacts, null, versions, null, null, null, null, null, new ObjectMapper()); - write.execute( - status -> - artifactService.stageExport( - game.getTenantId(), - version.getId(), - version.getVersionNumber(), - operation.workflowId())); + write.execute(status -> + artifactService.stageExport( + game.getTenantId(), + version.getId(), + version.getVersionNumber(), + operation.workflowId())); var candidateService = new VersionAssetExportCandidateServiceImpl( versions, @@ -2315,39 +2255,38 @@ private FrozenAssetExportCandidate candidate( private VersionAssetPublicationRepository.ExportSnapshot seedHistoricalAssetSnapshot( DSLContext dsl, TransactionTemplate write, Game game, Version version, GameAsset asset) { String contentDigest = sha256(ASSET_BYTES); - write.executeWithoutResult( - status -> { - dsl.execute( - "INSERT INTO version_asset (tenant_id, version_id, asset_id, usage_key, usage_type) " - + "VALUES (?, ?, ?, ?, ?)", - game.getTenantId(), - version.getId(), - asset.getId(), - ASSET_FILE_NAME, - "logo"); - dsl.execute( - "INSERT INTO version_asset_export_item " - + "(tenant_id, version_id, usage_key, asset_id, content_type, content_hash, byte_size) " - + "VALUES (?, ?, ?, ?, ?, ?, ?)", - game.getTenantId(), - version.getId(), - ASSET_FILE_NAME, - asset.getId(), - ASSET_CONTENT_TYPE, - contentDigest, - (long) ASSET_BYTES.length); - dsl.execute( - "INSERT INTO version_asset_export_snapshot " - + "(tenant_id, version_id, canonical_tenant_id, canonical_version_id, " - + "version_number, captured_version_state_epoch, item_count) " - + "VALUES (?, ?, ?, ?, ?, ?, 1)", - game.getTenantId(), - version.getId(), - version.getCanonicalTenantId(), - version.getCanonicalVersionId(), - version.getVersionNumber(), - version.getVersionStateEpoch()); - }); + write.executeWithoutResult(status -> { + dsl.execute( + "INSERT INTO version_asset (tenant_id, version_id, asset_id, usage_key, usage_type) " + + "VALUES (?, ?, ?, ?, ?)", + game.getTenantId(), + version.getId(), + asset.getId(), + ASSET_FILE_NAME, + "logo"); + dsl.execute( + "INSERT INTO version_asset_export_item " + + "(tenant_id, version_id, usage_key, asset_id, content_type, content_hash, byte_size) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)", + game.getTenantId(), + version.getId(), + ASSET_FILE_NAME, + asset.getId(), + ASSET_CONTENT_TYPE, + contentDigest, + (long) ASSET_BYTES.length); + dsl.execute( + "INSERT INTO version_asset_export_snapshot " + + "(tenant_id, version_id, canonical_tenant_id, canonical_version_id, " + + "version_number, captured_version_state_epoch, item_count) " + + "VALUES (?, ?, ?, ?, ?, ?, 1)", + game.getTenantId(), + version.getId(), + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getVersionNumber(), + version.getVersionStateEpoch()); + }); return new VersionAssetPublicationRepository(dsl) .readFrozenSnapshot(game.getTenantId(), version.getVersionNumber()); } @@ -2367,39 +2306,37 @@ private FrozenAssetExportCandidate seedHistoricalAssetCandidate( String objectProofsJson = historicalObjectProofsJson(requested, mapper); String assetKeysJson = mapper.writeValueAsString(requested.manifest().requiredManifestAssetKeys()); - write.executeWithoutResult( - status -> + write.executeWithoutResult(status -> + dsl.execute( + "INSERT INTO version_asset_artifact " + + "(tenant_id, version_id, exported_version_number, artifact_state, state_epoch, " + + "last_workflow_id, exported_manifest_asset_keys_json) " + + "VALUES (?, ?, ?, 'STAGED', 1, ?, '[]')", + game.getTenantId(), + version.getId(), + version.getVersionNumber(), + operation.workflowId())); + var updated = + write.execute(status -> dsl.execute( - "INSERT INTO version_asset_artifact " - + "(tenant_id, version_id, exported_version_number, artifact_state, state_epoch, " - + "last_workflow_id, exported_manifest_asset_keys_json) " - + "VALUES (?, ?, ?, 'STAGED', 1, ?, '[]')", + "UPDATE version_asset_artifact SET manifest_hash = ?, manifest_schema_version = ?, " + + "artifact_digests_json = ?, published_object_proofs_json = ?, " + + "candidate_snapshot_version_id = ?, candidate_public_base_url = ?, " + + "exported_manifest_asset_keys_json = ?, state_epoch = state_epoch + 1, " + + "updated_at = CURRENT_TIMESTAMP " + + "WHERE tenant_id = ? AND version_id = ? AND artifact_state = 'STAGED' " + + "AND state_epoch = 1 AND manifest_schema_version IS NULL " + + "AND last_workflow_id = ?", + requested.manifest().manifestHash(), + requested.manifest().manifestSchemaVersion(), + artifactDigestsJson, + objectProofsJson, + version.getId(), + requested.publicBaseUrl(), + assetKeysJson, game.getTenantId(), version.getId(), - version.getVersionNumber(), operation.workflowId())); - var updated = - write.execute( - status -> - dsl.execute( - "UPDATE version_asset_artifact SET manifest_hash = ?, manifest_schema_version = ?, " - + "artifact_digests_json = ?, published_object_proofs_json = ?, " - + "candidate_snapshot_version_id = ?, candidate_public_base_url = ?, " - + "exported_manifest_asset_keys_json = ?, state_epoch = state_epoch + 1, " - + "updated_at = CURRENT_TIMESTAMP " - + "WHERE tenant_id = ? AND version_id = ? AND artifact_state = 'STAGED' " - + "AND state_epoch = 1 AND manifest_schema_version IS NULL " - + "AND last_workflow_id = ?", - requested.manifest().manifestHash(), - requested.manifest().manifestSchemaVersion(), - artifactDigestsJson, - objectProofsJson, - version.getId(), - requested.publicBaseUrl(), - assetKeysJson, - game.getTenantId(), - version.getId(), - operation.workflowId())); if (updated == null || updated != 1) { throw new IllegalStateException("HISTORICAL_ASSET_CANDIDATE_WRITE_CONFLICT"); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java index a924b10f07..013630a6f1 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java @@ -170,91 +170,79 @@ void fixedWorldReadsQualifyRealPreexistingOwnersWithoutRewritingOrResolving( actualMountedWorldLeaf) .orElseThrow()); org.mockito.Mockito.clearInvocations(launchDescriptorService); - peerContext.run( - () -> { - assertThat(authorization.authorizeSource(sourceRequest)).isEqualTo(receipt); - assertThat(authorization.authorizeVersion(versionRequest)).isEqualTo(receipt); - var sourceOutput = - new FixedReadObserver< - net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse>(); - new net.firedevops.firemud.gamedesign.service.impl - .RunOwnedFixtureAuthoredWorldSourceReadGrpcService( - authorization, authoredWorldSourceRepository, NAMESPACE) - .resolveAuthoredWorldSource(sourceRequest, sourceOutput); - assertThat(sourceOutput.failure).isNull(); - assertThat(sourceOutput.completed).isTrue(); - assertThat( - net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec - .fromReadResponse( - net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec - .fromReadRequest(NAMESPACE, sourceRequest), - sourceOutput.value)) - .isEqualTo(source); - var versionOutput = - new FixedReadObserver< - net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse>(); - new net.firedevops.firemud.gamedesign.service.impl - .RunOwnedFixtureAuthoredWorldVersionStateGrpcService( - authorization, transactionManager, authoredWorldSourceRepository, NAMESPACE) - .getAuthoredWorldVersionState(versionRequest, versionOutput); - assertThat(versionOutput.failure).isNull(); - assertThat(versionOutput.completed).isTrue(); - var actual = + peerContext.run(() -> { + assertThat(authorization.authorizeSource(sourceRequest)).isEqualTo(receipt); + assertThat(authorization.authorizeVersion(versionRequest)).isEqualTo(receipt); + var sourceOutput = + new FixedReadObserver< + net.firedevops.firemud.gamedesign.v1.ResolveAuthoredWorldSourceResponse>(); + new net.firedevops.firemud.gamedesign.service.impl + .RunOwnedFixtureAuthoredWorldSourceReadGrpcService( + authorization, authoredWorldSourceRepository, NAMESPACE) + .resolveAuthoredWorldSource(sourceRequest, sourceOutput); + assertThat(sourceOutput.failure).isNull(); + assertThat(sourceOutput.completed).isTrue(); + assertThat( + net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.fromReadResponse( + net.firedevops.firemud.common.tenant.AuthoredWorldSourceGrpcCodec.fromReadRequest( + NAMESPACE, sourceRequest), + sourceOutput.value)) + .isEqualTo(source); + var versionOutput = + new FixedReadObserver< + net.firedevops.firemud.gamedesign.v1.GetAuthoredWorldVersionStateResponse>(); + new net.firedevops.firemud.gamedesign.service.impl + .RunOwnedFixtureAuthoredWorldVersionStateGrpcService( + authorization, transactionManager, authoredWorldSourceRepository, NAMESPACE) + .getAuthoredWorldVersionState(versionRequest, versionOutput); + assertThat(versionOutput.failure).isNull(); + assertThat(versionOutput.completed).isTrue(); + var actual = + net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec.fromResponse( net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec - .fromResponse( - net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateGrpcCodec - .fromRequest(versionRequest), - versionOutput.value); - assertThat(actual.sourceEvidence()).isEqualTo(source); - assertThat(actual.versionStateEpoch()) - .isEqualTo(receipt.launchReadEvidence().versionState().getVersionStateEpoch()); - }); + .fromRequest(versionRequest), + versionOutput.value); + assertThat(actual.sourceEvidence()).isEqualTo(source); + assertThat(actual.versionStateEpoch()) + .isEqualTo(receipt.launchReadEvidence().versionState().getVersionStateEpoch()); + }); org.mockito.Mockito.verify(launchDescriptorService, org.mockito.Mockito.never()) .resolveLaunchDescriptor(any()); assertThat(fixedReadOwnerRows()).isEqualTo(before); assertThat(Files.readAllBytes(fixture.receiptPath())).containsExactly(receiptBefore); org.mockito.Mockito.clearInvocations(authoredWorldSourceRepository, launchDescriptorService); - peerContext.run( - () -> { - assertThatThrownBy( - () -> - authorization.authorizeSource( - sourceRequest.toBuilder() - .setOperationId(UUID.randomUUID().toString()) - .build())) - .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - authorization.authorizeSource( - sourceRequest.toBuilder() - .setCanonicalTenantId(UUID.randomUUID().toString()) - .build())) - .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - authorization.authorizeSource( - sourceRequest.toBuilder().setWorldSlug("different-world").build())) - .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - authorization.authorizeVersion( - versionRequest.toBuilder().setTargetNamespace("other").build())) - .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - authorization.authorizeVersion( - versionRequest.toBuilder() - .setVersionId(versionRequest.getVersionId() + 1) - .build())) - .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - authorization.authorizeVersion( - versionRequest.toBuilder() - .setExpectedSourceEvidenceDigest("sha256:" + "f".repeat(64)) - .build())) - .isInstanceOf(SecurityException.class); - }); + peerContext.run(() -> { + assertThatThrownBy(() -> + authorization.authorizeSource( + sourceRequest.toBuilder().setOperationId(UUID.randomUUID().toString()).build())) + .isInstanceOf(SecurityException.class); + assertThatThrownBy(() -> + authorization.authorizeSource( + sourceRequest.toBuilder() + .setCanonicalTenantId(UUID.randomUUID().toString()) + .build())) + .isInstanceOf(SecurityException.class); + assertThatThrownBy(() -> + authorization.authorizeSource( + sourceRequest.toBuilder().setWorldSlug("different-world").build())) + .isInstanceOf(SecurityException.class); + assertThatThrownBy(() -> + authorization.authorizeVersion( + versionRequest.toBuilder().setTargetNamespace("other").build())) + .isInstanceOf(SecurityException.class); + assertThatThrownBy(() -> + authorization.authorizeVersion( + versionRequest.toBuilder() + .setVersionId(versionRequest.getVersionId() + 1) + .build())) + .isInstanceOf(SecurityException.class); + assertThatThrownBy(() -> + authorization.authorizeVersion( + versionRequest.toBuilder() + .setExpectedSourceEvidenceDigest("sha256:" + "f".repeat(64)) + .build())) + .isInstanceOf(SecurityException.class); + }); org.mockito.Mockito.verifyNoInteractions( authoredWorldSourceRepository, launchDescriptorService); assertThat(fixedReadOwnerRows()).isEqualTo(before); @@ -401,57 +389,52 @@ void fixedWorldClientsReadActualProducerOwnersOverMutualTlsWithoutOwnerWrites( fixture.worldManagementCertificatePath(), fixture.worldManagementCertificatePath().resolveSibling("world-management.key"), (sourceClient, versionClient) -> { - assertSocketReadDenied( - () -> - sourceClient.read( - new AuthoredWorldSourceGrpcCodec.ReadRequest( - NAMESPACE, - UUID.randomUUID(), - UUID.randomUUID(), - source.canonicalTenantId(), - source.worldSlug()))); - assertSocketReadDenied( - () -> - sourceClient.read( - new AuthoredWorldSourceGrpcCodec.ReadRequest( - NAMESPACE, - UUID.randomUUID(), - source.operationId(), - UUID.randomUUID(), - source.worldSlug()))); - assertSocketReadDenied( - () -> - sourceClient.read( - new AuthoredWorldSourceGrpcCodec.ReadRequest( - NAMESPACE, - UUID.randomUUID(), - source.operationId(), - source.canonicalTenantId(), - "different-world"))); - assertSocketReadDenied( - () -> - versionClient.read( - new AuthoredWorldVersionStateEvidence.Request( - 1, - NAMESPACE, - UUID.randomUUID(), - source.canonicalTenantId(), - source.worldSlug(), - source.operationId(), - source.evidenceDigest(), - versionRequest.versionId() + 1))); - assertSocketReadDenied( - () -> - versionClient.read( - new AuthoredWorldVersionStateEvidence.Request( - 1, - NAMESPACE, - UUID.randomUUID(), - source.canonicalTenantId(), - source.worldSlug(), - source.operationId(), - "sha256:" + "f".repeat(64), - versionRequest.versionId()))); + assertSocketReadDenied(() -> + sourceClient.read( + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, + UUID.randomUUID(), + UUID.randomUUID(), + source.canonicalTenantId(), + source.worldSlug()))); + assertSocketReadDenied(() -> + sourceClient.read( + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, + UUID.randomUUID(), + source.operationId(), + UUID.randomUUID(), + source.worldSlug()))); + assertSocketReadDenied(() -> + sourceClient.read( + new AuthoredWorldSourceGrpcCodec.ReadRequest( + NAMESPACE, + UUID.randomUUID(), + source.operationId(), + source.canonicalTenantId(), + "different-world"))); + assertSocketReadDenied(() -> + versionClient.read( + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + versionRequest.versionId() + 1))); + assertSocketReadDenied(() -> + versionClient.read( + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + "sha256:" + "f".repeat(64), + versionRequest.versionId()))); }); org.mockito.Mockito.verifyNoInteractions( authoredWorldSourceRepository, launchDescriptorService, fixtureReadback, fixturePolicy); @@ -492,13 +475,12 @@ void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( Path receiptPath = fixture.receiptPath(); new TransactionTemplate(transactionManager) - .execute( - status -> { - seeder.run(new DefaultApplicationArguments(new String[] {})); - assertThat(receiptPath).doesNotExist(); - status.setRollbackOnly(); - return null; - }); + .execute(status -> { + seeder.run(new DefaultApplicationArguments(new String[] {})); + assertThat(receiptPath).doesNotExist(); + status.setRollbackOnly(); + return null; + }); assertThat(receiptPath).doesNotExist(); assertThat(dsl.fetchCount(SOURCE_OPERATIONS, REGISTRATION_REQUEST_ID.eq(fixture.operationId()))) @@ -621,11 +603,9 @@ void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( creation.sourceGameRowId(), creation.sourceGameTenantKey(), creation.provenanceKind()); - assertThatThrownBy( - () -> - new net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationRepository( - dsl) - .readPublishedSet(fixtureTarget)) + assertThatThrownBy(() -> + new net.firedevops.firemud.gamedesign.publication.RealmPolicyPublicationRepository(dsl) + .readPublishedSet(fixtureTarget)) .hasMessageContaining("FIXTURE_POLICY_IS_NOT_HUMAN_PUBLICATION_EVIDENCE"); assertThat( net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec @@ -640,13 +620,12 @@ void publishesExactOwnerReceiptOnlyAfterCommitAndLeavesNoReceiptOnRollback( creation.canonicalTenantId()) .get(0, Long.class)) .isZero(); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_design_published_realm_policy_set " - + "SET fixture_request_digest=? WHERE canonical_tenant_id=?", - "sha256:" + "f".repeat(64), - creation.canonicalTenantId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_design_published_realm_policy_set " + + "SET fixture_request_digest=? WHERE canonical_tenant_id=?", + "sha256:" + "f".repeat(64), + creation.canonicalTenantId())) .hasMessageContaining("fixture policy seal is immutable"); JsonNode sourceJson = envelope.get("sourceEvidence"); assertThat(sourceJson.size()).isEqualTo(13); @@ -846,26 +825,23 @@ void refusesReceiptWhenVersionEpochChangesAfterCommitBeforeOwnerReadback( TransactionTemplate registration = new TransactionTemplate(transactionManager); try { - assertThatThrownBy( - () -> - registration.execute( - status -> { - TransactionSynchronizationManager.registerSynchronization( - new TransactionSynchronization() { - @Override - public int getOrder() { - return Ordered.HIGHEST_PRECEDENCE; - } + assertThatThrownBy(() -> + registration.execute(status -> { + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronization() { + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } - @Override - public void afterCommit() { - writeVersionStateEpoch( - versionMutation, tenantId, versionId, changedEpoch); - } - }); - seeder.run(new DefaultApplicationArguments(new String[] {})); - return null; - })) + @Override + public void afterCommit() { + writeVersionStateEpoch(versionMutation, tenantId, versionId, changedEpoch); + } + }); + seeder.run(new DefaultApplicationArguments(new String[] {})); + return null; + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Run-owned published version does not match its game source"); @@ -1316,13 +1292,8 @@ void policyOwnerRetainsValidatedExactHumanCaptureForeignKey() { GameDesignPublishedRealmPolicySet.GAME_DESIGN_PUBLISHED_REALM_POLICY_SET .getReferences() .stream() - .filter( - reference -> - reference - .getKey() - .getTable() - .getName() - .equals("game_design_realm_policy_capture")) + .filter(reference -> + reference.getKey().getTable().getName().equals("game_design_realm_policy_capture")) .toList(); assertThat(generatedCaptureReferences).hasSize(1); var generatedCaptureReference = generatedCaptureReferences.getFirst(); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java index e7661c3247..3964f23541 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/BrandingSourcePostgresIntegrationTest.java @@ -106,10 +106,9 @@ void actualFreshGenesisMixedSourceApplicationAndRestartReadbackPreserveOriginalH .containsExactly(new GameplayRuleManifest.AdmissionTag("branding-proof")); assertThat(new BrandingSourceRepository(f.dsl).readSnapshot(f.target, UUID.randomUUID())) .isEmpty(); - assertThatThrownBy( - () -> - f.dsl.execute( - "UPDATE game_assets SET data = ? WHERE id = ?", new byte[] {9}, logo.getId())) + assertThatThrownBy(() -> + f.dsl.execute( + "UPDATE game_assets SET data = ? WHERE id = ?", new byte[] {9}, logo.getId())) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThatThrownBy(() -> f.dsl.execute("DELETE FROM game_design_branding_source_revision")) .isInstanceOf(org.jooq.exception.DataAccessException.class); @@ -159,13 +158,12 @@ void v1025RetainedVersionPreservesFiveOwnerHistoryWithoutAcquiringBrandingGenesi "template_config_source"); var originalSourceRows = originalSources.stream() - .map( - name -> - f.dsl.fetchSingle( - "SELECT snapshot_json, xmin::text AS row_xmin FROM game_design_" - + name - + "_snapshot WHERE canonical_version_id = ?", - f.target.canonicalVersionId())) + .map(name -> + f.dsl.fetchSingle( + "SELECT snapshot_json, xmin::text AS row_xmin FROM game_design_" + + name + + "_snapshot WHERE canonical_version_id = ?", + f.target.canonicalVersionId())) .toList(); var sourceJson = originalSourceRows.stream().map(row -> row.get("snapshot_json", String.class)).toList(); @@ -222,15 +220,14 @@ void v1025RetainedVersionPreservesFiveOwnerHistoryWithoutAcquiringBrandingGenesi .isEqualTo(sourceJson); assertThat( originalSources.stream() - .map( - name -> - f.dsl - .fetchSingle( - "SELECT xmin::text AS row_xmin FROM game_design_" - + name - + "_snapshot WHERE canonical_version_id = ?", - f.target.canonicalVersionId()) - .get("row_xmin", String.class)) + .map(name -> + f.dsl + .fetchSingle( + "SELECT xmin::text AS row_xmin FROM game_design_" + + name + + "_snapshot WHERE canonical_version_id = ?", + f.target.canonicalVersionId()) + .get("row_xmin", String.class)) .toList()) .isEqualTo(sourceXmins); var migratedFence = @@ -263,23 +260,19 @@ void v1025RetainedVersionPreservesFiveOwnerHistoryWithoutAcquiringBrandingGenesi .isEqualTo(originalCommit.get("input_digest", String.class)); assertThat(migratedCommit.get("row_xmin", String.class)) .isEqualTo(originalCommit.get("row_xmin", String.class)); - assertThatThrownBy( - () -> - f.tx.execute( - ignored -> new GameDesignSourceRepository(f.dsl).captureSynchronized(original))) + assertThatThrownBy(() -> + f.tx.execute( + ignored -> new GameDesignSourceRepository(f.dsl).captureSynchronized(original))) .isInstanceOf(IllegalStateException.class) .hasMessage("GAME_DESIGN_SOURCE_GENESIS_INCOMPLETE"); assertThat(new BrandingSourceRepository(f.dsl).readGenesis(f.target)).isEmpty(); - assertThatThrownBy( - () -> - f.tx.execute( - ignored -> new BrandingSourceRepository(f.dsl).enrollFreshDraft(f.target))) + assertThatThrownBy(() -> + f.tx.execute(ignored -> new BrandingSourceRepository(f.dsl).enrollFreshDraft(f.target))) .isInstanceOf(IllegalStateException.class) .hasMessage("BRANDING_SOURCE_FRESH_INSERT_UNAVAILABLE"); - assertThatThrownBy( - () -> - f.tx.execute( - ignored -> new BrandingSourceRepository(f.dsl).captureSynchronized(original))) + assertThatThrownBy(() -> + f.tx.execute( + ignored -> new BrandingSourceRepository(f.dsl).captureSynchronized(original))) .isInstanceOf(IllegalStateException.class) .hasMessage("BRANDING_SOURCE_GENESIS_UNAVAILABLE"); assertThatThrownBy(() -> new GameDesignSourceRepository(f.dsl).readGenesis(f.target)) @@ -320,19 +313,18 @@ void retainedV2CaptureWithoutBrandingRemainsReadableAsPartialHistory() throws Ex assertThat(operationAfter.get("request_bytes", byte[].class)).containsExactly(operationBytes); assertThat(operationAfter.get("row_xmin", String.class)) .isEqualTo(operationBefore.get("row_xmin", String.class)); - captureRows.forEach( - (family, before) -> - assertRetainedCapture( - f, - switch (family) { - case "command" -> "game_design_command_source_capture"; - case "realm_policy" -> "game_design_realm_policy_capture"; - case "asset" -> "game_design_asset_source_capture"; - case "template_config" -> "game_design_template_config_source_capture"; - default -> throw new IllegalStateException("Unknown capture family " + family); - }, - operation.workflowId(), - before)); + captureRows.forEach((family, before) -> + assertRetainedCapture( + f, + switch (family) { + case "command" -> "game_design_command_source_capture"; + case "realm_policy" -> "game_design_realm_policy_capture"; + case "asset" -> "game_design_asset_source_capture"; + case "template_config" -> "game_design_template_config_source_capture"; + default -> throw new IllegalStateException("Unknown capture family " + family); + }, + operation.workflowId(), + before)); var retained = new GameDesignSourceRepository(f.dsl).readCapture(operation).orElseThrow(); assertThat(retained.branding()).isEmpty(); @@ -427,50 +419,47 @@ void wrongTenantSourceRowCannotWriteOrExposeSnapshot() { private DraftCommitBinding retainPreBrandingSourceCommit(Fixture f) { var original = binding(f, "0", CommandSource.SCOPE, commandUpsert("BRANDING_HISTORICAL"), policyPayload()); - f.tx.executeWithoutResult( - ignored -> { - var coordinator = new DraftCommitCoordinatorRepository(f.dsl); - coordinator.claim(original); - var policyGenesis = - new RealmPolicySourceRepository(f.dsl).readGenesis(f.target).orElseThrow(); - var commands = new CommandSourceRepository(f.dsl); - var commandGenesis = commands.readNewDraftGenesis(f.target).orElseThrow(); - var assetGenesis = new AssetSourceRepository(f.dsl).readGenesis(f.target).orElseThrow(); - var gameplayGenesis = - new GameplayRuleSourceRepository(f.dsl).readGenesis(f.target).orElseThrow(); - var templateGenesis = - new TemplateConfigSourceRepository(f.dsl).readGenesis(f.target).orElseThrow(); - var reviewedEvidence = - GameDesignReviewedBaseEvidence.genesis( - new GameDesignSourceRepository.Genesis( - policyGenesis, - commandGenesis, - Optional.of(assetGenesis), - Optional.of(gameplayGenesis), - Optional.of(templateGenesis))); - insertReviewedBaseV2(f.dsl, original, reviewedEvidence); - coordinator.claimApplicationSlot(original); - coordinator.markOwnerInProgress( - original, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); - var policies = new RealmPolicySourceRepository(f.dsl); - var command = commands.apply(original).orElseThrow(); - var policy = policies.applyMutation(original); - byte[] siblingEvidence = command.canonicalBytes(); - var appliedEpochs = - List.of( - command.commandAppliedEpoch(), policy.ownerOutcome().appliedEpochs().getFirst()); - policies.recordCombinedOwnerOutcome(original, siblingEvidence, appliedEpochs); - var outcome = policy.combinedOwnerOutcome(siblingEvidence, appliedEpochs); - coordinator.advanceVisibilityFence( - original, - new DraftCommitCoordinatorRepository.CoordinatorProof(original, List.of(outcome))); - commands.captureSynchronized(original); - policies.captureSynchronized(original); - new AssetSourceRepository(f.dsl).captureSynchronized(original); - new GameplayRuleSourceRepository(f.dsl).captureSynchronized(original); - new TemplateConfigSourceRepository(f.dsl).captureSynchronized(original); - coordinator.releaseApplicationSlot(original); - }); + f.tx.executeWithoutResult(ignored -> { + var coordinator = new DraftCommitCoordinatorRepository(f.dsl); + coordinator.claim(original); + var policyGenesis = + new RealmPolicySourceRepository(f.dsl).readGenesis(f.target).orElseThrow(); + var commands = new CommandSourceRepository(f.dsl); + var commandGenesis = commands.readNewDraftGenesis(f.target).orElseThrow(); + var assetGenesis = new AssetSourceRepository(f.dsl).readGenesis(f.target).orElseThrow(); + var gameplayGenesis = + new GameplayRuleSourceRepository(f.dsl).readGenesis(f.target).orElseThrow(); + var templateGenesis = + new TemplateConfigSourceRepository(f.dsl).readGenesis(f.target).orElseThrow(); + var reviewedEvidence = + GameDesignReviewedBaseEvidence.genesis( + new GameDesignSourceRepository.Genesis( + policyGenesis, + commandGenesis, + Optional.of(assetGenesis), + Optional.of(gameplayGenesis), + Optional.of(templateGenesis))); + insertReviewedBaseV2(f.dsl, original, reviewedEvidence); + coordinator.claimApplicationSlot(original); + coordinator.markOwnerInProgress(original, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + var policies = new RealmPolicySourceRepository(f.dsl); + var command = commands.apply(original).orElseThrow(); + var policy = policies.applyMutation(original); + byte[] siblingEvidence = command.canonicalBytes(); + var appliedEpochs = + List.of(command.commandAppliedEpoch(), policy.ownerOutcome().appliedEpochs().getFirst()); + policies.recordCombinedOwnerOutcome(original, siblingEvidence, appliedEpochs); + var outcome = policy.combinedOwnerOutcome(siblingEvidence, appliedEpochs); + coordinator.advanceVisibilityFence( + original, + new DraftCommitCoordinatorRepository.CoordinatorProof(original, List.of(outcome))); + commands.captureSynchronized(original); + policies.captureSynchronized(original); + new AssetSourceRepository(f.dsl).captureSynchronized(original); + new GameplayRuleSourceRepository(f.dsl).captureSynchronized(original); + new TemplateConfigSourceRepository(f.dsl).captureSynchronized(original); + coordinator.releaseApplicationSlot(original); + }); return original; } @@ -480,106 +469,101 @@ private GameDesignPublicationOperation retainPreBrandingV2Capture( var selectedCommit = seed.account().input().selection().selectedCommit(); var world = seed.world(); return Objects.requireNonNull( - f.tx.execute( - ignored -> { - var coordinator = new DraftCommitCoordinatorRepository(f.dsl); - var sources = new GameDesignSourceRepository(f.dsl); - var originalSources = - sources.readSynchronized(f.target, original.commitId()).orElseThrow(); - var originalOutcome = coordinator.read(f.target, original.requestId()).orElseThrow(); - var reviewed = - GameDesignReviewedBaseEvidence.authored(originalSources, originalOutcome); - sources.claimReviewed(selectedCommit, reviewed); - coordinator.claimApplicationSlot(selectedCommit); - coordinator.markOwnerInProgress( - selectedCommit, DraftCommitBinding.Owner.WORLD_MANAGEMENT); - var epochs = - selectedCommit.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new DraftCommitCoordinatorRepository.AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()) - .add(BigInteger.ONE) - .toString())) - .toList(); - var outcome = - new DraftCommitCoordinatorRepository.OwnerOutcome( - DraftCommitBinding.Owner.WORLD_MANAGEMENT, - DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, - selectedCommit.commitId(), - selectedCommit.digest(), - "ISOLATED-world-applied", - world.appliedResultBytes(), - epochs); - coordinator.recordOwnerOutcome(selectedCommit, outcome); - coordinator.advanceVisibilityFence( - selectedCommit, - new DraftCommitCoordinatorRepository.CoordinatorProof( - selectedCommit, List.of(outcome))); - new CommandSourceRepository(f.dsl).captureSynchronized(selectedCommit); - new RealmPolicySourceRepository(f.dsl).captureSynchronized(selectedCommit); - new AssetSourceRepository(f.dsl).captureSynchronized(selectedCommit); - new GameplayRuleSourceRepository(f.dsl).captureSynchronized(selectedCommit); - new TemplateConfigSourceRepository(f.dsl).captureSynchronized(selectedCommit); - coordinator.releaseApplicationSlot(selectedCommit); + f.tx.execute(ignored -> { + var coordinator = new DraftCommitCoordinatorRepository(f.dsl); + var sources = new GameDesignSourceRepository(f.dsl); + var originalSources = + sources.readSynchronized(f.target, original.commitId()).orElseThrow(); + var originalOutcome = coordinator.read(f.target, original.requestId()).orElseThrow(); + var reviewed = GameDesignReviewedBaseEvidence.authored(originalSources, originalOutcome); + sources.claimReviewed(selectedCommit, reviewed); + coordinator.claimApplicationSlot(selectedCommit); + coordinator.markOwnerInProgress( + selectedCommit, DraftCommitBinding.Owner.WORLD_MANAGEMENT); + var epochs = + selectedCommit.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map(unit -> + new DraftCommitCoordinatorRepository.AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(); + var outcome = + new DraftCommitCoordinatorRepository.OwnerOutcome( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + selectedCommit.commitId(), + selectedCommit.digest(), + "ISOLATED-world-applied", + world.appliedResultBytes(), + epochs); + coordinator.recordOwnerOutcome(selectedCommit, outcome); + coordinator.advanceVisibilityFence( + selectedCommit, + new DraftCommitCoordinatorRepository.CoordinatorProof( + selectedCommit, List.of(outcome))); + new CommandSourceRepository(f.dsl).captureSynchronized(selectedCommit); + new RealmPolicySourceRepository(f.dsl).captureSynchronized(selectedCommit); + new AssetSourceRepository(f.dsl).captureSynchronized(selectedCommit); + new GameplayRuleSourceRepository(f.dsl).captureSynchronized(selectedCommit); + new TemplateConfigSourceRepository(f.dsl).captureSynchronized(selectedCommit); + coordinator.releaseApplicationSlot(selectedCommit); - var intent = - new AuthoredDraftPublishSelection.PublishIntent( - f.target.canonicalTenantId(), - f.target.canonicalVersionId(), - UUID.randomUUID().toString(), - "1", - "ISOLATED retained pre-branding source capture", - selectedCommit.requestId(), - selectedCommit.commitId(), - selectedCommit.digest()); - var selection = - new AuthoredDraftPublishSelectionRepository(f.dsl, coordinator) - .reserve(intent) - .selection(); - var selectionBinding = - AuthoredDraftPublishSelectionBinding.fromStored( - selection.canonicalJson(), selection.digest()); - var operation = - IsolatedPublicationOperationFixtures.forSelection(selectionBinding, world); - var attempt = new PublishAttempt(); - attempt.setTenantId(f.target.gameDesignVersionTenantKey()); - attempt.setPublishWorkflowId(operation.workflowId()); - attempt.setPublishType(PublishType.FULL_VERSION); - attempt.setVersionId(f.target.gameDesignVersionRowId()); - attempt.setVersionNumber( - f.dsl - .fetchSingle( - "SELECT version_number FROM version WHERE id = ?", - f.target.gameDesignVersionRowId()) - .get("version_number", Integer.class)); - attempt.setRequestDigest(selection.digest()); - new PublishAttemptRepository(f.dsl).save(attempt); - var operations = new GameDesignPublicationOperationRepository(f.dsl); - operations.reserve(operation); - new CommandSourceRepository(f.dsl).freeze(operation); - new RealmPolicySourceRepository(f.dsl).freeze(operation); - new AssetSourceRepository(f.dsl).freeze(operation); - new TemplateConfigSourceRepository(f.dsl).freeze(operation); - var attempts = new PublishAttemptRepository(f.dsl); - var retainedAttempt = - attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); - retainedAttempt.setStatus(PublishAttemptStatus.FAILED); - retainedAttempt.setFailureCode("ISOLATED_PRE_BRANDING_CAPTURE_HISTORY"); - attempts.save(retainedAttempt); - operations.seal( - operation.tenantKey(), - operation.workflowId(), - operation.versionId(), - operation.selectionDigest(), - false); - return operation; - })); + var intent = + new AuthoredDraftPublishSelection.PublishIntent( + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + UUID.randomUUID().toString(), + "1", + "ISOLATED retained pre-branding source capture", + selectedCommit.requestId(), + selectedCommit.commitId(), + selectedCommit.digest()); + var selection = + new AuthoredDraftPublishSelectionRepository(f.dsl, coordinator) + .reserve(intent) + .selection(); + var selectionBinding = + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()); + var operation = + IsolatedPublicationOperationFixtures.forSelection(selectionBinding, world); + var attempt = new PublishAttempt(); + attempt.setTenantId(f.target.gameDesignVersionTenantKey()); + attempt.setPublishWorkflowId(operation.workflowId()); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setVersionId(f.target.gameDesignVersionRowId()); + attempt.setVersionNumber( + f.dsl + .fetchSingle( + "SELECT version_number FROM version WHERE id = ?", + f.target.gameDesignVersionRowId()) + .get("version_number", Integer.class)); + attempt.setRequestDigest(selection.digest()); + new PublishAttemptRepository(f.dsl).save(attempt); + var operations = new GameDesignPublicationOperationRepository(f.dsl); + operations.reserve(operation); + new CommandSourceRepository(f.dsl).freeze(operation); + new RealmPolicySourceRepository(f.dsl).freeze(operation); + new AssetSourceRepository(f.dsl).freeze(operation); + new TemplateConfigSourceRepository(f.dsl).freeze(operation); + var attempts = new PublishAttemptRepository(f.dsl); + var retainedAttempt = + attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); + retainedAttempt.setStatus(PublishAttemptStatus.FAILED); + retainedAttempt.setFailureCode("ISOLATED_PRE_BRANDING_CAPTURE_HISTORY"); + attempts.save(retainedAttempt); + operations.seal( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + false); + return operation; + })); } private GameDesignPublicationOperation retainFreshV2CaptureWithoutBranding(Fixture f) { @@ -591,26 +575,25 @@ private GameDesignPublicationOperation retainFreshV2CaptureWithoutBranding(Fixtu policyPayload()); apply(f, sourceCommit); return Objects.requireNonNull( - f.tx.execute( - ignored -> { - try { - var operation = - IsolatedPublicationOwnerSetup.retainSourceBacked( - f.dsl, - f.target, - 1, - "ISOLATED enrolled partial capture without branding", - sourceCommit.commitId().toString()); - new CommandSourceRepository(f.dsl).freeze(operation); - new RealmPolicySourceRepository(f.dsl).freeze(operation); - new AssetSourceRepository(f.dsl).freeze(operation); - new GameplayRuleSourceRepository(f.dsl).freeze(operation); - new TemplateConfigSourceRepository(f.dsl).freeze(operation); - return operation; - } catch (Exception failure) { - throw new IllegalStateException(failure); - } - })); + f.tx.execute(ignored -> { + try { + var operation = + IsolatedPublicationOwnerSetup.retainSourceBacked( + f.dsl, + f.target, + 1, + "ISOLATED enrolled partial capture without branding", + sourceCommit.commitId().toString()); + new CommandSourceRepository(f.dsl).freeze(operation); + new RealmPolicySourceRepository(f.dsl).freeze(operation); + new AssetSourceRepository(f.dsl).freeze(operation); + new GameplayRuleSourceRepository(f.dsl).freeze(operation); + new TemplateConfigSourceRepository(f.dsl).freeze(operation); + return operation; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + })); } private RetainedCapture retainedCapture(Fixture f, String table, String workflowId) { @@ -664,25 +647,23 @@ private static void insertReviewedBaseV2( } private void apply(Fixture f, DraftCommitBinding binding) { - f.tx.executeWithoutResult( - ignored -> { - var sources = new GameDesignSourceRepository(f.dsl); - sources.claimReviewed( - binding, - new GameDesignReviewedBaseRepository(f.dsl) - .resolve(f.target, DraftBaseReference.parse(binding.baseCommitId()))); - var coordinator = new DraftCommitCoordinatorRepository(f.dsl); - coordinator.claimApplicationSlot(binding); - coordinator.markOwnerInProgress( - binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); - var applied = sources.apply(binding); - coordinator.advanceSourceVisibilityFence( - binding, - new DraftCommitCoordinatorRepository.CoordinatorProof( - binding, List.of(applied.ownerOutcome()))); - sources.captureSynchronized(binding); - coordinator.releaseApplicationSlot(binding); - }); + f.tx.executeWithoutResult(ignored -> { + var sources = new GameDesignSourceRepository(f.dsl); + sources.claimReviewed( + binding, + new GameDesignReviewedBaseRepository(f.dsl) + .resolve(f.target, DraftBaseReference.parse(binding.baseCommitId()))); + var coordinator = new DraftCommitCoordinatorRepository(f.dsl); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress(binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + var applied = sources.apply(binding); + coordinator.advanceSourceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, List.of(applied.ownerOutcome()))); + sources.captureSynchronized(binding); + coordinator.releaseApplicationSlot(binding); + }); } private static String commandUpsert(String commandId) { @@ -718,15 +699,14 @@ private DraftCommitBinding binding( } var units = scopes.stream() - .map( - scope -> - new DraftCommitBinding.AffectedUnit( - DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, - scope, - f.target.canonicalVersionId().toString(), - scope, - "effective", - scope.equals(primaryScope) ? epoch : "0")) + .map(scope -> + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + scope, + f.target.canonicalVersionId().toString(), + scope, + "effective", + scope.equals(primaryScope) ? epoch : "0")) .toList(); return DraftCommitBinding.create( f.target, UUID.randomUUID(), UUID.randomUUID(), currentBaseReference(f), revisions, units); @@ -801,48 +781,44 @@ private Fixture fixture(String maximumMigration) { version.setVersionStateEpoch(1L); var saved = Objects.requireNonNull( - tx.execute( - ignored -> { - if (maximumMigration == null) return new VersionRepository(dsl).save(version); - // Retained fixture uses the V1025 producer transaction, with every then-current - // source genesis except Branding deliberately enrolled. - long id = - dsl.fetchSingle( - "INSERT INTO version (tenant_id, canonical_tenant_id, canonical_version_id, identity_source_game_row_id, identity_source_game_tenant_key, identity_source_provenance_kind, version_number, version_state, version_state_epoch, is_script_only, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'NEW_GAME_ROW', 1, 'DRAFT', 1, FALSE, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) RETURNING id", - savedGame.getTenantId(), - savedGame.getCanonicalTenantId(), - UUID.randomUUID(), - savedGame.getId(), - savedGame.getTenantId()) - .get(0, Long.class); - var retained = new VersionRepository(dsl).findById(id).orElseThrow(); - var oldTarget = - new DraftCommitBinding.TargetProof( - retained.getCanonicalTenantId(), - retained.getCanonicalVersionId(), - id, - retained.getTenantId(), - retained.getIdentitySourceGameRowId(), - retained.getIdentitySourceGameTenantKey(), - retained.getIdentitySourceProvenanceKind()); - var policy = - new net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository( - dsl) - .recordFreshGenesis(oldTarget); - new net.firedevops.firemud.gamedesign.publication.CommandSourceRepository(dsl) - .enrollNewDraftGenesis( - new CommandSource.NewDraftGenesisReceipt( - oldTarget, policy.receiptId(), policy.creationTransactionId())); - new net.firedevops.firemud.gamedesign.publication.AssetSourceRepository(dsl) - .enrollFreshDraft(oldTarget); - new net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository( - dsl) - .enrollFreshDraft(oldTarget); - new net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository( - dsl) - .enrollFreshDraft(oldTarget); - return retained; - })); + tx.execute(ignored -> { + if (maximumMigration == null) return new VersionRepository(dsl).save(version); + // Retained fixture uses the V1025 producer transaction, with every then-current + // source genesis except Branding deliberately enrolled. + long id = + dsl.fetchSingle( + "INSERT INTO version (tenant_id, canonical_tenant_id, canonical_version_id, identity_source_game_row_id, identity_source_game_tenant_key, identity_source_provenance_kind, version_number, version_state, version_state_epoch, is_script_only, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'NEW_GAME_ROW', 1, 'DRAFT', 1, FALSE, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP) RETURNING id", + savedGame.getTenantId(), + savedGame.getCanonicalTenantId(), + UUID.randomUUID(), + savedGame.getId(), + savedGame.getTenantId()) + .get(0, Long.class); + var retained = new VersionRepository(dsl).findById(id).orElseThrow(); + var oldTarget = + new DraftCommitBinding.TargetProof( + retained.getCanonicalTenantId(), + retained.getCanonicalVersionId(), + id, + retained.getTenantId(), + retained.getIdentitySourceGameRowId(), + retained.getIdentitySourceGameTenantKey(), + retained.getIdentitySourceProvenanceKind()); + var policy = + new net.firedevops.firemud.gamedesign.publication.RealmPolicySourceRepository(dsl) + .recordFreshGenesis(oldTarget); + new net.firedevops.firemud.gamedesign.publication.CommandSourceRepository(dsl) + .enrollNewDraftGenesis( + new CommandSource.NewDraftGenesisReceipt( + oldTarget, policy.receiptId(), policy.creationTransactionId())); + new net.firedevops.firemud.gamedesign.publication.AssetSourceRepository(dsl) + .enrollFreshDraft(oldTarget); + new net.firedevops.firemud.gamedesign.publication.GameplayRuleSourceRepository(dsl) + .enrollFreshDraft(oldTarget); + new net.firedevops.firemud.gamedesign.publication.TemplateConfigSourceRepository(dsl) + .enrollFreshDraft(oldTarget); + return retained; + })); var target = new DraftCommitBinding.TargetProof( saved.getCanonicalTenantId(), diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomePostgresIntegrationTest.java index a070e577b4..39facffa36 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignDraftTerminalOutcomePostgresIntegrationTest.java @@ -116,15 +116,13 @@ void committedOutcomeIsAtomicWithSynchronizedFenceAndCompleteOwnerVector() { List outcomes = beginAndApplyOwners(binding, account, null); - fixture.inTransaction( - () -> { - fixture - .coordinator() - .advanceVisibilityFence( - binding, - new DraftCommitCoordinatorRepository.CoordinatorProof(binding, outcomes)); - return null; - }); + fixture.inTransaction(() -> { + fixture + .coordinator() + .advanceVisibilityFence( + binding, new DraftCommitCoordinatorRepository.CoordinatorProof(binding, outcomes)); + return null; + }); GameDesignDraftTerminalOutcome readback = new GameDesignDraftTerminalOutcomeRepository(fixture.dsl()) @@ -160,34 +158,29 @@ void committedOutcomeIsAtomicWithSynchronizedFenceAndCompleteOwnerVector() { "changed-original-account-bytes"); assertThatThrownBy(() -> storedOwnerReadback.requireBinding(changedAccount)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new GameDesignDraftTerminalOutcomeRepository(fixture.dsl()) - .readAccountBound(changedAccount.canonicalBytes())) + assertThatThrownBy(() -> + new GameDesignDraftTerminalOutcomeRepository(fixture.dsl()) + .readAccountBound(changedAccount.canonicalBytes())) .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitIdentityConflictException.class); - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> { - fixture - .dsl() - .execute( - "UPDATE game_design_draft_terminal_outcome " - + "SET terminal_evidence_digest = ? WHERE operation_id = ?", - "sha256:" + "0".repeat(64), - account.operationId()); - return null; - })) + assertThatThrownBy(() -> + fixture.inTransaction(() -> { + fixture + .dsl() + .execute( + "UPDATE game_design_draft_terminal_outcome " + + "SET terminal_evidence_digest = ? WHERE operation_id = ?", + "sha256:" + "0".repeat(64), + account.operationId()); + return null; + })) .isInstanceOf(RuntimeException.class); - fixture.inTransaction( - () -> { - fixture - .coordinator() - .advanceVisibilityFence( - binding, - new DraftCommitCoordinatorRepository.CoordinatorProof(binding, outcomes)); - return null; - }); + fixture.inTransaction(() -> { + fixture + .coordinator() + .advanceVisibilityFence( + binding, new DraftCommitCoordinatorRepository.CoordinatorProof(binding, outcomes)); + return null; + }); assertThat( new GameDesignDraftTerminalOutcomeRepository(fixture.dsl()) .readAccountBound(account.canonicalBytes()) @@ -208,11 +201,10 @@ void abortRetainsMixedAppliedAndRejectedParticipantsAndDeniesLateWriters() { byte[] abortEvidence = "stipulated exact final-abort producer evidence".getBytes(StandardCharsets.UTF_8); - fixture.inTransaction( - () -> { - fixture.coordinator().recordDefinitiveFinalAbort(binding, abortEvidence); - return null; - }); + fixture.inTransaction(() -> { + fixture.coordinator().recordDefinitiveFinalAbort(binding, abortEvidence); + return null; + }); GameDesignDraftTerminalOutcome readback = new GameDesignDraftTerminalOutcomeRepository(fixture.dsl()) @@ -245,34 +237,27 @@ void abortRetainsMixedAppliedAndRejectedParticipantsAndDeniesLateWriters() { assertThatThrownBy( () -> fixture.inTransaction(() -> fixture.coordinator().claim(binding, account))) .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> - fixture.coordinator().markOwnerInProgress(binding, Owner.WORLD_MANAGEMENT))) + assertThatThrownBy(() -> + fixture.inTransaction( + () -> fixture.coordinator().markOwnerInProgress(binding, Owner.WORLD_MANAGEMENT))) .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> - fixture - .coordinator() - .recordOwnerOutcome( - binding, appliedOutcome(binding, Owner.WORLD_MANAGEMENT)))) + assertThatThrownBy(() -> + fixture.inTransaction(() -> + fixture + .coordinator() + .recordOwnerOutcome(binding, appliedOutcome(binding, Owner.WORLD_MANAGEMENT)))) .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); assertThatThrownBy( () -> fixture.inTransaction(() -> fixture.coordinator().claimApplicationSlot(binding))) .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> - fixture - .coordinator() - .advanceVisibilityFence( - binding, - new DraftCommitCoordinatorRepository.CoordinatorProof( - binding, allAppliedOutcomes(binding))))) + assertThatThrownBy(() -> + fixture.inTransaction(() -> + fixture + .coordinator() + .advanceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, allAppliedOutcomes(binding))))) .isInstanceOf(DraftCommitCoordinatorRepository.DraftCommitStateConflictException.class); } @@ -290,30 +275,25 @@ void terminalCommitAndAbortRaceHasOneSameVersionWinner() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(2); try { Future commit = - executor.submit( - () -> { - awaitStart(ready, start); - return attempt( - () -> - fixture - .coordinator() - .advanceVisibilityFence( - binding, - new DraftCommitCoordinatorRepository.CoordinatorProof( - binding, outcomes))); - }); + executor.submit(() -> { + awaitStart(ready, start); + return attempt(() -> + fixture + .coordinator() + .advanceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof(binding, outcomes))); + }); Future abort = - executor.submit( - () -> { - awaitStart(ready, start); - return attempt( - () -> - fixture - .coordinator() - .recordDefinitiveFinalAbort( - binding, - "stipulated race-abort evidence".getBytes(StandardCharsets.UTF_8))); - }); + executor.submit(() -> { + awaitStart(ready, start); + return attempt(() -> + fixture + .coordinator() + .recordDefinitiveFinalAbort( + binding, + "stipulated race-abort evidence".getBytes(StandardCharsets.UTF_8))); + }); await(ready); start.countDown(); FinalizeAttempt commitResult = commit.get(20, TimeUnit.SECONDS); @@ -345,15 +325,14 @@ void rollbackCannotLeaveAVisibilityFenceWithoutItsTerminalOutcome() { fixture .transaction() - .executeWithoutResult( - status -> { - fixture - .coordinator() - .advanceVisibilityFence( - binding, - new DraftCommitCoordinatorRepository.CoordinatorProof(binding, outcomes)); - status.setRollbackOnly(); - }); + .executeWithoutResult(status -> { + fixture + .coordinator() + .advanceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof(binding, outcomes)); + status.setRollbackOnly(); + }); assertThat(new GameDesignDraftTerminalOutcomeRepository(fixture.dsl()).read(operation)) .isEmpty(); @@ -376,11 +355,10 @@ void rollbackCannotLeaveFinalAbortTombstoneWithoutItsTerminalOutcome() { fixture .transaction() - .executeWithoutResult( - status -> { - fixture.coordinator().recordDefinitiveFinalAbort(binding, abortEvidence); - status.setRollbackOnly(); - }); + .executeWithoutResult(status -> { + fixture.coordinator().recordDefinitiveFinalAbort(binding, abortEvidence); + status.setRollbackOnly(); + }); assertThat(new GameDesignDraftTerminalOutcomeRepository(fixture.dsl()).read(operation)) .isEmpty(); @@ -408,79 +386,78 @@ void migrationDoesNotInventAccountOutcomesForRetainedStatusOnlyRows() { legacy.inTransaction(() -> legacy.coordinator().claim(binding)); legacy .transaction() - .executeWithoutResult( - status -> { - legacy - .dsl() - .execute( - "UPDATE game_design_draft_commit SET workflow_state = 'APPLYING' " - + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ?", - target.canonicalTenantId(), - target.canonicalVersionId(), - binding.requestId()); - for (DraftCommitCoordinatorRepository.OwnerOutcome outcome : outcomes) { - legacy - .dsl() - .execute( - "UPDATE game_design_draft_commit_owner_result SET status = 'IN_PROGRESS', " - + "updated_at = CURRENT_TIMESTAMP WHERE canonical_tenant_id = ? " - + "AND canonical_version_id = ? AND request_id = ? AND owner = ?", - target.canonicalTenantId(), - target.canonicalVersionId(), - binding.requestId(), - outcome.owner().name()); - legacy - .dsl() - .execute( - "UPDATE game_design_draft_commit_owner_result SET status = 'APPLIED', " - + "result_commit_id = ?, result_binding_digest = ?, result_identity = ?, " - + "result_bytes = ?, applied_units_json = ?, updated_at = CURRENT_TIMESTAMP " - + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " - + "AND request_id = ? AND owner = ?", - outcome.commitId(), - outcome.bindingDigest(), - outcome.resultIdentity(), - outcome.resultBytes(), - appliedEpochsJson(outcome.appliedEpochs()), - target.canonicalTenantId(), - target.canonicalVersionId(), - binding.requestId(), - outcome.owner().name()); - } - String vector = ownerVectorJson(binding, outcomes); - legacy - .dsl() - .execute( - "INSERT INTO game_design_draft_commit_visibility_fence " - + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, " - + "input_digest, result_vector_json) VALUES (?, ?, ?, ?, ?, ?)", - target.canonicalTenantId(), - target.canonicalVersionId(), - binding.requestId(), - binding.commitId(), - binding.digest(), - vector); - legacy - .dsl() - .execute( - "INSERT INTO game_design_draft_commit_visibility " - + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, input_digest) " - + "VALUES (?, ?, ?, ?, ?)", - target.canonicalTenantId(), - target.canonicalVersionId(), - binding.requestId(), - binding.commitId(), - binding.digest()); - legacy - .dsl() - .execute( - "UPDATE game_design_draft_commit SET workflow_state = 'SYNCHRONIZED', " - + "updated_at = CURRENT_TIMESTAMP WHERE canonical_tenant_id = ? " - + "AND canonical_version_id = ? AND request_id = ?", - target.canonicalTenantId(), - target.canonicalVersionId(), - binding.requestId()); - }); + .executeWithoutResult(status -> { + legacy + .dsl() + .execute( + "UPDATE game_design_draft_commit SET workflow_state = 'APPLYING' " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? AND request_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId()); + for (DraftCommitCoordinatorRepository.OwnerOutcome outcome : outcomes) { + legacy + .dsl() + .execute( + "UPDATE game_design_draft_commit_owner_result SET status = 'IN_PROGRESS', " + + "updated_at = CURRENT_TIMESTAMP WHERE canonical_tenant_id = ? " + + "AND canonical_version_id = ? AND request_id = ? AND owner = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId(), + outcome.owner().name()); + legacy + .dsl() + .execute( + "UPDATE game_design_draft_commit_owner_result SET status = 'APPLIED', " + + "result_commit_id = ?, result_binding_digest = ?, result_identity = ?, " + + "result_bytes = ?, applied_units_json = ?, updated_at = CURRENT_TIMESTAMP " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ? " + + "AND request_id = ? AND owner = ?", + outcome.commitId(), + outcome.bindingDigest(), + outcome.resultIdentity(), + outcome.resultBytes(), + appliedEpochsJson(outcome.appliedEpochs()), + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId(), + outcome.owner().name()); + } + String vector = ownerVectorJson(binding, outcomes); + legacy + .dsl() + .execute( + "INSERT INTO game_design_draft_commit_visibility_fence " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, " + + "input_digest, result_vector_json) VALUES (?, ?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest(), + vector); + legacy + .dsl() + .execute( + "INSERT INTO game_design_draft_commit_visibility " + + "(canonical_tenant_id, canonical_version_id, request_id, commit_id, input_digest) " + + "VALUES (?, ?, ?, ?, ?)", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId(), + binding.commitId(), + binding.digest()); + legacy + .dsl() + .execute( + "UPDATE game_design_draft_commit SET workflow_state = 'SYNCHRONIZED', " + + "updated_at = CURRENT_TIMESTAMP WHERE canonical_tenant_id = ? " + + "AND canonical_version_id = ? AND request_id = ?", + target.canonicalTenantId(), + target.canonicalVersionId(), + binding.requestId()); + }); legacy.migrateToLatest(); var retained = legacy.coordinator().read(target, binding.requestId()).orElseThrow(); @@ -503,21 +480,19 @@ private static List beginAndApply fixture.inTransaction(() -> fixture.coordinator().claim(binding, account)); List outcomes = binding.requiredOwners().stream() - .map( - owner -> - owner == rejectedOwner - ? rejectedOutcome(binding, owner) - : appliedOutcome(binding, owner)) + .map(owner -> + owner == rejectedOwner + ? rejectedOutcome(binding, owner) + : appliedOutcome(binding, owner)) .toList(); - fixture.inTransaction( - () -> { - fixture.coordinator().claimApplicationSlot(binding); - for (DraftCommitCoordinatorRepository.OwnerOutcome outcome : outcomes) { - fixture.coordinator().markOwnerInProgress(binding, outcome.owner()); - fixture.coordinator().recordOwnerOutcome(binding, outcome); - } - return null; - }); + fixture.inTransaction(() -> { + fixture.coordinator().claimApplicationSlot(binding); + for (DraftCommitCoordinatorRepository.OwnerOutcome outcome : outcomes) { + fixture.coordinator().markOwnerInProgress(binding, outcome.owner()); + fixture.coordinator().recordOwnerOutcome(binding, outcome); + } + return null; + }); return outcomes; } @@ -530,15 +505,14 @@ private static DraftCommitCoordinatorRepository.OwnerOutcome appliedOutcome( DraftCommitBinding binding, Owner owner) { List epochs = binding.affectedUnits(owner).stream() - .map( - unit -> - new DraftCommitCoordinatorRepository.AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .map(unit -> + new DraftCommitCoordinatorRepository.AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) .toList(); return new DraftCommitCoordinatorRepository.OwnerOutcome( owner, @@ -772,23 +746,22 @@ TargetProof newHistoricalTarget() { UUID canonicalVersionId = UUID.randomUUID(); org.jooq.Record savedVersion = Objects.requireNonNull( - transaction.execute( - status -> - dsl.resultQuery( - "INSERT INTO version (tenant_id, canonical_version_id, canonical_tenant_id, " - + "identity_source_game_row_id, identity_source_game_tenant_key, " - + "identity_source_provenance_kind, version_number, version_state, " - + "version_state_epoch, script_patch_version, base_version_id, " - + "is_script_only, notes) SELECT g.tenant_id, ?, g.canonical_tenant_id, " - + "g.id, g.tenant_id, g.tenant_identity_provenance_kind, 1, 'DRAFT', " - + "1, NULL, NULL, FALSE, ? FROM game g WHERE g.id = ? RETURNING " - + "id, tenant_id, canonical_tenant_id, canonical_version_id, " - + "identity_source_game_row_id, identity_source_game_tenant_key, " - + "identity_source_provenance_kind", - canonicalVersionId, - "V50.4 retained status-only migration fixture", - savedGame.getId()) - .fetchOne())); + transaction.execute(status -> + dsl.resultQuery( + "INSERT INTO version (tenant_id, canonical_version_id, canonical_tenant_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind, version_number, version_state, " + + "version_state_epoch, script_patch_version, base_version_id, " + + "is_script_only, notes) SELECT g.tenant_id, ?, g.canonical_tenant_id, " + + "g.id, g.tenant_id, g.tenant_identity_provenance_kind, 1, 'DRAFT', " + + "1, NULL, NULL, FALSE, ? FROM game g WHERE g.id = ? RETURNING " + + "id, tenant_id, canonical_tenant_id, canonical_version_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind", + canonicalVersionId, + "V50.4 retained status-only migration fixture", + savedGame.getId()) + .fetchOne())); return new TargetProof( savedVersion.get("canonical_tenant_id", UUID.class), savedVersion.get("canonical_version_id", UUID.class), diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java index 935c9fc284..990b6d8ef8 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java @@ -81,26 +81,22 @@ class GameDesignSourcePostgresIntegrationTest { void exactReviewedClaimReplayPreservesAllRetainedRowsAndChangedInputCannotRewriteThem() { var local = fixture(); var original = storageBinding(local, "reviewed-claim"); - local.tx( - () -> { - claimStorageBinding(local, original); - return null; - }); + local.tx(() -> { + claimStorageBinding(local, original); + return null; + }); var retained = reviewedClaimRows(local); - local.tx( - () -> { - claimStorageBinding(local, original); - return null; - }); + local.tx(() -> { + claimStorageBinding(local, original); + return null; + }); assertThat(reviewedClaimRows(local)).isEqualTo(retained); var changed = changedClaimInput(original); - assertThatThrownBy( - () -> - local.tx( - () -> { - claimStorageBinding(local, changed); - return null; - })) + assertThatThrownBy(() -> + local.tx(() -> { + claimStorageBinding(local, changed); + return null; + })) .isInstanceOf(IllegalArgumentException.class) .hasMessage("REVIEWED_BASE_STORED_BINDING_CONFLICT"); assertThat(reviewedClaimRows(local)).isEqualTo(retained); @@ -113,11 +109,10 @@ void reviewedClaimAndItsOwnerInventoryRollBackWithoutRetainingReviewEvidence() { var binding = storageBinding(local, "rolled-back-reviewed-claim"); local .write() - .executeWithoutResult( - status -> { - claimStorageBinding(local, binding); - status.setRollbackOnly(); - }); + .executeWithoutResult(status -> { + claimStorageBinding(local, binding); + status.setRollbackOnly(); + }); assertThat(local.coordinator().read(local.target(), binding.requestId())).isEmpty(); assertThat(new GameDesignReviewedBaseRepository(local.dsl()).read(binding)).isEmpty(); assertThat(local.coordinator().readApplicationSlot(local.target())).isEmpty(); @@ -136,11 +131,10 @@ void concurrentExactReviewedClaimsConvergeOnOneBindingAndOwnerInventory() throws var binding = storageBinding(local, "concurrent-exact-reviewed"); var claims = concurrentReviewedClaims(local, binding, binding); assertThat(claims) - .allSatisfy( - claim -> { - assertThat(claim.failure()).isNull(); - assertThat(claim.binding()).isEqualTo(binding); - }); + .allSatisfy(claim -> { + assertThat(claim.failure()).isNull(); + assertThat(claim.binding()).isEqualTo(binding); + }); assertReviewedClaimInventory(local, binding); } @@ -211,12 +205,11 @@ private static void assertReviewedClaimInventory(Fixture local, DraftCommitBindi assertThat(persisted.binding().canonicalBytes()).containsExactly(binding.canonicalBytes()); assertThat(persisted.ownerStates()).containsOnlyKeys(Owner.GAME_DESIGN_CONTROL_PLANE); assertThat(persisted.ownerStates().values()) - .allSatisfy( - state -> { - assertThat(state.status()) - .isEqualTo(DraftCommitCoordinatorRepository.OwnerStatus.NOT_ATTEMPTED); - assertThat(state.outcome()).isEmpty(); - }); + .allSatisfy(state -> { + assertThat(state.status()) + .isEqualTo(DraftCommitCoordinatorRepository.OwnerStatus.NOT_ATTEMPTED); + assertThat(state.outcome()).isEmpty(); + }); assertThat(new GameDesignReviewedBaseRepository(local.dsl()).read(binding)).isPresent(); assertThat(local.coordinator().readApplicationSlot(local.target())).isEmpty(); for (String table : @@ -253,15 +246,14 @@ private static ReviewedClaimAttempt reviewedClaimAttempt( throw new IllegalStateException("Reviewed claim launch timed out"); try { var persisted = - local.tx( - () -> { - claimStorageBinding(local, binding); - return local - .coordinator() - .read(local.target(), binding.requestId()) - .orElseThrow() - .binding(); - }); + local.tx(() -> { + claimStorageBinding(local, binding); + return local + .coordinator() + .read(local.target(), binding.requestId()) + .orElseThrow() + .binding(); + }); return new ReviewedClaimAttempt(persisted, null); } catch (RuntimeException failure) { return new ReviewedClaimAttempt(null, failure); @@ -272,11 +264,10 @@ private static DraftCommitBinding soleReviewedClaimWinner(List claim.failure() == null)).hasSize(1); assertThat(claims.stream().filter(claim -> claim.failure() != null)) .singleElement() - .satisfies( - claim -> - assertThat(claim.failure()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("REVIEWED_BASE_STORED_BINDING_CONFLICT")); + .satisfies(claim -> + assertThat(claim.failure()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("REVIEWED_BASE_STORED_BINDING_CONFLICT")); return claims.stream() .filter(claim -> claim.failure() == null) .findFirst() @@ -339,28 +330,25 @@ private static void assertFirstReferenceRejectsStaleUpdate(boolean branding, boo .get(0, byte[].class)) .containsExactly(bytes); if (branding) { - fixture.tx( - () -> { - applyBrandingFirstReference(fixture, assetId); - return null; - }); + fixture.tx(() -> { + applyBrandingFirstReference(fixture, assetId); + return null; + }); } else { - fixture.tx( - () -> - IsolatedAssetSourceOwnerSetup.upsert( - fixture.dsl(), fixture.target(), assetId, "logo.bin")); + fixture.tx(() -> + IsolatedAssetSourceOwnerSetup.upsert( + fixture.dsl(), fixture.target(), assetId, "logo.bin")); } assertThat(fixture.dsl().fetchCount(DSL.table(history))).isEqualTo(1); // A still sees the pre-reference history, so a row version fence must reject its write. assertThat(staleDsl.fetchCount(DSL.table(history))).isZero(); - assertThatThrownBy( - () -> - staleDsl.execute( - metadata - ? "UPDATE game_assets SET content_type = ? WHERE id = ?" - : "UPDATE game_assets SET data = ? WHERE id = ?", - metadata ? "image/png" : new byte[] {9}, - assetId)) + assertThatThrownBy(() -> + staleDsl.execute( + metadata + ? "UPDATE game_assets SET content_type = ? WHERE id = ?" + : "UPDATE game_assets SET data = ? WHERE id = ?", + metadata ? "image/png" : new byte[] {9}, + assetId)) .rootCause() .isInstanceOfSatisfying( PSQLException.class, failure -> assertThat(failure.getSQLState()).isEqualTo("40001")); @@ -557,13 +545,11 @@ void ordinaryAssetSourceProjectsInheritedAndDeletedReferencesThroughCoordinatorF command.commitId().toString(), "0", AssetSource.deletePayload("logo.bin")); - assertThatThrownBy( - () -> - fixture.tx( - () -> { - start(fixture, staleDelete); - return fixture.sources().apply(staleDelete); - })) + assertThatThrownBy(() -> + fixture.tx(() -> { + start(fixture, staleDelete); + return fixture.sources().apply(staleDelete); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("ASSET_SOURCE_EPOCH_CONFLICT"); assertThat(fixture.coordinator().readApplicationSlot(fixture.target())).isEmpty(); @@ -656,13 +642,12 @@ private static void assertAssetMutationDenied( assertThatThrownBy(mutation::run) .rootCause() .isInstanceOf(PSQLException.class) - .satisfies( - cause -> { - PSQLException postgresException = (PSQLException) cause; - assertThat(postgresException.getSQLState()).isEqualTo("23514"); - assertThat(postgresException.getServerErrorMessage().getMessage()) - .isEqualTo("ordinary asset source bytes are immutable from source history"); - }); + .satisfies(cause -> { + PSQLException postgresException = (PSQLException) cause; + assertThat(postgresException.getSQLState()).isEqualTo("23514"); + assertThat(postgresException.getServerErrorMessage().getMessage()) + .isEqualTo("ordinary asset source bytes are immutable from source history"); + }); assertThat( fixture.sources().readSynchronized(fixture.target(), binding.commitId()).orElseThrow()) .isEqualTo(snapshot); @@ -816,18 +801,14 @@ void sourceApplicationsRequireReservedReviewedBaseBeforeEitherOwnerCanWrite() { private static void assertMissingReviewedBaseDeniesOwnerApply( Fixture fixture, DraftCommitBinding binding, Runnable ownerApply) { var genesis = fixture.sources().readGenesis(fixture.target()).orElseThrow(); - assertThatThrownBy( - () -> - fixture.tx( - () -> { - fixture.coordinator().claim(binding); - fixture.coordinator().claimApplicationSlot(binding); - fixture - .coordinator() - .markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); - ownerApply.run(); - return null; - })) + assertThatThrownBy(() -> + fixture.tx(() -> { + fixture.coordinator().claim(binding); + fixture.coordinator().claimApplicationSlot(binding); + fixture.coordinator().markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + ownerApply.run(); + return null; + })) .hasMessageContaining("Draft source application requires exact reviewed base evidence"); assertThat(fixture.sources().readGenesis(fixture.target())).contains(genesis); @@ -860,11 +841,10 @@ void sourceRollbackIncompleteScopesAndPublicationCaptureFailClosed() { start(fixture, incomplete); fixture .write() - .executeWithoutResult( - status -> { - fixture.sources().apply(incomplete); - status.setRollbackOnly(); - }); + .executeWithoutResult(status -> { + fixture.sources().apply(incomplete); + status.setRollbackOnly(); + }); assertThat(fixture.dsl().fetchCount(DSL.table("game_design_realm_policy_application"))) .isZero(); assertThat( @@ -904,20 +884,19 @@ void sourceRollbackIncompleteScopesAndPublicationCaptureFailClosed() { .hasMessageContaining("Complete supported Game Design source scopes"); var operation = - fixture.tx( - () -> { - try { - var retained = - IsolatedPublicationOwnerSetup.retainSourceBacked( - fixture.dsl(), fixture.target(), 1); - fixture - .sources() - .captureSynchronized(retained.account().input().selection().selectedCommit()); - return retained; - } catch (Exception failure) { - throw new IllegalStateException(failure); - } - }); + fixture.tx(() -> { + try { + var retained = + IsolatedPublicationOwnerSetup.retainSourceBacked( + fixture.dsl(), fixture.target(), 1); + fixture + .sources() + .captureSynchronized(retained.account().input().selection().selectedCommit()); + return retained; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); assertThatThrownBy(() -> fixture.tx(() -> fixture.sources().freeze(operation))) .isInstanceOfSatisfying( PublishGateFailureException.class, @@ -931,20 +910,19 @@ void sourceRollbackIncompleteScopesAndPublicationCaptureFailClosed() { void emptyRealmPolicySourceFailsWithTypedPublicationGateBeforeCapture() { Fixture fixture = fixture(); var operation = - fixture.tx( - () -> { - try { - var retained = - IsolatedPublicationOwnerSetup.retainSourceBacked( - fixture.dsl(), fixture.target(), 1); - fixture - .sources() - .captureSynchronized(retained.account().input().selection().selectedCommit()); - return retained; - } catch (Exception failure) { - throw new IllegalStateException(failure); - } - }); + fixture.tx(() -> { + try { + var retained = + IsolatedPublicationOwnerSetup.retainSourceBacked( + fixture.dsl(), fixture.target(), 1); + fixture + .sources() + .captureSynchronized(retained.account().input().selection().selectedCommit()); + return retained; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); assertThatThrownBy(() -> fixture.tx(() -> fixture.sources().freeze(operation))) .isInstanceOfSatisfying( @@ -974,20 +952,19 @@ void completeSelectedSourcesFreezeTogetherAndExactRetryReadsStoredBytes() { true); synchronize(fixture, authored, apply(fixture, authored)); var operation = - fixture.tx( - () -> { - try { - var retained = - IsolatedPublicationOwnerSetup.retainSourceBacked( - fixture.dsl(), fixture.target(), 1); - fixture - .sources() - .captureSynchronized(retained.account().input().selection().selectedCommit()); - return retained; - } catch (Exception failure) { - throw new IllegalStateException(failure); - } - }); + fixture.tx(() -> { + try { + var retained = + IsolatedPublicationOwnerSetup.retainSourceBacked( + fixture.dsl(), fixture.target(), 1); + fixture + .sources() + .captureSynchronized(retained.account().input().selection().selectedCommit()); + return retained; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); assertThat(fixture.sources().readCapture(operation)).isEmpty(); var selectedBinding = operation.account().input().selection().selectedCommit(); var selectedRules = @@ -1000,21 +977,19 @@ void completeSelectedSourcesFreezeTogetherAndExactRetryReadsStoredBytes() { assertThat(selectedRules.entries()).isEmpty(); fixture .write() - .executeWithoutResult( - status -> { - fixture.sources().freeze(operation); - status.setRollbackOnly(); - }); + .executeWithoutResult(status -> { + fixture.sources().freeze(operation); + status.setRollbackOnly(); + }); assertThat(fixture.sources().readCapture(operation)).isEmpty(); - fixture.tx( - () -> { - new CommandSourceRepository(fixture.dsl()).freeze(operation); - new RealmPolicySourceRepository(fixture.dsl()).freeze(operation); - new net.firedevops.firemud.gamedesign.publication.AssetSourceRepository(fixture.dsl()) - .freeze(operation); - return null; - }); + fixture.tx(() -> { + new CommandSourceRepository(fixture.dsl()).freeze(operation); + new RealmPolicySourceRepository(fixture.dsl()).freeze(operation); + new net.firedevops.firemud.gamedesign.publication.AssetSourceRepository(fixture.dsl()) + .freeze(operation); + return null; + }); assertThatThrownBy(() -> fixture.sources().readCapture(operation)) .isInstanceOf(IllegalStateException.class) .hasMessage("GAME_DESIGN_SOURCE_CAPTURE_INCOMPLETE"); @@ -1023,16 +998,15 @@ void completeSelectedSourcesFreezeTogetherAndExactRetryReadsStoredBytes() { var originalAccount = operation.account(); var changedSources = originalAccount.sources().stream() - .map( - source -> - new SourceEvidence( - source.kind(), - source.scopeId(), - source.generation(), - source.sourceVersion() + "0", - source.checkpointStream(), - source.checkpointSequence(), - source.evidence())) + .map(source -> + new SourceEvidence( + source.kind(), + source.scopeId(), + source.generation(), + source.sourceVersion() + "0", + source.checkpointStream(), + source.checkpointSequence(), + source.evidence())) .toList(); var changedAccount = new AccountPublicationAuthorizationBinding( @@ -1119,27 +1093,25 @@ void completeSelectedSourcesFreezeTogetherAndExactRetryReadsStoredBytes() { assertThat(retry.gameplay().orElseThrow().snapshot().entries()).isEmpty(); assertThat(read.gameplay().orElseThrow().canonicalBytes()) .containsExactly(first.gameplay().orElseThrow().canonicalBytes()); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "UPDATE game_design_gameplay_rule_source_capture SET capture_bytes = ? " - + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", - new byte[] {1}, - fixture.target().canonicalTenantId(), - fixture.target().canonicalVersionId())) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "UPDATE game_design_gameplay_rule_source_capture SET capture_bytes = ? " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + new byte[] {1}, + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId())) .rootCause() .hasMessageContaining("gameplay-rule publication source capture is immutable"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "DELETE FROM game_design_gameplay_rule_source_capture " - + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", - fixture.target().canonicalTenantId(), - fixture.target().canonicalVersionId())) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "DELETE FROM game_design_gameplay_rule_source_capture " + + "WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId())) .rootCause() .hasMessageContaining("gameplay-rule publication source capture is immutable"); assertThatThrownBy( @@ -1159,20 +1131,19 @@ void nonemptySelectedGameplaySnapshotIsFrozenWithItsOriginalOperation() { binding(fixture.target(), genesisBase, "0", null, "main", true), gameplayUpsert()); synchronize(fixture, authored, apply(fixture, authored)); var operation = - fixture.tx( - () -> { - try { - var retained = - IsolatedPublicationOwnerSetup.retainSourceBacked( - fixture.dsl(), fixture.target(), 1); - fixture - .sources() - .captureSynchronized(retained.account().input().selection().selectedCommit()); - return retained; - } catch (Exception failure) { - throw new IllegalStateException(failure); - } - }); + fixture.tx(() -> { + try { + var retained = + IsolatedPublicationOwnerSetup.retainSourceBacked( + fixture.dsl(), fixture.target(), 1); + fixture + .sources() + .captureSynchronized(retained.account().input().selection().selectedCommit()); + return retained; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); var selectedBinding = operation.account().input().selection().selectedCommit(); var selectedRules = fixture @@ -1274,27 +1245,25 @@ void terminalV2CaptureWithMissingAssetAndGameplayIsIncomplete() { synchronize(fixture, authored, apply(fixture, authored)); var operation = retainSelectedOperation(fixture); - fixture.tx( - () -> { - new CommandSourceRepository(fixture.dsl()).freeze(operation); - new RealmPolicySourceRepository(fixture.dsl()).freeze(operation); - new BrandingSourceRepository(fixture.dsl()).freeze(operation); - new TemplateConfigSourceRepository(fixture.dsl()).freeze(operation); - var attempts = new PublishAttemptRepository(fixture.dsl()); - var attempt = - attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); - attempt.setStatus(PublishAttemptStatus.FAILED); - attempt.setFailureCode("ISOLATED_PARTIAL_CAPTURE_DENIAL"); - attempts.save(attempt); - new GameDesignPublicationOperationRepository(fixture.dsl()) - .seal( - operation.tenantKey(), - operation.workflowId(), - operation.versionId(), - operation.selectionDigest(), - false); - return null; - }); + fixture.tx(() -> { + new CommandSourceRepository(fixture.dsl()).freeze(operation); + new RealmPolicySourceRepository(fixture.dsl()).freeze(operation); + new BrandingSourceRepository(fixture.dsl()).freeze(operation); + new TemplateConfigSourceRepository(fixture.dsl()).freeze(operation); + var attempts = new PublishAttemptRepository(fixture.dsl()); + var attempt = attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); + attempt.setStatus(PublishAttemptStatus.FAILED); + attempt.setFailureCode("ISOLATED_PARTIAL_CAPTURE_DENIAL"); + attempts.save(attempt); + new GameDesignPublicationOperationRepository(fixture.dsl()) + .seal( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + false); + return null; + }); assertThatThrownBy(() -> fixture.sources().readCapture(operation)) .isInstanceOf(IllegalStateException.class) @@ -1321,38 +1290,35 @@ void terminalV2RetainsMissingTemplateCaptureButPendingV2RequiresIt() { synchronize(fixture, authored, apply(fixture, authored)); var operation = retainSelectedOperation(fixture); - fixture.tx( - () -> { - new CommandSourceRepository(fixture.dsl()).freeze(operation); - new RealmPolicySourceRepository(fixture.dsl()).freeze(operation); - new net.firedevops.firemud.gamedesign.publication.AssetSourceRepository(fixture.dsl()) - .freeze(operation); - new GameplayRuleSourceRepository(fixture.dsl()).freeze(operation); - new BrandingSourceRepository(fixture.dsl()).freeze(operation); - return null; - }); + fixture.tx(() -> { + new CommandSourceRepository(fixture.dsl()).freeze(operation); + new RealmPolicySourceRepository(fixture.dsl()).freeze(operation); + new net.firedevops.firemud.gamedesign.publication.AssetSourceRepository(fixture.dsl()) + .freeze(operation); + new GameplayRuleSourceRepository(fixture.dsl()).freeze(operation); + new BrandingSourceRepository(fixture.dsl()).freeze(operation); + return null; + }); assertThatThrownBy(() -> fixture.sources().readCapture(operation)) .isInstanceOf(IllegalStateException.class) .hasMessage("GAME_DESIGN_SOURCE_CAPTURE_INCOMPLETE"); - fixture.tx( - () -> { - var attempts = new PublishAttemptRepository(fixture.dsl()); - var attempt = - attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); - attempt.setStatus(PublishAttemptStatus.FAILED); - attempt.setFailureCode("ISOLATED_TERMINAL_CAPTURE_WITHOUT_TEMPLATE"); - attempts.save(attempt); - new GameDesignPublicationOperationRepository(fixture.dsl()) - .seal( - operation.tenantKey(), - operation.workflowId(), - operation.versionId(), - operation.selectionDigest(), - false); - return null; - }); + fixture.tx(() -> { + var attempts = new PublishAttemptRepository(fixture.dsl()); + var attempt = attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); + attempt.setStatus(PublishAttemptStatus.FAILED); + attempt.setFailureCode("ISOLATED_TERMINAL_CAPTURE_WITHOUT_TEMPLATE"); + attempts.save(attempt); + new GameDesignPublicationOperationRepository(fixture.dsl()) + .seal( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + false); + return null; + }); var retained = fixture.sources().readCapture(operation).orElseThrow(); assertThat(retained.command()).isNotNull(); @@ -1382,43 +1348,40 @@ void preGameplayTerminalCaptureStaysUnknownAndCannotBeExtendedAfterV1032() throw true); synchronize(fixture, authored, apply(fixture, authored)); var operation = - fixture.tx( - () -> { - try { - var retained = - IsolatedPublicationOwnerSetup.retainSourceBacked( - fixture.dsl(), fixture.target(), 1); - fixture - .sources() - .captureSynchronized(retained.account().input().selection().selectedCommit()); - return retained; - } catch (Exception failure) { - throw new IllegalStateException(failure); - } - }); - fixture.tx( - () -> { - new CommandSourceRepository(fixture.dsl()).freeze(operation); - new RealmPolicySourceRepository(fixture.dsl()).freeze(operation); - new net.firedevops.firemud.gamedesign.publication.AssetSourceRepository(fixture.dsl()) - .freeze(operation); - new BrandingSourceRepository(fixture.dsl()).freeze(operation); - new TemplateConfigSourceRepository(fixture.dsl()).freeze(operation); - var attempts = new PublishAttemptRepository(fixture.dsl()); - var attempt = - attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); - attempt.setStatus(PublishAttemptStatus.FAILED); - attempt.setFailureCode("ISOLATED_PRE_GAMEPLAY_STORAGE_DENIAL"); - attempts.save(attempt); - new GameDesignPublicationOperationRepository(fixture.dsl()) - .seal( - operation.tenantKey(), - operation.workflowId(), - operation.versionId(), - operation.selectionDigest(), - false); - return null; + fixture.tx(() -> { + try { + var retained = + IsolatedPublicationOwnerSetup.retainSourceBacked( + fixture.dsl(), fixture.target(), 1); + fixture + .sources() + .captureSynchronized(retained.account().input().selection().selectedCommit()); + return retained; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } }); + fixture.tx(() -> { + new CommandSourceRepository(fixture.dsl()).freeze(operation); + new RealmPolicySourceRepository(fixture.dsl()).freeze(operation); + new net.firedevops.firemud.gamedesign.publication.AssetSourceRepository(fixture.dsl()) + .freeze(operation); + new BrandingSourceRepository(fixture.dsl()).freeze(operation); + new TemplateConfigSourceRepository(fixture.dsl()).freeze(operation); + var attempts = new PublishAttemptRepository(fixture.dsl()); + var attempt = attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); + attempt.setStatus(PublishAttemptStatus.FAILED); + attempt.setFailureCode("ISOLATED_PRE_GAMEPLAY_STORAGE_DENIAL"); + attempts.save(attempt); + new GameDesignPublicationOperationRepository(fixture.dsl()) + .seal( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + false); + return null; + }); var operationBefore = Objects.requireNonNull( @@ -1480,9 +1443,8 @@ void preGameplayTerminalCaptureStaysUnknownAndCannotBeExtendedAfterV1032() throw assertThatThrownBy(() -> fixture.tx(() -> fixture.sources().freeze(operation))) .isInstanceOf(IllegalStateException.class) .hasMessage("GAMEPLAY_RULE_PUBLICATION_OPERATION_SEALED"); - assertThatThrownBy( - () -> - fixture.tx(() -> new GameplayRuleSourceRepository(fixture.dsl()).freeze(operation))) + assertThatThrownBy(() -> + fixture.tx(() -> new GameplayRuleSourceRepository(fixture.dsl()).freeze(operation))) .isInstanceOf(IllegalStateException.class) .hasMessage("GAMEPLAY_RULE_PUBLICATION_OPERATION_SEALED"); assertThat(fixture.dsl().fetchCount(DSL.table("game_design_gameplay_rule_source_capture"))) @@ -1502,42 +1464,38 @@ private static void assertInvalidGameplayCaptureInsert( byte[] captureBytes, String captureDigest, String expectedSqlGuardMessage) { - assertThatThrownBy( - () -> - fixture.tx( - () -> - fixture - .dsl() - .execute( - "INSERT INTO game_design_gameplay_rule_source_capture " - + "(canonical_tenant_id, canonical_version_id, publish_workflow_id, commit_id, " - + "operation_bytes, capture_bytes, capture_digest) VALUES (?, ?, ?, ?, ?, ?, ?)", - fixture.target().canonicalTenantId(), - fixture.target().canonicalVersionId(), - operation.workflowId(), - operation.account().input().selection().selectedCommit().commitId(), - operationBytes, - captureBytes, - captureDigest))) + assertThatThrownBy(() -> + fixture.tx(() -> + fixture + .dsl() + .execute( + "INSERT INTO game_design_gameplay_rule_source_capture " + + "(canonical_tenant_id, canonical_version_id, publish_workflow_id, commit_id, " + + "operation_bytes, capture_bytes, capture_digest) VALUES (?, ?, ?, ?, ?, ?, ?)", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + operation.workflowId(), + operation.account().input().selection().selectedCommit().commitId(), + operationBytes, + captureBytes, + captureDigest))) .rootCause() .hasMessageContaining(expectedSqlGuardMessage); } private static GameDesignPublicationOperation retainSelectedOperation(Fixture fixture) { - return fixture.tx( - () -> { - try { - var operation = - IsolatedPublicationOwnerSetup.retainSourceBacked( - fixture.dsl(), fixture.target(), 1); - fixture - .sources() - .captureSynchronized(operation.account().input().selection().selectedCommit()); - return operation; - } catch (Exception failure) { - throw new IllegalStateException(failure); - } - }); + return fixture.tx(() -> { + try { + var operation = + IsolatedPublicationOwnerSetup.retainSourceBacked(fixture.dsl(), fixture.target(), 1); + fixture + .sources() + .captureSynchronized(operation.account().input().selection().selectedCommit()); + return operation; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); } private static CaptureRow retainedCapture(Fixture fixture, String table) { @@ -1574,37 +1532,35 @@ private static GameDesignSourceRepository.Application apply( } private static void start(Fixture fixture, DraftCommitBinding binding) { - fixture.tx( - () -> { - var reviewed = new GameDesignReviewedBaseRepository(fixture.dsl()); - fixture - .sources() - .claimReviewed( - binding, - reviewed.resolve( - fixture.target(), - net.firedevops.firemud.common.authoring.DraftBaseReference.parse( - binding.baseCommitId()))); - fixture.coordinator().claimApplicationSlot(binding); - fixture.coordinator().markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); - return null; - }); + fixture.tx(() -> { + var reviewed = new GameDesignReviewedBaseRepository(fixture.dsl()); + fixture + .sources() + .claimReviewed( + binding, + reviewed.resolve( + fixture.target(), + net.firedevops.firemud.common.authoring.DraftBaseReference.parse( + binding.baseCommitId()))); + fixture.coordinator().claimApplicationSlot(binding); + fixture.coordinator().markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + return null; + }); } private static void synchronize( Fixture fixture, DraftCommitBinding binding, GameDesignSourceRepository.Application result) { - fixture.tx( - () -> { - fixture - .coordinator() - .advanceSourceVisibilityFence( - binding, - new DraftCommitCoordinatorRepository.CoordinatorProof( - binding, List.of(result.ownerOutcome()))); - fixture.sources().captureSynchronized(binding); - fixture.coordinator().releaseApplicationSlot(binding); - return null; - }); + fixture.tx(() -> { + fixture + .coordinator() + .advanceSourceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, List.of(result.ownerOutcome()))); + fixture.sources().captureSynchronized(binding); + fixture.coordinator().releaseApplicationSlot(binding); + return null; + }); } private static DraftCommitBinding binding( @@ -1797,12 +1753,11 @@ void rawLifecycleFirstRejectsSlotInsertAcrossSupportedIsolationLevels() throws E var started = new java.util.concurrent.CountDownLatch(1); var workerPid = new java.util.concurrent.atomic.AtomicInteger(); var inserting = - worker.submit( - () -> { - workerPid.set(storageBackendPid(slotSql)); - started.countDown(); - return failedStorageWrite(() -> insertRawSlot(slotSql, binding)); - }); + worker.submit(() -> { + workerPid.set(storageBackendPid(slotSql)); + started.countDown(); + return failedStorageWrite(() -> insertRawSlot(slotSql, binding)); + }); try { assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(awaitStorageBackendBlock(local, lifecyclePid, workerPid.get())) @@ -1849,16 +1804,14 @@ void rawSlotFirstRejectsLifecycleWriteIncludingStaleSnapshotsWithoutChangingVers var started = new java.util.concurrent.CountDownLatch(1); var workerPid = new java.util.concurrent.atomic.AtomicInteger(); var updating = - worker.submit( - () -> { - workerPid.set(storageBackendPid(lifecycleSql)); - started.countDown(); - return failedStorageWrite( - () -> - lifecycleSql.execute( - "UPDATE version SET version_state = 'RETIRED', version_state_epoch = version_state_epoch + 1 WHERE id = ?", - local.target().gameDesignVersionRowId())); - }); + worker.submit(() -> { + workerPid.set(storageBackendPid(lifecycleSql)); + started.countDown(); + return failedStorageWrite(() -> + lifecycleSql.execute( + "UPDATE version SET version_state = 'RETIRED', version_state_epoch = version_state_epoch + 1 WHERE id = ?", + local.target().gameDesignVersionRowId())); + }); try { assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(awaitStorageBackendBlock(local, slotPid, workerPid.get())) @@ -1899,12 +1852,11 @@ void rawSelectionFirstRejectsSlotInsertEvenWhenSlotSnapshotPredatesSelection() t var started = new java.util.concurrent.CountDownLatch(1); var workerPid = new java.util.concurrent.atomic.AtomicInteger(); var inserting = - worker.submit( - () -> { - workerPid.set(storageBackendPid(slotSql)); - started.countDown(); - return failedStorageWrite(() -> insertRawSlot(slotSql, later)); - }); + worker.submit(() -> { + workerPid.set(storageBackendPid(slotSql)); + started.countDown(); + return failedStorageWrite(() -> insertRawSlot(slotSql, later)); + }); try { assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(awaitStorageBackendBlock(local, selectionPid, workerPid.get())) @@ -1948,12 +1900,11 @@ void rawSlotFirstRejectsSelectionEvenWhenSelectionSnapshotPredatesSlot() throws var started = new java.util.concurrent.CountDownLatch(1); var workerPid = new java.util.concurrent.atomic.AtomicInteger(); var inserting = - worker.submit( - () -> { - workerPid.set(storageBackendPid(selectionSql)); - started.countDown(); - return failedStorageWrite(() -> insertRawSelection(selectionSql, selected)); - }); + worker.submit(() -> { + workerPid.set(storageBackendPid(selectionSql)); + started.countDown(); + return failedStorageWrite(() -> insertRawSelection(selectionSql, selected)); + }); try { assertThat(started.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(awaitStorageBackendBlock(local, slotPid, workerPid.get())) @@ -2062,25 +2013,23 @@ private static DraftCommitBinding storageBinding(Fixture fixture, String descrip String base = current .map(fence -> fence.commitId().toString()) - .orElseGet( - () -> - "genesis:" - + fixture - .sources() - .readGenesis(fixture.target()) - .orElseThrow() - .policy() - .receiptId()); - String epoch = - current - .map( - fence -> - fixture + .orElseGet(() -> + "genesis:" + + fixture .sources() - .readSynchronized(fixture.target(), fence.commitId()) + .readGenesis(fixture.target()) .orElseThrow() - .command() - .sourceEpoch()) + .policy() + .receiptId()); + String epoch = + current + .map(fence -> + fixture + .sources() + .readSynchronized(fixture.target(), fence.commitId()) + .orElseThrow() + .command() + .sourceEpoch()) .orElse("0"); return binding(fixture.target(), base, null, epoch, null, false); } @@ -2115,18 +2064,14 @@ private static AuthoredDraftPublishSelection synchronizedStorageSelection(Fixtur binding.requestId(), binding.commitId(), binding.digest()); - return fixture.tx( - () -> - AuthoredDraftPublishSelection.capture( - intent, - fixture.target(), - fixture - .coordinator() - .requireSynchronizedPublicationEvidence( - fixture.target(), - binding.requestId(), - binding.commitId(), - binding.digest()))); + return fixture.tx(() -> + AuthoredDraftPublishSelection.capture( + intent, + fixture.target(), + fixture + .coordinator() + .requireSynchronizedPublicationEvidence( + fixture.target(), binding.requestId(), binding.commitId(), binding.digest()))); } private void insertRawSelection(DSLContext sql, AuthoredDraftPublishSelection selected) { @@ -2185,25 +2130,24 @@ private static Fixture fixture(String migrationTarget) { var properties = new PostgresProperties(); properties.setSchema(schema); TargetProof target = - write.execute( - status -> { - var game = new Game(); - game.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); - game.setName("ISOLATED composed source"); - game = new GameRepository(dsl).save(game); - var version = new Version(); - version.setTenantId(game.getTenantId()); - version.setVersionNumber(1); - version = new VersionRepository(dsl).save(version); - return new TargetProof( - version.getCanonicalTenantId(), - version.getCanonicalVersionId(), - version.getId(), - version.getTenantId(), - version.getIdentitySourceGameRowId(), - version.getIdentitySourceGameTenantKey(), - version.getIdentitySourceProvenanceKind()); - }); + write.execute(status -> { + var game = new Game(); + game.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + game.setName("ISOLATED composed source"); + game = new GameRepository(dsl).save(game); + var version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(1); + version = new VersionRepository(dsl).save(version); + return new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + }); return new Fixture( schema, dsl, diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java index b23adeb398..e2a3f89712 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java @@ -338,42 +338,39 @@ void explicitDeleteRejectsAnAbsentSelectorWithoutAdvancingThePolicySource() { void retainedVersionUpdateIsNotFreshGenesisAndActualCreationRollbackLeavesNoReceipt() { var fixture = retainedFixture(); migrateLatest(fixture); - assertThatThrownBy( - () -> - fixture.tx( - () -> { - fixture - .dsl() - .execute( - "UPDATE version SET notes = 'ISOLATED retained update' WHERE id = ?", - fixture.target().gameDesignVersionRowId()); - return fixture.policies().recordFreshGenesis(fixture.target()); - })) + assertThatThrownBy(() -> + fixture.tx(() -> { + fixture + .dsl() + .execute( + "UPDATE version SET notes = 'ISOLATED retained update' WHERE id = ?", + fixture.target().gameDesignVersionRowId()); + return fixture.policies().recordFreshGenesis(fixture.target()); + })) .hasMessageContaining("POLICY_FRESH_VERSION_INSERT_PROOF_UNAVAILABLE"); var rolledBack = new java.util.concurrent.atomic.AtomicReference(); fixture .write() - .executeWithoutResult( - status -> { - var properties = new PostgresProperties(); - var version = new Version(); - version.setTenantId(fixture.target().gameDesignVersionTenantKey()); - version.setVersionNumber(2); - version = new VersionRepository(fixture.dsl()).save(version); - var target = - new TargetProof( - version.getCanonicalTenantId(), - version.getCanonicalVersionId(), - version.getId(), - version.getTenantId(), - version.getIdentitySourceGameRowId(), - version.getIdentitySourceGameTenantKey(), - version.getIdentitySourceProvenanceKind()); - rolledBack.set(target); - RealmPolicyGenesis receipt = fixture.policies().recordFreshGenesis(target); - assertThat(fixture.policies().recordFreshGenesis(target)).isEqualTo(receipt); - status.setRollbackOnly(); - }); + .executeWithoutResult(status -> { + var properties = new PostgresProperties(); + var version = new Version(); + version.setTenantId(fixture.target().gameDesignVersionTenantKey()); + version.setVersionNumber(2); + version = new VersionRepository(fixture.dsl()).save(version); + var target = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + rolledBack.set(target); + RealmPolicyGenesis receipt = fixture.policies().recordFreshGenesis(target); + assertThat(fixture.policies().recordFreshGenesis(target)).isEqualTo(receipt); + status.setRollbackOnly(); + }); assertThat(fixture.reads().readGenesis(rolledBack.get())).isEmpty(); assertThat( fixture @@ -477,54 +474,46 @@ void sourceHeadRejectsUnprovenTransitionsAndDisjointCaptureInheritsExactPredeces var current = fixture.reads().readSnapshot(fixture.target(), second.commitId()).orElseThrow(); assertThat(current.policies()).hasSize(2); - assertThatThrownBy( - () -> - fixture.tx( - () -> - fixture - .dsl() - .execute( - "UPDATE game_design_realm_policy_source SET source_epoch = '1', visible_commit_id = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", - first.commitId(), - fixture.target().canonicalTenantId(), - fixture.target().canonicalVersionId()))) + assertThatThrownBy(() -> + fixture.tx(() -> + fixture + .dsl() + .execute( + "UPDATE game_design_realm_policy_source SET source_epoch = '1', visible_commit_id = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + first.commitId(), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) .hasMessageContaining( "realm policy source epoch must advance through its exact owner application"); - assertThatThrownBy( - () -> - fixture.tx( - () -> - fixture - .dsl() - .execute( - "UPDATE game_design_realm_policy_source SET source_epoch = '1' WHERE canonical_tenant_id = ? AND canonical_version_id = ?", - fixture.target().canonicalTenantId(), - fixture.target().canonicalVersionId()))) + assertThatThrownBy(() -> + fixture.tx(() -> + fixture + .dsl() + .execute( + "UPDATE game_design_realm_policy_source SET source_epoch = '1' WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) .hasMessageContaining( "realm policy source epoch must advance through its exact owner application"); - assertThatThrownBy( - () -> - fixture.tx( - () -> - fixture - .dsl() - .execute( - "UPDATE game_design_realm_policy_source SET source_epoch = '4' WHERE canonical_tenant_id = ? AND canonical_version_id = ?", - fixture.target().canonicalTenantId(), - fixture.target().canonicalVersionId()))) + assertThatThrownBy(() -> + fixture.tx(() -> + fixture + .dsl() + .execute( + "UPDATE game_design_realm_policy_source SET source_epoch = '4' WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) .hasMessageContaining( "realm policy source epoch must advance through its exact owner application"); - assertThatThrownBy( - () -> - fixture.tx( - () -> - fixture - .dsl() - .execute( - "UPDATE game_design_realm_policy_source SET visible_commit_id = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", - first.commitId(), - fixture.target().canonicalTenantId(), - fixture.target().canonicalVersionId()))) + assertThatThrownBy(() -> + fixture.tx(() -> + fixture + .dsl() + .execute( + "UPDATE game_design_realm_policy_source SET visible_commit_id = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + first.commitId(), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) .hasMessageContaining( "realm policy source pointer must advance to its exact current synchronized snapshot"); @@ -559,17 +548,15 @@ void retainedHistoricalSourceHeadInsertRequiresItsVisibleSnapshotEpoch() { var snapshot = seedRetainedSnapshot(fixture, "1"); migrateLatest(fixture); - assertThatThrownBy( - () -> - fixture.tx( - () -> - fixture - .dsl() - .execute( - "INSERT INTO game_design_realm_policy_source (canonical_tenant_id, canonical_version_id, source_epoch, visible_commit_id) VALUES (?, ?, '2', ?)", - fixture.target().canonicalTenantId(), - fixture.target().canonicalVersionId(), - fixture.baseline().commitId()))) + assertThatThrownBy(() -> + fixture.tx(() -> + fixture + .dsl() + .execute( + "INSERT INTO game_design_realm_policy_source (canonical_tenant_id, canonical_version_id, source_epoch, visible_commit_id) VALUES (?, ?, '2', ?)", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + fixture.baseline().commitId()))) .hasMessageContaining("realm policy source head must match its visible snapshot epoch"); assertThat(fixture.dsl().fetchCount(DSL.table("game_design_realm_policy_source"))).isZero(); assertThat( @@ -579,17 +566,16 @@ void retainedHistoricalSourceHeadInsertRequiresItsVisibleSnapshotEpoch() { .orElseThrow()) .isEqualTo(snapshot); - fixture.tx( - () -> { - fixture - .dsl() - .execute( - "INSERT INTO game_design_realm_policy_source (canonical_tenant_id, canonical_version_id, source_epoch, visible_commit_id) VALUES (?, ?, '1', ?)", - fixture.target().canonicalTenantId(), - fixture.target().canonicalVersionId(), - fixture.baseline().commitId()); - return null; - }); + fixture.tx(() -> { + fixture + .dsl() + .execute( + "INSERT INTO game_design_realm_policy_source (canonical_tenant_id, canonical_version_id, source_epoch, visible_commit_id) VALUES (?, ?, '1', ?)", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + fixture.baseline().commitId()); + return null; + }); var sourceHead = java.util.Objects.requireNonNull( fixture @@ -619,50 +605,43 @@ void visibilityPointerCannotRewindDeleteOrTruncateAndExactFenceRetryRemainsStabl synchronize(fixture, second, secondApplication); var replayedFence = - fixture.tx( - () -> - fixture - .coordinator() - .advanceSourceVisibilityFence( - second, - new DraftCommitCoordinatorRepository.CoordinatorProof( - second, List.of(secondApplication.ownerOutcome())))); + fixture.tx(() -> + fixture + .coordinator() + .advanceSourceVisibilityFence( + second, + new DraftCommitCoordinatorRepository.CoordinatorProof( + second, List.of(secondApplication.ownerOutcome())))); assertThat(replayedFence.commitId()).isEqualTo(second.commitId()); assertThat(visiblePointerCommit(fixture)).isEqualTo(second.commitId()); - assertThatThrownBy( - () -> - fixture.tx( - () -> - fixture - .dsl() - .execute( - "UPDATE game_design_draft_commit_visibility SET request_id = ?, commit_id = ?, input_digest = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", - first.requestId(), - first.commitId(), - first.digest(), - fixture.target().canonicalTenantId(), - fixture.target().canonicalVersionId()))) + assertThatThrownBy(() -> + fixture.tx(() -> + fixture + .dsl() + .execute( + "UPDATE game_design_draft_commit_visibility SET request_id = ?, commit_id = ?, input_digest = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + first.requestId(), + first.commitId(), + first.digest(), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) .hasMessageContaining("may advance only to its actively applying commit"); assertThat(visiblePointerCommit(fixture)).isEqualTo(second.commitId()); - assertThatThrownBy( - () -> - fixture.tx( - () -> - fixture - .dsl() - .execute( - "DELETE FROM game_design_draft_commit_visibility WHERE canonical_tenant_id = ? AND canonical_version_id = ?", - fixture.target().canonicalTenantId(), - fixture.target().canonicalVersionId()))) + assertThatThrownBy(() -> + fixture.tx(() -> + fixture + .dsl() + .execute( + "DELETE FROM game_design_draft_commit_visibility WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) .hasMessageContaining("Draft visibility pointers cannot be deleted"); assertThat(visiblePointerCommit(fixture)).isEqualTo(second.commitId()); - assertThatThrownBy( - () -> - fixture.tx( - () -> fixture.dsl().execute("TRUNCATE game_design_draft_commit_visibility"))) + assertThatThrownBy(() -> + fixture.tx(() -> fixture.dsl().execute("TRUNCATE game_design_draft_commit_visibility"))) .hasMessageContaining("Draft visibility pointers cannot be truncated"); assertThat(visiblePointerCommit(fixture)).isEqualTo(second.commitId()); } @@ -715,11 +694,10 @@ void rollbackAndPartialWritesPreserveLastVisibleSourceThenDisjointCommitInherits start(fixture, mutation); fixture .write() - .executeWithoutResult( - status -> { - fixture.policies().apply(mutation); - status.setRollbackOnly(); - }); + .executeWithoutResult(status -> { + fixture.policies().apply(mutation); + status.setRollbackOnly(); + }); assertThat( fixture .dsl() @@ -762,14 +740,12 @@ void rollbackAndPartialWritesPreserveLastVisibleSourceThenDisjointCommitInherits "reserved publication fixture must have its persisted operation row") .get(0, String.class)) .isEqualTo("PENDING"); - assertThatThrownBy( - () -> - fixture.tx( - () -> - fixture - .dsl() - .execute( - "UPDATE game_design_realm_policy_snapshot SET snapshot_json = snapshot_json"))) + assertThatThrownBy(() -> + fixture.tx(() -> + fixture + .dsl() + .execute( + "UPDATE game_design_realm_policy_snapshot SET snapshot_json = snapshot_json"))) .isInstanceOf(RuntimeException.class) .hasMessageContaining("realm policy history is immutable"); } @@ -780,11 +756,10 @@ void freezeAndSourceWriterUseSameVersionLockAndRollbackDoesNotLeaveCapture() thr var operation = publication(fixture); fixture .write() - .executeWithoutResult( - status -> { - fixture.policies().freeze(operation); - status.setRollbackOnly(); - }); + .executeWithoutResult(status -> { + fixture.policies().freeze(operation); + status.setRollbackOnly(); + }); assertThat(fixture.reads().readCapture(operation)).isEmpty(); var frozen = new CountDownLatch(1); var release = new CountDownLatch(1); @@ -793,47 +768,43 @@ void freezeAndSourceWriterUseSameVersionLockAndRollbackDoesNotLeaveCapture() thr var writerPid = new java.util.concurrent.atomic.AtomicInteger(); try (var executor = Executors.newFixedThreadPool(2)) { var freezer = - executor.submit( - () -> - fixture.tx( - () -> { - var result = fixture.policies().freeze(operation); - freezerPid.set( - java.util.Objects.requireNonNull( - fixture.dsl().fetchOne("SELECT pg_backend_pid()"), - "freezer transaction must expose its PostgreSQL backend") - .get(0, Integer.class)); - frozen.countDown(); - await(release); - return result; - })); + executor.submit(() -> + fixture.tx(() -> { + var result = fixture.policies().freeze(operation); + freezerPid.set( + java.util.Objects.requireNonNull( + fixture.dsl().fetchOne("SELECT pg_backend_pid()"), + "freezer transaction must expose its PostgreSQL backend") + .get(0, Integer.class)); + frozen.countDown(); + await(release); + return result; + })); assertThat(frozen.await(10, TimeUnit.SECONDS)).isTrue(); var writer = - executor.submit( - () -> - fixture.tx( - () -> { - writerPid.set( - java.util.Objects.requireNonNull( - fixture.dsl().fetchOne("SELECT pg_backend_pid()"), - "writer transaction must expose its PostgreSQL backend") - .get(0, Integer.class)); - attempting.countDown(); - // Acquire the exact Version lock used by the repository's source writer - // before exercising the storage guard, independently of creator preflight. - fixture - .dsl() - .fetchOne( - "SELECT id FROM version WHERE canonical_tenant_id = ? AND canonical_version_id = ? FOR UPDATE", - fixture.target().canonicalTenantId(), - fixture.target().canonicalVersionId()); - return fixture - .dsl() - .execute( - "UPDATE game_design_realm_policy_source SET source_epoch = '2' WHERE canonical_tenant_id = ? AND canonical_version_id = ?", - fixture.target().canonicalTenantId(), - fixture.target().canonicalVersionId()); - })); + executor.submit(() -> + fixture.tx(() -> { + writerPid.set( + java.util.Objects.requireNonNull( + fixture.dsl().fetchOne("SELECT pg_backend_pid()"), + "writer transaction must expose its PostgreSQL backend") + .get(0, Integer.class)); + attempting.countDown(); + // Acquire the exact Version lock used by the repository's source writer + // before exercising the storage guard, independently of creator preflight. + fixture + .dsl() + .fetchOne( + "SELECT id FROM version WHERE canonical_tenant_id = ? AND canonical_version_id = ? FOR UPDATE", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()); + return fixture + .dsl() + .execute( + "UPDATE game_design_realm_policy_source SET source_epoch = '2' WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()); + })); assertThat(attempting.await(10, TimeUnit.SECONDS)).isTrue(); boolean observedVersionBlock = false; long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); @@ -885,26 +856,24 @@ private static void await(CountDownLatch latch) { } private static void start(Fixture fixture, DraftCommitBinding binding) { - fixture.tx( - () -> { - var reviewed = - new GameDesignReviewedBaseRepository(fixture.dsl()) - .resolve(binding.target(), DraftBaseReference.parse(binding.baseCommitId())); - fixture.sources().claimReviewed(binding, reviewed); - fixture.coordinator().claimApplicationSlot(binding); - fixture.coordinator().markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); - return null; - }); + fixture.tx(() -> { + var reviewed = + new GameDesignReviewedBaseRepository(fixture.dsl()) + .resolve(binding.target(), DraftBaseReference.parse(binding.baseCommitId())); + fixture.sources().claimReviewed(binding, reviewed); + fixture.coordinator().claimApplicationSlot(binding); + fixture.coordinator().markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + return null; + }); } private static void startUnreviewed(Fixture fixture, DraftCommitBinding binding) { - fixture.tx( - () -> { - fixture.coordinator().claim(binding); - fixture.coordinator().claimApplicationSlot(binding); - fixture.coordinator().markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); - return null; - }); + fixture.tx(() -> { + fixture.coordinator().claim(binding); + fixture.coordinator().claimApplicationSlot(binding); + fixture.coordinator().markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + return null; + }); } private static void synchronize( @@ -921,37 +890,34 @@ private static void synchronize( Fixture fixture, DraftCommitBinding binding, DraftCommitCoordinatorRepository.OwnerOutcome outcome) { - fixture.tx( - () -> { - fixture - .coordinator() - .advanceSourceVisibilityFence( - binding, - new DraftCommitCoordinatorRepository.CoordinatorProof(binding, List.of(outcome))); - fixture.coordinator().releaseApplicationSlot(binding); - return null; - }); + fixture.tx(() -> { + fixture + .coordinator() + .advanceSourceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof(binding, List.of(outcome))); + fixture.coordinator().releaseApplicationSlot(binding); + return null; + }); } private static GameDesignPublicationOperation publication(Fixture fixture) { - return fixture.tx( - () -> { - try { - // Existing fixture stipulates actual World and Account producer bytes; it runs GD's - // real - // disjoint World commit, selection, attempt and operation repositories. Capture - // integration - // here is isolated in the same transaction, not a claim of normal producer composition. - var operation = - IsolatedPublicationOwnerSetup.retain(fixture.dsl(), fixture.target(), 1); - fixture - .policies() - .captureSynchronized(operation.account().input().selection().selectedCommit()); - return operation; - } catch (Exception failure) { - throw new IllegalStateException(failure); - } - }); + return fixture.tx(() -> { + try { + // Existing fixture stipulates actual World and Account producer bytes; it runs GD's + // real + // disjoint World commit, selection, attempt and operation repositories. Capture + // integration + // here is isolated in the same transaction, not a claim of normal producer composition. + var operation = IsolatedPublicationOwnerSetup.retain(fixture.dsl(), fixture.target(), 1); + fixture + .policies() + .captureSynchronized(operation.account().input().selection().selectedCommit()); + return operation; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); } private static String playerCreatedPolicy(int schemaVersion, String descriptorRevisionId) { @@ -1189,18 +1155,17 @@ private static Fixture freshFixture() { write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); var dsl = DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); var target = - write.execute( - status -> { - var game = new Game(); - game.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); - game.setName("ISOLATED policy source"); - game = new GameRepository(dsl).save(game); - var version = new Version(); - version.setTenantId(game.getTenantId()); - version.setVersionNumber(1); - version = new VersionRepository(dsl).save(version); - return target(version); - }); + write.execute(status -> { + var game = new Game(); + game.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + game.setName("ISOLATED policy source"); + game = new GameRepository(dsl).save(game); + var version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(1); + version = new VersionRepository(dsl).save(version); + return target(version); + }); var policies = new RealmPolicySourceRepository(dsl); var sources = new GameDesignSourceRepository(dsl); var coordinator = new DraftCommitCoordinatorRepository(dsl); @@ -1253,13 +1218,12 @@ private static Fixture retainedFixture() { var properties = new PostgresProperties(); properties.setSchema(schema); var game = - write.execute( - status -> { - var created = new Game(); - created.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); - created.setName("ISOLATED retained policy source"); - return new GameRepository(dsl).save(created); - }); + write.execute(status -> { + var created = new Game(); + created.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + created.setName("ISOLATED retained policy source"); + return new GameRepository(dsl).save(created); + }); var version = write.execute(status -> insertRetainedVersion(dsl, properties, game, 1)); migrate(dataSource, schema, "50.13"); var target = target(version); @@ -1291,48 +1255,47 @@ private static void migrateLatest(Fixture fixture) { private static RealmPolicySnapshot seedRetainedSnapshot(Fixture fixture, String sourceEpoch) { // This is only a V50.13 historical row fixture: it creates no reviewed-base evidence and is // never used for a current source application. - return fixture.tx( - () -> { - var binding = fixture.baseline(); - fixture.coordinator().claim(binding); - fixture.coordinator().claimApplicationSlot(binding); - fixture.coordinator().markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); - var outcome = - new DraftCommitCoordinatorRepository.OwnerOutcome( - Owner.GAME_DESIGN_CONTROL_PLANE, - DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, - binding.commitId(), - binding.digest(), - "ISOLATED-initial-owner-baseline", - "ISOLATED-authenticated-baseline".getBytes(StandardCharsets.UTF_8), - List.of( - new DraftCommitCoordinatorRepository.AppliedEpoch( - RealmPolicySource.SCOPE, - fixture.target().canonicalVersionId().toString(), - RealmPolicySource.SCOPE, - "effective", - "0", - BigInteger.ONE.toString()))); - fixture.coordinator().recordOwnerOutcome(binding, outcome); - fixture - .coordinator() - .advanceVisibilityFence( - binding, - new DraftCommitCoordinatorRepository.CoordinatorProof(binding, List.of(outcome))); - fixture.coordinator().releaseApplicationSlot(binding); - var policy = RealmPolicySource.revision(binding, binding.revisions().getFirst()); - var snapshot = new RealmPolicySnapshot(binding, sourceEpoch, List.of(policy)); - fixture - .dsl() - .execute( - "INSERT INTO game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id, request_id, snapshot_json) VALUES (?, ?, ?, ?, ?)", - fixture.target().canonicalTenantId(), - fixture.target().canonicalVersionId(), - binding.commitId(), - binding.requestId(), - snapshot.canonicalJson()); - return snapshot; - }); + return fixture.tx(() -> { + var binding = fixture.baseline(); + fixture.coordinator().claim(binding); + fixture.coordinator().claimApplicationSlot(binding); + fixture.coordinator().markOwnerInProgress(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + var outcome = + new DraftCommitCoordinatorRepository.OwnerOutcome( + Owner.GAME_DESIGN_CONTROL_PLANE, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "ISOLATED-initial-owner-baseline", + "ISOLATED-authenticated-baseline".getBytes(StandardCharsets.UTF_8), + List.of( + new DraftCommitCoordinatorRepository.AppliedEpoch( + RealmPolicySource.SCOPE, + fixture.target().canonicalVersionId().toString(), + RealmPolicySource.SCOPE, + "effective", + "0", + BigInteger.ONE.toString()))); + fixture.coordinator().recordOwnerOutcome(binding, outcome); + fixture + .coordinator() + .advanceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof(binding, List.of(outcome))); + fixture.coordinator().releaseApplicationSlot(binding); + var policy = RealmPolicySource.revision(binding, binding.revisions().getFirst()); + var snapshot = new RealmPolicySnapshot(binding, sourceEpoch, List.of(policy)); + fixture + .dsl() + .execute( + "INSERT INTO game_design_realm_policy_snapshot (canonical_tenant_id, canonical_version_id, commit_id, request_id, snapshot_json) VALUES (?, ?, ?, ?, ?)", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + binding.commitId(), + binding.requestId(), + snapshot.canonicalJson()); + return snapshot; + }); } private static UUID visiblePointerCommit(Fixture fixture) { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java index 3e6ec183a8..de7a2e7cc7 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/SelectedPublicationStorageUpgradePostgresIntegrationTest.java @@ -260,16 +260,15 @@ void fullStorageUpgradeRetainsParentV1RowsBytesChecksumsAndOwnerReads() throws E () -> fixture .write() - .executeWithoutResult( - status -> - fixture - .operations() - .seal( - operation.tenantKey(), - operation.workflowId(), - operation.versionId(), - operation.selectionDigest(), - false)), + .executeWithoutResult(status -> + fixture + .operations() + .seal( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + false)), "Truncated publication inventory frame"); for (String family : List.of("command", "realm_policy", "asset")) { deny( @@ -356,9 +355,8 @@ void retainedReviewedV1RemainsByteExactReadableButCannotAuthorizeCurrentWrites() assertThat(retained.schema()).isEqualTo(GameDesignReviewedBaseEvidence.HISTORICAL_SCHEMA); assertThat(retained.canonicalBytes()).containsExactly(originalBytes); assertThat(retained.digest()).isEqualTo(originalDigest); - assertThatThrownBy( - () -> - new GameDesignReviewedBaseRepository(fixture.dsl()).requireCurrentRetained(binding)) + assertThatThrownBy(() -> + new GameDesignReviewedBaseRepository(fixture.dsl()).requireCurrentRetained(binding)) .isInstanceOf(IllegalStateException.class) .hasMessage("REVIEWED_BASE_ASSET_LINEAGE_UNAVAILABLE"); assertEnabledGuards(fixture); @@ -404,14 +402,13 @@ void retainedReviewedV1RemainsByteExactReadableButCannotAuthorizeCurrentWrites() () -> fixture .write() - .executeWithoutResult( - status -> - insertReviewedBaseV1( - fixture.dsl(), - newBinding, - originalBytes, - originalDigest, - newBinding.baseCommitId())), + .executeWithoutResult(status -> + insertReviewedBaseV1( + fixture.dsl(), + newBinding, + originalBytes, + originalDigest, + newBinding.baseCommitId())), "Fresh reviewed base requires complete asset-bound v2 owner evidence"); assertThat(reviewedBaseRow(fixture, binding)).isEqualTo(beforeRow); assertThat( @@ -431,23 +428,22 @@ void retainedTerminalFailureRemainsReadableWithItsOriginalReceiptAfterUpgrade() var operation = fixture.operation(); fixture .write() - .executeWithoutResult( - status -> { - var attempts = new PublishAttemptRepository(fixture.dsl()); - var attempt = - attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); - attempt.setStatus(PublishAttemptStatus.FAILED); - attempt.setFailureCode("ISOLATED_STORAGE_DENIAL"); - attempts.save(attempt); - fixture - .operations() - .seal( - operation.tenantKey(), - operation.workflowId(), - operation.versionId(), - operation.selectionDigest(), - false); - }); + .executeWithoutResult(status -> { + var attempts = new PublishAttemptRepository(fixture.dsl()); + var attempt = + attempts.findByPublishWorkflowIdForUpdate(operation.workflowId()).orElseThrow(); + attempt.setStatus(PublishAttemptStatus.FAILED); + attempt.setFailureCode("ISOLATED_STORAGE_DENIAL"); + attempts.save(attempt); + fixture + .operations() + .seal( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + false); + }); var original = fixture.operations().read(operation.workflowId()).orElseThrow(); assertThat(original.outcome()).isEqualTo("NO_PUBLICATION"); assertThat(original.receiptBytes()).isNotEmpty(); @@ -478,14 +474,13 @@ void upgradedTemplateInsertWitnessUsesEpochSafeXidProjectionAndRejectsForgery() .get(0, String.class)) .isEqualTo("1"); assertThatThrownBy(() -> fixture.dsl().fetchSingle("SELECT ('4294967297'::TEXT::XID)::TEXT")) - .satisfies( - failure -> { - Throwable cause = failure; - while (!(cause instanceof SQLException) && cause.getCause() != null) - cause = cause.getCause(); - assertThat(cause).isInstanceOf(SQLException.class); - assertThat(((SQLException) cause).getSQLState()).isEqualTo("22003"); - }); + .satisfies(failure -> { + Throwable cause = failure; + while (!(cause instanceof SQLException) && cause.getCause() != null) + cause = cause.getCause(); + assertThat(cause).isInstanceOf(SQLException.class); + assertThat(((SQLException) cause).getSQLState()).isEqualTo("22003"); + }); Long templateId = fixture @@ -549,17 +544,16 @@ void newParentV1ReservationIsDeniedAndRawV2ReservationUsesActualOwnerSelectionAn () -> fixture .write() - .executeWithoutResult( - status -> - fixture - .dsl() - .execute( - "INSERT INTO game_design_publication_operation (publish_workflow_id, tenant_id, version_id, selection_digest, request_bytes) VALUES (?, ?, ?, ?, ?)", - fixture.operation().workflowId(), - fixture.operation().tenantKey(), - fixture.operation().versionId(), - "sha256:" + "f".repeat(64), - originalV2)), + .executeWithoutResult(status -> + fixture + .dsl() + .execute( + "INSERT INTO game_design_publication_operation (publish_workflow_id, tenant_id, version_id, selection_digest, request_bytes) VALUES (?, ?, ?, ?, ?)", + fixture.operation().workflowId(), + fixture.operation().tenantKey(), + fixture.operation().versionId(), + "sha256:" + "f".repeat(64), + originalV2)), "publication operation does not bind exact selected attempt"); assertThat(retainedRows(fixture)).isEqualTo(before); fixture.write().executeWithoutResult(status -> insertOperation(fixture, originalV2)); @@ -740,59 +734,58 @@ private Fixture fixture(boolean reserveV1, boolean retainReviewedV1) throws Exce new DataSourceTransactionManager(dataSource))); var dsl = DSL.using(configuration); var operation = - write.execute( - status -> { - var requested = new Game(); - requested.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); - requested.setName("ISOLATED passive storage owner"); - var game = new GameRepository(dsl).save(requested); - // Reproduce the original owner insertion under its actual pre-tail schema. The - // current Version writer requires ordinary asset genesis, which did not exist here. - var inserted = - java.util.Objects.requireNonNull( - dsl.fetchOne( - "INSERT INTO version (tenant_id, canonical_version_id, canonical_tenant_id, " - + "identity_source_game_row_id, identity_source_game_tenant_key, " - + "identity_source_provenance_kind, version_number, version_state, " - + "version_state_epoch, is_script_only, created_at, updated_at) " - + "SELECT g.tenant_id, ?, g.canonical_tenant_id, g.id, g.tenant_id, " - + "g.tenant_identity_provenance_kind, 1, 'DRAFT', 1, FALSE, " - + "CURRENT_TIMESTAMP, CURRENT_TIMESTAMP FROM game g WHERE g.id = ? RETURNING id", - UUID.randomUUID(), - game.getId())); - var version = - new VersionRepository(dsl).findById(inserted.get("id", Long.class)).orElseThrow(); - var target = - new TargetProof( - version.getCanonicalTenantId(), - version.getCanonicalVersionId(), - version.getId(), - version.getTenantId(), - version.getIdentitySourceGameRowId(), - version.getIdentitySourceGameTenantKey(), - version.getIdentitySourceProvenanceKind()); - RealmPolicyGenesis reviewedGenesis = null; - String reviewedBaseReference = null; - if (retainReviewedV1) { - reviewedGenesis = new RealmPolicySourceRepository(dsl).recordFreshGenesis(target); - new CommandSourceRepository(dsl) - .enrollNewDraftGenesis( - new CommandSource.NewDraftGenesisReceipt( - target, - reviewedGenesis.receiptId(), - reviewedGenesis.creationTransactionId())); - reviewedBaseReference = "genesis:" + reviewedGenesis.receiptId(); - } - try { - return reserveV1 - ? IsolatedPublicationOwnerSetup.retainHistoricalV1PreV56( - dsl, target, version.getVersionStateEpoch()) - : prepareUnreservedOwnerOperation( - dsl, target, version, reviewedBaseReference, reviewedGenesis); - } catch (Exception failure) { - throw new IllegalStateException(failure); - } - }); + write.execute(status -> { + var requested = new Game(); + requested.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + requested.setName("ISOLATED passive storage owner"); + var game = new GameRepository(dsl).save(requested); + // Reproduce the original owner insertion under its actual pre-tail schema. The + // current Version writer requires ordinary asset genesis, which did not exist here. + var inserted = + java.util.Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO version (tenant_id, canonical_version_id, canonical_tenant_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind, version_number, version_state, " + + "version_state_epoch, is_script_only, created_at, updated_at) " + + "SELECT g.tenant_id, ?, g.canonical_tenant_id, g.id, g.tenant_id, " + + "g.tenant_identity_provenance_kind, 1, 'DRAFT', 1, FALSE, " + + "CURRENT_TIMESTAMP, CURRENT_TIMESTAMP FROM game g WHERE g.id = ? RETURNING id", + UUID.randomUUID(), + game.getId())); + var version = + new VersionRepository(dsl).findById(inserted.get("id", Long.class)).orElseThrow(); + var target = + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + RealmPolicyGenesis reviewedGenesis = null; + String reviewedBaseReference = null; + if (retainReviewedV1) { + reviewedGenesis = new RealmPolicySourceRepository(dsl).recordFreshGenesis(target); + new CommandSourceRepository(dsl) + .enrollNewDraftGenesis( + new CommandSource.NewDraftGenesisReceipt( + target, + reviewedGenesis.receiptId(), + reviewedGenesis.creationTransactionId())); + reviewedBaseReference = "genesis:" + reviewedGenesis.receiptId(); + } + try { + return reserveV1 + ? IsolatedPublicationOwnerSetup.retainHistoricalV1PreV56( + dsl, target, version.getVersionStateEpoch()) + : prepareUnreservedOwnerOperation( + dsl, target, version, reviewedBaseReference, reviewedGenesis); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); return new Fixture( dataSource, schema, @@ -832,15 +825,14 @@ private GameDesignPublicationOperation prepareUnreservedOwnerOperation( coordinator.markOwnerInProgress(draft, DraftCommitBinding.Owner.WORLD_MANAGEMENT); var epochs = draft.affectedUnits().stream() - .map( - unit -> - new DraftCommitCoordinatorRepository.AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .map(unit -> + new DraftCommitCoordinatorRepository.AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) .toList(); var outcome = new DraftCommitCoordinatorRepository.OwnerOutcome( @@ -1112,29 +1104,27 @@ private void requireInventory(Fixture fixture, byte[] bytes) { private void deny(Fixture fixture, Runnable write, String message) { assertThatThrownBy(write::run) .isInstanceOf(RuntimeException.class) - .satisfies( - failure -> { - Throwable cause = failure; - while (!(cause instanceof SQLException) && cause.getCause() != null) - cause = cause.getCause(); - assertThat(cause).isInstanceOf(SQLException.class); - assertThat(((SQLException) cause).getSQLState()).isEqualTo("23514"); - if (message != null) assertThat(cause.getMessage()).contains(message); - }); + .satisfies(failure -> { + Throwable cause = failure; + while (!(cause instanceof SQLException) && cause.getCause() != null) + cause = cause.getCause(); + assertThat(cause).isInstanceOf(SQLException.class); + assertThat(((SQLException) cause).getSQLState()).isEqualTo("23514"); + if (message != null) assertThat(cause.getMessage()).contains(message); + }); } private void denyReviewedBase(Fixture fixture, Runnable write, String message) { assertThatThrownBy(write::run) .isInstanceOf(RuntimeException.class) - .satisfies( - failure -> { - Throwable cause = failure; - while (!(cause instanceof SQLException) && cause.getCause() != null) - cause = cause.getCause(); - assertThat(cause).isInstanceOf(SQLException.class); - assertThat(((SQLException) cause).getSQLState()).isEqualTo("P0001"); - if (message != null) assertThat(cause.getMessage()).contains(message); - }); + .satisfies(failure -> { + Throwable cause = failure; + while (!(cause instanceof SQLException) && cause.getCause() != null) + cause = cause.getCause(); + assertThat(cause).isInstanceOf(SQLException.class); + assertThat(((SQLException) cause).getSQLState()).isEqualTo("P0001"); + if (message != null) assertThat(cause.getMessage()).contains(message); + }); } /** Raw supplied external inventory, matching the published isolated fixture's closed profile. */ @@ -1290,21 +1280,20 @@ private Map inventory(GameDesignPublicationOperation operation) model.put( "appliedEpochs", commit.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - Map.of( - "aggregateType", - unit.aggregateType(), - "aggregateId", - unit.aggregateId(), - "scopeType", - unit.scopeType(), - "scopeId", - unit.scopeId(), - "expectedEpoch", - unit.expectedEpoch(), - "resultingEpoch", - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .map(unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) .toList()); result.put("sourceModel", model); result.put( diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java index 76f8099586..a8e25d3a4e 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/TemplateConfigSourcePostgresIntegrationTest.java @@ -105,10 +105,9 @@ void authoredAutomationInventoryHasExactRetryInheritanceAndFrozenOriginalProvena .get(0, Long.class)) .isEqualTo(1L); - f.tx.executeWithoutResult( - ignored -> - assertThat(new TemplateConfigSourceRepository(f.dsl).apply(declaration).orElseThrow()) - .isEqualTo(new TemplateConfigSourceSnapshot.Application(declaration, "0", first))); + f.tx.executeWithoutResult(ignored -> + assertThat(new TemplateConfigSourceRepository(f.dsl).apply(declaration).orElseThrow()) + .isEqualTo(new TemplateConfigSourceSnapshot.Application(declaration, "0", first))); assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) .isZero(); @@ -140,19 +139,18 @@ void authoredAutomationInventoryHasExactRetryInheritanceAndFrozenOriginalProvena .isEqualTo(1L); var operation = - f.tx.execute( - ignored -> { - try { - return IsolatedPublicationOwnerSetup.retainSourceBacked( - f.dsl, - f.target, - 1L, - "Automation inventory declaration source freeze", - actualTemplate.commitId().toString()); - } catch (Exception e) { - throw new IllegalStateException("Unable to retain source-backed publication", e); - } - }); + f.tx.execute(ignored -> { + try { + return IsolatedPublicationOwnerSetup.retainSourceBacked( + f.dsl, + f.target, + 1L, + "Automation inventory declaration source freeze", + actualTemplate.commitId().toString()); + } catch (Exception e) { + throw new IllegalStateException("Unable to retain source-backed publication", e); + } + }); var capture = Objects.requireNonNull( f.tx.execute( @@ -195,11 +193,9 @@ void latestSameOrderAutomationDeclarationRetainsItsExactBindingAcrossRetryAndInh assertThat(latest.revisionId()).isEqualTo(second.revisions().getFirst().revisionId()); assertThat(latest.inventory()).isEqualTo(inventory); - f.tx.executeWithoutResult( - ignored -> - assertThat(new TemplateConfigSourceRepository(f.dsl).apply(second).orElseThrow()) - .isEqualTo( - new TemplateConfigSourceSnapshot.Application(second, "1", secondSnapshot))); + f.tx.executeWithoutResult(ignored -> + assertThat(new TemplateConfigSourceRepository(f.dsl).apply(second).orElseThrow()) + .isEqualTo(new TemplateConfigSourceSnapshot.Application(second, "1", secondSnapshot))); var unrelated = binding( f, @@ -356,12 +352,10 @@ void v1025RetainsV1AndV2SourceHistoryAcrossLatestUpgradeAndExactBindingRetry() { v1025MigrationHistory.size()) .getValues("history_entry", String.class)) .containsExactlyElementsOf(v1025MigrationHistory); - f.tx.executeWithoutResult( - ignored -> - assertThat(new TemplateConfigSourceRepository(f.dsl).apply(automation).orElseThrow()) - .isEqualTo( - new TemplateConfigSourceSnapshot.Application( - automation, "1", automationSource))); + f.tx.executeWithoutResult(ignored -> + assertThat(new TemplateConfigSourceRepository(f.dsl).apply(automation).orElseThrow()) + .isEqualTo( + new TemplateConfigSourceSnapshot.Application(automation, "1", automationSource))); var migratedDeclaration = f.dsl.fetchSingle( @@ -498,11 +492,9 @@ void v1025RetainsV1AndV2SourceHistoryAcrossLatestUpgradeAndExactBindingRetry() { assertThat(entitySource.entries()).hasSize(1); assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) .isEqualTo(1L); - f.tx.executeWithoutResult( - ignored -> - assertThat(new TemplateConfigSourceRepository(f.dsl).apply(entity).orElseThrow()) - .isEqualTo( - new TemplateConfigSourceSnapshot.Application(entity, "2", entitySource))); + f.tx.executeWithoutResult(ignored -> + assertThat(new TemplateConfigSourceRepository(f.dsl).apply(entity).orElseThrow()) + .isEqualTo(new TemplateConfigSourceSnapshot.Application(entity, "2", entitySource))); var unrelated = binding( @@ -575,14 +567,11 @@ void deferredTemplateApplicationGuardRejectsMissingOrChangedAtomicOwnerResult() DraftCommitBinding.Owner.AUTOMATION_SCRIPTING, automationInventory), TemplateConfigSource.SCOPE, "0"); - assertThatThrownBy( - () -> - f.tx.executeWithoutResult( - ignored -> { - stageInProgressTemplateApplication(f, missingResult); - f.dsl.execute( - "SET CONSTRAINTS template_config_application_commit_guard IMMEDIATE"); - })) + assertThatThrownBy(() -> + f.tx.executeWithoutResult(ignored -> { + stageInProgressTemplateApplication(f, missingResult); + f.dsl.execute("SET CONSTRAINTS template_config_application_commit_guard IMMEDIATE"); + })) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining("template config application requires exact atomic owner result"); @@ -594,27 +583,24 @@ void deferredTemplateApplicationGuardRejectsMissingOrChangedAtomicOwnerResult() DraftCommitBinding.Owner.ENTITY_MANAGEMENT, entityInventory), TemplateConfigSource.SCOPE, "0"); - assertThatThrownBy( - () -> - f.tx.executeWithoutResult( - ignored -> { - var application = stageInProgressTemplateApplication(f, changedResult); - byte[] alteredResultBytes = application.canonicalBytes(); - alteredResultBytes[0] ^= 1; - new DraftCommitCoordinatorRepository(f.dsl) - .recordOwnerOutcome( - changedResult, - new DraftCommitCoordinatorRepository.OwnerOutcome( - DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, - DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, - changedResult.commitId(), - changedResult.digest(), - "ordinary-source:" + changedResult.commitId(), - alteredResultBytes, - List.of(application.appliedEpoch()))); - f.dsl.execute( - "SET CONSTRAINTS template_config_application_commit_guard IMMEDIATE"); - })) + assertThatThrownBy(() -> + f.tx.executeWithoutResult(ignored -> { + var application = stageInProgressTemplateApplication(f, changedResult); + byte[] alteredResultBytes = application.canonicalBytes(); + alteredResultBytes[0] ^= 1; + new DraftCommitCoordinatorRepository(f.dsl) + .recordOwnerOutcome( + changedResult, + new DraftCommitCoordinatorRepository.OwnerOutcome( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + changedResult.commitId(), + changedResult.digest(), + "ordinary-source:" + changedResult.commitId(), + alteredResultBytes, + List.of(application.appliedEpoch()))); + f.dsl.execute("SET CONSTRAINTS template_config_application_commit_guard IMMEDIATE"); + })) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining( "template config owner result must contain exact complete tagged source bytes"); @@ -680,15 +666,14 @@ void actualCreateAndSameCommitGameplayInputHaveDurableGeneratedIdentityAndExactR .isEqualTo("LEGACY"); // Replay reads the actual original stored application, not a second CREATE or current name // lookup. - f.tx.executeWithoutResult( - ignored -> - assertThat( - new GameDesignSourceRepository(f.dsl) - .apply(binding) - .templateConfig() - .orElseThrow() - .snapshot()) - .isEqualTo(first)); + f.tx.executeWithoutResult(ignored -> + assertThat( + new GameDesignSourceRepository(f.dsl) + .apply(binding) + .templateConfig() + .orElseThrow() + .snapshot()) + .isEqualTo(first)); assertThat(f.dsl.fetchSingle("SELECT count(*) FROM game_templates").get(0, Long.class)) .isEqualTo(1L); var sibling = binding(f, commandUpsert("TEMPLATE_SIBLING"), CommandSource.SCOPE, "0"); @@ -735,18 +720,15 @@ void actualCreateAndSameCommitGameplayInputHaveDurableGeneratedIdentityAndExactR .get(0, Long.class)) .isEqualTo(1L); assertThat(source(f, binding)).isEqualTo(first); - assertThatThrownBy( - () -> - f.dsl.execute( - "UPDATE game_design_template_config_source_revision SET payload_json = '{}'")) + assertThatThrownBy(() -> + f.dsl.execute( + "UPDATE game_design_template_config_source_revision SET payload_json = '{}'")) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThatThrownBy(() -> f.dsl.execute("DELETE FROM game_design_template_config_source_ref")) .isInstanceOf(org.jooq.exception.DataAccessException.class); - assertThatThrownBy( - () -> - f.dsl.execute( - "UPDATE game_templates SET config = '{}' WHERE id = ?", - Long.parseLong(templateId))) + assertThatThrownBy(() -> + f.dsl.execute( + "UPDATE game_templates SET config = '{}' WHERE id = ?", Long.parseLong(templateId))) .isInstanceOf(org.jooq.exception.DataAccessException.class); } @@ -799,13 +781,11 @@ void legacyTenantMatchingRowCannotAcquireCanonicalSourceAssociation() { assertThatThrownBy(() -> apply(f, binding)) .isInstanceOf(IllegalStateException.class) .hasMessage("TEMPLATE_CONFIG_TEMPLATE_OWNER_PROVENANCE_UNAVAILABLE"); - assertThatThrownBy( - () -> - f.tx.executeWithoutResult( - ignored -> - f.dsl.execute( - "INSERT INTO game_design_template_config_source_row_insert VALUES (?, pg_current_xact_id()::TEXT)", - legacy))) + assertThatThrownBy(() -> + f.tx.executeWithoutResult(ignored -> + f.dsl.execute( + "INSERT INTO game_design_template_config_source_row_insert VALUES (?, pg_current_xact_id()::TEXT)", + legacy))) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(new TemplateConfigSourceRepository(f.dsl).readSnapshot(f.target, binding.commitId())) .isEmpty(); @@ -814,12 +794,11 @@ void legacyTenantMatchingRowCannotAcquireCanonicalSourceAssociation() { @Test void explicitTargetRawInsertAndLegacyReassignmentCannotCommit() { var f = fixture(); - assertThatThrownBy( - () -> - f.dsl.execute( - "INSERT INTO game_templates (tenant_id, name, config, default_version_id) VALUES (?, 'Raw target', '{}'::JSONB, ?)", - f.target.gameDesignVersionTenantKey(), - f.target.gameDesignVersionRowId())) + assertThatThrownBy(() -> + f.dsl.execute( + "INSERT INTO game_templates (tenant_id, name, config, default_version_id) VALUES (?, 'Raw target', '{}'::JSONB, ?)", + f.target.gameDesignVersionTenantKey(), + f.target.gameDesignVersionRowId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining( "explicit template target requires actual authorized CREATE qualification"); @@ -829,12 +808,11 @@ void explicitTargetRawInsertAndLegacyReassignmentCannotCommit() { "INSERT INTO game_templates (tenant_id, name, config) VALUES (?, 'Unrelated legacy', '{}'::JSONB) RETURNING id", f.target.gameDesignVersionTenantKey()) .get(0, Long.class); - assertThatThrownBy( - () -> - f.dsl.execute( - "UPDATE game_templates SET default_version_id = ? WHERE id = ?", - f.target.gameDesignVersionRowId(), - legacy)) + assertThatThrownBy(() -> + f.dsl.execute( + "UPDATE game_templates SET default_version_id = ? WHERE id = ?", + f.target.gameDesignVersionRowId(), + legacy)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining( "unqualified template cannot be reassigned into managed source target"); @@ -846,12 +824,11 @@ void explicitTargetRawInsertAndLegacyReassignmentCannotCommit() { var selected = binding(f, commandUpsert("TEMPLATE_SELECTED"), CommandSource.SCOPE, "0"); apply(f, selected); assertThat(source(f, selected).entries()).isEmpty(); - assertThatThrownBy( - () -> - f.dsl.execute( - "INSERT INTO game_templates (tenant_id, name, config, default_version_id) VALUES (?, 'After capture', '{}'::JSONB, ?)", - f.target.gameDesignVersionTenantKey(), - f.target.gameDesignVersionRowId())) + assertThatThrownBy(() -> + f.dsl.execute( + "INSERT INTO game_templates (tenant_id, name, config, default_version_id) VALUES (?, 'After capture', '{}'::JSONB, ?)", + f.target.gameDesignVersionTenantKey(), + f.target.gameDesignVersionRowId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining( "explicit template target requires actual authorized CREATE qualification"); @@ -862,18 +839,16 @@ void explicitTargetRawInsertAndLegacyReassignmentCannotCommit() { void newCaptureCannotIgnorePendingUnqualifiedExplicitTargetRow() { var f = fixture(); var selected = binding(f, commandUpsert("TEMPLATE_BLOCKED"), CommandSource.SCOPE, "0"); - assertThatThrownBy( - () -> - f.tx.executeWithoutResult( - ignored -> { - // The deferred insert guard has not fired: new source capture must - // independently deny. - f.dsl.execute( - "INSERT INTO game_templates (tenant_id, name, config, default_version_id) VALUES (?, 'Pending raw target', '{}'::JSONB, ?)", - f.target.gameDesignVersionTenantKey(), - f.target.gameDesignVersionRowId()); - apply(f, selected); - })) + assertThatThrownBy(() -> + f.tx.executeWithoutResult(ignored -> { + // The deferred insert guard has not fired: new source capture must + // independently deny. + f.dsl.execute( + "INSERT INTO game_templates (tenant_id, name, config, default_version_id) VALUES (?, 'Pending raw target', '{}'::JSONB, ?)", + f.target.gameDesignVersionTenantKey(), + f.target.gameDesignVersionRowId()); + apply(f, selected); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("TEMPLATE_CONFIG_EXPLICIT_TARGET_INVENTORY_UNQUALIFIED"); assertThat( @@ -971,15 +946,14 @@ void selectedPublicationRetainsInheritedTemplateToOriginalWorldSourceAssociation selectedPublicationInputs(f, selectedCommit, "selected inherited template association"); var reservation = Objects.requireNonNull( - f.tx.execute( - ignored -> - new SelectedDraftPublicationOwner(f.dsl) - .reserve( - inputs.intent(), - inputs.operation().account(), - inputs.operation().world(), - inputs.operation().inventory(), - inputs.firstRead()))); + f.tx.execute(ignored -> + new SelectedDraftPublicationOwner(f.dsl) + .reserve( + inputs.intent(), + inputs.operation().account(), + inputs.operation().world(), + inputs.operation().inventory(), + inputs.firstRead()))); var operation = reservation.operation(); var returnedGameplayCapture = reservation.sourceCapture().gameplay(); assertThat(returnedGameplayCapture).isPresent(); @@ -1036,15 +1010,14 @@ void selectedPublicationRetainsInheritedTemplateToOriginalWorldSourceAssociation originalWorldSourceRead.request().intakeRequestId(), originalWorldSourceRead.request().canonicalTenantId()), originalWorldSourceRead.receipt()); - f.tx.executeWithoutResult( - ignored -> - new SelectedDraftPublicationOwner(f.dsl) - .reserve( - selection.intent(), - operation.account(), - operation.world(), - operation.inventory(), - replayWorldSourceRead)); + f.tx.executeWithoutResult(ignored -> + new SelectedDraftPublicationOwner(f.dsl) + .reserve( + selection.intent(), + operation.account(), + operation.world(), + operation.inventory(), + replayWorldSourceRead)); assertThat(associations.readExact(operation, templateCapture).getFirst().canonicalBytes()) .containsExactly(retained.getFirst().canonicalBytes()); var originalReceipt = originalWorldSourceRead.receipt(); @@ -1074,25 +1047,22 @@ void selectedPublicationRetainsInheritedTemplateToOriginalWorldSourceAssociation originalWorldSourceRead.request().intakeRequestId(), originalWorldSourceRead.request().canonicalTenantId()), substitutedReceipt); - assertThatThrownBy( - () -> - f.tx.executeWithoutResult( - ignored -> - new SelectedDraftPublicationOwner(f.dsl) - .reserve( - selection.intent(), - operation.account(), - operation.world(), - operation.inventory(), - substitutedWorldSourceRead))) + assertThatThrownBy(() -> + f.tx.executeWithoutResult(ignored -> + new SelectedDraftPublicationOwner(f.dsl) + .reserve( + selection.intent(), + operation.account(), + operation.world(), + operation.inventory(), + substitutedWorldSourceRead))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("ASSOCIATION_CONFLICT"); assertThat(associations.readExact(operation, templateCapture).getFirst().canonicalBytes()) .containsExactly(retained.getFirst().canonicalBytes()); - assertThatThrownBy( - () -> - f.dsl.execute( - "UPDATE game_design_selected_template_world_source_association SET world_slug = 'substituted'")) + assertThatThrownBy(() -> + f.dsl.execute( + "UPDATE game_design_selected_template_world_source_association SET world_slug = 'substituted'")) .isInstanceOf(org.jooq.exception.DataAccessException.class); } @@ -1187,17 +1157,16 @@ private static SelectedDraftPublicationOwner.Reservation concurrentReserve( throw new IllegalStateException("Timed out waiting to start concurrent owner reservation"); } return Objects.requireNonNull( - f.tx.execute( - ignored -> - new SelectedDraftPublicationOwner(f.dsl) - .reserve( - AuthoredDraftPublishSelection.fromStored( - selection.canonicalJson(), selection.digest()) - .intent(), - operation.account(), - operation.world(), - operation.inventory(), - sourceRead)), + f.tx.execute(ignored -> + new SelectedDraftPublicationOwner(f.dsl) + .reserve( + AuthoredDraftPublishSelection.fromStored( + selection.canonicalJson(), selection.digest()) + .intent(), + operation.account(), + operation.world(), + operation.inventory(), + sourceRead)), "concurrent owner reservation returned no result"); } @@ -1205,36 +1174,35 @@ private SelectedPublicationInputs selectedPublicationInputs( Fixture f, DraftCommitBinding selectedCommit, String notes) throws Exception { var prepared = Objects.requireNonNull( - f.tx.execute( - ignored -> { - String versionEpoch = - Objects.requireNonNull( - f.dsl - .fetchSingle( - "SELECT version_state_epoch FROM version WHERE id = ?", - f.target.gameDesignVersionRowId()) - .get(0, Long.class)) - .toString(); - var intent = - new AuthoredDraftPublishSelection.PublishIntent( - f.target.canonicalTenantId(), - f.target.canonicalVersionId(), - UUID.randomUUID().toString(), - versionEpoch, - notes, - selectedCommit.requestId(), - selectedCommit.commitId(), - selectedCommit.digest()); - var coordinator = new DraftCommitCoordinatorRepository(f.dsl); - var evidence = - coordinator.requireSynchronizedPublicationEvidence( - f.target, - selectedCommit.requestId(), - selectedCommit.commitId(), - selectedCommit.digest()); - return new PreparedSelection( - intent, AuthoredDraftPublishSelection.capture(intent, f.target, evidence)); - })); + f.tx.execute(ignored -> { + String versionEpoch = + Objects.requireNonNull( + f.dsl + .fetchSingle( + "SELECT version_state_epoch FROM version WHERE id = ?", + f.target.gameDesignVersionRowId()) + .get(0, Long.class)) + .toString(); + var intent = + new AuthoredDraftPublishSelection.PublishIntent( + f.target.canonicalTenantId(), + f.target.canonicalVersionId(), + UUID.randomUUID().toString(), + versionEpoch, + notes, + selectedCommit.requestId(), + selectedCommit.commitId(), + selectedCommit.digest()); + var coordinator = new DraftCommitCoordinatorRepository(f.dsl); + var evidence = + coordinator.requireSynchronizedPublicationEvidence( + f.target, + selectedCommit.requestId(), + selectedCommit.commitId(), + selectedCommit.digest()); + return new PreparedSelection( + intent, AuthoredDraftPublishSelection.capture(intent, f.target, evidence)); + })); var selection = AuthoredDraftPublishSelectionBinding.fromStored( prepared.selection().canonicalJson(), prepared.selection().digest()); @@ -1336,68 +1304,62 @@ private TemplateConfigSourceSnapshot source(Fixture f, DraftCommitBinding bindin } private void apply(Fixture f, DraftCommitBinding binding) { - f.tx.executeWithoutResult( - ignored -> { - var coordinator = new DraftCommitCoordinatorRepository(f.dsl); - var reviewed = new GameDesignReviewedBaseRepository(f.dsl); - var sources = new GameDesignSourceRepository(f.dsl); - sources.claimReviewed( - binding, - reviewed.resolve(f.target, DraftBaseReference.parse(binding.baseCommitId()))); - coordinator.claimApplicationSlot(binding); - coordinator.markOwnerInProgress( - binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); - var applied = sources.apply(binding); - coordinator.advanceSourceVisibilityFence( - binding, - new DraftCommitCoordinatorRepository.CoordinatorProof( - binding, List.of(applied.ownerOutcome()))); - sources.captureSynchronized(binding); - coordinator.releaseApplicationSlot(binding); - }); + f.tx.executeWithoutResult(ignored -> { + var coordinator = new DraftCommitCoordinatorRepository(f.dsl); + var reviewed = new GameDesignReviewedBaseRepository(f.dsl); + var sources = new GameDesignSourceRepository(f.dsl); + sources.claimReviewed( + binding, reviewed.resolve(f.target, DraftBaseReference.parse(binding.baseCommitId()))); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress(binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + var applied = sources.apply(binding); + coordinator.advanceSourceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof( + binding, List.of(applied.ownerOutcome()))); + sources.captureSynchronized(binding); + coordinator.releaseApplicationSlot(binding); + }); } /** Retains controlled World owner/source inputs without reserving the publication under test. */ private void applyIsolatedWorldSuccessor( Fixture f, DraftCommitBinding binding, WorldPublishedStartLocationEvidence worldEvidence) { - f.tx.executeWithoutResult( - ignored -> { - var coordinator = new DraftCommitCoordinatorRepository(f.dsl); - var reviewed = new GameDesignReviewedBaseRepository(f.dsl); - var sources = new GameDesignSourceRepository(f.dsl); - sources.claimReviewed( - binding, - reviewed.resolve(f.target, DraftBaseReference.parse(binding.baseCommitId()))); - coordinator.claimApplicationSlot(binding); - coordinator.markOwnerInProgress(binding, DraftCommitBinding.Owner.WORLD_MANAGEMENT); - var appliedEpochs = - binding.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new DraftCommitCoordinatorRepository.AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) - .toList(); - var outcome = - new DraftCommitCoordinatorRepository.OwnerOutcome( - DraftCommitBinding.Owner.WORLD_MANAGEMENT, - DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, - binding.commitId(), - binding.digest(), - "ISOLATED-world-applied", - worldEvidence.appliedResultBytes(), - appliedEpochs); - coordinator.recordOwnerOutcome(binding, outcome); - coordinator.advanceSourceVisibilityFence( - binding, - new DraftCommitCoordinatorRepository.CoordinatorProof(binding, List.of(outcome))); - sources.captureSynchronized(binding); - coordinator.releaseApplicationSlot(binding); - }); + f.tx.executeWithoutResult(ignored -> { + var coordinator = new DraftCommitCoordinatorRepository(f.dsl); + var reviewed = new GameDesignReviewedBaseRepository(f.dsl); + var sources = new GameDesignSourceRepository(f.dsl); + sources.claimReviewed( + binding, reviewed.resolve(f.target, DraftBaseReference.parse(binding.baseCommitId()))); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress(binding, DraftCommitBinding.Owner.WORLD_MANAGEMENT); + var appliedEpochs = + binding.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map(unit -> + new DraftCommitCoordinatorRepository.AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(); + var outcome = + new DraftCommitCoordinatorRepository.OwnerOutcome( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + DraftCommitCoordinatorRepository.OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "ISOLATED-world-applied", + worldEvidence.appliedResultBytes(), + appliedEpochs); + coordinator.recordOwnerOutcome(binding, outcome); + coordinator.advanceSourceVisibilityFence( + binding, + new DraftCommitCoordinatorRepository.CoordinatorProof(binding, List.of(outcome))); + sources.captureSynchronized(binding); + coordinator.releaseApplicationSlot(binding); + }); } private static TemplateConfigSourceSnapshot.Application stageInProgressTemplateApplication( @@ -1481,15 +1443,14 @@ private DraftCommitBinding binding( Fixture f, List revisions, Map scopes) { var units = scopes.entrySet().stream() - .map( - e -> - new DraftCommitBinding.AffectedUnit( - DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, - e.getKey(), - f.target.canonicalVersionId().toString(), - e.getKey(), - "effective", - e.getValue())) + .map(e -> + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + e.getKey(), + f.target.canonicalVersionId().toString(), + e.getKey(), + "effective", + e.getValue())) .toList(); return DraftCommitBinding.create( f.target, UUID.randomUUID(), UUID.randomUUID(), currentBaseReference(f), revisions, units); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepositoryPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepositoryPostgresIntegrationTest.java index ca1ca3488d..00717af423 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepositoryPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepositoryPostgresIntegrationTest.java @@ -132,11 +132,10 @@ void rolledBackGameplayWriteLeavesFreshGenesisAndNoStagedOrVisibleHistory() { var binding = fixture.binding("0", fixture.genesisBase(), upsert("10")); fixture .write() - .executeWithoutResult( - status -> { - fixture.stageInTransaction(binding); - status.setRollbackOnly(); - }); + .executeWithoutResult(status -> { + fixture.stageInTransaction(binding); + status.setRollbackOnly(); + }); var owner = new GameplayRuleSourceRepository(fixture.sql()); assertThat(owner.readGenesis(fixture.target())).isPresent(); assertThat(owner.readSnapshot(fixture.target(), binding.commitId())).isEmpty(); @@ -151,17 +150,15 @@ void nonemptyReferencedGameplayCatalogSharesAssetOutcomeAndRetainsInheritedSourc var asset = fixture .write() - .execute( - ignored -> { - var value = new GameAsset(); - value.setTenantId(fixture.target().gameDesignVersionTenantKey()); - value.setFileName("catalog-resource.png"); - value.setContentType("image/png"); - value.setData( - "actual catalog asset bytes" - .getBytes(java.nio.charset.StandardCharsets.UTF_8)); - return new GameAssetRepository(fixture.sql()).save(value); - }); + .execute(ignored -> { + var value = new GameAsset(); + value.setTenantId(fixture.target().gameDesignVersionTenantKey()); + value.setFileName("catalog-resource.png"); + value.setContentType("image/png"); + value.setData( + "actual catalog asset bytes".getBytes(java.nio.charset.StandardCharsets.UTF_8)); + return new GameAssetRepository(fixture.sql()).save(value); + }); var payloads = new java.util.ArrayList<>(gameplayPayloads()); payloads.add( AssetSource.upsertPayload( @@ -228,10 +225,9 @@ void gameplayHandoffDeniesUnqualifiedLegacyEffectiveCommands() { new GameplayRuleSourceRepository(fixture.sql()) .readSnapshot(binding.target(), binding.commitId())) .isPresent(); - assertThatThrownBy( - () -> - new GameplayRuleSourceRepository(fixture.sql()) - .requireCompleteForGameLogic(binding.target(), binding.commitId())) + assertThatThrownBy(() -> + new GameplayRuleSourceRepository(fixture.sql()) + .requireCompleteForGameLogic(binding.target(), binding.commitId())) .isInstanceOf(IllegalStateException.class) .hasMessage("GAMEPLAY_RULE_LEGACY_COMMAND_SOURCE_NOT_CONVERGED"); } @@ -269,10 +265,9 @@ void gameplayHandoffDeniesGenericRuleEvenWhenTypedRevisionMatches(boolean legacy () -> repository.requireCompleteForGameLogic(binding.target(), binding.commitId())) .isInstanceOf(IllegalStateException.class) .hasMessage("GAMEPLAY_RULE_GENERIC_SOURCE_NOT_CONVERGED"); - assertThatThrownBy( - () -> - new GameplayRuleSourceRepository(fixture.sql()) - .requireCompleteForGameLogic(binding.target(), binding.commitId())) + assertThatThrownBy(() -> + new GameplayRuleSourceRepository(fixture.sql()) + .requireCompleteForGameLogic(binding.target(), binding.commitId())) .isInstanceOf(IllegalStateException.class) .hasMessage("GAMEPLAY_RULE_GENERIC_SOURCE_NOT_CONVERGED"); assertThat(repository.readSnapshot(binding.target(), binding.commitId()).orElseThrow()) @@ -287,23 +282,21 @@ void gameplayHandoffGenericRuleGuardUsesExactPrivateTenantAndVersion(boolean dif Version otherVersion = fixture .write() - .execute( - ignored -> { - var value = new Version(); - value.setTenantId(fixture.target().gameDesignVersionTenantKey()); - value.setVersionNumber(2); - return new VersionRepository(fixture.sql()).save(value); - }); + .execute(ignored -> { + var value = new Version(); + value.setTenantId(fixture.target().gameDesignVersionTenantKey()); + value.setVersionNumber(2); + return new VersionRepository(fixture.sql()).save(value); + }); String foreignTenant = fixture .write() - .execute( - ignored -> { - var value = new Game(); - value.setTenantId("foreign-" + UUID.randomUUID().toString().substring(0, 8)); - value.setName("Controlled foreign legacy history scope"); - return new GameRepository(fixture.sql()).save(value).getTenantId(); - }); + .execute(ignored -> { + var value = new Game(); + value.setTenantId("foreign-" + UUID.randomUUID().toString().substring(0, 8)); + value.setName("Controlled foreign legacy history scope"); + return new GameRepository(fixture.sql()).save(value).getTenantId(); + }); var binding = fixture.binding("0", fixture.genesisBase(), gameplayPayloads().toArray(String[]::new)); fixture.stage(binding); @@ -442,21 +435,19 @@ private static Fixture fixture() { var sql = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); var sources = new GameDesignSourceRepository(sql); var game = - write.execute( - ignored -> { - var requested = new Game(); - requested.setTenantId("rule-" + UUID.randomUUID().toString().substring(0, 8)); - requested.setName("Isolated authored gameplay rules"); - return new GameRepository(sql).save(requested); - }); + write.execute(ignored -> { + var requested = new Game(); + requested.setTenantId("rule-" + UUID.randomUUID().toString().substring(0, 8)); + requested.setName("Isolated authored gameplay rules"); + return new GameRepository(sql).save(requested); + }); Version version = - write.execute( - ignored -> { - var requested = new Version(); - requested.setTenantId(game.getTenantId()); - requested.setVersionNumber(1); - return new VersionRepository(sql).save(requested); - }); + write.execute(ignored -> { + var requested = new Version(); + requested.setTenantId(game.getTenantId()); + requested.setVersionNumber(1); + return new VersionRepository(sql).save(requested); + }); var target = new TargetProof( version.getCanonicalTenantId(), @@ -538,21 +529,20 @@ void stageInTransaction(DraftCommitBinding binding) { } void synchronize(DraftCommitBinding binding) { - write.executeWithoutResult( - ignored -> { - var coordinator = new DraftCommitCoordinatorRepository(sql); - var outcome = - coordinator - .read(target, binding.requestId()) - .orElseThrow() - .ownerStates() - .get(Owner.GAME_DESIGN_CONTROL_PLANE) - .outcome() - .orElseThrow(); - IsolatedPublicationOwnerSetup.advanceIsolatedSourceVisibility( - sql, binding, List.of(outcome)); - coordinator.releaseApplicationSlot(binding); - }); + write.executeWithoutResult(ignored -> { + var coordinator = new DraftCommitCoordinatorRepository(sql); + var outcome = + coordinator + .read(target, binding.requestId()) + .orElseThrow() + .ownerStates() + .get(Owner.GAME_DESIGN_CONTROL_PLANE) + .outcome() + .orElseThrow(); + IsolatedPublicationOwnerSetup.advanceIsolatedSourceVisibility( + sql, binding, List.of(outcome)); + coordinator.releaseApplicationSlot(binding); + }); } } } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java index db0c4959dd..9a18bf97a9 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java @@ -130,12 +130,11 @@ void fixtureOwnerMigrationPreservesGenuineHumanPolicyRowsAndExactRetry() throws assertThat(retainedHeader.get(fixtureField)).as(fixtureField).isNull(); } var retry = - fixture.tx( - () -> - fixture - .publicationWrites() - .retainSealedPublished(operation.workflowId()) - .orElseThrow()); + fixture.tx(() -> + fixture + .publicationWrites() + .retainSealedPublished(operation.workflowId()) + .orElseThrow()); assertPublishedSetUnchanged(original, retry); assertThat(retainedPolicyOwnerRows(fixture)).isEqualTo(originalRows); } @@ -172,14 +171,12 @@ void retainedAndFreshPolicyPublicationsSurviveAdditiveReleaseColumn() throws Exc .get("evidence", String.class); assertThat(originalReleaseEvidence).isEqualTo(originalWholeReleaseRow); - fixture.tx( - () -> { - fixture - .dsl() - .execute( - "ALTER TABLE published_release_bundle ADD COLUMN future_optional_evidence TEXT"); - return null; - }); + fixture.tx(() -> { + fixture + .dsl() + .execute("ALTER TABLE published_release_bundle ADD COLUMN future_optional_evidence TEXT"); + return null; + }); String expandedWholeReleaseRow = java.util.Objects.requireNonNull( fixture @@ -210,12 +207,11 @@ void retainedAndFreshPolicyPublicationsSurviveAdditiveReleaseColumn() throws Exc assertRejectedHeaderClonesPreserveOriginal(fixture, original); var exactRetry = - fixture.tx( - () -> - fixture - .publicationWrites() - .retainSealedPublished(operation.workflowId()) - .orElseThrow()); + fixture.tx(() -> + fixture + .publicationWrites() + .retainSealedPublished(operation.workflowId()) + .orElseThrow()); assertThat(exactRetry.policies().getFirst().policyId()) .isEqualTo(original.policies().getFirst().policyId()); assertThat(exactRetry.policySetDigest()).isEqualTo(original.policySetDigest()); @@ -238,41 +234,36 @@ void retainedAndFreshPolicyPublicationsSurviveAdditiveReleaseColumn() throws Exc .policyId()) .isEqualTo(original.policies().getFirst().policyId()); var retryAfterActivation = - fixture.tx( - () -> - fixture - .publicationWrites() - .retainSealedPublished(operation.workflowId()) - .orElseThrow()); + fixture.tx(() -> + fixture + .publicationWrites() + .retainSealedPublished(operation.workflowId()) + .orElseThrow()); assertThat(retryAfterActivation.policies().getFirst().policyId()) .isEqualTo(original.policies().getFirst().policyId()); assertThat(retryAfterActivation.policySetDigest()).isEqualTo(original.policySetDigest()); assertThat(retryAfterActivation.terminalEvidenceBytes()) .containsExactly(original.terminalEvidenceBytes()); - assertThatThrownBy( - () -> - fixture.tx( - () -> - fixture - .dsl() - .execute( - "UPDATE game_design_published_realm_policy_set " - + "SET policy_set_digest = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", - "sha256:" + "f".repeat(64), - fixture.target().canonicalTenantId(), - fixture.target().canonicalVersionId()))) + assertThatThrownBy(() -> + fixture.tx(() -> + fixture + .dsl() + .execute( + "UPDATE game_design_published_realm_policy_set " + + "SET policy_set_digest = ? WHERE canonical_tenant_id = ? AND canonical_version_id = ?", + "sha256:" + "f".repeat(64), + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()))) .isInstanceOf(RuntimeException.class); Fixture fresh = fixture(true); - fresh.tx( - () -> { - fresh - .dsl() - .execute( - "ALTER TABLE published_release_bundle ADD COLUMN future_optional_evidence TEXT"); - return null; - }); + fresh.tx(() -> { + fresh + .dsl() + .execute("ALTER TABLE published_release_bundle ADD COLUMN future_optional_evidence TEXT"); + return null; + }); GameDesignPublicationOperation freshOperation = fresh.prepare(true); fresh.writePublish(freshOperation, false); var freshRead = fresh.publicationReads().readPublishedSet(fresh.target()).orElseThrow(); @@ -290,12 +281,11 @@ void retainedAndFreshPolicyPublicationsSurviveAdditiveReleaseColumn() throws Exc byte[] freshReceipt = freshOwnerRead.receiptBytes(); assertThat(freshReceipt).isNotNull(); var freshRetry = - fresh.tx( - () -> - fresh - .publicationWrites() - .retainSealedPublished(freshOperation.workflowId()) - .orElseThrow()); + fresh.tx(() -> + fresh + .publicationWrites() + .retainSealedPublished(freshOperation.workflowId()) + .orElseThrow()); assertThat(freshRetry.policies().getFirst().policyId()) .isEqualTo(freshRead.policies().getFirst().policyId()); assertThat(freshRetry.operationBytes()).containsExactly(freshRead.operationBytes()); @@ -320,13 +310,12 @@ void openSetRejectsReplacedSourceAndWrongOrdinalWhileKeepingInheritedProvenance( // A second stipulated ISOLATED owner baseline replaces the main policy. The genuine // publication selection then inherits it through the ordinary frozen-source path. var replacementBinding = - fixture.tx( - () -> - baseline( - fixture.target(), - fixture.dsl(), - new GameDesignSourceRepository(fixture.dsl()), - "Replacement World")); + fixture.tx(() -> + baseline( + fixture.target(), + fixture.dsl(), + new GameDesignSourceRepository(fixture.dsl()), + "Replacement World")); GameDesignPublicationOperation operation = fixture.prepare(true); var selected = fixture.policySource().readCapture(operation).orElseThrow().snapshot(); var replacement = selected.policies().getFirst(); @@ -363,12 +352,11 @@ public void executeEnd(ExecuteContext context) { assertThat(published.policies()).hasSize(1); assertThat(published.policies().getFirst().source()).isEqualTo(replacement); var retry = - fixture.tx( - () -> - fixture - .publicationWrites() - .retainSealedPublished(operation.workflowId()) - .orElseThrow()); + fixture.tx(() -> + fixture + .publicationWrites() + .retainSealedPublished(operation.workflowId()) + .orElseThrow()); assertPublishedSetUnchanged(published, retry); assertPublishedSetUnchanged( published, fixture.publicationReads().readPublishedSet(fixture.target()).orElseThrow()); @@ -399,37 +387,34 @@ private static void assertRejectedOpenSetPolicy( release.publishWorkflowId(), release.manifestHash(), source); - assertThatThrownBy( - () -> - fixture - .dsl() - .transaction( - nested -> - DSL.using(nested) - .execute( - "INSERT INTO game_design_published_realm_policy " - + "(canonical_tenant_id, canonical_version_id, ordinal, realm_policy_id, " - + "source_commit_id, source_revision_id, logical_revision_id, world_slug, realm_slug, " - + "policy_json, policy_digest, visible, public_production) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - fixture.target().canonicalTenantId(), - fixture.target().canonicalVersionId(), - ordinal, - policyId, - source.commitId(), - source.revisionId(), - source.logicalRevisionId(), - policy.worldSlug(), - policy.realmSlug(), - policy.canonicalJson(), - digest, - policy.visible(), - policy.publicProduction()))) - .satisfies( - failure -> - assertThat(rootCause(failure).getMessage()) - .contains( - "published realm policy row differs from exact captured source revision")); + assertThatThrownBy(() -> + fixture + .dsl() + .transaction(nested -> + DSL.using(nested) + .execute( + "INSERT INTO game_design_published_realm_policy " + + "(canonical_tenant_id, canonical_version_id, ordinal, realm_policy_id, " + + "source_commit_id, source_revision_id, logical_revision_id, world_slug, realm_slug, " + + "policy_json, policy_digest, visible, public_production) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId(), + ordinal, + policyId, + source.commitId(), + source.revisionId(), + source.logicalRevisionId(), + policy.worldSlug(), + policy.realmSlug(), + policy.canonicalJson(), + digest, + policy.visible(), + policy.publicProduction()))) + .satisfies(failure -> + assertThat(rootCause(failure).getMessage()) + .contains( + "published realm policy row differs from exact captured source revision")); assertThat(fixture.dsl().fetchCount(DSL.table("game_design_published_realm_policy"))).isZero(); } @@ -502,26 +487,24 @@ private static Fixture fixture(boolean isolatedPolicyBaseline, String migrationT var games = new GameRepository(dsl); var versions = new VersionRepository(dsl); Game game = - write.execute( - status -> { - var requested = new Game(); - requested.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); - requested.setName("ISOLATED realm policy publication"); - return games.save(requested); - }); + write.execute(status -> { + var requested = new Game(); + requested.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + requested.setName("ISOLATED realm policy publication"); + return games.save(requested); + }); Version version = - write.execute( - status -> { - var requested = new Version(); - requested.setTenantId(game.getTenantId()); - requested.setVersionNumber(1); - Version created = versions.save(requested); - sources - .readGenesis(target(created)) - .orElseThrow( - () -> new IllegalStateException("fresh Version lacks actual source genesis")); - return created; - }); + write.execute(status -> { + var requested = new Version(); + requested.setTenantId(game.getTenantId()); + requested.setVersionNumber(1); + Version created = versions.save(requested); + sources + .readGenesis(target(created)) + .orElseThrow( + () -> new IllegalStateException("fresh Version lacks actual source genesis")); + return created; + }); TargetProof target = target(version); var baseline = isolatedPolicyBaseline @@ -748,18 +731,16 @@ private static void assertRejectedHeaderClonePreservesOriginal( .isEqualTo(original.policyCount()); String sql = headerCloneInsertSql(replacementColumn, replacementExpression); - assertThatThrownBy( - () -> - fixture.tx( - () -> { - fixture - .dsl() - .execute( - sql, - fixture.target().canonicalTenantId(), - fixture.target().canonicalVersionId()); - return null; - })) + assertThatThrownBy(() -> + fixture.tx(() -> { + fixture + .dsl() + .execute( + sql, + fixture.target().canonicalTenantId(), + fixture.target().canonicalVersionId()); + return null; + })) .satisfies( failure -> assertThat(rootCause(failure).getMessage()).contains(expectedGuardMessage)); @@ -781,12 +762,11 @@ private static String headerCloneInsertSql( String columnList = String.join(", ", PUBLISHED_SET_COLUMNS); String selectList = PUBLISHED_SET_COLUMNS.stream() - .map( - column -> { - if ("sealed".equals(column)) return "FALSE"; - if (column.equals(replacementColumn)) return replacementExpression; - return "existing." + column; - }) + .map(column -> { + if ("sealed".equals(column)) return "FALSE"; + if (column.equals(replacementColumn)) return replacementExpression; + return "existing." + column; + }) .collect(java.util.stream.Collectors.joining(", ")); return "INSERT INTO game_design_published_realm_policy_set (" + columnList @@ -896,63 +876,52 @@ T tx(Supplier work) { } GameDesignPublicationOperation prepare(boolean capturePolicySource) throws Exception { - return tx( - () -> { - try { - var sources = new GameDesignSourceRepository(dsl); - String sourceBaseReference = currentSourceHead(target, dsl, sources).baseReference(); - var operation = - IsolatedPublicationOwnerSetup.retainSourceBacked( - dsl, - target, - 1, - "ISOLATED remote owner transaction proof", - sourceBaseReference); - if (capturePolicySource) { - sources.freeze(operation); - } - return operation; - } catch (Exception failure) { - throw new IllegalStateException(failure); - } - }); + return tx(() -> { + try { + var sources = new GameDesignSourceRepository(dsl); + String sourceBaseReference = currentSourceHead(target, dsl, sources).baseReference(); + var operation = + IsolatedPublicationOwnerSetup.retainSourceBacked( + dsl, target, 1, "ISOLATED remote owner transaction proof", sourceBaseReference); + if (capturePolicySource) { + sources.freeze(operation); + } + return operation; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); } /** Retains command, policy, and asset captures as the predecessor operation did. */ GameDesignPublicationOperation preparePreGameplayCaptures() throws Exception { - return tx( - () -> { - try { - var sources = new GameDesignSourceRepository(dsl); - String sourceBaseReference = currentSourceHead(target, dsl, sources).baseReference(); - var operation = - IsolatedPublicationOwnerSetup.retainSourceBacked( - dsl, - target, - 1, - "ISOLATED remote owner transaction proof", - sourceBaseReference); - new CommandSourceRepository(dsl).freeze(operation); - policySource.freeze(operation); - new AssetSourceRepository(dsl).freeze(operation); - return operation; - } catch (Exception failure) { - throw new IllegalStateException(failure); - } - }); + return tx(() -> { + try { + var sources = new GameDesignSourceRepository(dsl); + String sourceBaseReference = currentSourceHead(target, dsl, sources).baseReference(); + var operation = + IsolatedPublicationOwnerSetup.retainSourceBacked( + dsl, target, 1, "ISOLATED remote owner transaction proof", sourceBaseReference); + new CommandSourceRepository(dsl).freeze(operation); + policySource.freeze(operation); + new AssetSourceRepository(dsl).freeze(operation); + return operation; + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); } void writePublish(GameDesignPublicationOperation operation, boolean rollBack) throws Exception { - write.executeWithoutResult( - status -> { - try { - IsolatedPublicationOwnerSetup.commitStorage( - dsl, versions, operation, () -> saveBundle(operation)); - if (rollBack) status.setRollbackOnly(); - } catch (Exception failure) { - throw new IllegalStateException(failure); - } - }); + write.executeWithoutResult(status -> { + try { + IsolatedPublicationOwnerSetup.commitStorage( + dsl, versions, operation, () -> saveBundle(operation)); + if (rollBack) status.setRollbackOnly(); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); } PublishedReleaseBundle saveBundle(GameDesignPublicationOperation operation) { @@ -964,18 +933,17 @@ PublishedReleaseBundle saveBundle(GameDesignPublicationOperation operation) { } void moveVersion(VersionLifecycleState next, long epoch) { - tx( - () -> { - var version = - versions - .findByTenantIdAndIdForUpdate( - target.gameDesignVersionTenantKey(), target.gameDesignVersionRowId()) - .orElseThrow(); - version.setVersionState(next); - version.setVersionStateEpoch(epoch); - versions.save(version); - return null; - }); + tx(() -> { + var version = + versions + .findByTenantIdAndIdForUpdate( + target.gameDesignVersionTenantKey(), target.gameDesignVersionRowId()) + .orElseThrow(); + version.setVersionState(next); + version.setVersionStateEpoch(epoch); + versions.save(version); + return null; + }); } } } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java index ddd732ca20..a78382511d 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptPostgresIntegrationTest.java @@ -59,10 +59,9 @@ void migrationPreservesHistoricalSelectionAndReceiptReadbackIsImmutableAndExact( fixture.tx().executeWithoutResult(ignored -> repository.retain(value)); fixture .tx() - .executeWithoutResult( - ignored -> - assertThat(repository.retain(value).receipt().canonicalBytes()) - .containsExactly(value.receipt().canonicalBytes())); + .executeWithoutResult(ignored -> + assertThat(repository.retain(value).receipt().canonicalBytes()) + .containsExactly(value.receipt().canonicalBytes())); var recovered = repository.read(value.selection(), value.authorization()).orElseThrow(); assertThat(recovered.receipt().canonicalBytes()) .containsExactly(value.receipt().canonicalBytes()); @@ -96,21 +95,16 @@ void migrationPreservesHistoricalSelectionAndReceiptReadbackIsImmutableAndExact( value.authorization().sources()); assertThatThrownBy(() -> repository.read(value.selection(), changed)) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_design_selected_game_logic_receipt SET receipt_bytes = ?", - new byte[] {1})) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_design_selected_game_logic_receipt SET receipt_bytes = ?", + new byte[] {1})) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThatThrownBy(() -> dsl.execute("DELETE FROM game_design_selected_game_logic_receipt")) .isInstanceOf(org.jooq.exception.DataAccessException.class); - assertThatThrownBy( - () -> - insert( - dsl, - value, - value.selection().canonicalBytes(), - value.receipt().canonicalBytes())) + assertThatThrownBy(() -> + insert( + dsl, value, value.selection().canonicalBytes(), value.receipt().canonicalBytes())) .isInstanceOf(org.jooq.exception.DataAccessException.class); } @@ -136,23 +130,21 @@ void publicationReadUsesExactTenantAndRequestAndRejectsChangedVersionOrPatchScop Long.toString(value.selection().target().gameDesignVersionRowId()), value.selection().intent().publishRequestId()))) .isEmpty(); - assertThatThrownBy( - () -> - repository.readForPublication( - PublicationDigestRequestBinding.full( - value.selection().intent().canonicalTenantId().toString(), - Long.toString(value.selection().target().gameDesignVersionRowId() + 1), - value.selection().intent().publishRequestId()))) + assertThatThrownBy(() -> + repository.readForPublication( + PublicationDigestRequestBinding.full( + value.selection().intent().canonicalTenantId().toString(), + Long.toString(value.selection().target().gameDesignVersionRowId() + 1), + value.selection().intent().publishRequestId()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("does not match publication request"); - assertThatThrownBy( - () -> - repository.readForPublication( - PublicationDigestRequestBinding.patch( - value.selection().intent().canonicalTenantId().toString(), - "1", - "patch-1", - value.selection().intent().publishRequestId()))) + assertThatThrownBy(() -> + repository.readForPublication( + PublicationDigestRequestBinding.patch( + value.selection().intent().canonicalTenantId().toString(), + "1", + "patch-1", + value.selection().intent().publishRequestId()))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("FULL_VERSION"); assertThat( @@ -330,10 +322,9 @@ private static void assertCurrentCaptureReceiptJoin(boolean changeReceiptSource) if (changeReceiptSource) { assertThatThrownBy(() -> digestReader.read("test", publicationBinding(readback), readback)) .isInstanceOf(io.grpc.StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(io.grpc.Status.fromThrowable(failure).getCode()) - .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); } else { assertThat( digestReader @@ -407,43 +398,40 @@ private static CurrentCaptureFixture currentCaptureFixture() throws Exception { tx.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); DraftCommitBinding.TargetProof target = - tx.execute( - ignored -> { - var game = new Game(); - game.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); - game.setName("ISOLATED captured Gameplay join"); - game = new GameRepository(dsl).save(game); - var version = new Version(); - version.setTenantId(game.getTenantId()); - version.setVersionNumber(1); - version = new VersionRepository(dsl).save(version); - var proof = - new DraftCommitBinding.TargetProof( - version.getCanonicalTenantId(), - version.getCanonicalVersionId(), - version.getId(), - version.getTenantId(), - version.getIdentitySourceGameRowId(), - version.getIdentitySourceGameTenantKey(), - version.getIdentitySourceProvenanceKind()); - new GameDesignSourceRepository(dsl).enrollFreshDraft(proof); - return proof; - }); + tx.execute(ignored -> { + var game = new Game(); + game.setTenantId("ISOLATED-" + UUID.randomUUID().toString().substring(0, 8)); + game.setName("ISOLATED captured Gameplay join"); + game = new GameRepository(dsl).save(game); + var version = new Version(); + version.setTenantId(game.getTenantId()); + version.setVersionNumber(1); + version = new VersionRepository(dsl).save(version); + var proof = + new DraftCommitBinding.TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + new GameDesignSourceRepository(dsl).enrollFreshDraft(proof); + return proof; + }); var sources = new GameDesignSourceRepository(dsl); GameDesignPublicationOperation operation = - tx.execute( - ignored -> { - try { - var retained = - IsolatedPublicationOwnerSetup.retainFrozenSourceBacked( - dsl, target, 1L, "controlled exact Gameplay receipt join"); - sources.freeze(retained); - return retained; - } catch (Exception failure) { - throw new IllegalStateException( - "Unable to retain controlled source capture", failure); - } - }); + tx.execute(ignored -> { + try { + var retained = + IsolatedPublicationOwnerSetup.retainFrozenSourceBacked( + dsl, target, 1L, "controlled exact Gameplay receipt join"); + sources.freeze(retained); + return retained; + } catch (Exception failure) { + throw new IllegalStateException("Unable to retain controlled source capture", failure); + } + }); return new CurrentCaptureFixture(dsl, tx, transactionManager, target, sources, operation); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/TemplateReferencePhasePostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/TemplateReferencePhasePostgresIntegrationTest.java index 84d89f00ce..b5c05fb0b9 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/TemplateReferencePhasePostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/TemplateReferencePhasePostgresIntegrationTest.java @@ -57,13 +57,11 @@ void freshOwnerCreationStartsBackfillingAndEmptyInventoryCannotAdvance() { assertThat(phase.sourceGameRowId()).isEqualTo(fixture.creation().sourceGameRowId()); assertThat(phase.sourceGameTenantKey()).isEqualTo(fixture.creation().sourceGameTenantKey()); - assertThatThrownBy( - () -> - fixture - .tx() - .execute( - ignored -> - references.validateAndEnforce(fixture.target().canonicalTenantId()))) + assertThatThrownBy(() -> + fixture + .tx() + .execute( + ignored -> references.validateAndEnforce(fixture.target().canonicalTenantId()))) .isInstanceOf(IllegalStateException.class) .hasMessage("TEMPLATE_REFERENCE_INVENTORY_EMPTY"); assertThat(references.readPhase(fixture.target().canonicalTenantId()).orElseThrow()) @@ -74,14 +72,12 @@ void freshOwnerCreationStartsBackfillingAndEmptyInventoryCannotAdvance() { applyTemplateSourceMutation( fixture, TemplateConfigSource.deletePayload(deletedTemplateId), "1"); assertThat(sourceSnapshot(fixture, deleted).entries()).isEmpty(); - assertThatThrownBy( - () -> - fixture - .tx() - .execute( - ignored -> - new TemplateReferenceRepository(fixture.dsl()) - .validateAndEnforce(fixture.target().canonicalTenantId()))) + assertThatThrownBy(() -> + fixture + .tx() + .execute(ignored -> + new TemplateReferenceRepository(fixture.dsl()) + .validateAndEnforce(fixture.target().canonicalTenantId()))) .isInstanceOf(IllegalStateException.class) .hasMessage("TEMPLATE_REFERENCE_INVENTORY_EMPTY"); assertThat( @@ -135,10 +131,9 @@ void latestDeleteAfterDecimalEpochBoundaryDoesNotBlockActiveTemplate() { var enforced = fixture .tx() - .execute( - ignored -> - new TemplateReferenceRepository(fixture.dsl()) - .validateAndEnforce(fixture.target().canonicalTenantId())); + .execute(ignored -> + new TemplateReferenceRepository(fixture.dsl()) + .validateAndEnforce(fixture.target().canonicalTenantId())); assertThat(enforced).isNotNull(); assertThat(enforced.phase()).isEqualTo(TemplateReferenceRepository.Phase.ENFORCED); assertThat(enforced.inventoryTemplateCount()).isEqualTo(1L); @@ -167,13 +162,11 @@ void upsertCannotResurrectDeletedTemplateAndFailureLeavesCurrentSourceUsable() { assertThat(currentSource.entries().getFirst().sourceBinding().commitId()) .isEqualTo(active.commitId()); - assertThatThrownBy( - () -> - applyTemplateSourceMutation( - fixture, - TemplateConfigSource.upsertPayload( - reactivatedTemplateId, templateConfig(fixture)), - "3")) + assertThatThrownBy(() -> + applyTemplateSourceMutation( + fixture, + TemplateConfigSource.upsertPayload(reactivatedTemplateId, templateConfig(fixture)), + "3")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Template source identity is not an existing qualified entry"); assertThat(sourceSnapshot(fixture, deleted)).isEqualTo(currentSource); @@ -224,10 +217,9 @@ reactivatedTemplateId, templateConfig(fixture)), var enforced = fixture .tx() - .execute( - ignored -> - new TemplateReferenceRepository(fixture.dsl()) - .validateAndEnforce(fixture.target().canonicalTenantId())); + .execute(ignored -> + new TemplateReferenceRepository(fixture.dsl()) + .validateAndEnforce(fixture.target().canonicalTenantId())); assertThat(enforced).isNotNull(); assertThat(enforced.phase()).isEqualTo(TemplateReferenceRepository.Phase.ENFORCED); assertThat(enforced.inventoryTemplateCount()).isEqualTo(1L); @@ -263,18 +255,16 @@ void qualifiedCurrentSourceCanEnforcePhaseAndRawCreateIsThenDenied() { assertThat(enforced.inventoryTemplateCount()).isEqualTo(1L); assertThat(enforced.inventoryDigest()).startsWith("sha256:"); - assertThatThrownBy( - () -> - fixture - .tx() - .executeWithoutResult( - ignored -> - fixture - .dsl() - .execute( - "INSERT INTO game_templates (tenant_id, name, config) " - + "VALUES (?, 'Raw bypass', '{}'::JSONB)", - fixture.creation().sourceGameTenantKey()))) + assertThatThrownBy(() -> + fixture + .tx() + .executeWithoutResult(ignored -> + fixture + .dsl() + .execute( + "INSERT INTO game_templates (tenant_id, name, config) " + + "VALUES (?, 'Raw bypass', '{}'::JSONB)", + fixture.creation().sourceGameTenantKey()))) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining( "validated template create requires exact active owner source binding"); @@ -356,23 +346,20 @@ void unqualifiedPhysicalTemplatePreventsTenantPromotion() { createTemplate(fixture, "Qualified"); fixture .tx() - .executeWithoutResult( - ignored -> - fixture - .dsl() - .execute( - "INSERT INTO game_templates (tenant_id, name, config) " - + "VALUES (?, 'Unqualified', '{}'::JSONB)", - fixture.creation().sourceGameTenantKey())); - - assertThatThrownBy( - () -> - fixture - .tx() - .execute( - ignored -> - new TemplateReferenceRepository(fixture.dsl()) - .validateAndEnforce(fixture.target().canonicalTenantId()))) + .executeWithoutResult(ignored -> + fixture + .dsl() + .execute( + "INSERT INTO game_templates (tenant_id, name, config) " + + "VALUES (?, 'Unqualified', '{}'::JSONB)", + fixture.creation().sourceGameTenantKey())); + + assertThatThrownBy(() -> + fixture + .tx() + .execute(ignored -> + new TemplateReferenceRepository(fixture.dsl()) + .validateAndEnforce(fixture.target().canonicalTenantId()))) .isInstanceOf(IllegalStateException.class) .hasMessage("TEMPLATE_REFERENCE_INVENTORY_UNQUALIFIED"); assertThat( @@ -443,32 +430,29 @@ private DraftCommitBinding applyTemplateSourceMutation( var sources = new GameDesignSourceRepository(fixture.dsl()); fixture .tx() - .executeWithoutResult( - ignored -> { - var coordinator = new DraftCommitCoordinatorRepository(fixture.dsl()); - var reviewed = new GameDesignReviewedBaseRepository(fixture.dsl()); - sources.claimReviewed( - binding, - reviewed.resolve( - fixture.target(), DraftBaseReference.parse(binding.baseCommitId()))); - coordinator.claimApplicationSlot(binding); - coordinator.markOwnerInProgress( - binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); - var applied = sources.apply(binding); - if (sourceAwareVisibility) { - net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup - .advanceIsolatedSourceVisibility( - fixture.dsl(), binding, List.of(applied.ownerOutcome())); - } else { - // These primitive-level cases deliberately leave promotion to the explicit - // validator. - net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup - .advanceIsolatedVisibility( - fixture.dsl(), binding, List.of(applied.ownerOutcome())); - sources.captureSynchronized(binding); - } - coordinator.releaseApplicationSlot(binding); - }); + .executeWithoutResult(ignored -> { + var coordinator = new DraftCommitCoordinatorRepository(fixture.dsl()); + var reviewed = new GameDesignReviewedBaseRepository(fixture.dsl()); + sources.claimReviewed( + binding, + reviewed.resolve(fixture.target(), DraftBaseReference.parse(binding.baseCommitId()))); + coordinator.claimApplicationSlot(binding); + coordinator.markOwnerInProgress( + binding, DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE); + var applied = sources.apply(binding); + if (sourceAwareVisibility) { + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .advanceIsolatedSourceVisibility( + fixture.dsl(), binding, List.of(applied.ownerOutcome())); + } else { + // These primitive-level cases deliberately leave promotion to the explicit + // validator. + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .advanceIsolatedVisibility(fixture.dsl(), binding, List.of(applied.ownerOutcome())); + sources.captureSynchronized(binding); + } + coordinator.releaseApplicationSlot(binding); + }); return binding; } @@ -530,15 +514,14 @@ private Fixture fixture() { String tenantKey = UUID.randomUUID().toString(); FreshTenantCreationEvidence creation = Objects.requireNonNull( - tx.execute( - ignored -> - new GameTenantCreationRepository(dsl, new GameRepository(dsl)) - .createCandidate( - "template-phase-test", - requestId, - tenantKey, - "Template reference phase fixture", - null))); + tx.execute(ignored -> + new GameTenantCreationRepository(dsl, new GameRepository(dsl)) + .createCandidate( + "template-phase-test", + requestId, + tenantKey, + "Template reference phase fixture", + null))); Version version = new Version(); version.setTenantId(tenantKey); version.setVersionNumber(1); diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/AccountAuthorizedTenantCreationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/AccountAuthorizedTenantCreationPostgresIntegrationTest.java index 8ff7f93a36..b1fada9934 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/AccountAuthorizedTenantCreationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/AccountAuthorizedTenantCreationPostgresIntegrationTest.java @@ -81,20 +81,18 @@ void commitsExactV30V1033ReceiptAndV1034AccountDeadlineFenceAtomically() { long validBefore = System.currentTimeMillis() + 60_000L; FreshTenantCreationEvidence receipt = - fixture.inTransaction( - () -> { - fixture.dispatches.applyLocalWriteTimeouts(); - assertThat(fixture.dispatches.isAuthorizationCurrent(validBefore)).isTrue(); - OriginalOutcomeSnapshot claim = fixture.outcomes.claimLocked(binding); - assertThat(claim.status()).isEqualTo(OutcomeStatus.PENDING); - FreshTenantCreationEvidence created = - fixture.creation.createCandidate( - NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION); - fixture.outcomes.markCreatedLocked(binding, created); - fixture.dispatches.recordAuthorizedDispatch( - binding, AUTHORIZATION_READ_ID, validBefore); - return created; - }); + fixture.inTransaction(() -> { + fixture.dispatches.applyLocalWriteTimeouts(); + assertThat(fixture.dispatches.isAuthorizationCurrent(validBefore)).isTrue(); + OriginalOutcomeSnapshot claim = fixture.outcomes.claimLocked(binding); + assertThat(claim.status()).isEqualTo(OutcomeStatus.PENDING); + FreshTenantCreationEvidence created = + fixture.creation.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION); + fixture.outcomes.markCreatedLocked(binding, created); + fixture.dispatches.recordAuthorizedDispatch(binding, AUTHORIZATION_READ_ID, validBefore); + return created; + }); OriginalOutcomeSnapshot outcome = fixture.outcomes.readCommitted(binding).orElseThrow(); var dispatch = fixture.dispatches.readCommitted(binding).orElseThrow(); @@ -115,22 +113,20 @@ void commitTimeDeadlineGuardRollsBackTenantAndBothOwnerEvidenceRows() { Binding binding = repositoryBinding(); long expiredBefore = System.currentTimeMillis() - 1_000L; - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> { - fixture.dispatches.applyLocalWriteTimeouts(); - fixture.outcomes.claimLocked(binding); - FreshTenantCreationEvidence receipt = - fixture.creation.createCandidate( - NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION); - fixture.outcomes.markCreatedLocked(binding, receipt); - // Intentionally bypass the preflight clock check to exercise V1034's deferred - // fresh-clock commit guard and prove the whole owner transaction rolls back. - fixture.dispatches.recordAuthorizedDispatch( - binding, AUTHORIZATION_READ_ID, expiredBefore); - return receipt; - })) + assertThatThrownBy(() -> + fixture.inTransaction(() -> { + fixture.dispatches.applyLocalWriteTimeouts(); + fixture.outcomes.claimLocked(binding); + FreshTenantCreationEvidence receipt = + fixture.creation.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION); + fixture.outcomes.markCreatedLocked(binding, receipt); + // Intentionally bypass the preflight clock check to exercise V1034's deferred + // fresh-clock commit guard and prove the whole owner transaction rolls back. + fixture.dispatches.recordAuthorizedDispatch( + binding, AUTHORIZATION_READ_ID, expiredBefore); + return receipt; + })) .isInstanceOf(RuntimeException.class) .hasStackTraceContaining("authorization expired before Game Design commit"); @@ -153,41 +149,36 @@ void tombstoneHoldingSharedIdentityLockBlocksDelayedAuthorizedCreation() throws try { Future tombstone = - executor.submit( - () -> - fixture.inTransaction( - () -> { - OriginalOutcomeSnapshot closed = - fixture.outcomes.closeNotCreatedLocked(binding); - tombstoneWritten.countDown(); - await(allowTombstoneCommit); - return closed; - })); + executor.submit(() -> + fixture.inTransaction(() -> { + OriginalOutcomeSnapshot closed = fixture.outcomes.closeNotCreatedLocked(binding); + tombstoneWritten.countDown(); + await(allowTombstoneCommit); + return closed; + })); assertThat(tombstoneWritten.await(10, TimeUnit.SECONDS)).isTrue(); Future delayedAuthorizedCreate = - executor.submit( - () -> { - try { - fixture.inTransaction( - () -> { - fixture.dispatches.applyLocalWriteTimeouts(); - if (!fixture.dispatches.isAuthorizationCurrent( - System.currentTimeMillis() + 60_000L)) { - throw new IllegalStateException("Controlled authorization expired"); - } - OriginalOutcomeSnapshot claim = fixture.outcomes.claimLocked(binding); - if (claim.status() == OutcomeStatus.NOT_CREATED) { - throw new IllegalStateException("Definitive tombstone blocks creation"); - } - return fixture.creation.createCandidate( - NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION); - }); - return null; - } catch (RuntimeException failure) { - return failure; + executor.submit(() -> { + try { + fixture.inTransaction(() -> { + fixture.dispatches.applyLocalWriteTimeouts(); + if (!fixture.dispatches.isAuthorizationCurrent( + System.currentTimeMillis() + 60_000L)) { + throw new IllegalStateException("Controlled authorization expired"); } + OriginalOutcomeSnapshot claim = fixture.outcomes.claimLocked(binding); + if (claim.status() == OutcomeStatus.NOT_CREATED) { + throw new IllegalStateException("Definitive tombstone blocks creation"); + } + return fixture.creation.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION); }); + return null; + } catch (RuntimeException failure) { + return failure; + } + }); waitForAdvisoryWaiter(fixture.dsl); allowTombstoneCommit.countDown(); @@ -251,22 +242,20 @@ void explicitClosureCommitsExactTombstoneAndRefusesChangedBindingAndDelayedCreat NAMESPACE, REQUEST_ID)); owner.closeOriginal(binding); - assertThatThrownBy( - () -> - owner.closeOriginal( - new Binding( - NAMESPACE, - REQUEST_ID, - ACCOUNT_OPERATION_ID, - UUID.randomUUID(), - REQUEST_DIGEST, - ACCOUNT_DIGEST))) + assertThatThrownBy(() -> + owner.closeOriginal( + new Binding( + NAMESPACE, + REQUEST_ID, + ACCOUNT_OPERATION_ID, + UUID.randomUUID(), + REQUEST_DIGEST, + ACCOUNT_DIGEST))) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - owner.create( - new AccountAuthorizedTenantCreationService.CandidateRequest( - UUID.randomUUID(), binding, SOURCE_KEY, NAME, DESCRIPTION))) + assertThatThrownBy(() -> + owner.create( + new AccountAuthorizedTenantCreationService.CandidateRequest( + UUID.randomUUID(), binding, SOURCE_KEY, NAME, DESCRIPTION))) .isInstanceOf(IllegalStateException.class); assertThat( java.util.Objects.requireNonNull( @@ -292,33 +281,30 @@ void creationHoldingOriginalLockWinsAgainstExplicitClosureWithoutOverwritingCrea ExecutorService executor = Executors.newFixedThreadPool(2); try { Future creation = - executor.submit( - () -> - fixture.inTransaction( - () -> { - var binding = repositoryBinding(); - fixture.outcomes.claimLocked(binding); - var receipt = - fixture.creation.createCandidate( - NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION); - fixture.outcomes.markCreatedLocked(binding, receipt); - fixture.dispatches.recordAuthorizedDispatch( - binding, AUTHORIZATION_READ_ID, System.currentTimeMillis() + 60000); - created.countDown(); - await(releaseCommit); - return receipt; - })); + executor.submit(() -> + fixture.inTransaction(() -> { + var binding = repositoryBinding(); + fixture.outcomes.claimLocked(binding); + var receipt = + fixture.creation.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION); + fixture.outcomes.markCreatedLocked(binding, receipt); + fixture.dispatches.recordAuthorizedDispatch( + binding, AUTHORIZATION_READ_ID, System.currentTimeMillis() + 60000); + created.countDown(); + await(releaseCommit); + return receipt; + })); assertThat(created.await(10, TimeUnit.SECONDS)).isTrue(); Future closure = - executor.submit( - () -> { - try { - owner.closeOriginal(closureBinding()); - return null; - } catch (RuntimeException failure) { - return failure; - } - }); + executor.submit(() -> { + try { + owner.closeOriginal(closureBinding()); + return null; + } catch (RuntimeException failure) { + return failure; + } + }); waitForAdvisoryWaiter(fixture.dsl); releaseCommit.countDown(); var receipt = creation.get(10, TimeUnit.SECONDS); @@ -389,16 +375,15 @@ private record Fixture( AccountAuthorizedTenantCreationRepository dispatches, TransactionTemplate write) { private T inTransaction(java.util.concurrent.Callable work) { - return write.execute( - status -> { - try { - return work.call(); - } catch (RuntimeException exception) { - throw exception; - } catch (Exception exception) { - throw new IllegalStateException(exception); - } - }); + return write.execute(status -> { + try { + return work.call(); + } catch (RuntimeException exception) { + throw exception; + } catch (Exception exception) { + throw new IllegalStateException(exception); + } + }); } } } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java index 603ac9cbbb..ea8c910ddf 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceDeliveryIntegrationTest.java @@ -165,24 +165,22 @@ void sourceAndDeliveryIntentRollBackTogether() { UUID registrationRequestId = uuid("22222222-2222-4222-8222-222222222222"); AtomicReference sourceRef = new AtomicReference<>(); - assertThatThrownBy( - () -> - fixture - .transactionTemplate() - .execute( - status -> { - sourceRef.set( - fixture - .sourceRepository() - .register( - NAMESPACE, - registrationRequestId, - fixture.freshGame().getCanonicalTenantId(), - "rollback-tenant", - "rollback-world", - "Rollback World")); - throw new IllegalStateException("simulate failed source owner commit"); - })) + assertThatThrownBy(() -> + fixture + .transactionTemplate() + .execute(status -> { + sourceRef.set( + fixture + .sourceRepository() + .register( + NAMESPACE, + registrationRequestId, + fixture.freshGame().getCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World")); + throw new IllegalStateException("simulate failed source owner commit"); + })) .hasMessageContaining("simulate failed source owner commit"); AuthoredWorldSourceEvidence attempted = sourceRef.get(); @@ -215,26 +213,24 @@ void databaseRejectsDeliverySourceRebindingAndReceiptMutation() { .execute(status -> fixture.deliveryRepository().acknowledge(pending, receipt)); assertThat(acknowledged).isNotNull(); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "UPDATE game_design_authored_world_source_deliveries " - + "SET source_evidence_digest = ? WHERE source_operation_id = ?", - digest('d'), - source.operationId())) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "UPDATE game_design_authored_world_source_deliveries " + + "SET source_evidence_digest = ? WHERE source_operation_id = ?", + digest('d'), + source.operationId())) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("claim cannot be rebound"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "UPDATE game_design_authored_world_source_deliveries " - + "SET world_receipt_digest = ? WHERE source_operation_id = ?", - digest('e'), - source.operationId())) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "UPDATE game_design_authored_world_source_deliveries " + + "SET world_receipt_digest = ? WHERE source_operation_id = ?", + digest('e'), + source.operationId())) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("acknowledgement is immutable"); assertThat(fixture.deliveryRepository().read(source.operationId()).orElseThrow()) @@ -462,45 +458,44 @@ private AuthoredWorldSourceEvidence seedPreDeliverySource( fixture .transactionTemplate() - .execute( - status -> { - fixture - .dsl() - .execute( - "INSERT INTO game_design_tenant_slug_binding " - + "(target_namespace, canonical_tenant_id, tenant_slug, " - + "source_game_row_id, source_game_tenant_key, provenance_kind) " - + "VALUES (?, ?, ?, ?, ?, ?)", - source.targetNamespace(), - source.canonicalTenantId(), - source.tenantSlug(), - source.sourceGameRowId(), - source.sourceGameTenantKey(), - source.provenanceKind()); - fixture - .dsl() - .execute( - "INSERT INTO game_design_authored_world_source_operations " - + "(operation_id, schema_version, target_namespace, " - + "registration_request_id, request_digest, canonical_tenant_id, " - + "tenant_slug, world_slug, world_display_name, source_game_row_id, " - + "source_game_tenant_key, provenance_kind, evidence_digest) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - source.operationId(), - source.schemaVersion(), - source.targetNamespace(), - source.registrationRequestId(), - source.requestDigest(), - source.canonicalTenantId(), - source.tenantSlug(), - source.worldSlug(), - source.worldDisplayName(), - source.sourceGameRowId(), - source.sourceGameTenantKey(), - source.provenanceKind(), - source.evidenceDigest()); - return null; - }); + .execute(status -> { + fixture + .dsl() + .execute( + "INSERT INTO game_design_tenant_slug_binding " + + "(target_namespace, canonical_tenant_id, tenant_slug, " + + "source_game_row_id, source_game_tenant_key, provenance_kind) " + + "VALUES (?, ?, ?, ?, ?, ?)", + source.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + fixture + .dsl() + .execute( + "INSERT INTO game_design_authored_world_source_operations " + + "(operation_id, schema_version, target_namespace, " + + "registration_request_id, request_digest, canonical_tenant_id, " + + "tenant_slug, world_slug, world_display_name, source_game_row_id, " + + "source_game_tenant_key, provenance_kind, evidence_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + source.operationId(), + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + return null; + }); return source; } @@ -579,15 +574,14 @@ AuthoredWorldSourceEvidence register( String tenantSlug, String worldSlug) { AuthoredWorldSourceEvidence source = - transactionTemplate.execute( - status -> - sourceRepository.register( - targetNamespace, - registrationRequestId, - sourceGame.getCanonicalTenantId(), - tenantSlug, - worldSlug, - "Authored World " + worldSlug)); + transactionTemplate.execute(status -> + sourceRepository.register( + targetNamespace, + registrationRequestId, + sourceGame.getCanonicalTenantId(), + tenantSlug, + worldSlug, + "Authored World " + worldSlug)); return java.util.Objects.requireNonNull(source); } @@ -607,15 +601,14 @@ AuthoredWorldSourceEvidence register( String worldSlug, String worldDisplayName) { AuthoredWorldSourceEvidence source = - transactionTemplate.execute( - status -> - sourceRepository.register( - NAMESPACE, - registrationRequestId, - canonicalTenantId, - tenantSlug, - worldSlug, - worldDisplayName)); + transactionTemplate.execute(status -> + sourceRepository.register( + NAMESPACE, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName)); return java.util.Objects.requireNonNull(source); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java index 8e9a89e7b9..71ee43b622 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameAuthoredWorldSourceRepositoryIntegrationTest.java @@ -127,14 +127,13 @@ void exactRetryReusesBothDigestsAndChangedRequestLeavesNoSecondClaim() { original.targetNamespace())) .contains(original); - assertThatThrownBy( - () -> - fixture.register( - requestId, - fixture.freshCanonicalTenantId(), - "stable-tenant", - "first-world", - "Changed World")) + assertThatThrownBy(() -> + fixture.register( + requestId, + fixture.freshCanonicalTenantId(), + "stable-tenant", + "first-world", + "Changed World")) .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) .hasMessageContaining("reused with changed input"); assertThat(gameXmin(fixture.dsl, "fresh-authored-tenant")).isEqualTo(gameXmin); @@ -146,26 +145,20 @@ void exactRetryReusesBothDigestsAndChangedRequestLeavesNoSecondClaim() { @Test void registrationRequiresOwnerTransactionAndReadRequiresCommittedOutcome() { Fixture fixture = fixtureWithRetainedAndFreshGame(); - assertThatThrownBy( - () -> - fixture.repository.register( - NAMESPACE, - uuid(11), - fixture.freshCanonicalTenantId(), - "transaction-tenant", - "transaction-world", - "Transaction World")) + assertThatThrownBy(() -> + fixture.repository.register( + NAMESPACE, + uuid(11), + fixture.freshCanonicalTenantId(), + "transaction-tenant", + "transaction-world", + "Transaction World")) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("active Game Design owner transaction"); - assertThatThrownBy( - () -> - fixture.transactionTemplate.execute( - status -> - fixture.repository.read( - uuid(12), - fixture.freshCanonicalTenantId(), - "transaction-world", - NAMESPACE))) + assertThatThrownBy(() -> + fixture.transactionTemplate.execute(status -> + fixture.repository.read( + uuid(12), fixture.freshCanonicalTenantId(), "transaction-world", NAMESPACE))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("committed-outcome owner read"); assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isZero(); @@ -178,27 +171,25 @@ void tenantSlugAndWorldSlugCollisionsFailWithoutPartialAssignments() { fixture.register( uuid(20), fixture.freshCanonicalTenantId(), "claimed-tenant", "one-world", "One World"); - assertThatThrownBy( - () -> - fixture.register( - uuid(21), - fixture.retainedCanonicalTenantId(), - "claimed-tenant", - "other-world", - "Other World")) + assertThatThrownBy(() -> + fixture.register( + uuid(21), + fixture.retainedCanonicalTenantId(), + "claimed-tenant", + "other-world", + "Other World")) .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) .hasMessageContaining("already owned"); assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); assertThat(fixture.dsl.fetchCount(OPERATIONS)).isEqualTo(1); - assertThatThrownBy( - () -> - fixture.register( - uuid(22), - fixture.freshCanonicalTenantId(), - "claimed-tenant", - "one-world", - "Different world metadata")) + assertThatThrownBy(() -> + fixture.register( + uuid(22), + fixture.freshCanonicalTenantId(), + "claimed-tenant", + "one-world", + "Different world metadata")) .isInstanceOf(GameAuthoredWorldSourceRepository.RegistrationConflictException.class) .hasMessageContaining("selector is already owned"); assertThat(fixture.dsl.fetchCount(TENANT_BINDINGS)).isEqualTo(1); @@ -209,19 +200,17 @@ void tenantSlugAndWorldSlugCollisionsFailWithoutPartialAssignments() { @Test void failedOwnerCommitRollsBackBothTenantSelectorAndWorldSource() { Fixture fixture = fixtureWithRetainedAndFreshGame(); - assertThatThrownBy( - () -> - fixture.transactionTemplate.execute( - status -> { - fixture.repository.register( - NAMESPACE, - uuid(30), - fixture.freshCanonicalTenantId(), - "rollback-tenant", - "rollback-world", - "Rollback World"); - throw new IllegalStateException("simulate failed owner commit"); - })) + assertThatThrownBy(() -> + fixture.transactionTemplate.execute(status -> { + fixture.repository.register( + NAMESPACE, + uuid(30), + fixture.freshCanonicalTenantId(), + "rollback-tenant", + "rollback-world", + "Rollback World"); + throw new IllegalStateException("simulate failed owner commit"); + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("simulate failed owner commit"); @@ -240,28 +229,26 @@ void failedOwnerCommitRollsBackBothTenantSelectorAndWorldSource() { @Test void databaseRejectsSelectorClaimsWithoutAnAtomicWorldSourceOperation() { Fixture fixture = fixtureWithRetainedAndFreshGame(); - assertThatThrownBy( - () -> - fixture.transactionTemplate.execute( - status -> { - fixture - .dsl - .insertInto(TENANT_BINDINGS) - .set(DSL.field(DSL.name("target_namespace"), String.class), NAMESPACE) - .set( - DSL.field(DSL.name("canonical_tenant_id"), UUID.class), - fixture.freshCanonicalTenantId()) - .set(DSL.field(DSL.name("tenant_slug"), String.class), "orphan-tenant") - .set( - DSL.field(DSL.name("source_game_row_id"), Long.class), - fixture.freshGameRowId()) - .set( - DSL.field(DSL.name("source_game_tenant_key"), String.class), - "fresh-authored-tenant") - .set(DSL.field(DSL.name("provenance_kind"), String.class), "NEW_GAME_ROW") - .execute(); - return null; - })) + assertThatThrownBy(() -> + fixture.transactionTemplate.execute(status -> { + fixture + .dsl + .insertInto(TENANT_BINDINGS) + .set(DSL.field(DSL.name("target_namespace"), String.class), NAMESPACE) + .set( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class), + fixture.freshCanonicalTenantId()) + .set(DSL.field(DSL.name("tenant_slug"), String.class), "orphan-tenant") + .set( + DSL.field(DSL.name("source_game_row_id"), Long.class), + fixture.freshGameRowId()) + .set( + DSL.field(DSL.name("source_game_tenant_key"), String.class), + "fresh-authored-tenant") + .set(DSL.field(DSL.name("provenance_kind"), String.class), "NEW_GAME_ROW") + .execute(); + return null; + })) .isInstanceOf(RuntimeException.class) .hasStackTraceContaining("cannot commit without a world source"); @@ -272,29 +259,26 @@ void databaseRejectsSelectorClaimsWithoutAnAtomicWorldSourceOperation() { @Test void databaseRejectsTenantSelectorBoundToContradictoryGameProvenance() { Fixture fixture = fixtureWithRetainedAndFreshGame(); - assertThatThrownBy( - () -> - fixture.transactionTemplate.execute( - status -> { - fixture - .dsl - .insertInto(TENANT_BINDINGS) - .set(DSL.field(DSL.name("target_namespace"), String.class), NAMESPACE) - .set( - DSL.field(DSL.name("canonical_tenant_id"), UUID.class), - fixture.freshCanonicalTenantId()) - .set( - DSL.field(DSL.name("tenant_slug"), String.class), "mismatched-tenant") - .set( - DSL.field(DSL.name("source_game_row_id"), Long.class), - fixture.freshGameRowId()) - .set( - DSL.field(DSL.name("source_game_tenant_key"), String.class), - "retained-authored-tenant") - .set(DSL.field(DSL.name("provenance_kind"), String.class), "NEW_GAME_ROW") - .execute(); - return null; - })) + assertThatThrownBy(() -> + fixture.transactionTemplate.execute(status -> { + fixture + .dsl + .insertInto(TENANT_BINDINGS) + .set(DSL.field(DSL.name("target_namespace"), String.class), NAMESPACE) + .set( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class), + fixture.freshCanonicalTenantId()) + .set(DSL.field(DSL.name("tenant_slug"), String.class), "mismatched-tenant") + .set( + DSL.field(DSL.name("source_game_row_id"), Long.class), + fixture.freshGameRowId()) + .set( + DSL.field(DSL.name("source_game_tenant_key"), String.class), + "retained-authored-tenant") + .set(DSL.field(DSL.name("provenance_kind"), String.class), "NEW_GAME_ROW") + .execute(); + return null; + })) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("does not match its game row"); @@ -331,28 +315,26 @@ void readIsExactAndPersistedBindingsAndSourceOperationsAreImmutable() { "other-namespace")) .isEmpty(); - assertThatThrownBy( - () -> - fixture - .dsl - .update(OPERATIONS) - .set(WORLD_DISPLAY_NAME, "Mutated") - .where(OPERATION_ID.eq(receipt.operationId())) - .execute()) + assertThatThrownBy(() -> + fixture + .dsl + .update(OPERATIONS) + .set(WORLD_DISPLAY_NAME, "Mutated") + .where(OPERATION_ID.eq(receipt.operationId())) + .execute()) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("evidence is immutable"); - assertThatThrownBy( - () -> - fixture - .dsl - .deleteFrom(TENANT_BINDINGS) - .where( - DSL.field(DSL.name("target_namespace"), String.class) - .eq(receipt.targetNamespace()) - .and( - DSL.field(DSL.name("canonical_tenant_id"), UUID.class) - .eq(receipt.canonicalTenantId()))) - .execute()) + assertThatThrownBy(() -> + fixture + .dsl + .deleteFrom(TENANT_BINDINGS) + .where( + DSL.field(DSL.name("target_namespace"), String.class) + .eq(receipt.targetNamespace()) + .and( + DSL.field(DSL.name("canonical_tenant_id"), UUID.class) + .eq(receipt.canonicalTenantId()))) + .execute()) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("binding is immutable"); assertThat( @@ -372,13 +354,11 @@ void concurrentExactRegistrationRetriesReturnOnePersistedReceipt() throws Except ExecutorService executor = Executors.newFixedThreadPool(2); try { Future first = - executor.submit( - () -> - concurrentRegister(fixture, ready, start, uuid(45), "same-tenant", "same-world")); + executor.submit(() -> + concurrentRegister(fixture, ready, start, uuid(45), "same-tenant", "same-world")); Future second = - executor.submit( - () -> - concurrentRegister(fixture, ready, start, uuid(45), "same-tenant", "same-world")); + executor.submit(() -> + concurrentRegister(fixture, ready, start, uuid(45), "same-tenant", "same-world")); assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); start.countDown(); @@ -409,27 +389,25 @@ void concurrentDifferentTenantsCannotClaimTheSameTenantSlug() throws Exception { ExecutorService executor = Executors.newFixedThreadPool(2); try { Future freshTenant = - executor.submit( - () -> - raceRegister( - fixture, - ready, - start, - uuid(50), - fixture.freshCanonicalTenantId(), - "racing-tenant", - "fresh-world")); + executor.submit(() -> + raceRegister( + fixture, + ready, + start, + uuid(50), + fixture.freshCanonicalTenantId(), + "racing-tenant", + "fresh-world")); Future secondTenant = - executor.submit( - () -> - raceRegister( - fixture, - ready, - start, - uuid(51), - secondCanonicalTenantId, - "racing-tenant", - "second-world")); + executor.submit(() -> + raceRegister( + fixture, + ready, + start, + uuid(51), + secondCanonicalTenantId, + "racing-tenant", + "second-world")); assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); start.countDown(); @@ -599,15 +577,14 @@ AuthoredWorldSourceEvidence register( String worldSlug, String worldDisplayName) { AuthoredWorldSourceEvidence receipt = - transactionTemplate.execute( - status -> - repository.register( - NAMESPACE, - requestId, - canonicalTenantId, - tenantSlug, - worldSlug, - worldDisplayName)); + transactionTemplate.execute(status -> + repository.register( + NAMESPACE, + requestId, + canonicalTenantId, + tenantSlug, + worldSlug, + worldDisplayName)); return java.util.Objects.requireNonNull(receipt); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationOriginalOutcomeRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationOriginalOutcomeRepositoryIntegrationTest.java index fade846a54..2539d69965 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationOriginalOutcomeRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationOriginalOutcomeRepositoryIntegrationTest.java @@ -83,16 +83,15 @@ void realCreationReceiptIsRecordedAndReplayedAsTheExactOriginalOutcome() { Binding binding = binding(); CreatedResult original = - fixture.inTransaction( - () -> { - OriginalOutcomeSnapshot pending = fixture.outcomeRepository.claimLocked(binding); - assertThat(pending.status()).isEqualTo(OutcomeStatus.PENDING); - FreshTenantCreationEvidence receipt = - fixture.creationRepository.createCandidate( - NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION); - return new CreatedResult( - receipt, fixture.outcomeRepository.markCreatedLocked(binding, receipt)); - }); + fixture.inTransaction(() -> { + OriginalOutcomeSnapshot pending = fixture.outcomeRepository.claimLocked(binding); + assertThat(pending.status()).isEqualTo(OutcomeStatus.PENDING); + FreshTenantCreationEvidence receipt = + fixture.creationRepository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION); + return new CreatedResult( + receipt, fixture.outcomeRepository.markCreatedLocked(binding, receipt)); + }); assertThat(original.snapshot().status()).isEqualTo(OutcomeStatus.CREATED); assertThat(original.snapshot().creationOperationId()) @@ -102,17 +101,14 @@ void realCreationReceiptIsRecordedAndReplayedAsTheExactOriginalOutcome() { assertThat(fixture.outcomeRepository.readCommitted(binding)).contains(original.snapshot()); OriginalOutcomeSnapshot exactRetry = - fixture.inTransaction( - () -> { - OriginalOutcomeSnapshot claimed = fixture.outcomeRepository.claimLocked(binding); - assertThat(claimed.status()).isEqualTo(OutcomeStatus.CREATED); - return fixture.outcomeRepository.markCreatedLocked(binding, original.receipt()); - }); + fixture.inTransaction(() -> { + OriginalOutcomeSnapshot claimed = fixture.outcomeRepository.claimLocked(binding); + assertThat(claimed.status()).isEqualTo(OutcomeStatus.CREATED); + return fixture.outcomeRepository.markCreatedLocked(binding, original.receipt()); + }); assertThat(exactRetry).isEqualTo(original.snapshot()); - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> fixture.outcomeRepository.closeNotCreatedLocked(binding))) + assertThatThrownBy(() -> + fixture.inTransaction(() -> fixture.outcomeRepository.closeNotCreatedLocked(binding))) .isInstanceOf(CreationRequestConflictException.class) .hasMessageContaining("cannot be closed as not created"); assertThat(fixture.creationRepository.read(REQUEST_ID, NAMESPACE)).contains(original.receipt()); @@ -132,12 +128,10 @@ void missingReadIsNotNoCreationProofAndDurableTombstoneBlocksDelayedCreate() { fixture.inTransaction(() -> fixture.outcomeRepository.closeNotCreatedLocked(binding)); assertThat(closed.status()).isEqualTo(OutcomeStatus.NOT_CREATED); assertThat(fixture.outcomeRepository.readCommitted(binding)).contains(closed); - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> - fixture.creationRepository.createCandidate( - NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION))) + assertThatThrownBy(() -> + fixture.inTransaction(() -> + fixture.creationRepository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION))) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("definitively closed"); @@ -151,15 +145,12 @@ void aRealCreationWinsAndCannotBeFalselyClosedAsNotCreated() { Fixture fixture = fixture(); Binding binding = binding(); FreshTenantCreationEvidence receipt = - fixture.inTransaction( - () -> - fixture.creationRepository.createCandidate( - NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION)); + fixture.inTransaction(() -> + fixture.creationRepository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION)); - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> fixture.outcomeRepository.closeNotCreatedLocked(binding))) + assertThatThrownBy(() -> + fixture.inTransaction(() -> fixture.outcomeRepository.closeNotCreatedLocked(binding))) .isInstanceOf(CreationRequestConflictException.class) .hasMessageContaining("cannot be closed as not created"); assertThat(fixture.creationRepository.read(REQUEST_ID, NAMESPACE)).contains(receipt); @@ -178,31 +169,27 @@ void concurrentCloseSerializesBeforeDelayedCreationInsert() throws Exception { try { Future close = - executor.submit( - () -> - fixture.inTransaction( - () -> { - OriginalOutcomeSnapshot result = - fixture.outcomeRepository.closeNotCreatedLocked(binding); - closeHasWritten.countDown(); - await(allowCloseCommit); - return result; - })); + executor.submit(() -> + fixture.inTransaction(() -> { + OriginalOutcomeSnapshot result = + fixture.outcomeRepository.closeNotCreatedLocked(binding); + closeHasWritten.countDown(); + await(allowCloseCommit); + return result; + })); assertThat(closeHasWritten.await(10, TimeUnit.SECONDS)).isTrue(); Future delayedCreate = - executor.submit( - () -> { - try { - fixture.inTransaction( - () -> - fixture.creationRepository.createCandidate( - NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION)); - return null; - } catch (RuntimeException exception) { - return exception; - } - }); + executor.submit(() -> { + try { + fixture.inTransaction(() -> + fixture.creationRepository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION)); + return null; + } catch (RuntimeException exception) { + return exception; + } + }); waitForAdvisoryWaiter(fixture.dsl); allowCloseCommit.countDown(); @@ -226,15 +213,14 @@ void changedBindingsAndDirectSqlCannotInventRewriteDeleteOrTruncateOutcomes() { Fixture fixture = fixture(); Binding binding = binding(); - assertThatThrownBy( - () -> - fixture - .dsl - .insertInto(OUTCOMES) - .set(TARGET_NAMESPACE, binding.targetNamespace()) - .set(TARGET_REQUEST_ID, binding.creationRequestId()) - .set(STATUS, "NOT_CREATED") - .execute()) + assertThatThrownBy(() -> + fixture + .dsl + .insertInto(OUTCOMES) + .set(TARGET_NAMESPACE, binding.targetNamespace()) + .set(TARGET_REQUEST_ID, binding.creationRequestId()) + .set(STATUS, "NOT_CREATED") + .execute()) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("must begin pending"); @@ -242,39 +228,35 @@ void changedBindingsAndDirectSqlCannotInventRewriteDeleteOrTruncateOutcomes() { () -> fixture.inTransaction(() -> fixture.outcomeRepository.claimLocked(binding))) .hasStackTraceContaining("cannot commit while pending"); - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> { - fixture.outcomeRepository.claimLocked(binding); - FreshTenantCreationEvidence receipt = - fixture.creationRepository.createCandidate( - NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION); - fixture - .dsl - .update(OUTCOMES) - .set(STATUS, "CREATED") - .set(CREATION_OPERATION_ID, UUID.randomUUID()) - .set(CREATION_EVIDENCE_DIGEST, receipt.evidenceDigest()) - .where( - TARGET_NAMESPACE - .eq(binding.targetNamespace()) - .and(TARGET_REQUEST_ID.eq(binding.creationRequestId()))) - .execute(); - return null; - })) + assertThatThrownBy(() -> + fixture.inTransaction(() -> { + fixture.outcomeRepository.claimLocked(binding); + FreshTenantCreationEvidence receipt = + fixture.creationRepository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION); + fixture + .dsl + .update(OUTCOMES) + .set(STATUS, "CREATED") + .set(CREATION_OPERATION_ID, UUID.randomUUID()) + .set(CREATION_EVIDENCE_DIGEST, receipt.evidenceDigest()) + .where( + TARGET_NAMESPACE + .eq(binding.targetNamespace()) + .and(TARGET_REQUEST_ID.eq(binding.creationRequestId()))) + .execute(); + return null; + })) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("exact V30 evidence"); - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> { - fixture.outcomeRepository.claimLocked(binding); - fixture.creationRepository.createCandidate( - NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION); - return fixture.outcomeRepository.closeNotCreatedLocked(binding); - })) + assertThatThrownBy(() -> + fixture.inTransaction(() -> { + fixture.outcomeRepository.claimLocked(binding); + fixture.creationRepository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION); + return fixture.outcomeRepository.closeNotCreatedLocked(binding); + })) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("cannot be closed as not created"); @@ -311,45 +293,39 @@ void changedBindingsAndDirectSqlCannotInventRewriteDeleteOrTruncateOutcomes() { "sha256:" + "c".repeat(64), binding.accountAuthorizationDigest())); for (Binding changedBinding : changedBindings) { - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> fixture.outcomeRepository.claimLocked(changedBinding))) + assertThatThrownBy(() -> + fixture.inTransaction(() -> fixture.outcomeRepository.claimLocked(changedBinding))) .isInstanceOf(CreationRequestConflictException.class) .hasMessageContaining("changed Account or request binding"); } - assertThatThrownBy( - () -> - fixture - .dsl - .update(OUTCOMES) - .set(STATUS, "CREATED") - .set(CREATION_OPERATION_ID, UUID.randomUUID()) - .set(CREATION_EVIDENCE_DIGEST, ACCOUNT_DIGEST) - .where( - TARGET_NAMESPACE - .eq(binding.targetNamespace()) - .and(TARGET_REQUEST_ID.eq(binding.creationRequestId()))) - .execute()) + assertThatThrownBy(() -> + fixture + .dsl + .update(OUTCOMES) + .set(STATUS, "CREATED") + .set(CREATION_OPERATION_ID, UUID.randomUUID()) + .set(CREATION_EVIDENCE_DIGEST, ACCOUNT_DIGEST) + .where( + TARGET_NAMESPACE + .eq(binding.targetNamespace()) + .and(TARGET_REQUEST_ID.eq(binding.creationRequestId()))) + .execute()) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("immutable"); - assertThatThrownBy( - () -> - fixture - .dsl - .deleteFrom(OUTCOMES) - .where( - TARGET_NAMESPACE - .eq(binding.targetNamespace()) - .and(TARGET_REQUEST_ID.eq(binding.creationRequestId()))) - .execute()) + assertThatThrownBy(() -> + fixture + .dsl + .deleteFrom(OUTCOMES) + .where( + TARGET_NAMESPACE + .eq(binding.targetNamespace()) + .and(TARGET_REQUEST_ID.eq(binding.creationRequestId()))) + .execute()) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("immutable"); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "TRUNCATE TABLE game_tenant_creation_original_outcomes CASCADE")) + assertThatThrownBy(() -> + fixture.dsl.execute("TRUNCATE TABLE game_tenant_creation_original_outcomes CASCADE")) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("cannot be truncated"); assertThat(fixture.outcomeRepository.readCommitted(binding)).contains(closed); @@ -378,10 +354,9 @@ void accountAuthorizationOperationCannotBindASecondOriginal() { secondNamespace, secondRequestId, secondSourceKey, secondName, DESCRIPTION), ACCOUNT_DIGEST); - assertThatThrownBy( - () -> - fixture.inTransaction( - () -> fixture.outcomeRepository.closeNotCreatedLocked(secondBinding))) + assertThatThrownBy(() -> + fixture.inTransaction( + () -> fixture.outcomeRepository.closeNotCreatedLocked(secondBinding))) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("uq_game_creation_original_account_operation"); @@ -396,10 +371,9 @@ void predecessorCreationSurvivesV1033AndCannotBeAdoptedOrClosed() { Fixture fixture = fixtureBeforeV1033(); Binding binding = binding(); FreshTenantCreationEvidence receipt = - fixture.inTransaction( - () -> - fixture.creationRepository.createCandidate( - NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION)); + fixture.inTransaction(() -> + fixture.creationRepository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION)); String predecessorBytesAndXmin = operationBytesAndXmin(fixture.dsl); migrate(fixture.dataSource(), fixture.schema(), null); @@ -407,10 +381,8 @@ void predecessorCreationSurvivesV1033AndCannotBeAdoptedOrClosed() { assertThat(operationBytesAndXmin(upgraded.dsl)).isEqualTo(predecessorBytesAndXmin); assertThat(upgraded.creationRepository.read(REQUEST_ID, NAMESPACE)).contains(receipt); - assertThatThrownBy( - () -> - upgraded.inTransaction( - () -> upgraded.outcomeRepository.closeNotCreatedLocked(binding))) + assertThatThrownBy(() -> + upgraded.inTransaction(() -> upgraded.outcomeRepository.closeNotCreatedLocked(binding))) .isInstanceOf(CreationRequestConflictException.class) .hasMessageContaining("cannot be closed as not created"); assertThat(upgraded.outcomeRepository.readCommitted(binding)).isEmpty(); @@ -544,16 +516,15 @@ private record Fixture( GameTenantCreationOriginalOutcomeRepository outcomeRepository, TransactionTemplate transactionTemplate) { private T inTransaction(java.util.concurrent.Callable work) { - return transactionTemplate.execute( - status -> { - try { - return work.call(); - } catch (RuntimeException exception) { - throw exception; - } catch (Exception exception) { - throw new IllegalStateException(exception); - } - }); + return transactionTemplate.execute(status -> { + try { + return work.call(); + } catch (RuntimeException exception) { + throw exception; + } catch (Exception exception) { + throw new IllegalStateException(exception); + } + }); } private Fixture withCurrentRepositories() { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java index 086d6446cc..a989161f1a 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryIntegrationTest.java @@ -48,17 +48,15 @@ static void stopPostgres() { void exactRetryReturnsCommittedReceiptWithoutSecondGameWrite() { Fixture fixture = fixture(); FreshTenantCreationEvidence first = - fixture.inTransaction( - () -> - fixture.repository.createCandidate( - NAMESPACE, REQUEST_ID, SOURCE_KEY, "The First World", "A description")); + fixture.inTransaction(() -> + fixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, "The First World", "A description")); assertThat(fixture.repository.read(REQUEST_ID, NAMESPACE)).contains(first); FreshTenantCreationEvidence exactRetry = - fixture.inTransaction( - () -> - fixture.repository.createCandidate( - NAMESPACE, REQUEST_ID, SOURCE_KEY, "The First World", "A description")); + fixture.inTransaction(() -> + fixture.repository.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, "The First World", "A description")); assertThat(exactRetry).isEqualTo(first); assertThat(fixture.dsl.fetchCount(GAME)).isEqualTo(1); @@ -69,28 +67,24 @@ void exactRetryReturnsCommittedReceiptWithoutSecondGameWrite() { void completedCreationEvidenceCannotBeChangedOrDeleted() { Fixture fixture = fixture(); FreshTenantCreationEvidence receipt = - fixture.inTransaction( - () -> - fixture.repository.createCandidate( - NAMESPACE, REQUEST_ID, SOURCE_KEY, "World", null)); + fixture.inTransaction(() -> + fixture.repository.createCandidate(NAMESPACE, REQUEST_ID, SOURCE_KEY, "World", null)); - assertThatThrownBy( - () -> - fixture - .dsl - .update(OPERATIONS) - .set(DSL.field(DSL.name("name"), String.class), "Changed") - .where(OPERATION_ID.eq(receipt.operationId())) - .execute()) + assertThatThrownBy(() -> + fixture + .dsl + .update(OPERATIONS) + .set(DSL.field(DSL.name("name"), String.class), "Changed") + .where(OPERATION_ID.eq(receipt.operationId())) + .execute()) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("evidence is immutable"); - assertThatThrownBy( - () -> - fixture - .dsl - .deleteFrom(OPERATIONS) - .where(OPERATION_ID.eq(receipt.operationId())) - .execute()) + assertThatThrownBy(() -> + fixture + .dsl + .deleteFrom(OPERATIONS) + .where(OPERATION_ID.eq(receipt.operationId())) + .execute()) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("evidence is immutable"); @@ -131,16 +125,15 @@ private record Fixture( GameTenantCreationRepository repository, TransactionTemplate transactionTemplate) { private T inTransaction(java.util.concurrent.Callable work) { - return transactionTemplate.execute( - status -> { - try { - return work.call(); - } catch (RuntimeException exception) { - throw exception; - } catch (Exception exception) { - throw new IllegalStateException(exception); - } - }); + return transactionTemplate.execute(status -> { + try { + return work.call(); + } catch (RuntimeException exception) { + throw exception; + } catch (Exception exception) { + throw new IllegalStateException(exception); + } + }); } } } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java index a08afa33da..49ae86f246 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/GameTenantIdentityRepositoryIntegrationTest.java @@ -96,13 +96,12 @@ void migratesOnlyExactOwnerKeysAndReadsImmutableGameRowProvenance() throws Excep .from(GAME) .where(ID.eq(quarantinedGameId)) .fetchOne()) - .satisfies( - row -> { - assertThat(row.get(CANONICAL_TENANT_ID)).isNull(); - assertThat(row.get(PROVENANCE_KIND)).isNull(); - assertThat(row.get(SOURCE_GAME_ID)).isNull(); - assertThat(row.get(SOURCE_LEGACY_TENANT_ID)).isNull(); - }); + .satisfies(row -> { + assertThat(row.get(CANONICAL_TENANT_ID)).isNull(); + assertThat(row.get(PROVENANCE_KIND)).isNull(); + assertThat(row.get(SOURCE_GAME_ID)).isNull(); + assertThat(row.get(SOURCE_LEGACY_TENANT_ID)).isNull(); + }); Game newGame = new Game(); newGame.setTenantId("new-owner-key"); newGame.setName("New"); @@ -124,19 +123,17 @@ void migratesOnlyExactOwnerKeysAndReadsImmutableGameRowProvenance() throws Excep assertThatThrownBy(() -> repository.save(forgedGame)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - dsl.update(GAME) - .set(TENANT_ID, "renamed-owner-key") - .where(ID.eq(retainedGameId)) - .execute()) + assertThatThrownBy(() -> + dsl.update(GAME) + .set(TENANT_ID, "renamed-owner-key") + .where(ID.eq(retainedGameId)) + .execute()) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.update(GAME) - .set(SOURCE_GAME_ID, SOURCE_GAME_ID.plus(1L)) - .where(ID.eq(retainedGameId)) - .execute()) + assertThatThrownBy(() -> + dsl.update(GAME) + .set(SOURCE_GAME_ID, SOURCE_GAME_ID.plus(1L)) + .where(ID.eq(retainedGameId)) + .execute()) .isInstanceOf(DataAccessException.class); assertThat(dsl.fetchCount(GAME)).isEqualTo(3); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/OriginalTenantCreationOutcomeReadPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/OriginalTenantCreationOutcomeReadPostgresIntegrationTest.java index 81609a0761..45b7bca2cb 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/OriginalTenantCreationOutcomeReadPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/OriginalTenantCreationOutcomeReadPostgresIntegrationTest.java @@ -65,15 +65,14 @@ void resolvesCreatedOutcomeWithActualV30ReceiptWithoutChangingCommittedRows() { Fixture fixture = fixture(); Binding binding = binding(); Created original = - fixture.inTransaction( - () -> { - fixture.outcomes.claimLocked(binding); - FreshTenantCreationEvidence receipt = - fixture.creation.createCandidate( - NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION); - fixture.outcomes.markCreatedLocked(binding, receipt); - return new Created(receipt, rowState(fixture.dsl, binding)); - }); + fixture.inTransaction(() -> { + fixture.outcomes.claimLocked(binding); + FreshTenantCreationEvidence receipt = + fixture.creation.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION); + fixture.outcomes.markCreatedLocked(binding, receipt); + return new Created(receipt, rowState(fixture.dsl, binding)); + }); ResolveOriginalTenantCreationOutcomeRequest request = request(binding); ReadObserver observer = resolve(fixture.service, request, ACCOUNT_URI); @@ -100,11 +99,10 @@ void resolvesOnlyDurableNotCreatedTombstoneAndLeavesItUnchanged() { Fixture fixture = fixture(); Binding binding = binding(); String tombstoneState = - fixture.inTransaction( - () -> { - fixture.outcomes.closeNotCreatedLocked(binding); - return rowState(fixture.dsl, binding); - }); + fixture.inTransaction(() -> { + fixture.outcomes.closeNotCreatedLocked(binding); + return rowState(fixture.dsl, binding); + }); ResolveOriginalTenantCreationOutcomeRequest request = request(binding); ReadObserver observer = resolve(fixture.service, request, ACCOUNT_URI); @@ -147,19 +145,18 @@ void changedAuthorizationDigestRefusesRealRetainedTerminalsWithoutChangingSqlSta for (boolean created : new boolean[] {true, false}) { Fixture fixture = fixture(); Binding original = binding(); - fixture.inTransaction( - () -> { - if (created) { - fixture.outcomes.claimLocked(original); - FreshTenantCreationEvidence receipt = - fixture.creation.createCandidate( - NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION); - fixture.outcomes.markCreatedLocked(original, receipt); - } else { - fixture.outcomes.closeNotCreatedLocked(original); - } - return true; - }); + fixture.inTransaction(() -> { + if (created) { + fixture.outcomes.claimLocked(original); + FreshTenantCreationEvidence receipt = + fixture.creation.createCandidate( + NAMESPACE, REQUEST_ID, SOURCE_KEY, NAME, DESCRIPTION); + fixture.outcomes.markCreatedLocked(original, receipt); + } else { + fixture.outcomes.closeNotCreatedLocked(original); + } + return true; + }); String before = rowState(fixture.dsl, original); Binding changed = new Binding( @@ -285,16 +282,15 @@ private record Fixture( OriginalTenantCreationOutcomeReadGrpcService service, TransactionTemplate transactionTemplate) { private T inTransaction(java.util.concurrent.Callable work) { - return transactionTemplate.execute( - status -> { - try { - return work.call(); - } catch (RuntimeException exception) { - throw exception; - } catch (Exception exception) { - throw new IllegalStateException(exception); - } - }); + return transactionTemplate.execute(status -> { + try { + return work.call(); + } catch (RuntimeException exception) { + throw exception; + } catch (Exception exception) { + throw new IllegalStateException(exception); + } + }); } } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java index 341be17fd1..ee515cdc18 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -92,14 +92,13 @@ void normalSavePersistsExactVersionAndVerifiedGameIdentityAndReadsBackWithinTran String versionXminBefore = versionXmin(fixture.dsl(), version.getId()); String gameXminBefore = gameXmin(fixture.dsl(), owner.getId()); String otherGameXminBefore = gameXmin(fixture.dsl(), other.getId()); - assertThatThrownBy( - () -> - fixture - .dsl() - .update(VERSION) - .set(CANONICAL_TENANT_ID, other.getCanonicalTenantId()) - .where(ID.eq(version.getId())) - .execute()) + assertThatThrownBy(() -> + fixture + .dsl() + .update(VERSION) + .set(CANONICAL_TENANT_ID, other.getCanonicalTenantId()) + .where(ID.eq(version.getId())) + .execute()) .isInstanceOf(DataAccessException.class) .hasMessageContaining("canonical Version identity and its tenant source are immutable"); @@ -127,40 +126,37 @@ void repositoryNestedTransactionRollsBackWithOuterSpringPublisherTransaction() { String versionXminBefore = versionXmin(fixture.dsl(), version.getId()); String gameXminBefore = gameXmin(fixture.dsl(), owner.getId()); - assertThatThrownBy( - () -> - fixture - .transactionTemplate() - .execute( - status -> { - PublishedReleaseBundle saved = - fixture - .releaseBundleRepository() - .save(bundle(owner.getTenantId(), version.getId())); - assertThat(saved.getCanonicalTenantId()) - .isEqualTo(owner.getCanonicalTenantId()); - assertThat(saved.getCanonicalVersionId()) - .isEqualTo(version.getCanonicalVersionId()); - assertThat(saved.getPublishedReleaseBundleRef()).isNotBlank(); - Version publishingVersion = - fixture - .versionRepository() - .findByTenantIdAndId(owner.getTenantId(), version.getId()) - .orElseThrow(); - publishingVersion.setVersionState(VersionLifecycleState.PUBLISHED); - publishingVersion.setVersionStateEpoch( - publishingVersion.getVersionStateEpoch() + 1L); - fixture.versionRepository().save(publishingVersion); - assertThat(bundleCount(fixture.dsl())).isEqualTo(1); - assertThat( - fixture - .versionRepository() - .findByTenantIdAndId(owner.getTenantId(), version.getId()) - .orElseThrow() - .getVersionState()) - .isEqualTo(VersionLifecycleState.PUBLISHED); - throw new IllegalStateException("simulate failed outer publication"); - })) + assertThatThrownBy(() -> + fixture + .transactionTemplate() + .execute(status -> { + PublishedReleaseBundle saved = + fixture + .releaseBundleRepository() + .save(bundle(owner.getTenantId(), version.getId())); + assertThat(saved.getCanonicalTenantId()).isEqualTo(owner.getCanonicalTenantId()); + assertThat(saved.getCanonicalVersionId()) + .isEqualTo(version.getCanonicalVersionId()); + assertThat(saved.getPublishedReleaseBundleRef()).isNotBlank(); + Version publishingVersion = + fixture + .versionRepository() + .findByTenantIdAndId(owner.getTenantId(), version.getId()) + .orElseThrow(); + publishingVersion.setVersionState(VersionLifecycleState.PUBLISHED); + publishingVersion.setVersionStateEpoch( + publishingVersion.getVersionStateEpoch() + 1L); + fixture.versionRepository().save(publishingVersion); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + assertThat( + fixture + .versionRepository() + .findByTenantIdAndId(owner.getTenantId(), version.getId()) + .orElseThrow() + .getVersionState()) + .isEqualTo(VersionLifecycleState.PUBLISHED); + throw new IllegalStateException("simulate failed outer publication"); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("simulate failed outer publication"); @@ -199,11 +195,8 @@ void deniesWrongTenantNilAndSubstitutedCallerOrDatabaseIdentityWithoutGrowingBun var otherBefore = sourceRow(fixture.dsl(), "game", other.getId()); var versionBefore = sourceRow(fixture.dsl(), "version", version.getId()); - assertThatThrownBy( - () -> - fixture - .releaseBundleRepository() - .save(bundle(other.getTenantId(), version.getId()))) + assertThatThrownBy(() -> + fixture.releaseBundleRepository().save(bundle(other.getTenantId(), version.getId()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("No exact canonical Game Design source association"); @@ -219,34 +212,31 @@ void deniesWrongTenantNilAndSubstitutedCallerOrDatabaseIdentityWithoutGrowingBun .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Caller-supplied canonical release identity"); - assertThatThrownBy( - () -> - insertRawBundle( - fixture.dsl(), - owner.getTenantId(), - version.getId(), - NIL_UUID, - version.getCanonicalVersionId())) + assertThatThrownBy(() -> + insertRawBundle( + fixture.dsl(), + owner.getTenantId(), + version.getId(), + NIL_UUID, + version.getCanonicalVersionId())) .isInstanceOf(DataAccessException.class) .hasMessageContaining("non-nil canonical identity"); - assertThatThrownBy( - () -> - insertRawBundle( - fixture.dsl(), - owner.getTenantId(), - version.getId(), - other.getCanonicalTenantId(), - version.getCanonicalVersionId())) + assertThatThrownBy(() -> + insertRawBundle( + fixture.dsl(), + owner.getTenantId(), + version.getId(), + other.getCanonicalTenantId(), + version.getCanonicalVersionId())) .isInstanceOf(DataAccessException.class) .hasMessageContaining("does not match its exact Version and Game source"); - assertThatThrownBy( - () -> - insertRawBundle( - fixture.dsl(), - other.getTenantId(), - version.getId(), - owner.getCanonicalTenantId(), - version.getCanonicalVersionId())) + assertThatThrownBy(() -> + insertRawBundle( + fixture.dsl(), + other.getTenantId(), + version.getId(), + owner.getCanonicalTenantId(), + version.getCanonicalVersionId())) .isInstanceOf(DataAccessException.class) .hasMessageContaining("does not match its exact Version and Game source"); assertThat(bundleCount(fixture.dsl())).isZero(); @@ -286,75 +276,68 @@ void bundleIdentityIsImmutableRetainedNullCannotBeBackfilledAndMetadataCannotBeD .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Published release bundle is immutable"); - assertThatThrownBy( - () -> - fixture - .dsl() - .update(RELEASE_BUNDLE) - .set(DSL.field(DSL.name("manifest_hash"), String.class), OTHER_MANIFEST_HASH) - .where(ID.eq(mapped.getId())) - .execute()) + assertThatThrownBy(() -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(DSL.field(DSL.name("manifest_hash"), String.class), OTHER_MANIFEST_HASH) + .where(ID.eq(mapped.getId())) + .execute()) .isInstanceOf(DataAccessException.class) .hasMessageContaining("published release bundle attestation is immutable"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "UPDATE published_release_bundle SET manifest_hash = manifest_hash " - + "WHERE id = ?", - mapped.getId())) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "UPDATE published_release_bundle SET manifest_hash = manifest_hash " + + "WHERE id = ?", + mapped.getId())) .isInstanceOf(DataAccessException.class) .hasMessageContaining("published release bundle attestation is immutable"); - assertThatThrownBy( - () -> - fixture - .dsl() - .update(RELEASE_BUNDLE) - .set(CANONICAL_TENANT_ID, UUID.randomUUID()) - .where(ID.eq(mapped.getId())) - .execute()) + assertThatThrownBy(() -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(CANONICAL_TENANT_ID, UUID.randomUUID()) + .where(ID.eq(mapped.getId())) + .execute()) .isInstanceOf(DataAccessException.class) .hasMessageContaining("published release bundle attestation is immutable"); - assertThatThrownBy( - () -> - fixture - .dsl() - .update(RELEASE_BUNDLE) - .set(CANONICAL_VERSION_ID, UUID.randomUUID()) - .where(ID.eq(mapped.getId())) - .execute()) + assertThatThrownBy(() -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(CANONICAL_VERSION_ID, UUID.randomUUID()) + .where(ID.eq(mapped.getId())) + .execute()) .isInstanceOf(DataAccessException.class) .hasMessageContaining("published release bundle attestation is immutable"); - assertThatThrownBy( - () -> - fixture - .dsl() - .update(RELEASE_BUNDLE) - .set(DSL.field(DSL.name("manifest_hash"), String.class), OTHER_MANIFEST_HASH) - .where(ID.eq(retainedBundleId)) - .execute()) + assertThatThrownBy(() -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(DSL.field(DSL.name("manifest_hash"), String.class), OTHER_MANIFEST_HASH) + .where(ID.eq(retainedBundleId)) + .execute()) .isInstanceOf(DataAccessException.class) .hasMessageContaining("published release bundle attestation is immutable"); - assertThatThrownBy( - () -> - fixture - .dsl() - .update(RELEASE_BUNDLE) - .set(PUBLISHED_RELEASE_BUNDLE_REF, "attempted-retained-release-reference") - .where(ID.eq(retainedBundleId)) - .execute()) + assertThatThrownBy(() -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(PUBLISHED_RELEASE_BUNDLE_REF, "attempted-retained-release-reference") + .where(ID.eq(retainedBundleId)) + .execute()) .isInstanceOf(DataAccessException.class) .hasMessageContaining("published release bundle attestation is immutable"); - assertThatThrownBy( - () -> - fixture - .dsl() - .update(RELEASE_BUNDLE) - .set(CANONICAL_TENANT_ID, game.getCanonicalTenantId()) - .set(CANONICAL_VERSION_ID, mappedVersion.getCanonicalVersionId()) - .where(ID.eq(retainedBundleId)) - .execute()) + assertThatThrownBy(() -> + fixture + .dsl() + .update(RELEASE_BUNDLE) + .set(CANONICAL_TENANT_ID, game.getCanonicalTenantId()) + .set(CANONICAL_VERSION_ID, mappedVersion.getCanonicalVersionId()) + .where(ID.eq(retainedBundleId)) + .execute()) .isInstanceOf(DataAccessException.class) .hasMessageContaining("published release bundle attestation is immutable"); @@ -416,26 +399,23 @@ void repositoryNestedTransactionRollsBackWithOuterJooqOwnerTransaction() { var gameBefore = sourceRow(fixture.dsl(), "game", owner.getId()); var versionBefore = sourceRow(fixture.dsl(), "version", version.getId()); - assertThatThrownBy( - () -> - fixture - .dsl() - .transaction( - configuration -> { - DSLContext ownerSql = DSL.using(configuration); - var repository = new PublishedReleaseBundleRepository(ownerSql); - var saved = repository.save(bundle(owner.getTenantId(), version.getId())); - assertThat(saved.getCanonicalTenantId()) - .isEqualTo(owner.getCanonicalTenantId()); - assertThat(saved.getCanonicalVersionId()) - .isEqualTo(version.getCanonicalVersionId()); - assertThat( - repository.findByTenantIdAndVersionId( - owner.getTenantId(), version.getId())) - .isPresent(); - assertThat(bundleCount(ownerSql)).isEqualTo(1); - throw new IllegalStateException("simulate failed outer jOOQ owner"); - })) + assertThatThrownBy(() -> + fixture + .dsl() + .transaction(configuration -> { + DSLContext ownerSql = DSL.using(configuration); + var repository = new PublishedReleaseBundleRepository(ownerSql); + var saved = repository.save(bundle(owner.getTenantId(), version.getId())); + assertThat(saved.getCanonicalTenantId()).isEqualTo(owner.getCanonicalTenantId()); + assertThat(saved.getCanonicalVersionId()) + .isEqualTo(version.getCanonicalVersionId()); + assertThat( + repository.findByTenantIdAndVersionId( + owner.getTenantId(), version.getId())) + .isPresent(); + assertThat(bundleCount(ownerSql)).isEqualTo(1); + throw new IllegalStateException("simulate failed outer jOOQ owner"); + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("simulate failed outer jOOQ owner"); @@ -472,10 +452,9 @@ void selectedFullV4StorageRejectsMixedProfilesAndExactlyReplaysOriginalBytes() t .put( "digestSchemaVersion", participant.digestSchemaVersion() == 1 ? 2 : participant.digestSchemaVersion() - 1); - assertThatThrownBy( - () -> - insertRawSelectedFull( - fixture, version, operation, original, json.writeValueAsString(mixed))) + assertThatThrownBy(() -> + insertRawSelectedFull( + fixture, version, operation, original, json.writeValueAsString(mixed))) .as("mixed storage profile for %s", participant.participantKey()) .isInstanceOf(DataAccessException.class) .hasMessageContaining("selected participant differs from commit/digest/schema"); @@ -487,14 +466,12 @@ void selectedFullV4StorageRejectsMixedProfilesAndExactlyReplaysOriginalBytes() t var saved = fixture .transactionTemplate() - .execute( - status -> - net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup - .commitStorage( - fixture.dsl(), - fixture.versionRepository(), - operation, - () -> fixture.releaseBundleRepository().save(requested))); + .execute(status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> fixture.releaseBundleRepository().save(requested))); assertThat(saved).isNotNull(); var tuple = releaseBundleTuple(fixture.dsl(), saved.getId()); var independent = @@ -532,16 +509,15 @@ void concurrentExactSelectedFullRetriesCommitOneImmutableBundle() throws Excepti start.await(); return fixture .transactionTemplate() - .execute( - status -> - net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup - .commitStorage( - fixture.dsl(), - fixture.versionRepository(), - operation, - () -> - new PublishedReleaseBundleRepository(fixture.dsl()) - .save(selectedFullBundle(version, operation.world())))); + .execute(status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> + new PublishedReleaseBundleRepository(fixture.dsl()) + .save(selectedFullBundle(version, operation.world())))); }; var first = executor.submit(save); var second = executor.submit(save); @@ -693,19 +669,18 @@ void sqlGuardRejectsMissingAndChangedSelectedFullBindingsWithoutAnyRelease() thr assertThat(sourceRow(fixture.dsl(), "version", version.getId())).isEqualTo(versionBefore); fixture .transactionTemplate() - .executeWithoutResult( - status -> - net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.commitStorage( - fixture.dsl(), - fixture.versionRepository(), - operation, - () -> { - insertRawSelectedFull(fixture, version, operation, original, participants); - return fixture - .releaseBundleRepository() - .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) - .orElseThrow(); - })); + .executeWithoutResult(status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> { + insertRawSelectedFull(fixture, version, operation, original, participants); + return fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow(); + })); assertThat( new PublishedReleaseBundleRepository(fixture.dsl()) .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) @@ -722,26 +697,24 @@ private void assertSelectedFullMutationRejected( String evidence, String participants, String rejectionMessage) { - assertThatThrownBy( - () -> - fixture - .transactionTemplate() - .executeWithoutResult( - status -> - net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup - .commitStorage( - fixture.dsl(), - fixture.versionRepository(), - operation, - () -> { - insertRawSelectedFull( - fixture, version, operation, evidence, participants); - return fixture - .releaseBundleRepository() - .findByTenantIdAndVersionId( - operation.tenantKey(), operation.versionId()) - .orElseThrow(); - }))) + assertThatThrownBy(() -> + fixture + .transactionTemplate() + .executeWithoutResult(status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> { + insertRawSelectedFull( + fixture, version, operation, evidence, participants); + return fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId( + operation.tenantKey(), operation.versionId()) + .orElseThrow(); + }))) .isInstanceOf(DataAccessException.class) .hasMessageContaining(rejectionMessage); } @@ -760,20 +733,19 @@ private void assertSelectedFullMutationRejected( version.getIdentitySourceProvenanceKind()); return fixture .transactionTemplate() - .execute( - status -> { - try { - return net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup - .retainFrozenSourceBackedSelectedFull( - fixture.dsl(), - target, - version.getVersionStateEpoch(), - "ISOLATED selected-full storage regression", - java.util.List.of()); - } catch (Exception failure) { - throw new IllegalStateException(failure); - } - }); + .execute(status -> { + try { + return net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .retainFrozenSourceBackedSelectedFull( + fixture.dsl(), + target, + version.getVersionStateEpoch(), + "ISOLATED selected-full storage regression", + java.util.List.of()); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); } private PublishedReleaseBundle selectedFullBundle( diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java index 20f4480856..e8f6e3a78a 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java @@ -66,23 +66,20 @@ void freshInstallAcceptsSelectedV2OnlyWithControlPlaneDigestSchemaTwo() throws E PersistedTarget rejected = persistTarget(jdbc, 2); WorldPublishedStartLocationEvidence rejectedEvidence = evidence(rejected); - assertThatThrownBy( - () -> - insertRelease( - jdbc, - rejected, - rejectedEvidence, - withRetainedControlPlaneSchema( - selectedV2Participants(rejected, rejectedEvidence)))) + assertThatThrownBy(() -> + insertRelease( + jdbc, + rejected, + rejectedEvidence, + withRetainedControlPlaneSchema(selectedV2Participants(rejected, rejectedEvidence)))) .rootCause() .isInstanceOf(PSQLException.class) - .satisfies( - cause -> { - PSQLException postgresException = (PSQLException) cause; - assertThat(postgresException.getSQLState()).isEqualTo("23514"); - assertThat(postgresException.getServerErrorMessage().getMessage()) - .isEqualTo("release v2 participant differs from selected commit/digest/schema"); - }); + .satisfies(cause -> { + PSQLException postgresException = (PSQLException) cause; + assertThat(postgresException.getSQLState()).isEqualTo("23514"); + assertThat(postgresException.getServerErrorMessage().getMessage()) + .isEqualTo("release v2 participant differs from selected commit/digest/schema"); + }); assertThat(releaseCount(jdbc, rejected.versionId())).isEqualTo(0L); migrate(dataSource, schema, null); @@ -142,23 +139,20 @@ void additiveUpgradeRetainsV1BytesAndGuardIdentityThenAppliesSelectedV2Schema() PersistedTarget rejected = persistTarget(jdbc, 3); WorldPublishedStartLocationEvidence rejectedEvidence = evidence(rejected); - assertThatThrownBy( - () -> - insertRelease( - jdbc, - rejected, - rejectedEvidence, - withRetainedControlPlaneSchema( - selectedV2Participants(rejected, rejectedEvidence)))) + assertThatThrownBy(() -> + insertRelease( + jdbc, + rejected, + rejectedEvidence, + withRetainedControlPlaneSchema(selectedV2Participants(rejected, rejectedEvidence)))) .rootCause() .isInstanceOf(PSQLException.class) - .satisfies( - cause -> { - PSQLException postgresException = (PSQLException) cause; - assertThat(postgresException.getSQLState()).isEqualTo("23514"); - assertThat(postgresException.getServerErrorMessage().getMessage()) - .isEqualTo("release v2 participant differs from selected commit/digest/schema"); - }); + .satisfies(cause -> { + PSQLException postgresException = (PSQLException) cause; + assertThat(postgresException.getSQLState()).isEqualTo("23514"); + assertThat(postgresException.getServerErrorMessage().getMessage()) + .isEqualTo("release v2 participant differs from selected commit/digest/schema"); + }); assertThat(releaseCount(jdbc, rejected.versionId())).isEqualTo(0L); migrate(dataSource, schema, null); @@ -179,10 +173,9 @@ private void assertLatestGuardRejectsReleaseWithoutOwnerAttempt( // A schema-valid v2 row still needs a genuine publication attempt under the latest guard. PersistedTarget target = persistTarget(jdbc, versionNumber); WorldPublishedStartLocationEvidence targetEvidence = evidence(target); - assertThatThrownBy( - () -> - insertRelease( - jdbc, target, targetEvidence, selectedV2Participants(target, targetEvidence))) + assertThatThrownBy(() -> + insertRelease( + jdbc, target, targetEvidence, selectedV2Participants(target, targetEvidence))) .rootCause() .isInstanceOf(PSQLException.class) .satisfies(cause -> assertThat(((PSQLException) cause).getSQLState()).isEqualTo("P0002")); @@ -270,20 +263,19 @@ private List selectedV2Participants( private List withRetainedControlPlaneSchema( List participants) { return participants.stream() - .map( - participant -> - "GAME_DESIGN_CONTROL_PLANE".equals(participant.participantKey()) - ? new PublishParticipantDigestDto( - participant.participantKey(), - participant.scopeValue(), - participant.baseVersionId(), - participant.appliedCommitId(), - participant.contentDigest(), - AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION, - participant.abilitySchemaDigest(), - participant.errorCode(), - participant.errorMessage()) - : participant) + .map(participant -> + "GAME_DESIGN_CONTROL_PLANE".equals(participant.participantKey()) + ? new PublishParticipantDigestDto( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION, + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage()) + : participant) .toList(); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionPostgresIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionPostgresIntegrationTest.java index 41944c145e..aa8f2ec428 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionPostgresIntegrationTest.java @@ -110,28 +110,25 @@ void migratesOwnerKeyReadsSyntheticRetainedStorageAndRejectsMutation() throws Ex connection.commit(); } - assertThatThrownBy( - () -> - mutate( - dataSource, - schema, - "UPDATE game_design_start_session_authored_actor_core_projection SET policy_order = 1")) + assertThatThrownBy(() -> + mutate( + dataSource, + schema, + "UPDATE game_design_start_session_authored_actor_core_projection SET policy_order = 1")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("insert-only"); - assertThatThrownBy( - () -> - mutate( - dataSource, - schema, - "DELETE FROM game_design_start_session_authored_actor_core_projection")) + assertThatThrownBy(() -> + mutate( + dataSource, + schema, + "DELETE FROM game_design_start_session_authored_actor_core_projection")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("insert-only"); - assertThatThrownBy( - () -> - mutate( - dataSource, - schema, - "TRUNCATE game_design_start_session_authored_actor_core_projection")) + assertThatThrownBy(() -> + mutate( + dataSource, + schema, + "TRUNCATE game_design_start_session_authored_actor_core_projection")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("retained"); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java index b69946852a..f481f6693f 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java @@ -98,17 +98,15 @@ void acceptsDigestOfExactMappedSourceBytes() { void freezesOnlyTheSynchronizedAssetProjectionAndDeniesDirectAssociation() { Fixture fixture = fixture(); var repository = new VersionAssetPublicationRepository(fixture.dsl); - assertThatThrownBy( - () -> - repository.associateDraftAsset( - fixture.tenantId, fixture.versionId, fixture.assetId, "RESOURCE")) + assertThatThrownBy(() -> + repository.associateDraftAsset( + fixture.tenantId, fixture.versionId, fixture.assetId, "RESOURCE")) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("synchronized ASSET_REFERENCE"); var snapshot = - fixture.dsl.transactionResult( - configuration -> - new VersionAssetPublicationRepository(DSL.using(configuration)) - .freezeOrReadSnapshot(fixture.tenantId, 1)); + fixture.dsl.transactionResult(configuration -> + new VersionAssetPublicationRepository(DSL.using(configuration)) + .freezeOrReadSnapshot(fixture.tenantId, 1)); assertThat(snapshot.items()).hasSize(1); assertThat(snapshot.items().getFirst().usageKey()).isEqualTo(USAGE_KEY); assertThat(snapshot.items().getFirst().contentDigest()).isEqualTo(sha256(SOURCE_BYTES)); @@ -167,10 +165,9 @@ void jooqOwnerCommitsFoundedEmptySnapshotBeforeIndependentReadback() { assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); var snapshot = - fixture.dsl.transactionResult( - configuration -> - new VersionAssetPublicationRepository(DSL.using(configuration)) - .freezeOrReadSnapshot(fixture.tenantId, 1)); + fixture.dsl.transactionResult(configuration -> + new VersionAssetPublicationRepository(DSL.using(configuration)) + .freezeOrReadSnapshot(fixture.tenantId, 1)); assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); assertThat(snapshot.items()).isEmpty(); @@ -206,14 +203,13 @@ public void release(Connection returned) { } }; var listener = - ExecuteListener.onExecuteStart( - context -> { - queryConnections.add(context.connection()); - assertThat(context.configuration().dialect()).isEqualTo(SQLDialect.POSTGRES); - assertThat(context.configuration().settings().isRenderFormatted()).isTrue(); - assertThat(context.configuration().data("asset-freeze-proof")) - .isEqualTo("caller-configuration"); - }); + ExecuteListener.onExecuteStart(context -> { + queryConnections.add(context.connection()); + assertThat(context.configuration().dialect()).isEqualTo(SQLDialect.POSTGRES); + assertThat(context.configuration().settings().isRenderFormatted()).isTrue(); + assertThat(context.configuration().data("asset-freeze-proof")) + .isEqualTo("caller-configuration"); + }); var configuration = fixture .dsl @@ -253,10 +249,9 @@ public void release(Connection returned) { void readsExistingSnapshotInCallerReadOnlyTransaction() throws Exception { Fixture fixture = fixture(); var frozen = - fixture.dsl.transactionResult( - configuration -> - new VersionAssetPublicationRepository(DSL.using(configuration)) - .freezeOrReadSnapshot(fixture.tenantId, 1)); + fixture.dsl.transactionResult(configuration -> + new VersionAssetPublicationRepository(DSL.using(configuration)) + .freezeOrReadSnapshot(fixture.tenantId, 1)); try (var connection = fixture.dataSource.getConnection()) { connection.setReadOnly(true); @@ -291,10 +286,9 @@ private static void assertUnwrappedFirstFreezeDenied(Fixture fixture) throws Exc .derive(ExecuteListener.onExecuteStart(context -> queries.incrementAndGet()))); Throwable failure = - catchThrowable( - () -> - new VersionAssetPublicationRepository(observed) - .freezeOrReadSnapshot(fixture.tenantId, 1)); + catchThrowable(() -> + new VersionAssetPublicationRepository(observed) + .freezeOrReadSnapshot(fixture.tenantId, 1)); assertAll( "An unwrapped first freeze must fail without committing snapshot rows", @@ -324,46 +318,45 @@ private Fixture foundedEmptyFixture() { Fixture fixture = fixture(); var write = new TransactionTemplate(new DataSourceTransactionManager(fixture.dataSource)); write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - write.executeWithoutResult( - status -> { - var selection = - new AssetSourceRepository(fixture.dsl) - .requireExportSelection(fixture.tenantId, fixture.versionId); - var target = selection.binding().target(); - var deletion = - DraftCommitBinding.create( - target, - UUID.randomUUID(), - UUID.randomUUID(), - selection.binding().commitId().toString(), - List.of( - new DraftCommitBinding.RevisionPayload( - "0", - UUID.randomUUID(), - Owner.GAME_DESIGN_CONTROL_PLANE, - AssetSource.deletePayload(USAGE_KEY))), - List.of( - new DraftCommitBinding.AffectedUnit( - Owner.GAME_DESIGN_CONTROL_PLANE, - AssetSource.SCOPE, - target.canonicalVersionId().toString(), - AssetSource.SCOPE, - AssetSource.SCOPE_ID, - selection.sourceEpoch()))); - var sources = new GameDesignSourceRepository(fixture.dsl); - sources.claimReviewed( - deletion, - new GameDesignReviewedBaseRepository(fixture.dsl) - .resolve(target, DraftBaseReference.parse(deletion.baseCommitId()))); - var coordinator = new DraftCommitCoordinatorRepository(fixture.dsl); - coordinator.claimApplicationSlot(deletion); - coordinator.markOwnerInProgress(deletion, Owner.GAME_DESIGN_CONTROL_PLANE); - var result = sources.apply(deletion); - IsolatedPublicationOwnerSetup.advanceIsolatedSourceVisibility( - fixture.dsl, deletion, List.of(result.ownerOutcome())); - sources.captureSynchronized(deletion); - coordinator.releaseApplicationSlot(deletion); - }); + write.executeWithoutResult(status -> { + var selection = + new AssetSourceRepository(fixture.dsl) + .requireExportSelection(fixture.tenantId, fixture.versionId); + var target = selection.binding().target(); + var deletion = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + selection.binding().commitId().toString(), + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.deletePayload(USAGE_KEY))), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.SCOPE, + target.canonicalVersionId().toString(), + AssetSource.SCOPE, + AssetSource.SCOPE_ID, + selection.sourceEpoch()))); + var sources = new GameDesignSourceRepository(fixture.dsl); + sources.claimReviewed( + deletion, + new GameDesignReviewedBaseRepository(fixture.dsl) + .resolve(target, DraftBaseReference.parse(deletion.baseCommitId()))); + var coordinator = new DraftCommitCoordinatorRepository(fixture.dsl); + coordinator.claimApplicationSlot(deletion); + coordinator.markOwnerInProgress(deletion, Owner.GAME_DESIGN_CONTROL_PLANE); + var result = sources.apply(deletion); + IsolatedPublicationOwnerSetup.advanceIsolatedSourceVisibility( + fixture.dsl, deletion, List.of(result.ownerOutcome())); + sources.captureSynchronized(deletion); + coordinator.releaseApplicationSlot(deletion); + }); // This is a real reviewed source deletion and synchronized projection, not missing history. assertThat( new AssetSourceRepository(fixture.dsl) @@ -377,13 +370,12 @@ private Fixture foundedEmptyFixture() { @Test void rejectsRenamingSynchronizedSourceBeforePersistingSnapshot() { Fixture fixture = fixture(); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "UPDATE game_assets SET file_name = ? WHERE tenant_id = ? AND id = ?", - "renamed-logo.bin", - fixture.tenantId, - fixture.assetId)) + assertThatThrownBy(() -> + fixture.dsl.execute( + "UPDATE game_assets SET file_name = ? WHERE tenant_id = ? AND id = ?", + "renamed-logo.bin", + fixture.tenantId, + fixture.assetId)) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("ordinary asset source bytes are immutable from source history"); assertThat( @@ -413,13 +405,11 @@ void rejectsRenamedMappedSourceBeforePersistingSnapshot() { fixture.tenantId, fixture.assetId); - assertThatThrownBy( - () -> - fixture.dsl.transaction( - configuration -> { - new VersionAssetPublicationRepository(DSL.using(configuration)) - .freezeOrReadSnapshot(fixture.tenantId, 1); - })) + assertThatThrownBy(() -> + fixture.dsl.transaction(configuration -> { + new VersionAssetPublicationRepository(DSL.using(configuration)) + .freezeOrReadSnapshot(fixture.tenantId, 1); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("ASSET_SOURCE_EXACT_BYTES_UNAVAILABLE"); assertThat( @@ -445,26 +435,24 @@ void retainsSourceTypeSizeAndExactMappingChecks() { .hasStackTraceContaining("export item differs from synchronized ordinary source"); Fixture wrongSize = fixture(); - assertThatThrownBy( - () -> - insertItem(wrongSize, sha256(SOURCE_BYTES), CONTENT_TYPE, SOURCE_BYTES.length + 1L)) + assertThatThrownBy(() -> + insertItem(wrongSize, sha256(SOURCE_BYTES), CONTENT_TYPE, SOURCE_BYTES.length + 1L)) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("export item differs from synchronized ordinary source"); Fixture wrongMapping = fixture(); - assertThatThrownBy( - () -> - wrongMapping.dsl.execute( - "INSERT INTO version_asset_export_item " - + "(tenant_id, version_id, usage_key, asset_id, content_type, content_hash, byte_size) " - + "VALUES (?, ?, ?, ?, ?, ?, ?)", - wrongMapping.tenantId, - wrongMapping.versionId, - "other.bin", - wrongMapping.assetId, - CONTENT_TYPE, - sha256(SOURCE_BYTES), - SOURCE_BYTES.length)) + assertThatThrownBy(() -> + wrongMapping.dsl.execute( + "INSERT INTO version_asset_export_item " + + "(tenant_id, version_id, usage_key, asset_id, content_type, content_hash, byte_size) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)", + wrongMapping.tenantId, + wrongMapping.versionId, + "other.bin", + wrongMapping.assetId, + CONTENT_TYPE, + sha256(SOURCE_BYTES), + SOURCE_BYTES.length)) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("export item differs from synchronized ordinary source"); } @@ -483,13 +471,12 @@ void requiresDraftVersionAndKeepsSnapshotItemsImmutable() { Fixture frozen = fixture(); insertItemAndSnapshot(frozen); - assertThatThrownBy( - () -> - frozen.dsl.execute( - "UPDATE version_asset_export_item SET byte_size = byte_size " - + "WHERE tenant_id = ? AND version_id = ?", - frozen.tenantId, - frozen.versionId)) + assertThatThrownBy(() -> + frozen.dsl.execute( + "UPDATE version_asset_export_item SET byte_size = byte_size " + + "WHERE tenant_id = ? AND version_id = ?", + frozen.tenantId, + frozen.versionId)) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("snapshot items are immutable"); } @@ -518,13 +505,12 @@ void preservesFrozenSourceBytesAgainstUpdateAfterMetadataSnapshotRead() { new VersionAssetPublicationRepository(fixture.dsl); VersionAssetPublicationRepository.AssetSelection selection = repository.readFrozenSnapshot(fixture.tenantId, 1).items().get(0); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "UPDATE game_assets SET data = ? WHERE tenant_id = ? AND id = ?", - new byte[] {9, 8, 7, 6}, - fixture.tenantId, - fixture.assetId)) + assertThatThrownBy(() -> + fixture.dsl.execute( + "UPDATE game_assets SET data = ? WHERE tenant_id = ? AND id = ?", + new byte[] {9, 8, 7, 6}, + fixture.tenantId, + fixture.assetId)) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("ordinary asset source bytes are immutable from source history"); assertThat(repository.readFrozenSnapshot(fixture.tenantId, 1).items()) @@ -538,12 +524,10 @@ void rejectsOversizedCurrentSourceBeforePersistingExportSnapshot() { byte[] oversized = new byte[(int) VersionAssetPublicationRepository.MAX_SOURCE_ASSET_BYTES + 1]; Fixture fixture = fixture(oversized); - assertThatThrownBy( - () -> - fixture.dsl.transaction( - configuration -> - new VersionAssetPublicationRepository(DSL.using(configuration)) - .freezeOrReadSnapshot(fixture.tenantId, 1))) + assertThatThrownBy(() -> + fixture.dsl.transaction(configuration -> + new VersionAssetPublicationRepository(DSL.using(configuration)) + .freezeOrReadSnapshot(fixture.tenantId, 1))) .isInstanceOf(IllegalStateException.class) .hasMessage("ASSET_TOO_LARGE"); assertThat( @@ -564,30 +548,28 @@ void rejectsOversizedCurrentSourceBeforePersistingExportSnapshot() { void rejectsOversizedRetainedFrozenSourceFromMetadataBeforePayloadRead() { Fixture fixture = fixture(MigrationVersion.fromVersion("49.1")); byte[] oversized = new byte[(int) VersionAssetPublicationRepository.MAX_SOURCE_ASSET_BYTES + 1]; - fixture.dsl.transaction( - configuration -> { - DSLContext transactionDsl = DSL.using(configuration); - transactionDsl.execute( - "UPDATE game_assets SET data = ? WHERE tenant_id = ? AND id = ?", - oversized, - fixture.tenantId, - fixture.assetId); - insertItem(transactionDsl, fixture, sha256(oversized), CONTENT_TYPE, oversized.length); - transactionDsl.execute( - "INSERT INTO version_asset_export_snapshot " - + "(tenant_id, version_id, canonical_tenant_id, canonical_version_id, version_number, " - + "captured_version_state_epoch, item_count) " - + "SELECT tenant_id, id, canonical_tenant_id, canonical_version_id, version_number, " - + "version_state_epoch, 1 FROM version WHERE tenant_id = ? AND id = ?", - fixture.tenantId, - fixture.versionId); - }); + fixture.dsl.transaction(configuration -> { + DSLContext transactionDsl = DSL.using(configuration); + transactionDsl.execute( + "UPDATE game_assets SET data = ? WHERE tenant_id = ? AND id = ?", + oversized, + fixture.tenantId, + fixture.assetId); + insertItem(transactionDsl, fixture, sha256(oversized), CONTENT_TYPE, oversized.length); + transactionDsl.execute( + "INSERT INTO version_asset_export_snapshot " + + "(tenant_id, version_id, canonical_tenant_id, canonical_version_id, version_number, " + + "captured_version_state_epoch, item_count) " + + "SELECT tenant_id, id, canonical_tenant_id, canonical_version_id, version_number, " + + "version_state_epoch, 1 FROM version WHERE tenant_id = ? AND id = ?", + fixture.tenantId, + fixture.versionId); + }); migrateToLatest(fixture); - assertThatThrownBy( - () -> - new VersionAssetPublicationRepository(fixture.dsl) - .readFrozenSnapshot(fixture.tenantId, 1)) + assertThatThrownBy(() -> + new VersionAssetPublicationRepository(fixture.dsl) + .readFrozenSnapshot(fixture.tenantId, 1)) .isInstanceOf(IllegalStateException.class) .hasMessage("ASSET_TOO_LARGE"); } @@ -638,23 +620,21 @@ void freezesCandidateOriginWhileAllowingArtifactLifecycleEpochUpdates() { .get("candidate_public_base_url", String.class)) .isEqualTo(origin); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "UPDATE version_asset_artifact SET candidate_public_base_url = ? " - + "WHERE tenant_id = ? AND version_id = ?", - "https://replacement.example.invalid/assets", - fixture.tenantId, - fixture.versionId)) + assertThatThrownBy(() -> + fixture.dsl.execute( + "UPDATE version_asset_artifact SET candidate_public_base_url = ? " + + "WHERE tenant_id = ? AND version_id = ?", + "https://replacement.example.invalid/assets", + fixture.tenantId, + fixture.versionId)) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("ASSET_EXPORT_CANDIDATE_IMMUTABLE"); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "UPDATE version_asset_artifact SET candidate_public_base_url = NULL " - + "WHERE tenant_id = ? AND version_id = ?", - fixture.tenantId, - fixture.versionId)) + assertThatThrownBy(() -> + fixture.dsl.execute( + "UPDATE version_asset_artifact SET candidate_public_base_url = NULL " + + "WHERE tenant_id = ? AND version_id = ?", + fixture.tenantId, + fixture.versionId)) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("ASSET_EXPORT_CANDIDATE_IMMUTABLE"); } @@ -673,14 +653,13 @@ void retainedPreV50CandidateWithoutOriginAllowsLifecycleUpdateButCannotBeBackfil fixture.tenantId, fixture.versionId)) .isEqualTo(1); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "UPDATE version_asset_artifact SET candidate_public_base_url = ? " - + "WHERE tenant_id = ? AND version_id = ?", - "https://assets.example.invalid/assets", - fixture.tenantId, - fixture.versionId)) + assertThatThrownBy(() -> + fixture.dsl.execute( + "UPDATE version_asset_artifact SET candidate_public_base_url = ? " + + "WHERE tenant_id = ? AND version_id = ?", + "https://assets.example.invalid/assets", + fixture.tenantId, + fixture.versionId)) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("ASSET_EXPORT_CANDIDATE_IMMUTABLE"); } @@ -759,23 +738,21 @@ void selectedCandidateLifecycleWorkflowCanChangeWhileOriginalEvidenceStaysImmuta "manifest_hash = 'sha256:" + "0".repeat(64) + "'", "published_object_proofs_json = '[]'" }) { - assertThatThrownBy( - () -> - fixture.dsl.execute( - "UPDATE version_asset_artifact SET " - + assignment - + " WHERE tenant_id = ? AND version_id = ?", - fixture.tenantId, - fixture.versionId)) + assertThatThrownBy(() -> + fixture.dsl.execute( + "UPDATE version_asset_artifact SET " + + assignment + + " WHERE tenant_id = ? AND version_id = ?", + fixture.tenantId, + fixture.versionId)) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("ASSET_EXPORT_CANDIDATE_IMMUTABLE"); } - assertThatThrownBy( - () -> - fixture.dsl.execute( - "DELETE FROM version_asset_artifact WHERE tenant_id = ? AND version_id = ?", - fixture.tenantId, - fixture.versionId)) + assertThatThrownBy(() -> + fixture.dsl.execute( + "DELETE FROM version_asset_artifact WHERE tenant_id = ? AND version_id = ?", + fixture.tenantId, + fixture.versionId)) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("ASSET_EXPORT_CANDIDATE_RETENTION_REQUIRED"); } @@ -788,22 +765,21 @@ void selectedCandidateRequiresOriginalWorkflowOnInsertAndFirstEvidenceUpdate() { .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("ASSET_EXPORT_SELECTED_CANDIDATE_CONFLICT"); insertArtifactWithoutCandidate(fixture); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "UPDATE version_asset_artifact SET manifest_hash = ?, " - + "manifest_schema_version = 1, artifact_digests_json = '[]', " - + "published_object_proofs_json = ?, selected_candidate_version_id = ?, " - + "selected_candidate_request_digest = ?, " - + "exported_manifest_asset_keys_json = '[]', last_workflow_id = ? " - + "WHERE tenant_id = ? AND version_id = ?", - sha256(SOURCE_BYTES), - selectedManifestProof(), - fixture.versionId, - sha256(SOURCE_BYTES).substring(7), - "unrelated-workflow", - fixture.tenantId, - fixture.versionId)) + assertThatThrownBy(() -> + fixture.dsl.execute( + "UPDATE version_asset_artifact SET manifest_hash = ?, " + + "manifest_schema_version = 1, artifact_digests_json = '[]', " + + "published_object_proofs_json = ?, selected_candidate_version_id = ?, " + + "selected_candidate_request_digest = ?, " + + "exported_manifest_asset_keys_json = '[]', last_workflow_id = ? " + + "WHERE tenant_id = ? AND version_id = ?", + sha256(SOURCE_BYTES), + selectedManifestProof(), + fixture.versionId, + sha256(SOURCE_BYTES).substring(7), + "unrelated-workflow", + fixture.tenantId, + fixture.versionId)) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("ASSET_EXPORT_SELECTED_CANDIDATE_CONFLICT"); } @@ -896,41 +872,40 @@ private Fixture fixture(MigrationVersion target, byte[] sourceBytes) { if (target == null) { var write = new TransactionTemplate(new DataSourceTransactionManager(dataSource)); write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - return write.execute( - status -> { - var game = new Game(); - game.setTenantId(tenantId); - game.setName("Export snapshot test"); - game = new GameRepository(dsl).save(game); - var version = new Version(); - version.setTenantId(tenantId); - version.setVersionNumber(1); - version = new VersionRepository(dsl).save(version); - Long assetId = - Objects.requireNonNull( - dsl.fetchOne( - "INSERT INTO game_assets (tenant_id, file_name, content_type, data) " - + "VALUES (?, ?, ?, ?) RETURNING id", - tenantId, - USAGE_KEY, - CONTENT_TYPE, - sourceBytes), - "asset insert returned no row") - .get(0, Long.class); - IsolatedAssetSourceOwnerSetup.upsert( - dsl, - new TargetProof( - version.getCanonicalTenantId(), - version.getCanonicalVersionId(), - version.getId(), - version.getTenantId(), - version.getIdentitySourceGameRowId(), - version.getIdentitySourceGameTenantKey(), - version.getIdentitySourceProvenanceKind()), - assetId, - USAGE_KEY); - return new Fixture(dsl, tenantId, version.getId(), assetId, dataSource, schema); - }); + return write.execute(status -> { + var game = new Game(); + game.setTenantId(tenantId); + game.setName("Export snapshot test"); + game = new GameRepository(dsl).save(game); + var version = new Version(); + version.setTenantId(tenantId); + version.setVersionNumber(1); + version = new VersionRepository(dsl).save(version); + Long assetId = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO game_assets (tenant_id, file_name, content_type, data) " + + "VALUES (?, ?, ?, ?) RETURNING id", + tenantId, + USAGE_KEY, + CONTENT_TYPE, + sourceBytes), + "asset insert returned no row") + .get(0, Long.class); + IsolatedAssetSourceOwnerSetup.upsert( + dsl, + new TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()), + assetId, + USAGE_KEY); + return new Fixture(dsl, tenantId, version.getId(), assetId, dataSource, schema); + }); } Long gameId = Objects.requireNonNull( @@ -1002,20 +977,18 @@ private static int insertItem( } private static void insertItemAndSnapshot(Fixture fixture) { - fixture.dsl.transaction( - configuration -> { - DSLContext transactionDsl = DSL.using(configuration); - insertItem( - transactionDsl, fixture, sha256(SOURCE_BYTES), CONTENT_TYPE, SOURCE_BYTES.length); - transactionDsl.execute( - "INSERT INTO version_asset_export_snapshot " - + "(tenant_id, version_id, canonical_tenant_id, canonical_version_id, version_number, " - + "captured_version_state_epoch, item_count) " - + "SELECT tenant_id, id, canonical_tenant_id, canonical_version_id, version_number, " - + "version_state_epoch, 1 FROM version WHERE tenant_id = ? AND id = ?", - fixture.tenantId, - fixture.versionId); - }); + fixture.dsl.transaction(configuration -> { + DSLContext transactionDsl = DSL.using(configuration); + insertItem(transactionDsl, fixture, sha256(SOURCE_BYTES), CONTENT_TYPE, SOURCE_BYTES.length); + transactionDsl.execute( + "INSERT INTO version_asset_export_snapshot " + + "(tenant_id, version_id, canonical_tenant_id, canonical_version_id, version_number, " + + "captured_version_state_epoch, item_count) " + + "SELECT tenant_id, id, canonical_tenant_id, canonical_version_id, version_number, " + + "version_state_epoch, 1 FROM version WHERE tenant_id = ? AND id = ?", + fixture.tenantId, + fixture.versionId); + }); } private static void insertArtifactWithoutCandidate(Fixture fixture) { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java index 2000df083d..0951e993c3 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionCanonicalIdentityIntegrationTest.java @@ -111,18 +111,17 @@ void v35_1PreservesRetainedVersionHistoryAndLeavesIdentityUnmapped() { game.getCanonicalTenantId(), UUID.randomUUID())) .isEmpty(); - assertThatThrownBy( - () -> - fixture - .dsl() - .update(VERSION) - .set(CANONICAL_VERSION_ID, UUID.randomUUID()) - .set(CANONICAL_TENANT_ID, game.getCanonicalTenantId()) - .set(IDENTITY_SOURCE_GAME_ROW_ID, game.getId()) - .set(IDENTITY_SOURCE_GAME_TENANT_KEY, game.getTenantId()) - .set(IDENTITY_SOURCE_PROVENANCE_KIND, "NEW_GAME_ROW") - .where(ID.eq(retainedVersionId)) - .execute()) + assertThatThrownBy(() -> + fixture + .dsl() + .update(VERSION) + .set(CANONICAL_VERSION_ID, UUID.randomUUID()) + .set(CANONICAL_TENANT_ID, game.getCanonicalTenantId()) + .set(IDENTITY_SOURCE_GAME_ROW_ID, game.getId()) + .set(IDENTITY_SOURCE_GAME_TENANT_KEY, game.getTenantId()) + .set(IDENTITY_SOURCE_PROVENANCE_KIND, "NEW_GAME_ROW") + .where(ID.eq(retainedVersionId)) + .execute()) .isInstanceOf(DataAccessException.class) .hasMessageContaining("retained Version rows cannot be assigned a canonical identity"); } @@ -269,14 +268,13 @@ void databaseRejectsIdentityMutationNilIdentityAndMismatchedSource() { .execute(status -> fixture.versionRepository().save(version(owner))); assertThat(saved).isNotNull(); - assertThatThrownBy( - () -> - fixture - .dsl() - .update(VERSION) - .set(CANONICAL_VERSION_ID, UUID.randomUUID()) - .where(ID.eq(saved.getId())) - .execute()) + assertThatThrownBy(() -> + fixture + .dsl() + .update(VERSION) + .set(CANONICAL_VERSION_ID, UUID.randomUUID()) + .where(ID.eq(saved.getId())) + .execute()) .isInstanceOf(DataAccessException.class) .hasMessageContaining("canonical Version identity and its tenant source are immutable"); assertThatThrownBy( @@ -284,52 +282,49 @@ void databaseRejectsIdentityMutationNilIdentityAndMismatchedSource() { .isInstanceOf(DataAccessException.class) .hasMessageContaining("canonical Version identity is immutable"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "INSERT INTO version (tenant_id, version_number, version_state, " - + "version_state_epoch, canonical_version_id, canonical_tenant_id, " - + "identity_source_game_row_id, identity_source_game_tenant_key, " - + "identity_source_provenance_kind) " - + "VALUES (?, 2, 'DRAFT', 1, ?, ?, ?, ?, ?)", - owner.getTenantId(), - NIL_UUID, - owner.getCanonicalTenantId(), - owner.getId(), - owner.getTenantId(), - "NEW_GAME_ROW")) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "INSERT INTO version (tenant_id, version_number, version_state, " + + "version_state_epoch, canonical_version_id, canonical_tenant_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind) " + + "VALUES (?, 2, 'DRAFT', 1, ?, ?, ?, ?, ?)", + owner.getTenantId(), + NIL_UUID, + owner.getCanonicalTenantId(), + owner.getId(), + owner.getTenantId(), + "NEW_GAME_ROW")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("chk_version_canonical_identity_shape"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "INSERT INTO version (tenant_id, version_number, version_state, " - + "version_state_epoch, canonical_version_id, canonical_tenant_id, " - + "identity_source_game_row_id, identity_source_game_tenant_key, " - + "identity_source_provenance_kind) " - + "VALUES (?, 3, 'DRAFT', 1, ?, ?, ?, ?, ?)", - owner.getTenantId(), - UUID.randomUUID(), - owner.getCanonicalTenantId(), - other.getId(), - other.getTenantId(), - "NEW_GAME_ROW")) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "INSERT INTO version (tenant_id, version_number, version_state, " + + "version_state_epoch, canonical_version_id, canonical_tenant_id, " + + "identity_source_game_row_id, identity_source_game_tenant_key, " + + "identity_source_provenance_kind) " + + "VALUES (?, 3, 'DRAFT', 1, ?, ?, ?, ?, ?)", + owner.getTenantId(), + UUID.randomUUID(), + owner.getCanonicalTenantId(), + other.getId(), + other.getTenantId(), + "NEW_GAME_ROW")) .isInstanceOf(DataAccessException.class) .hasMessageContaining( "canonical Version identity source does not match its exact game row"); Version wrongTenantAlias = version(owner); wrongTenantAlias.setTenantId(owner.getCanonicalTenantId().toString()); - assertThatThrownBy( - () -> - fixture - .transactionTemplate() - .execute(status -> fixture.versionRepository().save(wrongTenantAlias))) + assertThatThrownBy(() -> + fixture + .transactionTemplate() + .execute(status -> fixture.versionRepository().save(wrongTenantAlias))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("no exact Game Design source row"); } diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java index 3d60831180..210bb04a02 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/CompleteLaunchBindingServiceIntegrationTest.java @@ -187,33 +187,30 @@ void deniesCrossTenantAndSubstitutedSourceSelectorsWithoutMutatingPersistedEvide Map secondBefore = rowVersions(second); UUID absentCanonicalTenant = UUID.randomUUID(); - assertDenied( - () -> - completeLaunchBindingService.getCompleteLaunchBinding( - first.readRequestId(), - second.canonicalTenantId(), - second.source().worldSlug(), - first.controlPlaneRequestId(), - first.descriptor().authoredWorldBinding().requestDigest(), - first.descriptor().authoredWorldBinding().resultDigest())); - assertDenied( - () -> - completeLaunchBindingService.getCompleteLaunchBinding( - first.readRequestId(), - first.canonicalTenantId(), - second.source().worldSlug(), - first.controlPlaneRequestId(), - first.descriptor().authoredWorldBinding().requestDigest(), - first.descriptor().authoredWorldBinding().resultDigest())); - assertDenied( - () -> - completeLaunchBindingService.getCompleteLaunchBinding( - first.readRequestId(), - absentCanonicalTenant, - first.source().worldSlug(), - first.controlPlaneRequestId(), - first.descriptor().authoredWorldBinding().requestDigest(), - first.descriptor().authoredWorldBinding().resultDigest())); + assertDenied(() -> + completeLaunchBindingService.getCompleteLaunchBinding( + first.readRequestId(), + second.canonicalTenantId(), + second.source().worldSlug(), + first.controlPlaneRequestId(), + first.descriptor().authoredWorldBinding().requestDigest(), + first.descriptor().authoredWorldBinding().resultDigest())); + assertDenied(() -> + completeLaunchBindingService.getCompleteLaunchBinding( + first.readRequestId(), + first.canonicalTenantId(), + second.source().worldSlug(), + first.controlPlaneRequestId(), + first.descriptor().authoredWorldBinding().requestDigest(), + first.descriptor().authoredWorldBinding().resultDigest())); + assertDenied(() -> + completeLaunchBindingService.getCompleteLaunchBinding( + first.readRequestId(), + absentCanonicalTenant, + first.source().worldSlug(), + first.controlPlaneRequestId(), + first.descriptor().authoredWorldBinding().requestDigest(), + first.descriptor().authoredWorldBinding().resultDigest())); PublishedReleaseBundle swappedCanonicalSource = new PublishedReleaseBundle(); swappedCanonicalSource.setTenantId(first.privateTenantKey()); @@ -248,17 +245,15 @@ void descriptorSnapshotRejectsNonRepeatableReadBeforeAnyWrite() { readCommitted.setReadOnly(true); readCommitted.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - assertThatThrownBy( - () -> - readCommitted.execute( - status -> - launchDescriptorService.getLaunchDescriptorInOwnerSnapshot( - fixture.readRequestId(), - fixture.canonicalTenantId(), - fixture.source().worldSlug(), - fixture.controlPlaneRequestId(), - fixture.descriptor().authoredWorldBinding().requestDigest(), - fixture.descriptor().authoredWorldBinding().resultDigest()))) + assertThatThrownBy(() -> + readCommitted.execute(status -> + launchDescriptorService.getLaunchDescriptorInOwnerSnapshot( + fixture.readRequestId(), + fixture.canonicalTenantId(), + fixture.source().worldSlug(), + fixture.controlPlaneRequestId(), + fixture.descriptor().authoredWorldBinding().requestDigest(), + fixture.descriptor().authoredWorldBinding().resultDigest()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("read-only REPEATABLE_READ"); @@ -350,15 +345,14 @@ private Fixture fixture(String label, boolean completeEvidence) { AuthoredWorldSourceEvidence source = new TransactionTemplate(transactionManager) - .execute( - status -> - authoredWorldSourceRepository.register( - NAMESPACE, - UUID.randomUUID(), - persistedGame.getCanonicalTenantId(), - "tenant-" + suffix, - "world-" + suffix, - "Synthetic Complete Binding World")); + .execute(status -> + authoredWorldSourceRepository.register( + NAMESPACE, + UUID.randomUUID(), + persistedGame.getCanonicalTenantId(), + "tenant-" + suffix, + "world-" + suffix, + "Synthetic Complete Binding World")); Version version = new Version(); version.setTenantId(privateTenantKey); @@ -500,16 +494,15 @@ private CompleteLaunchBindingDto readComplete(Fixture fixture) { private void advanceVersion(Fixture fixture, VersionLifecycleState state, long epoch) { TransactionTemplate transaction = new TransactionTemplate(transactionManager); - transaction.execute( - status -> { - Version current = - versionRepository - .findByTenantIdAndId(fixture.privateTenantKey(), fixture.version().getId()) - .orElseThrow(); - current.setVersionState(state); - current.setVersionStateEpoch(epoch); - return versionRepository.save(current); - }); + transaction.execute(status -> { + Version current = + versionRepository + .findByTenantIdAndId(fixture.privateTenantKey(), fixture.version().getId()) + .orElseThrow(); + current.setVersionState(state); + current.setVersionStateEpoch(epoch); + return versionRepository.save(current); + }); } private Map rowVersions(Fixture fixture) { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java index 5667af98f1..7839afa4d1 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/LaunchDescriptorServiceIntegrationTest.java @@ -127,10 +127,9 @@ void legacyNumericResolveFailsClosedWithoutPersistingDescriptor() throws Excepti var applicationNameOrigin = environment.getPropertySources().stream() .filter(source -> source.containsProperty("spring.application.name")) - .map( - source -> - org.springframework.boot.origin.OriginLookup.getOrigin( - source, "spring.application.name")) + .map(source -> + org.springframework.boot.origin.OriginLookup.getOrigin( + source, "spring.application.name")) .filter(java.util.Objects::nonNull) .findFirst() .orElseThrow( @@ -158,10 +157,9 @@ void legacyNumericResolveFailsClosedWithoutPersistingDescriptor() throws Excepti actualApplicationConfig, expectedApplicationConfig) .isEqualTo(expectedApplicationConfig); - assertThatThrownBy( - () -> - legacyLaunchDescriptorService.resolveLaunchDescriptor( - "1", 9L, "integration-cp-unbound", null, null, null, null)) + assertThatThrownBy(() -> + legacyLaunchDescriptorService.resolveLaunchDescriptor( + "1", 9L, "integration-cp-unbound", null, null, null, null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage( "AUTHORED_WORLD_LAUNCH_BINDING_REQUIRED: canonical authored-world source binding is" @@ -366,10 +364,9 @@ void deterministicFailureIsFrozenAcrossDependencyChangeAndConcurrentExactRetries executor.shutdownNow(); } - assertThatThrownBy( - () -> - launchDescriptorService.resolveLaunchDescriptor( - fixture.requestWithPatch("different-patch"))) + assertThatThrownBy(() -> + launchDescriptorService.resolveLaunchDescriptor( + fixture.requestWithPatch("different-patch"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("control-plane request identity was reused with changed input"); @@ -410,10 +407,9 @@ public LaunchDescriptor insertImmutable(LaunchDescriptor descriptor) { ReflectionTestUtils.setField(corruptingService, "workloadNamespace", NAMESPACE); TransactionTemplate transaction = new TransactionTemplate(transactionManager); - assertThatThrownBy( - () -> - transaction.execute( - status -> corruptingService.resolveLaunchDescriptor(fixture.request()))) + assertThatThrownBy(() -> + transaction.execute( + status -> corruptingService.resolveLaunchDescriptor(fixture.request()))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("stored failure is not the exact immutable request outcome"); @@ -503,13 +499,11 @@ void rolledBackDescriptorInsertLeavesNoCanonicalOrPrivateRequestClaim() { candidate.setOutcomeStatus(LaunchDescriptor.OUTCOME_SUCCESS); TransactionTemplate transaction = new TransactionTemplate(transactionManager); - assertThatThrownBy( - () -> - transaction.execute( - status -> { - launchDescriptorRepository.insertImmutable(candidate); - throw new IllegalStateException("force owner transaction rollback"); - })) + assertThatThrownBy(() -> + transaction.execute(status -> { + launchDescriptorRepository.insertImmutable(candidate); + throw new IllegalStateException("force owner transaction rollback"); + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("force owner transaction rollback"); @@ -735,12 +729,11 @@ void v39MigrationPreservesRetainedPublicationEvidenceAndStoresLongDiagnostics() assertThat(requiredSnapshot(migratedRows, "version_asset_artifact").get("last_error_message")) .isEqualTo(longArtifactError); - assertThatThrownBy( - () -> - isolatedDsl.execute( - "UPDATE publish_attempt SET failure_message = ? WHERE id = ?", - "forbidden-terminal-rewrite-" + suffix, - attemptId)) + assertThatThrownBy(() -> + isolatedDsl.execute( + "UPDATE publish_attempt SET failure_message = ? WHERE id = ?", + "forbidden-terminal-rewrite-" + suffix, + attemptId)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining("publish attempt is stale or terminal"); Map> afterRejectedTerminalRewrite = @@ -999,12 +992,11 @@ void v35AndV36MigrationsPreserveRetainedBundleAndUnboundDescriptorWithoutBackfil before, launchRepository.findByPrivateRequest(privateTenantKey, requestId).orElseThrow()); assertThat(readRetainedRows.get()).isEqualTo(retainedCurrentRows); - assertThatThrownBy( - () -> - isolatedDsl.execute( - "UPDATE launch_descriptor SET runtime_flags_json = ? WHERE id = ?", - "{\"changed\":true}", - before.getId())) + assertThatThrownBy(() -> + isolatedDsl.execute( + "UPDATE launch_descriptor SET runtime_flags_json = ? WHERE id = ?", + "{\"changed\":true}", + before.getId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining("launch descriptors are immutable"); assertRetainedRowUnchanged( @@ -1026,15 +1018,14 @@ private Fixture fixture(String controlPlaneRequestId) { String suffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); AuthoredWorldSourceEvidence source = new TransactionTemplate(transactionManager) - .execute( - status -> - authoredWorldSourceRepository.register( - NAMESPACE, - UUID.randomUUID(), - persistedGame.getCanonicalTenantId(), - "tenant-" + suffix, - "world-" + suffix, - "Launch World 🐉")); + .execute(status -> + authoredWorldSourceRepository.register( + NAMESPACE, + UUID.randomUUID(), + persistedGame.getCanonicalTenantId(), + "tenant-" + suffix, + "world-" + suffix, + "Launch World 🐉")); assertThat(source).isNotNull(); Version version = new Version(); @@ -1082,43 +1073,42 @@ private Fixture fixture(String controlPlaneRequestId) { private void assertFailedShapeRejected( LaunchDescriptor failed, String controlPlaneRequestId, boolean nullSchemaVersion) { - assertThatThrownBy( - () -> - dsl.execute( - """ - INSERT INTO launch_descriptor ( - tenant_id, - control_plane_request_id, - request_hash, - descriptor_schema_version, - target_namespace, - canonical_tenant_id, - world_slug, - authored_world_source_operation_id, - authored_world_source_evidence_digest, - request_digest, - original_request_json, - source_evidence_json, - outcome_status, - failure_code, - failure_message) - VALUES (?, ?, ?, CAST(? AS SMALLINT), ?, CAST(? AS UUID), ?, - CAST(? AS UUID), ?, ?, ?, ?, 'FAILED', CAST(? AS VARCHAR(64)), ?) - """, - failed.getTenantId(), - controlPlaneRequestId, - failed.getRequestHash(), - nullSchemaVersion ? null : failed.getDescriptorSchemaVersion(), - failed.getTargetNamespace(), - failed.getCanonicalTenantId(), - failed.getWorldSlug(), - failed.getAuthoredWorldSourceOperationId(), - failed.getAuthoredWorldSourceEvidenceDigest(), - failed.getRequestDigest(), - failed.getOriginalRequestJson(), - failed.getSourceEvidenceJson(), - nullSchemaVersion ? failed.getFailureCode() : null, - failed.getFailureMessage())) + assertThatThrownBy(() -> + dsl.execute( + """ + INSERT INTO launch_descriptor ( + tenant_id, + control_plane_request_id, + request_hash, + descriptor_schema_version, + target_namespace, + canonical_tenant_id, + world_slug, + authored_world_source_operation_id, + authored_world_source_evidence_digest, + request_digest, + original_request_json, + source_evidence_json, + outcome_status, + failure_code, + failure_message) + VALUES (?, ?, ?, CAST(? AS SMALLINT), ?, CAST(? AS UUID), ?, + CAST(? AS UUID), ?, ?, ?, ?, 'FAILED', CAST(? AS VARCHAR(64)), ?) + """, + failed.getTenantId(), + controlPlaneRequestId, + failed.getRequestHash(), + nullSchemaVersion ? null : failed.getDescriptorSchemaVersion(), + failed.getTargetNamespace(), + failed.getCanonicalTenantId(), + failed.getWorldSlug(), + failed.getAuthoredWorldSourceOperationId(), + failed.getAuthoredWorldSourceEvidenceDigest(), + failed.getRequestDigest(), + failed.getOriginalRequestJson(), + failed.getSourceEvidenceJson(), + nullSchemaVersion ? failed.getFailureCode() : null, + failed.getFailureMessage())) .isInstanceOf(DataIntegrityViolationException.class) .hasStackTraceContaining("ck_launch_descriptor_authored_binding_complete"); } @@ -1150,18 +1140,17 @@ private String resolveCandidateInOwnerTransaction( ready.countDown(); await(start); return new TransactionTemplate(transactionManager) - .execute( - status -> { - try { - return "SUCCESS:" - + service - .resolveLaunchDescriptor(fixture.request()) - .authoredWorldBinding() - .resultDigest(); - } catch (IllegalArgumentException exception) { - return "FAILED:" + exception.getMessage(); - } - }); + .execute(status -> { + try { + return "SUCCESS:" + + service + .resolveLaunchDescriptor(fixture.request()) + .authoredWorldBinding() + .resultDigest(); + } catch (IllegalArgumentException exception) { + return "FAILED:" + exception.getMessage(); + } + }); } private LaunchDescriptorServiceImpl candidateForPhase( @@ -1177,12 +1166,11 @@ private LaunchDescriptorServiceImpl candidateForPhase( Mockito.when(view.getDefaultVersionId()).thenReturn(fixture.version().getId()); Mockito.when(view.getDefaultRuntimeFlagsJson()).thenReturn("{}"); Mockito.when(view.getTemplateReferencePhase()) - .thenAnswer( - invocation -> { - viewReached.countDown(); - await(continueResolution); - return phase; - }); + .thenAnswer(invocation -> { + viewReached.countDown(); + await(continueResolution); + return phase; + }); Mockito.when( templateRepository.findLaunchConfigByTenantIdAndId( fixture.privateSourceTenantKey(), fixture.template().getId())) @@ -1330,39 +1318,38 @@ private AuthoredWorldSourceEvidence seedPreV41AuthoredWorldSource( "NEW_GAME_ROW", evidenceDigest); - isolatedTransaction.execute( - status -> { - isolatedDsl.execute( - "INSERT INTO game_design_tenant_slug_binding " - + "(target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id, " - + "source_game_tenant_key, provenance_kind) VALUES (?, ?, ?, ?, ?, ?)", - source.targetNamespace(), - source.canonicalTenantId(), - source.tenantSlug(), - source.sourceGameRowId(), - source.sourceGameTenantKey(), - source.provenanceKind()); - isolatedDsl.execute( - "INSERT INTO game_design_authored_world_source_operations " - + "(operation_id, schema_version, target_namespace, registration_request_id, " - + "request_digest, canonical_tenant_id, tenant_slug, world_slug, " - + "world_display_name, source_game_row_id, source_game_tenant_key, " - + "provenance_kind, evidence_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - source.operationId(), - source.schemaVersion(), - source.targetNamespace(), - source.registrationRequestId(), - source.requestDigest(), - source.canonicalTenantId(), - source.tenantSlug(), - source.worldSlug(), - source.worldDisplayName(), - source.sourceGameRowId(), - source.sourceGameTenantKey(), - source.provenanceKind(), - source.evidenceDigest()); - return null; - }); + isolatedTransaction.execute(status -> { + isolatedDsl.execute( + "INSERT INTO game_design_tenant_slug_binding " + + "(target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id, " + + "source_game_tenant_key, provenance_kind) VALUES (?, ?, ?, ?, ?, ?)", + source.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind()); + isolatedDsl.execute( + "INSERT INTO game_design_authored_world_source_operations " + + "(operation_id, schema_version, target_namespace, registration_request_id, " + + "request_digest, canonical_tenant_id, tenant_slug, world_slug, " + + "world_display_name, source_game_row_id, source_game_tenant_key, " + + "provenance_kind, evidence_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + source.operationId(), + source.schemaVersion(), + source.targetNamespace(), + source.registrationRequestId(), + source.requestDigest(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), + source.worldDisplayName(), + source.sourceGameRowId(), + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()); + return null; + }); return source; } @@ -1462,14 +1449,13 @@ private Map> publicationEvidenceRows( private Map> priorPublicationEvidenceColumns( Map> snapshots, Map> prior) { Map> projected = new java.util.LinkedHashMap<>(); - prior.forEach( - (table, before) -> { - var after = requiredSnapshot(snapshots, table); - assertThat(after.keySet()).containsAll(before.keySet()); - Map columns = new java.util.LinkedHashMap<>(); - before.keySet().forEach(column -> columns.put(column, after.get(column))); - projected.put(table, columns); - }); + prior.forEach((table, before) -> { + var after = requiredSnapshot(snapshots, table); + assertThat(after.keySet()).containsAll(before.keySet()); + Map columns = new java.util.LinkedHashMap<>(); + before.keySet().forEach(column -> columns.put(column, after.get(column))); + projected.put(table, columns); + }); return projected; } @@ -1678,88 +1664,81 @@ void authoredSourceMigrationBindsFullSourceTupleAndRetainsLegacyRows() { null, null); - assertThatThrownBy( - () -> - insertFailedDescriptor( - tenantId, - "launch-schema-missing-source", - UUID.randomUUID(), - source, - source.evidenceDigest(), - requestDigest)) + assertThatThrownBy(() -> + insertFailedDescriptor( + tenantId, + "launch-schema-missing-source", + UUID.randomUUID(), + source, + source.evidenceDigest(), + requestDigest)) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - insertFailedDescriptor( - tenantId, - "launch-schema-mismatched-source", + assertThatThrownBy(() -> + insertFailedDescriptor( + tenantId, + "launch-schema-mismatched-source", + source.operationId(), + new AuthoredWorldSourceFixture( + source.targetNamespace(), + source.canonicalTenantId(), + source.tenantSlug(), + source.worldSlug(), source.operationId(), - new AuthoredWorldSourceFixture( - source.targetNamespace(), - source.canonicalTenantId(), - source.tenantSlug(), - source.worldSlug(), - source.operationId(), - source.sourceGameRowId() + 1, - source.sourceGameTenantKey(), - source.provenanceKind(), - source.evidenceDigest()), - source.evidenceDigest(), - requestDigest)) + source.sourceGameRowId() + 1, + source.sourceGameTenantKey(), + source.provenanceKind(), + source.evidenceDigest()), + source.evidenceDigest(), + requestDigest)) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - insertFailedDescriptor( - tenantId, - "launch-schema-malformed-source-digest", - source.operationId(), - source, - "sha256:" + "d".repeat(63), - requestDigest)) + assertThatThrownBy(() -> + insertFailedDescriptor( + tenantId, + "launch-schema-malformed-source-digest", + source.operationId(), + source, + "sha256:" + "d".repeat(63), + requestDigest)) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - insertFailedDescriptor( - tenantId, - "launch-schema-malformed-request-digest", - source.operationId(), - source, - source.evidenceDigest(), - "not-a-sha256-digest")) + assertThatThrownBy(() -> + insertFailedDescriptor( + tenantId, + "launch-schema-malformed-request-digest", + source.operationId(), + source, + source.evidenceDigest(), + "not-a-sha256-digest")) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - insertSuccessDescriptor( - "launch-schema-malformed-result-" + UUID.randomUUID(), - tenantId, - savedTemplate, - savedVersion, - savedBundle, - "launch-schema-malformed-result-request", - requestDigest, - "sha256:" + "e".repeat(63), - source, - source.evidenceDigest())) + assertThatThrownBy(() -> + insertSuccessDescriptor( + "launch-schema-malformed-result-" + UUID.randomUUID(), + tenantId, + savedTemplate, + savedVersion, + savedBundle, + "launch-schema-malformed-result-request", + requestDigest, + "sha256:" + "e".repeat(63), + source, + source.evidenceDigest())) .isInstanceOf(DataAccessException.class); assertThatThrownBy(() -> jdbcTemplate.execute("TRUNCATE TABLE launch_descriptor")) .isInstanceOf(DataAccessException.class) .rootCause() - .satisfies( - failure -> { - assertThat(failure).isInstanceOf(SQLException.class); - assertThat(((SQLException) failure).getSQLState()).isEqualTo("0A000"); - }) + .satisfies(failure -> { + assertThat(failure).isInstanceOf(SQLException.class); + assertThat(((SQLException) failure).getSQLState()).isEqualTo("0A000"); + }) .hasMessageContaining("cannot truncate a table referenced in a foreign key constraint"); assertThatThrownBy(() -> jdbcTemplate.execute("TRUNCATE TABLE launch_descriptor CASCADE")) .isInstanceOf(DataAccessException.class) .rootCause() .hasMessageContaining("launch descriptors are immutable"); - assertThatThrownBy( - () -> - jdbcTemplate.update( - "DELETE FROM launch_descriptor WHERE control_plane_request_id = ?", - "launch-schema-bound-request")) + assertThatThrownBy(() -> + jdbcTemplate.update( + "DELETE FROM launch_descriptor WHERE control_plane_request_id = ?", + "launch-schema-bound-request")) .isInstanceOf(DataAccessException.class) .rootCause() .hasMessageContaining("launch descriptors are immutable"); @@ -1780,38 +1759,37 @@ private AuthoredWorldSourceFixture insertAuthoredWorldSourceFixture(Game game) { String requestDigest = sha256("f"); String evidenceDigest = sha256("1"); new TransactionTemplate(transactionManager) - .execute( - transaction -> { - jdbcTemplate.update( - "INSERT INTO game_design_tenant_slug_binding " - + "(target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id, " - + "source_game_tenant_key, provenance_kind) VALUES (?, ?, ?, ?, ?, ?)", - targetNamespace, - game.getCanonicalTenantId(), - tenantSlug, - game.getId(), - game.getTenantId(), - provenanceKind); - jdbcTemplate.update( - "INSERT INTO game_design_authored_world_source_operations " - + "(operation_id, schema_version, target_namespace, registration_request_id, " - + "request_digest, canonical_tenant_id, tenant_slug, world_slug, " - + "world_display_name, source_game_row_id, source_game_tenant_key, " - + "provenance_kind, evidence_digest) VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - operationId, - targetNamespace, - UUID.randomUUID(), - requestDigest, - game.getCanonicalTenantId(), - tenantSlug, - worldSlug, - "Launch schema world", - game.getId(), - game.getTenantId(), - provenanceKind, - evidenceDigest); - return null; - }); + .execute(transaction -> { + jdbcTemplate.update( + "INSERT INTO game_design_tenant_slug_binding " + + "(target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id, " + + "source_game_tenant_key, provenance_kind) VALUES (?, ?, ?, ?, ?, ?)", + targetNamespace, + game.getCanonicalTenantId(), + tenantSlug, + game.getId(), + game.getTenantId(), + provenanceKind); + jdbcTemplate.update( + "INSERT INTO game_design_authored_world_source_operations " + + "(operation_id, schema_version, target_namespace, registration_request_id, " + + "request_digest, canonical_tenant_id, tenant_slug, world_slug, " + + "world_display_name, source_game_row_id, source_game_tenant_key, " + + "provenance_kind, evidence_digest) VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + targetNamespace, + UUID.randomUUID(), + requestDigest, + game.getCanonicalTenantId(), + tenantSlug, + worldSlug, + "Launch schema world", + game.getId(), + game.getTenantId(), + provenanceKind, + evidenceDigest); + return null; + }); return new AuthoredWorldSourceFixture( targetNamespace, game.getCanonicalTenantId(), diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java index c62ea5bb7d..9b3412734c 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/PublishAttemptServiceTransactionIntegrationTest.java @@ -254,13 +254,12 @@ void publishAttemptSaveUsesRevisionCasAndRejectsStaleAndTerminalUpdates() { void fullVersionSealTransactionUsesExplicitReadCommittedIsolation() { AtomicReference isolation = new AtomicReference<>(); - publishAttemptService.executeFullVersionTransaction( - () -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); - isolation.set(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()); - return null; - }); + publishAttemptService.executeFullVersionTransaction(() -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + isolation.set(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()); + return null; + }); assertThat(isolation.get()).isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); } @@ -273,54 +272,52 @@ void fullVersionTransactionRollsBackVersionBundleArtifactAndAttemptTogether() { gameRepository.save(game); AtomicReference savedVersion = new AtomicReference<>(); - assertThatThrownBy( - () -> - publishAttemptService.executeFullVersionTransaction( - () -> { - Version version = new Version(); - version.setTenantId(TENANT_ID); - version.setVersionNumber(1); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch(2L); - version.setNotes("transaction proof"); - Version persistedVersion = versionRepository.save(version); - savedVersion.set(persistedVersion); - - PublishAttempt attempt = new PublishAttempt(); - attempt.setTenantId(TENANT_ID); - attempt.setPublishWorkflowId(WORKFLOW_ID); - attempt.setPublishType(PublishType.FULL_VERSION); - attempt.setStatus(PublishAttemptStatus.SUCCEEDED); - attempt.setVersionId(persistedVersion.getId()); - attempt.setVersionNumber(persistedVersion.getVersionNumber()); - publishAttemptRepository.save(attempt); - - PublishedReleaseBundle bundle = new PublishedReleaseBundle(); - bundle.setTenantId(TENANT_ID); - bundle.setVersionId(persistedVersion.getId()); - bundle.setVersionNumber(persistedVersion.getVersionNumber()); - bundle.setAttestationSchemaVersion("v1"); - bundle.setPublishWorkflowId(WORKFLOW_ID); - bundle.setManifestHash("transaction-proof-manifest"); - bundle.setGenerationConfigRevision("transaction-proof-generation"); - bundle.setRequiredManifestAssetKeysJson("[]"); - bundle.setParticipantDigestsJson("[]"); - bundle.setCommandDefinitionsJson("[]"); - publishedReleaseBundleRepository.save(bundle); - - VersionAssetArtifact artifact = new VersionAssetArtifact(); - artifact.setTenantId(TENANT_ID); - artifact.setVersionId(persistedVersion.getId()); - artifact.setExportedVersionNumber(persistedVersion.getVersionNumber()); - artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); - artifact.setStateEpoch(2L); - artifact.setManifestHash(bundle.getManifestHash()); - artifact.setLastWorkflowId(WORKFLOW_ID); - artifact.setExportedManifestAssetKeysJson("[]"); - versionAssetArtifactRepository.save(artifact); - - throw new IllegalStateException("forced finalization failure"); - })) + assertThatThrownBy(() -> + publishAttemptService.executeFullVersionTransaction(() -> { + Version version = new Version(); + version.setTenantId(TENANT_ID); + version.setVersionNumber(1); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch(2L); + version.setNotes("transaction proof"); + Version persistedVersion = versionRepository.save(version); + savedVersion.set(persistedVersion); + + PublishAttempt attempt = new PublishAttempt(); + attempt.setTenantId(TENANT_ID); + attempt.setPublishWorkflowId(WORKFLOW_ID); + attempt.setPublishType(PublishType.FULL_VERSION); + attempt.setStatus(PublishAttemptStatus.SUCCEEDED); + attempt.setVersionId(persistedVersion.getId()); + attempt.setVersionNumber(persistedVersion.getVersionNumber()); + publishAttemptRepository.save(attempt); + + PublishedReleaseBundle bundle = new PublishedReleaseBundle(); + bundle.setTenantId(TENANT_ID); + bundle.setVersionId(persistedVersion.getId()); + bundle.setVersionNumber(persistedVersion.getVersionNumber()); + bundle.setAttestationSchemaVersion("v1"); + bundle.setPublishWorkflowId(WORKFLOW_ID); + bundle.setManifestHash("transaction-proof-manifest"); + bundle.setGenerationConfigRevision("transaction-proof-generation"); + bundle.setRequiredManifestAssetKeysJson("[]"); + bundle.setParticipantDigestsJson("[]"); + bundle.setCommandDefinitionsJson("[]"); + publishedReleaseBundleRepository.save(bundle); + + VersionAssetArtifact artifact = new VersionAssetArtifact(); + artifact.setTenantId(TENANT_ID); + artifact.setVersionId(persistedVersion.getId()); + artifact.setExportedVersionNumber(persistedVersion.getVersionNumber()); + artifact.setArtifactState(VersionAssetArtifactState.PUBLISHED); + artifact.setStateEpoch(2L); + artifact.setManifestHash(bundle.getManifestHash()); + artifact.setLastWorkflowId(WORKFLOW_ID); + artifact.setExportedManifestAssetKeysJson("[]"); + versionAssetArtifactRepository.save(artifact); + + throw new IllegalStateException("forced finalization failure"); + })) .isInstanceOf(PublishAttemptService.FullVersionTransactionException.class) .hasCauseInstanceOf(IllegalStateException.class); @@ -352,10 +349,9 @@ void failedScriptPatchRetainsCanonicalVersionAndReplaysDurableFailure() { .collectScriptPatchParticipantDigests( Mockito.any(VersionDto.class), Mockito.eq(publishRequestId), Mockito.eq(workflowId)); - assertThatThrownBy( - () -> - versionService.publishScriptPatchVersion( - tenantId, baseVersionId, scriptPatchVersion, "first notes", publishRequestId)) + assertThatThrownBy(() -> + versionService.publishScriptPatchVersion( + tenantId, baseVersionId, scriptPatchVersion, "first notes", publishRequestId)) .isInstanceOf(IllegalStateException.class) .hasMessage("script patch participant unavailable"); @@ -376,10 +372,9 @@ void failedScriptPatchRetainsCanonicalVersionAndReplaysDurableFailure() { assertThat(retainedVersion.getCanonicalVersionId()).isNotNull(); assertThat(retainedVersion.getCanonicalTenantId()).isEqualTo(savedGame.getCanonicalTenantId()); - assertThatThrownBy( - () -> - versionService.publishScriptPatchVersion( - tenantId, baseVersionId, scriptPatchVersion, "changed notes", publishRequestId)) + assertThatThrownBy(() -> + versionService.publishScriptPatchVersion( + tenantId, baseVersionId, scriptPatchVersion, "changed notes", publishRequestId)) .isInstanceOf(IllegalStateException.class) .hasMessage("script patch participant unavailable"); @@ -400,10 +395,9 @@ void failedScriptPatchRetainsCanonicalVersionAndReplaysDurableFailure() { assertThat(replayedAttempt.getVersionId()).isEqualTo(retainedVersion.getId()); assertThat(replayedAttempt.getStatus()).isEqualTo(PublishAttemptStatus.FAILED); - assertThatThrownBy( - () -> - versionService.publishScriptPatchVersion( - tenantId, baseVersionId, scriptPatchVersion, "new identity", "new-request-id")) + assertThatThrownBy(() -> + versionService.publishScriptPatchVersion( + tenantId, baseVersionId, scriptPatchVersion, "new identity", "new-request-id")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("PUBLISH_SCRIPT_PATCH_IDENTITY_CONFLICT"); assertThat( @@ -427,22 +421,20 @@ void failedScriptPatchRetainsCandidateForReplayAndReservesItsTuple() { Mockito.when( publishGateService.collectScriptPatchParticipantDigests( Mockito.any(VersionDto.class), Mockito.anyString(), Mockito.anyString())) - .thenAnswer( - invocation -> { - participantCollectionCount.incrementAndGet(); - throw new PublishGateFailureException( - PublishGateFailureCode.PARTICIPANT_SCOPE_MISMATCH, "script scope mismatch"); - }); + .thenAnswer(invocation -> { + participantCollectionCount.incrementAndGet(); + throw new PublishGateFailureException( + PublishGateFailureCode.PARTICIPANT_SCOPE_MISMATCH, "script scope mismatch"); + }); Throwable firstFailure = - catchThrowable( - () -> - versionService.publishScriptPatchVersion( - tenantId, - baseVersionId, - scriptPatchVersion, - "gate failure notes", - publishRequestId)); + catchThrowable(() -> + versionService.publishScriptPatchVersion( + tenantId, + baseVersionId, + scriptPatchVersion, + "gate failure notes", + publishRequestId)); assertThat(firstFailure).isInstanceOf(PublishGateFailureException.class); PublishGateFailureException firstGateFailure = (PublishGateFailureException) firstFailure; @@ -481,14 +473,13 @@ void failedScriptPatchRetainsCandidateForReplayAndReservesItsTuple() { .containsExactly(retainedCandidate.getId()); Throwable replayFailure = - catchThrowable( - () -> - versionService.publishScriptPatchVersion( - tenantId, - baseVersionId, - scriptPatchVersion, - "gate failure notes", - publishRequestId)); + catchThrowable(() -> + versionService.publishScriptPatchVersion( + tenantId, + baseVersionId, + scriptPatchVersion, + "gate failure notes", + publishRequestId)); assertThat(replayFailure).isInstanceOf(PublishGateFailureException.class); PublishGateFailureException replayGateFailure = (PublishGateFailureException) replayFailure; assertThat(replayGateFailure.failureCode()) @@ -509,14 +500,13 @@ void failedScriptPatchRetainsCandidateForReplayAndReservesItsTuple() { .containsExactly(retainedCandidate.getId()); Throwable changedNotesReplayFailure = - catchThrowable( - () -> - versionService.publishScriptPatchVersion( - tenantId, - baseVersionId, - scriptPatchVersion, - "changed replay notes", - publishRequestId)); + catchThrowable(() -> + versionService.publishScriptPatchVersion( + tenantId, + baseVersionId, + scriptPatchVersion, + "changed replay notes", + publishRequestId)); assertThat(changedNotesReplayFailure).isInstanceOf(PublishGateFailureException.class); PublishGateFailureException changedNotesReplayGateFailure = (PublishGateFailureException) changedNotesReplayFailure; @@ -532,14 +522,13 @@ void failedScriptPatchRetainsCandidateForReplayAndReservesItsTuple() { assertThat(attemptAfterReplay.getVersionId()).isEqualTo(retainedCandidate.getId()); Throwable tupleConflict = - catchThrowable( - () -> - versionService.publishScriptPatchVersion( - tenantId, - baseVersionId, - scriptPatchVersion, - "new request notes", - "script-patch-same-tuple-new-request")); + catchThrowable(() -> + versionService.publishScriptPatchVersion( + tenantId, + baseVersionId, + scriptPatchVersion, + "new request notes", + "script-patch-same-tuple-new-request")); assertThat(tupleConflict) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("PUBLISH_SCRIPT_PATCH_IDENTITY_CONFLICT"); @@ -562,14 +551,13 @@ void failedScriptPatchRetainsCandidateForReplayAndReservesItsTuple() { PublicationDigestRequestBinding.patch( tenantId, String.valueOf(baseVersionId), independentPatchVersion, independentRequestId); Throwable independentPatchFailure = - catchThrowable( - () -> - versionService.publishScriptPatchVersion( - tenantId, - baseVersionId, - independentPatchVersion, - "independent patch notes", - independentRequestId)); + catchThrowable(() -> + versionService.publishScriptPatchVersion( + tenantId, + baseVersionId, + independentPatchVersion, + "independent patch notes", + independentRequestId)); assertThat(independentPatchFailure).isInstanceOf(PublishGateFailureException.class); PublishAttempt independentAttempt = publishAttemptRepository @@ -604,10 +592,9 @@ void publicScriptPatchWithoutManifestRetainsCanonicalDraftAndReplaysTerminalFail .thenReturn(List.of()); Throwable first = - catchThrowable( - () -> - versionService.publishScriptPatchVersion( - tenantId, baseVersionId, patch, "original notes", requestId)); + catchThrowable(() -> + versionService.publishScriptPatchVersion( + tenantId, baseVersionId, patch, "original notes", requestId)); assertThat(first).isInstanceOf(ScriptPatchPublishFailureException.class); assertThat(((ScriptPatchPublishFailureException) first).failureCode()) .isEqualTo("SCRIPT_PATCH_MANIFEST_UNAVAILABLE"); @@ -651,10 +638,9 @@ void publicScriptPatchWithoutManifestRetainsCanonicalDraftAndReplaysTerminalFail .intoMap(); Throwable replay = - catchThrowable( - () -> - versionService.publishScriptPatchVersion( - tenantId, baseVersionId, patch, "changed notes", requestId)); + catchThrowable(() -> + versionService.publishScriptPatchVersion( + tenantId, baseVersionId, patch, "changed notes", requestId)); assertThat(replay).isInstanceOf(ScriptPatchPublishFailureException.class); assertThat(((ScriptPatchPublishFailureException) replay).failureCode()) .isEqualTo("SCRIPT_PATCH_MANIFEST_UNAVAILABLE"); @@ -673,10 +659,9 @@ void publicScriptPatchWithoutManifestRetainsCanonicalDraftAndReplaysTerminalFail assertThat(versionRepository.findAllByTenantIdOrderByVersionNumberAsc(tenantId)) .extracting(Version::getId) .containsExactly(baseVersionId, candidate.getId()); - assertThatThrownBy( - () -> - versionService.publishScriptPatchVersion( - tenantId, baseVersionId, patch, "fresh request", "another-request")) + assertThatThrownBy(() -> + versionService.publishScriptPatchVersion( + tenantId, baseVersionId, patch, "fresh request", "another-request")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("PUBLISH_SCRIPT_PATCH_IDENTITY_CONFLICT"); assertThat( @@ -708,15 +693,14 @@ void realPendingScriptPatchOriginalRequiresReconciliationWithoutMutationOrDispat "pending-original-request"); Version candidate = createLocalScriptPatchDraft(tenantId, baseVersionId, binding.scriptPatchVersion()); - publishAttemptService.executeScriptPatchTransaction( - () -> { - publishAttemptService.createScriptPatchAttempt( - versionMapper.toDto(candidate), - binding.derivedWorkflowIdentity(), - baseVersionId, - binding.requestDigest()); - return null; - }); + publishAttemptService.executeScriptPatchTransaction(() -> { + publishAttemptService.createScriptPatchAttempt( + versionMapper.toDto(candidate), + binding.derivedWorkflowIdentity(), + baseVersionId, + binding.requestDigest()); + return null; + }); PublishAttempt original = publishAttemptRepository .findByPublishWorkflowId(binding.derivedWorkflowIdentity()) @@ -731,14 +715,13 @@ void realPendingScriptPatchOriginalRequiresReconciliationWithoutMutationOrDispat for (int retry = 0; retry < 2; retry++) { Throwable failure = - catchThrowable( - () -> - versionService.publishScriptPatchVersion( - tenantId, - baseVersionId, - binding.scriptPatchVersion(), - "changed notes", - binding.publishRequestId())); + catchThrowable(() -> + versionService.publishScriptPatchVersion( + tenantId, + baseVersionId, + binding.scriptPatchVersion(), + "changed notes", + binding.publishRequestId())); assertThat(failure).isInstanceOf(ScriptPatchPublishFailureException.class); assertThat(((ScriptPatchPublishFailureException) failure).failureCode()) .isEqualTo(PublishAttemptPendingReconciliationException.ERROR_CODE); @@ -783,15 +766,14 @@ void scriptPatchOwnerTransactionRollsBackDraftEditAndAttemptFailureTogether() { "owner-rollback-request"); Version candidate = createLocalScriptPatchDraft(tenantId, baseVersionId, binding.scriptPatchVersion()); - publishAttemptService.executeScriptPatchTransaction( - () -> { - publishAttemptService.createScriptPatchAttempt( - versionMapper.toDto(candidate), - binding.derivedWorkflowIdentity(), - baseVersionId, - binding.requestDigest()); - return null; - }); + publishAttemptService.executeScriptPatchTransaction(() -> { + publishAttemptService.createScriptPatchAttempt( + versionMapper.toDto(candidate), + binding.derivedWorkflowIdentity(), + baseVersionId, + binding.requestDigest()); + return null; + }); PublishAttempt original = publishAttemptRepository .findByPublishWorkflowId(binding.derivedWorkflowIdentity()) @@ -804,26 +786,21 @@ void scriptPatchOwnerTransactionRollsBackDraftEditAndAttemptFailureTogether() { dsl.fetchSingle("SELECT *, xmin::text AS xmin FROM version WHERE id = ?", candidate.getId()) .intoMap(); - assertThatThrownBy( - () -> - publishAttemptService.executeScriptPatchTransaction( - () -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()) - .isTrue(); - assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) - .isFalse(); - Version locked = - versionRepository - .findByTenantIdAndIdForUpdate(tenantId, candidate.getId()) - .orElseThrow(); - locked.setNotes("rolled back owner edit"); - versionRepository.save(locked); - publishAttemptService.markScriptPatchFailed( - binding.derivedWorkflowIdentity(), - "OWNER_ROLLBACK_PROBE", - "rolled back failure"); - throw new IllegalStateException("forced script owner transaction failure"); - })) + assertThatThrownBy(() -> + publishAttemptService.executeScriptPatchTransaction(() -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + Version locked = + versionRepository + .findByTenantIdAndIdForUpdate(tenantId, candidate.getId()) + .orElseThrow(); + locked.setNotes("rolled back owner edit"); + versionRepository.save(locked); + publishAttemptService.markScriptPatchFailed( + binding.derivedWorkflowIdentity(), "OWNER_ROLLBACK_PROBE", "rolled back failure"); + throw new IllegalStateException("forced script owner transaction failure"); + })) .isInstanceOf(PublishAttemptService.ScriptPatchTransactionException.class) .hasCauseInstanceOf(IllegalStateException.class); assertThat( @@ -867,25 +844,23 @@ void selectedMechanicsRetainsCandidatePendingCompletePublicationReadback() { Mockito.when( publishGateService.collectSelectedFullVersionParticipantDigests( Mockito.any(VersionDto.class), - Mockito.argThat( - binding -> - binding != null - && binding - .canonicalPreimageHex() - .equals(expectedBinding.canonicalPreimageHex()) - && binding.requestDigest().equals(expectedBinding.requestDigest()) - && binding - .derivedWorkflowIdentity() - .equals(expectedBinding.derivedWorkflowIdentity())), + Mockito.argThat(binding -> + binding != null + && binding + .canonicalPreimageHex() + .equals(expectedBinding.canonicalPreimageHex()) + && binding.requestDigest().equals(expectedBinding.requestDigest()) + && binding + .derivedWorkflowIdentity() + .equals(expectedBinding.derivedWorkflowIdentity())), Mockito.eq(publishWorkflowId))) - .thenAnswer( - invocation -> { - VersionDto selectedVersion = invocation.getArgument(0); - return PublishedWorldSelectorFixtures.participants( - selectedVersion.id(), - fixture.operation().world(), - AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); - }); + .thenAnswer(invocation -> { + VersionDto selectedVersion = invocation.getArgument(0); + return PublishedWorldSelectorFixtures.participants( + selectedVersion.id(), + fixture.operation().world(), + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); + }); Mockito.doAnswer( invocation -> { try { @@ -1012,27 +987,25 @@ void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidate Mockito.when( publishGateService.collectSelectedFullVersionParticipantDigests( Mockito.any(VersionDto.class), - Mockito.argThat( - binding -> - binding != null - && binding - .canonicalPreimageHex() - .equals(expectedBinding.canonicalPreimageHex()) - && binding.requestDigest().equals(expectedBinding.requestDigest()) - && binding - .derivedWorkflowIdentity() - .equals(expectedBinding.derivedWorkflowIdentity())), + Mockito.argThat(binding -> + binding != null + && binding + .canonicalPreimageHex() + .equals(expectedBinding.canonicalPreimageHex()) + && binding.requestDigest().equals(expectedBinding.requestDigest()) + && binding + .derivedWorkflowIdentity() + .equals(expectedBinding.derivedWorkflowIdentity())), Mockito.eq(publishWorkflowId))) - .thenAnswer( - invocation -> { - VersionDto candidate = invocation.getArgument(0); - candidateVersionId.set(candidate.id()); - candidateVersionNumber.set(candidate.versionNumber()); - return PublishedWorldSelectorFixtures.participants( - candidate.id(), - fixture.operation().world(), - AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); - }); + .thenAnswer(invocation -> { + VersionDto candidate = invocation.getArgument(0); + candidateVersionId.set(candidate.id()); + candidateVersionNumber.set(candidate.versionNumber()); + return PublishedWorldSelectorFixtures.participants( + candidate.id(), + fixture.operation().world(), + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); + }); Mockito.doAnswer( invocation -> { try { @@ -1048,29 +1021,27 @@ void fullVersionMechanicsLeavesPostExportFinalizationFailurePendingWithCandidate Mockito.eq(tenantId), Mockito.eq(PublishType.FULL_VERSION), Mockito.anyList()); ExportedAssetManifest exportedManifest = exportedManifest(); Mockito.when(assetExportService.exportAssets(Mockito.eq(tenantId), Mockito.anyInt())) - .thenAnswer( - invocation -> { - exportedVersionNumber.set(invocation.getArgument(1)); - try { - VersionTemplateRemapSet approvedRemapSet = new VersionTemplateRemapSet(); - approvedRemapSet.setRemapSetId(approvedRemapSetId); - approvedRemapSet.setTenantId(tenantId); - approvedRemapSet.setSourceVersionId(sourceVersionId); - approvedRemapSet.setTargetVersionId(candidateVersionId.get()); - approvedRemapSet.setStatus(TemplateRemapSetStatus.APPROVED); - approvedRemapSet.setCreatedReason( - "approved remap references publication candidate"); - approvedRemapSet.setApprovalReason("approved for replacement launch"); - approvedRemapSet.setApprovedAt(LocalDateTime.now()); - templateRemapSetRepository.save(approvedRemapSet); - remapSetId.set(approvedRemapSet.getRemapSetId()); - exportCompleted.set(true); - return recordFixtureCandidate(fixture, exportedManifest); - } catch (Throwable failure) { - exportCallbackFailure.set(failure); - throw failure; - } - }); + .thenAnswer(invocation -> { + exportedVersionNumber.set(invocation.getArgument(1)); + try { + VersionTemplateRemapSet approvedRemapSet = new VersionTemplateRemapSet(); + approvedRemapSet.setRemapSetId(approvedRemapSetId); + approvedRemapSet.setTenantId(tenantId); + approvedRemapSet.setSourceVersionId(sourceVersionId); + approvedRemapSet.setTargetVersionId(candidateVersionId.get()); + approvedRemapSet.setStatus(TemplateRemapSetStatus.APPROVED); + approvedRemapSet.setCreatedReason("approved remap references publication candidate"); + approvedRemapSet.setApprovalReason("approved for replacement launch"); + approvedRemapSet.setApprovedAt(LocalDateTime.now()); + templateRemapSetRepository.save(approvedRemapSet); + remapSetId.set(approvedRemapSet.getRemapSetId()); + exportCompleted.set(true); + return recordFixtureCandidate(fixture, exportedManifest); + } catch (Throwable failure) { + exportCallbackFailure.set(failure); + throw failure; + } + }); Mockito.doAnswer( invocation -> { finalizationFailureInjected.set(true); @@ -1202,25 +1173,23 @@ void privateMechanicsCommitsGdsOwnerButRemainsPendingWithoutWorldProducer() { Mockito.when( publishGateService.collectSelectedFullVersionParticipantDigests( Mockito.any(VersionDto.class), - Mockito.argThat( - binding -> - binding != null - && binding - .canonicalPreimageHex() - .equals(expectedBinding.canonicalPreimageHex()) - && binding.requestDigest().equals(expectedBinding.requestDigest()) - && binding - .derivedWorkflowIdentity() - .equals(expectedBinding.derivedWorkflowIdentity())), + Mockito.argThat(binding -> + binding != null + && binding + .canonicalPreimageHex() + .equals(expectedBinding.canonicalPreimageHex()) + && binding.requestDigest().equals(expectedBinding.requestDigest()) + && binding + .derivedWorkflowIdentity() + .equals(expectedBinding.derivedWorkflowIdentity())), Mockito.eq(publishWorkflowId))) - .thenAnswer( - invocation -> { - VersionDto version = invocation.getArgument(0); - return PublishedWorldSelectorFixtures.participants( - version.id(), - fixture.operation().world(), - AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); - }); + .thenAnswer(invocation -> { + VersionDto version = invocation.getArgument(0); + return PublishedWorldSelectorFixtures.participants( + version.id(), + fixture.operation().world(), + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); + }); Mockito.when(assetExportService.exportAssets(tenantId, fixture.version().getVersionNumber())) .thenAnswer(invocation -> recordFixtureCandidate(fixture)); @@ -1265,10 +1234,9 @@ void publicFreshAndPendingFullVersionPublicationAreDeniedBeforeMutation() { freshGame.setName("fresh-public-denial-game"); gameRepository.save(freshGame); - assertThatThrownBy( - () -> - versionPublishCommandService.publishFullVersion( - freshTenantId, "fresh public denial", freshRequestId, freshWorkflowId)) + assertThatThrownBy(() -> + versionPublishCommandService.publishFullVersion( + freshTenantId, "fresh public denial", freshRequestId, freshWorkflowId)) .isInstanceOf(MutationOwnerProofUnavailableException.class) .hasMessage( "FULL_VERSION_PUBLICATION_UNAVAILABLE: fresh and pending full-version publication require a production Draft association"); @@ -1303,10 +1271,9 @@ void publicFreshAndPendingFullVersionPublicationAreDeniedBeforeMutation() { pendingAttempt.setVersionNumber(savedDraft.getVersionNumber()); publishAttemptRepository.save(pendingAttempt); - assertThatThrownBy( - () -> - versionPublishCommandService.publishFullVersion( - pendingTenantId, "pending public denial", pendingRequestId, pendingWorkflowId)) + assertThatThrownBy(() -> + versionPublishCommandService.publishFullVersion( + pendingTenantId, "pending public denial", pendingRequestId, pendingWorkflowId)) .isInstanceOf(MutationOwnerProofUnavailableException.class) .hasMessage( "FULL_VERSION_PUBLICATION_UNAVAILABLE: fresh and pending full-version publication require a production Draft association"); @@ -1336,60 +1303,59 @@ private SelectedPublicationFixture selectedFullPublicationFixture( String tenantId, String gameName, boolean includePublishedSource) { TransactionTemplate sourceTransaction = new TransactionTemplate(transactionManager); sourceTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - return sourceTransaction.execute( - status -> { - Game game = new Game(); - game.setTenantId(tenantId); - game.setName(gameName); - gameRepository.save(game); - - if (includePublishedSource) { - Version source = new Version(); - source.setTenantId(tenantId); - source.setVersionNumber(1); - source.setVersionState(VersionLifecycleState.PUBLISHED); - source.setVersionStateEpoch(2L); - source.setNotes("ISOLATED remap source"); - versionRepository.save(source); - } + return sourceTransaction.execute(status -> { + Game game = new Game(); + game.setTenantId(tenantId); + game.setName(gameName); + gameRepository.save(game); + + if (includePublishedSource) { + Version source = new Version(); + source.setTenantId(tenantId); + source.setVersionNumber(1); + source.setVersionState(VersionLifecycleState.PUBLISHED); + source.setVersionStateEpoch(2L); + source.setNotes("ISOLATED remap source"); + versionRepository.save(source); + } - Version draft = new Version(); - draft.setTenantId(tenantId); - draft.setVersionNumber(includePublishedSource ? 2 : 1); - draft.setVersionState(VersionLifecycleState.DRAFT); - draft.setVersionStateEpoch(1L); - draft.setNotes("ISOLATED selected publication"); - Version persisted = versionRepository.save(draft); - TargetProof target = - new TargetProof( - persisted.getCanonicalTenantId(), - persisted.getCanonicalVersionId(), - persisted.getId(), - persisted.getTenantId(), - persisted.getIdentitySourceGameRowId(), - persisted.getIdentitySourceGameTenantKey(), - persisted.getIdentitySourceProvenanceKind()); - GameAsset asset = new GameAsset(); - asset.setTenantId(tenantId); - asset.setFileName("fixture.bin"); - asset.setContentType("application/octet-stream"); - asset.setData(FIXTURE_ASSET_BYTES); - GameAsset persistedAsset = gameAssetRepository.save(asset); - try { - GameDesignPublicationOperation operation = - IsolatedPublicationOwnerSetup.retainFrozenSourceBackedSelectedFull( - dsl, - target, - persisted.getVersionStateEpoch(), - "ISOLATED publication proof", - List.of( - new IsolatedPublicationOwnerSetup.OrdinaryAsset( - persistedAsset.getId(), "fixture.bin"))); - return new SelectedPublicationFixture(persisted, operation); - } catch (Exception failure) { - throw new IllegalStateException("Selected publication fixture setup failed", failure); - } - }); + Version draft = new Version(); + draft.setTenantId(tenantId); + draft.setVersionNumber(includePublishedSource ? 2 : 1); + draft.setVersionState(VersionLifecycleState.DRAFT); + draft.setVersionStateEpoch(1L); + draft.setNotes("ISOLATED selected publication"); + Version persisted = versionRepository.save(draft); + TargetProof target = + new TargetProof( + persisted.getCanonicalTenantId(), + persisted.getCanonicalVersionId(), + persisted.getId(), + persisted.getTenantId(), + persisted.getIdentitySourceGameRowId(), + persisted.getIdentitySourceGameTenantKey(), + persisted.getIdentitySourceProvenanceKind()); + GameAsset asset = new GameAsset(); + asset.setTenantId(tenantId); + asset.setFileName("fixture.bin"); + asset.setContentType("application/octet-stream"); + asset.setData(FIXTURE_ASSET_BYTES); + GameAsset persistedAsset = gameAssetRepository.save(asset); + try { + GameDesignPublicationOperation operation = + IsolatedPublicationOwnerSetup.retainFrozenSourceBackedSelectedFull( + dsl, + target, + persisted.getVersionStateEpoch(), + "ISOLATED publication proof", + List.of( + new IsolatedPublicationOwnerSetup.OrdinaryAsset( + persistedAsset.getId(), "fixture.bin"))); + return new SelectedPublicationFixture(persisted, operation); + } catch (Exception failure) { + throw new IllegalStateException("Selected publication fixture setup failed", failure); + } + }); } private Object reconcileSelectedPublicationMechanics(SelectedPublicationFixture fixture) { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java index a1ea37a2a8..6e6b001bdf 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java @@ -143,25 +143,21 @@ void reconnectionScopeLockIsHeldUntilOwningTransactionCompletes() throws Excepti CountDownLatch releaseFirstTransaction = new CountDownLatch(1); try (ExecutorService executor = Executors.newFixedThreadPool(2)) { Future firstTransaction = - executor.submit( - () -> - transactionTemplate.executeWithoutResult( - status -> { - repository.findReconnectionRowsByTenantIdForUpdate("lock-tenant"); - firstLockAcquired.countDown(); - awaitLatch(releaseFirstTransaction); - })); + executor.submit(() -> + transactionTemplate.executeWithoutResult(status -> { + repository.findReconnectionRowsByTenantIdForUpdate("lock-tenant"); + firstLockAcquired.countDown(); + awaitLatch(releaseFirstTransaction); + })); assertThat(firstLockAcquired.await(5, TimeUnit.SECONDS)).isTrue(); Future secondTransaction = - executor.submit( - () -> - transactionTemplate.executeWithoutResult( - status -> { - secondTransactionStarted.countDown(); - repository.findReconnectionRowsByTenantIdForUpdate("lock-tenant"); - secondLockAcquired.countDown(); - })); + executor.submit(() -> + transactionTemplate.executeWithoutResult(status -> { + secondTransactionStarted.countDown(); + repository.findReconnectionRowsByTenantIdForUpdate("lock-tenant"); + secondLockAcquired.countDown(); + })); assertThat(secondTransactionStarted.await(5, TimeUnit.SECONDS)).isTrue(); assertThat(secondLockAcquired.await(250, TimeUnit.MILLISECONDS)).isFalse(); diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java index 4f54642590..d75ef38fd6 100644 --- a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java @@ -57,20 +57,17 @@ void storedSnapshotCannotChangeBoundRequirednessIdentityOrCanonicalRepresentatio assertThatThrownBy(() -> AssetSnapshot.fromStored(invalid)) .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( - reference, "", CommandSource.sha256(new byte[0]), 0)) + assertThatThrownBy(() -> + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "", CommandSource.sha256(new byte[0]), 0)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( - reference, "image/png", "sha256:00", 0)) + assertThatThrownBy(() -> + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "image/png", "sha256:00", 0)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( - reference, "image/png", CommandSource.sha256(new byte[0]), -1)) + assertThatThrownBy(() -> + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "image/png", CommandSource.sha256(new byte[0]), -1)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceTest.java index ef7ac23699..b231ead355 100644 --- a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceTest.java +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/BrandingSourceTest.java @@ -29,10 +29,9 @@ void everyRoleRetainsItsExactBindingAndRequiredPolicy() { assertThat(reference.role()).isEqualTo(role); assertThat(reference.family()).isEqualTo("BRANDING"); assertThat(reference.sourceBinding()).isSameAs(binding); - assertThatThrownBy( - () -> - BrandingSource.upsertPayload( - "1", "image.png", role, BrandingSource.Requiredness.OPTIONAL)) + assertThatThrownBy(() -> + BrandingSource.upsertPayload( + "1", "image.png", role, BrandingSource.Requiredness.OPTIONAL)) .isInstanceOf(IllegalArgumentException.class); } } @@ -52,10 +51,9 @@ void replayPreservesUntouchedOriginalRevisionAndExplicitRoleDeclarations() { assertThat(replay.references().getFirst().sourceBinding()).isEqualTo(original); var items = replay.references().stream() - .map( - r -> - new net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot.Item( - r, "image/png", "sha256:" + "a".repeat(64), 1)) + .map(r -> + new net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot.Item( + r, "image/png", "sha256:" + "a".repeat(64), 1)) .toList(); var snapshot = new BrandingSourceSnapshot(changed, "2", original.commitId(), UUID.randomUUID(), items); @@ -63,12 +61,11 @@ void replayPreservesUntouchedOriginalRevisionAndExplicitRoleDeclarations() { .isEqualTo( Map.of("RESOURCE", "EMPTY", "LOGO", "PRESENT", "FAVICON", "EMPTY", "THEME", "PRESENT")); assertThat(BrandingSourceSnapshot.fromStored(snapshot.canonicalJson())).isEqualTo(snapshot); - assertThatThrownBy( - () -> - BrandingSourceSnapshot.fromStored( - snapshot - .canonicalJson() - .replace("\"FAVICON\":\"EMPTY\"", "\"FAVICON\":\"PRESENT\""))) + assertThatThrownBy(() -> + BrandingSourceSnapshot.fromStored( + snapshot + .canonicalJson() + .replace("\"FAVICON\":\"EMPTY\"", "\"FAVICON\":\"PRESENT\""))) .isInstanceOf(IllegalArgumentException.class); } @@ -88,21 +85,17 @@ void unknownMalformedOptionalAndOrdinaryReinterpretationDeny() { assertThatThrownBy(() -> BrandingSource.mutations(binding(invalid))) .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - BrandingSource.replay( - List.of(), - binding( - BrandingSource.upsertPayload( - "1", - "a", - BrandingSource.Role.LOGO, - BrandingSource.Requiredness.REQUIRED), - BrandingSource.upsertPayload( - "1", - "b", - BrandingSource.Role.THEME, - BrandingSource.Requiredness.REQUIRED)))) + assertThatThrownBy(() -> + BrandingSource.replay( + List.of(), + binding( + BrandingSource.upsertPayload( + "1", "a", BrandingSource.Role.LOGO, BrandingSource.Requiredness.REQUIRED), + BrandingSource.upsertPayload( + "1", + "b", + BrandingSource.Role.THEME, + BrandingSource.Requiredness.REQUIRED)))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java index 0080bc3335..d65be8de07 100644 --- a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/TemplateConfigSourceTest.java @@ -74,16 +74,12 @@ void canonicalOwnerUuidSyntaxCannotQualifyWorldEntityOrAutomationReferences() { .hasMessage("TEMPLATE_CONFIG_AUTOMATION_EXACT_OWNER_READ_UNAVAILABLE"); assertThatThrownBy(patch::requireAvailableOwnerReads) .hasMessage("TEMPLATE_CONFIG_AUTOMATION_EXACT_OWNER_READ_UNAVAILABLE"); - assertThatThrownBy( - () -> - new TemplateConfigSource.Config( - config().replace("\"items\":[]", "\"equipment\":[]"))) + assertThatThrownBy(() -> + new TemplateConfigSource.Config(config().replace("\"items\":[]", "\"equipment\":[]"))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new TemplateConfigSource.Config( - config() - .replace("\"regions\":[]", "\"regions\":[{\"regionTemplateId\":\"7\"}]"))) + assertThatThrownBy(() -> + new TemplateConfigSource.Config( + config().replace("\"regions\":[]", "\"regions\":[{\"regionTemplateId\":\"7\"}]"))) .isInstanceOf(IllegalArgumentException.class); } @@ -106,19 +102,17 @@ void actualGeneratedRowAndOriginalRevisionRemainSeparateFromAuthoredPreimage() { sibling, "1", create.commitId(), UUID.randomUUID(), inherited); assertThat(TemplateConfigSourceSnapshot.fromStored(snapshot.canonicalJson())) .isEqualTo(snapshot); - assertThatThrownBy( - () -> - TemplateConfigSource.replay( - List.of(), binding(TemplateConfigSource.deletePayload("7")), Map.of())) + assertThatThrownBy(() -> + TemplateConfigSource.replay( + List.of(), binding(TemplateConfigSource.deletePayload("7")), Map.of())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - TemplateConfigSource.replay( - List.of(), - binding( - TemplateConfigSource.upsertPayload( - "7", new TemplateConfigSource.Config(config()))), - Map.of())) + assertThatThrownBy(() -> + TemplateConfigSource.replay( + List.of(), + binding( + TemplateConfigSource.upsertPayload( + "7", new TemplateConfigSource.Config(config()))), + Map.of())) .isInstanceOf(IllegalArgumentException.class); } @@ -136,12 +130,11 @@ void siblingDispatchDoesNotInventUnknownSourceKindsOrChangeOriginalBinding() { assertThat(GameplayRuleSource.mutations(binding)).isEmpty(); assertThat(CommandSource.hasRealmPolicyRevision(binding)).isFalse(); String wrongBase = config().replace(VERSION.toString(), UUID.randomUUID().toString()); - assertThatThrownBy( - () -> - TemplateConfigSource.mutations( - binding( - TemplateConfigSource.createPayload( - "Starter", new TemplateConfigSource.Config(wrongBase))))) + assertThatThrownBy(() -> + TemplateConfigSource.mutations( + binding( + TemplateConfigSource.createPayload( + "Starter", new TemplateConfigSource.Config(wrongBase))))) .isInstanceOf(IllegalArgumentException.class); } @@ -233,16 +226,14 @@ void ownerInventoryOperationRejectsMissingUnknownAndUnsupportedContent() { "AUTOMATION_SCRIPTING")); assertThatThrownBy(() -> TemplateConfigSource.mutations(binding(missingInventory))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - TemplateConfigSource.mutations( - binding(valid.replace("AUTOMATION_SCRIPTING", "ENTITY_MANAGEMENT")))) + assertThatThrownBy(() -> + TemplateConfigSource.mutations( + binding(valid.replace("AUTOMATION_SCRIPTING", "ENTITY_MANAGEMENT")))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - AutomationAuthoredSourceInventoryDeclaration.parse( - automationInventory() - .replace("\"SCRIPT_DEFINITIONS\":[]", "\"SCRIPT_DEFINITIONS\":[{}]"))) + assertThatThrownBy(() -> + AutomationAuthoredSourceInventoryDeclaration.parse( + automationInventory() + .replace("\"SCRIPT_DEFINITIONS\":[]", "\"SCRIPT_DEFINITIONS\":[{}]"))) .isInstanceOf(IllegalArgumentException.class); assertThat( TemplateConfigSourceSnapshot.fromStored( @@ -294,16 +285,14 @@ void entityInventoryUsesClosedTypedOperationAndRejectsOwnerContentSubstitution() "ENTITY_MANAGEMENT")); assertThatThrownBy(() -> TemplateConfigSource.mutations(binding(missingEntityInventory))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - EntityAuthoredSourceInventoryDeclaration.parse( - entityInventory() - .replace("\"ITEM_TEMPLATE_ROOTS\":[]", "\"ITEM_TEMPLATE_ROOTS\":[{}]"))) + assertThatThrownBy(() -> + EntityAuthoredSourceInventoryDeclaration.parse( + entityInventory() + .replace("\"ITEM_TEMPLATE_ROOTS\":[]", "\"ITEM_TEMPLATE_ROOTS\":[{}]"))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - EntityAuthoredSourceInventoryDeclaration.parse( - entityInventory().replace("\"families\":{", "\"families\":{\"UNKNOWN\":[],"))) + assertThatThrownBy(() -> + EntityAuthoredSourceInventoryDeclaration.parse( + entityInventory().replace("\"families\":{", "\"families\":{\"UNKNOWN\":[],"))) .isInstanceOf(IllegalArgumentException.class); var declarations = TemplateConfigSource.replayOwnerInventoryDeclarations(List.of(), authored); diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java index 24c249c744..09c2679869 100644 --- a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java @@ -134,42 +134,39 @@ void setup() { .when( publicationService.readFrozenAssetBytes( any(String.class), anyInt(), any(AssetSelection.class))) - .thenAnswer( - invocation -> { - AssetSelection selection = invocation.getArgument(2); - byte[] bytes = frozenAssetBytes.get(selection.assetId()); - if (bytes == null) { - throw new IllegalStateException("frozen asset bytes are unavailable"); - } - return bytes.clone(); - }); + .thenAnswer(invocation -> { + AssetSelection selection = invocation.getArgument(2); + byte[] bytes = frozenAssetBytes.get(selection.assetId()); + if (bytes == null) { + throw new IllegalStateException("frozen asset bytes are unavailable"); + } + return bytes.clone(); + }); lenient() .when( candidateService.recordExportCandidate( any(String.class), anyInt(), any(FrozenAssetExportCandidate.class))) - .thenAnswer( - invocation -> { - FrozenAssetExportCandidate requested = invocation.getArgument(2); - FrozenAssetExportCandidate existing = storedCandidate.get(); - if (existing == null) { - storedCandidate.set(requested); - existing = requested; - } - if (!existing.equals(requested)) { - throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_CONFLICT"); - } - return existing; - }); + .thenAnswer(invocation -> { + FrozenAssetExportCandidate requested = invocation.getArgument(2); + FrozenAssetExportCandidate existing = storedCandidate.get(); + if (existing == null) { + storedCandidate.set(requested); + existing = requested; + } + if (!existing.equals(requested)) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_CONFLICT"); + } + return existing; + }); lenient() .when(candidateService.readExportCandidate(any(String.class), anyInt())) - .thenAnswer( - ignored -> { - FrozenAssetExportCandidate existing = storedCandidate.get(); - if (existing == null) { - throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_NOT_FOUND"); - } - return existing; - }); + .thenAnswer(ignored -> { + FrozenAssetExportCandidate existing = storedCandidate.get(); + if (existing == null) { + throw new IllegalStateException("ASSET_EXPORT_CANDIDATE_NOT_FOUND"); + } + return existing; + }); lenient() .when(s3Client.putObject(any(PutObjectRequest.class), any(RequestBody.class))) .thenAnswer(this::putObject); @@ -195,10 +192,8 @@ void readsAndMatchesDurableSnapshotBeforeConditionalObjectWrites() { order .verify(s3Client) .putObject( - argThat( - (PutObjectRequest request) -> - "*".equals(request.ifNoneMatch()) - && request.key().startsWith("artifacts/sha256/")), + argThat((PutObjectRequest request) -> + "*".equals(request.ifNoneMatch()) && request.key().startsWith("artifacts/sha256/")), any(RequestBody.class)); } @@ -316,15 +311,14 @@ void exportsCanonicalActualByteDigestsAndManifestWithoutPrivateStorageLocation() assertEquals(-1, manifestJson.indexOf("bucket")); verify(s3Client) .putObject( - argThat( - (PutObjectRequest request) -> - request - .key() - .equals( - "manifests/sha256/" - + exported.manifestHash().substring("sha256:".length())) - && "application/json".equals(request.contentType()) - && "*".equals(request.ifNoneMatch())), + argThat((PutObjectRequest request) -> + request + .key() + .equals( + "manifests/sha256/" + + exported.manifestHash().substring("sha256:".length())) + && "application/json".equals(request.contentType()) + && "*".equals(request.ifNoneMatch())), any(RequestBody.class)); } @@ -956,14 +950,13 @@ private ExportSnapshot copySnapshot(ExportSnapshot source) { source.canonicalTenantId(), source.canonicalVersionId(), source.items().stream() - .map( - item -> - new AssetSelection( - item.usageKey(), - item.assetId(), - item.byteSize(), - item.contentType(), - item.contentDigest())) + .map(item -> + new AssetSelection( + item.usageKey(), + item.assetId(), + item.byteSize(), + item.contentType(), + item.contentDigest())) .toList()); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/GameDesignTemporalHostingTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/GameDesignTemporalHostingTest.java index 6128cf9779..cebc67bb1f 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/GameDesignTemporalHostingTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/GameDesignTemporalHostingTest.java @@ -34,22 +34,20 @@ class GameDesignTemporalHostingTest { @Test void gameDesignModuleUsesSharedTemporalHostingPattern() { - contextRunner.run( - context -> { - TemporalTaskQueueResolver taskQueues = context.getBean(TemporalTaskQueueResolver.class); - WorkerFactory workerFactory = context.getBean(WorkerFactory.class); - Worker worker = context.getBean(Worker.class); - String taskQueue = taskQueues.forWorkflowFamily("publish"); + contextRunner.run(context -> { + TemporalTaskQueueResolver taskQueues = context.getBean(TemporalTaskQueueResolver.class); + WorkerFactory workerFactory = context.getBean(WorkerFactory.class); + Worker worker = context.getBean(Worker.class); + String taskQueue = taskQueues.forWorkflowFamily("publish"); - assertThat(taskQueue).isEqualTo("firemud:game-design-service:publish"); - assertThat( - FiremudWorkflowIds.workflowId("publish", "tenant-1", "publish-request", "req-1")) - .isEqualTo("publish:tenant-1:publish-request:req-1"); + assertThat(taskQueue).isEqualTo("firemud:game-design-service:publish"); + assertThat(FiremudWorkflowIds.workflowId("publish", "tenant-1", "publish-request", "req-1")) + .isEqualTo("publish:tenant-1:publish-request:req-1"); - verify(workerFactory).newWorker(taskQueue); - verify(worker).registerWorkflowImplementationTypes(HostProbeWorkflowImpl.class); - verify(workerFactory).start(); - }); + verify(workerFactory).newWorker(taskQueue); + verify(worker).registerWorkflowImplementationTypes(HostProbeWorkflowImpl.class); + verify(workerFactory).start(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/AccountTenantCreationCurrentAuthorizationClientTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/AccountTenantCreationCurrentAuthorizationClientTest.java index eb144a9862..564884682f 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/AccountTenantCreationCurrentAuthorizationClientTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/AccountTenantCreationCurrentAuthorizationClientTest.java @@ -56,21 +56,18 @@ void requiresFileBackedWorkloadMtlsAndCanonicalNamespace() { var plaintext = new CommonGrpcClientProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new AccountTenantCreationCurrentAuthorizationClient( - endpoints, plaintext, new GrpcChannelFactory(), "test")) + assertThatThrownBy(() -> + new AccountTenantCreationCurrentAuthorizationClient( + endpoints, plaintext, new GrpcChannelFactory(), "test")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("workload mTLS"); - assertThatThrownBy( - () -> - new AccountTenantCreationCurrentAuthorizationClient( - endpoints, new CommonGrpcClientProperties(), new GrpcChannelFactory(), "test")) + assertThatThrownBy(() -> + new AccountTenantCreationCurrentAuthorizationClient( + endpoints, new CommonGrpcClientProperties(), new GrpcChannelFactory(), "test")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new AccountTenantCreationCurrentAuthorizationClient( - endpoints, tlsFiles(), new GrpcChannelFactory(), "not/a/namespace")) + assertThatThrownBy(() -> + new AccountTenantCreationCurrentAuthorizationClient( + endpoints, tlsFiles(), new GrpcChannelFactory(), "not/a/namespace")) .isInstanceOf(IllegalArgumentException.class); } @@ -195,12 +192,11 @@ public void resolveCurrentTenantCreationAuthorization( try (var incoming = Context.current().withDeadlineAfter(1, TimeUnit.SECONDS, scheduler)) { var incomingCancelled = new CountDownLatch(1); incoming.addListener(ignored -> incomingCancelled.countDown(), Runnable::run); - incoming.run( - () -> - assertThatThrownBy(() -> client.resolveCurrent(binding)) - .isInstanceOf(StatusRuntimeException.class) - .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + incoming.run(() -> + assertThatThrownBy(() -> client.resolveCurrent(binding)) + .isInstanceOf(StatusRuntimeException.class) + .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); assertThat(incomingCancelled.await(2, TimeUnit.SECONDS)).isTrue(); assertThat(incoming.isCancelled()).isTrue(); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/AutomationScriptingClientTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/AutomationScriptingClientTest.java index 29077384a7..9c1cde5aa6 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/AutomationScriptingClientTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/client/AutomationScriptingClientTest.java @@ -112,10 +112,9 @@ void notificationWithoutAcceptedReadinessFailsClosed() throws Exception { stub); client.initialize(); - assertThatThrownBy( - () -> - client.notifyScriptVersionUpdate( - "tenant-1", 7L, "patch-7", java.util.List.of("script-a"))) + assertThatThrownBy(() -> + client.notifyScriptVersionUpdate( + "tenant-1", 7L, "patch-7", java.util.List.of("script-a"))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("SCRIPT_PATCH_NOTIFICATION_REJECTED"); var requestCaptor = org.mockito.ArgumentCaptor.forClass(NotifyScriptVersionUpdateRequest.class); @@ -269,10 +268,9 @@ void scriptPatchNotificationRejectsMissingOrNonpositiveBaseBeforeCallingAutomati client.initialize(); for (Long baseVersionId : java.util.Arrays.asList(null, 0L, -1L)) { - assertThatThrownBy( - () -> - client.notifyScriptVersionUpdate( - "tenant-1", baseVersionId, "patch-7", java.util.List.of("script-a"))) + assertThatThrownBy(() -> + client.notifyScriptVersionUpdate( + "tenant-1", baseVersionId, "patch-7", java.util.List.of("script-a"))) .isInstanceOf(IllegalArgumentException.class); } assertThatThrownBy(() -> client.notifyScriptVersionUpdate("tenant-1", 7L, "patch-7", null)) diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java index 2486a381ff..6562c81d5a 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/config/RealmPolicyPublicationReadConfigurationTest.java @@ -30,13 +30,12 @@ class RealmPolicyPublicationReadConfigurationTest { @Test void ownerReadCompositionAndGrpcAdapterAreAbsentByDefault() { - contextRunner.run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(RealmPolicyPublicationRepository.class); - assertThat(context).doesNotHaveBean(RealmPolicyPublicationService.class); - assertThat(context).doesNotHaveBean(RealmPolicyPublicationGrpcService.class); - }); + contextRunner.run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(RealmPolicyPublicationRepository.class); + assertThat(context).doesNotHaveBean(RealmPolicyPublicationService.class); + assertThat(context).doesNotHaveBean(RealmPolicyPublicationGrpcService.class); + }); } @Test @@ -45,13 +44,12 @@ void explicitEnablementComposesActualOwnerBeansAndGrpcAdapter() { .withPropertyValues( "firemud.game-design.published-realm-entry-policy-read.enabled=true", "firemud.grpc.workload-namespace=firemud-test") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).hasSingleBean(RealmPolicyPublicationRepository.class); - assertThat(context).hasSingleBean(RealmPolicyPublicationService.class); - assertThat(context).hasSingleBean(RealmPolicyPublicationGrpcService.class); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(RealmPolicyPublicationRepository.class); + assertThat(context).hasSingleBean(RealmPolicyPublicationService.class); + assertThat(context).hasSingleBean(RealmPolicyPublicationGrpcService.class); + }); } @Test @@ -78,27 +76,23 @@ private static void assertConfiguredGrpcMethods(String fileName) throws IOExcept new YamlPropertySourceLoader() .load(fileName, new FileSystemResource("src/main/resources/" + fileName)); new ApplicationContextRunner() - .withInitializer( - context -> - propertySources.forEach(context.getEnvironment().getPropertySources()::addFirst)) - .run( - context -> - assertThat( - Binder.get(context.getEnvironment()) - .bind("firemud.auth.grpc.public-methods", Bindable.listOf(String.class)) - .orElse(List.of())) - .containsExactly( - "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation", - PublishedRealmEntryPolicyServiceGrpc - .getResolvePublishedRealmEntryPolicyMethod() - .getFullMethodName(), - PublishedRealmEntryPolicyServiceGrpc - .getListPublishedRealmEntryPoliciesMethod() - .getFullMethodName(), - "gamedesign.v1.GameDesignService/ResolveLaunchDescriptor", - "gamedesign.v1.GameDesignService/GetLaunchDescriptor", - "gamedesign.v1.GameDesignService/GetCompleteLaunchBinding", - "gamedesign.v1.AuthoredWorldSourceReadService/ResolveAuthoredWorldSource", - "gamedesign.v1.AuthoredWorldVersionStateService/GetAuthoredWorldVersionState")); + .withInitializer(context -> + propertySources.forEach(context.getEnvironment().getPropertySources()::addFirst)) + .run(context -> + assertThat( + Binder.get(context.getEnvironment()) + .bind("firemud.auth.grpc.public-methods", Bindable.listOf(String.class)) + .orElse(List.of())) + .containsExactly( + "gamedesign.v1.TenantIdentityService/ResolveFreshTenantCreation", + PublishedRealmEntryPolicyServiceGrpc.getResolvePublishedRealmEntryPolicyMethod() + .getFullMethodName(), + PublishedRealmEntryPolicyServiceGrpc.getListPublishedRealmEntryPoliciesMethod() + .getFullMethodName(), + "gamedesign.v1.GameDesignService/ResolveLaunchDescriptor", + "gamedesign.v1.GameDesignService/GetLaunchDescriptor", + "gamedesign.v1.GameDesignService/GetCompleteLaunchBinding", + "gamedesign.v1.AuthoredWorldSourceReadService/ResolveAuthoredWorldSource", + "gamedesign.v1.AuthoredWorldVersionStateService/GetAuthoredWorldVersionState")); } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorizationTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorizationTest.java index e1de4bc5c7..7479706a50 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorizationTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerReadAuthorizationTest.java @@ -28,10 +28,9 @@ class RunOwnedFixtureOwnerReadAuthorizationTest { void missingFixedConfigurationFailsClosedWithoutOwnerAccess() { var readback = mock(RunOwnedFixtureLaunchReadback.class); var policy = mock(RunOwnedFixturePolicyProducer.class); - assertThatThrownBy( - () -> - new RunOwnedFixtureOwnerReadAuthorization( - readback, policy, "dev", "", "", "", "", "", "", "")) + assertThatThrownBy(() -> + new RunOwnedFixtureOwnerReadAuthorization( + readback, policy, "dev", "", "", "", "", "", "", "")) .isInstanceOf(IllegalStateException.class); verifyNoInteractions(readback, policy); } @@ -44,17 +43,16 @@ void callerMissingPeerWrongNamespaceServiceAndLeafDenyBeforeMalformedSelector() when(trusted.worldManagementLeafSha256()).thenReturn("a".repeat(64)); try (var configuration = mockStatic(TestDataSeeder.class)) { configuration - .when( - () -> - TestDataSeeder.verifyFixtureConfiguration( - anyString(), - anyString(), - anyString(), - anyString(), - anyString(), - anyString(), - anyString(), - anyString())) + .when(() -> + TestDataSeeder.verifyFixtureConfiguration( + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString())) .thenReturn(trusted); var authorization = new RunOwnedFixtureOwnerReadAuthorization( @@ -136,29 +134,26 @@ void rawReceiptAndQualifiedLaunchStillRequirePreexistingPolicyWithoutSealing() t net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec .class)) { configuration - .when( - () -> - TestDataSeeder.verifyFixtureConfiguration( - anyString(), - anyString(), - anyString(), - anyString(), - anyString(), - anyString(), - anyString(), - anyString())) + .when(() -> + TestDataSeeder.verifyFixtureConfiguration( + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString(), + anyString())) .thenReturn(trusted); byte[] controlledReceipt = new byte[] {7}; files - .when( - () -> - net.firedevops.firemud.common.smoke.RunOwnedFixtureImmutableFileReader - .readBoundedImmutableFile(any(java.nio.file.Path.class), anyInt(), any())) + .when(() -> + net.firedevops.firemud.common.smoke.RunOwnedFixtureImmutableFileReader + .readBoundedImmutableFile(any(java.nio.file.Path.class), anyInt(), any())) .thenReturn(controlledReceipt); - wire.when( - () -> - net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec - .parseSourceReceipt(controlledReceipt, capability)) + wire.when(() -> + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .parseSourceReceipt(controlledReceipt, capability)) .thenReturn(receipt); var authorization = new RunOwnedFixtureOwnerReadAuthorization( @@ -182,11 +177,10 @@ void rawReceiptAndQualifiedLaunchStillRequirePreexistingPolicyWithoutSealing() t GrpcPeerIdentity.parseUri("spiffe://firemud/ns/dev/sa/world-management-service") .orElseThrow()) .withValue(GrpcPeerCertificateEvidence.CONTEXT_KEY, certificate) - .run( - () -> - assertThatThrownBy(() -> authorization.authorizeSource(request)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Preexisting")); + .run(() -> + assertThatThrownBy(() -> authorization.authorizeSource(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Preexisting")); verify(readback).readCommittedReceipt(receipt); verify(policy).readExisting(trusted, creation, committed.snapshot(), committed.descriptor()); verify(policy, never()).sealAndRead(any(), any(), any(), any()); @@ -194,15 +188,12 @@ void rawReceiptAndQualifiedLaunchStillRequirePreexistingPolicyWithoutSealing() t } private static void assertBothDeny(RunOwnedFixtureOwnerReadAuthorization authorization) { - assertThatThrownBy( - () -> - authorization.authorizeSource( - ResolveAuthoredWorldSourceRequest.getDefaultInstance())) + assertThatThrownBy(() -> + authorization.authorizeSource(ResolveAuthoredWorldSourceRequest.getDefaultInstance())) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - authorization.authorizeVersion( - GetAuthoredWorldVersionStateRequest.getDefaultInstance())) + assertThatThrownBy(() -> + authorization.authorizeVersion( + GetAuthoredWorldVersionStateRequest.getDefaultInstance())) .isInstanceOf(SecurityException.class); } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java index b2da73bad2..20b1ee7b54 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java @@ -150,12 +150,11 @@ void runSeedsAndReassertsCanonicalPublishedRuntimeData() throws Exception { when(publishedReleaseBundleRepository.findByTenantIdAndVersionId("1", 7L)) .thenReturn(java.util.Optional.empty()); when(publishedReleaseBundleRepository.save(any(PublishedReleaseBundle.class))) - .thenAnswer( - invocation -> { - PublishedReleaseBundle inserted = invocation.getArgument(0); - inserted.setPublishedAt(java.time.LocalDateTime.now()); - return inserted; - }); + .thenAnswer(invocation -> { + PublishedReleaseBundle inserted = invocation.getArgument(0); + inserted.setPublishedAt(java.time.LocalDateTime.now()); + return inserted; + }); when(versionAssetArtifactRepository.findByTenantIdAndVersionId("1", 7L)) .thenReturn(java.util.Optional.empty()); when(versionAssetArtifactRepository.save(any(VersionAssetArtifact.class))) @@ -441,17 +440,16 @@ void rejectsWrongWorldManagementLeafPinDespiteMatchingSessionPin() throws Except CertificateFixture worldManagement = certificateFixture("world-management", List.of(List.of(6, WORLD_MANAGEMENT_URI_SAN))); - assertThatThrownBy( - () -> - ReflectionTestUtils.invokeMethod( - seeder, - "requireCertificatePins", - gameSession.leaf(), - worldManagement.leaf(), - gameSession.ca(), - gameSession.leafDigest(), - "0".repeat(64), - gameSession.caDigest())) + assertThatThrownBy(() -> + ReflectionTestUtils.invokeMethod( + seeder, + "requireCertificatePins", + gameSession.leaf(), + worldManagement.leaf(), + gameSession.ca(), + gameSession.leafDigest(), + "0".repeat(64), + gameSession.caDigest())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("certificates do not match capability pins"); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java index 3663aada47..0649f8c0ce 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/AuthoredDraftPublishSelectionTest.java @@ -145,17 +145,16 @@ void rejectsInvalidSelectionEpochAndChangedIntent() { DraftCommitBinding binding = binding(target); PublishIntent original = intent(target, binding, "original notes"); - assertThatThrownBy( - () -> - new PublishIntent( - target.canonicalTenantId(), - target.canonicalVersionId(), - original.publishRequestId(), - "01", - original.notes(), - binding.requestId(), - binding.commitId(), - binding.digest())) + assertThatThrownBy(() -> + new PublishIntent( + target.canonicalTenantId(), + target.canonicalVersionId(), + original.publishRequestId(), + "01", + original.notes(), + binding.requestId(), + binding.commitId(), + binding.digest())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("positive canonical decimal"); assertThat(original).isNotEqualTo(intent(target, binding, "changed notes")); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidenceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidenceTest.java index 21ee6fc447..f5dcafd3d7 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidenceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseEvidenceTest.java @@ -44,10 +44,9 @@ void genesisBindsPolicyCommandAndDistinctAssetBaselineWithoutCommit() { .isNotEqualTo( GameDesignReviewedBaseEvidence.genesis( genesis(target, receipt, "11", UUID.randomUUID()))); - assertThatThrownBy( - () -> - GameDesignReviewedBaseEvidence.genesis( - new GameDesignSourceRepository.Genesis(genesis.policy(), genesis.command()))) + assertThatThrownBy(() -> + GameDesignReviewedBaseEvidence.genesis( + new GameDesignSourceRepository.Genesis(genesis.policy(), genesis.command()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("GAME_DESIGN_SOURCE_ASSET_GENESIS_UNAVAILABLE"); byte[] returned = evidence.canonicalBytes(); @@ -63,9 +62,8 @@ void readbackRejectsChangedDigestAndDefensivelyCopiesBytes() { bytes, DraftAuthorizationFenceBinding.digest(bytes)); bytes[bytes.length - 1] ^= 1; assertThat(retained.canonicalBytes()).isNotEqualTo(bytes); - assertThatThrownBy( - () -> - new GameDesignReviewedBaseRepository.ReviewedBaseReadback(bytes, retained.digest())) + assertThatThrownBy(() -> + new GameDesignReviewedBaseRepository.ReviewedBaseReadback(bytes, retained.digest())) .isInstanceOf(IllegalArgumentException.class); } @@ -78,10 +76,8 @@ void readbackRequiresSupportedSchemaToMatchTheFirstEvidenceFrame() { historical, historicalDigest, GameDesignReviewedBaseEvidence.HISTORICAL_SCHEMA); assertThat(retainedHistorical.schema()) .isEqualTo(GameDesignReviewedBaseEvidence.HISTORICAL_SCHEMA); - assertThatThrownBy( - () -> - new GameDesignReviewedBaseRepository.ReviewedBaseReadback( - historical, historicalDigest)) + assertThatThrownBy(() -> + new GameDesignReviewedBaseRepository.ReviewedBaseReadback(historical, historicalDigest)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("REVIEWED_BASE_STORED_SCHEMA_CONFLICT"); @@ -95,20 +91,18 @@ void readbackRequiresSupportedSchemaToMatchTheFirstEvidenceFrame() { current, currentDigest, GameDesignReviewedBaseEvidence.SCHEMA) .canonicalBytes()) .containsExactly(current); - assertThatThrownBy( - () -> - new GameDesignReviewedBaseRepository.ReviewedBaseReadback( - current, currentDigest, GameDesignReviewedBaseEvidence.HISTORICAL_SCHEMA)) + assertThatThrownBy(() -> + new GameDesignReviewedBaseRepository.ReviewedBaseReadback( + current, currentDigest, GameDesignReviewedBaseEvidence.HISTORICAL_SCHEMA)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("REVIEWED_BASE_STORED_SCHEMA_CONFLICT"); byte[] truncated = {0, 0, 0}; - assertThatThrownBy( - () -> - new GameDesignReviewedBaseRepository.ReviewedBaseReadback( - truncated, - DraftAuthorizationFenceBinding.digest(truncated), - GameDesignReviewedBaseEvidence.SCHEMA)) + assertThatThrownBy(() -> + new GameDesignReviewedBaseRepository.ReviewedBaseReadback( + truncated, + DraftAuthorizationFenceBinding.digest(truncated), + GameDesignReviewedBaseEvidence.SCHEMA)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Truncated immutable source frame"); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionLaunchDescriptorGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionLaunchDescriptorGrpcServiceTest.java index 2f514b0fe7..43527f42b5 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionLaunchDescriptorGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignStartSessionLaunchDescriptorGrpcServiceTest.java @@ -141,13 +141,12 @@ void typedStoredDenialUsesItsExactAssociationBindingAndMessage() { .when(() -> StartSessionLaunchDescriptorGrpcCodec.fromRequest(request)) .thenReturn(decoded); codec - .when( - () -> - StartSessionLaunchDescriptorGrpcCodec.toFailureResponse( - decoded, - association, - "INVALID_TEMPLATE_CONFIGURATION", - "INVALID_TEMPLATE_CONFIGURATION: captured source is unsupported")) + .when(() -> + StartSessionLaunchDescriptorGrpcCodec.toFailureResponse( + decoded, + association, + "INVALID_TEMPLATE_CONFIGURATION", + "INVALID_TEMPLATE_CONFIGURATION: captured source is unsupported")) .thenReturn(response); var observer = invokeAs(request, "game-session-service"); @@ -156,13 +155,12 @@ void typedStoredDenialUsesItsExactAssociationBindingAndMessage() { assertThat(observer.value).isEqualTo(response); assertThat(observer.completed).isTrue(); verify(producer).resolve(decoded); - codec.verify( - () -> - StartSessionLaunchDescriptorGrpcCodec.toFailureResponse( - decoded, - association, - "INVALID_TEMPLATE_CONFIGURATION", - "INVALID_TEMPLATE_CONFIGURATION: captured source is unsupported")); + codec.verify(() -> + StartSessionLaunchDescriptorGrpcCodec.toFailureResponse( + decoded, + association, + "INVALID_TEMPLATE_CONFIGURATION", + "INVALID_TEMPLATE_CONFIGURATION: captured source is unsupported")); } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignWorldSourceCommitServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignWorldSourceCommitServiceTest.java index 990b499e68..b500aa6988 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignWorldSourceCommitServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/draft/GameDesignWorldSourceCommitServiceTest.java @@ -166,11 +166,10 @@ void worldFailureKeepsLocalAppliedAndRetryDoesNotReapplyLocalSource() { var original = original(); var state = arrange(original, false); when(world.apply(any())) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - throw io.grpc.Status.UNAVAILABLE.asRuntimeException(); - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + throw io.grpc.Status.UNAVAILABLE.asRuntimeException(); + }); for (int retry = 0; retry < 2; retry++) { assertThatThrownBy(() -> service.commit(original, "creator.credential")) .isInstanceOf(io.grpc.StatusRuntimeException.class); @@ -348,18 +347,16 @@ void lostWorldReplyRecoversOriginalResultWithoutReapplyingLocalSource() { new java.util.concurrent.atomic.AtomicReference< WorldOriginalDraftGraphApplyEvidence.Result>(); when(world.apply(any())) - .thenAnswer( - invocation -> { - var request = - (WorldOriginalDraftGraphApplyEvidence.Request) invocation.getArgument(0); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - if (retained.get() == null) { - retained.set(successfulWorld(request)); - throw io.grpc.Status.UNAVAILABLE.asRuntimeException(); - } - assertThat(request).isEqualTo(retained.get().request()); - return retained.get(); - }); + .thenAnswer(invocation -> { + var request = (WorldOriginalDraftGraphApplyEvidence.Request) invocation.getArgument(0); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + if (retained.get() == null) { + retained.set(successfulWorld(request)); + throw io.grpc.Status.UNAVAILABLE.asRuntimeException(); + } + assertThat(request).isEqualTo(retained.get().request()); + return retained.get(); + }); assertThatThrownBy(() -> service.commit(original, "creator.credential")) .isInstanceOf(io.grpc.StatusRuntimeException.class); assertThat(service.commit(original, "creator.credential").result()) @@ -398,16 +395,15 @@ void lostFinalCommitReplyRecoversTerminalWithoutReauthorizingOrReapplying() { @Test void emptyAppliedEpochVectorIsRejectedByCanonicalOutcomeConstructor() { var binding = new GameDesignDraftTerminalOperation(original()).gameDesignBinding(); - assertThatThrownBy( - () -> - new OwnerOutcome( - Owner.GAME_DESIGN_CONTROL_PLANE, - OwnerStatus.APPLIED, - binding.commitId(), - binding.digest(), - "mock", - new byte[] {1}, - List.of())) + assertThatThrownBy(() -> + new OwnerOutcome( + Owner.GAME_DESIGN_CONTROL_PLANE, + OwnerStatus.APPLIED, + binding.commitId(), + binding.digest(), + "mock", + new byte[] {1}, + List.of())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("complete tuple vector"); verifyNoInteractions(account, world, coordinator, terminals, sources, transactions); @@ -562,39 +558,34 @@ private EnumMap arrange( when(coordinator.read(any(), any())) .thenAnswer(ignored -> Optional.of(snapshot(binding, states))); when(coordinator.markOwnerInProgress(any(), any())) - .thenAnswer( - invocation -> { - Owner owner = invocation.getArgument(1); - var updated = state(owner, OwnerStatus.IN_PROGRESS, null); - states.put(owner, updated); - return updated; - }); + .thenAnswer(invocation -> { + Owner owner = invocation.getArgument(1); + var updated = state(owner, OwnerStatus.IN_PROGRESS, null); + states.put(owner, updated); + return updated; + }); when(sources.apply(any())) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - var local = outcome(binding, Owner.GAME_DESIGN_CONTROL_PLANE); - states.put( - Owner.GAME_DESIGN_CONTROL_PLANE, state(local.owner(), local.status(), local)); - var applied = mock(GameDesignSourceRepository.Application.class); - when(applied.ownerOutcome()).thenReturn(local); - return applied; - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + var local = outcome(binding, Owner.GAME_DESIGN_CONTROL_PLANE); + states.put(Owner.GAME_DESIGN_CONTROL_PLANE, state(local.owner(), local.status(), local)); + var applied = mock(GameDesignSourceRepository.Application.class); + when(applied.ownerOutcome()).thenReturn(local); + return applied; + }); when(coordinator.recordOwnerOutcome(any(), any())) - .thenAnswer( - invocation -> { - OwnerOutcome actual = invocation.getArgument(1); - var retained = state(actual.owner(), actual.status(), actual); - states.put(actual.owner(), retained); - return retained; - }); + .thenAnswer(invocation -> { + OwnerOutcome actual = invocation.getArgument(1); + var retained = state(actual.owner(), actual.status(), actual); + states.put(actual.owner(), retained); + return retained; + }); when(coordinator.advanceSourceVisibilityFence(any(), any())) - .thenAnswer( - ignored -> { - assertThat(states.values()).allMatch(value -> value.status() == OwnerStatus.APPLIED); - completed.set(true); - return null; - }); + .thenAnswer(ignored -> { + assertThat(states.values()).allMatch(value -> value.status() == OwnerStatus.APPLIED); + completed.set(true); + return null; + }); var synchronizedSources = mock(GameDesignSourceRepository.SynchronizedSources.class); var command = mock(CommandSnapshot.class); when(command.binding()).thenReturn(binding); @@ -609,17 +600,15 @@ private EnumMap arrange( var order = mock(AccountOriginalDraftOrderEvidence.class); when(order.matches(any())).thenReturn(true); when(account.claim(any())) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return order; - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return order; + }); when(transactions.getTransaction(any())) - .thenAnswer( - ignored -> { - TransactionSynchronizationManager.setActualTransactionActive(true); - return mock(TransactionStatus.class); - }); + .thenAnswer(ignored -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + return mock(TransactionStatus.class); + }); doAnswer( ignored -> { TransactionSynchronizationManager.setActualTransactionActive(false); @@ -699,15 +688,14 @@ private static OwnerOutcome outcome(DraftCommitBinding binding, Owner owner) { "mock-owner-result", new byte[] {1}, binding.affectedUnits(owner).stream() - .map( - unit -> - new AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - "1")) + .map(unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + "1")) .toList()); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java index 7f14f21f1d..ef6cdabf03 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java @@ -239,12 +239,10 @@ void snapshotRoundTripAndCaptureBindTheActualSelectedCommit() throws Exception { selected.baseCommitId(), selected.revisions(), selected.affectedUnits()); - assertThatThrownBy( - () -> - new CommandSnapshot.Capture( - operation, - new CommandSnapshot( - wrongCommit, "0", null, "sha256:" + "a".repeat(64), List.of()))) + assertThatThrownBy(() -> + new CommandSnapshot.Capture( + operation, + new CommandSnapshot(wrongCommit, "0", null, "sha256:" + "a".repeat(64), List.of()))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java index eec9ef0f00..b8708c13c6 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignGameplayRuleSourceReadServiceTest.java @@ -41,14 +41,13 @@ void sanitizesForeignPermissionStatuses(Status.Code foreignCode, Status.Code exp assertThatThrownBy(() -> asAccount(() -> owner.read(accountScopeRequest()))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> { - var status = Status.fromThrowable(error); - assertThat(status.getCode()).isEqualTo(expectedCode); - assertThat(status.getDescription()).isNull(); - assertThat(error.getCause()).isNull(); - assertThat(((StatusRuntimeException) error).getTrailers()).isNull(); - }); + .satisfies(error -> { + var status = Status.fromThrowable(error); + assertThat(status.getCode()).isEqualTo(expectedCode); + assertThat(status.getDescription()).isNull(); + assertThat(error.getCause()).isNull(); + assertThat(((StatusRuntimeException) error).getTrailers()).isNull(); + }); org.mockito.Mockito.verifyNoInteractions(transactions, repository); } @@ -59,10 +58,9 @@ void exportsOnlyTheCompleteOwnerReadForTheExactSynchronizedBinding() { when(transactions.getTransaction(any())).thenReturn(mock(TransactionStatus.class)); var permissions = mock(net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadClient.class); - org.mockito.Mockito.doAnswer( - invocation -> - new net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence( - invocation.getArgument(0))) + org.mockito.Mockito.doAnswer(invocation -> + new net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence( + invocation.getArgument(0))) .when(permissions) .read(any()); var owner = @@ -124,10 +122,9 @@ void exportsOnlyTheCompleteOwnerReadForTheExactSynchronizedBinding() { assertThatThrownBy(() -> asAccount(() -> owner.read(request))) .isInstanceOf(io.grpc.StatusRuntimeException.class); org.mockito.Mockito.verifyNoInteractions(transactions, repository); - org.mockito.Mockito.doAnswer( - invocation -> - new net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence( - invocation.getArgument(0))) + org.mockito.Mockito.doAnswer(invocation -> + new net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence( + invocation.getArgument(0))) .when(permissions) .read(any()); @@ -153,10 +150,9 @@ void exportsOnlyTheCompleteOwnerReadForTheExactSynchronizedBinding() { new byte[] {1}))); var finalizedRequest = GameplayRuleSourceReadEvidence.Request.forFinalizedIntake("test", finalAuthorization); - asGameLogic( - () -> - assertThat(owner.read(finalizedRequest).source().canonicalBytes()) - .containsExactly(snapshot.canonicalBytes())); + asGameLogic(() -> + assertThat(owner.read(finalizedRequest).source().canonicalBytes()) + .containsExactly(snapshot.canonicalBytes())); org.mockito.Mockito.clearInvocations(permissions, transactions, repository); assertThatThrownBy(() -> asAccount(() -> owner.read(finalizedRequest))) .isInstanceOf(io.grpc.StatusRuntimeException.class); @@ -193,10 +189,9 @@ void exportsOnlyTheCompleteOwnerReadForTheExactSynchronizedBinding() { assertThatThrownBy(() -> asAccount(() -> owner.read(request))) .isInstanceOf(io.grpc.StatusRuntimeException.class); org.mockito.Mockito.verifyNoInteractions(transactions, repository); - org.mockito.Mockito.doAnswer( - invocation -> - new net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence( - invocation.getArgument(0))) + org.mockito.Mockito.doAnswer(invocation -> + new net.firedevops.firemud.common.gamelogic.GameLogicIntakeSourceReadEvidence( + invocation.getArgument(0))) .when(permissions) .read(any()); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationServiceTest.java index 38e424472a..9dc77b4306 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationServiceTest.java @@ -48,13 +48,12 @@ void scopeReadUsesIndependentRepeatableReadAndRejectsChangedScope() throws Excep assertThat(definition.getValue().getIsolationLevel()) .isEqualTo(TransactionDefinition.ISOLATION_REPEATABLE_READ); assertThat(definition.getValue().isReadOnly()).isTrue(); - assertThatThrownBy( - () -> - service.readExact( - "changed", - operation.workflowId(), - operation.versionId(), - operation.selectionDigest())) + assertThatThrownBy(() -> + service.readExact( + "changed", + operation.workflowId(), + operation.versionId(), + operation.selectionDigest())) .hasMessage("PUBLICATION_OPERATION_IDENTITY_CONFLICT"); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcServiceTest.java index 233a1123c8..479e0f6bd6 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignSelectedOwnerIntakeSourceGrpcServiceTest.java @@ -55,10 +55,9 @@ void authenticatesAccountPeerAndRejectsMalformedOrMismatchedInputBeforeOwnerRead var wrongNamespace = new Collector(); peer(NAMESPACE, "account-service") - .run( - () -> - service.readSelectedSource( - valid.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); + .run(() -> + service.readSelectedSource( + valid.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); assertThat(wrongNamespace.error).isEqualTo(Status.Code.PERMISSION_DENIED); SessionContext.setContext("123", List.of(), java.util.Map.of()); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignWorldPublicationTerminalProducerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignWorldPublicationTerminalProducerTest.java index 858822ed21..ca161932dc 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignWorldPublicationTerminalProducerTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameDesignWorldPublicationTerminalProducerTest.java @@ -123,35 +123,32 @@ void absentPendingHistoricalOrChangedOutcomeNeverCallsWorld() { @Test void wrongNamespaceScopeExpectedOutcomeOrReturnedEvidenceRemainUnresolved() { var wrongNamespace = new GameDesignWorldPublicationTerminalProducer(owner, client, "other"); - assertThatThrownBy( - () -> - wrongNamespace.reconcile( - operation.tenantKey(), - operation.workflowId(), - operation.versionId(), - operation.selectionDigest(), - Outcome.NO_PUBLICATION)) + assertThatThrownBy(() -> + wrongNamespace.reconcile( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + Outcome.NO_PUBLICATION)) .isInstanceOf(IllegalStateException.class); when(owner.readExact( "other", operation.workflowId(), operation.versionId(), operation.selectionDigest())) .thenReturn(Optional.of(readback("NO_PUBLICATION", terminal.canonicalBytes()))); - assertThatThrownBy( - () -> - producer.reconcile( - "other", - operation.workflowId(), - operation.versionId(), - operation.selectionDigest(), - Outcome.NO_PUBLICATION)) + assertThatThrownBy(() -> + producer.reconcile( + "other", + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + Outcome.NO_PUBLICATION)) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - producer.reconcile( - operation.tenantKey(), - operation.workflowId(), - operation.versionId(), - operation.selectionDigest(), - Outcome.PUBLISHED)) + assertThatThrownBy(() -> + producer.reconcile( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + Outcome.PUBLISHED)) .isInstanceOf(IllegalStateException.class); verifyNoInteractions(client); var changed = mock(GameDesignPublicationTerminalEvidence.class); @@ -184,13 +181,12 @@ void concurrentReconciliationsCanBothEnterOwnerRead() throws Exception { operation.workflowId(), operation.versionId(), operation.selectionDigest())) - .thenAnswer( - ignored -> { - readsEntered.countDown(); - if (!releaseReads.await(5, TimeUnit.SECONDS)) - throw new IllegalStateException("Timed out waiting to release owner read"); - return Optional.of(readback("NO_PUBLICATION", terminal.canonicalBytes())); - }); + .thenAnswer(ignored -> { + readsEntered.countDown(); + if (!releaseReads.await(5, TimeUnit.SECONDS)) + throw new IllegalStateException("Timed out waiting to release owner read"); + return Optional.of(readback("NO_PUBLICATION", terminal.canonicalBytes())); + }); var workers = daemonPool(2); try { var first = workers.submit(this::reconcile); @@ -223,29 +219,27 @@ void closeRejectsNewCallsAndDrainsAdmittedReconciliationBeforeClosingClient() th operation.workflowId(), operation.versionId(), operation.selectionDigest())) - .thenAnswer( - ignored -> { - readEntered.countDown(); - if (!releaseRead.await(5, TimeUnit.SECONDS)) - throw new IllegalStateException("Timed out waiting to release owner read"); - return Optional.of(readback("NO_PUBLICATION", terminal.canonicalBytes())); - }); + .thenAnswer(ignored -> { + readEntered.countDown(); + if (!releaseRead.await(5, TimeUnit.SECONDS)) + throw new IllegalStateException("Timed out waiting to release owner read"); + return Optional.of(readback("NO_PUBLICATION", terminal.canonicalBytes())); + }); var workers = daemonPool(1); var closeStarted = new CountDownLatch(1); var closeFailure = new AtomicReference(); var interruptRestored = new AtomicBoolean(); var closer = - daemonThread( - () -> { - closeStarted.countDown(); - try { - producer.close(); - } catch (Throwable failure) { - closeFailure.set(failure); - } finally { - interruptRestored.set(Thread.currentThread().isInterrupted()); - } - }); + daemonThread(() -> { + closeStarted.countDown(); + try { + producer.close(); + } catch (Throwable failure) { + closeFailure.set(failure); + } finally { + interruptRestored.set(Thread.currentThread().isInterrupted()); + } + }); try { var activeReconciliation = workers.submit(this::reconcile); assertThat(readEntered.await(5, TimeUnit.SECONDS)).isTrue(); @@ -308,11 +302,10 @@ void ownerAndWorldFailuresReleaseAdmissionsForClose() throws Exception { var workers = daemonPool(1); try { var close = - workers.submit( - () -> { - producer.close(); - return null; - }); + workers.submit(() -> { + producer.close(); + return null; + }); close.get(5, TimeUnit.SECONDS); verify(client).close(); } finally { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java index bc5dab2a20..d9530e217b 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameLogicClientTest.java @@ -130,10 +130,8 @@ void propagatesUnavailableTransportFailureForRetry(@TempDir Path tlsDirectory) assertThatThrownBy( () -> clientAndStub.client().getDraftDesignDigestForVersion(publication, receipt)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAVAILABLE)); verify(clientAndStub.stub()).getDraftDesignDigest(any(GetDraftDesignDigestRequest.class)); } @@ -217,9 +215,8 @@ void rejectsPublicationRequestThatDoesNotMatchTheReceiptSelection(@TempDir Path publication.publishRequestId() + "-different"); var clientAndStub = client(tlsDirectory); - assertThatThrownBy( - () -> - clientAndStub.client().getDraftDesignDigestForVersion(changedPublication, receipt)) + assertThatThrownBy(() -> + clientAndStub.client().getDraftDesignDigestForVersion(changedPublication, receipt)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("differs from immutable selected Game Logic receipt"); verifyNoInteractions(clientAndStub.stub()); @@ -303,11 +300,10 @@ void activeSqlTransactionDeniesBeforeRpc(@TempDir Path tlsDirectory) throws IOEx var clientAndStub = client(tlsDirectory); TransactionSynchronizationManager.setActualTransactionActive(true); try { - assertThatThrownBy( - () -> - clientAndStub - .client() - .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt)) + assertThatThrownBy(() -> + clientAndStub + .client() + .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("no ambient SQL transaction"); } finally { @@ -322,11 +318,10 @@ void activeSqlSynchronizationDeniesBeforeRpc(@TempDir Path tlsDirectory) throws var clientAndStub = client(tlsDirectory); TransactionSynchronizationManager.initSynchronization(); try { - assertThatThrownBy( - () -> - clientAndStub - .client() - .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt)) + assertThatThrownBy(() -> + clientAndStub + .client() + .getDraftDesignDigestForVersion(publicationBinding(receipt), receipt)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("no ambient SQL transaction"); } finally { diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepositoryTest.java index 45dbd8d725..9dabec8bcd 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceRepositoryTest.java @@ -49,12 +49,11 @@ void canonicalSnapshotRetainsItsExactBindingAndExplicitInventory() { var decoded = GameplayRuleSnapshot.fromStored(snapshot.canonicalJson()); assertThat(decoded).isEqualTo(snapshot); assertThat(decoded.manifest().families()).hasSize(Family.values().length); - assertThatThrownBy( - () -> - GameplayRuleSnapshot.fromStored( - snapshot - .canonicalJson() - .replace("game-design-gameplay-rule-source-snapshot/v1", "unknown/v1"))) + assertThatThrownBy(() -> + GameplayRuleSnapshot.fromStored( + snapshot + .canonicalJson() + .replace("game-design-gameplay-rule-source-snapshot/v1", "unknown/v1"))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java index 8dc7c51ca7..a509ed76d4 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java @@ -119,13 +119,11 @@ void inheritedCatalogPreservesUnchangedProvenanceAndExplicitDelete() { .containsExactly("second", "third"); assertThat(replayed.getFirst().sourceBinding()).isEqualTo(initial); assertThat(replayed.getLast().sourceBinding()).isEqualTo(changed); - assertThatThrownBy( - () -> - GameplayRuleSource.replay( - replayed, - binding( - List.of( - GameplayRuleSource.deletePayload(Family.ADMISSION_TAGS, "missing"))))) + assertThatThrownBy(() -> + GameplayRuleSource.replay( + replayed, + binding( + List.of(GameplayRuleSource.deletePayload(Family.ADMISSION_TAGS, "missing"))))) .isInstanceOf(IllegalArgumentException.class); } @@ -171,20 +169,18 @@ void incompleteInventoryAndUnresolvedReferencesDenyInsteadOfBecomingEmpty() { families.remove(Family.FEEDBACK); assertThatThrownBy(() -> new GameplayRuleManifest(families)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameplayRuleSource.replay( - List.of(), - binding( - List.of( - GameplayRuleSource.upsertPayload( - new Ability("ability", "Ability", "missingAction")))))) + assertThatThrownBy(() -> + GameplayRuleSource.replay( + List.of(), + binding( + List.of( + GameplayRuleSource.upsertPayload( + new Ability("ability", "Ability", "missingAction")))))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unresolved ACTIONS"); - assertThatThrownBy( - () -> - GameplayRuleManifest.fromStored( - "{\"schema\":\"gameplay-rule-manifest/v1\",\"families\":{}}")) + assertThatThrownBy(() -> + GameplayRuleManifest.fromStored( + "{\"schema\":\"gameplay-rule-manifest/v1\",\"families\":{}}")) .isInstanceOf(IllegalArgumentException.class); } @@ -193,30 +189,25 @@ void unknownDefinitionFieldsDuplicateFieldsAndMissingAdmissionTagsDeny() { String command = GameplayRuleManifest.canonical( exampleManifest().families().get(Family.COMMANDS).getFirst()); - assertThatThrownBy( - () -> - GameplayRuleManifest.definition( - Family.COMMANDS, - command.replace("\"admissionTags\":[\"gameplay\",\"canFocus\"],", ""))) + assertThatThrownBy(() -> + GameplayRuleManifest.definition( + Family.COMMANDS, + command.replace("\"admissionTags\":[\"gameplay\",\"canFocus\"],", ""))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameplayRuleManifest.definition( - Family.ADMISSION_TAGS, "{\"tagKey\":\"tag\",\"unknownPolicy\":true}")) + assertThatThrownBy(() -> + GameplayRuleManifest.definition( + Family.ADMISSION_TAGS, "{\"tagKey\":\"tag\",\"unknownPolicy\":true}")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameplayRuleManifest.definition( - Family.ADMISSION_TAGS, "{\"tagKey\":\"first\",\"tagKey\":\"second\"}")) + assertThatThrownBy(() -> + GameplayRuleManifest.definition( + Family.ADMISSION_TAGS, "{\"tagKey\":\"first\",\"tagKey\":\"second\"}")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameplayRuleManifest.definition(Family.ADMISSION_TAGS, "{\"tagKey\":\"first\"} {}")) + assertThatThrownBy(() -> + GameplayRuleManifest.definition(Family.ADMISSION_TAGS, "{\"tagKey\":\"first\"} {}")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameplayRuleSource.mutations( - binding(List.of("{\"revisionKind\":\"UNKNOWN_RULE_FAMILY\"}")))) + assertThatThrownBy(() -> + GameplayRuleSource.mutations( + binding(List.of("{\"revisionKind\":\"UNKNOWN_RULE_FAMILY\"}")))) .isInstanceOf(IllegalArgumentException.class); } @@ -239,22 +230,21 @@ void continuousEffectsCannotBecomeInstantActionEffectsOrGrantDeniedAdmission() { action.feedbackKeys()))); assertThatThrownBy(() -> new GameplayRuleManifest(families)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameplayRuleManifest.definition( - Family.CONTINUOUS_OVERLAYS, - GameplayRuleManifest.canonical( - Map.of( - "overlayKey", - "overlay", - "eligibleWhen", - truth(), - "deniedAdmissionTags", - List.of(), - "effectKeys", - List.of(), - "grantedAdmissionTags", - List.of("gameplay"))))) + assertThatThrownBy(() -> + GameplayRuleManifest.definition( + Family.CONTINUOUS_OVERLAYS, + GameplayRuleManifest.canonical( + Map.of( + "overlayKey", + "overlay", + "eligibleWhen", + truth(), + "deniedAdmissionTags", + List.of(), + "effectKeys", + List.of(), + "grantedAdmissionTags", + List.of("gameplay"))))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java index 61a8caa3d9..b58a7623ce 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java @@ -314,25 +314,19 @@ private static ReleaseContent release(GameDesignPublicationOperation operation) var request = operation.world().request(); var participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new Participant( - owner, - Long.toString( - operation - .account() - .input() - .selection() - .target() - .gameDesignVersionRowId()), - null, - request.appliedCommitId(), - owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - owner.equals("GAME_LOGIC") ? DIGEST : null, - null, - null)) + .map(owner -> + new Participant( + owner, + Long.toString( + operation.account().input().selection().target().gameDesignVersionRowId()), + null, + request.appliedCommitId(), + owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + owner.equals("GAME_LOGIC") ? DIGEST : null, + null, + null)) .toList(); return new ReleaseContent( request.canonicalTenantId(), diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationMtlsTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationMtlsTest.java index 6ebe197e69..23f18f658f 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationMtlsTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationMtlsTest.java @@ -148,11 +148,10 @@ void exactGameSessionPeerReadsTheFullSetAndResolvesOnlyItsExactSelector() throws PublishedRealmEntryPolicyReadGrpcCodec.fromResponse(resolveRequest, resolved); assertThat(selected).isEqualTo(complete); assertThat(selected.policies()) - .anySatisfy( - policy -> { - assertThat(policy.policy().worldSlug()).isEqualTo("earth"); - assertThat(policy.policy().realmSlug()).isEqualTo("main"); - }); + .anySatisfy(policy -> { + assertThat(policy.policy().worldSlug()).isEqualTo("earth"); + assertThat(policy.policy().realmSlug()).isEqualTo("main"); + }); verify(owner, times(2)) .readPublishedSet( fixture.target().canonicalTenantId(), fixture.target().canonicalVersionId()); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceTest.java index ecf180cf61..92671d1138 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceTest.java @@ -89,12 +89,11 @@ void closedTypedRevisionRejectsMalformedUnknownAndUnsupportedFields() { payload.replace( "\"revisionKind\":", "\"revisionKind\":\"REALM_ENTRY_POLICY\",\"revisionKind\":"))) { - assertThatThrownBy( - () -> - RealmPolicySource.revision( - binding, - new DraftCommitBinding.RevisionPayload( - "0", input.revisionId(), input.owner(), malformed))) + assertThatThrownBy(() -> + RealmPolicySource.revision( + binding, + new DraftCommitBinding.RevisionPayload( + "0", input.revisionId(), input.owner(), malformed))) .isInstanceOf(IllegalArgumentException.class); } } @@ -154,29 +153,27 @@ void explicitDeletionAppliesBeforeFinalTenantRealmUniquenessCheck() { assertThat(RealmPolicySource.effective(List.of(retained, unrelated), List.of(deletion, moved))) .containsExactly(moved, unrelated); - assertThatThrownBy( - () -> - RealmPolicySource.effective( - List.of(retained), - List.of( - new RealmPolicySource.Deletion( - UUID.randomUUID(), - UUID.randomUUID(), - "authored-delete-missing", - "old-world", - "missing")))) + assertThatThrownBy(() -> + RealmPolicySource.effective( + List.of(retained), + List.of( + new RealmPolicySource.Deletion( + UUID.randomUUID(), + UUID.randomUUID(), + "authored-delete-missing", + "old-world", + "missing")))) .hasMessageContaining("absent policy selector"); - assertThatThrownBy( - () -> - RealmPolicySource.effective( - List.of(retained), - List.of( - new RealmPolicySource.Deletion( - UUID.randomUUID(), - UUID.randomUUID(), - "different-logical-identity", - "old-world", - "main")))) + assertThatThrownBy(() -> + RealmPolicySource.effective( + List.of(retained), + List.of( + new RealmPolicySource.Deletion( + UUID.randomUUID(), + UUID.randomUUID(), + "different-logical-identity", + "old-world", + "main")))) .hasMessageContaining("logical revision identity does not match"); assertThatThrownBy(() -> RealmPolicySource.effective(List.of(retained), List.of(moved))) .hasMessageContaining("Duplicate tenant realm selector"); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandServiceTest.java index 824ee7bbee..fc23126772 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicIntakeCommandServiceTest.java @@ -38,15 +38,14 @@ void verifiesImmutableSelectionThenAuthorizesAndRetainsOutsideSqlInOrder() { var account = mock(GameLogicIntakeAuthorizationClient.class); var events = new ArrayList(); when(account.authorize(any(), anyString())) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(call.getArgument(0, GameLogicIntakeAuthorizationEvidence.Request.class)) - .isSameAs(request); - assertThat(call.getArgument(1, String.class)).isEqualTo(CREDENTIAL); - events.add("account.authorize"); - return GameLogicIntakeAuthorizationEvidence.Result.authorized(request, authorization); - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(call.getArgument(0, GameLogicIntakeAuthorizationEvidence.Request.class)) + .isSameAs(request); + assertThat(call.getArgument(1, String.class)).isEqualTo(CREDENTIAL); + events.add("account.authorize"); + return GameLogicIntakeAuthorizationEvidence.Result.authorized(request, authorization); + }); var service = new SelectedDraftGameLogicIntakeCommandService( selected -> { @@ -126,10 +125,9 @@ void rejectsMalformedRequestOrChangedDurableSelectionBeforeAccountRpc() { return value; }, "test"); - assertThatThrownBy( - () -> - changedSelectionService.authorizeAndRetain( - value.selection(), request(value.selection()), CREDENTIAL)) + assertThatThrownBy(() -> + changedSelectionService.authorizeAndRetain( + value.selection(), request(value.selection()), CREDENTIAL)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("immutable selection"); @@ -285,13 +283,12 @@ void exactRecoveryUsesCallerIntakeIdentityWithoutIssuingAnotherAuthorization() { var expectedReceipt = receiptFor(value.selection(), authorization); var account = mock(GameLogicIntakeAuthorizationClient.class); when(account.recover(any(), anyString())) - .thenAnswer( - call -> { - assertThat(call.getArgument(0, GameLogicIntakeAuthorizationEvidence.Request.class)) - .isSameAs(request); - assertThat(call.getArgument(1, String.class)).isEqualTo(CREDENTIAL); - return GameLogicIntakeAuthorizationEvidence.Result.authorized(request, authorization); - }); + .thenAnswer(call -> { + assertThat(call.getArgument(0, GameLogicIntakeAuthorizationEvidence.Request.class)) + .isSameAs(request); + assertThat(call.getArgument(1, String.class)).isEqualTo(CREDENTIAL); + return GameLogicIntakeAuthorizationEvidence.Result.authorized(request, authorization); + }); var service = new SelectedDraftGameLogicIntakeCommandService( ignored -> Optional.of(value.selection()), diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptServiceTest.java index 428881c867..61d2e56f2c 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptServiceTest.java @@ -36,19 +36,16 @@ void ownerCallsOutsideSqlThenStoresExactAccountReceiptAndRecoversWithoutRpc() { when(repository.read(any(), any())).thenReturn(Optional.empty()); when(repository.retain(any())).thenReturn(value); when(gl.retain(any())) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return new GameLogicIntakeRetainEvidence( - call.getArgument(0), value.receipt().terminal()); - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new GameLogicIntakeRetainEvidence(call.getArgument(0), value.receipt().terminal()); + }); when(account.read(any())) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return new AccountGameLogicIntakeSettlementReadEvidence( - call.getArgument(0), value.receipt()); - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return new AccountGameLogicIntakeSettlementReadEvidence( + call.getArgument(0), value.receipt()); + }); var service = new SelectedDraftGameLogicReceiptService( repository, @@ -83,10 +80,9 @@ void missingSelectionAndWrongCompleteSelectionDenyBeforeRpcOrTransaction() { assertThatThrownBy(() -> service.retain(value.selection(), value.authorization())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("SELECTION_UNAVAILABLE"); - assertThatThrownBy( - () -> - service.retain( - value.selection(), SelectedDraftGameLogicReceiptTest.fixture().authorization())) + assertThatThrownBy(() -> + service.retain( + value.selection(), SelectedDraftGameLogicReceiptTest.fixture().authorization())) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(repository, transactions, gl, account); } @@ -110,21 +106,18 @@ void abortedOrMissingRemoteResultCannotStoreReceipt() { assertThatThrownBy(() -> service.retain(value.selection(), value.authorization())) .isInstanceOf(IllegalStateException.class); when(gl.retain(any())) - .thenAnswer( - call -> - new GameLogicIntakeRetainEvidence( - call.getArgument(0), - GameLogicGameplayRuleIntakeTerminal.aborted( - new GameLogicGameplayRuleIntakeOperation("test", value.authorization())))); + .thenAnswer(call -> + new GameLogicIntakeRetainEvidence( + call.getArgument(0), + GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation("test", value.authorization())))); when(account.read(any())) - .thenAnswer( - call -> - new AccountGameLogicIntakeSettlementReadEvidence( - call.getArgument(0), - new AccountGameLogicIntakeSettlementEvidence( - GameLogicGameplayRuleIntakeTerminal.aborted( - new GameLogicGameplayRuleIntakeOperation( - "test", value.authorization()))))); + .thenAnswer(call -> + new AccountGameLogicIntakeSettlementReadEvidence( + call.getArgument(0), + new AccountGameLogicIntakeSettlementEvidence( + GameLogicGameplayRuleIntakeTerminal.aborted( + new GameLogicGameplayRuleIntakeOperation("test", value.authorization()))))); assertThatThrownBy(() -> service.retain(value.selection(), value.authorization())) .isInstanceOf(IllegalArgumentException.class); verify(account).read(any()); @@ -142,9 +135,8 @@ void lostAccountSettlementAcknowledgementRecoversOriginalIntakeWithNewTransportC var gl = mock(GameLogicIntakeRetainClient.class); var account = mock(AccountGameLogicIntakeSettlementReadClient.class); when(gl.retain(any())) - .thenAnswer( - call -> - new GameLogicIntakeRetainEvidence(call.getArgument(0), value.receipt().terminal())); + .thenAnswer(call -> + new GameLogicIntakeRetainEvidence(call.getArgument(0), value.receipt().terminal())); when(account.read(any())) .thenThrow(new IllegalStateException("lost settlement acknowledgement")); var service = @@ -159,10 +151,8 @@ void lostAccountSettlementAcknowledgementRecoversOriginalIntakeWithNewTransportC .hasMessage("lost settlement acknowledgement"); verify(repository, never()).retain(any()); verifyNoInteractions(transactions); - doAnswer( - call -> - new AccountGameLogicIntakeSettlementReadEvidence( - call.getArgument(0), value.receipt())) + doAnswer(call -> + new AccountGameLogicIntakeSettlementReadEvidence(call.getArgument(0), value.receipt())) .when(account) .read(any()); assertThat(service.retain(value.selection(), value.authorization())).isSameAs(value); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptTest.java index 073eecba48..64f5c843f8 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftGameLogicReceiptTest.java @@ -48,18 +48,16 @@ void rejectsAbortedDifferentSelectionAndChangedAuthorizationRetry() { var abort = GameLogicGameplayRuleIntakeTerminal.aborted( new GameLogicGameplayRuleIntakeOperation("test", value.authorization())); - assertThatThrownBy( - () -> - new SelectedDraftGameLogicReceipt( - value.selection(), - value.authorization(), - new AccountGameLogicIntakeSettlementEvidence(abort))) + assertThatThrownBy(() -> + new SelectedDraftGameLogicReceipt( + value.selection(), + value.authorization(), + new AccountGameLogicIntakeSettlementEvidence(abort))) .isInstanceOf(IllegalArgumentException.class); var other = fixture(); - assertThatThrownBy( - () -> - SelectedDraftGameLogicReceipt.requireExactSelection( - value.selection(), other.authorization())) + assertThatThrownBy(() -> + SelectedDraftGameLogicReceipt.requireExactSelection( + value.selection(), other.authorization())) .isInstanceOf(IllegalArgumentException.class); var changed = new GameLogicIntakeAuthorizationBinding( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java index f23215b237..4769bd64af 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java @@ -55,12 +55,11 @@ void retainedSelectionAccountFreezeAndDerivedSelectorPrecedeReservation() throws var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); var sourceFixture = sourceFixture(fixture.worldRequest()); when(sourceIntake.readById(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - return sourceReceipt(invocation.getArgument(0), sourceFixture); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return sourceReceipt(invocation.getArgument(0), sourceFixture); + }); when(sourceRepository.read( sourceFixture.source().operationId(), sourceFixture.source().canonicalTenantId(), @@ -81,30 +80,27 @@ void retainedSelectionAccountFreezeAndDerivedSelectorPrecedeReservation() throws fixture.operation().account().input().selection().digest()); when(reader.read(fixture.intent())).thenReturn(Optional.of(retained)); when(account.read(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); - when(evidence.request()).thenReturn(invocation.getArgument(0)); - return evidence; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); when(world.read(fixture.worldRequest())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - return fixture.operation().world(); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return fixture.operation().world(); + }); var reservation = mock(SelectedDraftPublicationOwner.Reservation.class); // Request.binding() reconstructs the exact Account bytes; its nested selection does not use // value equality. Match the complete canonical binding rather than decoded object identity. when(owner.reserve( eq(fixture.intent()), - argThat( - binding -> - Arrays.equals( - binding.canonicalBytes(), fixture.operation().account().canonicalBytes())), + argThat(binding -> + Arrays.equals( + binding.canonicalBytes(), fixture.operation().account().canonicalBytes())), same(fixture.operation().world()), same(fixture.operation().inventory()), any())) @@ -145,17 +141,14 @@ void retainedSelectionAccountFreezeAndDerivedSelectorPrecedeReservation() throws order .verify(sourceIntake) .readById( - argThat( - request -> - request.schemaVersion() == 1 - && request.targetNamespace().equals(NAMESPACE) - && request - .intakeRequestId() - .equals(fixture.worldRequest().intakeRequestId()) - && request - .canonicalTenantId() - .equals(fixture.worldRequest().canonicalTenantId()) - && !request.readRequestId().equals(request.intakeRequestId()))); + argThat(request -> + request.schemaVersion() == 1 + && request.targetNamespace().equals(NAMESPACE) + && request.intakeRequestId().equals(fixture.worldRequest().intakeRequestId()) + && request + .canonicalTenantId() + .equals(fixture.worldRequest().canonicalTenantId()) + && !request.readRequestId().equals(request.intakeRequestId()))); order .verify(sourceRepository) .read( @@ -169,10 +162,9 @@ void retainedSelectionAccountFreezeAndDerivedSelectorPrecedeReservation() throws .verify(owner) .reserve( eq(fixture.intent()), - argThat( - binding -> - Arrays.equals( - binding.canonicalBytes(), fixture.operation().account().canonicalBytes())), + argThat(binding -> + Arrays.equals( + binding.canonicalBytes(), fixture.operation().account().canonicalBytes())), same(fixture.operation().world()), same(fixture.operation().inventory()), any()); @@ -225,12 +217,11 @@ void mismatchedRetainedDeliveryAcknowledgementDeniesBeforeReservation() throws E var fixture = fixture(); var account = mock(AccountPublicationAuthorizationReadClient.class); when(account.read(any())) - .thenAnswer( - invocation -> { - var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); - when(evidence.request()).thenReturn(invocation.getArgument(0)); - return evidence; - }); + .thenAnswer(invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); var sourceFixture = sourceFixture(fixture.worldRequest()); var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); when(sourceIntake.readById(any())) @@ -330,12 +321,11 @@ void freezeFailureNeverReadsSelectorOrReserves() throws Exception { selection.canonicalJson(), selection.digest())), NAMESPACE); when(account.read(any())) - .thenAnswer( - invocation -> { - var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); - when(evidence.request()).thenReturn(invocation.getArgument(0)); - return evidence; - }); + .thenAnswer(invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); var failure = Status.UNAVAILABLE.asRuntimeException(); when(freeze.begin(any())).thenThrow(failure); @@ -358,12 +348,11 @@ void missingInventoryAfterAcknowledgedFreezeNeverReadsSelectorOrOpensSql() throw var fixture = fixture(); var account = mock(AccountPublicationAuthorizationReadClient.class); when(account.read(any())) - .thenAnswer( - invocation -> { - var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); - when(evidence.request()).thenReturn(invocation.getArgument(0)); - return evidence; - }); + .thenAnswer(invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); var inventory = mock(WorldSelectedPublicationArtifactInventoryClient.class); var world = mock(WorldPublishedStartLocationClient.class); var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); @@ -489,12 +478,11 @@ void worldUnavailableAfterAccountReadNeverOpensReservation() throws Exception { // The client is a transport double here; the mock evidence is never accepted as proof because // the World read fails before the reservation boundary. when(accountClient.read(any())) - .thenAnswer( - invocation -> { - var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); - when(evidence.request()).thenReturn(invocation.getArgument(0)); - return evidence; - }); + .thenAnswer(invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); var failure = Status.UNAVAILABLE.asRuntimeException(); when(worldClient.read(fixture.worldRequest())).thenThrow(failure); @@ -533,39 +521,35 @@ private static SelectedDraftPublicationAdmissionService service( private static WorldSelectedPublicationArtifactInventoryClient inventoryClient(Fixture fixture) { var client = mock(WorldSelectedPublicationArtifactInventoryClient.class); when(client.read(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - return fixture.operation().inventory(); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return fixture.operation().inventory(); + }); return client; } private static WorldSelectedDraftPublicationFreezeClient freezeClient(Fixture fixture) { var client = mock(WorldSelectedDraftPublicationFreezeClient.class); when(client.begin(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - WorldSelectedDraftPublicationFreezeEvidence.Request request = - invocation.getArgument(0); - var world = fixture.worldRequest(); - var acknowledgement = - new WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement( - request, - world.intakeRequestId(), - world.versionStateEpoch(), - world.publicationFence(), - WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN, - world.appliedCommitId(), - world.contentDigest(), - world.digestSchemaVersion()); - return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + WorldSelectedDraftPublicationFreezeEvidence.Request request = invocation.getArgument(0); + var world = fixture.worldRequest(); + var acknowledgement = + new WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement( request, - WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); - }); + world.intakeRequestId(), + world.versionStateEpoch(), + world.publicationFence(), + WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN, + world.appliedCommitId(), + world.contentDigest(), + world.digestSchemaVersion()); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + request, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + }); return client; } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java index c6a4df7194..cb5a44d1ae 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationDigestReadServiceTest.java @@ -551,14 +551,13 @@ private void assertSanitizedUnavailable( SelectedDraftPublicationDigestReadService service, PublicationDigestRequestBinding request) { assertThatThrownBy(() -> service.read(NAMESPACE, request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - var status = ((StatusRuntimeException) failure).getStatus(); - assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); - assertThat(status.getDescription()) - .isEqualTo("Selected publication source readback unavailable") - .doesNotContain("secret"); - }); + .satisfies(failure -> { + var status = ((StatusRuntimeException) failure).getStatus(); + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status.getDescription()) + .isEqualTo("Selected publication source readback unavailable") + .doesNotContain("secret"); + }); } private record Fixture( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java index 10d1290ec1..af1637bf2e 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedOwnerIntakeSourceExportTest.java @@ -106,15 +106,14 @@ void contentIsDeterministicAndCanonicalBytesAreDefensivelyExposed() { void rejectsDifferentSelectedBindingAndChangedFamilyContent() { var selected = binding(COMMIT, CommandSource.deletePayload("absent-command")); var sources = sources(selected, "0"); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceExport.create( - scope( - Owner.ENTITY_MANAGEMENT, - binding( - id("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), - CommandSource.deletePayload("absent-command"))), - sources)) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceExport.create( + scope( + Owner.ENTITY_MANAGEMENT, + binding( + id("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + CommandSource.deletePayload("absent-command"))), + sources)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("COMMAND"); @@ -148,16 +147,14 @@ void missingBrandingOrTemplateSourceIsNotAnEmptyFamily() { complete.branding(), Optional.empty()); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceExport.create( - scope(Owner.ENTITY_MANAGEMENT, selected), missingBranding)) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceExport.create( + scope(Owner.ENTITY_MANAGEMENT, selected), missingBranding)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("branding"); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceExport.create( - scope(Owner.AUTOMATION_SCRIPTING, selected), missingTemplate)) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceExport.create( + scope(Owner.AUTOMATION_SCRIPTING, selected), missingTemplate)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("template-config"); } @@ -166,10 +163,9 @@ void missingBrandingOrTemplateSourceIsNotAnEmptyFamily() { void rejectsExportLargerThanEightMib() { var selected = binding(COMMIT, "x".repeat(1_400_000)); - assertThatThrownBy( - () -> - SelectedOwnerIntakeSourceExport.create( - scope(Owner.ENTITY_MANAGEMENT, selected), sources(selected, "0"))) + assertThatThrownBy(() -> + SelectedOwnerIntakeSourceExport.create( + scope(Owner.ENTITY_MANAGEMENT, selected), sources(selected, "0"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("8 MiB"); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java index 8304f5ca9e..16f08c692a 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionLaunchDescriptorProducerTest.java @@ -100,15 +100,13 @@ void requiresExactReplayAndSameNamespacePeerBeforeOwnerWork() { .isInstanceOf(NullPointerException.class); verifyNoInteractions(associationReader, transactions); - assertThatThrownBy( - () -> - withPeer( - () -> - producer.resolve( - request( - new ExactReplay( - VERSION, COMMIT, "selected-workflow", digest('a')))), - "account-service")) + assertThatThrownBy(() -> + withPeer( + () -> + producer.resolve( + request( + new ExactReplay(VERSION, COMMIT, "selected-workflow", digest('a')))), + "account-service")) .isInstanceOf(StatusRuntimeException.class) .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) .isEqualTo(Status.Code.PERMISSION_DENIED); @@ -224,13 +222,12 @@ void sharedReleaseEncodingKeepsCallerSpecificFailureMappings() throws Exception assertThatThrownBy(() -> producer.toPublishedReleaseBundle(failedDto)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - var status = ((StatusRuntimeException) failure).getStatus(); - assertThat(status.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); - assertThat(status.getDescription()) - .isEqualTo("Published release participant did not succeed"); - }); + .satisfies(failure -> { + var status = ((StatusRuntimeException) failure).getStatus(); + assertThat(status.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(status.getDescription()) + .isEqualTo("Published release participant did not succeed"); + }); assertThatThrownBy(() -> associationReader.toPublishedReleaseBundle(failedDto)) .isInstanceOf(IllegalStateException.class) .hasMessage("START_SESSION_PUBLISHED_PARTICIPANT_FAILURE"); @@ -242,13 +239,12 @@ void sharedReleaseEncodingKeepsCallerSpecificFailureMappings() throws Exception assertThat(legacyBundle.getArtifactDigestsList()).isEmpty(); assertThatThrownBy(() -> producer.releaseContent(incomplete)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - var status = ((StatusRuntimeException) failure).getStatus(); - assertThat(status.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); - assertThat(status.getDescription()) - .isEqualTo("Immutable release content evidence is incomplete"); - }); + .satisfies(failure -> { + var status = ((StatusRuntimeException) failure).getStatus(); + assertThat(status.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(status.getDescription()) + .isEqualTo("Immutable release content evidence is incomplete"); + }); assertThatThrownBy(() -> associationReader.releaseContent(incomplete)) .isInstanceOf(IllegalStateException.class) .hasMessage("START_SESSION_IMMUTABLE_RELEASE_ARTIFACT_PROOF_MISSING"); @@ -308,18 +304,17 @@ void selectedSchema3ActorCoreIsResolvedFromExactOwnerSnapshots() { new net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot( otherCommit, "1", fixture.policySnapshot().policies()); - assertThatThrownBy( - () -> - StartSessionLaunchDescriptorProducer.resolveSelectedAuthoredInitialActorCoreSources( - uuid("66666666-6666-4666-8666-666666666666"), - digest('a'), - "world", - "selected-workflow", - bytes("selected publication operation"), - bytes("selected publication terminal evidence"), - fixture.binding(), - changedPolicySnapshot, - fixture.gameplayRules())) + assertThatThrownBy(() -> + StartSessionLaunchDescriptorProducer.resolveSelectedAuthoredInitialActorCoreSources( + uuid("66666666-6666-4666-8666-666666666666"), + digest('a'), + "world", + "selected-workflow", + bytes("selected publication operation"), + bytes("selected publication terminal evidence"), + fixture.binding(), + changedPolicySnapshot, + fixture.gameplayRules())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("selected authored commit"); } @@ -364,35 +359,31 @@ void resolvedBindingDefensivelyRetainsMinimalActorCoreProjectionAndRejectsChange assertThatThrownBy(resolved.actorCoreProjections()::clear) .isInstanceOf(UnsupportedOperationException.class); - assertThatThrownBy( - () -> - resolvedBinding( - sourceBindings, - uuid("77777777-7777-4777-8777-777777777777"), - "world", - COMMIT, - "selected-workflow")) + assertThatThrownBy(() -> + resolvedBinding( + sourceBindings, + uuid("77777777-7777-4777-8777-777777777777"), + "world", + COMMIT, + "selected-workflow")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact selected StartSession release"); - assertThatThrownBy( - () -> - resolvedBinding( - sourceBindings, sourceOperation, "other-world", COMMIT, "selected-workflow")) + assertThatThrownBy(() -> + resolvedBinding( + sourceBindings, sourceOperation, "other-world", COMMIT, "selected-workflow")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact selected StartSession release"); - assertThatThrownBy( - () -> - resolvedBinding( - sourceBindings, - sourceOperation, - "world", - uuid("88888888-8888-4888-8888-888888888888"), - "selected-workflow")) + assertThatThrownBy(() -> + resolvedBinding( + sourceBindings, + sourceOperation, + "world", + uuid("88888888-8888-4888-8888-888888888888"), + "selected-workflow")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact selected StartSession release"); - assertThatThrownBy( - () -> - resolvedBinding(sourceBindings, sourceOperation, "world", COMMIT, "other-workflow")) + assertThatThrownBy(() -> + resolvedBinding(sourceBindings, sourceOperation, "world", COMMIT, "other-workflow")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact selected StartSession release"); } @@ -435,13 +426,12 @@ private static StartSessionLaunchDescriptorProducer.ResolvedBinding resolvedBind // Structural projection fixtures only; Common integrity checks do not authenticate a producer. List projections = java.util.stream.IntStream.range(0, actorCoreBindings.size()) - .mapToObj( - index -> - AuthoredInitialActorCoreProjection.fromValidatedBinding( - UUID.nameUUIDFromBytes( - (index + ":" + actorCoreBindings.get(index).digest()) - .getBytes(StandardCharsets.UTF_8)), - actorCoreBindings.get(index))) + .mapToObj(index -> + AuthoredInitialActorCoreProjection.fromValidatedBinding( + UUID.nameUUIDFromBytes( + (index + ":" + actorCoreBindings.get(index).digest()) + .getBytes(StandardCharsets.UTF_8)), + actorCoreBindings.get(index))) .toList(); return new StartSessionLaunchDescriptorProducer.ResolvedBinding( request, associationRead, descriptor, projections); @@ -660,30 +650,28 @@ private static GameDesignPublicationTerminalEvidence.ReleaseContent expectedRele PublishedReleaseBundleDto dto) { var participants = dto.participantDigests().stream() - .map( - value -> - new GameDesignPublicationTerminalEvidence.Participant( - value.participantKey(), - value.scopeValue(), - value.baseVersionId(), - value.appliedCommitId(), - value.contentDigest(), - value.digestSchemaVersion(), - value.abilitySchemaDigest(), - value.errorCode(), - value.errorMessage())) + .map(value -> + new GameDesignPublicationTerminalEvidence.Participant( + value.participantKey(), + value.scopeValue(), + value.baseVersionId(), + value.appliedCommitId(), + value.contentDigest(), + value.digestSchemaVersion(), + value.abilitySchemaDigest(), + value.errorCode(), + value.errorMessage())) .toList(); var artifacts = dto.artifactDigests().stream() - .map( - value -> - new AuthoredWorldReleaseAttestationEvidence.Artifact( - value.usageKey(), - value.artifactKind(), - value.immutableObjectKey(), - value.contentDigest(), - value.contentType(), - value.artifactSchemaVersion())) + .map(value -> + new AuthoredWorldReleaseAttestationEvidence.Artifact( + value.usageKey(), + value.artifactKind(), + value.immutableObjectKey(), + value.contentDigest(), + value.contentType(), + value.artifactSchemaVersion())) .toList(); return new GameDesignPublicationTerminalEvidence.ReleaseContent( dto.canonicalTenantId(), diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java index 61d379ea32..2fb2306804 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/StartSessionTemplateAssociationReadServiceTest.java @@ -294,14 +294,13 @@ private static void assertTransactionFailureMapsToUnavailable( RuntimeException cause) { assertThatThrownBy(() -> withPeer(service, request, "game-session-service")) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - thrown -> { - var status = ((StatusRuntimeException) thrown).getStatus(); - assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); - assertThat(status.getDescription()) - .isEqualTo("Game Design association owner storage unavailable"); - assertThat(status.getCause()).isSameAs(cause); - }); + .satisfies(thrown -> { + var status = ((StatusRuntimeException) thrown).getStatus(); + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status.getDescription()) + .isEqualTo("Game Design association owner storage unavailable"); + assertThat(status.getCause()).isSameAs(cause); + }); } private void assertAuthoredCoreStorageFailure( @@ -321,17 +320,14 @@ private void assertAuthoredCoreStorageFailure( dsl.fetchOne( org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(Object[].class))) - .thenAnswer( - ignored -> { - assertThat(snapshotOpened).isTrue(); - throw storageFailure; - }); - - assertThatThrownBy( - () -> - withPeer( - "game-session-service", - () -> authoredCoreReader.read(authoredCoreRequest(tuple)))) + .thenAnswer(ignored -> { + assertThat(snapshotOpened).isTrue(); + throw storageFailure; + }); + + assertThatThrownBy(() -> + withPeer( + "game-session-service", () -> authoredCoreReader.read(authoredCoreRequest(tuple)))) .isInstanceOf(StatusRuntimeException.class) .extracting(failure -> ((StatusRuntimeException) failure).getStatus().getCode()) .isEqualTo(expectedStatus); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryTest.java index 0c1be6b9d9..6f0a0a2569 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/GameTenantCreationRepositoryTest.java @@ -99,9 +99,8 @@ void readRejectsChangedStoredRequestDigestAsCorruptEvidence() throws Exception { evidenceDigest(NAMESPACE, REQUEST_ID, changedRequestDigest, TENANT_ID, 91L, SOURCE_KEY)); GameRepository gameRepository = mock(GameRepository.class); - assertThatThrownBy( - () -> - new GameTenantCreationRepository(dsl, gameRepository).read(REQUEST_ID, NAMESPACE)) + assertThatThrownBy(() -> + new GameTenantCreationRepository(dsl, gameRepository).read(REQUEST_ID, NAMESPACE)) .isInstanceOf(GameTenantCreationRepository.InvalidCreationEvidenceException.class) .hasMessageContaining("request digest does not match"); verifyNoInteractions(gameRepository); @@ -131,9 +130,8 @@ void readRejectsGameRowIdentityDriftEvenWhenOperationDigestsMatch() throws Excep 91L, SOURCE_KEY))); - assertThatThrownBy( - () -> - new GameTenantCreationRepository(dsl, gameRepository).read(REQUEST_ID, NAMESPACE)) + assertThatThrownBy(() -> + new GameTenantCreationRepository(dsl, gameRepository).read(REQUEST_ID, NAMESPACE)) .isInstanceOf(GameTenantCreationRepository.InvalidCreationEvidenceException.class) .hasMessageContaining("source tuple no longer matches"); verify(gameRepository).findRuntimeTenantIdentityByTenantKey(SOURCE_KEY); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionRepositoryTest.java index e352692494..01a4501a31 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/StartSessionAuthoredActorCoreProjectionRepositoryTest.java @@ -68,20 +68,18 @@ void deniesHistoricalMissingProofAndFullPrivateContentConflict() { AuthoredInitialActorCoreProjection projection = AuthoredInitialActorCoreProjection.fromValidatedBinding(BINDING_ID, source); - assertThatThrownBy( - () -> - StartSessionAuthoredActorCoreProjectionRepository.validateReplay( - List.of(), List.of(source), owner())) + assertThatThrownBy(() -> + StartSessionAuthoredActorCoreProjectionRepository.validateReplay( + List.of(), List.of(source), owner())) .isInstanceOf( StartSessionAuthoredActorCoreProjectionRepository.MissingRetainedProjectionException .class); AuthoredInitialActorCoreSourceBinding changed = sourceBinding("different but internally well-formed terminal evidence"); - assertThatThrownBy( - () -> - StartSessionAuthoredActorCoreProjectionRepository.validateReplay( - List.of(retained(owner(), source, projection, 0)), List.of(changed), owner())) + assertThatThrownBy(() -> + StartSessionAuthoredActorCoreProjectionRepository.validateReplay( + List.of(retained(owner(), source, projection, 0)), List.of(changed), owner())) .isInstanceOf( StartSessionAuthoredActorCoreProjectionRepository.RetainedProjectionConflictException .class) @@ -95,21 +93,19 @@ void deniesIncompleteOrReorderedOwnerProofSets() { AuthoredInitialActorCoreProjection.fromValidatedBinding(BINDING_ID, source); RetainedProjection wrongOrder = retained(owner(), source, projection, 1); - assertThatThrownBy( - () -> - StartSessionAuthoredActorCoreProjectionRepository.validateReplay( - List.of(wrongOrder), List.of(source), owner())) + assertThatThrownBy(() -> + StartSessionAuthoredActorCoreProjectionRepository.validateReplay( + List.of(wrongOrder), List.of(source), owner())) .isInstanceOf( StartSessionAuthoredActorCoreProjectionRepository.RetainedProjectionConflictException .class) .hasMessageContaining("owner identity or order changed"); - assertThatThrownBy( - () -> - StartSessionAuthoredActorCoreProjectionRepository.validateReplay( - List.of(retained(owner(), source, projection, 0)), - List.of(source, source), - owner())) + assertThatThrownBy(() -> + StartSessionAuthoredActorCoreProjectionRepository.validateReplay( + List.of(retained(owner(), source, projection, 0)), + List.of(source, source), + owner())) .isInstanceOf( StartSessionAuthoredActorCoreProjectionRepository.RetainedProjectionConflictException .class) @@ -277,15 +273,14 @@ private static GameplayRuleSelectedSource selectedGameplaySource( snapshot.put( "entries", entries.stream() - .map( - entry -> - Map.of( - "family", entry.family().name(), - "definitionJson", GameplayRuleManifest.canonical(entry.definition()), - "sourceBindingJson", entry.sourceBinding().canonicalJson(), - "sourceBindingDigest", entry.sourceBinding().digest(), - "revisionOrder", entry.revisionOrder(), - "revisionId", entry.revisionId().toString())) + .map(entry -> + Map.of( + "family", entry.family().name(), + "definitionJson", GameplayRuleManifest.canonical(entry.definition()), + "sourceBindingJson", entry.sourceBinding().canonicalJson(), + "sourceBindingDigest", entry.sourceBinding().digest(), + "revisionOrder", entry.revisionOrder(), + "revisionId", entry.revisionId().toString())) .toList()); return new GameplayRuleSelectedSource(CommandSource.canonical(snapshot)); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryTest.java index d006f6aa46..bb2dc71b08 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionAssetArtifactRepositoryTest.java @@ -88,12 +88,11 @@ public void executeStart(ExecuteContext context) { assertThat(executedSql) .filteredOn(sql -> sql.toLowerCase().contains(" where ")) .singleElement() - .satisfies( - sql -> { - assertThat(sql.toLowerCase()).contains("where \"id\" = "); - assertThat(sql.toLowerCase()).doesNotContain("tenant_id"); - assertThat(sql.toLowerCase()).doesNotContain("version_id"); - }); + .satisfies(sql -> { + assertThat(sql.toLowerCase()).contains("where \"id\" = "); + assertThat(sql.toLowerCase()).doesNotContain("tenant_id"); + assertThat(sql.toLowerCase()).doesNotContain("version_id"); + }); VersionAssetArtifactRepository repository = new VersionAssetArtifactRepository(dsl); VersionAssetArtifact stale = diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java index df4800fc4f..46cfff4d08 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionRepositoryTest.java @@ -64,14 +64,13 @@ void scriptPatchPublicationLookupUsesExactRetainedScopeAndLeavesAmbiguityVisible VersionLifecycleState.ACTIVE, VersionLifecycleState.PUBLISHED); assertThat(candidates) - .allSatisfy( - candidate -> { - assertThat(candidate.getCanonicalVersionId()).isNull(); - assertThat(candidate.getCanonicalTenantId()).isNull(); - assertThat(candidate.getIdentitySourceGameRowId()).isNull(); - assertThat(candidate.getIdentitySourceGameTenantKey()).isNull(); - assertThat(candidate.getIdentitySourceProvenanceKind()).isNull(); - }); + .allSatisfy(candidate -> { + assertThat(candidate.getCanonicalVersionId()).isNull(); + assertThat(candidate.getCanonicalTenantId()).isNull(); + assertThat(candidate.getIdentitySourceGameRowId()).isNull(); + assertThat(candidate.getIdentitySourceGameTenantKey()).isNull(); + assertThat(candidate.getIdentitySourceProvenanceKind()).isNull(); + }); } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionTemplateRemapSetRepositoryTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionTemplateRemapSetRepositoryTest.java index fe80ac006d..850250a064 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionTemplateRemapSetRepositoryTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/VersionTemplateRemapSetRepositoryTest.java @@ -77,21 +77,19 @@ public void executeStart(ExecuteContext context) { assertThat(inserted.getRemapEntries()) .singleElement() - .satisfies( - savedEntry -> { - assertThat(savedEntry.getId()).isNotNull(); - assertThat(savedEntry.getCreatedAt()).isEqualTo(entryCreatedAt); - }); + .satisfies(savedEntry -> { + assertThat(savedEntry.getId()).isNotNull(); + assertThat(savedEntry.getCreatedAt()).isEqualTo(entryCreatedAt); + }); assertThat(executedSql) .filteredOn( sql -> sql.toLowerCase().contains("insert into \"version_template_remap_entry\"")) .singleElement() - .satisfies( - sql -> { - assertThat(sql.toLowerCase()) - .contains("select \"id\", \"created_at\" from final table"); - assertThat(sql.toLowerCase()).doesNotContain("select *"); - }); + .satisfies(sql -> { + assertThat(sql.toLowerCase()) + .contains("select \"id\", \"created_at\" from final table"); + assertThat(sql.toLowerCase()).doesNotContain("select *"); + }); } } } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java index 949b1dd1ff..63e4f547fe 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/security/TenantIdentityGrpcAuthWiringTest.java @@ -95,50 +95,48 @@ void defaultAndProductionProfilesKeepExactReadAllowlistAndRequireClientTls() thr @Test void allowlistedNoTokenReadStillRequiresExactOwnerPeerBeforeOwnerRead() { - withConfiguredInterceptor( - interceptor -> { - GameTenantCreationRepository repository = mock(GameTenantCreationRepository.class); - TenantIdentityGrpcService service = new TenantIdentityGrpcService(repository, "test"); - FreshTenantCreationEvidence evidence = evidence("test", REQUEST_DIGEST); - when(repository.read(REQUEST_ID, "test")).thenReturn(Optional.of(evidence)); + withConfiguredInterceptor(interceptor -> { + GameTenantCreationRepository repository = mock(GameTenantCreationRepository.class); + TenantIdentityGrpcService service = new TenantIdentityGrpcService(repository, "test"); + FreshTenantCreationEvidence evidence = evidence("test", REQUEST_DIGEST); + when(repository.read(REQUEST_ID, "test")).thenReturn(Optional.of(evidence)); - DispatchResult account = dispatch(interceptor, service, ACCOUNT_URI); - assertThat(account.observer().failure).isNull(); - assertThat(account.observer().completed).isTrue(); - assertThat(account.observer().response.getEvidenceDigest()) - .isEqualTo(evidence.evidenceDigest()); - assertThat(account.handlerDispatched()).isTrue(); - verify(repository).read(REQUEST_ID, "test"); + DispatchResult account = dispatch(interceptor, service, ACCOUNT_URI); + assertThat(account.observer().failure).isNull(); + assertThat(account.observer().completed).isTrue(); + assertThat(account.observer().response.getEvidenceDigest()) + .isEqualTo(evidence.evidenceDigest()); + assertThat(account.handlerDispatched()).isTrue(); + verify(repository).read(REQUEST_ID, "test"); - GameTenantCreationRepository gameSessionRepository = - mock(GameTenantCreationRepository.class); - TenantIdentityGrpcService gameSessionService = - new TenantIdentityGrpcService(gameSessionRepository, "test"); - when(gameSessionRepository.read(REQUEST_ID, "test")).thenReturn(Optional.of(evidence)); + GameTenantCreationRepository gameSessionRepository = mock(GameTenantCreationRepository.class); + TenantIdentityGrpcService gameSessionService = + new TenantIdentityGrpcService(gameSessionRepository, "test"); + when(gameSessionRepository.read(REQUEST_ID, "test")).thenReturn(Optional.of(evidence)); - DispatchResult gameSession = dispatch(interceptor, gameSessionService, GAME_SESSION_URI); - assertThat(gameSession.observer().failure).isNull(); - assertThat(gameSession.observer().completed).isTrue(); - assertThat(gameSession.observer().response.getEvidenceDigest()) - .isEqualTo(evidence.evidenceDigest()); - assertThat(gameSession.handlerDispatched()).isTrue(); - verify(gameSessionRepository).read(REQUEST_ID, "test"); + DispatchResult gameSession = dispatch(interceptor, gameSessionService, GAME_SESSION_URI); + assertThat(gameSession.observer().failure).isNull(); + assertThat(gameSession.observer().completed).isTrue(); + assertThat(gameSession.observer().response.getEvidenceDigest()) + .isEqualTo(evidence.evidenceDigest()); + assertThat(gameSession.handlerDispatched()).isTrue(); + verify(gameSessionRepository).read(REQUEST_ID, "test"); - GameTenantCreationRepository unauthorizedRepository = - mock(GameTenantCreationRepository.class); - TenantIdentityGrpcService unauthorizedService = - new TenantIdentityGrpcService(unauthorizedRepository, "test"); - DispatchResult unauthorized = - dispatch( - interceptor, - unauthorizedService, - "spiffe://firemud/ns/test/sa/entity-management-service"); - assertThat(unauthorized.observer().failure).isEqualTo(Status.Code.PERMISSION_DENIED); - assertThat(unauthorized.observer().response).isNull(); - assertThat(unauthorized.observer().completed).isFalse(); - assertThat(unauthorized.handlerDispatched()).isTrue(); - verifyNoInteractions(unauthorizedRepository); - }); + GameTenantCreationRepository unauthorizedRepository = + mock(GameTenantCreationRepository.class); + TenantIdentityGrpcService unauthorizedService = + new TenantIdentityGrpcService(unauthorizedRepository, "test"); + DispatchResult unauthorized = + dispatch( + interceptor, + unauthorizedService, + "spiffe://firemud/ns/test/sa/entity-management-service"); + assertThat(unauthorized.observer().failure).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(unauthorized.observer().response).isNull(); + assertThat(unauthorized.observer().completed).isFalse(); + assertThat(unauthorized.handlerDispatched()).isTrue(); + verifyNoInteractions(unauthorizedRepository); + }); } @Test @@ -186,26 +184,23 @@ private static void withConfiguredInterceptor(Consumer act AutoConfigurations.of( ConfigurationPropertiesAutoConfiguration.class, CommonSecurityAutoConfiguration.class)) - .withInitializer( - context -> { - try { - context - .getEnvironment() - .getPropertySources() - .addFirst(propertySource("application.yml")); - } catch (IOException exception) { - throw new IllegalStateException( - "Could not load Game Design configuration", exception); - } - }) + .withInitializer(context -> { + try { + context + .getEnvironment() + .getPropertySources() + .addFirst(propertySource("application.yml")); + } catch (IOException exception) { + throw new IllegalStateException("Could not load Game Design configuration", exception); + } + }) .withPropertyValues("firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234") - .run( - context -> { - assertThat(context).hasSingleBean(AuthTokenInterceptor.class); - assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) - .containsExactlyElementsOf(ALLOWLISTED_METHODS); - action.accept(context.getBean(AuthTokenInterceptor.class)); - }); + .run(context -> { + assertThat(context).hasSingleBean(AuthTokenInterceptor.class); + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .containsExactlyElementsOf(ALLOWLISTED_METHODS); + action.accept(context.getBean(AuthTokenInterceptor.class)); + }); } private static DispatchResult dispatch( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AccountAuthorizedTenantCreationServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AccountAuthorizedTenantCreationServiceTest.java index 472d00aa68..fef4dd8b40 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AccountAuthorizedTenantCreationServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/AccountAuthorizedTenantCreationServiceTest.java @@ -123,12 +123,11 @@ void changedCandidateDigestIsRejectedBeforeOwnerReadsOrAccountCallback() { "sha256:" + "c".repeat(64), ACCOUNT_DIGEST); - assertThatThrownBy( - () -> - service() - .create( - new AccountAuthorizedTenantCreationService.CandidateRequest( - CREATE_ID, changed, SOURCE_KEY, NAME, DESCRIPTION))) + assertThatThrownBy(() -> + service() + .create( + new AccountAuthorizedTenantCreationService.CandidateRequest( + CREATE_ID, changed, SOURCE_KEY, NAME, DESCRIPTION))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact Account original request digest"); verifyNoInteractions( @@ -180,14 +179,13 @@ void transientReadFailuresRecoverBeforeExactlyOneOwnerWrite() { VerifiedAuthorization authorization = prepareFreshCreation(); AtomicInteger attempts = new AtomicInteger(); when(authorizationClient.resolveCurrent(BINDING)) - .thenAnswer( - invocation -> { - assertOutsideSql(); - int attempt = attempts.incrementAndGet(); - if (attempt == 1) throw Status.UNAVAILABLE.asRuntimeException(); - if (attempt == 2) throw Status.DEADLINE_EXCEEDED.asRuntimeException(); - return authorization; - }); + .thenAnswer(invocation -> { + assertOutsideSql(); + int attempt = attempts.incrementAndGet(); + if (attempt == 1) throw Status.UNAVAILABLE.asRuntimeException(); + if (attempt == 2) throw Status.DEADLINE_EXCEEDED.asRuntimeException(); + return authorization; + }); assertThat(service().create(candidate())).isEqualTo(receipt()); assertThat(retryDelays) @@ -292,10 +290,8 @@ public void resolveCurrentTenantCreationAuthorization( .when(client) .resolveCurrent(BINDING); when(dispatchRepository.readCommitted(BINDING)) - .thenAnswer( - invocation -> - Optional.of( - new AuthorizedDispatch(BINDING, successfulReadId.get(), validBefore))); + .thenAnswer(invocation -> + Optional.of(new AuthorizedDispatch(BINDING, successfulReadId.get(), validBefore))); try (var incoming = Context.current().withDeadlineAfter(5, TimeUnit.SECONDS, scheduler)) { incoming.run(() -> assertThat(service(client).create(candidate())).isEqualTo(receipt())); @@ -328,11 +324,10 @@ public void resolveCurrentTenantCreationAuthorization( void transientReadExhaustionWithoutIncomingDeadlineStopsAfterThreeAttemptsBeforeWrites() { StatusRuntimeException unavailable = Status.UNAVAILABLE.asRuntimeException(); when(authorizationClient.resolveCurrent(BINDING)) - .thenAnswer( - invocation -> { - assertOutsideSql(); - throw unavailable; - }); + .thenAnswer(invocation -> { + assertOutsideSql(); + throw unavailable; + }); assertThatThrownBy(() -> service().create(candidate())).isSameAs(unavailable); @@ -403,12 +398,11 @@ public long nanoTime() { }); StatusRuntimeException unavailable = Status.UNAVAILABLE.asRuntimeException(); when(authorizationClient.resolveCurrent(BINDING)) - .thenAnswer( - invocation -> { - assertOutsideSql(); - nanos.set(TimeUnit.MILLISECONDS.toNanos(1500)); - throw unavailable; - }); + .thenAnswer(invocation -> { + assertOutsideSql(); + nanos.set(TimeUnit.MILLISECONDS.toNanos(1500)); + throw unavailable; + }); try (var incoming = Context.current().withDeadline(deadline, scheduler)) { incoming.run( () -> assertThatThrownBy(() -> service().create(candidate())).isSameAs(unavailable)); @@ -422,12 +416,11 @@ void incomingCancellationDuringReadPreventsRetry() { StatusRuntimeException unavailable = Status.UNAVAILABLE.asRuntimeException(); try (var incoming = Context.current().withCancellation()) { when(authorizationClient.resolveCurrent(BINDING)) - .thenAnswer( - invocation -> { - assertOutsideSql(); - incoming.cancel(null); - throw unavailable; - }); + .thenAnswer(invocation -> { + assertOutsideSql(); + incoming.cancel(null); + throw unavailable; + }); incoming.run( () -> assertThatThrownBy(() -> service().create(candidate())).isSameAs(unavailable)); verify(authorizationClient).resolveCurrent(BINDING); @@ -524,11 +517,10 @@ void cancellationDuringDelayPreventsAnotherRead() { void interruptionDuringReadPreventsDelayAndAnotherReadWithoutClearingFlag() { StatusRuntimeException unavailable = Status.UNAVAILABLE.asRuntimeException(); when(authorizationClient.resolveCurrent(BINDING)) - .thenAnswer( - invocation -> { - Thread.currentThread().interrupt(); - throw unavailable; - }); + .thenAnswer(invocation -> { + Thread.currentThread().interrupt(); + throw unavailable; + }); try { assertThatThrownBy(() -> service().create(candidate())).isSameAs(unavailable); assertThat(Thread.currentThread().isInterrupted()).isTrue(); @@ -589,11 +581,10 @@ public long nanoTime() { }); StatusRuntimeException unavailable = Status.UNAVAILABLE.asRuntimeException(); when(authorizationClient.resolveCurrent(BINDING)) - .thenAnswer( - invocation -> { - assertOutsideSql(); - throw unavailable; - }); + .thenAnswer(invocation -> { + assertOutsideSql(); + throw unavailable; + }); try (var incoming = Context.current().withDeadline(deadline, scheduler)) { incoming.run( () -> assertThatThrownBy(() -> service().create(candidate())).isSameAs(unavailable)); @@ -633,11 +624,10 @@ private VerifiedAuthorization prepareFreshCreation() { .thenReturn( Optional.of(new AuthorizedDispatch(BINDING, AUTHORIZATION_READ_ID, validBefore))); when(transactionManager.getTransaction(any(TransactionDefinition.class))) - .thenAnswer( - invocation -> { - TransactionSynchronizationManager.setActualTransactionActive(true); - return mock(TransactionStatus.class); - }); + .thenAnswer(invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + return mock(TransactionStatus.class); + }); doAnswer( invocation -> { TransactionSynchronizationManager.setActualTransactionActive(false); @@ -744,10 +734,9 @@ void explicitClosureUsesExistingIdentityLockedOwnerWithoutCreationOrCurrentAutho service().closeOriginal(BINDING); verify(transactionManager) .getTransaction( - org.mockito.ArgumentMatchers.argThat( - definition -> - definition.getIsolationLevel() == TransactionDefinition.ISOLATION_READ_COMMITTED - && !definition.isReadOnly())); + org.mockito.ArgumentMatchers.argThat(definition -> + definition.getIsolationLevel() == TransactionDefinition.ISOLATION_READ_COMMITTED + && !definition.isReadOnly())); verify(dispatchRepository).applyLocalWriteTimeouts(); verify(outcomeRepository).closeNotCreatedLocked(BINDING); verifyNoInteractions(authorizationClient, creationRepository); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java index d296297cae..17b2790016 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/CompleteLaunchBindingServiceImplTest.java @@ -1096,24 +1096,23 @@ private PublishedReleaseBundleDto selectedFullBundle( private List selectorParticipants( WorldPublishedStartLocationEvidence selector) { return PublishedWorldSelectorFixtures.participants(VERSION_ID, selector).stream() - .map( - participant -> - PublishParticipantKey.GAME_DESIGN_CONTROL_PLANE - .name() - .equals(participant.participantKey()) - ? new PublishParticipantDigestDto( + .map(participant -> + PublishParticipantKey.GAME_DESIGN_CONTROL_PLANE + .name() + .equals(participant.participantKey()) + ? new PublishParticipantDigestDto( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( participant.participantKey(), - participant.scopeValue(), - participant.baseVersionId(), - participant.appliedCommitId(), - participant.contentDigest(), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - participant.participantKey(), - AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - participant.abilitySchemaDigest(), - participant.errorCode(), - participant.errorMessage()) - : participant) + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage()) + : participant) .toList(); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImplTest.java index 8c12d157f6..e8693ada92 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/GameAuthoredHelpTopicServiceImplTest.java @@ -84,12 +84,11 @@ void normalizesPersistedTopicAndRejectsDuplicateAliases() { assertThat(savedCaptor.getValue().getCanonicalTopicKey()).isEqualTo("movement"); assertThat(result.canonicalTopicId()).isEqualTo("movement"); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.putTopic( - "42", - 7L, - new HelpTopicDto("look", "Look", "Inspect.", List.of("SEE", "see"), false))) + .isThrownBy(() -> + service.putTopic( + "42", + 7L, + new HelpTopicDto("look", "Look", "Inspect.", List.of("SEE", "see"), false))) .withMessage("aliases must be unique after normalization"); } @@ -103,12 +102,11 @@ void rejectsAliasThatConflictsWithAnotherCanonicalTopic() { when(repository.findByScopeAndCanonicalKey("42", 7L, "move")).thenReturn(Optional.of(existing)); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.putTopic( - "42", - 7L, - new HelpTopicDto("travel", "Travel", "Walk onward.", List.of("move"), true))) + .isThrownBy(() -> + service.putTopic( + "42", + 7L, + new HelpTopicDto("travel", "Travel", "Walk onward.", List.of("move"), true))) .withMessage("alias conflicts with an existing canonicalTopicId"); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java index 06813808f5..b73218bf54 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/LaunchDescriptorServiceImplTest.java @@ -278,21 +278,20 @@ private PublishedReleaseBundleDto selectorBundle( if (retainControlPlaneDigestSchema) { participants = participants.stream() - .map( - participant -> - "GAME_DESIGN_CONTROL_PLANE".equals(participant.participantKey()) - ? new net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto( - participant.participantKey(), - participant.scopeValue(), - participant.baseVersionId(), - participant.appliedCommitId(), - participant.contentDigest(), - net.firedevops.firemud.common.gamedesign - .AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION, - participant.abilitySchemaDigest(), - participant.errorCode(), - participant.errorMessage()) - : participant) + .map(participant -> + "GAME_DESIGN_CONTROL_PLANE".equals(participant.participantKey()) + ? new net.firedevops.firemud.gamedesign.dto.PublishParticipantDigestDto( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + net.firedevops.firemud.common.gamedesign + .AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION, + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage()) + : participant) .toList(); } return new PublishedReleaseBundleDto( @@ -341,12 +340,11 @@ void resolveLaunchDescriptorPersistsCanonicalBindingAndResolvedRelease() { stubSuccessfulLaunch(request, 7L, 11L); AtomicReference inserted = new AtomicReference<>(); when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) - .thenAnswer( - invocation -> { - LaunchDescriptor descriptor = invocation.getArgument(0); - inserted.set(descriptor); - return descriptor; - }); + .thenAnswer(invocation -> { + LaunchDescriptor descriptor = invocation.getArgument(0); + inserted.set(descriptor); + return descriptor; + }); var resolved = service.resolveLaunchDescriptor(request); @@ -418,12 +416,11 @@ void validRequestedRuntimeFlagsPreserveOriginalJsonAndRequestDigest() { stubSuccessfulLaunch(request, 7L, 11L); AtomicReference inserted = new AtomicReference<>(); when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) - .thenAnswer( - invocation -> { - LaunchDescriptor descriptor = invocation.getArgument(0); - inserted.set(descriptor); - return descriptor; - }); + .thenAnswer(invocation -> { + LaunchDescriptor descriptor = invocation.getArgument(0); + inserted.set(descriptor); + return descriptor; + }); var resolved = service.resolveLaunchDescriptor(request); @@ -459,12 +456,11 @@ void exactRetryReturnsStoredResultWithoutReadingChangedTemplateDefaultsVersionOr when(launchDescriptorRepository.findByPrivateRequest(PRIVATE_SOURCE_TENANT_KEY, "cp-retry")) .thenReturn(Optional.empty()); when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) - .thenAnswer( - invocation -> { - LaunchDescriptor descriptor = invocation.getArgument(0); - stored.set(descriptor); - return descriptor; - }); + .thenAnswer(invocation -> { + LaunchDescriptor descriptor = invocation.getArgument(0); + stored.set(descriptor); + return descriptor; + }); var first = service.resolveLaunchDescriptor(request); when(template.getDefaultVersionId()).thenReturn(8L); @@ -899,12 +895,11 @@ void missingOpaqueBundleReferenceDeniesCreationAndExactRetryWithoutSynthesizing( PRIVATE_SOURCE_TENANT_KEY, request.controlPlaneRequestId())) .thenReturn(Optional.empty()); when(launchDescriptorRepository.insertImmutable(any(LaunchDescriptor.class))) - .thenAnswer( - invocation -> { - LaunchDescriptor descriptor = invocation.getArgument(0); - stored.set(descriptor); - return descriptor; - }); + .thenAnswer(invocation -> { + LaunchDescriptor descriptor = invocation.getArgument(0); + stored.set(descriptor); + return descriptor; + }); IllegalArgumentException first = assertThrows( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java index 4ae810148b..29ad54ac02 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java @@ -31,10 +31,9 @@ class PublishedReleaseBundleContractTest { @Test void exactRepairAcceptsCompleteSelectorV2Bundle() throws Exception { WorldPublishedStartLocationEvidence selector = selectorEvidence(); - assertDoesNotThrow( - () -> - PublishedReleaseBundleContract.requireExactRepairMatch( - selectorBundle(selector, selectorParticipants(selector)), exportedManifest)); + assertDoesNotThrow(() -> + PublishedReleaseBundleContract.requireExactRepairMatch( + selectorBundle(selector, selectorParticipants(selector)), exportedManifest)); } @Test @@ -223,10 +222,9 @@ void exactRepairRetainsManifestSchemaDigestHashAndOrderedKeyChecks() throws Exce @Test void exactRepairContinuesToAcceptV1AndRejectV3() { - assertDoesNotThrow( - () -> - PublishedReleaseBundleContract.requireExactRepairMatch( - bundle("v1", null, List.of()), exportedManifest)); + assertDoesNotThrow(() -> + PublishedReleaseBundleContract.requireExactRepairMatch( + bundle("v1", null, List.of()), exportedManifest)); IllegalStateException unsupported = assertThrows( @@ -349,22 +347,21 @@ private static WorldPublishedStartLocationEvidence selectorEvidence(int digestSc private static List selectorParticipants( WorldPublishedStartLocationEvidence selector) { return PublishedWorldSelectorFixtures.participants(VERSION_ID, selector).stream() - .map( - participant -> - "GAME_DESIGN_CONTROL_PLANE".equals(participant.participantKey()) - ? new PublishParticipantDigestDto( + .map(participant -> + "GAME_DESIGN_CONTROL_PLANE".equals(participant.participantKey()) + ? new PublishParticipantDigestDto( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( participant.participantKey(), - participant.scopeValue(), - participant.baseVersionId(), - participant.appliedCommitId(), - participant.contentDigest(), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - participant.participantKey(), - AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - participant.abilitySchemaDigest(), - participant.errorCode(), - participant.errorMessage()) - : participant) + AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage()) + : participant) .toList(); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java index 612b022b33..3cdee0044f 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java @@ -54,15 +54,14 @@ class PublishedReleaseBundleServiceImplTest { when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) .thenReturn(List.of(validCommandDefinition())); when(repository.save(any(PublishedReleaseBundle.class))) - .thenAnswer( - invocation -> { - PublishedReleaseBundle saved = invocation.getArgument(0); - saved.setId(11L); - saved.setPublishedReleaseBundleRef("owner-release"); - when(repository.findByTenantIdAndVersionId("tenant-1", 7L)) - .thenReturn(Optional.of(saved)); - return saved; - }); + .thenAnswer(invocation -> { + PublishedReleaseBundle saved = invocation.getArgument(0); + saved.setId(11L); + saved.setPublishedReleaseBundleRef("owner-release"); + when(repository.findByTenantIdAndVersionId("tenant-1", 7L)) + .thenReturn(Optional.of(saved)); + return saved; + }); var first = service.createFullVersionBundle( selectorVersion(), @@ -92,15 +91,14 @@ class PublishedReleaseBundleServiceImplTest { org.mockito.Mockito.verify(repository) .requireSelectedCommandDefinitions(any(), any(), any(), any()); org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); - assertThatThrownBy( - () -> - service.createFullVersionBundle( - selectorVersion(), - "publish-workflow", - emptyManifest(), - "changed", - participants, - evidence)) + assertThatThrownBy(() -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "changed", + participants, + evidence)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("IDEMPOTENCY_CONFLICT"); PublishedReleaseBundleContract.requireSelectedFullBinding(first); @@ -165,35 +163,32 @@ void selectedFullV4RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChanged var participants = PublishedWorldSelectorFixtures.participants( 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION); - assertThatThrownBy( - () -> - service.createFullVersionBundle( - selectorVersion(), - "publish-workflow", - emptyManifest(), - "genrev-1", - participants, - null)) + assertThatThrownBy(() -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants, + null)) .isInstanceOf(NullPointerException.class); - assertThatThrownBy( - () -> - service.createFullVersionBundle( - selectorVersion(), - "wrong-workflow", - emptyManifest(), - "genrev-1", - participants, - evidence)) + assertThatThrownBy(() -> + service.createFullVersionBundle( + selectorVersion(), + "wrong-workflow", + emptyManifest(), + "genrev-1", + participants, + evidence)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - service.createFullVersionBundle( - selectorVersion(), - "publish-workflow", - emptyManifest(), - "genrev-1", - participants.subList(0, 4), - evidence)) + assertThatThrownBy(() -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants.subList(0, 4), + evidence)) .isInstanceOf(IllegalArgumentException.class); var world = participants.getFirst(); var changed = new java.util.ArrayList<>(participants); @@ -209,28 +204,24 @@ void selectedFullV4RejectsMissingEvidenceWrongWorkflowIncompleteOwnersAndChanged null, null, null)); - assertThatThrownBy( - () -> - service.createFullVersionBundle( - selectorVersion(), - "publish-workflow", - emptyManifest(), - "genrev-1", - changed, - evidence)) + assertThatThrownBy(() -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + changed, + evidence)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - service.createFullVersionBundle( - selectorVersion(), - "publish-workflow", - emptyManifest(), - "genrev-1", - PublishedWorldSelectorFixtures.participants( - 7L, - evidence, - AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - evidence)) + assertThatThrownBy(() -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + PublishedWorldSelectorFixtures.participants( + 7L, evidence, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + evidence)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Selected-full"); org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); @@ -257,15 +248,14 @@ void selectedFullV4RejectsEveryMixedParticipantSchemaBeforeWrite() throws Except participant.abilitySchemaDigest(), participant.errorCode(), participant.errorMessage())); - assertThatThrownBy( - () -> - service.createFullVersionBundle( - selectorVersion(), - "publish-workflow", - emptyManifest(), - "genrev-1", - mixed, - evidence)) + assertThatThrownBy(() -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + mixed, + evidence)) .as("mixed profile for %s", participant.participantKey()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Selected-full release requires the exact 4/3/1/6/2"); @@ -279,18 +269,17 @@ void selectedFullV4RequiresSelectedSourceCaptureBeforeBundleWrite() throws Excep when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) .thenThrow(new IllegalStateException("SELECTED_SOURCE_CAPTURE_UNAVAILABLE")); - assertThatThrownBy( - () -> - service.createFullVersionBundle( - selectorVersion(), - "publish-workflow", - emptyManifest(), - "genrev-1", - PublishedWorldSelectorFixtures.participants( - 7L, - evidence, - AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION), - evidence)) + assertThatThrownBy(() -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + PublishedWorldSelectorFixtures.participants( + 7L, + evidence, + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION), + evidence)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("SELECTED_SOURCE_CAPTURE_UNAVAILABLE"); org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); @@ -307,18 +296,17 @@ void historicalReleaseNeverGainsSelectorAndCorruptedStoredCarrierFailsReadback() assertNull( service.getPublishedReleaseBundle("tenant-1", 7L).worldPublishedStartLocationEvidence()); var evidence = selectorEvidence(); - assertThatThrownBy( - () -> - service.createFullVersionBundle( - selectorVersion(), - "publish-workflow", - emptyManifest(), - "genrev-1", - PublishedWorldSelectorFixtures.participants( - 7L, - evidence, - AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION), - evidence)) + assertThatThrownBy(() -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + PublishedWorldSelectorFixtures.participants( + 7L, + evidence, + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION), + evidence)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("selector-ineligible"); retained.setWorldPublishedStartLocationEvidenceJson( @@ -380,10 +368,9 @@ void setUp() { @Test void legacyFullVersionCannotCreateV1BundleFromMutableRevisions() { - assertThatThrownBy( - () -> - service.createFullVersionBundle( - version(), "workflow-1", logoManifest(), "genrev-1", List.of())) + assertThatThrownBy(() -> + service.createFullVersionBundle( + version(), "workflow-1", logoManifest(), "genrev-1", List.of())) .isInstanceOf(IllegalStateException.class) .hasMessageStartingWith("PUBLISH_SELECTION_REQUIRED"); org.mockito.Mockito.verifyNoInteractions(repository, versionRepository); @@ -517,15 +504,14 @@ void selectedBundleEntryPointRequiresCapturedCommandAndPolicySources() throws Ex when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) .thenThrow(new IllegalStateException("SELECTED_SOURCE_CAPTURE_UNAVAILABLE")); - assertThatThrownBy( - () -> - service.createFullVersionBundle( - selectorVersion(), - "publish-workflow", - emptyManifest(), - "genrev-1", - participants, - evidence)) + assertThatThrownBy(() -> + service.createFullVersionBundle( + selectorVersion(), + "publish-workflow", + emptyManifest(), + "genrev-1", + participants, + evidence)) .isInstanceOf(IllegalStateException.class) .hasMessage("SELECTED_SOURCE_CAPTURE_UNAVAILABLE"); org.mockito.Mockito.verify(repository, org.mockito.Mockito.never()).save(any()); @@ -555,13 +541,12 @@ void selectedFullVersionBundlePersistsImmutableAttestation() throws Exception { when(repository.requireSelectedCommandDefinitions(any(), any(), any(), any())) .thenReturn(List.of(validCommandDefinition())); when(repository.save(any(PublishedReleaseBundle.class))) - .thenAnswer( - invocation -> { - PublishedReleaseBundle saved = invocation.getArgument(0); - saved.setId(11L); - saved.setPublishedReleaseBundleRef("owner-issued-reference-11"); - return saved; - }); + .thenAnswer(invocation -> { + PublishedReleaseBundle saved = invocation.getArgument(0); + saved.setId(11L); + saved.setPublishedReleaseBundleRef("owner-issued-reference-11"); + return saved; + }); var dto = service.createFullVersionBundle( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java index 42f442ee2e..106ee0450a 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RunOwnedFixtureAuthoredWorldOwnerReadGrpcServiceTest.java @@ -44,43 +44,39 @@ void fixedServicesRemainUnregisteredByDefaultAndUseExistingServiceIdsWhenEnabled .withUserConfiguration( RunOwnedFixtureAuthoredWorldSourceReadGrpcService.class, RunOwnedFixtureAuthoredWorldVersionStateGrpcService.class); - runner.run( - context -> { + runner.run(context -> { + assertThat(context).doesNotHaveBean(RunOwnedFixtureAuthoredWorldSourceReadGrpcService.class); + assertThat(context) + .doesNotHaveBean(RunOwnedFixtureAuthoredWorldVersionStateGrpcService.class); + }); + runner + .withPropertyValues("FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false") + .run(context -> { assertThat(context) .doesNotHaveBean(RunOwnedFixtureAuthoredWorldSourceReadGrpcService.class); assertThat(context) .doesNotHaveBean(RunOwnedFixtureAuthoredWorldVersionStateGrpcService.class); }); - runner - .withPropertyValues("FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false") - .run( - context -> { - assertThat(context) - .doesNotHaveBean(RunOwnedFixtureAuthoredWorldSourceReadGrpcService.class); - assertThat(context) - .doesNotHaveBean(RunOwnedFixtureAuthoredWorldVersionStateGrpcService.class); - }); runner .withPropertyValues( "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=true", "firemud.grpc.workload-namespace=dev") - .run( - context -> { - assertThat( - context - .getBean(RunOwnedFixtureAuthoredWorldSourceReadGrpcService.class) - .bindService() - .getServiceDescriptor() - .getName()) - .isEqualTo("gamedesign.v1.AuthoredWorldSourceReadService"); - assertThat( - context - .getBean(RunOwnedFixtureAuthoredWorldVersionStateGrpcService.class) - .bindService() - .getServiceDescriptor() - .getName()) - .isEqualTo("gamedesign.v1.AuthoredWorldVersionStateService"); - }); + .run(context -> { + assertThat( + context + .getBean(RunOwnedFixtureAuthoredWorldSourceReadGrpcService.class) + .bindService() + .getServiceDescriptor() + .getName()) + .isEqualTo("gamedesign.v1.AuthoredWorldSourceReadService"); + assertThat( + context + .getBean(RunOwnedFixtureAuthoredWorldVersionStateGrpcService.class) + .bindService() + .getServiceDescriptor() + .getName()) + .isEqualTo("gamedesign.v1.AuthoredWorldVersionStateService"); + }); verifyNoInteractions(repository, transactions, authorization); } @@ -202,15 +198,13 @@ void authorizedStorageFailuresReachRepositoriesAndTransactions() { } var sourceFailure = new AtomicReference(); var versionFailure = new AtomicReference(); - peer.run( - () -> { - new RunOwnedFixtureAuthoredWorldSourceReadGrpcService( - authorization, repository, "dev") - .resolveAuthoredWorldSource(sourceRequest, refusingObserver(sourceFailure)); - new RunOwnedFixtureAuthoredWorldVersionStateGrpcService( - authorization, transactions, repository, "dev") - .getAuthoredWorldVersionState(versionRequest, refusingObserver(versionFailure)); - }); + peer.run(() -> { + new RunOwnedFixtureAuthoredWorldSourceReadGrpcService(authorization, repository, "dev") + .resolveAuthoredWorldSource(sourceRequest, refusingObserver(sourceFailure)); + new RunOwnedFixtureAuthoredWorldVersionStateGrpcService( + authorization, transactions, repository, "dev") + .getAuthoredWorldVersionState(versionRequest, refusingObserver(versionFailure)); + }); assertThat(Status.fromThrowable(sourceFailure.get()).getCode()) .as("authorized source storage %s", failure.exception().getClass().getSimpleName()) .isEqualTo(failure.expectedCode()); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java index 834647b114..c09d067e9c 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java @@ -33,10 +33,9 @@ void rejectsOutOfRangeCommandHistoryRetentionBeforePersistence(int maxEntries) { new ScopedSettingsOverrides.CommandHistoryOverride(maxEntries)); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.putDomainOverride( - "demo", 7L, ScopedSettingsOverrides.SettingsDomain.COMMAND_HISTORY, overrides)) + .isThrownBy(() -> + service.putDomainOverride( + "demo", 7L, ScopedSettingsOverrides.SettingsDomain.COMMAND_HISTORY, overrides)) .withMessage("Command history maxEntries must be between 1 and 20"); verifyNoInteractions(repository); @@ -55,13 +54,9 @@ void rejectsAnEmptyCommandCapabilitiesOverrideBeforePersistence() { new ScopedSettingsOverrides.CommandCapabilitiesOverride(null, null, null, null)); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.putDomainOverride( - "demo", - 7L, - ScopedSettingsOverrides.SettingsDomain.COMMAND_CAPABILITIES, - overrides)) + .isThrownBy(() -> + service.putDomainOverride( + "demo", 7L, ScopedSettingsOverrides.SettingsDomain.COMMAND_CAPABILITIES, overrides)) .withMessage("Command capabilities override must set at least one capability"); verifyNoInteractions(repository); @@ -82,10 +77,9 @@ void rejectsNonPositiveReconnectTranscriptEntryLimitsBeforePersistence(int maxEn null); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.putDomainOverride( - "demo", 7L, ScopedSettingsOverrides.SettingsDomain.RECONNECTION, overrides)) + .isThrownBy(() -> + service.putDomainOverride( + "demo", 7L, ScopedSettingsOverrides.SettingsDomain.RECONNECTION, overrides)) .withMessage("Reconnection buffer maxEntries must be positive"); verifyNoInteractions(repository); @@ -105,10 +99,9 @@ void rejectsExplicitReconnectByteBoundsBeforePersistence() { null); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.putDomainOverride( - "demo", null, ScopedSettingsOverrides.SettingsDomain.RECONNECTION, overrides)) + .isThrownBy(() -> + service.putDomainOverride( + "demo", null, ScopedSettingsOverrides.SettingsDomain.RECONNECTION, overrides)) .withMessage("Reconnection buffer hardMaxBytes must be at least softMaxBytes"); verifyNoInteractions(repository); @@ -128,10 +121,9 @@ void rejectsSparseTenantByteBoundsWithoutAuthoritativeCounterpartBeforePersisten null); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.putDomainOverride( - "demo", null, ScopedSettingsOverrides.SettingsDomain.RECONNECTION, overrides)) + .isThrownBy(() -> + service.putDomainOverride( + "demo", null, ScopedSettingsOverrides.SettingsDomain.RECONNECTION, overrides)) .withMessage( "Reconnection buffer softMaxBytes and hardMaxBytes must be set together " + "or inherited from a complete tenant override"); @@ -170,10 +162,9 @@ void rejectsSparseGameInstanceByteBoundsAgainstTenantInheritedValuesBeforePersis null); assertThatIllegalArgumentException() - .isThrownBy( - () -> - gameInstanceService.putDomainOverride( - "demo", 7L, ScopedSettingsOverrides.SettingsDomain.RECONNECTION, overrides)) + .isThrownBy(() -> + gameInstanceService.putDomainOverride( + "demo", 7L, ScopedSettingsOverrides.SettingsDomain.RECONNECTION, overrides)) .withMessage("Reconnection buffer hardMaxBytes must be at least softMaxBytes"); Mockito.verify(repository, Mockito.never()).save(Mockito.any()); @@ -277,10 +268,9 @@ void rejectsTenantPutThatInvalidatesAnExistingSparseGameInstanceChild() { null); assertThatIllegalArgumentException() - .isThrownBy( - () -> - tenantService.putDomainOverride( - "demo", null, ScopedSettingsOverrides.SettingsDomain.RECONNECTION, overrides)) + .isThrownBy(() -> + tenantService.putDomainOverride( + "demo", null, ScopedSettingsOverrides.SettingsDomain.RECONNECTION, overrides)) .withMessage("Reconnection buffer hardMaxBytes must be at least softMaxBytes"); Mockito.verify(repository, Mockito.never()).save(Mockito.any()); @@ -306,10 +296,9 @@ void rejectsTenantDeleteThatLeavesAnExistingSparseGameInstanceChildUnresolved() new SettingsAuthorityServiceImpl(repository, objectMapper); assertThatIllegalArgumentException() - .isThrownBy( - () -> - tenantService.deleteDomainOverride( - "demo", null, ScopedSettingsOverrides.SettingsDomain.RECONNECTION)) + .isThrownBy(() -> + tenantService.deleteDomainOverride( + "demo", null, ScopedSettingsOverrides.SettingsDomain.RECONNECTION)) .withMessage( "Reconnection buffer softMaxBytes and hardMaxBytes must be set together " + "or inherited from a complete tenant override"); @@ -332,10 +321,9 @@ void rejectsSemanticallyEmptyNestedReconnectionOverridesBeforePersistence() { ScopedSettingsOverrides overrides = new ScopedSettingsOverrides(reconnection, null, null, null, null); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.putDomainOverride( - "demo", 7L, ScopedSettingsOverrides.SettingsDomain.RECONNECTION, overrides)) + .isThrownBy(() -> + service.putDomainOverride( + "demo", 7L, ScopedSettingsOverrides.SettingsDomain.RECONNECTION, overrides)) .withMessage("Reconnection override must set policy or buffer values"); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java index c71906e386..45ba298a39 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/TenantIdentityGrpcServiceTest.java @@ -113,10 +113,9 @@ void deniesMissingWrongServiceWrongNamespaceAndUnconfiguredPeerBeforeRead() { GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(ACCOUNT_URI).orElseThrow(); Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .run( - () -> - unconfigured.resolveFreshTenantCreation( - request(REQUEST_ID.toString(), REQUEST_DIGEST), observer)); + .run(() -> + unconfigured.resolveFreshTenantCreation( + request(REQUEST_ID.toString(), REQUEST_DIGEST), observer)); assertThat(status(observer)).isEqualTo(Status.Code.PERMISSION_DENIED); verifyNoInteractions(repository); } diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java index 4878462249..62aef8d924 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java @@ -153,32 +153,30 @@ void setUp() throws IOException { TENANT_ID, VERSION_NUMBER, snapshot.items().get(0))) .thenReturn(sourceBytes.clone()); when(s3Client.putObject(any(PutObjectRequest.class), any(RequestBody.class))) - .thenAnswer( - invocation -> { - PutObjectRequest request = invocation.getArgument(0); - RequestBody body = invocation.getArgument(1); - byte[] bytes; - try (InputStream input = body.contentStreamProvider().newStream()) { - bytes = input.readAllBytes(); - } - objectStore.put(request.key(), new StoredObject(bytes, request.contentType())); - return PutObjectResponse.builder().build(); - }); + .thenAnswer(invocation -> { + PutObjectRequest request = invocation.getArgument(0); + RequestBody body = invocation.getArgument(1); + byte[] bytes; + try (InputStream input = body.contentStreamProvider().newStream()) { + bytes = input.readAllBytes(); + } + objectStore.put(request.key(), new StoredObject(bytes, request.contentType())); + return PutObjectResponse.builder().build(); + }); when(s3Client.getObject(any(GetObjectRequest.class))) - .thenAnswer( - invocation -> { - GetObjectRequest request = invocation.getArgument(0); - StoredObject stored = objectStore.get(request.key()); - if (stored == null) { - throw new IllegalStateException("object is missing"); - } - return new ResponseInputStream<>( - GetObjectResponse.builder() - .contentType(stored.contentType()) - .contentLength((long) stored.bytes().length) - .build(), - new ByteArrayInputStream(stored.bytes())); - }); + .thenAnswer(invocation -> { + GetObjectRequest request = invocation.getArgument(0); + StoredObject stored = objectStore.get(request.key()); + if (stored == null) { + throw new IllegalStateException("object is missing"); + } + return new ResponseInputStream<>( + GetObjectResponse.builder() + .contentType(stored.contentType()) + .contentLength((long) stored.bytes().length) + .build(), + new ByteArrayInputStream(stored.bytes())); + }); candidateService = new VersionAssetExportCandidateServiceImpl( diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java index 3154858876..1f136d42dc 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java @@ -119,12 +119,11 @@ void setup() { when(worldProducerProvider.getIfAvailable()).thenReturn(worldProducer); when(worldProducer.reconcile( any(String.class), any(String.class), any(Long.class), any(String.class), any())) - .thenAnswer( - invocation -> { - org.junit.jupiter.api.Assertions.assertFalse( - ownerCommitActive.get(), "World handoff ran before owner commit returned"); - return null; - }); + .thenAnswer(invocation -> { + org.junit.jupiter.api.Assertions.assertFalse( + ownerCommitActive.get(), "World handoff ran before owner commit returned"); + return null; + }); when(publishedReleaseBundleService.findPublishedReleaseBundle( any(String.class), any(Long.class))) .thenReturn(Optional.empty()); @@ -134,20 +133,19 @@ void setup() { .thenReturn(capturedWorldPublicationEvidence); when(versionAssetArtifactService.stageExport( any(String.class), any(Long.class), any(Integer.class), any(String.class))) - .thenAnswer( - invocation -> - new VersionAssetArtifactStateDto( - invocation.getArgument(0), - invocation.getArgument(1), - invocation.getArgument(2), - "STAGED", - 1L, - null, - invocation.getArgument(3), - null, - null, - LocalDateTime.now(), - List.of())); + .thenAnswer(invocation -> + new VersionAssetArtifactStateDto( + invocation.getArgument(0), + invocation.getArgument(1), + invocation.getArgument(2), + "STAGED", + 1L, + null, + invocation.getArgument(3), + null, + null, + LocalDateTime.now(), + List.of())); org.mockito.Mockito.doAnswer( invocation -> { ownerCommitActive.set(true); @@ -490,13 +488,12 @@ void selectedSucceededReplayWrapsSelectionReadFailureDuringWorldHandoff() throws .getIfAvailable(); when(authoredSelections.readByPublishRequest( fixture.request().intent().canonicalTenantId(), fixture.request().publishRequestId())) - .thenAnswer( - invocation -> { - if (handoffStarted.get()) { - throw readFailure; - } - return Optional.of(fixture.reservation()); - }); + .thenAnswer(invocation -> { + if (handoffStarted.get()) { + throw readFailure; + } + return Optional.of(fixture.reservation()); + }); VersionPublishCommandServiceImpl.PendingReconciliationException thrown = assertThrows( @@ -2338,20 +2335,19 @@ void freshSelectedPublishRejectsLegacyOwnerVectorBeforeAssetEffects() throws Exc var legacySchemas = List.of(3, 2, 1, 5, 2); List legacyVector = java.util.stream.IntStream.range(0, fullVector.size()) - .mapToObj( - index -> { - var participant = fullVector.get(index); - return new PublishParticipantDigestDto( - participant.participantKey(), - participant.scopeValue(), - participant.baseVersionId(), - participant.appliedCommitId(), - participant.contentDigest(), - legacySchemas.get(index), - participant.abilitySchemaDigest(), - participant.errorCode(), - participant.errorMessage()); - }) + .mapToObj(index -> { + var participant = fullVector.get(index); + return new PublishParticipantDigestDto( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + legacySchemas.get(index), + participant.abilitySchemaDigest(), + participant.errorCode(), + participant.errorMessage()); + }) .toList(); when(publishGateService.collectSelectedFullVersionParticipantDigests( any(VersionDto.class), any(PublicationDigestRequestBinding.class), any(String.class))) @@ -3327,15 +3323,14 @@ private static ExportedAssetManifest exportedManifest(List usageKeys) { private static List artifactDigests(List usageKeys) { return usageKeys.stream() - .map( - usageKey -> - new PublishedArtifactDigest( - usageKey, - "BINARY", - "artifacts/sha256/" + ARTIFACT_DIGEST.substring("sha256:".length()), - ARTIFACT_DIGEST, - "manifest.json".equals(usageKey) ? "application/json" : "image/png", - 1)) + .map(usageKey -> + new PublishedArtifactDigest( + usageKey, + "BINARY", + "artifacts/sha256/" + ARTIFACT_DIGEST.substring("sha256:".length()), + ARTIFACT_DIGEST, + "manifest.json".equals(usageKey) ? "application/json" : "image/png", + 1)) .toList(); } diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/controller/EffectiveCommunicationSettingsController.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/controller/EffectiveCommunicationSettingsController.java index d5966d016e..88d2844d64 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/controller/EffectiveCommunicationSettingsController.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/controller/EffectiveCommunicationSettingsController.java @@ -25,17 +25,16 @@ public EffectiveCommunicationSettingsController( public ResponseEntity>> communication( @RequestParam(required = false) String tenantId, @RequestParam(required = false) String gameInstanceId) { - return GameLogicRequestReaders.withBadRequest( - () -> { - Long parsedTenantId = - GameLogicRequestReaders.requireOptionalPositiveLong(tenantId, "tenantId"); - Long parsedGameInstanceId = - GameLogicRequestReaders.requireOptionalPositiveLong(gameInstanceId, "gameInstanceId"); - EffectiveCommunicationSettingsResolver.ResolvedValue resolved = - settingsResolver.resolvedCommunication(parsedTenantId, parsedGameInstanceId); - return ResponseEntity.ok( - ApiResponse.success(new DomainSettings<>(resolved.effective(), resolved.sources()))); - }); + return GameLogicRequestReaders.withBadRequest(() -> { + Long parsedTenantId = + GameLogicRequestReaders.requireOptionalPositiveLong(tenantId, "tenantId"); + Long parsedGameInstanceId = + GameLogicRequestReaders.requireOptionalPositiveLong(gameInstanceId, "gameInstanceId"); + EffectiveCommunicationSettingsResolver.ResolvedValue resolved = + settingsResolver.resolvedCommunication(parsedTenantId, parsedGameInstanceId); + return ResponseEntity.ok( + ApiResponse.success(new DomainSettings<>(resolved.effective(), resolved.sources()))); + }); } public record DomainSettings(T effective, List sources) { diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java index 68a853bc43..5257284574 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationService.java @@ -201,16 +201,15 @@ private CommunicationAudience buildSayAudience( roomEntities.getEntitiesList().stream() .filter(entity -> entity.getEntityType() == EntityType.PLAYER) .filter(entity -> !entity.getEntityId().equals(speakerId)) - .forEach( - entity -> - recipientViews.add( - recipientView( - entity.getEntityId(), - entity.getDisplayName(), - CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET, - CommunicationPerception.COMMUNICATION_PERCEPTION_FULL_CONTENT, - speakerName, - ""))); + .forEach(entity -> + recipientViews.add( + recipientView( + entity.getEntityId(), + entity.getDisplayName(), + CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET, + CommunicationPerception.COMMUNICATION_PERCEPTION_FULL_CONTENT, + speakerName, + ""))); return new CommunicationAudience( delivered, buildNpcEchoes(roomEntities), @@ -323,18 +322,16 @@ private List resolveMetadataOnlyWhisperObservers( return roomEntities.getEntitiesList().stream() .filter(entity -> !entity.getEntityId().equals(speakerId)) .filter(entity -> !entity.getEntityId().equals(targetId)) - .filter( - entity -> - entity.getStateFlagsList().stream().anyMatch(OBSERVER_METADATA_ONLY_FLAG::equals)) - .map( - entity -> - recipientView( - entity.getEntityId(), - entity.getDisplayName(), - CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_OBSERVER, - CommunicationPerception.COMMUNICATION_PERCEPTION_METADATA_ONLY, - speakerName, - targetName)) + .filter(entity -> + entity.getStateFlagsList().stream().anyMatch(OBSERVER_METADATA_ONLY_FLAG::equals)) + .map(entity -> + recipientView( + entity.getEntityId(), + entity.getDisplayName(), + CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_OBSERVER, + CommunicationPerception.COMMUNICATION_PERCEPTION_METADATA_ONLY, + speakerName, + targetName)) .toList(); } diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookResultRenderer.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookResultRenderer.java index 855e07cf42..beb69b4519 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookResultRenderer.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookResultRenderer.java @@ -15,12 +15,11 @@ public String render(LookResult result) { out.append("Exits: "); out.append( result.getExitsList().stream() - .map( - e -> - e.getLabel() - + " (" - + (e.getDescription().isEmpty() ? "no description" : e.getDescription()) - + ")") + .map(e -> + e.getLabel() + + " (" + + (e.getDescription().isEmpty() ? "no description" : e.getDescription()) + + ")") .collect(Collectors.joining(", "))); out.append("\nEntities:\n"); for (var entity : result.getEntitiesList()) { diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java index 457478aa5c..c6b0068c91 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeService.java @@ -90,20 +90,17 @@ public GameLogicGameplayRuleIntakeTerminal retain( sourceEvidence.source().manifest().canonicalJson().getBytes(StandardCharsets.UTF_8); var retained = GameLogicGameplayRuleIntakeTerminal.retained(operation, sourceBytes, manifestBytes); - return ownerTransaction.execute( - status -> { - repository.lockOperation(authorization.operationId()); - var concurrent = repository.findTerminal(authorization.operationId()); - if (concurrent.isPresent()) return exactTerminal(concurrent.orElseThrow(), operation); - repository.insertTerminal(retained); - return repository - .findTerminal(authorization.operationId()) - .filter(value -> Arrays.equals(value.canonicalBytes(), retained.canonicalBytes())) - .orElseThrow( - () -> - new IllegalStateException( - "GL_GAMEPLAY_RULE_INTAKE_COMMIT_READBACK_MISMATCH")); - }); + return ownerTransaction.execute(status -> { + repository.lockOperation(authorization.operationId()); + var concurrent = repository.findTerminal(authorization.operationId()); + if (concurrent.isPresent()) return exactTerminal(concurrent.orElseThrow(), operation); + repository.insertTerminal(retained); + return repository + .findTerminal(authorization.operationId()) + .filter(value -> Arrays.equals(value.canonicalBytes(), retained.canonicalBytes())) + .orElseThrow( + () -> new IllegalStateException("GL_GAMEPLAY_RULE_INTAKE_COMMIT_READBACK_MISMATCH")); + }); } /** No value means there is no actual owner terminal; ABORTED is an explicit durable terminal. */ @@ -135,20 +132,18 @@ public GameLogicGameplayRuleIntakeTerminal abort( .asRuntimeException(); } - return ownerTransaction.execute( - status -> { - repository.lockOperation(authorization.operationId()); - var concurrent = repository.findTerminal(authorization.operationId()); - if (concurrent.isPresent()) return exactTerminal(concurrent.orElseThrow(), operation); - var aborted = GameLogicGameplayRuleIntakeTerminal.aborted(operation); - repository.insertTerminal(aborted); - return repository - .findTerminal(authorization.operationId()) - .filter(value -> Arrays.equals(value.canonicalBytes(), aborted.canonicalBytes())) - .orElseThrow( - () -> - new IllegalStateException("GL_GAMEPLAY_RULE_INTAKE_ABORT_READBACK_MISMATCH")); - }); + return ownerTransaction.execute(status -> { + repository.lockOperation(authorization.operationId()); + var concurrent = repository.findTerminal(authorization.operationId()); + if (concurrent.isPresent()) return exactTerminal(concurrent.orElseThrow(), operation); + var aborted = GameLogicGameplayRuleIntakeTerminal.aborted(operation); + repository.insertTerminal(aborted); + return repository + .findTerminal(authorization.operationId()) + .filter(value -> Arrays.equals(value.canonicalBytes(), aborted.canonicalBytes())) + .orElseThrow( + () -> new IllegalStateException("GL_GAMEPLAY_RULE_INTAKE_ABORT_READBACK_MISMATCH")); + }); } private GameLogicGameplayRuleIntakeOperation requestOperation( diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadService.java index a9638ec90d..ae119e1f61 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadService.java @@ -35,11 +35,10 @@ public GameLogicIntakeTerminalReadEvidence read( throw Status.FAILED_PRECONDITION.asRuntimeException(); var original = new GameLogicGameplayRuleIntakeOperation(namespace, request.binding()); var terminal = repository.findTerminal(request.binding().operationId()); - terminal.ifPresent( - value -> { - if (!Arrays.equals(original.canonicalBytes(), value.operation().canonicalBytes())) - throw Status.ALREADY_EXISTS.asRuntimeException(); - }); + terminal.ifPresent(value -> { + if (!Arrays.equals(original.canonicalBytes(), value.operation().canonicalBytes())) + throw Status.ALREADY_EXISTS.asRuntimeException(); + }); return new GameLogicIntakeTerminalReadEvidence(request, terminal); } diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadService.java index 6f5265daaf..c19e831cf4 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationSourceReadService.java @@ -57,11 +57,10 @@ public Result read(GameLogicPublicationSourceReadBinding binding) { GameLogicGameplayRuleIntakeTerminal terminal = repository .findTerminal(authorization.operationId()) - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription("Exact retained Game Logic source is unavailable") - .asRuntimeException()); + .orElseThrow(() -> + Status.FAILED_PRECONDITION + .withDescription("Exact retained Game Logic source is unavailable") + .asRuntimeException()); requireExactRetainedTerminal(terminal, requestedOperation, authorization); GameplayRuleSelectedSource retainedSource = diff --git a/services/game-logic-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GameLogicIntakeSettlementComposedPostgresIntegrationTest.java b/services/game-logic-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GameLogicIntakeSettlementComposedPostgresIntegrationTest.java index d9631aa2a7..b200b6e93f 100644 --- a/services/game-logic-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GameLogicIntakeSettlementComposedPostgresIntegrationTest.java +++ b/services/game-logic-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/GameLogicIntakeSettlementComposedPostgresIntegrationTest.java @@ -135,21 +135,20 @@ void exactTerminalSettlementReleasesOnlyItsOrderAndSurvivesOwnerOutage() throws .withRequiredOwners(); issued.actors().claimOriginalDraft(issued.compact(), original, issued.environment()); // Upstream original-author terminal fixture; this test does not manufacture GL HELD evidence. - f.tx( - () -> { - f.fences.recordOwnerReadback( - original, - new DraftAuthorizationFenceBinding.OwnerReadback( - DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, - DraftAuthorizationFenceBinding.Outcome.COMMITTED, - original.operationId(), - original.commitId(), - original.fenceId(), - original.inputDigest(), - original.canonicalBytes(), - new byte[] {1})); - return null; - }); + f.tx(() -> { + f.fences.recordOwnerReadback( + original, + new DraftAuthorizationFenceBinding.OwnerReadback( + DraftAuthorizationFenceBinding.Owner.GAME_DESIGN, + DraftAuthorizationFenceBinding.Outcome.COMMITTED, + original.operationId(), + original.commitId(), + original.fenceId(), + original.inputDigest(), + original.canonicalBytes(), + new byte[] {1})); + return null; + }); var source = source(selected); var gd = mock(GameplayRuleSourceReadClient.class); when(gd.read(any())) @@ -159,15 +158,13 @@ void exactTerminalSettlementReleasesOnlyItsOrderAndSurvivesOwnerOutage() throws new AccountGameLogicIntakeAuthorizationService( issued.actors(), f.fences, accountRepository, gd, f.manager, NAMESPACE); var retainedOrder = - asGameDesign( - () -> - producer.authorize( - issued.compact(), UUID.randomUUID(), selected, issued.environment())); + asGameDesign(() -> + producer.authorize( + issued.compact(), UUID.randomUUID(), selected, issued.environment())); var abortedOrder = - asGameDesign( - () -> - producer.authorize( - issued.compact(), UUID.randomUUID(), selected, issued.environment())); + asGameDesign(() -> + producer.authorize( + issued.compact(), UUID.randomUUID(), selected, issued.environment())); String schema = "gl_settlement_" + UUID.randomUUID().toString().replace("-", ""); var dataSource = @@ -224,16 +221,14 @@ void exactTerminalSettlementReleasesOnlyItsOrderAndSurvivesOwnerOutage() throws var request = GameLogicIntakeTerminalReadEvidence.Request.create(NAMESPACE, retainedOrder); assertThat(terminals.read(request).terminal()).isEmpty(); assertThatThrownBy(() -> asGameDesign(() -> settlement.settle(retainedOrder))) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); assertThat(f.dsl.fetchCount(DSL.table("account_game_logic_intake_settlements"))).isZero(); - f.tx( - () -> { - accountRepository.readHeld(retainedOrder, NAMESPACE); - return null; - }); + f.tx(() -> { + accountRepository.readHeld(retainedOrder, NAMESPACE); + return null; + }); var change = new DraftAuthorizationFenceRepository.SourceChange( UUID.randomUUID(), retainedOrder.sources(), new byte[] {2}); @@ -249,13 +244,11 @@ void exactTerminalSettlementReleasesOnlyItsOrderAndSurvivesOwnerOutage() throws assertThat(terminals.read(request).terminal().orElseThrow().canonicalBytes()) .isEqualTo(retained.canonicalBytes()); assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isFalse(); - assertThatThrownBy( - () -> - f.tx( - () -> { - f.fences.requireDisclosurePreparation(retainedOrder.sources()); - return null; - })) + assertThatThrownBy(() -> + f.tx(() -> { + f.fences.requireDisclosurePreparation(retainedOrder.sources()); + return null; + })) .isInstanceOf(IllegalStateException.class); // Unknown/changed operation identity, peer workload and namespace fail at the real @@ -268,24 +261,21 @@ void exactTerminalSettlementReleasesOnlyItsOrderAndSurvivesOwnerOutage() throws retainedOrder.actorAccountId(), retainedOrder.source(), retainedOrder.sources()); - assertThatThrownBy( - () -> - terminals.read( - GameLogicIntakeTerminalReadEvidence.Request.create(NAMESPACE, changed))) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.ALREADY_EXISTS)); + assertThatThrownBy(() -> + terminals.read( + GameLogicIntakeTerminalReadEvidence.Request.create(NAMESPACE, changed))) + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.ALREADY_EXISTS)); for (var identity : List.of(pki.wrongClient, pki.otherNamespaceClient)) { try (var denied = new GameLogicIntakeTerminalReadClient( endpoints, identity.properties(pki.ca), new GrpcChannelFactory(), NAMESPACE)) { denied.init(); assertThatThrownBy(() -> denied.read(request)) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } } for (var identity : List.of(pki.wrongServer, pki.otherNamespaceServer)) { @@ -300,45 +290,39 @@ void exactTerminalSettlementReleasesOnlyItsOrderAndSurvivesOwnerOutage() throws NAMESPACE)) { denied.init(); assertThatThrownBy(() -> denied.read(request)) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); } finally { stop(substituted); } } // Rollback leaves the exact order held; a fabricated/different terminal cannot release it. - assertThatThrownBy( - () -> - f.tx( - () -> { - accountRepository.settle(new AccountGameLogicIntakeSettlement(retained)); - throw new IllegalStateException("rollback settlement"); - })) + assertThatThrownBy(() -> + f.tx(() -> { + accountRepository.settle(new AccountGameLogicIntakeSettlement(retained)); + throw new IllegalStateException("rollback settlement"); + })) .hasMessageContaining("rollback"); - f.tx( - () -> { - accountRepository.readHeld(retainedOrder, NAMESPACE); - return null; - }); - assertThatThrownBy( - () -> - f.tx( - () -> { - var receipt = new AccountGameLogicIntakeSettlement(retained); - f.dsl.execute( - "INSERT INTO account_game_logic_intake_settlements (operation_id, target_namespace, outcome, terminal_bytes, terminal_digest, receipt_bytes, receipt_digest) VALUES (?, ?, ?, ?, ?, ?, ?)", - abortedOrder.operationId(), - NAMESPACE, - "RETAINED", - retained.canonicalBytes(), - retained.digest(), - receipt.canonicalBytes(), - receipt.digest()); - return null; - })) + f.tx(() -> { + accountRepository.readHeld(retainedOrder, NAMESPACE); + return null; + }); + assertThatThrownBy(() -> + f.tx(() -> { + var receipt = new AccountGameLogicIntakeSettlement(retained); + f.dsl.execute( + "INSERT INTO account_game_logic_intake_settlements (operation_id, target_namespace, outcome, terminal_bytes, terminal_digest, receipt_bytes, receipt_digest) VALUES (?, ?, ?, ?, ?, ?, ?)", + abortedOrder.operationId(), + NAMESPACE, + "RETAINED", + retained.canonicalBytes(), + retained.digest(), + receipt.canonicalBytes(), + receipt.digest()); + return null; + })) .hasStackTraceContaining("Changed original Game Logic operation authorization"); AccountGameLogicIntakeSettlement receipt; @@ -352,64 +336,52 @@ void exactTerminalSettlementReleasesOnlyItsOrderAndSurvivesOwnerOutage() throws assertThat(receipt.terminal().canonicalBytes()).isEqualTo(retained.canonicalBytes()); assertThat(f.dsl.fetchCount(DSL.table("account_game_logic_intake_settlements"))) .isEqualTo(1); - assertThatThrownBy( - () -> - held.read( - GameLogicIntakeAuthorizationReadEvidence.Request.create( - NAMESPACE, retainedOrder))) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); - f.tx( - () -> { - accountRepository.readHeld(abortedOrder, NAMESPACE); - return null; - }); + assertThatThrownBy(() -> + held.read( + GameLogicIntakeAuthorizationReadEvidence.Request.create( + NAMESPACE, retainedOrder))) + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + f.tx(() -> { + accountRepository.readHeld(abortedOrder, NAMESPACE); + return null; + }); assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isFalse(); - assertThatThrownBy( - () -> - f.tx( - () -> { - f.fences.requireDisclosurePreparation(retainedOrder.sources()); - return null; - })) + assertThatThrownBy(() -> + f.tx(() -> { + f.fences.requireDisclosurePreparation(retainedOrder.sources()); + return null; + })) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - f.tx( - () -> { - f.dsl.execute( - "UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()); - return null; - })) + assertThatThrownBy(() -> + f.tx(() -> { + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", f.account.getId()); + return null; + })) .hasStackTraceContaining("Distinct Game Logic intake remains pending"); var abortReceipt = asGameDesign(() -> settlement.settle(abortedOrder)); assertThat(abortReceipt.terminal().canonicalBytes()).isEqualTo(aborted.canonicalBytes()); assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isTrue(); - f.tx( - () -> { - f.fences.markSourceAborted( - change, - DraftAuthorizationFenceRepository.SourceChangeAbortReason.DEFINITIVE_ABORT); - return null; - }); - f.tx( - () -> { - f.fences.requireDisclosurePreparation(retainedOrder.sources()); - return null; - }); - assertThatThrownBy( - () -> - f.dsl.execute( - "UPDATE account_game_logic_intake_settlements SET outcome = 'ABORTED' WHERE operation_id = ?", - retainedOrder.operationId())) + f.tx(() -> { + f.fences.markSourceAborted( + change, DraftAuthorizationFenceRepository.SourceChangeAbortReason.DEFINITIVE_ABORT); + return null; + }); + f.tx(() -> { + f.fences.requireDisclosurePreparation(retainedOrder.sources()); + return null; + }); + assertThatThrownBy(() -> + f.dsl.execute( + "UPDATE account_game_logic_intake_settlements SET outcome = 'ABORTED' WHERE operation_id = ?", + retainedOrder.operationId())) .hasStackTraceContaining("immutable"); - assertThatThrownBy( - () -> - f.dsl.execute( - "DELETE FROM account_game_logic_intake_settlements WHERE operation_id = ?", - retainedOrder.operationId())) + assertThatThrownBy(() -> + f.dsl.execute( + "DELETE FROM account_game_logic_intake_settlements WHERE operation_id = ?", + retainedOrder.operationId())) .hasStackTraceContaining("immutable"); assertThatThrownBy(() -> f.dsl.execute("TRUNCATE account_game_logic_intake_settlements")) .hasStackTraceContaining("immutable"); diff --git a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java index 2ee36dbed3..127546f559 100644 --- a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java +++ b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakePostgresIntegrationTest.java @@ -100,11 +100,10 @@ void upgradesActualV1AndSagaParentWithoutChangingHistoryOrRetainedSagaData( "V1001__saga_instance_table.sql", "V1002__saga_step_table.sql"); assertThat(installedParents) - .allSatisfy( - row -> { - assertThat(row.checksum()).isNotNull(); - assertThat(row.success()).isTrue(); - }); + .allSatisfy(row -> { + assertThat(row.checksum()).isNotNull(); + assertThat(row.success()).isTrue(); + }); long intakeTablesBeforeUpgrade = Objects.requireNonNull( dsl.fetchOne( @@ -165,14 +164,13 @@ private static List migrationHistory(DSLContext dsl, String hi "SELECT installed_rank, version, script, checksum, success FROM " + historyTable + " WHERE version IS NOT NULL ORDER BY installed_rank") - .map( - row -> - new MigrationHistory( - row.get("installed_rank", Integer.class), - row.get("version", String.class), - row.get("script", String.class), - row.get("checksum", Integer.class), - row.get("success", Boolean.class))); + .map(row -> + new MigrationHistory( + row.get("installed_rank", Integer.class), + row.get("version", String.class), + row.get("script", String.class), + row.get("checksum", Integer.class), + row.get("success", Boolean.class))); } private static SagaRowSnapshot sagaSnapshot(DSLContext dsl, String schema, long sagaId) { @@ -199,28 +197,26 @@ void exactConcurrentRetriesRetainOneImmutableOriginalTerminalAndReadItWithoutOwn var accountReader = mock(GameLogicIntakeAuthorizationReadClient.class); var gameDesignReader = mock(GameplayRuleSourceReadClient.class); when(accountReader.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - accountReads.incrementAndGet(); - return new GameLogicIntakeAuthorizationReadEvidence(invocation.getArgument(0)); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + accountReads.incrementAndGet(); + return new GameLogicIntakeAuthorizationReadEvidence(invocation.getArgument(0)); + }); when(gameDesignReader.read(any(GameplayRuleSourceReadEvidence.Request.class))) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - gameDesignReads.incrementAndGet(); - var sourceRequest = invocation.getArgument(0); - assertThat(sourceRequest.proof()) - .isInstanceOf(GameplayRuleSourceReadEvidence.Finalized.class); - assertThat(sourceRequest.proof().canonicalBytes()) - .containsExactly(authorization.canonicalBytes()); - bothSourceReads.countDown(); - if (!bothSourceReads.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException("Concurrent source-read barrier timed out"); - } - return new GameplayRuleSourceReadEvidence(invocation.getArgument(0), source); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + gameDesignReads.incrementAndGet(); + var sourceRequest = invocation.getArgument(0); + assertThat(sourceRequest.proof()) + .isInstanceOf(GameplayRuleSourceReadEvidence.Finalized.class); + assertThat(sourceRequest.proof().canonicalBytes()) + .containsExactly(authorization.canonicalBytes()); + bothSourceReads.countDown(); + if (!bothSourceReads.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent source-read barrier timed out"); + } + return new GameplayRuleSourceReadEvidence(invocation.getArgument(0), source); + }); var first = fixture.service(accountReader, gameDesignReader); var second = fixture.service(accountReader, gameDesignReader); byte[] originalTerminalBytes; @@ -244,17 +240,15 @@ void exactConcurrentRetriesRetainOneImmutableOriginalTerminalAndReadItWithoutOwn assertThat(stored.manifestBytes()) .containsExactly(source.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "UPDATE game_logic_gameplay_rule_intake_terminal SET outcome = 'ABORTED' WHERE operation_id = ?", - authorization.operationId())) + assertThatThrownBy(() -> + fixture.dsl.execute( + "UPDATE game_logic_gameplay_rule_intake_terminal SET outcome = 'ABORTED' WHERE operation_id = ?", + authorization.operationId())) .isInstanceOf(RuntimeException.class); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "DELETE FROM game_logic_gameplay_rule_intake_terminal WHERE operation_id = ?", - authorization.operationId())) + assertThatThrownBy(() -> + fixture.dsl.execute( + "DELETE FROM game_logic_gameplay_rule_intake_terminal WHERE operation_id = ?", + authorization.operationId())) .isInstanceOf(RuntimeException.class); assertThatThrownBy( () -> fixture.dsl.execute("TRUNCATE game_logic_gameplay_rule_intake_terminal")) @@ -285,15 +279,14 @@ void explicitAbortWinsBeforeRetentionAndPreventsLaterSourceReadsAndCommit() thro .thenAnswer( invocation -> new GameLogicIntakeAuthorizationReadEvidence(invocation.getArgument(0))); when(gameDesignReader.read(any(GameplayRuleSourceReadEvidence.Request.class))) - .thenAnswer( - invocation -> { - sourceReadEntered.countDown(); - if (!allowSourceRead.await(10, TimeUnit.SECONDS)) { - throw new IllegalStateException("Source-read barrier timed out"); - } - return new GameplayRuleSourceReadEvidence( - invocation.getArgument(0), authorization.source()); - }); + .thenAnswer(invocation -> { + sourceReadEntered.countDown(); + if (!allowSourceRead.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Source-read barrier timed out"); + } + return new GameplayRuleSourceReadEvidence( + invocation.getArgument(0), authorization.source()); + }); var service = fixture.service(accountReader, gameDesignReader); try (var executor = Executors.newSingleThreadExecutor()) { @@ -327,10 +320,8 @@ void publicationReadUsesCommittedTerminalAfterUpstreamReadersAreUnavailableAndNe .thenAnswer( invocation -> new GameLogicIntakeAuthorizationReadEvidence(invocation.getArgument(0))); when(gameDesignReader.read(any(GameplayRuleSourceReadEvidence.Request.class))) - .thenAnswer( - invocation -> - new GameplayRuleSourceReadEvidence( - invocation.getArgument(0), authorization.source())); + .thenAnswer(invocation -> + new GameplayRuleSourceReadEvidence(invocation.getArgument(0), authorization.source())); var retained = asGameDesign(() -> fixture.service(accountReader, gameDesignReader).retain(authorization)); diff --git a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java index 831feb639c..317e9dee6e 100644 --- a/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java +++ b/services/game-logic-service/src/test/java/integration/net/firedevops/firemud/gamelogic/sourceintake/GameLogicPublicationDigestReadPostgresIntegrationTest.java @@ -79,26 +79,21 @@ void actualRetainedOwnerFlowsThroughDigestServiceAndReceiverWithExactReplayAndRe var authorization = authorization(); var accountReader = mock(GameLogicIntakeAuthorizationReadClient.class); when(accountReader.read(any())) - .thenAnswer( - invocation -> { - GameLogicIntakeAuthorizationReadEvidence.Request request = invocation.getArgument(0); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(request.binding().canonicalBytes()) - .isEqualTo(authorization.canonicalBytes()); - return new GameLogicIntakeAuthorizationReadEvidence(request); - }); + .thenAnswer(invocation -> { + GameLogicIntakeAuthorizationReadEvidence.Request request = invocation.getArgument(0); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(request.binding().canonicalBytes()).isEqualTo(authorization.canonicalBytes()); + return new GameLogicIntakeAuthorizationReadEvidence(request); + }); var sourceReader = mock(GameplayRuleSourceReadClient.class); when(sourceReader.read(any())) - .thenAnswer( - invocation -> { - GameplayRuleSourceReadEvidence.Request request = invocation.getArgument(0); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(request.proof()) - .isInstanceOf(GameplayRuleSourceReadEvidence.Finalized.class); - assertThat(request.proof().canonicalBytes()) - .isEqualTo(authorization.canonicalBytes()); - return new GameplayRuleSourceReadEvidence(request, authorization.source()); - }); + .thenAnswer(invocation -> { + GameplayRuleSourceReadEvidence.Request request = invocation.getArgument(0); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(request.proof()).isInstanceOf(GameplayRuleSourceReadEvidence.Finalized.class); + assertThat(request.proof().canonicalBytes()).isEqualTo(authorization.canonicalBytes()); + return new GameplayRuleSourceReadEvidence(request, authorization.source()); + }); var intake = new GameLogicGameplayRuleIntakeService( f.repository(), f.manager(), accountReader, sourceReader, NAMESPACE); @@ -175,15 +170,13 @@ void actualRetainedOwnerFlowsThroughDigestServiceAndReceiverWithExactReplayAndRe var abortedAuthorization = authorization(); var abortAccountReader = mock(GameLogicIntakeAuthorizationReadClient.class); when(abortAccountReader.read(any())) - .thenAnswer( - invocation -> { - GameLogicIntakeAuthorizationReadEvidence.Request heldRequest = - invocation.getArgument(0); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(heldRequest.binding().canonicalBytes()) - .isEqualTo(abortedAuthorization.canonicalBytes()); - return new GameLogicIntakeAuthorizationReadEvidence(heldRequest); - }); + .thenAnswer(invocation -> { + GameLogicIntakeAuthorizationReadEvidence.Request heldRequest = invocation.getArgument(0); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(heldRequest.binding().canonicalBytes()) + .isEqualTo(abortedAuthorization.canonicalBytes()); + return new GameLogicIntakeAuthorizationReadEvidence(heldRequest); + }); var unusedAbortSourceReader = mock(GameplayRuleSourceReadClient.class); var abortOwner = new GameLogicGameplayRuleIntakeService( @@ -254,28 +247,27 @@ private static void assertTransportError( var failure = new AtomicReference(); var response = new AtomicReference(); var completed = new AtomicReference<>(false); - asGameDesign( - () -> { - receiver.getDraftDesignDigest( - request, - new StreamObserver<>() { - @Override - public void onNext(GetDraftDesignDigestResponse value) { - response.set(value); - } + asGameDesign(() -> { + receiver.getDraftDesignDigest( + request, + new StreamObserver<>() { + @Override + public void onNext(GetDraftDesignDigestResponse value) { + response.set(value); + } - @Override - public void onError(Throwable value) { - failure.set(value); - } + @Override + public void onError(Throwable value) { + failure.set(value); + } - @Override - public void onCompleted() { - completed.set(true); - } - }); - return null; - }); + @Override + public void onCompleted() { + completed.set(true); + } + }); + return null; + }); assertThat(failure.get()).isInstanceOf(StatusRuntimeException.class); var statusFailure = (StatusRuntimeException) failure.get(); assertThat(statusFailure.getStatus().getCode()).isEqualTo(code); diff --git a/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java b/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java index b13a3656b4..9d7e5caae5 100644 --- a/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java +++ b/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/CommunicationAggregationServiceTest.java @@ -286,24 +286,22 @@ void sayIncludesDeliveryMetadata() { assertThat(resp.getNpcEchoesList()).containsExactly("Kobold Scout"); assertThat(resp.getRecipientViewsList()).hasSize(2); assertThat(resp.getRecipientViewsList().get(0)) - .satisfies( - view -> { - assertThat(view.getRecipientId()).isEqualTo("player-0"); - assertThat(view.getRecipientName()).isEqualTo("Emberline"); - assertThat(view.getRole()) - .isEqualTo(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_ACTOR); - }); + .satisfies(view -> { + assertThat(view.getRecipientId()).isEqualTo("player-0"); + assertThat(view.getRecipientName()).isEqualTo("Emberline"); + assertThat(view.getRole()) + .isEqualTo(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_ACTOR); + }); assertThat(resp.getRecipientViewsList().get(1)) - .satisfies( - view -> { - assertThat(view.getRecipientId()).isEqualTo("player-1"); - assertThat(view.getRecipientName()).isEqualTo("Sora"); - assertThat(view.getRole()) - .isEqualTo(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET); - assertThat(view.getPerception()) - .isEqualTo(CommunicationPerception.COMMUNICATION_PERCEPTION_FULL_CONTENT); - assertThat(view.getSpeakerName()).isEqualTo("Emberline"); - }); + .satisfies(view -> { + assertThat(view.getRecipientId()).isEqualTo("player-1"); + assertThat(view.getRecipientName()).isEqualTo("Sora"); + assertThat(view.getRole()) + .isEqualTo(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET); + assertThat(view.getPerception()) + .isEqualTo(CommunicationPerception.COMMUNICATION_PERCEPTION_FULL_CONTENT); + assertThat(view.getSpeakerName()).isEqualTo("Emberline"); + }); ArgumentCaptor captor = ArgumentCaptor.forClass(SendMessageRequest.class); verify(socialStub).sendMessage(captor.capture()); @@ -385,25 +383,23 @@ void whisperTargetsSingleRoomPlayer() { assertThat(resp.getDeliveredToList()).containsExactly("Emberline", "Sora"); assertThat(resp.getRecipientViewsList()).hasSize(2); assertThat(resp.getRecipientViewsList().get(0)) - .satisfies( - view -> { - assertThat(view.getRecipientId()).isEqualTo("player-0"); - assertThat(view.getRecipientName()).isEqualTo("Emberline"); - assertThat(view.getRole()) - .isEqualTo(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_ACTOR); - assertThat(view.getSpeakerName()).isEqualTo("Emberline"); - assertThat(view.getTargetName()).isEqualTo("Sora"); - }); + .satisfies(view -> { + assertThat(view.getRecipientId()).isEqualTo("player-0"); + assertThat(view.getRecipientName()).isEqualTo("Emberline"); + assertThat(view.getRole()) + .isEqualTo(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_ACTOR); + assertThat(view.getSpeakerName()).isEqualTo("Emberline"); + assertThat(view.getTargetName()).isEqualTo("Sora"); + }); assertThat(resp.getRecipientViewsList().get(1)) - .satisfies( - view -> { - assertThat(view.getRecipientId()).isEqualTo("player-1"); - assertThat(view.getRecipientName()).isEqualTo("Sora"); - assertThat(view.getRole()) - .isEqualTo(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET); - assertThat(view.getSpeakerName()).isEqualTo("Emberline"); - assertThat(view.getTargetName()).isEqualTo("Sora"); - }); + .satisfies(view -> { + assertThat(view.getRecipientId()).isEqualTo("player-1"); + assertThat(view.getRecipientName()).isEqualTo("Sora"); + assertThat(view.getRole()) + .isEqualTo(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET); + assertThat(view.getSpeakerName()).isEqualTo("Emberline"); + assertThat(view.getTargetName()).isEqualTo("Sora"); + }); ArgumentCaptor captor = ArgumentCaptor.forClass(SendMessageRequest.class); verify(socialStub).sendMessage(captor.capture()); @@ -434,21 +430,19 @@ void sendAddsGameplayLoggingContext() { .build()) .build(); when(entityStub.listRoomEntities(any())) - .thenAnswer( - ignored -> { - assertThat(MDC.get("tenantId")).isEqualTo("1"); - assertThat(MDC.get("gameInstanceId")).isEqualTo("7"); - assertThat(MDC.get("characterId")).isEqualTo("player-0"); - return roomEntities; - }); + .thenAnswer(ignored -> { + assertThat(MDC.get("tenantId")).isEqualTo("1"); + assertThat(MDC.get("gameInstanceId")).isEqualTo("7"); + assertThat(MDC.get("characterId")).isEqualTo("player-0"); + return roomEntities; + }); when(socialStub.sendMessage(any())) - .thenAnswer( - ignored -> { - assertThat(MDC.get("tenantId")).isEqualTo("1"); - assertThat(MDC.get("gameInstanceId")).isEqualTo("7"); - assertThat(MDC.get("characterId")).isEqualTo("player-0"); - return SendMessageResponse.newBuilder().setSuccess(true).build(); - }); + .thenAnswer(ignored -> { + assertThat(MDC.get("tenantId")).isEqualTo("1"); + assertThat(MDC.get("gameInstanceId")).isEqualTo("7"); + assertThat(MDC.get("characterId")).isEqualTo("player-0"); + return SendMessageResponse.newBuilder().setSuccess(true).build(); + }); service.send( SendCommunicationRequest.newBuilder() @@ -518,19 +512,17 @@ void whisperAddsMetadataOnlyObserverViewWhenFlagged() { assertThat(resp.getSuccess()).isTrue(); assertThat(resp.getRecipientViewsList()).hasSize(3); assertThat(resp.getRecipientViewsList()) - .filteredOn( - view -> - view.getRole() == CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_OBSERVER) + .filteredOn(view -> + view.getRole() == CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_OBSERVER) .singleElement() - .satisfies( - view -> { - assertThat(view.getRecipientId()).isEqualTo("player-2"); - assertThat(view.getRecipientName()).isEqualTo("Nyx"); - assertThat(view.getPerception()) - .isEqualTo(CommunicationPerception.COMMUNICATION_PERCEPTION_METADATA_ONLY); - assertThat(view.getSpeakerName()).isEqualTo("Emberline"); - assertThat(view.getTargetName()).isEqualTo("Sora"); - }); + .satisfies(view -> { + assertThat(view.getRecipientId()).isEqualTo("player-2"); + assertThat(view.getRecipientName()).isEqualTo("Nyx"); + assertThat(view.getPerception()) + .isEqualTo(CommunicationPerception.COMMUNICATION_PERCEPTION_METADATA_ONLY); + assertThat(view.getSpeakerName()).isEqualTo("Emberline"); + assertThat(view.getTargetName()).isEqualTo("Sora"); + }); } @Test @@ -577,9 +569,8 @@ void whisperObserverMetadataCanBeDisabled() { assertThat(resp.getSuccess()).isTrue(); assertThat(resp.getRecipientViewsList()) - .filteredOn( - view -> - view.getRole() == CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_OBSERVER) + .filteredOn(view -> + view.getRole() == CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_OBSERVER) .isEmpty(); } @@ -606,25 +597,23 @@ void tellUsesDirectRecipientId() { assertThat(resp.getSpeakerName()).isEqualTo("Emberline"); assertThat(resp.getRecipientViewsList()).hasSize(2); assertThat(resp.getRecipientViewsList().get(0)) - .satisfies( - view -> { - assertThat(view.getRecipientId()).isEqualTo("player-0"); - assertThat(view.getRecipientName()).isEqualTo("Emberline"); - assertThat(view.getRole()) - .isEqualTo(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_ACTOR); - assertThat(view.getSpeakerName()).isEqualTo("Emberline"); - assertThat(view.getTargetName()).isEqualTo("Sora"); - }); + .satisfies(view -> { + assertThat(view.getRecipientId()).isEqualTo("player-0"); + assertThat(view.getRecipientName()).isEqualTo("Emberline"); + assertThat(view.getRole()) + .isEqualTo(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_ACTOR); + assertThat(view.getSpeakerName()).isEqualTo("Emberline"); + assertThat(view.getTargetName()).isEqualTo("Sora"); + }); assertThat(resp.getRecipientViewsList().get(1)) - .satisfies( - view -> { - assertThat(view.getRecipientId()).isEqualTo("player-9"); - assertThat(view.getRecipientName()).isEqualTo("Sora"); - assertThat(view.getRole()) - .isEqualTo(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET); - assertThat(view.getSpeakerName()).isEqualTo("Emberline"); - assertThat(view.getTargetName()).isEqualTo("Sora"); - }); + .satisfies(view -> { + assertThat(view.getRecipientId()).isEqualTo("player-9"); + assertThat(view.getRecipientName()).isEqualTo("Sora"); + assertThat(view.getRole()) + .isEqualTo(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET); + assertThat(view.getSpeakerName()).isEqualTo("Emberline"); + assertThat(view.getTargetName()).isEqualTo("Sora"); + }); ArgumentCaptor captor = ArgumentCaptor.forClass(SendMessageRequest.class); verify(socialStub).sendMessage(captor.capture()); diff --git a/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/LookAggregationServiceTest.java b/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/LookAggregationServiceTest.java index c631d90da5..04cfb44e46 100644 --- a/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/LookAggregationServiceTest.java +++ b/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/LookAggregationServiceTest.java @@ -183,13 +183,12 @@ void rejectsMixedReadFenceComposition() { @Test void resolveAddsGameplayLoggingContext() { when(worldStub.getRoomSnapshot(any())) - .thenAnswer( - ignored -> { - assertThat(MDC.get("tenantId")).isEqualTo("tenant-1"); - assertThat(MDC.get("characterId")).isEqualTo("player-1"); - assertThat(MDC.get("gameInstanceId")).isEqualTo("game-1"); - return GetRoomSnapshotResponse.newBuilder().setSnapshot(snapshot).build(); - }); + .thenAnswer(ignored -> { + assertThat(MDC.get("tenantId")).isEqualTo("tenant-1"); + assertThat(MDC.get("characterId")).isEqualTo("player-1"); + assertThat(MDC.get("gameInstanceId")).isEqualTo("game-1"); + return GetRoomSnapshotResponse.newBuilder().setSnapshot(snapshot).build(); + }); service.resolve(request); diff --git a/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/MoveAggregationServiceTest.java b/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/MoveAggregationServiceTest.java index 29c0207627..877bf0424d 100644 --- a/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/MoveAggregationServiceTest.java +++ b/services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/MoveAggregationServiceTest.java @@ -370,27 +370,26 @@ void resolveConvertsWorldFailureToAppError() { @Test void resolveAddsGameplayLoggingContext() { when(worldStub.getRoomSnapshot(any())) - .thenAnswer( - ignored -> { - assertThat(MDC.get("tenantId")).isEqualTo(LookTestFixtures.TENANT); - assertThat(MDC.get("characterId")).isEqualTo("player-1"); - assertThat(MDC.get("gameInstanceId")).isNull(); - return GetRoomSnapshotResponse.newBuilder() - .setSnapshot( - RoomSnapshot.newBuilder() - .setTenantId(LookTestFixtures.TENANT) - .setGameInstanceId(LookTestFixtures.GAME_INSTANCE_ID) - .setRoomInstanceId(LookTestFixtures.ROOM_INSTANCE_ID) - .setRoomName(LookTestFixtures.ROOM_NAME) - .addExits( - RoomExitSnapshot.newBuilder() - .setDirection("EAST") - .setLabel("EAST") - .setTargetRoomInstanceId("R-2045") - .build()) - .build()) - .build(); - }); + .thenAnswer(ignored -> { + assertThat(MDC.get("tenantId")).isEqualTo(LookTestFixtures.TENANT); + assertThat(MDC.get("characterId")).isEqualTo("player-1"); + assertThat(MDC.get("gameInstanceId")).isNull(); + return GetRoomSnapshotResponse.newBuilder() + .setSnapshot( + RoomSnapshot.newBuilder() + .setTenantId(LookTestFixtures.TENANT) + .setGameInstanceId(LookTestFixtures.GAME_INSTANCE_ID) + .setRoomInstanceId(LookTestFixtures.ROOM_INSTANCE_ID) + .setRoomName(LookTestFixtures.ROOM_NAME) + .addExits( + RoomExitSnapshot.newBuilder() + .setDirection("EAST") + .setLabel("EAST") + .setTargetRoomInstanceId("R-2045") + .build()) + .build()) + .build(); + }); service.resolve( MoveRequest.newBuilder() .setTenantId(LookTestFixtures.TENANT) diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/config/InternalGrpcClientAuthConfigTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/config/InternalGrpcClientAuthConfigTest.java index 02d669ba94..0873b2c793 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/config/InternalGrpcClientAuthConfigTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/config/InternalGrpcClientAuthConfigTest.java @@ -55,23 +55,22 @@ class InternalGrpcClientAuthConfigTest { @Test void serviceOverridesSharedStubCustomizerWithInternalOnlyBehavior() { - contextRunner.run( - ctx -> { - BlockingGrpcStubCustomizer customizer = ctx.getBean(BlockingGrpcStubCustomizer.class); - CapturingChannel channel = new CapturingChannel(); - CapturingStub stub = new CapturingStub(channel, CallOptions.DEFAULT); - - CapturingStub customized = customizer.customize(stub); - - assertThat(customized).isNotSameAs(stub); - customized.invoke(); - String authorization = channel.lastAuthorization(); - assertThat(authorization).startsWith("Bearer "); - String token = authorization.substring(7); - String payloadJson = jwtPayload(token); - assertThat(payloadJson).contains("\"sub\":\"service:game-logic-service\""); - assertThat(payloadJson).contains("\"internalService\":true"); - }); + contextRunner.run(ctx -> { + BlockingGrpcStubCustomizer customizer = ctx.getBean(BlockingGrpcStubCustomizer.class); + CapturingChannel channel = new CapturingChannel(); + CapturingStub stub = new CapturingStub(channel, CallOptions.DEFAULT); + + CapturingStub customized = customizer.customize(stub); + + assertThat(customized).isNotSameAs(stub); + customized.invoke(); + String authorization = channel.lastAuthorization(); + assertThat(authorization).startsWith("Bearer "); + String token = authorization.substring(7); + String payloadJson = jwtPayload(token); + assertThat(payloadJson).contains("\"sub\":\"service:game-logic-service\""); + assertThat(payloadJson).contains("\"internalService\":true"); + }); } private static String jwtPayload(String token) { diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/security/JwtUsageTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/security/JwtUsageTest.java index 163c57fb00..654c72509e 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/security/JwtUsageTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/security/JwtUsageTest.java @@ -144,31 +144,28 @@ void noJwtReferencesInMainSources() throws IOException { try (Stream paths = Files.walk(Path.of("src/main/java"))) { paths .filter(p -> p.toString().endsWith(".java")) - .filter( - p -> - !p.endsWith( - Path.of( - "net", - "firedevops", - "firemud", - "gamelogic", - "config", - "InternalGrpcClientAuthConfig.java"))) - .forEach( - p -> { - try { - String content = Files.readString(p, StandardCharsets.UTF_8); - assertFalse(content.contains("JwtUtil"), p + " should not reference JwtUtil"); - assertFalse( - content.contains("SessionContext"), - p + " should not reference SessionContext"); - assertFalse( - containsAuthorizationHeaderReference(content), - p + " should not reference the Authorization HTTP header"); - } catch (IOException e) { - throw new RuntimeException(e); - } - }); + .filter(p -> + !p.endsWith( + Path.of( + "net", + "firedevops", + "firemud", + "gamelogic", + "config", + "InternalGrpcClientAuthConfig.java"))) + .forEach(p -> { + try { + String content = Files.readString(p, StandardCharsets.UTF_8); + assertFalse(content.contains("JwtUtil"), p + " should not reference JwtUtil"); + assertFalse( + content.contains("SessionContext"), p + " should not reference SessionContext"); + assertFalse( + containsAuthorizationHeaderReference(content), + p + " should not reference the Authorization HTTP header"); + } catch (IOException e) { + throw new RuntimeException(e); + } + }); } } diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java index 3b1043f54d..33581af593 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/service/impl/GameLogicGrpcServiceTest.java @@ -393,24 +393,23 @@ void getDraftDesignDigestMapsUnconfiguredRetainedSourceToErrorResponse() { publicationReadGuard()); AtomicReference ref = new AtomicReference<>(); - runAsGameDesign( - () -> - service.getDraftDesignDigest( - fullDigestRequest(TEST_TENANT.toString(), "7"), - new StreamObserver<>() { - @Override - public void onNext(GetDraftDesignDigestResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) { - fail(t); - } - - @Override - public void onCompleted() {} - })); + runAsGameDesign(() -> + service.getDraftDesignDigest( + fullDigestRequest(TEST_TENANT.toString(), "7"), + new StreamObserver<>() { + @Override + public void onNext(GetDraftDesignDigestResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + })); assertTrue(ref.get().hasError()); assertEquals("UNSUPPORTED_SCOPE", ref.get().getError().getCode()); @@ -471,17 +470,16 @@ void getDraftDesignDigestRejectsMissingBindingAndUnversionedScopeBeforeServiceCa valid.toBuilder().clearSourceReadBinding().clearSourceReadBindingDigest().build(); var unversionedScope = valid.toBuilder().clearScope().build(); - runAsGameDesign( - () -> { - var missingResponse = invokeDigest(service, missingBinding); - assertEquals("INVALID_ARGUMENT", missingResponse.getError().getCode()); - assertEquals("", missingResponse.getContentDigest()); - assertEquals(0, missingResponse.getDigestSchemaVersion()); - var scopeResponse = invokeDigest(service, unversionedScope); - assertEquals("INVALID_ARGUMENT", scopeResponse.getError().getCode()); - assertEquals("", scopeResponse.getContentDigest()); - assertEquals(0, scopeResponse.getDigestSchemaVersion()); - }); + runAsGameDesign(() -> { + var missingResponse = invokeDigest(service, missingBinding); + assertEquals("INVALID_ARGUMENT", missingResponse.getError().getCode()); + assertEquals("", missingResponse.getContentDigest()); + assertEquals(0, missingResponse.getDigestSchemaVersion()); + var scopeResponse = invokeDigest(service, unversionedScope); + assertEquals("INVALID_ARGUMENT", scopeResponse.getError().getCode()); + assertEquals("", scopeResponse.getContentDigest()); + assertEquals(0, scopeResponse.getDigestSchemaVersion()); + }); Mockito.verifyNoInteractions(digestService); } @@ -509,9 +507,8 @@ void getDraftDesignDigestDeniesSourceBindingThatDiffersFromRetainedOperation() { null, List.of(), Map.of(), true, "game-design-service", "test-instance"); AtomicReference failureReference = new AtomicReference<>(); - runAsGameDesign( - () -> - failureReference.set(invokeDigestFailure(service, fullDigestRequest(changedBinding)))); + runAsGameDesign(() -> + failureReference.set(invokeDigestFailure(service, fullDigestRequest(changedBinding)))); assertThat(failureReference.get().getStatus().getCode()).isEqualTo(Status.Code.ALREADY_EXISTS); Mockito.verify(repository).findTerminal(authorization.operationId()); @@ -558,10 +555,9 @@ void getDraftDesignDigestReturnsSanitizedTransportStatusesWhenSourceReadFails() .withDescription("database-password-secret") .asRuntimeException()); AtomicReference failure = new AtomicReference<>(); - runAsGameDesign( - () -> - failure.set( - invokeDigestFailure(service, fullDigestRequest(TEST_TENANT.toString(), "7")))); + runAsGameDesign(() -> + failure.set( + invokeDigestFailure(service, fullDigestRequest(TEST_TENANT.toString(), "7")))); var statusFailure = failure.get(); assertThat(statusFailure.getStatus().getCode()).isEqualTo(code); @@ -598,22 +594,21 @@ void getDraftDesignDigestRejectsMissingPeerIdentityForInternalCaller() { AtomicReference ref = new AtomicReference<>(); Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, null) - .run( - () -> - service.getDraftDesignDigest( - fullDigestRequest(TEST_TENANT.toString(), "7"), - new StreamObserver<>() { - @Override - public void onNext(GetDraftDesignDigestResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - })); + .run(() -> + service.getDraftDesignDigest( + fullDigestRequest(TEST_TENANT.toString(), "7"), + new StreamObserver<>() { + @Override + public void onNext(GetDraftDesignDigestResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) {} + + @Override + public void onCompleted() {} + })); assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); Mockito.verifyNoInteractions(digestService); } @@ -681,13 +676,12 @@ void getDraftDesignDigestFailsClosedWhenWorkloadNamespaceIsMissingOrInvalid() { for (String workloadNamespace : new String[] {null, " ", "not a namespace"}) { GameLogicGrpcService service = newDigestService(digestService, workloadNamespace); - runAsGameDesign( - () -> - assertEquals( - "PERMISSION_DENIED", - invokeDigest(service, fullDigestRequest(TEST_TENANT.toString(), "7")) - .getError() - .getCode())); + runAsGameDesign(() -> + assertEquals( + "PERMISSION_DENIED", + invokeDigest(service, fullDigestRequest(TEST_TENANT.toString(), "7")) + .getError() + .getCode())); } Mockito.verifyNoInteractions(digestService); } diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java index b81e916712..2aacb73e38 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeGrpcServiceTest.java @@ -47,10 +47,9 @@ void exactRetryReturnsAndEchoesTheCompleteOriginalTerminal() { var request = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, fixture.authorization); var observer = new RecordingObserver(); - asGameDesign( - () -> - fixture.transport.retainGameplayRuleIntake( - GameLogicIntakeRetainProtoCodec.toRequest(request), observer)); + asGameDesign(() -> + fixture.transport.retainGameplayRuleIntake( + GameLogicIntakeRetainProtoCodec.toRequest(request), observer)); assertThat(observer.error).isNull(); assertThat(observer.completed).isTrue(); @@ -91,11 +90,9 @@ void rejectsChangedNamespaceAndChangedAuthorizationForExistingOperation() { var wrongNamespace = new RecordingObserver(); var requestForOtherNamespace = GameLogicIntakeRetainEvidence.Request.create("other", fixture.authorization); - asGameDesign( - () -> - fixture.transport.retainGameplayRuleIntake( - GameLogicIntakeRetainProtoCodec.toRequest(requestForOtherNamespace), - wrongNamespace)); + asGameDesign(() -> + fixture.transport.retainGameplayRuleIntake( + GameLogicIntakeRetainProtoCodec.toRequest(requestForOtherNamespace), wrongNamespace)); assertCode(wrongNamespace.error, Status.Code.PERMISSION_DENIED); var changed = @@ -108,10 +105,9 @@ void rejectsChangedNamespaceAndChangedAuthorizationForExistingOperation() { fixture.authorization.sources()); var changedRequest = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, changed); var conflict = new RecordingObserver(); - asGameDesign( - () -> - fixture.transport.retainGameplayRuleIntake( - GameLogicIntakeRetainProtoCodec.toRequest(changedRequest), conflict)); + asGameDesign(() -> + fixture.transport.retainGameplayRuleIntake( + GameLogicIntakeRetainProtoCodec.toRequest(changedRequest), conflict)); assertCode(conflict.error, Status.Code.ALREADY_EXISTS); verify(fixture.repository).findTerminal(fixture.authorization.operationId()); verify(fixture.accountReader, never()).read(any()); @@ -150,10 +146,9 @@ void mapsPermanentOwnerFailuresToSanitizedFailedPrecondition() { var request = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, fixture.authorization); var observer = new RecordingObserver(); - asGameDesign( - () -> - fixture.transport.retainGameplayRuleIntake( - GameLogicIntakeRetainProtoCodec.toRequest(request), observer)); + asGameDesign(() -> + fixture.transport.retainGameplayRuleIntake( + GameLogicIntakeRetainProtoCodec.toRequest(request), observer)); assertSanitizedFailure(observer, Status.Code.FAILED_PRECONDITION, secret); verify(fixture.accountReader, never()).read(any()); @@ -171,40 +166,35 @@ void keepsStorageAndTransactionCreationFailuresRetryableAndSanitized() { var storageRequest = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, storageFixture.authorization); - asGameDesign( - () -> - storageFixture.transport.retainGameplayRuleIntake( - GameLogicIntakeRetainProtoCodec.toRequest(storageRequest), storageObserver)); + asGameDesign(() -> + storageFixture.transport.retainGameplayRuleIntake( + GameLogicIntakeRetainProtoCodec.toRequest(storageRequest), storageObserver)); assertSanitizedFailure(storageObserver, Status.Code.UNAVAILABLE, secret); var transactionFixture = new Fixture(); when(transactionFixture.repository.findTerminal(any(UUID.class))).thenReturn(Optional.empty()); when(transactionFixture.accountReader.read(any())) - .thenAnswer( - invocation -> { - var request = - invocation.getArgument(0, GameLogicIntakeAuthorizationReadEvidence.Request.class); - return new GameLogicIntakeAuthorizationReadEvidence(request); - }); + .thenAnswer(invocation -> { + var request = + invocation.getArgument(0, GameLogicIntakeAuthorizationReadEvidence.Request.class); + return new GameLogicIntakeAuthorizationReadEvidence(request); + }); when(transactionFixture.gameDesignReader.read(any())) - .thenAnswer( - invocation -> { - var request = invocation.getArgument(0, GameplayRuleSourceReadEvidence.Request.class); - return new GameplayRuleSourceReadEvidence( - request, transactionFixture.authorization.source()); - }); + .thenAnswer(invocation -> { + var request = invocation.getArgument(0, GameplayRuleSourceReadEvidence.Request.class); + return new GameplayRuleSourceReadEvidence( + request, transactionFixture.authorization.source()); + }); when(transactionFixture.transactions.getTransaction(any())) .thenThrow(new CannotCreateTransactionException(secret)); var transactionObserver = new RecordingObserver(); var transactionRequest = GameLogicIntakeRetainEvidence.Request.create(NAMESPACE, transactionFixture.authorization); - asGameDesign( - () -> - transactionFixture.transport.retainGameplayRuleIntake( - GameLogicIntakeRetainProtoCodec.toRequest(transactionRequest), - transactionObserver)); + asGameDesign(() -> + transactionFixture.transport.retainGameplayRuleIntake( + GameLogicIntakeRetainProtoCodec.toRequest(transactionRequest), transactionObserver)); assertSanitizedFailure(transactionObserver, Status.Code.UNAVAILABLE, secret); } diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java index 4a948abe56..4892eab6bb 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeServiceTest.java @@ -129,10 +129,8 @@ void explicitAbortRequiresAnExactHeldAccountReadAndDoesNotWriteOnAbsence() { assertThatThrownBy(() -> asGameDesign(() -> fixture.service.abort(authorization))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()).isEqualTo(Status.Code.UNAVAILABLE)); assertThat(fixture.stored.get()).isNull(); verify(fixture.repository, never()) .insertTerminal(any(GameLogicGameplayRuleIntakeTerminal.class)); @@ -153,23 +151,21 @@ void explicitAbortRejectsAChangedAccountAuthorizationReadback() { authorization.source(), authorization.sources()); when(fixture.accountReader.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) - .thenAnswer( - invocation -> - new GameLogicIntakeAuthorizationReadEvidence( - new GameLogicIntakeAuthorizationReadEvidence.Request( - 1, - NAMESPACE, - invocation - .getArgument(0) - .readRequestId(), - changed))); + .thenAnswer(invocation -> + new GameLogicIntakeAuthorizationReadEvidence( + new GameLogicIntakeAuthorizationReadEvidence.Request( + 1, + NAMESPACE, + invocation + .getArgument(0) + .readRequestId(), + changed))); assertThatThrownBy(() -> asGameDesign(() -> fixture.service.abort(authorization))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); assertThat(fixture.stored.get()).isNull(); verify(fixture.repository, never()) .insertTerminal(any(GameLogicGameplayRuleIntakeTerminal.class)); @@ -186,10 +182,9 @@ void authenticatedSourceMismatchDeniesWithoutWritingAnAbortOrTerminal() { assertThatThrownBy(() -> asGameDesign(() -> fixture.service.retain(authorization))) .isInstanceOf(RuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); assertThat(fixture.stored.get()).isNull(); assertThat(asAccount(() -> fixture.service.readTerminal(authorization))).isEmpty(); verify(fixture.repository, never()) @@ -205,10 +200,8 @@ void unavailableAccountReadLeavesNoTerminalAndDoesNotInferAbort() { assertThatThrownBy(() -> asGameDesign(() -> fixture.service.retain(authorization))) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()).isEqualTo(Status.Code.UNAVAILABLE)); assertThat(fixture.stored.get()).isNull(); assertThat(asAccount(() -> fixture.service.readTerminal(authorization))).isEmpty(); verify(fixture.gameDesignReader, never()) @@ -233,24 +226,20 @@ void sanitizesOnlyForeignDependencyStatuses( .thenThrow(failure); } - assertThatThrownBy( - () -> - asGameDesign( - () -> { - if (call == DependencyCall.ABORT_ACCOUNT) - fixture.service.abort(authorization); - else fixture.service.retain(authorization); - return null; - })) + assertThatThrownBy(() -> + asGameDesign(() -> { + if (call == DependencyCall.ABORT_ACCOUNT) fixture.service.abort(authorization); + else fixture.service.retain(authorization); + return null; + })) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - error -> { - var status = Status.fromThrowable(error); - assertThat(status.getCode()).isEqualTo(expectedCode); - assertThat(status.getDescription()).isNull(); - assertThat(error.getCause()).isNull(); - assertThat(((StatusRuntimeException) error).getTrailers()).isNull(); - }); + .satisfies(error -> { + var status = Status.fromThrowable(error); + assertThat(status.getCode()).isEqualTo(expectedCode); + assertThat(status.getDescription()).isNull(); + assertThat(error.getCause()).isNull(); + assertThat(((StatusRuntimeException) error).getTrailers()).isNull(); + }); verify(fixture.repository, never()) .insertTerminal(any(GameLogicGameplayRuleIntakeTerminal.class)); } @@ -279,9 +268,8 @@ private static Stream dependencyFailures() { Arguments.of(Status.Code.DATA_LOSS, Status.Code.UNAVAILABLE), Arguments.of(Status.Code.UNKNOWN, Status.Code.UNKNOWN)); return calls.stream() - .flatMap( - call -> - cases.stream().map(values -> Arguments.of(call, values.get()[0], values.get()[1]))); + .flatMap(call -> + cases.stream().map(values -> Arguments.of(call, values.get()[0], values.get()[1]))); } private static StatusRuntimeException foreignFailure(Status.Code code) { @@ -318,10 +306,9 @@ void changedOrderUnderExistingOperationIdentityIsDeniedBeforeRemoteReads() { assertThatThrownBy(() -> asGameDesign(() -> fixture.service.retain(changedAuthorization))) .isInstanceOf(RuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.ALREADY_EXISTS)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.ALREADY_EXISTS)); verify(fixture.accountReader, never()) .read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class)); verify(fixture.gameDesignReader, never()) @@ -340,10 +327,9 @@ void onlyTheExactSameNamespaceGameDesignPeerCanInvokeTheOwner() { try { assertThatThrownBy(() -> fixture.service.retain(authorization)) .isInstanceOf(RuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } finally { Context.current().detach(previous); } @@ -372,10 +358,9 @@ void creatorIntakeCredentialCannotBeMixedWithTheServicePeer() { try { assertThatThrownBy(() -> fixture.service.retain(authorization)) .isInstanceOf(RuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } finally { Context.current().detach(previous); } @@ -403,10 +388,9 @@ void originalDraftCredentialCannotBeMixedWithTheServicePeer() { try { assertThatThrownBy(() -> fixture.service.retain(authorization)) .isInstanceOf(RuntimeException.class) - .satisfies( - error -> - assertThat(Status.fromThrowable(error).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } finally { Context.current().detach(previous); } @@ -535,25 +519,23 @@ private void respondFor( GameLogicIntakeAuthorizationBinding authorization, GameplayRuleSelectedSource selected) { respondAuthorizationOnly(authorization); when(gameDesignReader.read(any(GameplayRuleSourceReadEvidence.Request.class))) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - var request = invocation.getArgument(0); - return new GameplayRuleSourceReadEvidence(request, selected); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var request = invocation.getArgument(0); + return new GameplayRuleSourceReadEvidence(request, selected); + }); } private void respondAuthorizationOnly(GameLogicIntakeAuthorizationBinding authorization) { when(accountReader.read(any(GameLogicIntakeAuthorizationReadEvidence.Request.class))) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - var request = - invocation.getArgument(0); - assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); - assertThat(request.binding()).isEqualTo(authorization); - return new GameLogicIntakeAuthorizationReadEvidence(request); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var request = + invocation.getArgument(0); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.binding()).isEqualTo(authorization); + return new GameLogicIntakeAuthorizationReadEvidence(request); + }); } } diff --git a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcServiceTest.java b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcServiceTest.java index b825a3cde3..eac18036f1 100644 --- a/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcServiceTest.java +++ b/services/game-logic-service/src/test/java/unit/net/firedevops/firemud/gamelogic/sourceintake/GameLogicGameplayRuleIntakeTerminalReadGrpcServiceTest.java @@ -56,10 +56,9 @@ void mapsPermanentOwnerFailuresToFailedPreconditionAndStorageFailuresToUnavailab GameLogicIntakeTerminalReadEvidence.Request.create(NAMESPACE, authorization()); var observer = new RecordingObserver(); - asAccount( - () -> - transport.readGameplayRuleIntakeTerminal( - GameLogicIntakeTerminalReadGrpcCodec.toRequest(evidenceRequest), observer)); + asAccount(() -> + transport.readGameplayRuleIntakeTerminal( + GameLogicIntakeTerminalReadGrpcCodec.toRequest(evidenceRequest), observer)); assertThat(observer.error).isEqualTo(expectedCodes.get(index)); assertThat(observer.failureHasCause).isFalse(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayLegacyMigrationStorageIdentity.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayLegacyMigrationStorageIdentity.java index 2009d765b9..fe3544f09a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayLegacyMigrationStorageIdentity.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/binding/CanonicalGameplayLegacyMigrationStorageIdentity.java @@ -66,9 +66,8 @@ public String digest() { redisRunId, redisStorageUid); StringBuilder framed = new StringBuilder("canonical-gameplay-storage-identity/v1|"); - fields.forEach( - field -> - framed.append(field.getBytes(StandardCharsets.UTF_8).length).append(':').append(field)); + fields.forEach(field -> + framed.append(field.getBytes(StandardCharsets.UTF_8).length).append(':').append(field)); try { return "sha256:" + HexFormat.of() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceService.java index 2c2c27f878..f946b5e5c2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceService.java @@ -109,10 +109,9 @@ public ResolveCharacterCreatePublicTargetResponse resolve( if (visible == null || visible.stream().anyMatch(Objects::isNull)) throw missing(); var selected = visible.stream() - .filter( - route -> - request.getWorldSlug().equals(route.worldSlug()) - && request.getRealmSlug().equals(route.realmSlug())) + .filter(route -> + request.getWorldSlug().equals(route.worldSlug()) + && request.getRealmSlug().equals(route.realmSlug())) .toList(); if (selected.size() != 1) throw missing(); CanonicalPlayableTarget discovery = selected.getFirst(); @@ -478,18 +477,17 @@ private PublishedPolicies readPublishedPolicies( || !sourceRelease.commandDefinitions().equals(worldRelease.commandDefinitions()) || !sourceRelease.generationConfigRevision().equals(worldRelease.generationConfigRevision()) || !sourceRelease.participantDigests().stream() - .map( - value -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - value.participantKey(), - value.scopeValue(), - value.baseVersionId() != null, - value.baseVersionId(), - value.appliedCommitId(), - value.contentDigest(), - value.digestSchemaVersion(), - value.abilitySchemaDigest() != null, - value.abilitySchemaDigest())) + .map(value -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + value.participantKey(), + value.scopeValue(), + value.baseVersionId() != null, + value.baseVersionId(), + value.appliedCommitId(), + value.contentDigest(), + value.digestSchemaVersion(), + value.abilitySchemaDigest() != null, + value.abilitySchemaDigest())) .toList() .equals(worldRelease.participantDigests()) || !Arrays.equals( @@ -501,10 +499,9 @@ private PublishedPolicies readPublishedPolicies( || set.versionNumber() != bundle.getVersionNumber()) throw missing(); var matches = set.policies().stream() - .filter( - evidence -> - evidence.policy().worldSlug().equals(route.worldSlug()) - && evidence.policy().realmSlug().equals(route.realmSlug())) + .filter(evidence -> + evidence.policy().worldSlug().equals(route.worldSlug()) + && evidence.policy().realmSlug().equals(route.realmSlug())) .toList(); if (matches.size() != 1) throw missing(); var evidence = matches.getFirst().requireValidDigest(set); @@ -724,11 +721,10 @@ private static AuthoredInitialActorCoreProjection requireProjection( AuthoredInitialActorCoreReadEvidence.ReadResult source) { var selected = source.projections().stream() - .filter( - projection -> - RealmEntryPolicy.parseCanonical(projection.policy().canonicalJson(), JSON) - .realmSlug() - .equals(route.realmSlug())) + .filter(projection -> + RealmEntryPolicy.parseCanonical(projection.policy().canonicalJson(), JSON) + .realmSlug() + .equals(route.realmSlug())) .toList(); if (selected.size() != 1) throw missing(); var projection = selected.getFirst(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReader.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReader.java index dd631864ff..30b45d68bf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReader.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReader.java @@ -71,10 +71,9 @@ Optional admissionFor(SessionContext context, String c return gameInstanceRepository .findById(context.gameInstanceId()) .filter(instance -> matchesContext(instance, context)) - .flatMap( - instance -> - readBundle(bundleKey(context.tenantId(), instance)) - .flatMap(response -> admissionFromBundle(instance, commandId, response))); + .flatMap(instance -> + readBundle(bundleKey(context.tenantId(), instance)) + .flatMap(response -> admissionFromBundle(instance, commandId, response))); } catch (RuntimeException ex) { LOG.warn( "Unable to resolve admitted command declaration tenantId={} gameInstanceId={} commandId={}", @@ -120,10 +119,9 @@ private Optional> readDefinitions( try { BundleKey bundleKey = bundleKey(tenantId, instance); return readBundle(bundleKey) - .map( - response -> - definitionsByBundle.computeIfAbsent( - bundleKey, ignored -> parseDefinitions(response))); + .map(response -> + definitionsByBundle.computeIfAbsent( + bundleKey, ignored -> parseDefinitions(response))); } catch (RuntimeException ex) { LOG.warn( "Unable to read admitted command definitions tenantId={} versionId={} releaseBundleId={}", diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java index 87a812da80..5f2468f618 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java @@ -84,14 +84,13 @@ public Optional resolve for (String commandToken : commandTokens) { Optional metadata = resolveDefinition(registry, commandToken) - .map( - definition -> - new TextCommandMetadataResolver.ResolvedTextCommandMetadata( - definition.dispatchGroup(), - definition.promptPolicy(), - definition.actionCategory(), - definition.actionTags(), - definition.capability())); + .map(definition -> + new TextCommandMetadataResolver.ResolvedTextCommandMetadata( + definition.dispatchGroup(), + definition.promptPolicy(), + definition.actionCategory(), + definition.actionTags(), + definition.capability())); if (metadata.isPresent()) { return metadata; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandler.java index 44e77f8a2c..80b249a7b1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandler.java @@ -32,16 +32,15 @@ public TextCommandInterpretationResult handle(TextCommandDispatchRequest request SessionContext context = request.sessionContext().orElseThrow(); return admittedRegistryResolver .resolveAdmission(context, request.command().commandId()) - .map( - admission -> - handler.handle( - context, - request.command(), - commandService.enqueue( - request.sessionId(), - request.command().rawLine(), - request.requiresSoloTick(), - admission))) + .map(admission -> + handler.handle( + context, + request.command(), + commandService.enqueue( + request.sessionId(), + request.command().rawLine(), + request.requiresSoloTick(), + admission))) .orElseGet(() -> handler.handle(context, request.command())); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java index 53298477eb..1b79e98d7e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/CanonicalGameplayActorSelection.java @@ -73,10 +73,9 @@ public static SelectionResult select(VerifiedPlayerCreatedRoster roster, String } var actors = roster.actors().stream() - .map( - actor -> - new CanonicalGameplayRosterClient.RosterActor( - UUID.fromString(actor.getCharacterUuid()), actor.getDisplayName())) + .map(actor -> + new CanonicalGameplayRosterClient.RosterActor( + UUID.fromString(actor.getCharacterUuid()), actor.getDisplayName())) .toList(); return select( roster.canonicalAccountUuid(), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java index bd4b016d75..6c98d93414 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionService.java @@ -179,9 +179,8 @@ private static Optional select(List choices, String selector) { } List matches = choices.stream() - .filter( - choice -> - folded.equals(choice.selector()) || folded.equals(choice.target().tenantSlug())) + .filter(choice -> + folded.equals(choice.selector()) || folded.equals(choice.target().tenantSlug())) .toList(); return matches.size() == 1 ? Optional.of(matches.getFirst()) : Optional.empty(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java index 56d2c3adb3..e23241b1c6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java @@ -474,12 +474,11 @@ private void publishCommandEvent(SessionContext context, String rawCommandText) private FriendPresenceViewOutput toView(ListFriendsResponse response, FriendListFilter filter) { List allEntries = java.util.stream.IntStream.range(0, response.getFriendsCount()) - .mapToObj( - index -> { - FriendRosterEntry entry = response.getFriends(index); - int ordinal = entry.getOrdinal() > 0 ? entry.getOrdinal() : index + 1; - return toEntry(ordinal, entry); - }) + .mapToObj(index -> { + FriendRosterEntry entry = response.getFriends(index); + int ordinal = entry.getOrdinal() > 0 ? entry.getOrdinal() : index + 1; + return toEntry(ordinal, entry); + }) .toList(); boolean canonicalFiltered = filter == FriendListFilter.ALL diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index e640d0387e..76709f00fb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -157,10 +157,9 @@ public Optional realmDiscoverySnapshot(WorldView selecte List selectedWorldMatches = visibleWorlds(snapshot).stream() .filter(world -> world.slug().equals(selectedWorld.slug())) - .filter( - world -> - world.realms().stream() - .anyMatch(realm -> realm.tenantId() == publicRealm.tenantId())) + .filter(world -> + world.realms().stream() + .anyMatch(realm -> realm.tenantId() == publicRealm.tenantId())) .toList(); if (selectedWorldMatches.size() != 1) { return Optional.empty(); @@ -266,10 +265,9 @@ private Optional resolveDefaultRealm(WorldView world, CatalogSnapshot && visibleRealms.stream() .map(RealmView::tenantId) .distinct() - .allMatch( - tenantId -> - publicProductionRealmCardinality(snapshot, tenantId) - == PublicProductionRealmCardinality.EXACTLY_ONE) + .allMatch(tenantId -> + publicProductionRealmCardinality(snapshot, tenantId) + == PublicProductionRealmCardinality.EXACTLY_ONE) ? Optional.of(visibleRealms.getFirst()) : Optional.empty(); } @@ -309,10 +307,9 @@ public boolean hasValidPublicProductionRealm(WorldView world) { return visibleRealms.stream() .map(RealmView::tenantId) .distinct() - .allMatch( - tenantId -> - publicProductionRealmCardinality(snapshot, tenantId) - == PublicProductionRealmCardinality.EXACTLY_ONE); + .allMatch(tenantId -> + publicProductionRealmCardinality(snapshot, tenantId) + == PublicProductionRealmCardinality.EXACTLY_ONE); } public boolean requiresExplicitRealmSelection(WorldView world) { @@ -334,18 +331,13 @@ public Optional resolveRuntimeTarget(long tenantId, long gam CatalogSnapshot snapshot = loadWorldSnapshot(); List matches = snapshot.worlds().stream() - .flatMap( - world -> - world.realms().stream() - .filter(realm -> realm.tenantId() == tenantId) - .filter(realm -> realm.gameInstanceId() == gameInstanceId) - .map( - realm -> - new RuntimeRealmTarget( - world.slug(), - world.displayName(), - realm.slug(), - realm.displayName()))) + .flatMap(world -> + world.realms().stream() + .filter(realm -> realm.tenantId() == tenantId) + .filter(realm -> realm.gameInstanceId() == gameInstanceId) + .map(realm -> + new RuntimeRealmTarget( + world.slug(), world.displayName(), realm.slug(), realm.displayName()))) .toList(); return matches.size() == 1 ? Optional.of(matches.getFirst()) : Optional.empty(); } @@ -359,17 +351,12 @@ public Optional resolveRealmTarget(String worldSlug, String List matches = visibleWorlds(loadWorldSnapshot()).stream() .filter(world -> normalizedWorld.equals(selectorKey(world.slug()))) - .flatMap( - world -> - visibleRealms(world).stream() - .filter(realm -> normalizedRealm.equals(selectorKey(realm.slug()))) - .map( - realm -> - new RuntimeRealmTarget( - world.slug(), - world.displayName(), - realm.slug(), - realm.displayName()))) + .flatMap(world -> + visibleRealms(world).stream() + .filter(realm -> normalizedRealm.equals(selectorKey(realm.slug()))) + .map(realm -> + new RuntimeRealmTarget( + world.slug(), world.displayName(), realm.slug(), realm.displayName()))) .toList(); return matches.size() == 1 ? Optional.of(matches.getFirst()) : Optional.empty(); } @@ -600,18 +587,16 @@ private boolean hasVisibleRealmEntries(WorldView world) { private List publicDiscoveryWorlds(CatalogSnapshot snapshot) { return visibleWorlds(snapshot).stream() - .map( - world -> - new WorldView( - world.slug(), - world.displayName(), - visibleRealms(world).stream() - .filter(RealmView::publicProductionRealm) - .filter( - realm -> - publicProductionRealmCardinality(snapshot, realm.tenantId()) - == PublicProductionRealmCardinality.EXACTLY_ONE) - .toList())) + .map(world -> + new WorldView( + world.slug(), + world.displayName(), + visibleRealms(world).stream() + .filter(RealmView::publicProductionRealm) + .filter(realm -> + publicProductionRealmCardinality(snapshot, realm.tenantId()) + == PublicProductionRealmCardinality.EXACTLY_ONE) + .toList())) .filter(world -> world.realms().size() == 1) .toList(); } @@ -784,15 +769,14 @@ private static List toWorlds(List p } return normalizeWorlds( worlds.values().stream() - .map( - world -> - new WorldView( - world.slug, - world.displayName, - world.realmsBySlug.entrySet().stream() - .filter(entry -> entry.getValue().size() == 1) - .map(entry -> toRealmView(entry.getValue().getFirst())) - .toList())) + .map(world -> + new WorldView( + world.slug, + world.displayName, + world.realmsBySlug.entrySet().stream() + .filter(entry -> entry.getValue().size() == 1) + .map(entry -> toRealmView(entry.getValue().getFirst())) + .toList())) .toList()); } @@ -921,11 +905,9 @@ private static WorldView copyWorldView(WorldView input) { input.slug(), input.displayName(), realms.stream() - .filter( - realm -> - realmCounts.get( - new RealmSelectorKey(realm.tenantId(), selectorKey(realm.slug()))) - == 1) + .filter(realm -> + realmCounts.get(new RealmSelectorKey(realm.tenantId(), selectorKey(realm.slug()))) + == 1) .toList()); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java index 1d411e6b68..ec3cce3dcc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/HelpCommandHandler.java @@ -292,11 +292,9 @@ private String topicIndex(Optional maybeContext) { "- HELP SAY", "- HELP WHISPER", "- HELP TELL")); - lines.removeIf( - line -> - line.startsWith("- HELP ") - && !isEnabled( - capabilityForTopic(line.substring("- HELP ".length())), maybeContext)); + lines.removeIf(line -> + line.startsWith("- HELP ") + && !isEnabled(capabilityForTopic(line.substring("- HELP ".length())), maybeContext)); List admittedDefinitions = admittedRegistryResolver == null ? List.of() @@ -327,10 +325,9 @@ private boolean isEnabled( } try { return maybeContext - .map( - context -> - commandCapabilitiesSettingsResolver.isEnabled( - capability, context.tenantId(), context.gameInstanceId())) + .map(context -> + commandCapabilitiesSettingsResolver.isEnabled( + capability, context.tenantId(), context.gameInstanceId())) .orElseGet(() -> commandCapabilitiesSettingsResolver.isEnabled(capability, 0L, null)); } catch (RuntimeException ex) { return false; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java index 15e7ffd123..2d56aa3c1b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java @@ -375,11 +375,10 @@ private SessionContext authenticatedBootstrapContext( private long resolveBootstrapGameInstanceId(long sessionId) { return sessionRoutingNormalizationService .resolveProjectedSessionContext(Long.toString(sessionId)) - .map( - context -> - context.bootstrapGameInstanceId() > 0 - ? context.bootstrapGameInstanceId() - : context.gameInstanceId()) + .map(context -> + context.bootstrapGameInstanceId() > 0 + ? context.bootstrapGameInstanceId() + : context.gameInstanceId()) .filter(candidate -> candidate > 0) .orElse(0L); } @@ -410,18 +409,17 @@ private Optional currentAdmissionPointer( gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(tenantId, gameInstanceId); Optional maybePointer = GameplayAdmissionPointerSnapshots.singularCompletePointer(pointers); - return maybePointer.filter( - pointer -> - GameplayAdmissionPointerSnapshots.matchesCurrentRuntimeTarget( - pointers, - tenantId, - gameInstanceId, - worldSlug, - realmSlug, - pointerVersion, - expectedPlayableStateScope != null - ? expectedPlayableStateScope - : pointer.stateScope())); + return maybePointer.filter(pointer -> + GameplayAdmissionPointerSnapshots.matchesCurrentRuntimeTarget( + pointers, + tenantId, + gameInstanceId, + worldSlug, + realmSlug, + pointerVersion, + expectedPlayableStateScope != null + ? expectedPlayableStateScope + : pointer.stateScope())); } private void clearFailedLoginSessionState( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index 9bc88481bc..f7793e5f1d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -339,9 +339,8 @@ public PlayCommandHandlingResult handle(String sessionId, TextCommand command) { .filter(SessionContext::hasGameplayRegionBinding); boolean resumedOrTookOver = existingBinding - .map( - existing -> - handleExistingBinding(context, existing, gameInstanceId, characterId)) + .map(existing -> + handleExistingBinding(context, existing, gameInstanceId, characterId)) .orElse(false); String roomInstanceId = @@ -504,10 +503,9 @@ private ResolvedCharacter resolveCharacter( if (StringUtils.hasText(requestedCharacter)) { List matches = roster.stream() - .filter( - character -> - Objects.equals( - normalizeName(character.getName()), normalizeName(requestedCharacter))) + .filter(character -> + Objects.equals( + normalizeName(character.getName()), normalizeName(requestedCharacter))) .toList(); if (matches.size() != 1) { throw new CharacterSelectionRequiredException( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/RegistryBackedTextCommandMetadataResolver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/RegistryBackedTextCommandMetadataResolver.java index 9ee43deae3..4d8f96674a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/RegistryBackedTextCommandMetadataResolver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/RegistryBackedTextCommandMetadataResolver.java @@ -19,13 +19,12 @@ public Optional resolve(String commandIdOrAlias) { return textCommandRegistry .findDefinition(commandIdOrAlias) .or(() -> textCommandRegistry.findDefinitionByAlias(commandIdOrAlias)) - .map( - definition -> - new ResolvedTextCommandMetadata( - definition.dispatchGroup(), - definition.promptPolicy(), - definition.actionCategory(), - definition.actionTags(), - definition.capability())); + .map(definition -> + new ResolvedTextCommandMetadata( + definition.dispatchGroup(), + definition.promptPolicy(), + definition.actionCategory(), + definition.actionTags(), + definition.capability())); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/StatusCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/StatusCommandHandler.java index a2a73e5732..05a71ed39b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/StatusCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/StatusCommandHandler.java @@ -42,22 +42,20 @@ public TextCommandInterpretationResult handle(TextCommand command, SessionContex PlayerOutput.view( new ActorStateViewOutput( response.getResourcesList().stream() - .map( - resource -> - new ActorStateViewOutput.Resource( - resource.getStatKey(), - resource.getCurrentValue(), - resource.hasMaxValue() ? resource.getMaxValue() : null, - resource.hasBaseValue() ? resource.getBaseValue() : null)) + .map(resource -> + new ActorStateViewOutput.Resource( + resource.getStatKey(), + resource.getCurrentValue(), + resource.hasMaxValue() ? resource.getMaxValue() : null, + resource.hasBaseValue() ? resource.getBaseValue() : null)) .sorted(Comparator.comparing(ActorStateViewOutput.Resource::key)) .toList(), response.getActiveConditionsList().stream() - .map( - condition -> - new ActorStateViewOutput.Condition( - condition.getConditionKey(), - condition.getStackCount(), - condition.getExpiresAt())) + .map(condition -> + new ActorStateViewOutput.Condition( + condition.getConditionKey(), + condition.getStackCount(), + condition.getExpiresAt())) .sorted(Comparator.comparing(ActorStateViewOutput.Condition::key)) .toList())))); } catch (RuntimeException ex) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandDispatchRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandDispatchRequest.java index b6cc65db33..9e671ff3e3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandDispatchRequest.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandDispatchRequest.java @@ -12,12 +12,11 @@ record TextCommandDispatchRequest( Optional observedDirectTextTransport) { TextCommandDispatchRequest { Objects.requireNonNull(observedDirectTextTransport, "transport observation must not be null"); - observedDirectTextTransport.ifPresent( - observed -> { - if (!Objects.equals(sessionId, observed.transportSessionId())) { - throw new IllegalArgumentException( - "Observed transport session ID must match dispatch session ID"); - } - }); + observedDirectTextTransport.ifPresent(observed -> { + if (!Objects.equals(sessionId, observed.transportSessionId())) { + throw new IllegalArgumentException( + "Observed transport session ID must match dispatch session ID"); + } + }); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java index 85ac46887f..cb5b038aac 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreter.java @@ -297,9 +297,8 @@ private TextCommandInterpretationResult interpret( TextCommandDefinition definition = activeRegistry .findDefinition(command.commandId()) - .orElseGet( - () -> - TextCommandDefinition.extensionDefinition(command.type(), command.commandId())); + .orElseGet(() -> + TextCommandDefinition.extensionDefinition(command.type(), command.commandId())); if (command.type() == TextCommandType.NOOP) { return withResolvedCommand( new TextCommandInterpretationResult(CommandEnqueueResult.success()), command, definition); @@ -378,28 +377,26 @@ private TextCommandInterpretationResult applyPromptPolicy( case NEVER -> result; case WHEN_LOGGED_IN -> maybeContext - .map( - context -> - new TextCommandInterpretationResult( - result.commandResult(), - appendPrompt(context, result.outputs()), - result.reconnectRedrawRecommended(), - result.meaningfulGameplayActivity(), - result.resolvedCommand(), - result.resolvedMetadata())) + .map(context -> + new TextCommandInterpretationResult( + result.commandResult(), + appendPrompt(context, result.outputs()), + result.reconnectRedrawRecommended(), + result.meaningfulGameplayActivity(), + result.resolvedCommand(), + result.resolvedMetadata())) .orElse(result); case WHEN_GAMEPLAY -> maybeContext .filter(SessionContext::hasGameplayRegionBinding) - .map( - context -> - new TextCommandInterpretationResult( - result.commandResult(), - appendPrompt(context, result.outputs()), - result.reconnectRedrawRecommended(), - result.meaningfulGameplayActivity(), - result.resolvedCommand(), - result.resolvedMetadata())) + .map(context -> + new TextCommandInterpretationResult( + result.commandResult(), + appendPrompt(context, result.outputs()), + result.reconnectRedrawRecommended(), + result.meaningfulGameplayActivity(), + result.resolvedCommand(), + result.resolvedMetadata())) .orElse(result); }; } @@ -472,10 +469,9 @@ private boolean isCapabilityEnabled( } try { return maybeContext - .map( - context -> - commandCapabilitiesSettingsResolver.isEnabled( - definition.capability(), context.tenantId(), context.gameInstanceId())) + .map(context -> + commandCapabilitiesSettingsResolver.isEnabled( + definition.capability(), context.tenantId(), context.gameInstanceId())) .orElse(true); } catch (RuntimeException ex) { LOG.warn( @@ -515,12 +511,11 @@ private List appendPrompt( List outputs) { return promptComposer .compose(context) - .map( - prompt -> { - java.util.ArrayList combined = new java.util.ArrayList<>(outputs); - combined.add(prompt); - return List.copyOf(combined); - }) + .map(prompt -> { + java.util.ArrayList combined = new java.util.ArrayList<>(outputs); + combined.add(prompt); + return List.copyOf(combined); + }) .orElse(outputs); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java index d0968ecf41..92c2ae61cf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/TextCommandParser.java @@ -50,16 +50,14 @@ public TextCommand parse(String rawLine, TextCommandRegistry registry) { TextCommandDefinition resolvedDefinition = registry .findDefinitionByAlias(aliasUsed) - .orElseGet( - () -> - registry - .findDefinition(aliasUsed) - .or( - () -> - normalizedCommandId.equals(aliasUsed) - ? java.util.Optional.empty() - : registry.findDefinition(normalizedCommandId)) - .orElse(null)); + .orElseGet(() -> + registry + .findDefinition(aliasUsed) + .or(() -> + normalizedCommandId.equals(aliasUsed) + ? java.util.Optional.empty() + : registry.findDefinition(normalizedCommandId)) + .orElse(null)); TextCommandType type = resolvedDefinition == null ? TextCommandType.UNKNOWN : resolvedDefinition.type(); String commandId = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java index 89766acfb7..440acfe7ed 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandler.java @@ -57,17 +57,13 @@ private TextCommandInterpretationResult handleRealms(TextCommand command) { return command .realmBrowsePayload() .flatMap(payload -> worldsHandler.browseRealms(payload.worldSelector())) - .map( - view -> - new TextCommandInterpretationResult( - net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), - List.of( - net.firedevops.firemud.gamesession.presentation.PlayerOutput.view(view)))) - .orElseGet( - () -> - errorResult( - "INVALID_ARGUMENT", - "REALMS requires a valid world selector. Use WORLDS first.")); + .map(view -> + new TextCommandInterpretationResult( + net.firedevops.firemud.gamesession.dto.CommandEnqueueResult.success(), + List.of(net.firedevops.firemud.gamesession.presentation.PlayerOutput.view(view)))) + .orElseGet(() -> + errorResult( + "INVALID_ARGUMENT", "REALMS requires a valid world selector. Use WORLDS first.")); } private TextCommandInterpretationResult handleChars(TextCommandDispatchRequest request) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/AsyncConfig.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/AsyncConfig.java index 6f3c6c5ae1..7073be16f2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/AsyncConfig.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/AsyncConfig.java @@ -58,11 +58,10 @@ public ThreadPoolTaskScheduler commandHistoryRetentionScheduler() { @Bean(name = "queueLockRenewalExecutor", destroyMethod = "shutdown") public ScheduledExecutorService queueLockRenewalExecutor() { - return Executors.newSingleThreadScheduledExecutor( - runnable -> { - Thread thread = new Thread(runnable, "queue-lock-renewal"); - thread.setDaemon(true); - return thread; - }); + return Executors.newSingleThreadScheduledExecutor(runnable -> { + Thread thread = new Thread(runnable, "queue-lock-renewal"); + thread.setDaemon(true); + return thread; + }); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/DurableResumeTranscriptConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/DurableResumeTranscriptConfiguration.java index 138ecee291..c01465fbe2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/DurableResumeTranscriptConfiguration.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/DurableResumeTranscriptConfiguration.java @@ -27,9 +27,8 @@ public ScreenBufferService durableScreenBufferService( MeterRegistry meterRegistry) { ScreenBufferService hotCache = Optional.ofNullable(redisTemplateProvider.getIfAvailable()) - .map( - redisTemplate -> - new RedisScreenBufferService(redisTemplate, objectMapper, settingsResolver)) + .map(redisTemplate -> + new RedisScreenBufferService(redisTemplate, objectMapper, settingsResolver)) .orElseGet(NoopScreenBufferService::new); return new DurableScreenBufferService(repository, settingsResolver, hotCache, meterRegistry); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionAccountPublicJwksConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionAccountPublicJwksConfiguration.java index 97caf6eded..4ed27ee178 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionAccountPublicJwksConfiguration.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameSessionAccountPublicJwksConfiguration.java @@ -92,12 +92,11 @@ static final class PublicJwksRefresh implements AutoCloseable { this( cache, maximumAge, - Executors.newSingleThreadScheduledExecutor( - task -> { - Thread thread = new Thread(task, "game-session-account-public-jwks-refresh"); - thread.setDaemon(true); - return thread; - })); + Executors.newSingleThreadScheduledExecutor(task -> { + Thread thread = new Thread(task, "game-session-account-public-jwks-refresh"); + thread.setDaemon(true); + return thread; + })); } PublicJwksRefresh( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java index 2b6cd3b1ca..932323d28c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java @@ -134,11 +134,9 @@ private SessionResolution resolveContext( SessionContext context = sessionAuthenticationService .resolveUnverifiedSessionContext(Long.toString(parsedSessionId)) - .orElseThrow( - () -> - new ResponseStatusException( - HttpStatus.NOT_FOUND, - "Session context not found for " + parsedSessionId)); + .orElseThrow(() -> + new ResponseStatusException( + HttpStatus.NOT_FOUND, "Session context not found for " + parsedSessionId)); return new SessionResolution(parsedSessionId, context, true); } long resolvedTenantId = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginJournalSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginJournalSnapshot.java index 88ebe7a7c0..7beafa0f7b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginJournalSnapshot.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginJournalSnapshot.java @@ -20,30 +20,24 @@ public record InitialGameplayLoginJournalSnapshot( Objects.requireNonNull(verifiedWitness, "verifiedWitness"); Objects.requireNonNull(frozenRetirementRequest, "frozenRetirementRequest"); Objects.requireNonNull(retainedReceipt, "retainedReceipt"); - verifiedWitness.ifPresent( - witness -> - InitialGameplayLoginDisposalResult.requireOriginalRequest( - request(coordinates, witness))); - frozenRetirementRequest.ifPresent( - request -> { - InitialGameplayLoginDisposalResult.requireOriginalRequest(request); - requireOriginal(coordinates, request.getRequestId(), request.getCallerContextId()); - if (!abandoned - || request.hasTokenWitness() - && !verifiedWitness.filter(request.getTokenWitness()::equals).isPresent()) { - throw new IllegalArgumentException( - "Invalid retained original LOGIN retirement request"); - } - }); - retainedReceipt.ifPresent( - receipt -> { - requireOriginal( - coordinates, receipt.requestId().toString(), receipt.callerContextId().toString()); - if (!abandoned || frozenRetirementRequest.isEmpty()) { - throw new IllegalArgumentException( - "Original LOGIN receipt requires frozen abandonment"); - } - }); + verifiedWitness.ifPresent(witness -> + InitialGameplayLoginDisposalResult.requireOriginalRequest(request(coordinates, witness))); + frozenRetirementRequest.ifPresent(request -> { + InitialGameplayLoginDisposalResult.requireOriginalRequest(request); + requireOriginal(coordinates, request.getRequestId(), request.getCallerContextId()); + if (!abandoned + || request.hasTokenWitness() + && !verifiedWitness.filter(request.getTokenWitness()::equals).isPresent()) { + throw new IllegalArgumentException("Invalid retained original LOGIN retirement request"); + } + }); + retainedReceipt.ifPresent(receipt -> { + requireOriginal( + coordinates, receipt.requestId().toString(), receipt.callerContextId().toString()); + if (!abandoned || frozenRetirementRequest.isEmpty()) { + throw new IllegalArgumentException("Original LOGIN receipt requires frozen abandonment"); + } + }); } public static RetireInitialGameplayLoginRequest request( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/LookViewOutput.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/LookViewOutput.java index f9cd0f7cf1..0f63f8bdbf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/LookViewOutput.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/LookViewOutput.java @@ -112,13 +112,12 @@ public static LookViewOutput from( .map(exit -> new LookViewExit(exit.getLabel(), exit.getDescription())) .collect(Collectors.toList()), result.getEntitiesList().stream() - .map( - entity -> - new LookViewEntity( - entity.getEntityType().name(), - entity.getDisplayName(), - entity.getRole(), - entity.getStateFlagsList().stream().collect(Collectors.toList()))) + .map(entity -> + new LookViewEntity( + entity.getEntityType().name(), + entity.getDisplayName(), + entity.getRole(), + entity.getStateFlagsList().stream().collect(Collectors.toList()))) .collect(Collectors.toList())); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java index 0c6bf6e041..530ee89b4f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/presentation/TextPlayerOutputRenderer.java @@ -361,16 +361,15 @@ private String renderWorldsView(WorldsViewOutput output) { private String renderRealmsView(RealmBrowseViewOutput output) { return output.realms().stream() - .map( - realm -> - realm.displayName() - + " (" - + realm.realmSlug() - + ") [" - + realm.stateScope().toLowerCase(java.util.Locale.ROOT) - + ", " - + realm.characterCreationPolicy().toLowerCase(java.util.Locale.ROOT) - + "]") + .map(realm -> + realm.displayName() + + " (" + + realm.realmSlug() + + ") [" + + realm.stateScope().toLowerCase(java.util.Locale.ROOT) + + ", " + + realm.characterCreationPolicy().toLowerCase(java.util.Locale.ROOT) + + "]") .collect(Collectors.joining("\n")); } @@ -388,14 +387,13 @@ private String renderCharactersView(CharacterBrowseViewOutput output) { } String roster = output.characters().stream() - .map( - character -> - character.ordinal() - + ") " - + character.characterName() - + " [lvl " - + character.level() - + "]") + .map(character -> + character.ordinal() + + ") " + + character.characterName() + + " [lvl " + + character.level() + + "]") .collect(Collectors.joining("\n")); return roster + "\n\n" @@ -443,13 +441,12 @@ private String renderActorStateView(ActorStateViewOutput output) { private String renderWhoEntries(List entries) { return entries.stream() - .map( - entry -> - switch (entry.activityState()) { - case "AUTO_AFK" -> entry.characterName() + " (idle)"; - case "EXPLICIT_AFK" -> entry.characterName() + " (AFK)"; - default -> entry.characterName(); - }) + .map(entry -> + switch (entry.activityState()) { + case "AUTO_AFK" -> entry.characterName() + " (idle)"; + case "EXPLICIT_AFK" -> entry.characterName() + " (AFK)"; + default -> entry.characterName(); + }) .collect(Collectors.joining(", ")); } @@ -466,17 +463,16 @@ private String renderFriendsView(FriendPresenceViewOutput output) { } String body = output.friends().stream() - .map( - entry -> - entry.ordinal() - + ") " - + entry.displayName() - + " [acct #" - + entry.friendAccountId() - + "]" - + renderFriendStatusSuffix(entry) - + " - " - + renderFriendStatus(entry)) + .map(entry -> + entry.ordinal() + + ") " + + entry.displayName() + + " [acct #" + + entry.friendAccountId() + + "]" + + renderFriendStatusSuffix(entry) + + " - " + + renderFriendStatus(entry)) .collect(Collectors.joining("\n")); if ("ALL".equalsIgnoreCase(output.filter())) { return body; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java index 004306f200..f0dcbf6a41 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java @@ -169,10 +169,9 @@ public CanonicalGameInstanceLaunchAssociation capture( CanonicalGameInstanceLaunchAssociation inserted = findByRequest(binding.descriptor().controlPlaneRequestId(), true) .map(this::toAssociation) - .orElseThrow( - () -> - new IllegalStateException( - "Canonical launch association insert readback is missing")); + .orElseThrow(() -> + new IllegalStateException( + "Canonical launch association insert readback is missing")); requireExactRetry( inserted, tenantAssociation, gameInstanceId, runtime, binding.evidence(), mapping, realm); return inserted; @@ -217,12 +216,11 @@ public Optional readWithCatalog(String controlPlaneReque requireOutsideTransaction(); requireRequestId(controlPlaneRequestId); return findByRequest(controlPlaneRequestId, false) - .map( - row -> - new HumanLaunchAssociation( - toAssociation(row), - requiredUuid(row, "canonical_realm_id"), - requiredLong(row, "catalog_revision"))); + .map(row -> + new HumanLaunchAssociation( + toAssociation(row), + requiredUuid(row, "canonical_realm_id"), + requiredLong(row, "catalog_revision"))); } public record HumanLaunchAssociation( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepository.java index 00e8e8da2f..24814e8281 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepository.java @@ -81,82 +81,81 @@ CanonicalGameplayAccountAdmissionFenceIntent beginFenceIntent(UUID accountId, UU requireNonNil(accountId, "accountId"); requireNonNil(requestId, "requestId"); requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger inventoryRevision = lockInventoryRevision(transaction); - Record control = lockExistingControl(transaction, accountId); - String controlState = control.get("state", String.class); - - Record priorIntent = - transaction.fetchOne( - "SELECT * FROM " + INTENT + " WHERE account_id = ? AND request_id = ? FOR UPDATE", - accountId, - requestId); - if ("ACQUISITION_INTENT".equals(controlState)) { - if (priorIntent == null) { - throw conflict("A different account-fence intent already owns this account"); - } - return loadAndRequireCurrent(transaction, control, priorIntent); - } - if (priorIntent != null) { - throw conflict("The requested account-fence intent is no longer the current owner"); - } - requireNoActiveControl(control, accountId); - CanonicalGameplayLegacyMigrationDisposition legacyDisposition = - readVerifiedLegacyDisposition(transaction, inventoryRevision, true); - requireNoFutureAccountRows(transaction, accountId, inventoryRevision); - - BigInteger previousFence = readBigInteger(control, "last_operation_fence"); - BigInteger operationFence = previousFence.add(BigInteger.ONE); - UUID operationId = randomNonNilUuid(); - while (operationId.equals(accountId) || operationId.equals(requestId)) { - operationId = randomNonNilUuid(); - } - UUID plannedAccountAdmissionFence = randomNonNilUuid(); - while (plannedAccountAdmissionFence.equals(operationId) - || plannedAccountAdmissionFence.equals(requestId) - || plannedAccountAdmissionFence.equals(accountId)) { - plannedAccountAdmissionFence = randomNonNilUuid(); - } - - List cohortRows = - captureCohortRows(transaction, accountId); - requireResolvableCohortScopes(cohortRows); - List barrierTargets = - captureBarrierTargets(transaction, accountId); - requireBarrierTargetsCoverCohort(cohortRows, barrierTargets); - String cohortDigest = digestCohortRows(cohortRows); - String barrierTargetDigest = digestBarrierTargets(barrierTargets); - insertIntent( - transaction, - operationId, - requestId, - accountId, - operationFence, - plannedAccountAdmissionFence, - inventoryRevision, - legacyDisposition, - cohortRows, - barrierTargets, - cohortDigest, - barrierTargetDigest); - closeNewPreparation( - transaction, + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger inventoryRevision = lockInventoryRevision(transaction); + Record control = lockExistingControl(transaction, accountId); + String controlState = control.get("state", String.class); + + Record priorIntent = + transaction.fetchOne( + "SELECT * FROM " + INTENT + " WHERE account_id = ? AND request_id = ? FOR UPDATE", accountId, - previousFence, - operationFence, - operationId, - plannedAccountAdmissionFence, - inventoryRevision); - Record savedIntent = - Objects.requireNonNull( - transaction.fetchOne( - "SELECT * FROM " + INTENT + " WHERE operation_id = ?", operationId), - "persisted account-fence intent must exist"); - Record savedControl = lockExistingControl(transaction, accountId); - return loadAndRequireCurrent(transaction, savedControl, savedIntent); - }); + requestId); + if ("ACQUISITION_INTENT".equals(controlState)) { + if (priorIntent == null) { + throw conflict("A different account-fence intent already owns this account"); + } + return loadAndRequireCurrent(transaction, control, priorIntent); + } + if (priorIntent != null) { + throw conflict("The requested account-fence intent is no longer the current owner"); + } + requireNoActiveControl(control, accountId); + CanonicalGameplayLegacyMigrationDisposition legacyDisposition = + readVerifiedLegacyDisposition(transaction, inventoryRevision, true); + requireNoFutureAccountRows(transaction, accountId, inventoryRevision); + + BigInteger previousFence = readBigInteger(control, "last_operation_fence"); + BigInteger operationFence = previousFence.add(BigInteger.ONE); + UUID operationId = randomNonNilUuid(); + while (operationId.equals(accountId) || operationId.equals(requestId)) { + operationId = randomNonNilUuid(); + } + UUID plannedAccountAdmissionFence = randomNonNilUuid(); + while (plannedAccountAdmissionFence.equals(operationId) + || plannedAccountAdmissionFence.equals(requestId) + || plannedAccountAdmissionFence.equals(accountId)) { + plannedAccountAdmissionFence = randomNonNilUuid(); + } + + List cohortRows = + captureCohortRows(transaction, accountId); + requireResolvableCohortScopes(cohortRows); + List barrierTargets = + captureBarrierTargets(transaction, accountId); + requireBarrierTargetsCoverCohort(cohortRows, barrierTargets); + String cohortDigest = digestCohortRows(cohortRows); + String barrierTargetDigest = digestBarrierTargets(barrierTargets); + insertIntent( + transaction, + operationId, + requestId, + accountId, + operationFence, + plannedAccountAdmissionFence, + inventoryRevision, + legacyDisposition, + cohortRows, + barrierTargets, + cohortDigest, + barrierTargetDigest); + closeNewPreparation( + transaction, + accountId, + previousFence, + operationFence, + operationId, + plannedAccountAdmissionFence, + inventoryRevision); + Record savedIntent = + Objects.requireNonNull( + transaction.fetchOne( + "SELECT * FROM " + INTENT + " WHERE operation_id = ?", operationId), + "persisted account-fence intent must exist"); + Record savedControl = lockExistingControl(transaction, accountId); + return loadAndRequireCurrent(transaction, savedControl, savedIntent); + }); } /** Reads and verifies the immutable persisted tuple, cohort rows, and target rows. */ @@ -164,45 +163,42 @@ CanonicalGameplayAccountAdmissionFenceIntent readFenceIntent(UUID accountId, UUI requireNonNil(accountId, "accountId"); requireNonNil(requestId, "requestId"); requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - Record control = readControl(transaction, accountId); - Record intent = - transaction.fetchOne( - "SELECT * FROM " + INTENT + " WHERE account_id = ? AND request_id = ?", - accountId, - requestId); - if (control == null || intent == null) { - throw conflict("The exact account-fence intent or its positive control row is missing"); - } - return loadAndRequireCurrent(transaction, control, intent); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + Record control = readControl(transaction, accountId); + Record intent = + transaction.fetchOne( + "SELECT * FROM " + INTENT + " WHERE account_id = ? AND request_id = ?", + accountId, + requestId); + if (control == null || intent == null) { + throw conflict("The exact account-fence intent or its positive control row is missing"); + } + return loadAndRequireCurrent(transaction, control, intent); + }); } /** Reloads the current durable intent and account control using only the operation identity. */ CanonicalGameplayAccountAdmissionFenceIntent readCurrentFenceIntent(UUID operationId) { requireNonNil(operationId, "operationId"); requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - Record intent = - transaction.fetchOne( - "SELECT * FROM " + INTENT + " WHERE operation_id = ?", operationId); - if (intent == null) { - throw conflict("The exact account-fence intent operation is missing"); - } - UUID accountId = - Objects.requireNonNull(intent.get("account_id", UUID.class), "intent account id"); - Record control = readControl(transaction, accountId); - if (control == null) { - throw conflict("The account-fence intent lost its positive account-control row"); - } - return loadAndRequireCurrent(transaction, control, intent); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + Record intent = + transaction.fetchOne("SELECT * FROM " + INTENT + " WHERE operation_id = ?", operationId); + if (intent == null) { + throw conflict("The exact account-fence intent operation is missing"); + } + UUID accountId = + Objects.requireNonNull(intent.get("account_id", UUID.class), "intent account id"); + Record control = readControl(transaction, accountId); + if (control == null) { + throw conflict("The account-fence intent lost its positive account-control row"); + } + return loadAndRequireCurrent(transaction, control, intent); + }); } /** @@ -223,196 +219,192 @@ StoredClosedBarrierReceipt acceptClosedBarrierReadback( throw conflict("CLOSED readback differs from the explicitly expected operation and target"); } - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + + // The prepare owner takes this same inventory-clock then account-control lock order. + // The operation lookup below is only a locator; current SQL ownership is reloaded. + lockInventoryRevision(transaction); + Record identity = + transaction.fetchOne( + "SELECT account_id FROM " + INTENT + " WHERE operation_id = ?", expectedOperationId); + if (identity == null) { + throw conflict("The exact CLOSED receipt acquisition intent is missing"); + } + UUID accountId = + Objects.requireNonNull(identity.get("account_id", UUID.class), "intent account id"); + Record control = lockExistingControl(transaction, accountId); + Record intentRow = + transaction.fetchOne( + "SELECT * FROM " + INTENT + " WHERE operation_id = ? FOR UPDATE", + expectedOperationId); + if (intentRow == null) { + throw conflict("The exact CLOSED receipt acquisition intent is missing"); + } + CanonicalGameplayAccountAdmissionFenceIntent currentIntent = + loadAndRequireCurrent(transaction, control, intentRow); + requireSameIntentSnapshot(readback.intent(), currentIntent); + if (!expectedOperationId.equals(currentIntent.operationId()) + || !accountId.equals(currentIntent.accountId()) + || !accountId.equals(readback.accountId())) { + throw conflict("CLOSED readback differs from the exact current intent owner"); + } - // The prepare owner takes this same inventory-clock then account-control lock order. - // The operation lookup below is only a locator; current SQL ownership is reloaded. - lockInventoryRevision(transaction); - Record identity = - transaction.fetchOne( - "SELECT account_id FROM " + INTENT + " WHERE operation_id = ?", - expectedOperationId); - if (identity == null) { - throw conflict("The exact CLOSED receipt acquisition intent is missing"); - } - UUID accountId = - Objects.requireNonNull(identity.get("account_id", UUID.class), "intent account id"); - Record control = lockExistingControl(transaction, accountId); - Record intentRow = - transaction.fetchOne( - "SELECT * FROM " + INTENT + " WHERE operation_id = ? FOR UPDATE", - expectedOperationId); - if (intentRow == null) { - throw conflict("The exact CLOSED receipt acquisition intent is missing"); - } - CanonicalGameplayAccountAdmissionFenceIntent currentIntent = - loadAndRequireCurrent(transaction, control, intentRow); - requireSameIntentSnapshot(readback.intent(), currentIntent); - if (!expectedOperationId.equals(currentIntent.operationId()) - || !accountId.equals(currentIntent.accountId()) - || !accountId.equals(readback.accountId())) { - throw conflict("CLOSED readback differs from the exact current intent owner"); - } + CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget target = + requireUniqueBarrierTarget(currentIntent, expectedTargetOrdinal); + Record persistedTarget = + transaction.fetchOne( + "SELECT account_id, tenant_id, playable_state_namespace_id, target_state FROM " + + BARRIER_TARGET + + " WHERE operation_id = ? AND target_ordinal = ? FOR SHARE", + expectedOperationId, + expectedTargetOrdinal); + if (persistedTarget == null + || !"REQUIRED".equals(persistedTarget.get("target_state", String.class)) + || !accountId.equals(persistedTarget.get("account_id", UUID.class)) + || !target.tenantId().equals(persistedTarget.get("tenant_id", UUID.class)) + || !target + .playableStateNamespaceId() + .equals(persistedTarget.get("playable_state_namespace_id", UUID.class))) { + throw conflict("CLOSED receipt target is not the exact current REQUIRED SQL target"); + } - CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget target = - requireUniqueBarrierTarget(currentIntent, expectedTargetOrdinal); - Record persistedTarget = - transaction.fetchOne( - "SELECT account_id, tenant_id, playable_state_namespace_id, target_state FROM " - + BARRIER_TARGET - + " WHERE operation_id = ? AND target_ordinal = ? FOR SHARE", - expectedOperationId, - expectedTargetOrdinal); - if (persistedTarget == null - || !"REQUIRED".equals(persistedTarget.get("target_state", String.class)) - || !accountId.equals(persistedTarget.get("account_id", UUID.class)) - || !target.tenantId().equals(persistedTarget.get("tenant_id", UUID.class)) - || !target - .playableStateNamespaceId() - .equals(persistedTarget.get("playable_state_namespace_id", UUID.class))) { - throw conflict("CLOSED receipt target is not the exact current REQUIRED SQL target"); - } + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = readback.assignment(); + requireReadbackAssignment( + assignment, currentIntent, target, expectedOperationId, expectedTargetOrdinal); + Record persistedTag = + transaction.fetchOne( + "SELECT tenant_id, allocation_version, tenant_gameplay_tag FROM " + + TENANT_TAG_MAPPING + + " WHERE tenant_id = ? FOR SHARE", + target.tenantId()); + if (persistedTag == null + || !target.tenantId().equals(persistedTag.get("tenant_id", UUID.class)) + || !Integer.valueOf(assignment.allocationVersion()) + .equals(persistedTag.get("allocation_version", Integer.class)) + || !assignment + .tenantGameplayTag() + .equals(persistedTag.get("tenant_gameplay_tag", String.class))) { + throw conflict("Persisted tenant mapping differs from the CLOSED readback assignment"); + } - CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = - readback.assignment(); - requireReadbackAssignment( - assignment, currentIntent, target, expectedOperationId, expectedTargetOrdinal); - Record persistedTag = - transaction.fetchOne( - "SELECT tenant_id, allocation_version, tenant_gameplay_tag FROM " - + TENANT_TAG_MAPPING - + " WHERE tenant_id = ? FOR SHARE", - target.tenantId()); - if (persistedTag == null - || !target.tenantId().equals(persistedTag.get("tenant_id", UUID.class)) - || !Integer.valueOf(assignment.allocationVersion()) - .equals(persistedTag.get("allocation_version", Integer.class)) - || !assignment - .tenantGameplayTag() - .equals(persistedTag.get("tenant_gameplay_tag", String.class))) { - throw conflict("Persisted tenant mapping differs from the CLOSED readback assignment"); - } + String redisKey = CanonicalGameplaySessionRedisKeys.accountAdmissionBarrier(assignment); + if (!redisKey.equals(readback.key())) { + throw conflict("Canonical CLOSED barrier key differs from the physical readback"); + } - String redisKey = CanonicalGameplaySessionRedisKeys.accountAdmissionBarrier(assignment); - if (!redisKey.equals(readback.key())) { - throw conflict("Canonical CLOSED barrier key differs from the physical readback"); - } + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before = + readback.beforeIncarnation(); + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after = + readback.afterIncarnation(); + requireVerifiedIncarnation(before, currentIntent, target, assignment); + requireVerifiedIncarnation(after, currentIntent, target, assignment); + if (!before.incarnationDigest().equals(after.incarnationDigest()) + || !before.acceptedAttestationDigest().equals(after.acceptedAttestationDigest()) + || after.issuedAtEpochMillis() < before.issuedAtEpochMillis() + || after.observedAtEpochMillis() < before.observedAtEpochMillis()) { + throw conflict("Protected observations changed incarnation or regressed"); + } - CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before = - readback.beforeIncarnation(); - CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after = - readback.afterIncarnation(); - requireVerifiedIncarnation(before, currentIntent, target, assignment); - requireVerifiedIncarnation(after, currentIntent, target, assignment); - if (!before.incarnationDigest().equals(after.incarnationDigest()) - || !before.acceptedAttestationDigest().equals(after.acceptedAttestationDigest()) - || after.issuedAtEpochMillis() < before.issuedAtEpochMillis() - || after.observedAtEpochMillis() < before.observedAtEpochMillis()) { - throw conflict("Protected observations changed incarnation or regressed"); - } + Map expectedFields = + expectedClosedBarrierFields(currentIntent, target, assignment, after.incarnationDigest()); + if (!CLOSED_BARRIER_FIELDS.equals(readback.barrierFields().keySet()) + || !expectedFields.equals(readback.barrierFields()) + || !CLOSED_BARRIER_SCHEMA.equals(readback.barrierFields().get("schema")) + || !CLOSED_BARRIER_STATE.equals(readback.barrierFields().get("state"))) { + throw conflict("Physical CLOSED barrier fields differ from the current owner tuple"); + } + requireSuccessfulClosedMutation(readback.mutationOutcome()); + String fieldsDigest = digestClosedBarrierFields(expectedFields); - Map expectedFields = - expectedClosedBarrierFields( - currentIntent, target, assignment, after.incarnationDigest()); - if (!CLOSED_BARRIER_FIELDS.equals(readback.barrierFields().keySet()) - || !expectedFields.equals(readback.barrierFields()) - || !CLOSED_BARRIER_SCHEMA.equals(readback.barrierFields().get("schema")) - || !CLOSED_BARRIER_STATE.equals(readback.barrierFields().get("state"))) { - throw conflict("Physical CLOSED barrier fields differ from the current owner tuple"); - } - requireSuccessfulClosedMutation(readback.mutationOutcome()); - String fieldsDigest = digestClosedBarrierFields(expectedFields); + // Clock is trusted owner configuration and is sampled only after all SQL guards. + long now = clock.millis(); + if (now <= 0) { + throw conflict("Trusted CLOSED receipt acceptance time must be positive"); + } + requireCurrentObservationWindow(before, now); + requireCurrentObservationWindow(after, now); - // Clock is trusted owner configuration and is sampled only after all SQL guards. - long now = clock.millis(); - if (now <= 0) { - throw conflict("Trusted CLOSED receipt acceptance time must be positive"); - } - requireCurrentObservationWindow(before, now); - requireCurrentObservationWindow(after, now); + Record existing = + transaction.fetchOne( + "SELECT * FROM " + + CLOSED_RECEIPT + + " WHERE operation_id = ? AND target_ordinal = ? FOR UPDATE", + expectedOperationId, + expectedTargetOrdinal); + if (existing != null) { + StoredClosedBarrierReceipt original = toStoredClosedBarrierReceipt(existing); + requireSameStoredBarrierIdentity( + original, + currentIntent, + target, + assignment, + redisKey, + fieldsDigest, + before.acceptedAttestationDigest(), + before.incarnationDigest()); + // A fresh protected observation has new source bytes/times. Exact retry returns the + // original immutable SQL row, including its original creation time and source digests. + return original; + } - Record existing = + transaction.execute( + "INSERT INTO " + + CLOSED_RECEIPT + + " (operation_id, request_id, account_id, operation_fence," + + " planned_account_admission_fence, inventory_snapshot_revision, cohort_digest," + + " barrier_target_digest, target_ordinal, tenant_id," + + " playable_state_namespace_id, tenant_gameplay_tag, workload_namespace," + + " allocation_version, barrier_key, barrier_schema, incarnation_digest," + + " barrier_state, accepted_attestation_digest, barrier_fields_digest," + + " before_source_payload_digest, before_observation_issued_at_epoch_millis," + + " before_observation_observed_at_epoch_millis," + + " before_observation_expires_at_epoch_millis, after_source_payload_digest," + + " after_observation_issued_at_epoch_millis," + + " after_observation_observed_at_epoch_millis," + + " after_observation_expires_at_epoch_millis)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," + + " ?, ?, ?, ?, ?, ?)", + currentIntent.operationId(), + currentIntent.requestId(), + currentIntent.accountId(), + decimal(currentIntent.operationFence()), + currentIntent.plannedAccountAdmissionFence(), + decimal(currentIntent.inventorySnapshotRevision()), + currentIntent.cohortDigest(), + currentIntent.barrierTargetDigest(), + target.ordinal(), + target.tenantId(), + target.playableStateNamespaceId(), + assignment.tenantGameplayTag(), + assignment.workloadNamespace(), + assignment.allocationVersion(), + redisKey, + CLOSED_BARRIER_SCHEMA, + after.incarnationDigest(), + CLOSED_BARRIER_STATE, + before.acceptedAttestationDigest(), + fieldsDigest, + before.payloadDigest(), + before.issuedAtEpochMillis(), + before.observedAtEpochMillis(), + before.expiresAtEpochMillis(), + after.payloadDigest(), + after.issuedAtEpochMillis(), + after.observedAtEpochMillis(), + after.expiresAtEpochMillis()); + + Record saved = + Objects.requireNonNull( transaction.fetchOne( "SELECT * FROM " + CLOSED_RECEIPT + " WHERE operation_id = ? AND target_ordinal = ? FOR UPDATE", expectedOperationId, - expectedTargetOrdinal); - if (existing != null) { - StoredClosedBarrierReceipt original = toStoredClosedBarrierReceipt(existing); - requireSameStoredBarrierIdentity( - original, - currentIntent, - target, - assignment, - redisKey, - fieldsDigest, - before.acceptedAttestationDigest(), - before.incarnationDigest()); - // A fresh protected observation has new source bytes/times. Exact retry returns the - // original immutable SQL row, including its original creation time and source digests. - return original; - } - - transaction.execute( - "INSERT INTO " - + CLOSED_RECEIPT - + " (operation_id, request_id, account_id, operation_fence," - + " planned_account_admission_fence, inventory_snapshot_revision, cohort_digest," - + " barrier_target_digest, target_ordinal, tenant_id," - + " playable_state_namespace_id, tenant_gameplay_tag, workload_namespace," - + " allocation_version, barrier_key, barrier_schema, incarnation_digest," - + " barrier_state, accepted_attestation_digest, barrier_fields_digest," - + " before_source_payload_digest, before_observation_issued_at_epoch_millis," - + " before_observation_observed_at_epoch_millis," - + " before_observation_expires_at_epoch_millis, after_source_payload_digest," - + " after_observation_issued_at_epoch_millis," - + " after_observation_observed_at_epoch_millis," - + " after_observation_expires_at_epoch_millis)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?," - + " ?, ?, ?, ?, ?, ?)", - currentIntent.operationId(), - currentIntent.requestId(), - currentIntent.accountId(), - decimal(currentIntent.operationFence()), - currentIntent.plannedAccountAdmissionFence(), - decimal(currentIntent.inventorySnapshotRevision()), - currentIntent.cohortDigest(), - currentIntent.barrierTargetDigest(), - target.ordinal(), - target.tenantId(), - target.playableStateNamespaceId(), - assignment.tenantGameplayTag(), - assignment.workloadNamespace(), - assignment.allocationVersion(), - redisKey, - CLOSED_BARRIER_SCHEMA, - after.incarnationDigest(), - CLOSED_BARRIER_STATE, - before.acceptedAttestationDigest(), - fieldsDigest, - before.payloadDigest(), - before.issuedAtEpochMillis(), - before.observedAtEpochMillis(), - before.expiresAtEpochMillis(), - after.payloadDigest(), - after.issuedAtEpochMillis(), - after.observedAtEpochMillis(), - after.expiresAtEpochMillis()); - - Record saved = - Objects.requireNonNull( - transaction.fetchOne( - "SELECT * FROM " - + CLOSED_RECEIPT - + " WHERE operation_id = ? AND target_ordinal = ? FOR UPDATE", - expectedOperationId, - expectedTargetOrdinal), - "inserted CLOSED receipt must exist"); - return toStoredClosedBarrierReceipt(saved); - }); + expectedTargetOrdinal), + "inserted CLOSED receipt must exist"); + return toStoredClosedBarrierReceipt(saved); + }); } private static void insertIntent( @@ -838,24 +830,23 @@ private static List read + COHORT + " WHERE operation_id = ? ORDER BY row_ordinal", operationId) - .map( - row -> { - CanonicalGameplayAccountAdmissionFenceIntent.CohortKind kind; - try { - kind = - CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.valueOf( - row.get("source_kind", String.class)); - } catch (RuntimeException malformed) { - throw conflict("Persisted account-fence cohort contains an unknown source kind"); - } - return CanonicalGameplayAccountAdmissionFenceIntent.cohortRow( - readLong(row, "row_ordinal"), - kind, - row.get("source_key", String.class), - row.get("tenant_id", UUID.class), - row.get("playable_state_namespace_id", UUID.class), - row.get("source_record_json", String.class)); - }); + .map(row -> { + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind kind; + try { + kind = + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.valueOf( + row.get("source_kind", String.class)); + } catch (RuntimeException malformed) { + throw conflict("Persisted account-fence cohort contains an unknown source kind"); + } + return CanonicalGameplayAccountAdmissionFenceIntent.cohortRow( + readLong(row, "row_ordinal"), + kind, + row.get("source_key", String.class), + row.get("tenant_id", UUID.class), + row.get("playable_state_namespace_id", UUID.class), + row.get("source_record_json", String.class)); + }); } private static List @@ -866,12 +857,11 @@ private static List read + BARRIER_TARGET + " WHERE operation_id = ? ORDER BY target_ordinal", operationId) - .map( - row -> - CanonicalGameplayAccountAdmissionFenceIntent.barrierTarget( - readLong(row, "target_ordinal"), - row.get("tenant_id", UUID.class), - row.get("playable_state_namespace_id", UUID.class))); + .map(row -> + CanonicalGameplayAccountAdmissionFenceIntent.barrierTarget( + readLong(row, "target_ordinal"), + row.get("tenant_id", UUID.class), + row.get("playable_state_namespace_id", UUID.class))); } private static CanonicalGameplayLegacyMigrationDisposition readVerifiedLegacyDisposition( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java index ed4281cef3..4bc49c2064 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java @@ -66,118 +66,112 @@ InitializerSnapshot beginOrRead( requireOriginalEvidence(original, accountEvidence); String accountEvidenceDigest = digestAccountEvidence(accountEvidence); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger inventoryRevision = lockInventoryRevision(transaction); - Record control = lockExistingControl(transaction, accountEvidence.accountId()); - AccountControlSource source = readNoActiveControl(control, accountEvidence.accountId()); - if (inventoryRevision.signum() <= 0) { - throw conflict( - "Initial account barrier requires positive canonical inventory revision"); - } - requireExactOriginalLogin(transaction, original, accountEvidence); - - Record prior = readInitializer(transaction, original.requestId(), true); - if (prior != null) { - InitializerSnapshot snapshot = toSnapshot(prior); - requireSameOriginalTarget( - snapshot, - original, - accountEvidence.accountId(), - tenantId, - playableStateNamespaceId, - accountEvidenceDigest); - requireSameCurrentSource(snapshot, source); - return snapshot; - } - - UUID initializerId = randomNonNilUuid(); - while (initializerId.equals(original.requestId()) - || initializerId.equals(original.callerContextId()) - || initializerId.equals(accountEvidence.accountId())) { - initializerId = randomNonNilUuid(); - } - transaction.execute( - "INSERT INTO " - + INITIALIZER - + " (initializer_id, original_request_id, original_caller_context_id," - + " original_attempt_fence, account_id, account_login_evidence_digest," - + " source_control_state, source_control_epoch, inventory_snapshot_revision," - + " source_control_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - initializerId, - original.requestId(), - original.callerContextId(), - original.expectedAttemptFence(), - accountEvidence.accountId(), - accountEvidenceDigest, - NO_ACTIVE, - new BigDecimal(source.epoch()), - new BigDecimal(inventoryRevision), - source.digest()); - transaction.execute( - "INSERT INTO " - + TARGET - + " (initializer_id, original_request_id, account_id, target_ordinal, tenant_id," - + " playable_state_namespace_id, target_state)" - + " VALUES (?, ?, ?, 0, ?, ?, 'NEVER_DISPATCHED')", - initializerId, - original.requestId(), - accountEvidence.accountId(), - tenantId, - playableStateNamespaceId); - Record created = readInitializer(transaction, original.requestId(), true); - if (created == null) throw conflict("Initial account barrier target readback is missing"); - InitializerSnapshot snapshot = toSnapshot(created); - requireSameOriginalTarget( - snapshot, - original, - accountEvidence.accountId(), - tenantId, - playableStateNamespaceId, - accountEvidenceDigest); - requireSameCurrentSource(snapshot, source); - return snapshot; - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger inventoryRevision = lockInventoryRevision(transaction); + Record control = lockExistingControl(transaction, accountEvidence.accountId()); + AccountControlSource source = readNoActiveControl(control, accountEvidence.accountId()); + if (inventoryRevision.signum() <= 0) { + throw conflict("Initial account barrier requires positive canonical inventory revision"); + } + requireExactOriginalLogin(transaction, original, accountEvidence); + + Record prior = readInitializer(transaction, original.requestId(), true); + if (prior != null) { + InitializerSnapshot snapshot = toSnapshot(prior); + requireSameOriginalTarget( + snapshot, + original, + accountEvidence.accountId(), + tenantId, + playableStateNamespaceId, + accountEvidenceDigest); + requireSameCurrentSource(snapshot, source); + return snapshot; + } + + UUID initializerId = randomNonNilUuid(); + while (initializerId.equals(original.requestId()) + || initializerId.equals(original.callerContextId()) + || initializerId.equals(accountEvidence.accountId())) { + initializerId = randomNonNilUuid(); + } + transaction.execute( + "INSERT INTO " + + INITIALIZER + + " (initializer_id, original_request_id, original_caller_context_id," + + " original_attempt_fence, account_id, account_login_evidence_digest," + + " source_control_state, source_control_epoch, inventory_snapshot_revision," + + " source_control_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + initializerId, + original.requestId(), + original.callerContextId(), + original.expectedAttemptFence(), + accountEvidence.accountId(), + accountEvidenceDigest, + NO_ACTIVE, + new BigDecimal(source.epoch()), + new BigDecimal(inventoryRevision), + source.digest()); + transaction.execute( + "INSERT INTO " + + TARGET + + " (initializer_id, original_request_id, account_id, target_ordinal, tenant_id," + + " playable_state_namespace_id, target_state)" + + " VALUES (?, ?, ?, 0, ?, ?, 'NEVER_DISPATCHED')", + initializerId, + original.requestId(), + accountEvidence.accountId(), + tenantId, + playableStateNamespaceId); + Record created = readInitializer(transaction, original.requestId(), true); + if (created == null) throw conflict("Initial account barrier target readback is missing"); + InitializerSnapshot snapshot = toSnapshot(created); + requireSameOriginalTarget( + snapshot, + original, + accountEvidence.accountId(), + tenantId, + playableStateNamespaceId, + accountEvidenceDigest); + requireSameCurrentSource(snapshot, source); + return snapshot; + }); } /** Reads the exact live owner context for protected INITIAL incarnation observation. */ InitialObservationContext readCurrentObservationContext(UUID originalRequestId) { requireNonNil(originalRequestId, "originalRequestId"); requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - Record row = readInitializer(transaction, originalRequestId, false); - if (row == null) throw conflict("Exact original INITIAL account target is missing"); - InitializerSnapshot snapshot = toSnapshot(row); - AccountControlSource current = - readCurrentNoActiveControl(transaction, snapshot.accountId()); - requireSameCurrentSource(snapshot, current); - if (snapshot.state() != State.OPEN_INSTALLED) { - requireOriginalJournalStillCurrent(transaction, snapshot); - } - return InitialObservationContext.from(snapshot); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + Record row = readInitializer(transaction, originalRequestId, false); + if (row == null) throw conflict("Exact original INITIAL account target is missing"); + InitializerSnapshot snapshot = toSnapshot(row); + AccountControlSource current = readCurrentNoActiveControl(transaction, snapshot.accountId()); + requireSameCurrentSource(snapshot, current); + if (snapshot.state() != State.OPEN_INSTALLED) { + requireOriginalJournalStillCurrent(transaction, snapshot); + } + return InitialObservationContext.from(snapshot); + }); } InitializerSnapshot readCurrent(UUID originalRequestId) { requireNonNil(originalRequestId, "originalRequestId"); requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - InitializerSnapshot snapshot = readRequiredCurrent(transaction, originalRequestId, false); - AccountControlSource current = - readCurrentNoActiveControl(transaction, snapshot.accountId()); - requireSameCurrentSource(snapshot, current); - if (snapshot.state() != State.OPEN_INSTALLED) { - requireOriginalJournalStillCurrent(transaction, snapshot); - } - return snapshot; - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + InitializerSnapshot snapshot = readRequiredCurrent(transaction, originalRequestId, false); + AccountControlSource current = readCurrentNoActiveControl(transaction, snapshot.accountId()); + requireSameCurrentSource(snapshot, current); + if (snapshot.state() != State.OPEN_INSTALLED) { + requireOriginalJournalStillCurrent(transaction, snapshot); + } + return snapshot; + }); } /** @@ -191,53 +185,52 @@ InitializerSnapshot readInstalledOpenForTarget( requireNonNil(tenantId, "tenantId"); requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - var rows = - transaction.fetch( - "SELECT i.initializer_id, i.original_request_id, i.original_caller_context_id," - + " i.original_attempt_fence, i.account_id, i.account_login_evidence_digest," - + " i.source_control_state, i.source_control_epoch," - + " i.inventory_snapshot_revision, i.source_control_digest, t.tenant_id," - + " t.playable_state_namespace_id, t.target_state," - + " t.before_accepted_attestation_digest, t.before_incarnation_digest," - + " t.before_source_payload_digest," - + " t.before_observation_issued_at_epoch_millis," - + " t.before_observation_observed_at_epoch_millis," - + " t.before_observation_expires_at_epoch_millis, t.installed_fields_digest" - + " FROM " - + INITIALIZER - + " i JOIN " - + TARGET - + " t ON t.initializer_id = i.initializer_id" - + " AND t.original_request_id = i.original_request_id" - + " WHERE i.account_id = ? AND t.account_id = ? AND t.tenant_id = ?" - + " AND t.playable_state_namespace_id = ?" - + " AND t.target_state = 'OPEN_INSTALLED'" - + " ORDER BY i.initializer_id, t.target_ordinal", - accountId, - accountId, - tenantId, - playableStateNamespaceId); - if (rows.size() != 1) { - throw conflict( - rows.isEmpty() - ? "No retained installed INITIAL OPEN target matches the exact account scope" - : "Multiple retained installed INITIAL OPEN targets match the exact account scope"); - } - InitializerSnapshot snapshot = toSnapshot(rows.get(0)); - if (snapshot.state() != State.OPEN_INSTALLED - || !accountId.equals(snapshot.accountId()) - || !tenantId.equals(snapshot.tenantId()) - || !playableStateNamespaceId.equals(snapshot.playableStateNamespaceId())) { - throw conflict("Retained INITIAL OPEN target differs from the exact account scope"); - } - AccountControlSource current = readCurrentNoActiveControl(transaction, accountId); - requireSameCurrentSource(snapshot, current); - return snapshot; - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + var rows = + transaction.fetch( + "SELECT i.initializer_id, i.original_request_id, i.original_caller_context_id," + + " i.original_attempt_fence, i.account_id, i.account_login_evidence_digest," + + " i.source_control_state, i.source_control_epoch," + + " i.inventory_snapshot_revision, i.source_control_digest, t.tenant_id," + + " t.playable_state_namespace_id, t.target_state," + + " t.before_accepted_attestation_digest, t.before_incarnation_digest," + + " t.before_source_payload_digest," + + " t.before_observation_issued_at_epoch_millis," + + " t.before_observation_observed_at_epoch_millis," + + " t.before_observation_expires_at_epoch_millis, t.installed_fields_digest" + + " FROM " + + INITIALIZER + + " i JOIN " + + TARGET + + " t ON t.initializer_id = i.initializer_id" + + " AND t.original_request_id = i.original_request_id" + + " WHERE i.account_id = ? AND t.account_id = ? AND t.tenant_id = ?" + + " AND t.playable_state_namespace_id = ?" + + " AND t.target_state = 'OPEN_INSTALLED'" + + " ORDER BY i.initializer_id, t.target_ordinal", + accountId, + accountId, + tenantId, + playableStateNamespaceId); + if (rows.size() != 1) { + throw conflict( + rows.isEmpty() + ? "No retained installed INITIAL OPEN target matches the exact account scope" + : "Multiple retained installed INITIAL OPEN targets match the exact account scope"); + } + InitializerSnapshot snapshot = toSnapshot(rows.get(0)); + if (snapshot.state() != State.OPEN_INSTALLED + || !accountId.equals(snapshot.accountId()) + || !tenantId.equals(snapshot.tenantId()) + || !playableStateNamespaceId.equals(snapshot.playableStateNamespaceId())) { + throw conflict("Retained INITIAL OPEN target differs from the exact account scope"); + } + AccountControlSource current = readCurrentNoActiveControl(transaction, accountId); + requireSameCurrentSource(snapshot, current); + return snapshot; + }); } /** @@ -250,51 +243,50 @@ InitializerSnapshot recordDispatchPossible( requireNonNil(originalRequestId, "originalRequestId"); Objects.requireNonNull(beforeIncarnation, "beforeIncarnation"); requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - lockInventoryRevision(transaction); - Record locator = readInitializer(transaction, originalRequestId, false); - if (locator == null) throw conflict("Exact original INITIAL account target is missing"); - InitializerSnapshot located = toSnapshot(locator); - Record control = lockExistingControl(transaction, located.accountId()); - AccountControlSource source = readNoActiveControl(control, located.accountId()); - InitializerSnapshot current = readRequiredCurrent(transaction, originalRequestId, true); - requireSameCurrentSource(current, source); - requireOriginalJournalStillCurrent(transaction, current); - requireInitialObservationMatches(current, beforeIncarnation); - if (current.state() != State.NEVER_DISPATCHED) { - throw conflict("INITIAL remote attempt was already possible and cannot be reissued"); - } - int updated = - transaction.execute( - "UPDATE " - + TARGET - + " SET target_state = 'DISPATCH_POSSIBLE'," - + " before_accepted_attestation_digest = ?, before_incarnation_digest = ?," - + " before_source_payload_digest = ?," - + " before_observation_issued_at_epoch_millis = ?," - + " before_observation_observed_at_epoch_millis = ?," - + " before_observation_expires_at_epoch_millis = ?" - + " WHERE initializer_id = ? AND target_ordinal = 0" - + " AND target_state = 'NEVER_DISPATCHED'", - beforeIncarnation.acceptedAttestationDigest(), - beforeIncarnation.incarnationDigest(), - beforeIncarnation.payloadDigest(), - beforeIncarnation.issuedAtEpochMillis(), - beforeIncarnation.observedAtEpochMillis(), - beforeIncarnation.expiresAtEpochMillis(), - current.initializerId()); - requireOne(updated, "INITIAL one-time remote dispatch claim was lost"); - InitializerSnapshot saved = readRequiredCurrent(transaction, originalRequestId, true); - if (saved.state() != State.DISPATCH_POSSIBLE - || !saved.beforeIncarnationDigest().equals(beforeIncarnation.incarnationDigest()) - || !saved.beforeSourcePayloadDigest().equals(beforeIncarnation.payloadDigest())) { - throw conflict("INITIAL remote dispatch state did not read back exactly"); - } - requireSameCurrentSource(saved, source); - return saved; - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + lockInventoryRevision(transaction); + Record locator = readInitializer(transaction, originalRequestId, false); + if (locator == null) throw conflict("Exact original INITIAL account target is missing"); + InitializerSnapshot located = toSnapshot(locator); + Record control = lockExistingControl(transaction, located.accountId()); + AccountControlSource source = readNoActiveControl(control, located.accountId()); + InitializerSnapshot current = readRequiredCurrent(transaction, originalRequestId, true); + requireSameCurrentSource(current, source); + requireOriginalJournalStillCurrent(transaction, current); + requireInitialObservationMatches(current, beforeIncarnation); + if (current.state() != State.NEVER_DISPATCHED) { + throw conflict("INITIAL remote attempt was already possible and cannot be reissued"); + } + int updated = + transaction.execute( + "UPDATE " + + TARGET + + " SET target_state = 'DISPATCH_POSSIBLE'," + + " before_accepted_attestation_digest = ?, before_incarnation_digest = ?," + + " before_source_payload_digest = ?," + + " before_observation_issued_at_epoch_millis = ?," + + " before_observation_observed_at_epoch_millis = ?," + + " before_observation_expires_at_epoch_millis = ?" + + " WHERE initializer_id = ? AND target_ordinal = 0" + + " AND target_state = 'NEVER_DISPATCHED'", + beforeIncarnation.acceptedAttestationDigest(), + beforeIncarnation.incarnationDigest(), + beforeIncarnation.payloadDigest(), + beforeIncarnation.issuedAtEpochMillis(), + beforeIncarnation.observedAtEpochMillis(), + beforeIncarnation.expiresAtEpochMillis(), + current.initializerId()); + requireOne(updated, "INITIAL one-time remote dispatch claim was lost"); + InitializerSnapshot saved = readRequiredCurrent(transaction, originalRequestId, true); + if (saved.state() != State.DISPATCH_POSSIBLE + || !saved.beforeIncarnationDigest().equals(beforeIncarnation.incarnationDigest()) + || !saved.beforeSourcePayloadDigest().equals(beforeIncarnation.payloadDigest())) { + throw conflict("INITIAL remote dispatch state did not read back exactly"); + } + requireSameCurrentSource(saved, source); + return saved; + }); } /** @@ -313,60 +305,58 @@ InitializerSnapshot acceptOpenReadback( requireReadback(readback); String fieldsDigest = digestFields(readback.value().fields()); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - lockInventoryRevision(transaction); - Record locator = readInitializer(transaction, originalRequestId, false); - if (locator == null) throw conflict("Exact original INITIAL account target is missing"); - InitializerSnapshot located = toSnapshot(locator); - Record control = lockExistingControl(transaction, located.accountId()); - AccountControlSource source = readNoActiveControl(control, located.accountId()); - InitializerSnapshot current = readRequiredCurrent(transaction, originalRequestId, true); - requireSameCurrentSource(current, source); - requireOriginalJournalStillCurrent(transaction, current); - requireSameReadbackContext(current, readback); - long now = clock.millis(); - if (now <= 0 - || now < readback.beforeIncarnation().issuedAtEpochMillis() - || now >= readback.beforeIncarnation().expiresAtEpochMillis() - || now < readback.afterIncarnation().issuedAtEpochMillis() - || now >= readback.afterIncarnation().expiresAtEpochMillis()) { - throw conflict( - "INITIAL protected incarnation observation expired before SQL completion"); - } - if (current.state() == State.OPEN_INSTALLED) { - if (!fieldsDigest.equals(current.installedFieldsDigest())) { - throw conflict("An installed INITIAL OPEN value cannot be replaced"); - } - return current; - } - if (current.state() != State.DISPATCH_POSSIBLE) { - throw conflict("INITIAL OPEN readback has no persisted possible-dispatch state"); - } - int updated = - transaction.execute( - "UPDATE " - + TARGET - + " SET target_state = 'OPEN_INSTALLED', installed_fields_digest = ?," - + " completed_at = CURRENT_TIMESTAMP" - + " WHERE initializer_id = ? AND target_ordinal = 0" - + " AND target_state = 'DISPATCH_POSSIBLE'" - + " AND before_incarnation_digest = ?" - + " AND before_accepted_attestation_digest = ?", - fieldsDigest, - current.initializerId(), - readback.beforeIncarnation().incarnationDigest(), - readback.beforeIncarnation().acceptedAttestationDigest()); - requireOne(updated, "INITIAL OPEN completion lost its exact original SQL target"); - InitializerSnapshot saved = readRequiredCurrent(transaction, originalRequestId, true); - if (saved.state() != State.OPEN_INSTALLED - || !fieldsDigest.equals(saved.installedFieldsDigest())) { - throw conflict("INITIAL OPEN completion readback differs from its exact SQL postimage"); - } - requireSameCurrentSource(saved, source); - return saved; - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + lockInventoryRevision(transaction); + Record locator = readInitializer(transaction, originalRequestId, false); + if (locator == null) throw conflict("Exact original INITIAL account target is missing"); + InitializerSnapshot located = toSnapshot(locator); + Record control = lockExistingControl(transaction, located.accountId()); + AccountControlSource source = readNoActiveControl(control, located.accountId()); + InitializerSnapshot current = readRequiredCurrent(transaction, originalRequestId, true); + requireSameCurrentSource(current, source); + requireOriginalJournalStillCurrent(transaction, current); + requireSameReadbackContext(current, readback); + long now = clock.millis(); + if (now <= 0 + || now < readback.beforeIncarnation().issuedAtEpochMillis() + || now >= readback.beforeIncarnation().expiresAtEpochMillis() + || now < readback.afterIncarnation().issuedAtEpochMillis() + || now >= readback.afterIncarnation().expiresAtEpochMillis()) { + throw conflict("INITIAL protected incarnation observation expired before SQL completion"); + } + if (current.state() == State.OPEN_INSTALLED) { + if (!fieldsDigest.equals(current.installedFieldsDigest())) { + throw conflict("An installed INITIAL OPEN value cannot be replaced"); + } + return current; + } + if (current.state() != State.DISPATCH_POSSIBLE) { + throw conflict("INITIAL OPEN readback has no persisted possible-dispatch state"); + } + int updated = + transaction.execute( + "UPDATE " + + TARGET + + " SET target_state = 'OPEN_INSTALLED', installed_fields_digest = ?," + + " completed_at = CURRENT_TIMESTAMP" + + " WHERE initializer_id = ? AND target_ordinal = 0" + + " AND target_state = 'DISPATCH_POSSIBLE'" + + " AND before_incarnation_digest = ?" + + " AND before_accepted_attestation_digest = ?", + fieldsDigest, + current.initializerId(), + readback.beforeIncarnation().incarnationDigest(), + readback.beforeIncarnation().acceptedAttestationDigest()); + requireOne(updated, "INITIAL OPEN completion lost its exact original SQL target"); + InitializerSnapshot saved = readRequiredCurrent(transaction, originalRequestId, true); + if (saved.state() != State.OPEN_INSTALLED + || !fieldsDigest.equals(saved.installedFieldsDigest())) { + throw conflict("INITIAL OPEN completion readback differs from its exact SQL postimage"); + } + requireSameCurrentSource(saved, source); + return saved; + }); } void requireNoAmbientTransaction() { @@ -375,13 +365,12 @@ void requireNoAmbientTransaction() { throw conflict("INITIAL account barrier phases require no ambient SQL transaction"); } try { - dsl.connectionResult( - connection -> { - if (!connection.getAutoCommit()) { - throw conflict("INITIAL account barrier phases cannot join a jOOQ transaction"); - } - return Boolean.TRUE; - }); + dsl.connectionResult(connection -> { + if (!connection.getAutoCommit()) { + throw conflict("INITIAL account barrier phases cannot join a jOOQ transaction"); + } + return Boolean.TRUE; + }); } catch (RuntimeException failure) { if (failure instanceof CanonicalGameplayBindingInventoryConflictException) throw failure; throw conflict("INITIAL account barrier SQL connection state is unavailable"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index ead11ff154..44dbb206df 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -99,30 +99,29 @@ CanonicalGameplayBindingTransitionSnapshot prepareAfterInstalledIssuerAnchor( Objects.requireNonNull(requestFactory, "requestFactory"); Objects.requireNonNull(currentIssuerState, "currentIssuerState"); Objects.requireNonNull(registrationRecorder, "registrationRecorder"); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger revision = lockInventoryRevision(transaction); - CanonicalGameplayIssuerInstalledAnchor actualAnchor = - CanonicalGameplayIssuerBootstrapCoverageRepository - .readInstalledAnchorForBindingPreparationInTransaction( - transaction, currentIssuerState); - CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( - transaction, actualAnchor, currentIssuerState); - InstalledAnchorPreparationContext context = - new InstalledAnchorPreparationContext(revision, actualAnchor, currentIssuerState); - CanonicalGameplayBindingTransitionRequest request = - Objects.requireNonNull( - requestFactory.create(transaction, actualAnchor, currentIssuerState), - "installed-anchor request factory returned null"); - validateRequest(request); - if (request.expectedPriorBindingRef() != null - || request.expectedPriorBindingGeneration() != null) { - throw conflict("Installed-anchor local issuer operation accepts only ordinary NEW"); - } - requireCandidateMatchesInstalledAnchor(request.candidate(), actualAnchor); - return prepareInTransaction(transaction, request, context, registrationRecorder); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger revision = lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor actualAnchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction( + transaction, currentIssuerState); + CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( + transaction, actualAnchor, currentIssuerState); + InstalledAnchorPreparationContext context = + new InstalledAnchorPreparationContext(revision, actualAnchor, currentIssuerState); + CanonicalGameplayBindingTransitionRequest request = + Objects.requireNonNull( + requestFactory.create(transaction, actualAnchor, currentIssuerState), + "installed-anchor request factory returned null"); + validateRequest(request); + if (request.expectedPriorBindingRef() != null + || request.expectedPriorBindingGeneration() != null) { + throw conflict("Installed-anchor local issuer operation accepts only ordinary NEW"); + } + requireCandidateMatchesInstalledAnchor(request.candidate(), actualAnchor); + return prepareInTransaction(transaction, request, context, registrationRecorder); + }); } @FunctionalInterface @@ -164,112 +163,111 @@ private record InstalledAnchorPreparationContext( * Reads the complete typed inventory and all retained repair obligations from one DB snapshot. */ CanonicalGameplayBindingInventorySnapshot readSnapshot() { - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - BigInteger revision = - readBigInteger( - Objects.requireNonNull( - transaction.fetchOne( - "SELECT inventory_revision FROM " - + "game_session_canonical_binding_inventory_clock WHERE singleton_id = 1"), - "inventory revision clock row must exist"), - "inventory_revision"); - List bindings = - transaction - .fetch( - "SELECT * FROM " - + INVENTORY - + " WHERE inventory_revision <= ? ORDER BY binding_ref", - decimal(revision)) - .map(CanonicalGameplayBindingInventoryRepository::toInventoryEntry); - List transitions = - transaction - .fetch( - "SELECT t.transition_id, t.expected_prior_binding_ref," - + " t.expected_prior_binding_generation, t.candidate_binding_generation," - + " t.status, t.inventory_revision, t.issuer_reservation_id," - + " t.candidate_account_index_fence, t.account_coverage_state," - + " t.account_coverage_operation_id, t.account_coverage_lifecycle," - + " t.account_coverage_operation_fence, t.account_admission_fence_kind," - + " t.account_admission_fence, t.historical_account_admission_fence_kind," - + " t.historical_account_admission_fence, t.resolved_scope_kind," - + " t.resolved_scope_account_id, t.account_coverage_fence," - + " t.account_coverage_generation, t.account_inventory_snapshot_revision," - + " i.account_id, i.tenant_id, i.playable_state_namespace_id, i.character_id," - + " i.playable_state_scope, i.game_instance_id," - + " i.runtime_game_instance_id, i.session_id, i.region_id," - + " i.region_epoch, i.issuer_id, i.issuer_auth_generation," - + " i.issuer_index_layout_version, i.issuer_index_partition_count," - + " i.issuer_index_partition_capacity, i.binding_ref, r.reservation_fence" - + " FROM " - + TRANSITION - + " t JOIN " - + INVENTORY - + " i ON i.binding_ref = t.candidate_binding_ref JOIN " - + RESERVATION - + " r ON r.reservation_id = t.issuer_reservation_id" - + " WHERE t.inventory_revision <= ? ORDER BY t.transition_id", - decimal(revision)) - .map(CanonicalGameplayBindingInventoryRepository::toTransitionSnapshot); - List reservations = - transaction - .fetch( - "SELECT * FROM " - + RESERVATION - + " WHERE inventory_revision <= ? ORDER BY reservation_id", - decimal(revision)) - .map(CanonicalGameplayBindingInventoryRepository::toReservation); - List accountObligations = - transaction - .fetch( - "SELECT o.*, i.playable_state_namespace_id, i.character_id," - + " i.playable_state_scope, i.game_instance_id," - + " i.runtime_game_instance_id, i.session_id, i.region_id," - + " i.region_epoch, i.issuer_id, i.issuer_auth_generation," - + " i.issuer_index_layout_version, i.issuer_index_partition_count," - + " i.issuer_index_partition_capacity FROM " - + ACCOUNT_OBLIGATION - + " o JOIN " - + INVENTORY - + " i ON i.binding_ref = o.binding_ref" - + " WHERE o.inventory_revision <= ? ORDER BY o.transition_id, o.obligation_ordinal", - decimal(revision)) - .map(CanonicalGameplayBindingInventoryRepository::toAccountObligation); - List issuerObligations = - transaction - .fetch( - "SELECT o.*, i.account_id, i.tenant_id, i.playable_state_namespace_id," - + " i.character_id, i.playable_state_scope, i.game_instance_id," - + " i.runtime_game_instance_id, i.session_id," - + " i.region_id, i.region_epoch, i.issuer_id, i.issuer_auth_generation," - + " i.issuer_index_layout_version, i.issuer_index_partition_count," - + " i.issuer_index_partition_capacity FROM " - + ISSUER_OBLIGATION - + " o JOIN " - + INVENTORY - + " i ON i.binding_ref = o.binding_ref" - + " WHERE o.inventory_revision <= ? ORDER BY o.transition_id, o.binding_ref", - decimal(revision)) - .map(CanonicalGameplayBindingInventoryRepository::toIssuerObligation); - List regionObligations = - transaction - .fetch( - "SELECT * FROM " - + REGION_OBLIGATION - + " WHERE inventory_revision <= ? ORDER BY transition_id", - decimal(revision)) - .map(CanonicalGameplayBindingInventoryRepository::toRegionObligation); - return new CanonicalGameplayBindingInventorySnapshot( - revision, - bindings, - transitions, - reservations, - accountObligations, - issuerObligations, - regionObligations); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + BigInteger revision = + readBigInteger( + Objects.requireNonNull( + transaction.fetchOne( + "SELECT inventory_revision FROM " + + "game_session_canonical_binding_inventory_clock WHERE singleton_id = 1"), + "inventory revision clock row must exist"), + "inventory_revision"); + List bindings = + transaction + .fetch( + "SELECT * FROM " + + INVENTORY + + " WHERE inventory_revision <= ? ORDER BY binding_ref", + decimal(revision)) + .map(CanonicalGameplayBindingInventoryRepository::toInventoryEntry); + List transitions = + transaction + .fetch( + "SELECT t.transition_id, t.expected_prior_binding_ref," + + " t.expected_prior_binding_generation, t.candidate_binding_generation," + + " t.status, t.inventory_revision, t.issuer_reservation_id," + + " t.candidate_account_index_fence, t.account_coverage_state," + + " t.account_coverage_operation_id, t.account_coverage_lifecycle," + + " t.account_coverage_operation_fence, t.account_admission_fence_kind," + + " t.account_admission_fence, t.historical_account_admission_fence_kind," + + " t.historical_account_admission_fence, t.resolved_scope_kind," + + " t.resolved_scope_account_id, t.account_coverage_fence," + + " t.account_coverage_generation, t.account_inventory_snapshot_revision," + + " i.account_id, i.tenant_id, i.playable_state_namespace_id, i.character_id," + + " i.playable_state_scope, i.game_instance_id," + + " i.runtime_game_instance_id, i.session_id, i.region_id," + + " i.region_epoch, i.issuer_id, i.issuer_auth_generation," + + " i.issuer_index_layout_version, i.issuer_index_partition_count," + + " i.issuer_index_partition_capacity, i.binding_ref, r.reservation_fence" + + " FROM " + + TRANSITION + + " t JOIN " + + INVENTORY + + " i ON i.binding_ref = t.candidate_binding_ref JOIN " + + RESERVATION + + " r ON r.reservation_id = t.issuer_reservation_id" + + " WHERE t.inventory_revision <= ? ORDER BY t.transition_id", + decimal(revision)) + .map(CanonicalGameplayBindingInventoryRepository::toTransitionSnapshot); + List reservations = + transaction + .fetch( + "SELECT * FROM " + + RESERVATION + + " WHERE inventory_revision <= ? ORDER BY reservation_id", + decimal(revision)) + .map(CanonicalGameplayBindingInventoryRepository::toReservation); + List accountObligations = + transaction + .fetch( + "SELECT o.*, i.playable_state_namespace_id, i.character_id," + + " i.playable_state_scope, i.game_instance_id," + + " i.runtime_game_instance_id, i.session_id, i.region_id," + + " i.region_epoch, i.issuer_id, i.issuer_auth_generation," + + " i.issuer_index_layout_version, i.issuer_index_partition_count," + + " i.issuer_index_partition_capacity FROM " + + ACCOUNT_OBLIGATION + + " o JOIN " + + INVENTORY + + " i ON i.binding_ref = o.binding_ref" + + " WHERE o.inventory_revision <= ? ORDER BY o.transition_id, o.obligation_ordinal", + decimal(revision)) + .map(CanonicalGameplayBindingInventoryRepository::toAccountObligation); + List issuerObligations = + transaction + .fetch( + "SELECT o.*, i.account_id, i.tenant_id, i.playable_state_namespace_id," + + " i.character_id, i.playable_state_scope, i.game_instance_id," + + " i.runtime_game_instance_id, i.session_id," + + " i.region_id, i.region_epoch, i.issuer_id, i.issuer_auth_generation," + + " i.issuer_index_layout_version, i.issuer_index_partition_count," + + " i.issuer_index_partition_capacity FROM " + + ISSUER_OBLIGATION + + " o JOIN " + + INVENTORY + + " i ON i.binding_ref = o.binding_ref" + + " WHERE o.inventory_revision <= ? ORDER BY o.transition_id, o.binding_ref", + decimal(revision)) + .map(CanonicalGameplayBindingInventoryRepository::toIssuerObligation); + List regionObligations = + transaction + .fetch( + "SELECT * FROM " + + REGION_OBLIGATION + + " WHERE inventory_revision <= ? ORDER BY transition_id", + decimal(revision)) + .map(CanonicalGameplayBindingInventoryRepository::toRegionObligation); + return new CanonicalGameplayBindingInventorySnapshot( + revision, + bindings, + transitions, + reservations, + accountObligations, + issuerObligations, + regionObligations); + }); } /** @@ -278,12 +276,11 @@ CanonicalGameplayBindingInventorySnapshot readSnapshot() { */ CanonicalGameplayBindingProvisionalCasEvidence readProvisionalCasEvidence(UUID transitionId) { Objects.requireNonNull(transitionId, "transitionId"); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - return loadProvisionalCasEvidence(transaction, transitionId, false); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + return loadProvisionalCasEvidence(transaction, transitionId, false); + }); } /** Irreversibly selects one still-PREPARED dispatch claim without inferring any Redis outcome. */ @@ -291,72 +288,68 @@ public CanonicalGameplayOriginalNewAbandonmentSource selectOriginalNewAbandonmen UUID transitionId) { Objects.requireNonNull(transitionId, "transitionId"); requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger currentRevision = lockInventoryRevision(transaction); - Record existing = findTransition(transaction, transitionId); - if (existing == null) throw conflict("Original NEW transition does not exist"); - if (existing.get("original_new_abandonment_id", UUID.class) != null) { - return loadOriginalNewAbandonmentSource(transaction, transitionId, true); - } - // Negative selection consumes the retained dispatch, not authority to admit again. - // Account acquisition may already own the frozen original candidate in its cohort. - CanonicalGameplayBindingProvisionalCasEvidence evidence = - loadProvisionalCasEvidence(transaction, transitionId, true, false); - if (evidence.transition().status() - != CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED - || evidence.expectedPrior() != null - || existing.get("admission_lease_id", UUID.class) != null - || !"DISPATCH_POSSIBLE" - .equals(existing.get("original_new_candidate_state", String.class)) - || existing.get("original_new_candidate_readback_digest", String.class) != null) { - throw conflict( - "Only an unresolved original NEW PREPARED dispatch may select abandonment"); - } - byte[] bytes = existing.get("original_new_candidate_bytes", byte[].class); - if (bytes == null - || !CanonicalGameplayIssuerMemberV2Codec.sha256(bytes) - .equals(existing.get("original_new_candidate_digest", String.class))) { - throw conflict("Abandonment requires the immutable original candidate bytes"); - } - CanonicalGameplayOriginalNewCandidate candidate = - CanonicalGameplayOriginalNewCandidate.parseCanonical(bytes); - if (!candidate.matchesProvisionalSources(evidence)) { - throw conflict("Abandonment candidate differs from its original sources"); - } - requireOriginalNewNeverDispatchedFollowups(transaction, transitionId); - BigInteger prior = evidence.transition().inventoryRevision(); - BigInteger next = currentRevision.add(BigInteger.ONE); - requireOne( - transaction.execute( - "UPDATE " - + TRANSITION - + " SET original_new_abandonment_id = ?, original_new_abandonment_state = 'ABANDONMENT_SELECTED', inventory_revision = ?" - + " WHERE transition_id = ? AND status = 'PREPARED' AND inventory_revision = ?" - + " AND original_new_abandonment_id IS NULL AND original_new_candidate_state = 'DISPATCH_POSSIBLE'" - + " AND original_new_candidate_readback_digest IS NULL", - UUID.randomUUID(), - decimal(next), - transitionId, - decimal(prior)), - "Original NEW abandonment selection lost its exact source"); - advanceOriginalNewAbandonmentRevision(transaction, transitionId, prior, next); - bumpInventoryClock(transaction, currentRevision, next); - return loadOriginalNewAbandonmentSource(transaction, transitionId, false); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger currentRevision = lockInventoryRevision(transaction); + Record existing = findTransition(transaction, transitionId); + if (existing == null) throw conflict("Original NEW transition does not exist"); + if (existing.get("original_new_abandonment_id", UUID.class) != null) { + return loadOriginalNewAbandonmentSource(transaction, transitionId, true); + } + // Negative selection consumes the retained dispatch, not authority to admit again. + // Account acquisition may already own the frozen original candidate in its cohort. + CanonicalGameplayBindingProvisionalCasEvidence evidence = + loadProvisionalCasEvidence(transaction, transitionId, true, false); + if (evidence.transition().status() + != CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED + || evidence.expectedPrior() != null + || existing.get("admission_lease_id", UUID.class) != null + || !"DISPATCH_POSSIBLE".equals(existing.get("original_new_candidate_state", String.class)) + || existing.get("original_new_candidate_readback_digest", String.class) != null) { + throw conflict("Only an unresolved original NEW PREPARED dispatch may select abandonment"); + } + byte[] bytes = existing.get("original_new_candidate_bytes", byte[].class); + if (bytes == null + || !CanonicalGameplayIssuerMemberV2Codec.sha256(bytes) + .equals(existing.get("original_new_candidate_digest", String.class))) { + throw conflict("Abandonment requires the immutable original candidate bytes"); + } + CanonicalGameplayOriginalNewCandidate candidate = + CanonicalGameplayOriginalNewCandidate.parseCanonical(bytes); + if (!candidate.matchesProvisionalSources(evidence)) { + throw conflict("Abandonment candidate differs from its original sources"); + } + requireOriginalNewNeverDispatchedFollowups(transaction, transitionId); + BigInteger prior = evidence.transition().inventoryRevision(); + BigInteger next = currentRevision.add(BigInteger.ONE); + requireOne( + transaction.execute( + "UPDATE " + + TRANSITION + + " SET original_new_abandonment_id = ?, original_new_abandonment_state = 'ABANDONMENT_SELECTED', inventory_revision = ?" + + " WHERE transition_id = ? AND status = 'PREPARED' AND inventory_revision = ?" + + " AND original_new_abandonment_id IS NULL AND original_new_candidate_state = 'DISPATCH_POSSIBLE'" + + " AND original_new_candidate_readback_digest IS NULL", + UUID.randomUUID(), + decimal(next), + transitionId, + decimal(prior)), + "Original NEW abandonment selection lost its exact source"); + advanceOriginalNewAbandonmentRevision(transaction, transitionId, prior, next); + bumpInventoryClock(transaction, currentRevision, next); + return loadOriginalNewAbandonmentSource(transaction, transitionId, false); + }); } public CanonicalGameplayOriginalNewAbandonmentSource readOriginalNewAbandonmentSource( UUID transitionId) { Objects.requireNonNull(transitionId, "transitionId"); requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - return loadOriginalNewAbandonmentSource(transaction, transitionId, false); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + return loadOriginalNewAbandonmentSource(transaction, transitionId, false); + }); } public CanonicalGameplayOriginalNewAbandonmentSource recordOriginalNewAbandonmentClosure( @@ -365,44 +358,42 @@ public CanonicalGameplayOriginalNewAbandonmentSource recordOriginalNewAbandonmen Objects.requireNonNull(expected, "expected"); Objects.requireNonNull(actual, "owner-produced closure readback"); requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger currentRevision = lockInventoryRevision(transaction); - var current = - loadOriginalNewAbandonmentSource( - transaction, expected.transition().transitionId(), true); - if (!current.abandonmentId().equals(expected.abandonmentId()) - || !current.candidate().equals(expected.candidate()) - || !actual.matches(current)) { - throw conflict("Original NEW closure does not match its retained abandonment"); - } - if (current.closureDigest() != null) { - if (!current.closureDigest().equals(actual.digest())) - throw conflict("Original NEW closure digest changed"); - return current; - } - BigInteger prior = current.transition().inventoryRevision(); - BigInteger next = currentRevision.add(BigInteger.ONE); - requireOne( - transaction.execute( - "UPDATE " - + TRANSITION - + " SET original_new_abandonment_state = 'NEVER_ADMITTED_CLOSED', original_new_abandonment_closure_digest = ?, inventory_revision = ?" - + " WHERE transition_id = ? AND status = 'PREPARED' AND inventory_revision = ?" - + " AND original_new_abandonment_id = ? AND original_new_abandonment_state = 'ABANDONMENT_SELECTED'", - actual.digest(), - decimal(next), - current.transition().transitionId(), - decimal(prior), - current.abandonmentId()), - "Original NEW closure lost its selected abandonment"); - advanceOriginalNewAbandonmentRevision( - transaction, current.transition().transitionId(), prior, next); - bumpInventoryClock(transaction, currentRevision, next); - return loadOriginalNewAbandonmentSource( - transaction, current.transition().transitionId(), false); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger currentRevision = lockInventoryRevision(transaction); + var current = + loadOriginalNewAbandonmentSource(transaction, expected.transition().transitionId(), true); + if (!current.abandonmentId().equals(expected.abandonmentId()) + || !current.candidate().equals(expected.candidate()) + || !actual.matches(current)) { + throw conflict("Original NEW closure does not match its retained abandonment"); + } + if (current.closureDigest() != null) { + if (!current.closureDigest().equals(actual.digest())) + throw conflict("Original NEW closure digest changed"); + return current; + } + BigInteger prior = current.transition().inventoryRevision(); + BigInteger next = currentRevision.add(BigInteger.ONE); + requireOne( + transaction.execute( + "UPDATE " + + TRANSITION + + " SET original_new_abandonment_state = 'NEVER_ADMITTED_CLOSED', original_new_abandonment_closure_digest = ?, inventory_revision = ?" + + " WHERE transition_id = ? AND status = 'PREPARED' AND inventory_revision = ?" + + " AND original_new_abandonment_id = ? AND original_new_abandonment_state = 'ABANDONMENT_SELECTED'", + actual.digest(), + decimal(next), + current.transition().transitionId(), + decimal(prior), + current.abandonmentId()), + "Original NEW closure lost its selected abandonment"); + advanceOriginalNewAbandonmentRevision( + transaction, current.transition().transitionId(), prior, next); + bumpInventoryClock(transaction, currentRevision, next); + return loadOriginalNewAbandonmentSource( + transaction, current.transition().transitionId(), false); + }); } private static void requireOriginalNewNeverDispatchedFollowups( @@ -512,193 +503,185 @@ public CanonicalGameplayOriginalNewAbandonmentSource recordNeverAdmittedAccountA Objects.requireNonNull(expected, "expected"); Objects.requireNonNull(actual, "authenticated Account negative readback"); requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger revision = lockInventoryRevision(transaction); - var current = - loadOriginalNewAbandonmentSource( - transaction, expected.transition().transitionId(), true); - if (!current.abandonmentId().equals(expected.abandonmentId()) - || !current.candidate().equals(expected.candidate()) - || !actual.matches(current) - || current.state() - != CanonicalGameplayOriginalNewAbandonmentSource.State.NEVER_ADMITTED_CLOSED) { - throw conflict( - "Account negative terminal does not match the closed original abandonment"); - } - var evidence = actual.evidence(); - if (current.orphanCleanupId() != null) { - if (!current.orphanCleanupId().equals(evidence.orphanCleanupId()) - || !current.negativeResolutionId().equals(evidence.negativeResolutionId())) { - throw conflict("Account negative terminal retry changed retained evidence"); - } - return current; - } - requireOriginalNewNeverDispatchedFollowups( - transaction, current.transition().transitionId()); - BigInteger prior = current.transition().inventoryRevision(); - BigInteger next = revision.add(BigInteger.ONE); - UUID transitionId = current.transition().transitionId(); - requireOne( - transaction.execute( - "UPDATE " - + TRANSITION - + " SET status = 'ABORTED', original_new_abandonment_orphan_cleanup_id = ?, original_new_abandonment_resolution_id = ?, inventory_revision = ?" - + " WHERE transition_id = ? AND status = 'PREPARED' AND inventory_revision = ? AND original_new_abandonment_id = ?" - + " AND original_new_abandonment_state = 'NEVER_ADMITTED_CLOSED'", - evidence.orphanCleanupId(), - evidence.negativeResolutionId(), - decimal(next), - transitionId, - decimal(prior), - current.abandonmentId()), - "Original NEW negative terminal lost its selected source"); - requireOne( - transaction.execute( - "UPDATE " - + INVENTORY - + " SET lifecycle = 'TERMINAL_UNRESOLVED', inventory_revision = ? WHERE transition_id = ? AND lifecycle = 'CANDIDATE_PREPARED' AND inventory_revision = ?", - decimal(next), - transitionId, - decimal(prior)), - "Original NEW negative terminal lost its candidate"); - requireOne( - transaction.execute( - "UPDATE " - + RESERVATION - + " SET lifecycle = 'RELEASE_PENDING', inventory_revision = ? WHERE transition_id = ? AND lifecycle = 'RESERVED' AND inventory_revision = ?", - decimal(next), - transitionId, - decimal(prior)), - "Original NEW negative terminal lost its reservation"); - requireOne( - transaction.execute( - "UPDATE " - + ACCOUNT_OBLIGATION - + " SET status = 'NEVER_DISPATCHED', inventory_revision = ? WHERE transition_id = ? AND status = 'REQUIRED' AND inventory_revision = ?", - decimal(next), - transitionId, - decimal(prior)), - "Original NEW account obligation was not never dispatched"); - requireOne( - transaction.execute( - "UPDATE " - + REGION_OBLIGATION - + " SET status = 'NEVER_DISPATCHED', inventory_revision = ? WHERE transition_id = ? AND status = 'REQUIRED' AND bridge_operation_id IS NULL AND inventory_revision = ?", - decimal(next), - transitionId, - decimal(prior)), - "Original NEW region obligation was not never dispatched"); - requireOne( - transaction.execute( - "UPDATE " - + ISSUER_OBLIGATION - + " SET inventory_revision = ? WHERE transition_id = ? AND inventory_revision = ? AND status = 'REQUIRED'", - decimal(next), - transitionId, - decimal(prior)), - "Original NEW negative terminal lost its issuer obligation"); - bumpInventoryClock(transaction, revision, next); - return loadOriginalNewAbandonmentSource(transaction, transitionId, false); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger revision = lockInventoryRevision(transaction); + var current = + loadOriginalNewAbandonmentSource(transaction, expected.transition().transitionId(), true); + if (!current.abandonmentId().equals(expected.abandonmentId()) + || !current.candidate().equals(expected.candidate()) + || !actual.matches(current) + || current.state() + != CanonicalGameplayOriginalNewAbandonmentSource.State.NEVER_ADMITTED_CLOSED) { + throw conflict("Account negative terminal does not match the closed original abandonment"); + } + var evidence = actual.evidence(); + if (current.orphanCleanupId() != null) { + if (!current.orphanCleanupId().equals(evidence.orphanCleanupId()) + || !current.negativeResolutionId().equals(evidence.negativeResolutionId())) { + throw conflict("Account negative terminal retry changed retained evidence"); + } + return current; + } + requireOriginalNewNeverDispatchedFollowups(transaction, current.transition().transitionId()); + BigInteger prior = current.transition().inventoryRevision(); + BigInteger next = revision.add(BigInteger.ONE); + UUID transitionId = current.transition().transitionId(); + requireOne( + transaction.execute( + "UPDATE " + + TRANSITION + + " SET status = 'ABORTED', original_new_abandonment_orphan_cleanup_id = ?, original_new_abandonment_resolution_id = ?, inventory_revision = ?" + + " WHERE transition_id = ? AND status = 'PREPARED' AND inventory_revision = ? AND original_new_abandonment_id = ?" + + " AND original_new_abandonment_state = 'NEVER_ADMITTED_CLOSED'", + evidence.orphanCleanupId(), + evidence.negativeResolutionId(), + decimal(next), + transitionId, + decimal(prior), + current.abandonmentId()), + "Original NEW negative terminal lost its selected source"); + requireOne( + transaction.execute( + "UPDATE " + + INVENTORY + + " SET lifecycle = 'TERMINAL_UNRESOLVED', inventory_revision = ? WHERE transition_id = ? AND lifecycle = 'CANDIDATE_PREPARED' AND inventory_revision = ?", + decimal(next), + transitionId, + decimal(prior)), + "Original NEW negative terminal lost its candidate"); + requireOne( + transaction.execute( + "UPDATE " + + RESERVATION + + " SET lifecycle = 'RELEASE_PENDING', inventory_revision = ? WHERE transition_id = ? AND lifecycle = 'RESERVED' AND inventory_revision = ?", + decimal(next), + transitionId, + decimal(prior)), + "Original NEW negative terminal lost its reservation"); + requireOne( + transaction.execute( + "UPDATE " + + ACCOUNT_OBLIGATION + + " SET status = 'NEVER_DISPATCHED', inventory_revision = ? WHERE transition_id = ? AND status = 'REQUIRED' AND inventory_revision = ?", + decimal(next), + transitionId, + decimal(prior)), + "Original NEW account obligation was not never dispatched"); + requireOne( + transaction.execute( + "UPDATE " + + REGION_OBLIGATION + + " SET status = 'NEVER_DISPATCHED', inventory_revision = ? WHERE transition_id = ? AND status = 'REQUIRED' AND bridge_operation_id IS NULL AND inventory_revision = ?", + decimal(next), + transitionId, + decimal(prior)), + "Original NEW region obligation was not never dispatched"); + requireOne( + transaction.execute( + "UPDATE " + + ISSUER_OBLIGATION + + " SET inventory_revision = ? WHERE transition_id = ? AND inventory_revision = ? AND status = 'REQUIRED'", + decimal(next), + transitionId, + decimal(prior)), + "Original NEW negative terminal lost its issuer obligation"); + bumpInventoryClock(transaction, revision, next); + return loadOriginalNewAbandonmentSource(transaction, transitionId, false); + }); } /** Completes only after retained real issuer release and physical-retirement proof. */ public CanonicalGameplayOriginalNewAbandonmentSource completeOriginalNewAbandonmentCleanup( UUID transitionId) { requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger revision = lockInventoryRevision(transaction); - var source = loadOriginalNewAbandonmentSource(transaction, transitionId, true); - if (source.orphanCleanupId() == null - || source.transition().status() - != CanonicalGameplayBindingTransitionSnapshot.Status.ABORTED) { - throw conflict( - "Original NEW cleanup requires an attributable negative Account terminal"); - } - if (source.inventory().lifecycle() - == CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL) return source; - Record proof = - transaction.fetchOne( - "SELECT r.retirement_operation_id FROM game_session_canonical_issuer_binding_local_retirement r" - + " JOIN game_session_canonical_issuer_binding_local_release_operation release ON release.operation_id = r.release_operation_id" - + " JOIN " - + ISSUER_OBLIGATION - + " obligation ON obligation.transition_id = release.transition_id" - + " AND obligation.local_release_operation_id = release.operation_id" - + " AND obligation.status = 'RELEASED' AND obligation.binding_ref = release.binding_ref" - + " AND obligation.reservation_id = release.reservation_id" - + " AND obligation.inventory_revision = release.completion_inventory_revision" - + " WHERE release.transition_id = ? AND release.orphan_cleanup_id = ? AND release.status = 'RELEASED' AND r.status = 'RETIRED'", - transitionId, - source.orphanCleanupId()); - if (proof == null - || source.reservation().lifecycle() - != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) { - throw conflict("Original NEW cleanup lacks real released and retired issuer evidence"); - } - Record account = - transaction.fetchOne( - "SELECT status FROM " - + ACCOUNT_OBLIGATION - + " WHERE transition_id = ? AND obligation_ordinal = 0", - transitionId); - Record region = - transaction.fetchOne( - "SELECT status FROM " + REGION_OBLIGATION + " WHERE transition_id = ?", - transitionId); - if (account == null - || region == null - || !"NEVER_DISPATCHED".equals(account.get("status", String.class)) - || !"NEVER_DISPATCHED".equals(region.get("status", String.class))) - throw conflict("Original NEW untouched followups lack terminal evidence"); - BigInteger prior = source.transition().inventoryRevision(); - BigInteger next = revision.add(BigInteger.ONE); - requireOne( - transaction.execute( - "UPDATE " - + TRANSITION - + " SET inventory_revision = ? WHERE transition_id = ? AND inventory_revision = ? AND status = 'ABORTED'", - decimal(next), - transitionId, - decimal(prior)), - "Original NEW cleanup lost its terminal source"); - // Completed followup obligations retain their original evidence and revisions. - // Only the mutable inventory/reservation snapshots follow this terminal clock edge. - for (String table : List.of(INVENTORY, RESERVATION)) { - requireOne( - transaction.execute( - "UPDATE " - + table - + " SET inventory_revision = ? WHERE transition_id = ? AND inventory_revision = ?", - decimal(next), - transitionId, - decimal(prior)), - "Original NEW completion lost its exact inventory or reservation"); - } - requireOne( - transaction.execute( - "UPDATE " - + INVENTORY - + " SET lifecycle = 'TERMINAL' WHERE transition_id = ? AND lifecycle = 'TERMINAL_UNRESOLVED'", - transitionId), - "Original NEW cleanup lost its unresolved inventory"); - bumpInventoryClock(transaction, revision, next); - return loadOriginalNewAbandonmentSource(transaction, transitionId, false); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger revision = lockInventoryRevision(transaction); + var source = loadOriginalNewAbandonmentSource(transaction, transitionId, true); + if (source.orphanCleanupId() == null + || source.transition().status() + != CanonicalGameplayBindingTransitionSnapshot.Status.ABORTED) { + throw conflict("Original NEW cleanup requires an attributable negative Account terminal"); + } + if (source.inventory().lifecycle() + == CanonicalGameplayBindingInventoryEntry.Lifecycle.TERMINAL) return source; + Record proof = + transaction.fetchOne( + "SELECT r.retirement_operation_id FROM game_session_canonical_issuer_binding_local_retirement r" + + " JOIN game_session_canonical_issuer_binding_local_release_operation release ON release.operation_id = r.release_operation_id" + + " JOIN " + + ISSUER_OBLIGATION + + " obligation ON obligation.transition_id = release.transition_id" + + " AND obligation.local_release_operation_id = release.operation_id" + + " AND obligation.status = 'RELEASED' AND obligation.binding_ref = release.binding_ref" + + " AND obligation.reservation_id = release.reservation_id" + + " AND obligation.inventory_revision = release.completion_inventory_revision" + + " WHERE release.transition_id = ? AND release.orphan_cleanup_id = ? AND release.status = 'RELEASED' AND r.status = 'RETIRED'", + transitionId, + source.orphanCleanupId()); + if (proof == null + || source.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) { + throw conflict("Original NEW cleanup lacks real released and retired issuer evidence"); + } + Record account = + transaction.fetchOne( + "SELECT status FROM " + + ACCOUNT_OBLIGATION + + " WHERE transition_id = ? AND obligation_ordinal = 0", + transitionId); + Record region = + transaction.fetchOne( + "SELECT status FROM " + REGION_OBLIGATION + " WHERE transition_id = ?", transitionId); + if (account == null + || region == null + || !"NEVER_DISPATCHED".equals(account.get("status", String.class)) + || !"NEVER_DISPATCHED".equals(region.get("status", String.class))) + throw conflict("Original NEW untouched followups lack terminal evidence"); + BigInteger prior = source.transition().inventoryRevision(); + BigInteger next = revision.add(BigInteger.ONE); + requireOne( + transaction.execute( + "UPDATE " + + TRANSITION + + " SET inventory_revision = ? WHERE transition_id = ? AND inventory_revision = ? AND status = 'ABORTED'", + decimal(next), + transitionId, + decimal(prior)), + "Original NEW cleanup lost its terminal source"); + // Completed followup obligations retain their original evidence and revisions. + // Only the mutable inventory/reservation snapshots follow this terminal clock edge. + for (String table : List.of(INVENTORY, RESERVATION)) { + requireOne( + transaction.execute( + "UPDATE " + + table + + " SET inventory_revision = ? WHERE transition_id = ? AND inventory_revision = ?", + decimal(next), + transitionId, + decimal(prior)), + "Original NEW completion lost its exact inventory or reservation"); + } + requireOne( + transaction.execute( + "UPDATE " + + INVENTORY + + " SET lifecycle = 'TERMINAL' WHERE transition_id = ? AND lifecycle = 'TERMINAL_UNRESOLVED'", + transitionId), + "Original NEW cleanup lost its unresolved inventory"); + bumpInventoryClock(transaction, revision, next); + return loadOriginalNewAbandonmentSource(transaction, transitionId, false); + }); } CanonicalGameplayIssuerCleanupSource readIssuerCleanupSource(UUID transitionId) { requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - return readIssuerCleanupSourceInTransaction(transaction, transitionId, false); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + return readIssuerCleanupSourceInTransaction(transaction, transitionId, false); + }); } static CanonicalGameplayIssuerCleanupSource readIssuerCleanupSourceInTransaction( @@ -742,101 +725,99 @@ private OriginalNewCandidateInstallationClaim originalNewCandidateInstallationSo CanonicalGameplayAdmissionDecision originalDecision, boolean claimCreation) { Objects.requireNonNull(originalDecision, "originalDecision"); requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger currentRevision = lockInventoryRevision(transaction); - CanonicalGameplayAccountCoverageEvidence accountCoverage = - lockAccountCoverageEvidence(transaction, originalDecision.candidate().accountId()); - lockLeaseBoundRuntimeBeforeTransition( - transaction, - originalDecision.bindingDecisionId(), - originalDecision.candidate().bindingRef().bytes(), - originalDecision.targetEvidence()); - CanonicalGameplayBindingProvisionalCasEvidence evidence = - loadProvisionalCasEvidence(transaction, originalDecision.bindingDecisionId(), true); - if (!accountCoverage.equals(evidence.transition().accountCoverageEvidence())) { - throw conflict("Original NEW account control changed before candidate dispatch claim"); - } - requireDecisionMatchesOperation(originalDecision, evidence); - CanonicalGameplayOriginalNewCandidate candidate; - try { - candidate = - CanonicalGameplayOriginalNewCandidate.fromOriginalSources( - evidence, originalDecision); - } catch (RuntimeException invalidSource) { - throw conflict("Original NEW candidate source is not exact and public-production"); - } - - Record transition = findTransition(transaction, evidence.transition().transitionId()); - byte[] storedBytes = transition.get("original_new_candidate_bytes", byte[].class); - String storedDigest = transition.get("original_new_candidate_digest", String.class); - String storedState = transition.get("original_new_candidate_state", String.class); - String storedReadbackDigest = - transition.get("original_new_candidate_readback_digest", String.class); - if (storedBytes == null) { - if (storedDigest != null - || storedState != null - || storedReadbackDigest != null - || evidence.transition().status() - != CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED - || transition.get("admission_lease_id", UUID.class) != null) { - throw conflict("Only an untouched PREPARED original NEW row can claim creation"); - } - if (!claimCreation) { - return new OriginalNewCandidateInstallationClaim( - evidence, - originalDecision, - candidate, - OriginalNewCandidateInstallationState.NEVER_DISPATCHED, - null); - } - byte[] bytes = candidate.canonicalBytes(); - String digest = CanonicalGameplayIssuerMemberV2Codec.sha256(bytes); - BigInteger priorRevision = evidence.transition().inventoryRevision(); - BigInteger nextRevision = currentRevision.add(BigInteger.ONE); - updateOriginalNewCandidateRevisionRows( - transaction, evidence, priorRevision, nextRevision, bytes, digest); - bumpInventoryClock(transaction, currentRevision, nextRevision); - CanonicalGameplayBindingProvisionalCasEvidence current = - loadProvisionalCasEvidence(transaction, evidence.transition().transitionId(), true); - return new OriginalNewCandidateInstallationClaim( - current, - originalDecision, - candidate, - OriginalNewCandidateInstallationState.DISPATCH_POSSIBLE, - new OriginalNewCandidateCreatePermission()); - } + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger currentRevision = lockInventoryRevision(transaction); + CanonicalGameplayAccountCoverageEvidence accountCoverage = + lockAccountCoverageEvidence(transaction, originalDecision.candidate().accountId()); + lockLeaseBoundRuntimeBeforeTransition( + transaction, + originalDecision.bindingDecisionId(), + originalDecision.candidate().bindingRef().bytes(), + originalDecision.targetEvidence()); + CanonicalGameplayBindingProvisionalCasEvidence evidence = + loadProvisionalCasEvidence(transaction, originalDecision.bindingDecisionId(), true); + if (!accountCoverage.equals(evidence.transition().accountCoverageEvidence())) { + throw conflict("Original NEW account control changed before candidate dispatch claim"); + } + requireDecisionMatchesOperation(originalDecision, evidence); + CanonicalGameplayOriginalNewCandidate candidate; + try { + candidate = + CanonicalGameplayOriginalNewCandidate.fromOriginalSources(evidence, originalDecision); + } catch (RuntimeException invalidSource) { + throw conflict("Original NEW candidate source is not exact and public-production"); + } - if (storedDigest == null - || !storedDigest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(storedBytes)) - || !Arrays.equals(storedBytes, candidate.canonicalBytes()) - || (!"DISPATCH_POSSIBLE".equals(storedState) - && !"READBACK_CONFIRMED".equals(storedState))) { - throw conflict("Original NEW candidate retry differs from its immutable SQL source"); - } - CanonicalGameplayOriginalNewCandidate parsed = - CanonicalGameplayOriginalNewCandidate.parseCanonical(storedBytes); - if (!parsed.equals(candidate) - || !parsed.matchesOriginalDecision(originalDecision) - || !parsed.matchesProvisionalSources(evidence)) { - throw conflict("Stored original NEW candidate no longer matches its durable sources"); - } - if (evidence.transition().status() - == CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) { - CanonicalGameplayAdmissionDecision stored = toAdmissionDecision(transition, evidence); - requireSameAdmissionDecision(originalDecision, stored); - if (!"READBACK_CONFIRMED".equals(storedState) || storedReadbackDigest == null) { - throw conflict("PROVISIONAL original NEW source lacks retained physical readback"); - } - } + Record transition = findTransition(transaction, evidence.transition().transitionId()); + byte[] storedBytes = transition.get("original_new_candidate_bytes", byte[].class); + String storedDigest = transition.get("original_new_candidate_digest", String.class); + String storedState = transition.get("original_new_candidate_state", String.class); + String storedReadbackDigest = + transition.get("original_new_candidate_readback_digest", String.class); + if (storedBytes == null) { + if (storedDigest != null + || storedState != null + || storedReadbackDigest != null + || evidence.transition().status() + != CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED + || transition.get("admission_lease_id", UUID.class) != null) { + throw conflict("Only an untouched PREPARED original NEW row can claim creation"); + } + if (!claimCreation) { return new OriginalNewCandidateInstallationClaim( evidence, originalDecision, - parsed, - OriginalNewCandidateInstallationState.valueOf(storedState), + candidate, + OriginalNewCandidateInstallationState.NEVER_DISPATCHED, null); - }); + } + byte[] bytes = candidate.canonicalBytes(); + String digest = CanonicalGameplayIssuerMemberV2Codec.sha256(bytes); + BigInteger priorRevision = evidence.transition().inventoryRevision(); + BigInteger nextRevision = currentRevision.add(BigInteger.ONE); + updateOriginalNewCandidateRevisionRows( + transaction, evidence, priorRevision, nextRevision, bytes, digest); + bumpInventoryClock(transaction, currentRevision, nextRevision); + CanonicalGameplayBindingProvisionalCasEvidence current = + loadProvisionalCasEvidence(transaction, evidence.transition().transitionId(), true); + return new OriginalNewCandidateInstallationClaim( + current, + originalDecision, + candidate, + OriginalNewCandidateInstallationState.DISPATCH_POSSIBLE, + new OriginalNewCandidateCreatePermission()); + } + + if (storedDigest == null + || !storedDigest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(storedBytes)) + || !Arrays.equals(storedBytes, candidate.canonicalBytes()) + || (!"DISPATCH_POSSIBLE".equals(storedState) + && !"READBACK_CONFIRMED".equals(storedState))) { + throw conflict("Original NEW candidate retry differs from its immutable SQL source"); + } + CanonicalGameplayOriginalNewCandidate parsed = + CanonicalGameplayOriginalNewCandidate.parseCanonical(storedBytes); + if (!parsed.equals(candidate) + || !parsed.matchesOriginalDecision(originalDecision) + || !parsed.matchesProvisionalSources(evidence)) { + throw conflict("Stored original NEW candidate no longer matches its durable sources"); + } + if (evidence.transition().status() + == CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) { + CanonicalGameplayAdmissionDecision stored = toAdmissionDecision(transition, evidence); + requireSameAdmissionDecision(originalDecision, stored); + if (!"READBACK_CONFIRMED".equals(storedState) || storedReadbackDigest == null) { + throw conflict("PROVISIONAL original NEW source lacks retained physical readback"); + } + } + return new OriginalNewCandidateInstallationClaim( + evidence, + originalDecision, + parsed, + OriginalNewCandidateInstallationState.valueOf(storedState), + null); + }); } /** @@ -859,189 +840,178 @@ OriginalNewFinalAdmissionSource readOriginalNewFinalAdmissionSource( CanonicalGameplayAdmissionDecision originalDecision) { Objects.requireNonNull(originalDecision, "original Account decision"); requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger revision = lockInventoryRevision(transaction); - requireNoActiveAccountControl( - lockExistingAccountCoverageControl( - transaction, originalDecision.candidate().accountId())); - String runtimeStatus = - lockLeaseBoundRuntimeBeforeTransition( - transaction, - originalDecision.bindingDecisionId(), - originalDecision.candidate().bindingRef().bytes(), - originalDecision.targetEvidence()); - // This capability feeds final CAS/recovery, including COMMITTED retries. Historical - // receipt retention alone cannot mint current admission source for a stopped runtime. - if (!"RUNNING".equals(runtimeStatus)) { - throw conflict( - "Original NEW final admission source requires its current RUNNING runtime"); - } + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger revision = lockInventoryRevision(transaction); + requireNoActiveAccountControl( + lockExistingAccountCoverageControl( + transaction, originalDecision.candidate().accountId())); + String runtimeStatus = + lockLeaseBoundRuntimeBeforeTransition( + transaction, + originalDecision.bindingDecisionId(), + originalDecision.candidate().bindingRef().bytes(), + originalDecision.targetEvidence()); + // This capability feeds final CAS/recovery, including COMMITTED retries. Historical + // receipt retention alone cannot mint current admission source for a stopped runtime. + if (!"RUNNING".equals(runtimeStatus)) { + throw conflict("Original NEW final admission source requires its current RUNNING runtime"); + } - Record row = - transaction.fetchOne( - "SELECT * FROM " + TRANSITION + " WHERE transition_id = ? FOR UPDATE", - originalDecision.bindingDecisionId()); - if (row == null) throw conflict("Original NEW transition is missing"); - String status = row.get("status", String.class); - boolean committed = "COMMITTED".equals(status); - if (!committed && !"PROVISIONAL".equals(status)) { - throw conflict("Only a provisional or committed original NEW can be a final source"); - } - Record inventoryRow = - transaction.fetchOne( - "SELECT * FROM " + INVENTORY + " WHERE binding_ref = ? FOR UPDATE", - originalDecision.candidate().bindingRef().bytes()); - UUID reservationId = row.get("issuer_reservation_id", UUID.class); - Record reservationRow = - reservationId == null - ? null - : transaction.fetchOne( - "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ? FOR UPDATE", - reservationId); - if (inventoryRow == null || reservationRow == null) { - throw conflict("Original NEW candidate or reservation is missing"); - } - var entry = toInventoryEntry(inventoryRow); - var reservation = toReservation(reservationRow); - var transition = toTransitionSnapshot(row, inventoryRow, reservationRow); - var storedDecision = toAdmissionDecision(row, transition, entry); - if (transition.inventoryRevision().compareTo(revision) > 0 - || transition.expectedPriorBindingRef() != null - || transition.expectedPriorBindingGeneration() != null - || !transition.transitionId().equals(originalDecision.bindingDecisionId()) - || !entry.identity().equals(originalDecision.candidate()) - || !entry.bindingGeneration().equals(transition.bindingGeneration()) - || !entry.transitionId().equals(transition.transitionId()) - || !entry.accountIndexFence().equals(transition.candidateAccountIndexFence()) - || !entry.issuerReservationId().equals(transition.issuerReservationId()) - || !reservation.owner().equals(entry.identity()) - || !reservation.transitionId().equals(transition.transitionId()) - || !reservation.inventoryRevision().equals(transition.inventoryRevision()) - || !entry.inventoryRevision().equals(transition.inventoryRevision()) - || entry.lifecycle() - != (committed - ? CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE - : CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL) - || reservation.lifecycle() - != (committed - ? CanonicalIssuerPartitionReservation.Lifecycle.BOUND - : CanonicalIssuerPartitionReservation.Lifecycle.RESERVED) - || entry.accountIndexState() - != CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED - || entry.issuerIndexState() - != (committed - ? CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED - : CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED)) { - throw conflict( - "Current SQL identity, reservation, or lifecycle differs from original NEW"); - } - requireSameAdmissionDecision(originalDecision, storedDecision); - - byte[] candidateBytes = row.get("original_new_candidate_bytes", byte[].class); - byte[] canonicalBytes = null; - try { - String candidateDigest = row.get("original_new_candidate_digest", String.class); - String readbackDigest = row.get("original_new_candidate_readback_digest", String.class); - if (!"READBACK_CONFIRMED".equals(row.get("original_new_candidate_state", String.class)) - || candidateBytes == null - || candidateBytes.length == 0 - || candidateBytes.length - > CanonicalGameplayOriginalNewCandidateCodec.MAX_CANDIDATE_BYTES - || candidateDigest == null - || !candidateDigest.equals( - CanonicalGameplayIssuerMemberV2Codec.sha256(candidateBytes)) - || readbackDigest == null - || !readbackDigest.matches("sha256:[0-9a-f]{64}") - || !Arrays.equals( - row.get("candidate_binding_ref", byte[].class), - originalDecision.candidate().bindingRef().bytes()) - || !Objects.equals( - row.get("issuer_reservation_id", UUID.class), reservation.reservationId())) { - throw conflict("Original NEW has no exact retained candidate readback marker"); - } - CanonicalGameplayOriginalNewCandidate candidate; - try { - candidate = CanonicalGameplayOriginalNewCandidate.parseCanonical(candidateBytes); - } catch (RuntimeException malformed) { - throw conflict("Retained original NEW candidate bytes are not canonical"); - } - if (!candidate.matchesOriginalDecision(storedDecision) - || !candidate.bindingIdentity().equals(entry.identity()) - || !candidate - .reservation() - .equals( - CanonicalGameplayOriginalNewCandidateCodec.reservationSource(reservation)) - || !candidate.transition().transitionId().equals(transition.transitionId()) - || !candidate - .transition() - .bindingGeneration() - .equals(transition.bindingGeneration()) - || !candidate - .transition() - .issuerReservationId() - .equals(transition.issuerReservationId()) - || !candidate.transition().reservationFence().equals(transition.reservationFence()) - || !candidate - .transition() - .candidateAccountIndexFence() - .equals(transition.candidateAccountIndexFence())) { - throw conflict( - "Retained candidate differs from its original lease, decision, or reservation"); - } - if (!committed) { - CanonicalGameplayBindingProvisionalCasEvidence evidence = - loadProvisionalCasEvidence(transaction, transition.transitionId(), true); - CanonicalGameplayOriginalNewCandidate current = - CanonicalGameplayOriginalNewCandidate.fromOriginalSources( - evidence, originalDecision); - if (evidence.transition().status() - != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL - || !current.equals(candidate) - || !candidate.matchesProvisionalSources(evidence)) { - throw conflict("Provisional candidate no longer matches its exact source"); - } - } - - var obligations = - loadAccountIndexObligations(transaction, transition.transitionId(), true); - if (obligations.size() != 1) { - throw conflict("Original NEW account obligation is not exact"); - } - requireCompletedMemberRepairAcknowledgement( - transaction, transition, entry, obligations.getFirst()); - CanonicalGameplayIssuerBindingLocalAcknowledgement issuerAcknowledgement = - requireOriginalNewFinalIssuerAcknowledgement( - transaction, candidate, transition, committed); - CanonicalGameplayBindingRegionBridgeObligation regionAcknowledgement = - requireOriginalNewFinalRegionAcknowledgement( - transaction, candidate, transition, entry); - - Optional receipt; - if (committed) { - receipt = Optional.of(readOriginalNewFinalAdmissionReceipt(row, storedDecision)); - } else { - requireNoOriginalNewFinalAdmissionReceipt(row); - receipt = Optional.empty(); - } - canonicalBytes = candidate.canonicalBytes(); - if (!Arrays.equals(candidateBytes, canonicalBytes)) { - throw conflict("Retained original NEW candidate changed during source decoding"); - } - return new OriginalNewFinalAdmissionSource( - candidate, - candidateDigest, - readbackDigest, - CanonicalGameplayBindingTransitionSnapshot.Status.valueOf(status), - receipt, - regionAcknowledgement, - issuerAcknowledgement); - } finally { - if (candidateBytes != null) Arrays.fill(candidateBytes, (byte) 0); - if (canonicalBytes != null) Arrays.fill(canonicalBytes, (byte) 0); + Record row = + transaction.fetchOne( + "SELECT * FROM " + TRANSITION + " WHERE transition_id = ? FOR UPDATE", + originalDecision.bindingDecisionId()); + if (row == null) throw conflict("Original NEW transition is missing"); + String status = row.get("status", String.class); + boolean committed = "COMMITTED".equals(status); + if (!committed && !"PROVISIONAL".equals(status)) { + throw conflict("Only a provisional or committed original NEW can be a final source"); + } + Record inventoryRow = + transaction.fetchOne( + "SELECT * FROM " + INVENTORY + " WHERE binding_ref = ? FOR UPDATE", + originalDecision.candidate().bindingRef().bytes()); + UUID reservationId = row.get("issuer_reservation_id", UUID.class); + Record reservationRow = + reservationId == null + ? null + : transaction.fetchOne( + "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ? FOR UPDATE", + reservationId); + if (inventoryRow == null || reservationRow == null) { + throw conflict("Original NEW candidate or reservation is missing"); + } + var entry = toInventoryEntry(inventoryRow); + var reservation = toReservation(reservationRow); + var transition = toTransitionSnapshot(row, inventoryRow, reservationRow); + var storedDecision = toAdmissionDecision(row, transition, entry); + if (transition.inventoryRevision().compareTo(revision) > 0 + || transition.expectedPriorBindingRef() != null + || transition.expectedPriorBindingGeneration() != null + || !transition.transitionId().equals(originalDecision.bindingDecisionId()) + || !entry.identity().equals(originalDecision.candidate()) + || !entry.bindingGeneration().equals(transition.bindingGeneration()) + || !entry.transitionId().equals(transition.transitionId()) + || !entry.accountIndexFence().equals(transition.candidateAccountIndexFence()) + || !entry.issuerReservationId().equals(transition.issuerReservationId()) + || !reservation.owner().equals(entry.identity()) + || !reservation.transitionId().equals(transition.transitionId()) + || !reservation.inventoryRevision().equals(transition.inventoryRevision()) + || !entry.inventoryRevision().equals(transition.inventoryRevision()) + || entry.lifecycle() + != (committed + ? CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE + : CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL) + || reservation.lifecycle() + != (committed + ? CanonicalIssuerPartitionReservation.Lifecycle.BOUND + : CanonicalIssuerPartitionReservation.Lifecycle.RESERVED) + || entry.accountIndexState() + != CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED + || entry.issuerIndexState() + != (committed + ? CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED + : CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED)) { + throw conflict("Current SQL identity, reservation, or lifecycle differs from original NEW"); + } + requireSameAdmissionDecision(originalDecision, storedDecision); + + byte[] candidateBytes = row.get("original_new_candidate_bytes", byte[].class); + byte[] canonicalBytes = null; + try { + String candidateDigest = row.get("original_new_candidate_digest", String.class); + String readbackDigest = row.get("original_new_candidate_readback_digest", String.class); + if (!"READBACK_CONFIRMED".equals(row.get("original_new_candidate_state", String.class)) + || candidateBytes == null + || candidateBytes.length == 0 + || candidateBytes.length + > CanonicalGameplayOriginalNewCandidateCodec.MAX_CANDIDATE_BYTES + || candidateDigest == null + || !candidateDigest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(candidateBytes)) + || readbackDigest == null + || !readbackDigest.matches("sha256:[0-9a-f]{64}") + || !Arrays.equals( + row.get("candidate_binding_ref", byte[].class), + originalDecision.candidate().bindingRef().bytes()) + || !Objects.equals( + row.get("issuer_reservation_id", UUID.class), reservation.reservationId())) { + throw conflict("Original NEW has no exact retained candidate readback marker"); + } + CanonicalGameplayOriginalNewCandidate candidate; + try { + candidate = CanonicalGameplayOriginalNewCandidate.parseCanonical(candidateBytes); + } catch (RuntimeException malformed) { + throw conflict("Retained original NEW candidate bytes are not canonical"); + } + if (!candidate.matchesOriginalDecision(storedDecision) + || !candidate.bindingIdentity().equals(entry.identity()) + || !candidate + .reservation() + .equals(CanonicalGameplayOriginalNewCandidateCodec.reservationSource(reservation)) + || !candidate.transition().transitionId().equals(transition.transitionId()) + || !candidate.transition().bindingGeneration().equals(transition.bindingGeneration()) + || !candidate + .transition() + .issuerReservationId() + .equals(transition.issuerReservationId()) + || !candidate.transition().reservationFence().equals(transition.reservationFence()) + || !candidate + .transition() + .candidateAccountIndexFence() + .equals(transition.candidateAccountIndexFence())) { + throw conflict( + "Retained candidate differs from its original lease, decision, or reservation"); + } + if (!committed) { + CanonicalGameplayBindingProvisionalCasEvidence evidence = + loadProvisionalCasEvidence(transaction, transition.transitionId(), true); + CanonicalGameplayOriginalNewCandidate current = + CanonicalGameplayOriginalNewCandidate.fromOriginalSources(evidence, originalDecision); + if (evidence.transition().status() + != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL + || !current.equals(candidate) + || !candidate.matchesProvisionalSources(evidence)) { + throw conflict("Provisional candidate no longer matches its exact source"); } - }); + } + + var obligations = loadAccountIndexObligations(transaction, transition.transitionId(), true); + if (obligations.size() != 1) { + throw conflict("Original NEW account obligation is not exact"); + } + requireCompletedMemberRepairAcknowledgement( + transaction, transition, entry, obligations.getFirst()); + CanonicalGameplayIssuerBindingLocalAcknowledgement issuerAcknowledgement = + requireOriginalNewFinalIssuerAcknowledgement( + transaction, candidate, transition, committed); + CanonicalGameplayBindingRegionBridgeObligation regionAcknowledgement = + requireOriginalNewFinalRegionAcknowledgement(transaction, candidate, transition, entry); + + Optional receipt; + if (committed) { + receipt = Optional.of(readOriginalNewFinalAdmissionReceipt(row, storedDecision)); + } else { + requireNoOriginalNewFinalAdmissionReceipt(row); + receipt = Optional.empty(); + } + canonicalBytes = candidate.canonicalBytes(); + if (!Arrays.equals(candidateBytes, canonicalBytes)) { + throw conflict("Retained original NEW candidate changed during source decoding"); + } + return new OriginalNewFinalAdmissionSource( + candidate, + candidateDigest, + readbackDigest, + CanonicalGameplayBindingTransitionSnapshot.Status.valueOf(status), + receipt, + regionAcknowledgement, + issuerAcknowledgement); + } finally { + if (candidateBytes != null) Arrays.fill(candidateBytes, (byte) 0); + if (canonicalBytes != null) Arrays.fill(canonicalBytes, (byte) 0); + } + }); } void requireSameProvisionalSource( @@ -1070,56 +1040,55 @@ CanonicalGameplayBindingRegionBridgeObligation prepareRegionBridge( requireBridgeInputs( expectedEvidence, worldRequest, resolvedRegion, runtimeReference, ownerStatus); requireExactBridgePreimage(preimage, inputs, expectedEvidence, ownerStatus); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger currentRevision = lockInventoryRevision(transaction); - lockLeaseBoundRuntimeBeforeTransition( - transaction, - expectedEvidence.transition().transitionId(), - expectedEvidence.candidate().bindingRef().bytes(), - null); - CanonicalGameplayBindingProvisionalCasEvidence currentEvidence = - loadProvisionalCasEvidence( - transaction, expectedEvidence.transition().transitionId(), true); - requireSameProvisionalOperation(expectedEvidence, currentEvidence); - BridgeInputs currentInputs = - requireBridgeInputs( - currentEvidence, worldRequest, resolvedRegion, runtimeReference, ownerStatus); - if (!inputs.equals(currentInputs) || currentEvidence.expectedPrior() != null) { - throw conflict("Region bridge source changed or is not a first-NEW transition"); - } - requireCurrentRegionOwner(transaction, ownerStatus); - Record regionRow = - transaction.fetchOne( - "SELECT * FROM " + REGION_OBLIGATION + " WHERE transition_id = ? FOR UPDATE", - currentEvidence.transition().transitionId()); - if (regionRow == null) throw conflict("Region bridge obligation is missing"); - CanonicalGameplayBindingRegionBridgeObligation existing = toRegionObligation(regionRow); - if (existing.bridgeOperationId() != null) { - if (!matchesPreparedOperation(existing, inputs)) { - throw conflict("A retry changed the retained Entity or World bridge source"); - } - boolean sameGrant = - Objects.equals(existing.executorFence(), ownerStatus.executorFence()) - && Objects.equals( - existing.leaseTokenCorrelation(), ownerStatus.leaseTokenCorrelation()); - if (sameGrant) return existing; - if (existing.status() - == CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED) { - throw conflict( - "A completed region bridge acknowledgement cannot be rewritten for a new grant"); - } - return rewritePreparedBridgeForCurrentGrant( - transaction, currentRevision, currentEvidence, existing, inputs, ownerStatus); - } - if (preimage.state() != CanonicalGameplayRegionLeaseRedisOwner.PreimageState.ABSENT) { - throw conflict("First region bridge operation requires a proven absent Redis preimage"); - } - UUID operationId = UUID.randomUUID(); - return writePreparedBridge( - transaction, currentRevision, currentEvidence, inputs, ownerStatus, operationId); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger currentRevision = lockInventoryRevision(transaction); + lockLeaseBoundRuntimeBeforeTransition( + transaction, + expectedEvidence.transition().transitionId(), + expectedEvidence.candidate().bindingRef().bytes(), + null); + CanonicalGameplayBindingProvisionalCasEvidence currentEvidence = + loadProvisionalCasEvidence( + transaction, expectedEvidence.transition().transitionId(), true); + requireSameProvisionalOperation(expectedEvidence, currentEvidence); + BridgeInputs currentInputs = + requireBridgeInputs( + currentEvidence, worldRequest, resolvedRegion, runtimeReference, ownerStatus); + if (!inputs.equals(currentInputs) || currentEvidence.expectedPrior() != null) { + throw conflict("Region bridge source changed or is not a first-NEW transition"); + } + requireCurrentRegionOwner(transaction, ownerStatus); + Record regionRow = + transaction.fetchOne( + "SELECT * FROM " + REGION_OBLIGATION + " WHERE transition_id = ? FOR UPDATE", + currentEvidence.transition().transitionId()); + if (regionRow == null) throw conflict("Region bridge obligation is missing"); + CanonicalGameplayBindingRegionBridgeObligation existing = toRegionObligation(regionRow); + if (existing.bridgeOperationId() != null) { + if (!matchesPreparedOperation(existing, inputs)) { + throw conflict("A retry changed the retained Entity or World bridge source"); + } + boolean sameGrant = + Objects.equals(existing.executorFence(), ownerStatus.executorFence()) + && Objects.equals( + existing.leaseTokenCorrelation(), ownerStatus.leaseTokenCorrelation()); + if (sameGrant) return existing; + if (existing.status() + == CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED) { + throw conflict( + "A completed region bridge acknowledgement cannot be rewritten for a new grant"); + } + return rewritePreparedBridgeForCurrentGrant( + transaction, currentRevision, currentEvidence, existing, inputs, ownerStatus); + } + if (preimage.state() != CanonicalGameplayRegionLeaseRedisOwner.PreimageState.ABSENT) { + throw conflict("First region bridge operation requires a proven absent Redis preimage"); + } + UUID operationId = UUID.randomUUID(); + return writePreparedBridge( + transaction, currentRevision, currentEvidence, inputs, ownerStatus, operationId); + }); } /** @@ -1153,88 +1122,85 @@ RegionBridgeAcknowledgement acknowledgeRegionBridge( || !readback.leaseTokenCorrelation().equals(ownerStatus.leaseTokenCorrelation())) { throw conflict("Exact fenced bridge readback does not match the prepared operation"); } - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger currentRevision = lockInventoryRevision(transaction); - lockLeaseBoundRuntimeBeforeTransition( - transaction, + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger currentRevision = lockInventoryRevision(transaction); + lockLeaseBoundRuntimeBeforeTransition( + transaction, + prepared.transitionId(), + expectedEvidence.candidate().bindingRef().bytes(), + null); + CanonicalGameplayBindingProvisionalCasEvidence currentEvidence = + loadProvisionalCasEvidence(transaction, prepared.transitionId(), true); + requireSameProvisionalOperation(expectedEvidence, currentEvidence); + BridgeInputs currentInputs = + requireBridgeInputs( + currentEvidence, worldRequest, resolvedRegion, runtimeReference, ownerStatus); + if (!inputs.equals(currentInputs) || currentEvidence.expectedPrior() != null) { + throw conflict("Region bridge sources changed before durable acknowledgement"); + } + requireCurrentRegionOwner(transaction, ownerStatus); + Record regionRow = + transaction.fetchOne( + "SELECT * FROM " + REGION_OBLIGATION + " WHERE transition_id = ? FOR UPDATE", + prepared.transitionId()); + if (regionRow == null) throw conflict("Region bridge obligation is missing"); + CanonicalGameplayBindingRegionBridgeObligation current = toRegionObligation(regionRow); + if (!matchesPreparedOperation(current, inputs) + || !current.bridgeOperationId().equals(prepared.bridgeOperationId()) + || !Objects.equals(current.executorFence(), ownerStatus.executorFence()) + || !Objects.equals( + current.leaseTokenCorrelation(), ownerStatus.leaseTokenCorrelation())) { + throw conflict("Prepared region bridge grant or source changed before acknowledgement"); + } + if (current.status() == CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED) { + if (!ownerStatus.executorFence().equals(readback.executorFence()) + || !current.redisReadbackDigest().equals(readback.digest())) { + throw conflict("A completed region acknowledgement has different readback provenance"); + } + return new RegionBridgeAcknowledgement(current); + } + BigInteger oldRevision = currentEvidence.transition().inventoryRevision(); + BigInteger nextRevision = currentRevision.add(BigInteger.ONE); + writeRevisionRows(transaction, currentEvidence, oldRevision, nextRevision); + requireOne( + transaction.execute( + "UPDATE " + + REGION_OBLIGATION + + " SET status = 'ACKNOWLEDGED', redis_readback_digest = ?," + + " acknowledged_at = ?::timestamptz, inventory_revision = ?" + + " WHERE transition_id = ? AND status = 'REQUIRED'" + + " AND bridge_operation_id = ? AND executor_fence = ?" + + " AND lease_token_correlation = ? AND inventory_revision = ?", + readback.digest(), + OffsetDateTime.ofInstant(persistedAcknowledgedAt, ZoneOffset.UTC), + decimal(nextRevision), prepared.transitionId(), - expectedEvidence.candidate().bindingRef().bytes(), - null); - CanonicalGameplayBindingProvisionalCasEvidence currentEvidence = - loadProvisionalCasEvidence(transaction, prepared.transitionId(), true); - requireSameProvisionalOperation(expectedEvidence, currentEvidence); - BridgeInputs currentInputs = - requireBridgeInputs( - currentEvidence, worldRequest, resolvedRegion, runtimeReference, ownerStatus); - if (!inputs.equals(currentInputs) || currentEvidence.expectedPrior() != null) { - throw conflict("Region bridge sources changed before durable acknowledgement"); - } - requireCurrentRegionOwner(transaction, ownerStatus); - Record regionRow = - transaction.fetchOne( - "SELECT * FROM " + REGION_OBLIGATION + " WHERE transition_id = ? FOR UPDATE", - prepared.transitionId()); - if (regionRow == null) throw conflict("Region bridge obligation is missing"); - CanonicalGameplayBindingRegionBridgeObligation current = toRegionObligation(regionRow); - if (!matchesPreparedOperation(current, inputs) - || !current.bridgeOperationId().equals(prepared.bridgeOperationId()) - || !Objects.equals(current.executorFence(), ownerStatus.executorFence()) - || !Objects.equals( - current.leaseTokenCorrelation(), ownerStatus.leaseTokenCorrelation())) { - throw conflict("Prepared region bridge grant or source changed before acknowledgement"); - } - if (current.status() - == CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED) { - if (!ownerStatus.executorFence().equals(readback.executorFence()) - || !current.redisReadbackDigest().equals(readback.digest())) { - throw conflict( - "A completed region acknowledgement has different readback provenance"); - } - return new RegionBridgeAcknowledgement(current); - } - BigInteger oldRevision = currentEvidence.transition().inventoryRevision(); - BigInteger nextRevision = currentRevision.add(BigInteger.ONE); - writeRevisionRows(transaction, currentEvidence, oldRevision, nextRevision); - requireOne( - transaction.execute( - "UPDATE " - + REGION_OBLIGATION - + " SET status = 'ACKNOWLEDGED', redis_readback_digest = ?," - + " acknowledged_at = ?::timestamptz, inventory_revision = ?" - + " WHERE transition_id = ? AND status = 'REQUIRED'" - + " AND bridge_operation_id = ? AND executor_fence = ?" - + " AND lease_token_correlation = ? AND inventory_revision = ?", - readback.digest(), - OffsetDateTime.ofInstant(persistedAcknowledgedAt, ZoneOffset.UTC), - decimal(nextRevision), - prepared.transitionId(), - prepared.bridgeOperationId(), - decimal(ownerStatus.executorFence()), - ownerStatus.leaseTokenCorrelation(), - decimal(oldRevision)), - "Region bridge obligation changed before acknowledgement commit"); - bumpInventoryClock(transaction, currentRevision, nextRevision); - Record acknowledgedRow = - transaction.fetchOne( - "SELECT * FROM " + REGION_OBLIGATION + " WHERE transition_id = ?", - prepared.transitionId()); - CanonicalGameplayBindingRegionBridgeObligation acknowledged = - acknowledgedRow == null ? null : toRegionObligation(acknowledgedRow); - if (acknowledged == null - || acknowledged.status() - != CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED - || !acknowledged.bridgeOperationId().equals(prepared.bridgeOperationId()) - || !acknowledged.executorFence().equals(ownerStatus.executorFence()) - || !acknowledged.leaseTokenCorrelation().equals(ownerStatus.leaseTokenCorrelation()) - || !acknowledged.redisReadbackDigest().equals(readback.digest()) - || !acknowledged.acknowledgedAt().equals(persistedAcknowledgedAt) - || !acknowledged.inventoryRevision().equals(nextRevision)) { - throw conflict("Region bridge acknowledgement did not survive exact SQL readback"); - } - return new RegionBridgeAcknowledgement(acknowledged); - }); + prepared.bridgeOperationId(), + decimal(ownerStatus.executorFence()), + ownerStatus.leaseTokenCorrelation(), + decimal(oldRevision)), + "Region bridge obligation changed before acknowledgement commit"); + bumpInventoryClock(transaction, currentRevision, nextRevision); + Record acknowledgedRow = + transaction.fetchOne( + "SELECT * FROM " + REGION_OBLIGATION + " WHERE transition_id = ?", + prepared.transitionId()); + CanonicalGameplayBindingRegionBridgeObligation acknowledged = + acknowledgedRow == null ? null : toRegionObligation(acknowledgedRow); + if (acknowledged == null + || acknowledged.status() + != CanonicalGameplayBindingRegionBridgeObligation.Status.ACKNOWLEDGED + || !acknowledged.bridgeOperationId().equals(prepared.bridgeOperationId()) + || !acknowledged.executorFence().equals(ownerStatus.executorFence()) + || !acknowledged.leaseTokenCorrelation().equals(ownerStatus.leaseTokenCorrelation()) + || !acknowledged.redisReadbackDigest().equals(readback.digest()) + || !acknowledged.acknowledgedAt().equals(persistedAcknowledgedAt) + || !acknowledged.inventoryRevision().equals(nextRevision)) { + throw conflict("Region bridge acknowledgement did not survive exact SQL readback"); + } + return new RegionBridgeAcknowledgement(acknowledged); + }); } private CanonicalGameplayBindingRegionBridgeObligation rewritePreparedBridgeForCurrentGrant( @@ -1716,25 +1682,24 @@ public CanonicalGameplayAdmissionDecision readAdmissionDecision( UUID bindingDecisionId, AccountGameplayAdmissionLeaseEvidence expectedLeaseEvidence) { Objects.requireNonNull(bindingDecisionId, "bindingDecisionId"); Objects.requireNonNull(expectedLeaseEvidence, "expectedLeaseEvidence"); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - CanonicalGameplayBindingProvisionalCasEvidence operation = - loadProvisionalCasEvidence(transaction, bindingDecisionId, false); - if (operation.transition().status() - != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL - || operation.candidate().lifecycle() - != CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL) { - throw conflict("Only an exact durable PROVISIONAL transition is a decision"); - } - Record row = readTransition(transaction, bindingDecisionId); - CanonicalGameplayAdmissionDecision stored = toAdmissionDecision(row, operation); - if (!stored.leaseEvidence().hasSameIdentity(expectedLeaseEvidence)) { - throw conflict("Expected Account lease differs from the immutable stored decision"); - } - return stored; - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + CanonicalGameplayBindingProvisionalCasEvidence operation = + loadProvisionalCasEvidence(transaction, bindingDecisionId, false); + if (operation.transition().status() + != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL + || operation.candidate().lifecycle() + != CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL) { + throw conflict("Only an exact durable PROVISIONAL transition is a decision"); + } + Record row = readTransition(transaction, bindingDecisionId); + CanonicalGameplayAdmissionDecision stored = toAdmissionDecision(row, operation); + if (!stored.leaseEvidence().hasSameIdentity(expectedLeaseEvidence)) { + throw conflict("Expected Account lease differs from the immutable stored decision"); + } + return stored; + }); } /** @@ -1744,12 +1709,11 @@ public CanonicalGameplayAdmissionDecision readAdmissionDecision( */ CanonicalGameplayAdmissionAbortSource readFirstNewAdmissionAbortSource(UUID transitionId) { Objects.requireNonNull(transitionId, "transitionId"); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - return loadFirstNewAdmissionAbortSource(transaction, transitionId, false); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + return loadFirstNewAdmissionAbortSource(transaction, transitionId, false); + }); } /** @@ -1757,12 +1721,11 @@ CanonicalGameplayAdmissionAbortSource readFirstNewAdmissionAbortSource(UUID tran */ CanonicalGameplayAdmissionAbortSource readFirstNewAdmissionAbortRetrySource(UUID transitionId) { Objects.requireNonNull(transitionId, "transitionId"); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - return loadFirstNewAdmissionAbortRetrySource(transaction, transitionId, false); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + return loadFirstNewAdmissionAbortRetrySource(transaction, transitionId, false); + }); } /** @@ -1773,12 +1736,11 @@ CanonicalGameplayAdmissionAbortSource readFirstNewAdmissionAbortRetrySource(UUID CanonicalGameplayAdmissionAbortSource readRetainedDefinitiveFirstNewAccountAbortSource( UUID transitionId) { Objects.requireNonNull(transitionId, "transitionId"); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - return loadFirstNewAdmissionAbortSource(transaction, transitionId, false, true); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + return loadFirstNewAdmissionAbortSource(transaction, transitionId, false, true); + }); } /** @@ -1819,179 +1781,178 @@ CanonicalGameplayAdmissionAbortSource recordFirstNewAccountAbort( return retained; } - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger currentRevision = lockInventoryRevision(transaction); - UUID transitionId = expectedSource.transition().transitionId(); - CanonicalGameplayAdmissionAbortSource beforeRuntimeLock = - loadFirstNewAdmissionAbortRetrySource(transaction, transitionId, false); - if (beforeRuntimeLock.isAccountAborted()) { - requireSameFirstNewAdmissionAbortSource(expectedSource, beforeRuntimeLock); - if (!orphanCleanupId.equals(beforeRuntimeLock.orphanCleanupId())) { - throw conflict("Concurrent Account abort changed the durable cleanup identity"); - } - return beforeRuntimeLock; - } - lockLeaseBoundRuntimeBeforeTransition( - transaction, - transitionId, - expectedSource.transition().bindingRef().bytes(), - expectedSource.originalDecision().targetEvidence()); - CanonicalGameplayAdmissionAbortSource current = - loadFirstNewAdmissionAbortRetrySource(transaction, transitionId, true); - requireSameFirstNewAdmissionAbortSource(expectedSource, current); - - if (current.isAccountAborted()) { - if (!orphanCleanupId.equals(current.orphanCleanupId())) { - throw conflict("Concurrent Account abort changed the durable cleanup identity"); - } - return current; - } - requireAccountCoverageEvidenceCurrent( - transaction, - current.candidate().identity().accountId(), - current.transition().accountCoverageEvidence()); - if (current.transition().status() - != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) { - throw conflict("Only the exact PROVISIONAL first-NEW transition may abort"); - } + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger currentRevision = lockInventoryRevision(transaction); + UUID transitionId = expectedSource.transition().transitionId(); + CanonicalGameplayAdmissionAbortSource beforeRuntimeLock = + loadFirstNewAdmissionAbortRetrySource(transaction, transitionId, false); + if (beforeRuntimeLock.isAccountAborted()) { + requireSameFirstNewAdmissionAbortSource(expectedSource, beforeRuntimeLock); + if (!orphanCleanupId.equals(beforeRuntimeLock.orphanCleanupId())) { + throw conflict("Concurrent Account abort changed the durable cleanup identity"); + } + return beforeRuntimeLock; + } + lockLeaseBoundRuntimeBeforeTransition( + transaction, + transitionId, + expectedSource.transition().bindingRef().bytes(), + expectedSource.originalDecision().targetEvidence()); + CanonicalGameplayAdmissionAbortSource current = + loadFirstNewAdmissionAbortRetrySource(transaction, transitionId, true); + requireSameFirstNewAdmissionAbortSource(expectedSource, current); + + if (current.isAccountAborted()) { + if (!orphanCleanupId.equals(current.orphanCleanupId())) { + throw conflict("Concurrent Account abort changed the durable cleanup identity"); + } + return current; + } + requireAccountCoverageEvidenceCurrent( + transaction, + current.candidate().identity().accountId(), + current.transition().accountCoverageEvidence()); + if (current.transition().status() + != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) { + throw conflict("Only the exact PROVISIONAL first-NEW transition may abort"); + } - BigInteger priorRevision = current.transition().inventoryRevision(); - BigInteger nextRevision = currentRevision.add(BigInteger.ONE); - int transitionChanged = - transaction.execute( - "UPDATE " - + TRANSITION - + " SET status = 'ABORTED', admission_orphan_cleanup_id = ?," - + " inventory_revision = ?" - + " WHERE transition_id = ? AND status = 'PROVISIONAL'" - + " AND inventory_revision = ? AND candidate_binding_ref = ?" - + " AND candidate_binding_generation = ?" - + " AND candidate_account_index_fence = ? AND issuer_reservation_id = ?" - + " AND expected_prior_binding_ref IS NULL" - + " AND expected_prior_binding_generation IS NULL" - + " AND admission_lease_kind = 'NEW_BINDING'" - + " AND admission_request_id = ? AND admission_lease_id = ?" - + " AND admission_lease_fence = ? AND admission_lease_digest = ?" - + " AND admission_lease_evidence = ?" - + " AND admission_orphan_cleanup_id IS NULL", - orphanCleanupId, - decimal(nextRevision), - transitionId, - decimal(priorRevision), - current.transition().bindingRef().bytes(), - decimal(current.transition().bindingGeneration()), - current.transition().candidateAccountIndexFence(), - current.transition().issuerReservationId(), - current.originalDecision().requestId(), - current.originalDecision().leaseId(), - decimal(current.originalDecision().leaseFence()), - current.originalDecision().leaseSha256(), - current.originalDecision().leaseEvidenceJson()); - requireOne( - transitionChanged, - "Exact first-NEW Account abort lost its immutable transition compare-and-set"); + BigInteger priorRevision = current.transition().inventoryRevision(); + BigInteger nextRevision = currentRevision.add(BigInteger.ONE); + int transitionChanged = + transaction.execute( + "UPDATE " + + TRANSITION + + " SET status = 'ABORTED', admission_orphan_cleanup_id = ?," + + " inventory_revision = ?" + + " WHERE transition_id = ? AND status = 'PROVISIONAL'" + + " AND inventory_revision = ? AND candidate_binding_ref = ?" + + " AND candidate_binding_generation = ?" + + " AND candidate_account_index_fence = ? AND issuer_reservation_id = ?" + + " AND expected_prior_binding_ref IS NULL" + + " AND expected_prior_binding_generation IS NULL" + + " AND admission_lease_kind = 'NEW_BINDING'" + + " AND admission_request_id = ? AND admission_lease_id = ?" + + " AND admission_lease_fence = ? AND admission_lease_digest = ?" + + " AND admission_lease_evidence = ?" + + " AND admission_orphan_cleanup_id IS NULL", + orphanCleanupId, + decimal(nextRevision), + transitionId, + decimal(priorRevision), + current.transition().bindingRef().bytes(), + decimal(current.transition().bindingGeneration()), + current.transition().candidateAccountIndexFence(), + current.transition().issuerReservationId(), + current.originalDecision().requestId(), + current.originalDecision().leaseId(), + decimal(current.originalDecision().leaseFence()), + current.originalDecision().leaseSha256(), + current.originalDecision().leaseEvidenceJson()); + requireOne( + transitionChanged, + "Exact first-NEW Account abort lost its immutable transition compare-and-set"); - int reservationChanged = - transaction.execute( - "UPDATE " - + RESERVATION - + " SET lifecycle = 'RELEASE_PENDING', inventory_revision = ?" - + " WHERE reservation_id = ? AND transition_id = ?" - + " AND lifecycle = 'RESERVED' AND inventory_revision = ?" - + " AND binding_ref = ? AND binding_generation = ?" - + " AND reservation_fence = ? AND account_id = ? AND tenant_id = ?" - + " AND playable_state_namespace_id = ? AND character_id = ?" - + " AND game_instance_id = ? AND runtime_game_instance_id = ?" - + " AND session_id = ? AND region_id = ? AND region_epoch = ?" - + " AND issuer_id = ? AND issuer_auth_generation = ?", - decimal(nextRevision), - current.reservation().reservationId(), - transitionId, - decimal(priorRevision), - current.transition().bindingRef().bytes(), - decimal(current.transition().bindingGeneration()), - current.reservation().reservationFence(), - current.candidate().identity().accountId(), - current.candidate().identity().tenantId(), - current.candidate().identity().playableStateNamespaceId(), - current.candidate().identity().characterId(), - current.candidate().identity().gameInstanceId(), - current.candidate().identity().runtimeGameInstanceId(), - current.candidate().identity().sessionId(), - current.candidate().identity().regionId(), - decimal(current.candidate().identity().regionEpoch()), - current.candidate().identity().issuerId(), - decimal(current.candidate().identity().issuerAuthGeneration())); - requireOne( - reservationChanged, - "Exact first-NEW Account abort lost its retained reservation compare-and-set"); + int reservationChanged = + transaction.execute( + "UPDATE " + + RESERVATION + + " SET lifecycle = 'RELEASE_PENDING', inventory_revision = ?" + + " WHERE reservation_id = ? AND transition_id = ?" + + " AND lifecycle = 'RESERVED' AND inventory_revision = ?" + + " AND binding_ref = ? AND binding_generation = ?" + + " AND reservation_fence = ? AND account_id = ? AND tenant_id = ?" + + " AND playable_state_namespace_id = ? AND character_id = ?" + + " AND game_instance_id = ? AND runtime_game_instance_id = ?" + + " AND session_id = ? AND region_id = ? AND region_epoch = ?" + + " AND issuer_id = ? AND issuer_auth_generation = ?", + decimal(nextRevision), + current.reservation().reservationId(), + transitionId, + decimal(priorRevision), + current.transition().bindingRef().bytes(), + decimal(current.transition().bindingGeneration()), + current.reservation().reservationFence(), + current.candidate().identity().accountId(), + current.candidate().identity().tenantId(), + current.candidate().identity().playableStateNamespaceId(), + current.candidate().identity().characterId(), + current.candidate().identity().gameInstanceId(), + current.candidate().identity().runtimeGameInstanceId(), + current.candidate().identity().sessionId(), + current.candidate().identity().regionId(), + decimal(current.candidate().identity().regionEpoch()), + current.candidate().identity().issuerId(), + decimal(current.candidate().identity().issuerAuthGeneration())); + requireOne( + reservationChanged, + "Exact first-NEW Account abort lost its retained reservation compare-and-set"); - int candidateChanged = - transaction.execute( - "UPDATE " - + INVENTORY - + " SET lifecycle = 'TERMINAL_UNRESOLVED', inventory_revision = ?" - + " WHERE binding_ref = ? AND transition_id = ?" - + " AND lifecycle = 'PROVISIONAL' AND inventory_revision = ?" - + " AND binding_generation = ? AND account_index_fence = ?" - + " AND tenant_id = ? AND playable_state_namespace_id = ?" - + " AND character_id = ? AND account_id = ?", - decimal(nextRevision), - current.transition().bindingRef().bytes(), - transitionId, - decimal(priorRevision), - decimal(current.transition().bindingGeneration()), - current.transition().candidateAccountIndexFence(), - current.candidate().identity().tenantId(), - current.candidate().identity().playableStateNamespaceId(), - current.candidate().identity().characterId(), - current.candidate().identity().accountId()); - requireOne( - candidateChanged, - "Exact first-NEW Account abort lost its retained candidate compare-and-set"); + int candidateChanged = + transaction.execute( + "UPDATE " + + INVENTORY + + " SET lifecycle = 'TERMINAL_UNRESOLVED', inventory_revision = ?" + + " WHERE binding_ref = ? AND transition_id = ?" + + " AND lifecycle = 'PROVISIONAL' AND inventory_revision = ?" + + " AND binding_generation = ? AND account_index_fence = ?" + + " AND tenant_id = ? AND playable_state_namespace_id = ?" + + " AND character_id = ? AND account_id = ?", + decimal(nextRevision), + current.transition().bindingRef().bytes(), + transitionId, + decimal(priorRevision), + decimal(current.transition().bindingGeneration()), + current.transition().candidateAccountIndexFence(), + current.candidate().identity().tenantId(), + current.candidate().identity().playableStateNamespaceId(), + current.candidate().identity().characterId(), + current.candidate().identity().accountId()); + requireOne( + candidateChanged, + "Exact first-NEW Account abort lost its retained candidate compare-and-set"); - requireOne( - transaction.execute( - "UPDATE " - + ACCOUNT_OBLIGATION - + " SET inventory_revision = ? WHERE transition_id = ?" - + " AND inventory_revision = ?", - decimal(nextRevision), - transitionId, - decimal(priorRevision)), - "First-NEW Account abort lost its required account-index obligation"); - requireOne( - transaction.execute( - "UPDATE " - + ISSUER_OBLIGATION - + " SET inventory_revision = ? WHERE transition_id = ?" - + " AND inventory_revision = ?", - decimal(nextRevision), - transitionId, - decimal(priorRevision)), - "First-NEW Account abort lost its required issuer-index obligation"); - requireOne( - transaction.execute( - "UPDATE " - + REGION_OBLIGATION - + " SET inventory_revision = ? WHERE transition_id = ?" - + " AND inventory_revision = ?", - decimal(nextRevision), - transitionId, - decimal(priorRevision)), - "First-NEW Account abort lost its required region-bridge obligation"); - requireOne( - transaction.execute( - "UPDATE game_session_canonical_binding_inventory_clock" - + " SET inventory_revision = ? WHERE singleton_id = 1" - + " AND inventory_revision = ?", - decimal(nextRevision), - decimal(currentRevision)), - "First-NEW Account abort lost its inventory revision compare-and-set"); - return loadFirstNewAdmissionAbortSource(transaction, transitionId, false); - }); + requireOne( + transaction.execute( + "UPDATE " + + ACCOUNT_OBLIGATION + + " SET inventory_revision = ? WHERE transition_id = ?" + + " AND inventory_revision = ?", + decimal(nextRevision), + transitionId, + decimal(priorRevision)), + "First-NEW Account abort lost its required account-index obligation"); + requireOne( + transaction.execute( + "UPDATE " + + ISSUER_OBLIGATION + + " SET inventory_revision = ? WHERE transition_id = ?" + + " AND inventory_revision = ?", + decimal(nextRevision), + transitionId, + decimal(priorRevision)), + "First-NEW Account abort lost its required issuer-index obligation"); + requireOne( + transaction.execute( + "UPDATE " + + REGION_OBLIGATION + + " SET inventory_revision = ? WHERE transition_id = ?" + + " AND inventory_revision = ?", + decimal(nextRevision), + transitionId, + decimal(priorRevision)), + "First-NEW Account abort lost its required region-bridge obligation"); + requireOne( + transaction.execute( + "UPDATE game_session_canonical_binding_inventory_clock" + + " SET inventory_revision = ? WHERE singleton_id = 1" + + " AND inventory_revision = ?", + decimal(nextRevision), + decimal(currentRevision)), + "First-NEW Account abort lost its inventory revision compare-and-set"); + return loadFirstNewAdmissionAbortSource(transaction, transitionId, false); + }); } /** @@ -2002,191 +1963,188 @@ CanonicalGameplayBindingAccountIndexProjectionReceipt markCandidateAccountIndexP CanonicalGameplayBindingProvisionalCasEvidence expectedEvidence, String member) { Objects.requireNonNull(expectedEvidence, "expectedEvidence"); Objects.requireNonNull(member, "member"); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger currentRevision = lockInventoryRevision(transaction); - UUID transitionId = expectedEvidence.transition().transitionId(); - lockLeaseBoundRuntimeBeforeTransition( - transaction, transitionId, expectedEvidence.candidate().bindingRef().bytes(), null); - CanonicalGameplayBindingProvisionalCasEvidence current = - loadProvisionalCasEvidence(transaction, transitionId, true); - requireAccountCoverageEvidenceCurrent( - transaction, - current.candidate().identity().accountId(), - current.transition().accountCoverageEvidence()); - requireSameProvisionalOperation(expectedEvidence, current); - if (current.transition().status() - != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) { - throw conflict("Only the exact PROVISIONAL candidate may project its account member"); - } - CanonicalGameplayAccountIndexMember exactMember = - CanonicalGameplayAccountIndexMember.of(current.candidate()); - if (!exactMember.value().equals(member)) { - throw conflict("Redis readback member differs from the exact durable candidate tuple"); - } + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger currentRevision = lockInventoryRevision(transaction); + UUID transitionId = expectedEvidence.transition().transitionId(); + lockLeaseBoundRuntimeBeforeTransition( + transaction, transitionId, expectedEvidence.candidate().bindingRef().bytes(), null); + CanonicalGameplayBindingProvisionalCasEvidence current = + loadProvisionalCasEvidence(transaction, transitionId, true); + requireAccountCoverageEvidenceCurrent( + transaction, + current.candidate().identity().accountId(), + current.transition().accountCoverageEvidence()); + requireSameProvisionalOperation(expectedEvidence, current); + if (current.transition().status() + != CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) { + throw conflict("Only the exact PROVISIONAL candidate may project its account member"); + } + CanonicalGameplayAccountIndexMember exactMember = + CanonicalGameplayAccountIndexMember.of(current.candidate()); + if (!exactMember.value().equals(member)) { + throw conflict("Redis readback member differs from the exact durable candidate tuple"); + } - List obligations = - loadAccountIndexObligations(transaction, transitionId, true); - int expectedObligations = current.expectedPrior() == null ? 1 : 2; - if (obligations.size() != expectedObligations) { - throw conflict("The exact transition no longer has every required account obligation"); - } - var candidateObligation = obligations.getFirst(); - if (candidateObligation.ordinal() != 0 - || candidateObligation.action() - != CanonicalGameplayBindingAccountIndexObligation.Action.ADD_OR_RETAIN - || candidateObligation.executionPhase() - != CanonicalGameplayBindingAccountIndexObligation.ExecutionPhase.BEFORE_FINAL_CAS - || !candidateObligation.bindingRef().equals(current.candidate().bindingRef()) - || !candidateObligation.accountId().equals(current.candidate().identity().accountId()) - || !candidateObligation.tenantId().equals(current.candidate().identity().tenantId()) - || !candidateObligation - .bindingGeneration() - .equals(current.candidate().bindingGeneration()) - || !candidateObligation - .accountIndexFence() - .equals(current.candidate().accountIndexFence()) - || (candidateObligation.status() - != CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED - && candidateObligation.status() - != CanonicalGameplayBindingAccountIndexObligation.Status.ACKNOWLEDGED)) { - throw conflict("The account-index candidate obligation differs from durable ownership"); - } - if (candidateObligation.status() - == CanonicalGameplayBindingAccountIndexObligation.Status.ACKNOWLEDGED) { - if (candidateObligation.projectionState() - != CanonicalGameplayBindingAccountIndexObligation.ProjectionState - .PRESENT_AWAITING_COVERAGE - || !member.equals(candidateObligation.projectedMember())) { - throw conflict( - "Completed account-index acknowledgement differs from the exact member"); - } - return projectionReceipt(candidateObligation); - } - if (candidateObligation.projectionState() - == CanonicalGameplayBindingAccountIndexObligation.ProjectionState - .PRESENT_AWAITING_COVERAGE) { - if (!member.equals(candidateObligation.projectedMember())) { - throw conflict("A prior exact account-index readback retained a different member"); - } - return projectionReceipt(candidateObligation); - } - if (candidateObligation.projectionState() - != CanonicalGameplayBindingAccountIndexObligation.ProjectionState.REQUIRED) { - throw conflict( - "Candidate account-index obligation is in a conflicting projection state"); - } + List obligations = + loadAccountIndexObligations(transaction, transitionId, true); + int expectedObligations = current.expectedPrior() == null ? 1 : 2; + if (obligations.size() != expectedObligations) { + throw conflict("The exact transition no longer has every required account obligation"); + } + var candidateObligation = obligations.getFirst(); + if (candidateObligation.ordinal() != 0 + || candidateObligation.action() + != CanonicalGameplayBindingAccountIndexObligation.Action.ADD_OR_RETAIN + || candidateObligation.executionPhase() + != CanonicalGameplayBindingAccountIndexObligation.ExecutionPhase.BEFORE_FINAL_CAS + || !candidateObligation.bindingRef().equals(current.candidate().bindingRef()) + || !candidateObligation.accountId().equals(current.candidate().identity().accountId()) + || !candidateObligation.tenantId().equals(current.candidate().identity().tenantId()) + || !candidateObligation + .bindingGeneration() + .equals(current.candidate().bindingGeneration()) + || !candidateObligation + .accountIndexFence() + .equals(current.candidate().accountIndexFence()) + || (candidateObligation.status() + != CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED + && candidateObligation.status() + != CanonicalGameplayBindingAccountIndexObligation.Status.ACKNOWLEDGED)) { + throw conflict("The account-index candidate obligation differs from durable ownership"); + } + if (candidateObligation.status() + == CanonicalGameplayBindingAccountIndexObligation.Status.ACKNOWLEDGED) { + if (candidateObligation.projectionState() + != CanonicalGameplayBindingAccountIndexObligation.ProjectionState + .PRESENT_AWAITING_COVERAGE + || !member.equals(candidateObligation.projectedMember())) { + throw conflict("Completed account-index acknowledgement differs from the exact member"); + } + return projectionReceipt(candidateObligation); + } + if (candidateObligation.projectionState() + == CanonicalGameplayBindingAccountIndexObligation.ProjectionState + .PRESENT_AWAITING_COVERAGE) { + if (!member.equals(candidateObligation.projectedMember())) { + throw conflict("A prior exact account-index readback retained a different member"); + } + return projectionReceipt(candidateObligation); + } + if (candidateObligation.projectionState() + != CanonicalGameplayBindingAccountIndexObligation.ProjectionState.REQUIRED) { + throw conflict("Candidate account-index obligation is in a conflicting projection state"); + } - BigInteger transitionRevision = current.transition().inventoryRevision(); - BigInteger nextRevision = currentRevision.add(BigInteger.ONE); - requireOne( - transaction.execute( - "UPDATE " - + TRANSITION - + " SET inventory_revision = ?" - + " WHERE transition_id = ? AND status = 'PROVISIONAL'" - + " AND inventory_revision = ? AND candidate_binding_ref = ?" - + " AND candidate_binding_generation = ? AND candidate_account_index_fence = ?", - decimal(nextRevision), - transitionId, - decimal(transitionRevision), - current.candidate().bindingRef().bytes(), - decimal(current.transition().bindingGeneration()), - current.transition().candidateAccountIndexFence()), - "Durable transition changed before account-index readback persistence"); - requireOne( - transaction.execute( - "UPDATE " - + INVENTORY - + " SET inventory_revision = ?" - + " WHERE binding_ref = ? AND transition_id = ? AND lifecycle = 'PROVISIONAL'" - + " AND binding_generation = ? AND account_index_fence = ?" - + " AND account_index_state = 'REPAIR_REQUIRED' AND inventory_revision = ?", - decimal(nextRevision), - current.candidate().bindingRef().bytes(), - transitionId, - decimal(current.transition().bindingGeneration()), - current.transition().candidateAccountIndexFence(), - decimal(transitionRevision)), - "Durable candidate changed before account-index readback persistence"); - requireOne( - transaction.execute( - "UPDATE " - + ACCOUNT_OBLIGATION - + " SET projection_state = 'PRESENT_AWAITING_COVERAGE'," - + " projection_member = ?, projection_inventory_revision = ?, inventory_revision = ?" - + " WHERE transition_id = ? AND obligation_ordinal = 0" - + " AND action = 'ADD_OR_RETAIN' AND projection_state = 'REQUIRED'" - + " AND binding_ref = ? AND account_id = ? AND tenant_id = ?" - + " AND binding_generation = ? AND account_index_fence = ?" - + " AND inventory_revision = ?", - member, - decimal(nextRevision), - decimal(nextRevision), - transitionId, - candidateObligation.bindingRef().bytes(), - candidateObligation.accountId(), - candidateObligation.tenantId(), - decimal(candidateObligation.bindingGeneration()), - candidateObligation.accountIndexFence(), - decimal(transitionRevision)), - "Durable candidate account-index obligation changed before readback persistence"); - requireCount( - transaction.execute( - "UPDATE " - + ACCOUNT_OBLIGATION - + " SET inventory_revision = ?" - + " WHERE transition_id = ? AND obligation_ordinal = 1" - + " AND inventory_revision = ?", - decimal(nextRevision), - transitionId, - decimal(transitionRevision)), - current.expectedPrior() == null ? 0 : 1, - "Durable prior account-index obligation changed before readback persistence"); - requireOne( - transaction.execute( - "UPDATE " - + ISSUER_OBLIGATION - + " SET inventory_revision = ?" - + " WHERE transition_id = ? AND inventory_revision = ?", - decimal(nextRevision), - transitionId, - decimal(transitionRevision)), - "Durable issuer obligation changed before account-index readback persistence"); - requireOne( - transaction.execute( - "UPDATE " - + REGION_OBLIGATION - + " SET inventory_revision = ?" - + " WHERE transition_id = ? AND inventory_revision = ?", - decimal(nextRevision), - transitionId, - decimal(transitionRevision)), - "Durable region obligation changed before account-index readback persistence"); - requireOne( - transaction.execute( - "UPDATE " - + RESERVATION - + " SET inventory_revision = ?" - + " WHERE reservation_id = ? AND transition_id = ?" - + " AND lifecycle = 'RESERVED' AND inventory_revision = ?", - decimal(nextRevision), - current.transition().issuerReservationId(), - transitionId, - decimal(transitionRevision)), - "Durable issuer reservation changed before account-index readback persistence"); - requireOne( - transaction.execute( - "UPDATE game_session_canonical_binding_inventory_clock" - + " SET inventory_revision = ? WHERE singleton_id = 1" - + " AND inventory_revision = ?", - decimal(nextRevision), - decimal(currentRevision)), - "Durable inventory revision compare-and-set lost during account-index readback"); - var saved = loadAccountIndexObligations(transaction, transitionId, false).getFirst(); - return projectionReceipt(saved); - }); + BigInteger transitionRevision = current.transition().inventoryRevision(); + BigInteger nextRevision = currentRevision.add(BigInteger.ONE); + requireOne( + transaction.execute( + "UPDATE " + + TRANSITION + + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND status = 'PROVISIONAL'" + + " AND inventory_revision = ? AND candidate_binding_ref = ?" + + " AND candidate_binding_generation = ? AND candidate_account_index_fence = ?", + decimal(nextRevision), + transitionId, + decimal(transitionRevision), + current.candidate().bindingRef().bytes(), + decimal(current.transition().bindingGeneration()), + current.transition().candidateAccountIndexFence()), + "Durable transition changed before account-index readback persistence"); + requireOne( + transaction.execute( + "UPDATE " + + INVENTORY + + " SET inventory_revision = ?" + + " WHERE binding_ref = ? AND transition_id = ? AND lifecycle = 'PROVISIONAL'" + + " AND binding_generation = ? AND account_index_fence = ?" + + " AND account_index_state = 'REPAIR_REQUIRED' AND inventory_revision = ?", + decimal(nextRevision), + current.candidate().bindingRef().bytes(), + transitionId, + decimal(current.transition().bindingGeneration()), + current.transition().candidateAccountIndexFence(), + decimal(transitionRevision)), + "Durable candidate changed before account-index readback persistence"); + requireOne( + transaction.execute( + "UPDATE " + + ACCOUNT_OBLIGATION + + " SET projection_state = 'PRESENT_AWAITING_COVERAGE'," + + " projection_member = ?, projection_inventory_revision = ?, inventory_revision = ?" + + " WHERE transition_id = ? AND obligation_ordinal = 0" + + " AND action = 'ADD_OR_RETAIN' AND projection_state = 'REQUIRED'" + + " AND binding_ref = ? AND account_id = ? AND tenant_id = ?" + + " AND binding_generation = ? AND account_index_fence = ?" + + " AND inventory_revision = ?", + member, + decimal(nextRevision), + decimal(nextRevision), + transitionId, + candidateObligation.bindingRef().bytes(), + candidateObligation.accountId(), + candidateObligation.tenantId(), + decimal(candidateObligation.bindingGeneration()), + candidateObligation.accountIndexFence(), + decimal(transitionRevision)), + "Durable candidate account-index obligation changed before readback persistence"); + requireCount( + transaction.execute( + "UPDATE " + + ACCOUNT_OBLIGATION + + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND obligation_ordinal = 1" + + " AND inventory_revision = ?", + decimal(nextRevision), + transitionId, + decimal(transitionRevision)), + current.expectedPrior() == null ? 0 : 1, + "Durable prior account-index obligation changed before readback persistence"); + requireOne( + transaction.execute( + "UPDATE " + + ISSUER_OBLIGATION + + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND inventory_revision = ?", + decimal(nextRevision), + transitionId, + decimal(transitionRevision)), + "Durable issuer obligation changed before account-index readback persistence"); + requireOne( + transaction.execute( + "UPDATE " + + REGION_OBLIGATION + + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND inventory_revision = ?", + decimal(nextRevision), + transitionId, + decimal(transitionRevision)), + "Durable region obligation changed before account-index readback persistence"); + requireOne( + transaction.execute( + "UPDATE " + + RESERVATION + + " SET inventory_revision = ?" + + " WHERE reservation_id = ? AND transition_id = ?" + + " AND lifecycle = 'RESERVED' AND inventory_revision = ?", + decimal(nextRevision), + current.transition().issuerReservationId(), + transitionId, + decimal(transitionRevision)), + "Durable issuer reservation changed before account-index readback persistence"); + requireOne( + transaction.execute( + "UPDATE game_session_canonical_binding_inventory_clock" + + " SET inventory_revision = ? WHERE singleton_id = 1" + + " AND inventory_revision = ?", + decimal(nextRevision), + decimal(currentRevision)), + "Durable inventory revision compare-and-set lost during account-index readback"); + var saved = loadAccountIndexObligations(transaction, transitionId, false).getFirst(); + return projectionReceipt(saved); + }); } /** @@ -2196,75 +2154,71 @@ CanonicalGameplayBindingAccountIndexProjectionReceipt markCandidateAccountIndexP */ CanonicalGameplayAccountMemberRepairOperation beginAccountMemberRepair(UUID transitionId) { Objects.requireNonNull(transitionId, "transitionId"); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger inventoryRevision = lockInventoryRevision(transaction); - CanonicalGameplayBindingProvisionalCasEvidence evidence = - loadProvisionalCasEvidence(transaction, transitionId, true); - UUID accountId = evidence.candidate().identity().accountId(); - AccountCoverageControl control = - lockExistingAccountCoverageControl(transaction, accountId); - requireNoActiveAccountControl(control); - if (!control.evidence().equals(evidence.transition().accountCoverageEvidence())) { - throw conflict( - "Binding transition did not retain the current positively read account-control state"); - } - readVerifiedLegacyDisposition(transaction, inventoryRevision, true); - requireOrdinaryNewMemberRepairTransition(evidence); - - Record existing = findMemberRepairOperation(transaction, transitionId, true); - if (existing != null) { - CanonicalGameplayAccountMemberRepairOperation operation = - toMemberRepairOperation(existing); - if (!operation.accountControlEpoch().equals(control.epoch())) { - throw conflict("The account-wide control fence advanced after member repair began"); - } - CanonicalGameplayBindingAccountIndexObligation currentObligation = - loadAccountIndexObligations(transaction, transitionId, true).getFirst(); - boolean completed = "ACKNOWLEDGED".equals(existing.get("status", String.class)); - requireMemberRepairObligationCurrent( - operation, evidence.candidate(), currentObligation, completed); - if (completed) { - toMemberAcknowledgement(existing); - } - return operation; - } + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger inventoryRevision = lockInventoryRevision(transaction); + CanonicalGameplayBindingProvisionalCasEvidence evidence = + loadProvisionalCasEvidence(transaction, transitionId, true); + UUID accountId = evidence.candidate().identity().accountId(); + AccountCoverageControl control = lockExistingAccountCoverageControl(transaction, accountId); + requireNoActiveAccountControl(control); + if (!control.evidence().equals(evidence.transition().accountCoverageEvidence())) { + throw conflict( + "Binding transition did not retain the current positively read account-control state"); + } + readVerifiedLegacyDisposition(transaction, inventoryRevision, true); + requireOrdinaryNewMemberRepairTransition(evidence); + + Record existing = findMemberRepairOperation(transaction, transitionId, true); + if (existing != null) { + CanonicalGameplayAccountMemberRepairOperation operation = toMemberRepairOperation(existing); + if (!operation.accountControlEpoch().equals(control.epoch())) { + throw conflict("The account-wide control fence advanced after member repair began"); + } + CanonicalGameplayBindingAccountIndexObligation currentObligation = + loadAccountIndexObligations(transaction, transitionId, true).getFirst(); + boolean completed = "ACKNOWLEDGED".equals(existing.get("status", String.class)); + requireMemberRepairObligationCurrent( + operation, evidence.candidate(), currentObligation, completed); + if (completed) { + toMemberAcknowledgement(existing); + } + return operation; + } - CanonicalGameplayBindingAccountIndexObligation originalObligation = - loadAccountIndexObligations(transaction, transitionId, true).getFirst(); - if (originalObligation.status() - != CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED - || evidence.candidate().accountIndexState() - != CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED) { - throw conflict( - "A new member repair requires the original unresolved account obligation"); - } + CanonicalGameplayBindingAccountIndexObligation originalObligation = + loadAccountIndexObligations(transaction, transitionId, true).getFirst(); + if (originalObligation.status() + != CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED + || evidence.candidate().accountIndexState() + != CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED) { + throw conflict("A new member repair requires the original unresolved account obligation"); + } - UUID operationId = freshOperationId(transitionId); - UUID coverageFence = - freshDistinctCoverageFence( - operationId, transitionId, evidence.candidate().accountIndexFence()); - BigInteger operationFence = allocateMemberRepairFence(transaction, accountId); - String member = CanonicalGameplayAccountIndexMember.of(evidence.candidate()).value(); - CanonicalGameplayAccountMemberRepairOperation operation = - new CanonicalGameplayAccountMemberRepairOperation( - transitionId, - operationId, - operationFence, - coverageFence, - inventoryRevision, - evidence.candidate().bindingRef(), - accountId, - evidence.candidate().identity().tenantId(), - evidence.candidate().bindingGeneration(), - evidence.candidate().accountIndexFence(), - originalObligation, - member, - control.epoch()); - insertMemberRepairOperation(transaction, operation); - return operation; - }); + UUID operationId = freshOperationId(transitionId); + UUID coverageFence = + freshDistinctCoverageFence( + operationId, transitionId, evidence.candidate().accountIndexFence()); + BigInteger operationFence = allocateMemberRepairFence(transaction, accountId); + String member = CanonicalGameplayAccountIndexMember.of(evidence.candidate()).value(); + CanonicalGameplayAccountMemberRepairOperation operation = + new CanonicalGameplayAccountMemberRepairOperation( + transitionId, + operationId, + operationFence, + coverageFence, + inventoryRevision, + evidence.candidate().bindingRef(), + accountId, + evidence.candidate().identity().tenantId(), + evidence.candidate().bindingGeneration(), + evidence.candidate().accountIndexFence(), + originalObligation, + member, + control.epoch()); + insertMemberRepairOperation(transaction, operation); + return operation; + }); } /** @@ -2280,63 +2234,59 @@ CanonicalGameplayAccountMemberAcknowledgement acknowledgeAccountMemberRepair( if (!expected.equals(actual.operation()) || !expected.member().equals(actual.member())) { throw conflict("Redis readback is not bound to the exact expected member repair operation"); } - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger currentRevision = lockInventoryRevision(transaction); - lockLeaseBoundRuntimeBeforeTransition( - transaction, expected.transitionId(), expected.bindingRef().bytes(), null); - AccountCoverageControl control = - lockExistingAccountCoverageControl(transaction, expected.accountId()); - requireNoActiveAccountControl(control); - if (!control.epoch().equals(expected.accountControlEpoch())) { - throw conflict("The account-wide control fence changed during member repair"); - } - readVerifiedLegacyDisposition(transaction, currentRevision, true); - Record operationRow = - findMemberRepairOperation(transaction, expected.transitionId(), true); - if (operationRow == null) { - throw conflict("The exact durable account-member repair operation is missing"); - } - CanonicalGameplayAccountMemberRepairOperation stored = - toMemberRepairOperation(operationRow); - if (!stored.equals(expected) - || !stored.equals(actual.operation()) - || !stored.member().equals(actual.member())) { - throw conflict("Expected and actual member repair differ from the durable owner tuple"); - } - CanonicalGameplayBindingProvisionalCasEvidence current = - loadProvisionalCasEvidence(transaction, expected.transitionId(), true); - requireOrdinaryNewMemberRepairTransition(current); - CanonicalGameplayBindingAccountIndexObligation currentObligation = - loadAccountIndexObligations(transaction, expected.transitionId(), true).getFirst(); - boolean completed = "ACKNOWLEDGED".equals(operationRow.get("status", String.class)); - requireMemberRepairObligationCurrent( - stored, current.candidate(), currentObligation, completed); - if (!current.transition().accountCoverageEvidence().equals(control.evidence())) { - throw conflict( - "Transition account-wide state no longer matches the pinned control row"); - } - String exactMember = CanonicalGameplayAccountIndexMember.of(current.candidate()).value(); - if (!exactMember.equals(actual.member())) { - throw conflict("Redis readback member differs from the exact durable candidate tuple"); - } - if (completed) { - return toMemberAcknowledgement(operationRow); - } + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger currentRevision = lockInventoryRevision(transaction); + lockLeaseBoundRuntimeBeforeTransition( + transaction, expected.transitionId(), expected.bindingRef().bytes(), null); + AccountCoverageControl control = + lockExistingAccountCoverageControl(transaction, expected.accountId()); + requireNoActiveAccountControl(control); + if (!control.epoch().equals(expected.accountControlEpoch())) { + throw conflict("The account-wide control fence changed during member repair"); + } + readVerifiedLegacyDisposition(transaction, currentRevision, true); + Record operationRow = findMemberRepairOperation(transaction, expected.transitionId(), true); + if (operationRow == null) { + throw conflict("The exact durable account-member repair operation is missing"); + } + CanonicalGameplayAccountMemberRepairOperation stored = toMemberRepairOperation(operationRow); + if (!stored.equals(expected) + || !stored.equals(actual.operation()) + || !stored.member().equals(actual.member())) { + throw conflict("Expected and actual member repair differ from the durable owner tuple"); + } + CanonicalGameplayBindingProvisionalCasEvidence current = + loadProvisionalCasEvidence(transaction, expected.transitionId(), true); + requireOrdinaryNewMemberRepairTransition(current); + CanonicalGameplayBindingAccountIndexObligation currentObligation = + loadAccountIndexObligations(transaction, expected.transitionId(), true).getFirst(); + boolean completed = "ACKNOWLEDGED".equals(operationRow.get("status", String.class)); + requireMemberRepairObligationCurrent( + stored, current.candidate(), currentObligation, completed); + if (!current.transition().accountCoverageEvidence().equals(control.evidence())) { + throw conflict("Transition account-wide state no longer matches the pinned control row"); + } + String exactMember = CanonicalGameplayAccountIndexMember.of(current.candidate()).value(); + if (!exactMember.equals(actual.member())) { + throw conflict("Redis readback member differs from the exact durable candidate tuple"); + } + if (completed) { + return toMemberAcknowledgement(operationRow); + } - BigInteger nextRevision = currentRevision.add(BigInteger.ONE); - BigInteger coverageGeneration = - allocateMemberRepairCoverageGeneration( - transaction, stored.accountId(), stored.inventorySnapshotRevision()); - if (coverageGeneration.compareTo(stored.inventorySnapshotRevision()) <= 0) { - throw conflict("Binding-local evidence generation must advance beyond its snapshot"); - } - persistMemberRepairAcknowledgement( - transaction, stored, current, nextRevision, coverageGeneration, actual.member()); - return new CanonicalGameplayAccountMemberAcknowledgement( - stored, coverageGeneration, actual.member()); - }); + BigInteger nextRevision = currentRevision.add(BigInteger.ONE); + BigInteger coverageGeneration = + allocateMemberRepairCoverageGeneration( + transaction, stored.accountId(), stored.inventorySnapshotRevision()); + if (coverageGeneration.compareTo(stored.inventorySnapshotRevision()) <= 0) { + throw conflict("Binding-local evidence generation must advance beyond its snapshot"); + } + persistMemberRepairAcknowledgement( + transaction, stored, current, nextRevision, coverageGeneration, actual.member()); + return new CanonicalGameplayAccountMemberAcknowledgement( + stored, coverageGeneration, actual.member()); + }); } /** @@ -2368,203 +2318,197 @@ private CanonicalGameplayBindingTransitionSnapshot markProvisional( if ((candidate == null) != (readback == null)) { throw new IllegalArgumentException("Candidate and owner readback must be supplied together"); } - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger currentRevision = lockInventoryRevision(transaction); - if (expectedDecision != null) { - lockLeaseBoundRuntimeBeforeTransition( - transaction, - expectedEvidence.transition().transitionId(), - expectedEvidence.candidate().bindingRef().bytes(), - expectedDecision.targetEvidence()); - } - CanonicalGameplayBindingProvisionalCasEvidence current = - loadProvisionalCasEvidence( - transaction, expectedEvidence.transition().transitionId(), true); - requireAccountCoverageEvidenceCurrent( - transaction, - current.candidate().identity().accountId(), - current.transition().accountCoverageEvidence()); - requireSameProvisionalOperation(expectedEvidence, current); - if (current.expectedPrior() == null && expectedDecision == null) { - throw conflict( - "First-binding provisional publication requires the exact Account lease decision"); - } - boolean originalNew = current.expectedPrior() == null && expectedDecision != null; - if (originalNew - && candidate == null - && findTransition(transaction, current.transition().transitionId()) - .get("original_new_candidate_bytes", byte[].class) - != null) { - throw conflict( - "Claimed original NEW candidate requires owner-produced physical readback"); - } - if (originalNew && candidate != null) { - if (readback == null) throw conflict("Original NEW readback source is unavailable"); - requireDecisionMatchesOperation(expectedDecision, current); - CanonicalGameplayOriginalNewCandidate actualCandidate; - try { - actualCandidate = - CanonicalGameplayOriginalNewCandidate.fromOriginalSources( - current, expectedDecision); - } catch (RuntimeException invalidSource) { - throw conflict("Original NEW candidate sources are not exact"); - } - if (!actualCandidate.equals(candidate) - || !candidate.matchesOriginalDecision(expectedDecision) - || !candidate.matchesProvisionalSources(current) - || !readback.matches(candidate, current)) { - throw conflict("Owner readback does not bind the exact original NEW source"); - } - Record installation = findTransition(transaction, current.transition().transitionId()); - byte[] storedCandidate = installation.get("original_new_candidate_bytes", byte[].class); - String storedCandidateDigest = - installation.get("original_new_candidate_digest", String.class); - String installationState = - installation.get("original_new_candidate_state", String.class); - String storedReadbackDigest = - installation.get("original_new_candidate_readback_digest", String.class); - if (storedCandidate == null - || !Arrays.equals(storedCandidate, candidate.canonicalBytes()) - || !Objects.equals( - storedCandidateDigest, - CanonicalGameplayIssuerMemberV2Codec.sha256(storedCandidate))) { - throw conflict("Original NEW candidate bytes differ from the retained SQL source"); - } - if ("READBACK_CONFIRMED".equals(installationState)) { - if (!Objects.equals(storedReadbackDigest, readback.digest())) { - throw conflict("Original NEW candidate has a different retained physical readback"); - } - } else if ("DISPATCH_POSSIBLE".equals(installationState) - && current.transition().status() - == CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED) { - requireOne( - transaction.execute( - "UPDATE " - + TRANSITION - + " SET original_new_candidate_state = 'READBACK_CONFIRMED'," - + " original_new_candidate_readback_digest = ?" - + " WHERE transition_id = ? AND status = 'PREPARED'" - + " AND original_new_candidate_bytes = ?" - + " AND original_new_candidate_digest = ?" - + " AND original_new_candidate_state = 'DISPATCH_POSSIBLE'" - + " AND original_new_candidate_readback_digest IS NULL", - readback.digest(), - current.transition().transitionId(), - candidate.canonicalBytes(), - storedCandidateDigest), - "Original NEW candidate readback source changed before provisional CAS"); - } else { - throw conflict("Original NEW candidate is not in a readback-confirmable state"); - } - } else if (candidate != null || readback != null) { - throw conflict("Original NEW candidate readback cannot authorize a transfer"); - } - if (current.transition().status() - == CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) { - Record row = findTransition(transaction, current.transition().transitionId()); - if (expectedDecision == null) { - if (row.get("admission_lease_id", UUID.class) != null) { - throw conflict("A lease-bound decision cannot be retried through legacy publish"); - } - } else { - CanonicalGameplayAdmissionDecision stored = toAdmissionDecision(row, current); - requireSameAdmissionDecision(expectedDecision, stored); - } - return current.transition(); - } - if (current.transition().status() - != CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED) { - throw conflict("Only the exact PREPARED operation can become PROVISIONAL"); - } - - BigInteger priorRevision = current.transition().inventoryRevision(); - BigInteger nextRevision = currentRevision.add(BigInteger.ONE); - if (expectedDecision != null) { - requireDecisionMatchesOperation(expectedDecision, current); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger currentRevision = lockInventoryRevision(transaction); + if (expectedDecision != null) { + lockLeaseBoundRuntimeBeforeTransition( + transaction, + expectedEvidence.transition().transitionId(), + expectedEvidence.candidate().bindingRef().bytes(), + expectedDecision.targetEvidence()); + } + CanonicalGameplayBindingProvisionalCasEvidence current = + loadProvisionalCasEvidence( + transaction, expectedEvidence.transition().transitionId(), true); + requireAccountCoverageEvidenceCurrent( + transaction, + current.candidate().identity().accountId(), + current.transition().accountCoverageEvidence()); + requireSameProvisionalOperation(expectedEvidence, current); + if (current.expectedPrior() == null && expectedDecision == null) { + throw conflict( + "First-binding provisional publication requires the exact Account lease decision"); + } + boolean originalNew = current.expectedPrior() == null && expectedDecision != null; + if (originalNew + && candidate == null + && findTransition(transaction, current.transition().transitionId()) + .get("original_new_candidate_bytes", byte[].class) + != null) { + throw conflict("Claimed original NEW candidate requires owner-produced physical readback"); + } + if (originalNew && candidate != null) { + if (readback == null) throw conflict("Original NEW readback source is unavailable"); + requireDecisionMatchesOperation(expectedDecision, current); + CanonicalGameplayOriginalNewCandidate actualCandidate; + try { + actualCandidate = + CanonicalGameplayOriginalNewCandidate.fromOriginalSources(current, expectedDecision); + } catch (RuntimeException invalidSource) { + throw conflict("Original NEW candidate sources are not exact"); + } + if (!actualCandidate.equals(candidate) + || !candidate.matchesOriginalDecision(expectedDecision) + || !candidate.matchesProvisionalSources(current) + || !readback.matches(candidate, current)) { + throw conflict("Owner readback does not bind the exact original NEW source"); + } + Record installation = findTransition(transaction, current.transition().transitionId()); + byte[] storedCandidate = installation.get("original_new_candidate_bytes", byte[].class); + String storedCandidateDigest = + installation.get("original_new_candidate_digest", String.class); + String installationState = installation.get("original_new_candidate_state", String.class); + String storedReadbackDigest = + installation.get("original_new_candidate_readback_digest", String.class); + if (storedCandidate == null + || !Arrays.equals(storedCandidate, candidate.canonicalBytes()) + || !Objects.equals( + storedCandidateDigest, + CanonicalGameplayIssuerMemberV2Codec.sha256(storedCandidate))) { + throw conflict("Original NEW candidate bytes differ from the retained SQL source"); + } + if ("READBACK_CONFIRMED".equals(installationState)) { + if (!Objects.equals(storedReadbackDigest, readback.digest())) { + throw conflict("Original NEW candidate has a different retained physical readback"); } - int transitionChanged = - expectedDecision == null - ? updateLegacyProvisionalTransition( - transaction, current, priorRevision, nextRevision) - : updateLeaseBoundProvisionalTransition( - transaction, current, expectedDecision, priorRevision, nextRevision); + } else if ("DISPATCH_POSSIBLE".equals(installationState) + && current.transition().status() + == CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED) { requireOne( - transitionChanged, "Durable transition compare-and-set lost its exact prepared row"); - int candidateChanged = transaction.execute( "UPDATE " - + INVENTORY - + " SET lifecycle = 'PROVISIONAL', inventory_revision = ?" - + " WHERE binding_ref = ? AND transition_id = ?" - + " AND lifecycle = 'CANDIDATE_PREPARED'" - + " AND binding_generation = ? AND account_index_fence = ?" - + " AND account_index_state = 'REPAIR_REQUIRED'" - + " AND issuer_index_state = 'REPAIR_REQUIRED' AND inventory_revision = ?", - decimal(nextRevision), - current.candidate().bindingRef().bytes(), - current.transition().transitionId(), - decimal(current.transition().bindingGeneration()), - current.transition().candidateAccountIndexFence(), - decimal(priorRevision)); - requireOne( - candidateChanged, "Durable candidate compare-and-set lost its exact prepared row"); - requireCount( - transaction.execute( - "UPDATE " - + ACCOUNT_OBLIGATION - + " SET inventory_revision = ?" - + " WHERE transition_id = ? AND inventory_revision = ?", - decimal(nextRevision), - current.transition().transitionId(), - decimal(priorRevision)), - current.expectedPrior() == null ? 1 : 2, - "Durable account-index obligations changed during provisional publication"); - requireOne( - transaction.execute( - "UPDATE " - + ISSUER_OBLIGATION - + " SET inventory_revision = ?" - + " WHERE transition_id = ? AND inventory_revision = ?", - decimal(nextRevision), - current.transition().transitionId(), - decimal(priorRevision)), - "Durable issuer-index obligation changed during provisional publication"); - requireOne( - transaction.execute( - "UPDATE " - + REGION_OBLIGATION - + " SET inventory_revision = ?" - + " WHERE transition_id = ? AND inventory_revision = ?", - decimal(nextRevision), - current.transition().transitionId(), - decimal(priorRevision)), - "Durable region-bridge obligation changed during provisional publication"); - requireOne( - transaction.execute( - "UPDATE " - + RESERVATION - + " SET inventory_revision = ?" - + " WHERE reservation_id = ? AND transition_id = ?" - + " AND lifecycle = 'RESERVED' AND inventory_revision = ?", - decimal(nextRevision), - current.transition().issuerReservationId(), + + TRANSITION + + " SET original_new_candidate_state = 'READBACK_CONFIRMED'," + + " original_new_candidate_readback_digest = ?" + + " WHERE transition_id = ? AND status = 'PREPARED'" + + " AND original_new_candidate_bytes = ?" + + " AND original_new_candidate_digest = ?" + + " AND original_new_candidate_state = 'DISPATCH_POSSIBLE'" + + " AND original_new_candidate_readback_digest IS NULL", + readback.digest(), current.transition().transitionId(), - decimal(priorRevision)), - "Durable issuer reservation changed during provisional publication"); - requireOne( - transaction.execute( - "UPDATE game_session_canonical_binding_inventory_clock" - + " SET inventory_revision = ? WHERE singleton_id = 1" - + " AND inventory_revision = ?", - decimal(nextRevision), - decimal(currentRevision)), - "Durable inventory revision compare-and-set lost during provisional publication"); - return loadProvisionalCasEvidence( - transaction, expectedEvidence.transition().transitionId(), true) - .transition(); - }); + candidate.canonicalBytes(), + storedCandidateDigest), + "Original NEW candidate readback source changed before provisional CAS"); + } else { + throw conflict("Original NEW candidate is not in a readback-confirmable state"); + } + } else if (candidate != null || readback != null) { + throw conflict("Original NEW candidate readback cannot authorize a transfer"); + } + if (current.transition().status() + == CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL) { + Record row = findTransition(transaction, current.transition().transitionId()); + if (expectedDecision == null) { + if (row.get("admission_lease_id", UUID.class) != null) { + throw conflict("A lease-bound decision cannot be retried through legacy publish"); + } + } else { + CanonicalGameplayAdmissionDecision stored = toAdmissionDecision(row, current); + requireSameAdmissionDecision(expectedDecision, stored); + } + return current.transition(); + } + if (current.transition().status() + != CanonicalGameplayBindingTransitionSnapshot.Status.PREPARED) { + throw conflict("Only the exact PREPARED operation can become PROVISIONAL"); + } + + BigInteger priorRevision = current.transition().inventoryRevision(); + BigInteger nextRevision = currentRevision.add(BigInteger.ONE); + if (expectedDecision != null) { + requireDecisionMatchesOperation(expectedDecision, current); + } + int transitionChanged = + expectedDecision == null + ? updateLegacyProvisionalTransition(transaction, current, priorRevision, nextRevision) + : updateLeaseBoundProvisionalTransition( + transaction, current, expectedDecision, priorRevision, nextRevision); + requireOne( + transitionChanged, "Durable transition compare-and-set lost its exact prepared row"); + int candidateChanged = + transaction.execute( + "UPDATE " + + INVENTORY + + " SET lifecycle = 'PROVISIONAL', inventory_revision = ?" + + " WHERE binding_ref = ? AND transition_id = ?" + + " AND lifecycle = 'CANDIDATE_PREPARED'" + + " AND binding_generation = ? AND account_index_fence = ?" + + " AND account_index_state = 'REPAIR_REQUIRED'" + + " AND issuer_index_state = 'REPAIR_REQUIRED' AND inventory_revision = ?", + decimal(nextRevision), + current.candidate().bindingRef().bytes(), + current.transition().transitionId(), + decimal(current.transition().bindingGeneration()), + current.transition().candidateAccountIndexFence(), + decimal(priorRevision)); + requireOne(candidateChanged, "Durable candidate compare-and-set lost its exact prepared row"); + requireCount( + transaction.execute( + "UPDATE " + + ACCOUNT_OBLIGATION + + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND inventory_revision = ?", + decimal(nextRevision), + current.transition().transitionId(), + decimal(priorRevision)), + current.expectedPrior() == null ? 1 : 2, + "Durable account-index obligations changed during provisional publication"); + requireOne( + transaction.execute( + "UPDATE " + + ISSUER_OBLIGATION + + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND inventory_revision = ?", + decimal(nextRevision), + current.transition().transitionId(), + decimal(priorRevision)), + "Durable issuer-index obligation changed during provisional publication"); + requireOne( + transaction.execute( + "UPDATE " + + REGION_OBLIGATION + + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND inventory_revision = ?", + decimal(nextRevision), + current.transition().transitionId(), + decimal(priorRevision)), + "Durable region-bridge obligation changed during provisional publication"); + requireOne( + transaction.execute( + "UPDATE " + + RESERVATION + + " SET inventory_revision = ?" + + " WHERE reservation_id = ? AND transition_id = ?" + + " AND lifecycle = 'RESERVED' AND inventory_revision = ?", + decimal(nextRevision), + current.transition().issuerReservationId(), + current.transition().transitionId(), + decimal(priorRevision)), + "Durable issuer reservation changed during provisional publication"); + requireOne( + transaction.execute( + "UPDATE game_session_canonical_binding_inventory_clock" + + " SET inventory_revision = ? WHERE singleton_id = 1" + + " AND inventory_revision = ?", + decimal(nextRevision), + decimal(currentRevision)), + "Durable inventory revision compare-and-set lost during provisional publication"); + return loadProvisionalCasEvidence( + transaction, expectedEvidence.transition().transitionId(), true) + .transition(); + }); } /** @@ -2600,221 +2544,211 @@ CanonicalGameplayBindingTransitionSnapshot commitOriginalNewFinalAdmission( != actual.admissionAtMillis() + actual.canonicalSessionDurationMillis()) { throw conflict("Final controller readback differs from its authenticated original NEW"); } - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger revision = lockInventoryRevision(transaction); - requireNoActiveAccountControl( - lockExistingAccountCoverageControl( - transaction, candidate.bindingIdentity().accountId())); - String runtimeStatus = - lockLeaseBoundRuntimeBeforeTransition( - transaction, - candidate.transition().transitionId(), - candidate.bindingIdentity().bindingRef().bytes(), - candidate.targetEvidence()); - if (!"RUNNING".equals(runtimeStatus)) { - throw conflict( - "Original NEW final admission commit requires its current RUNNING runtime"); - } - Record row = - transaction.fetchOne( - "SELECT * FROM " + TRANSITION + " WHERE transition_id = ? FOR UPDATE", - candidate.transition().transitionId()); - if (row == null) throw conflict("Original NEW transition is missing"); - boolean committed = "COMMITTED".equals(row.get("status", String.class)); - if (!committed && !"PROVISIONAL".equals(row.get("status", String.class))) { - throw conflict("Only an exact provisional or committed original NEW can finalize"); - } - Record inventoryRow = - transaction.fetchOne( - "SELECT * FROM " + INVENTORY + " WHERE binding_ref = ? FOR UPDATE", - candidate.bindingIdentity().bindingRef().bytes()); - Record reservationRow = - transaction.fetchOne( - "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ? FOR UPDATE", - candidate.reservation().reservationId()); - if (inventoryRow == null || reservationRow == null) { - throw conflict("Original NEW candidate or reservation is missing"); - } - var entry = toInventoryEntry(inventoryRow); - var reservation = toReservation(reservationRow); - var transition = toTransitionSnapshot(row, inventoryRow, reservationRow); - var decision = toAdmissionDecision(row, transition, entry); - if (transition.expectedPriorBindingRef() != null - || transition.expectedPriorBindingGeneration() != null - || !candidate.matchesOriginalDecision(decision) - || !Arrays.equals( - row.get("candidate_binding_ref", byte[].class), - candidate.transition().bindingRef().bytes()) - || !transition.bindingGeneration().equals(candidate.transition().bindingGeneration()) - || !Objects.equals( - row.get("issuer_reservation_id", UUID.class), - candidate.transition().issuerReservationId()) - || !transition.reservationFence().equals(candidate.transition().reservationFence()) - || !transition - .candidateAccountIndexFence() - .equals(candidate.transition().candidateAccountIndexFence()) - || transition.inventoryRevision().compareTo(revision) > 0 - || !candidate.bindingIdentity().equals(entry.identity()) - || !candidate.transition().bindingGeneration().equals(entry.bindingGeneration()) - || !candidate.transition().transitionId().equals(entry.transitionId()) - || !candidate - .transition() - .candidateAccountIndexFence() - .equals(entry.accountIndexFence()) - || !candidate.transition().issuerReservationId().equals(entry.issuerReservationId()) - || !candidate - .reservation() - .equals(CanonicalGameplayOriginalNewCandidateCodec.reservationSource(reservation)) - || !reservation.owner().equals(entry.identity()) - || !entry.inventoryRevision().equals(transition.inventoryRevision()) - || !reservation.inventoryRevision().equals(transition.inventoryRevision()) - || entry.lifecycle() - != (committed - ? CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE - : CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL) - || reservation.lifecycle() - != (committed - ? CanonicalIssuerPartitionReservation.Lifecycle.BOUND - : CanonicalIssuerPartitionReservation.Lifecycle.RESERVED) - || entry.accountIndexState() - != CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED - || entry.issuerIndexState() - != (committed - ? CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED - : CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED) - || !"READBACK_CONFIRMED".equals(row.get("original_new_candidate_state", String.class)) - || !Arrays.equals( - candidate.canonicalBytes(), row.get("original_new_candidate_bytes", byte[].class)) - || !CanonicalGameplayIssuerMemberV2Codec.sha256(candidate.canonicalBytes()) - .equals(row.get("original_new_candidate_digest", String.class)) - || !source - .candidateDigest() - .equals(row.get("original_new_candidate_digest", String.class)) - || !source - .originalCandidateReadbackDigest() - .equals(row.get("original_new_candidate_readback_digest", String.class)) - || (source.transitionStatus() - == CanonicalGameplayBindingTransitionSnapshot.Status.COMMITTED - && !committed) - || BigInteger.valueOf(actual.admissionAtMillis()) - .compareTo(decision.leaseExpiresAtEpochMillis()) - >= 0) { - throw conflict("Final controller source differs from the retained original NEW"); - } - if (!committed) { - var evidence = loadProvisionalCasEvidence(transaction, transition.transitionId(), true); - if (!candidate.matchesProvisionalSources(evidence)) { - throw conflict("Final readback lost its exact provisional source"); - } - } - var obligations = - loadAccountIndexObligations(transaction, transition.transitionId(), true); - if (obligations.size() != 1) - throw conflict("Original NEW account obligation is not exact"); - requireCompletedMemberRepairAcknowledgement( - transaction, transition, entry, obligations.getFirst()); - CanonicalGameplayIssuerBindingLocalAcknowledgement issuerAcknowledgement = - requireOriginalNewFinalIssuerAcknowledgement( - transaction, candidate, transition, committed); - if (!Arrays.equals( - source.issuerAcknowledgement().exactBytes(), issuerAcknowledgement.exactBytes())) { - throw conflict( - "Final issuer acknowledgement differs from the retained original source"); - } - requireOriginalNewFinalRegionAcknowledgement(transaction, candidate, transition, entry); - if (committed) { - requireOriginalNewFinalReceipt(row, actual, decision); - return transition; - } - requireNoOriginalNewFinalAdmissionReceipt(row); - BigInteger next = revision.add(BigInteger.ONE); - BigDecimal prior = decimal(transition.inventoryRevision()); - requireOne( - transaction.execute( - "UPDATE " - + TRANSITION - + " SET status = 'COMMITTED', inventory_revision = ?," - + " original_new_final_session_sha256 = ?, original_new_admission_at_ms = ?," - + " original_new_continuity_expires_at_ms = ?, original_new_session_duration_ms = ?" - + " WHERE transition_id = ? AND status = 'PROVISIONAL' AND inventory_revision = ?", - decimal(next), - actual.finalSessionSha256(), - actual.admissionAtMillis(), - actual.continuityExpiresAtMillis(), - actual.canonicalSessionDurationMillis(), - transition.transitionId(), - prior), - "Original NEW final transition CAS changed"); - requireOne( - transaction.execute( - "UPDATE " - + INVENTORY - + " SET lifecycle = 'ACTIVE', issuer_index_state = 'ACKNOWLEDGED', inventory_revision = ?" - + " WHERE binding_ref = ? AND transition_id = ? AND lifecycle = 'PROVISIONAL'" - + " AND account_index_state = 'ACKNOWLEDGED' AND issuer_index_state = 'REPAIR_REQUIRED'" - + " AND inventory_revision = ?", - decimal(next), - entry.bindingRef().bytes(), - transition.transitionId(), - prior), - "Original NEW final inventory CAS changed"); - requireOne( - transaction.execute( - "UPDATE " - + ACCOUNT_OBLIGATION - + " SET inventory_revision = ?" - + " WHERE transition_id = ? AND obligation_ordinal = 0 AND status = 'ACKNOWLEDGED'" - + " AND inventory_revision = ?", - decimal(next), - transition.transitionId(), - prior), - "Original NEW account receipt changed"); - requireOne( - transaction.execute( - "UPDATE " - + ISSUER_OBLIGATION - + " SET status = 'ACKNOWLEDGED', inventory_revision = ?" - + " WHERE transition_id = ? AND status = 'REQUIRED' AND inventory_revision = ?", - decimal(next), - transition.transitionId(), - prior), - "Original NEW issuer receipt changed"); - requireOne( - transaction.execute( - "UPDATE " - + REGION_OBLIGATION - + " SET inventory_revision = ?" - + " WHERE transition_id = ? AND status = 'ACKNOWLEDGED' AND inventory_revision = ?", - decimal(next), - transition.transitionId(), - prior), - "Original NEW region receipt changed"); - requireOne( - transaction.execute( - "UPDATE " - + RESERVATION - + " SET lifecycle = 'BOUND', inventory_revision = ?" - + " WHERE reservation_id = ? AND transition_id = ? AND lifecycle = 'RESERVED'" - + " AND inventory_revision = ?", - decimal(next), - reservation.reservationId(), - transition.transitionId(), - prior), - "Original NEW reservation CAS changed"); - bumpInventoryClock(transaction, revision, next); - return toTransitionSnapshot( - Objects.requireNonNull( - findTransition(transaction, transition.transitionId()), - "Committed original NEW transition must remain present"), - transaction.fetchSingle( - "SELECT * FROM " + INVENTORY + " WHERE binding_ref = ?", - entry.bindingRef().bytes()), - transaction.fetchSingle( - "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ?", - reservation.reservationId())); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger revision = lockInventoryRevision(transaction); + requireNoActiveAccountControl( + lockExistingAccountCoverageControl(transaction, candidate.bindingIdentity().accountId())); + String runtimeStatus = + lockLeaseBoundRuntimeBeforeTransition( + transaction, + candidate.transition().transitionId(), + candidate.bindingIdentity().bindingRef().bytes(), + candidate.targetEvidence()); + if (!"RUNNING".equals(runtimeStatus)) { + throw conflict("Original NEW final admission commit requires its current RUNNING runtime"); + } + Record row = + transaction.fetchOne( + "SELECT * FROM " + TRANSITION + " WHERE transition_id = ? FOR UPDATE", + candidate.transition().transitionId()); + if (row == null) throw conflict("Original NEW transition is missing"); + boolean committed = "COMMITTED".equals(row.get("status", String.class)); + if (!committed && !"PROVISIONAL".equals(row.get("status", String.class))) { + throw conflict("Only an exact provisional or committed original NEW can finalize"); + } + Record inventoryRow = + transaction.fetchOne( + "SELECT * FROM " + INVENTORY + " WHERE binding_ref = ? FOR UPDATE", + candidate.bindingIdentity().bindingRef().bytes()); + Record reservationRow = + transaction.fetchOne( + "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ? FOR UPDATE", + candidate.reservation().reservationId()); + if (inventoryRow == null || reservationRow == null) { + throw conflict("Original NEW candidate or reservation is missing"); + } + var entry = toInventoryEntry(inventoryRow); + var reservation = toReservation(reservationRow); + var transition = toTransitionSnapshot(row, inventoryRow, reservationRow); + var decision = toAdmissionDecision(row, transition, entry); + if (transition.expectedPriorBindingRef() != null + || transition.expectedPriorBindingGeneration() != null + || !candidate.matchesOriginalDecision(decision) + || !Arrays.equals( + row.get("candidate_binding_ref", byte[].class), + candidate.transition().bindingRef().bytes()) + || !transition.bindingGeneration().equals(candidate.transition().bindingGeneration()) + || !Objects.equals( + row.get("issuer_reservation_id", UUID.class), + candidate.transition().issuerReservationId()) + || !transition.reservationFence().equals(candidate.transition().reservationFence()) + || !transition + .candidateAccountIndexFence() + .equals(candidate.transition().candidateAccountIndexFence()) + || transition.inventoryRevision().compareTo(revision) > 0 + || !candidate.bindingIdentity().equals(entry.identity()) + || !candidate.transition().bindingGeneration().equals(entry.bindingGeneration()) + || !candidate.transition().transitionId().equals(entry.transitionId()) + || !candidate.transition().candidateAccountIndexFence().equals(entry.accountIndexFence()) + || !candidate.transition().issuerReservationId().equals(entry.issuerReservationId()) + || !candidate + .reservation() + .equals(CanonicalGameplayOriginalNewCandidateCodec.reservationSource(reservation)) + || !reservation.owner().equals(entry.identity()) + || !entry.inventoryRevision().equals(transition.inventoryRevision()) + || !reservation.inventoryRevision().equals(transition.inventoryRevision()) + || entry.lifecycle() + != (committed + ? CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE + : CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL) + || reservation.lifecycle() + != (committed + ? CanonicalIssuerPartitionReservation.Lifecycle.BOUND + : CanonicalIssuerPartitionReservation.Lifecycle.RESERVED) + || entry.accountIndexState() + != CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED + || entry.issuerIndexState() + != (committed + ? CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED + : CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED) + || !"READBACK_CONFIRMED".equals(row.get("original_new_candidate_state", String.class)) + || !Arrays.equals( + candidate.canonicalBytes(), row.get("original_new_candidate_bytes", byte[].class)) + || !CanonicalGameplayIssuerMemberV2Codec.sha256(candidate.canonicalBytes()) + .equals(row.get("original_new_candidate_digest", String.class)) + || !source + .candidateDigest() + .equals(row.get("original_new_candidate_digest", String.class)) + || !source + .originalCandidateReadbackDigest() + .equals(row.get("original_new_candidate_readback_digest", String.class)) + || (source.transitionStatus() + == CanonicalGameplayBindingTransitionSnapshot.Status.COMMITTED + && !committed) + || BigInteger.valueOf(actual.admissionAtMillis()) + .compareTo(decision.leaseExpiresAtEpochMillis()) + >= 0) { + throw conflict("Final controller source differs from the retained original NEW"); + } + if (!committed) { + var evidence = loadProvisionalCasEvidence(transaction, transition.transitionId(), true); + if (!candidate.matchesProvisionalSources(evidence)) { + throw conflict("Final readback lost its exact provisional source"); + } + } + var obligations = loadAccountIndexObligations(transaction, transition.transitionId(), true); + if (obligations.size() != 1) throw conflict("Original NEW account obligation is not exact"); + requireCompletedMemberRepairAcknowledgement( + transaction, transition, entry, obligations.getFirst()); + CanonicalGameplayIssuerBindingLocalAcknowledgement issuerAcknowledgement = + requireOriginalNewFinalIssuerAcknowledgement( + transaction, candidate, transition, committed); + if (!Arrays.equals( + source.issuerAcknowledgement().exactBytes(), issuerAcknowledgement.exactBytes())) { + throw conflict("Final issuer acknowledgement differs from the retained original source"); + } + requireOriginalNewFinalRegionAcknowledgement(transaction, candidate, transition, entry); + if (committed) { + requireOriginalNewFinalReceipt(row, actual, decision); + return transition; + } + requireNoOriginalNewFinalAdmissionReceipt(row); + BigInteger next = revision.add(BigInteger.ONE); + BigDecimal prior = decimal(transition.inventoryRevision()); + requireOne( + transaction.execute( + "UPDATE " + + TRANSITION + + " SET status = 'COMMITTED', inventory_revision = ?," + + " original_new_final_session_sha256 = ?, original_new_admission_at_ms = ?," + + " original_new_continuity_expires_at_ms = ?, original_new_session_duration_ms = ?" + + " WHERE transition_id = ? AND status = 'PROVISIONAL' AND inventory_revision = ?", + decimal(next), + actual.finalSessionSha256(), + actual.admissionAtMillis(), + actual.continuityExpiresAtMillis(), + actual.canonicalSessionDurationMillis(), + transition.transitionId(), + prior), + "Original NEW final transition CAS changed"); + requireOne( + transaction.execute( + "UPDATE " + + INVENTORY + + " SET lifecycle = 'ACTIVE', issuer_index_state = 'ACKNOWLEDGED', inventory_revision = ?" + + " WHERE binding_ref = ? AND transition_id = ? AND lifecycle = 'PROVISIONAL'" + + " AND account_index_state = 'ACKNOWLEDGED' AND issuer_index_state = 'REPAIR_REQUIRED'" + + " AND inventory_revision = ?", + decimal(next), + entry.bindingRef().bytes(), + transition.transitionId(), + prior), + "Original NEW final inventory CAS changed"); + requireOne( + transaction.execute( + "UPDATE " + + ACCOUNT_OBLIGATION + + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND obligation_ordinal = 0 AND status = 'ACKNOWLEDGED'" + + " AND inventory_revision = ?", + decimal(next), + transition.transitionId(), + prior), + "Original NEW account receipt changed"); + requireOne( + transaction.execute( + "UPDATE " + + ISSUER_OBLIGATION + + " SET status = 'ACKNOWLEDGED', inventory_revision = ?" + + " WHERE transition_id = ? AND status = 'REQUIRED' AND inventory_revision = ?", + decimal(next), + transition.transitionId(), + prior), + "Original NEW issuer receipt changed"); + requireOne( + transaction.execute( + "UPDATE " + + REGION_OBLIGATION + + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND status = 'ACKNOWLEDGED' AND inventory_revision = ?", + decimal(next), + transition.transitionId(), + prior), + "Original NEW region receipt changed"); + requireOne( + transaction.execute( + "UPDATE " + + RESERVATION + + " SET lifecycle = 'BOUND', inventory_revision = ?" + + " WHERE reservation_id = ? AND transition_id = ? AND lifecycle = 'RESERVED'" + + " AND inventory_revision = ?", + decimal(next), + reservation.reservationId(), + transition.transitionId(), + prior), + "Original NEW reservation CAS changed"); + bumpInventoryClock(transaction, revision, next); + return toTransitionSnapshot( + Objects.requireNonNull( + findTransition(transaction, transition.transitionId()), + "Committed original NEW transition must remain present"), + transaction.fetchSingle( + "SELECT * FROM " + INVENTORY + " WHERE binding_ref = ?", entry.bindingRef().bytes()), + transaction.fetchSingle( + "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ?", + reservation.reservationId())); + }); } private static void requireOriginalNewFinalReceipt( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java index 9d83b6dca5..f7ed657332 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java @@ -60,75 +60,72 @@ final class CanonicalGameplayIssuerAdmissionBarrierRepository CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState before = readCurrentState(); PreparedInitializerSource source = - dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - if (requestAssignment != null) { - requireCurrentTagMapping( - transaction, - requestAssignment.tenantId(), - requestAssignment.tenantGameplayTag()); - } - CanonicalGameplayIssuerInstalledAnchor anchor = - CanonicalGameplayIssuerBootstrapCoverageRepository - .readInstalledAnchorForBindingPreparationInTransaction(transaction, before); - CanonicalGameplayIssuerAdmissionControlValue control = - CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( - transaction, anchor, before); - Record byOperation = - transaction.fetchOne( - "SELECT * FROM " - + INITIALIZER - + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", - operationId, - ISSUER); - if (byOperation != null) { - CanonicalGameplayIssuerAdmissionBarrierValue frozen = - readFrozenInitializer(transaction, byOperation, null, anchor, control, before); - if (requestAssignment != null) { - requireSameTargetAssignment(requestAssignment, frozen.initializer()); - } - return new PreparedInitializerSource(frozen, null); - } - if (requestAssignment == null) { - throw conflict("The exact original tenant initializer disappeared"); - } - - CurrentRequestTarget requestTarget = - requireCurrentRequestTarget(transaction, operationId, requestAssignment, before); - Record targetInitializer = - transaction.fetchOne( - "SELECT * FROM " - + INITIALIZER - + " WHERE issuer_id = ? AND tenant_id = ?" - + " AND playable_state_namespace_id = ? AND live_barrier_epoch = ?" - + " FOR UPDATE", - ISSUER, - requestAssignment.tenantId(), - requestAssignment.playableStateNamespaceId(), - control.liveBarrierEpoch()); - if (targetInitializer != null) { - CanonicalGameplayIssuerAdmissionBarrierValue frozen = - readFrozenInitializer( - transaction, targetInitializer, requestAssignment, anchor, control, before); - return new PreparedInitializerSource(frozen, requestAssignment); - } - - CanonicalGameplayAdmissionBarrierTuple tuple = - buildOriginalInitializer( - transaction, - operationId, - requestTarget, - requestAssignment, - anchor, - control, - before); - CanonicalGameplayIssuerAdmissionBarrierValue original = - CanonicalGameplayIssuerAdmissionBarrierValue.open(tuple.initializer()); - persistOriginalInitializer(transaction, original); - return new PreparedInitializerSource(original, requestAssignment); - }); + dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + if (requestAssignment != null) { + requireCurrentTagMapping( + transaction, requestAssignment.tenantId(), requestAssignment.tenantGameplayTag()); + } + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, before); + CanonicalGameplayIssuerAdmissionControlValue control = + CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( + transaction, anchor, before); + Record byOperation = + transaction.fetchOne( + "SELECT * FROM " + + INITIALIZER + + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + operationId, + ISSUER); + if (byOperation != null) { + CanonicalGameplayIssuerAdmissionBarrierValue frozen = + readFrozenInitializer(transaction, byOperation, null, anchor, control, before); + if (requestAssignment != null) { + requireSameTargetAssignment(requestAssignment, frozen.initializer()); + } + return new PreparedInitializerSource(frozen, null); + } + if (requestAssignment == null) { + throw conflict("The exact original tenant initializer disappeared"); + } + + CurrentRequestTarget requestTarget = + requireCurrentRequestTarget(transaction, operationId, requestAssignment, before); + Record targetInitializer = + transaction.fetchOne( + "SELECT * FROM " + + INITIALIZER + + " WHERE issuer_id = ? AND tenant_id = ?" + + " AND playable_state_namespace_id = ? AND live_barrier_epoch = ?" + + " FOR UPDATE", + ISSUER, + requestAssignment.tenantId(), + requestAssignment.playableStateNamespaceId(), + control.liveBarrierEpoch()); + if (targetInitializer != null) { + CanonicalGameplayIssuerAdmissionBarrierValue frozen = + readFrozenInitializer( + transaction, targetInitializer, requestAssignment, anchor, control, before); + return new PreparedInitializerSource(frozen, requestAssignment); + } + + CanonicalGameplayAdmissionBarrierTuple tuple = + buildOriginalInitializer( + transaction, + operationId, + requestTarget, + requestAssignment, + anchor, + control, + before); + CanonicalGameplayIssuerAdmissionBarrierValue original = + CanonicalGameplayIssuerAdmissionBarrierValue.open(tuple.initializer()); + persistOriginalInitializer(transaction, original); + return new PreparedInitializerSource(original, requestAssignment); + }); CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = readCurrentState(); CanonicalGameplayIssuerAdmissionBarrierValue value = source.value(); @@ -205,56 +202,54 @@ CanonicalGameplayIssuerAdmissionControlValue completeCutoff(UUID operationId) { requireNoAmbientTransaction(); CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = readCurrentState(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - CanonicalGameplayIssuerInstalledAnchor anchor = - CanonicalGameplayIssuerBootstrapCoverageRepository - .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); - CanonicalGameplayIssuerAdmissionControlValue control = - readCurrentControl(transaction, anchor, current); - if (!cutoffOperationId.equals(control.currentOperationId()) - || control.state() - != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING) { - throw conflict("The exact current issuer cutoff is not pending"); - } - new CanonicalGameplayIssuerAdmissionControlRepository(dsl) - .verifyCurrentCutoffTarget(transaction, control, tenantId, namespaceId, null); - Record target = - transaction.fetchOne( - "SELECT * FROM " - + CUTOFF_TARGET - + " WHERE operation_id = ? AND issuer_id = ? AND tenant_id = ?" - + " AND playable_state_namespace_id = ? FOR UPDATE", - cutoffOperationId, - ISSUER, - tenantId, - namespaceId); - if (target == null - || !tenantId.equals(requiredUuid(target, "tenant_id")) - || !namespaceId.equals(requiredUuid(target, "playable_state_namespace_id"))) { - throw conflict("The exact durable cutoff target is unavailable"); - } - String tenantTag = requireText(target, "tenant_gameplay_tag"); - requireCurrentTagMapping(transaction, tenantId, tenantTag); - CanonicalGameplayIssuerAdmissionBarrierValue closed = - CanonicalGameplayIssuerAdmissionBarrierValue.decode( - requireBytes(target, "closed_payload_bytes")); - byte[] capturedOpen = target.get("captured_open_payload_bytes", byte[].class); - CanonicalGameplayIssuerAdmissionBarrierValue expectedOpen = - capturedOpen == null - ? null - : CanonicalGameplayIssuerAdmissionBarrierValue.decode(capturedOpen); - if (!closed.exactDigest().equals(target.get("closed_payload_digest", String.class))) { - throw conflict("Persisted issuer cutoff target digest is invalid"); - } - return new CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget( - closed, - expectedOpen, - CanonicalGameplayIssuerAdmissionBarrierKey.forTarget( - ISSUER, tenantId, namespaceId, tenantTag)); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + CanonicalGameplayIssuerAdmissionControlValue control = + readCurrentControl(transaction, anchor, current); + if (!cutoffOperationId.equals(control.currentOperationId()) + || control.state() != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING) { + throw conflict("The exact current issuer cutoff is not pending"); + } + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .verifyCurrentCutoffTarget(transaction, control, tenantId, namespaceId, null); + Record target = + transaction.fetchOne( + "SELECT * FROM " + + CUTOFF_TARGET + + " WHERE operation_id = ? AND issuer_id = ? AND tenant_id = ?" + + " AND playable_state_namespace_id = ? FOR UPDATE", + cutoffOperationId, + ISSUER, + tenantId, + namespaceId); + if (target == null + || !tenantId.equals(requiredUuid(target, "tenant_id")) + || !namespaceId.equals(requiredUuid(target, "playable_state_namespace_id"))) { + throw conflict("The exact durable cutoff target is unavailable"); + } + String tenantTag = requireText(target, "tenant_gameplay_tag"); + requireCurrentTagMapping(transaction, tenantId, tenantTag); + CanonicalGameplayIssuerAdmissionBarrierValue closed = + CanonicalGameplayIssuerAdmissionBarrierValue.decode( + requireBytes(target, "closed_payload_bytes")); + byte[] capturedOpen = target.get("captured_open_payload_bytes", byte[].class); + CanonicalGameplayIssuerAdmissionBarrierValue expectedOpen = + capturedOpen == null + ? null + : CanonicalGameplayIssuerAdmissionBarrierValue.decode(capturedOpen); + if (!closed.exactDigest().equals(target.get("closed_payload_digest", String.class))) { + throw conflict("Persisted issuer cutoff target digest is invalid"); + } + return new CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget( + closed, + expectedOpen, + CanonicalGameplayIssuerAdmissionBarrierKey.forTarget( + ISSUER, tenantId, namespaceId, tenantTag)); + }); } @Override @@ -274,37 +269,35 @@ public void requireStillCurrent( ? null : tenantTags.assignmentForTransition(prepared.assignment().transitionId()); if (assignment != null) requireSameAssignment(prepared.assignment(), assignment); - dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - CanonicalGameplayIssuerInstalledAnchor anchor = - CanonicalGameplayIssuerBootstrapCoverageRepository - .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); - CanonicalGameplayIssuerAdmissionControlValue control = - CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( - transaction, anchor, current); - if (!control.liveBarrierEpoch().equals(initializer.admissionEpoch()) - || !control.currentOperationId().equals(anchor.bootstrapOperationId())) { - throw conflict("Original initializer no longer belongs to current OPEN live control"); - } - if (assignment != null) { - requireCurrentTagMapping( - transaction, assignment.tenantId(), assignment.tenantGameplayTag()); - requireCurrentRequestTarget( - transaction, prepared.requestOperationId(), assignment, current); - } - Record saved = - transaction.fetchOne( - "SELECT * FROM " - + INITIALIZER - + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", - initializer.operationId(), - ISSUER); - readFrozenInitializer( - transaction, saved, prepared.assignment(), anchor, control, current); - return null; - }); + dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + CanonicalGameplayIssuerAdmissionControlValue control = + CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( + transaction, anchor, current); + if (!control.liveBarrierEpoch().equals(initializer.admissionEpoch()) + || !control.currentOperationId().equals(anchor.bootstrapOperationId())) { + throw conflict("Original initializer no longer belongs to current OPEN live control"); + } + if (assignment != null) { + requireCurrentTagMapping( + transaction, assignment.tenantId(), assignment.tenantGameplayTag()); + requireCurrentRequestTarget( + transaction, prepared.requestOperationId(), assignment, current); + } + Record saved = + transaction.fetchOne( + "SELECT * FROM " + + INITIALIZER + + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + initializer.operationId(), + ISSUER); + readFrozenInitializer(transaction, saved, prepared.assignment(), anchor, control, current); + return null; + }); } @Override @@ -315,30 +308,29 @@ public void requireStillCurrent( CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = readCurrentState(); CanonicalGameplayIssuerAdmissionBarrierValue closed = prepared.closedValue(); - dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - CanonicalGameplayIssuerInstalledAnchor anchor = - CanonicalGameplayIssuerBootstrapCoverageRepository - .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); - CanonicalGameplayIssuerAdmissionControlValue value = - readCurrentControl(transaction, anchor, current); - if (!closed.ownerOperationId().equals(value.currentOperationId()) - || value.state() != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING - || !closed.admissionEpoch().equals(value.liveBarrierEpoch())) { - throw conflict("Prepared CLOSED target no longer belongs to current pending cutoff"); - } - new CanonicalGameplayIssuerAdmissionControlRepository(dsl) - .verifyCurrentCutoffTarget( - transaction, - value, - closed.tenantId(), - closed.playableStateNamespaceId(), - closed.exactBytes()); - requireCurrentTagMapping(transaction, closed.tenantId(), closed.tenantGameplayTag()); - return null; - }); + dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + CanonicalGameplayIssuerAdmissionControlValue value = + readCurrentControl(transaction, anchor, current); + if (!closed.ownerOperationId().equals(value.currentOperationId()) + || value.state() != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING + || !closed.admissionEpoch().equals(value.liveBarrierEpoch())) { + throw conflict("Prepared CLOSED target no longer belongs to current pending cutoff"); + } + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .verifyCurrentCutoffTarget( + transaction, + value, + closed.tenantId(), + closed.playableStateNamespaceId(), + closed.exactBytes()); + requireCurrentTagMapping(transaction, closed.tenantId(), closed.tenantGameplayTag()); + return null; + }); } @Override @@ -357,70 +349,66 @@ public void recordOpenReadback( } CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = readCurrentState(); - dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - CanonicalGameplayIssuerInstalledAnchor anchor = - CanonicalGameplayIssuerBootstrapCoverageRepository - .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); - CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( - transaction, anchor, current); - Record initializer = - transaction.fetchSingle( - "SELECT * FROM " - + INITIALIZER - + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", - value.initializer().operationId(), - ISSUER); - requirePersistedInitializer(initializer, value); - String initializationState = initializer.get("initialization_state", String.class); - if (!List.of("INITIALIZING", "OPEN_CONFIRMED").contains(initializationState)) { - throw conflict("OPEN readback has no durable first-attempt initializer state"); - } - transaction.execute( - "INSERT INTO " + dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( + transaction, anchor, current); + Record initializer = + transaction.fetchSingle( + "SELECT * FROM " + + INITIALIZER + + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + value.initializer().operationId(), + ISSUER); + requirePersistedInitializer(initializer, value); + String initializationState = initializer.get("initialization_state", String.class); + if (!List.of("INITIALIZING", "OPEN_CONFIRMED").contains(initializationState)) { + throw conflict("OPEN readback has no durable first-attempt initializer state"); + } + transaction.execute( + "INSERT INTO " + + INITIALIZER_RECEIPT + + " (operation_id, issuer_id, exact_open_payload_bytes," + + " exact_open_payload_digest, script_outcome) VALUES (?, ?, ?, ?, ?)" + + " ON CONFLICT (operation_id) DO NOTHING", + value.initializer().operationId(), + ISSUER, + value.exactBytes(), + value.exactDigest(), + (short) readback.scriptOutcome()); + Record receipt = + transaction.fetchOne( + "SELECT * FROM " + INITIALIZER_RECEIPT - + " (operation_id, issuer_id, exact_open_payload_bytes," - + " exact_open_payload_digest, script_outcome) VALUES (?, ?, ?, ?, ?)" - + " ON CONFLICT (operation_id) DO NOTHING", + + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", value.initializer().operationId(), - ISSUER, - value.exactBytes(), - value.exactDigest(), - (short) readback.scriptOutcome()); - Record receipt = - transaction.fetchOne( - "SELECT * FROM " - + INITIALIZER_RECEIPT - + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", - value.initializer().operationId(), - ISSUER); - if (receipt == null - || !Arrays.equals( - requireBytes(receipt, "exact_open_payload_bytes"), value.exactBytes()) - || !value.exactDigest().equals(receipt.get("exact_open_payload_digest", String.class)) - || !List.of((short) 1, (short) 2) - .contains(receipt.get("script_outcome", Short.class))) { - throw conflict( - "Original OPEN readback receipt conflicts with durable initializer bytes"); - } - if ("INITIALIZING".equals(initializationState)) { - int confirmed = - transaction.execute( - "UPDATE " - + INITIALIZER - + " SET initialization_state = 'OPEN_CONFIRMED'" - + " WHERE operation_id = ? AND issuer_id = ?" - + " AND initialization_state = 'INITIALIZING'", - value.initializer().operationId(), - ISSUER); - if (confirmed != 1) { - throw conflict("Original OPEN receipt could not confirm its initializer state"); - } - } - return null; - }); + ISSUER); + if (receipt == null + || !Arrays.equals(requireBytes(receipt, "exact_open_payload_bytes"), value.exactBytes()) + || !value.exactDigest().equals(receipt.get("exact_open_payload_digest", String.class)) + || !List.of((short) 1, (short) 2).contains(receipt.get("script_outcome", Short.class))) { + throw conflict("Original OPEN readback receipt conflicts with durable initializer bytes"); + } + if ("INITIALIZING".equals(initializationState)) { + int confirmed = + transaction.execute( + "UPDATE " + + INITIALIZER + + " SET initialization_state = 'OPEN_CONFIRMED'" + + " WHERE operation_id = ? AND issuer_id = ?" + + " AND initialization_state = 'INITIALIZING'", + value.initializer().operationId(), + ISSUER); + if (confirmed != 1) { + throw conflict("Original OPEN receipt could not confirm its initializer state"); + } + } + return null; + }); } @Override @@ -437,70 +425,65 @@ public void recordClosedReadback( } CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = readCurrentState(); - dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - CanonicalGameplayIssuerInstalledAnchor anchor = - CanonicalGameplayIssuerBootstrapCoverageRepository - .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); - CanonicalGameplayIssuerAdmissionControlValue control = - readCurrentControl(transaction, anchor, current); - if (!value.ownerOperationId().equals(control.currentOperationId()) - || control.state() - != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING) { - throw conflict("CLOSED readback is not owned by the current pending cutoff"); - } - new CanonicalGameplayIssuerAdmissionControlRepository(dsl) - .verifyCurrentCutoffTarget( - transaction, - control, - value.tenantId(), - value.playableStateNamespaceId(), - value.exactBytes()); - requireCurrentTagMapping(transaction, value.tenantId(), value.tenantGameplayTag()); - Record target = - transaction.fetchOne( - "SELECT * FROM " - + CUTOFF_TARGET - + " WHERE operation_id = ? AND issuer_id = ? AND tenant_id = ?" - + " AND playable_state_namespace_id = ? FOR UPDATE", - value.ownerOperationId(), - ISSUER, - value.tenantId(), - value.playableStateNamespaceId()); - if (target == null - || !Arrays.equals(requireBytes(target, "closed_payload_bytes"), value.exactBytes()) - || !value.exactDigest().equals(target.get("closed_payload_digest", String.class))) { - throw conflict("CLOSED readback target changed before durable acknowledgement"); - } - String state = target.get("target_state", String.class); - if ("REQUIRED".equals(state)) { - int updated = - transaction.execute( - "UPDATE " - + CUTOFF_TARGET - + " SET exact_closed_readback_bytes = ?, exact_closed_readback_digest = ? ," - + " script_outcome = ?, target_state = 'CLOSED'" - + " WHERE operation_id = ? AND target_ordinal = ? AND target_state = 'REQUIRED'", - value.exactBytes(), - value.exactDigest(), - (short) readback.scriptOutcome(), - value.ownerOperationId(), - target.get("target_ordinal", Long.class)); - if (updated != 1) throw conflict("CLOSED target changed during receipt persistence"); - } else if (!"CLOSED".equals(state) - || !Arrays.equals( - requireBytes(target, "exact_closed_readback_bytes"), value.exactBytes()) - || !value - .exactDigest() - .equals(target.get("exact_closed_readback_digest", String.class)) - || !List.of((short) 1, (short) 2, (short) 3) - .contains(target.get("script_outcome", Short.class))) { - throw conflict("CLOSED retry conflicts with its immutable durable readback"); - } - return null; - }); + dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + CanonicalGameplayIssuerAdmissionControlValue control = + readCurrentControl(transaction, anchor, current); + if (!value.ownerOperationId().equals(control.currentOperationId()) + || control.state() != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING) { + throw conflict("CLOSED readback is not owned by the current pending cutoff"); + } + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .verifyCurrentCutoffTarget( + transaction, + control, + value.tenantId(), + value.playableStateNamespaceId(), + value.exactBytes()); + requireCurrentTagMapping(transaction, value.tenantId(), value.tenantGameplayTag()); + Record target = + transaction.fetchOne( + "SELECT * FROM " + + CUTOFF_TARGET + + " WHERE operation_id = ? AND issuer_id = ? AND tenant_id = ?" + + " AND playable_state_namespace_id = ? FOR UPDATE", + value.ownerOperationId(), + ISSUER, + value.tenantId(), + value.playableStateNamespaceId()); + if (target == null + || !Arrays.equals(requireBytes(target, "closed_payload_bytes"), value.exactBytes()) + || !value.exactDigest().equals(target.get("closed_payload_digest", String.class))) { + throw conflict("CLOSED readback target changed before durable acknowledgement"); + } + String state = target.get("target_state", String.class); + if ("REQUIRED".equals(state)) { + int updated = + transaction.execute( + "UPDATE " + + CUTOFF_TARGET + + " SET exact_closed_readback_bytes = ?, exact_closed_readback_digest = ? ," + + " script_outcome = ?, target_state = 'CLOSED'" + + " WHERE operation_id = ? AND target_ordinal = ? AND target_state = 'REQUIRED'", + value.exactBytes(), + value.exactDigest(), + (short) readback.scriptOutcome(), + value.ownerOperationId(), + target.get("target_ordinal", Long.class)); + if (updated != 1) throw conflict("CLOSED target changed during receipt persistence"); + } else if (!"CLOSED".equals(state) + || !Arrays.equals(requireBytes(target, "exact_closed_readback_bytes"), value.exactBytes()) + || !value.exactDigest().equals(target.get("exact_closed_readback_digest", String.class)) + || !List.of((short) 1, (short) 2, (short) 3) + .contains(target.get("script_outcome", Short.class))) { + throw conflict("CLOSED retry conflicts with its immutable durable readback"); + } + return null; + }); } private CurrentRequestTarget requireCurrentRequestTarget( @@ -788,76 +771,73 @@ public boolean claimFirstCreatePermit( ? null : tenantTags.assignmentForTransition(prepared.assignment().transitionId()); if (assignment != null) requireSameAssignment(prepared.assignment(), assignment); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - CanonicalGameplayIssuerInstalledAnchor anchor = - CanonicalGameplayIssuerBootstrapCoverageRepository - .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); - CanonicalGameplayIssuerAdmissionControlValue control = - CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( - transaction, anchor, current); - if (!control.liveBarrierEpoch().equals(value.admissionEpoch()) - || !control.currentOperationId().equals(anchor.bootstrapOperationId())) { - throw conflict( - "Original initializer no longer belongs to the current OPEN live control"); - } - if (assignment != null) { - requireCurrentTagMapping( - transaction, assignment.tenantId(), assignment.tenantGameplayTag()); - requireCurrentRequestTarget( - transaction, prepared.requestOperationId(), assignment, current); - } - Record saved = - transaction.fetchSingle( - "SELECT * FROM " - + INITIALIZER - + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", - operationId, - ISSUER); - readFrozenInitializer( - transaction, saved, prepared.assignment(), anchor, control, current); - requirePersistedInitializer(saved, value); - String state = saved.get("initialization_state", String.class); - if ("PREPARED".equals(state)) { - Record origin = - transaction.fetchOne( - "SELECT transition.status AS transition_status FROM " - + LOCAL_OPERATION - + " operation JOIN game_session_canonical_binding_transition transition" - + " ON transition.transition_id = operation.transition_id" - + " WHERE operation.operation_id = ? AND operation.issuer_id = ?" - + " FOR SHARE OF operation, transition", - operationId, - ISSUER); - if (origin == null) { - throw conflict("Original initializer lost its persisted local-operation provenance"); - } - if ("ABORTED".equals(origin.get("transition_status", String.class))) { - return false; - } - if (!List.of("PROVISIONAL", "COMMITTED") - .contains(origin.get("transition_status", String.class))) { - throw conflict("Original initializer source is no longer an eligible first NEW"); - } - int claimed = - transaction.execute( - "UPDATE " - + INITIALIZER - + " SET initialization_state = 'INITIALIZING'" - + " WHERE operation_id = ? AND issuer_id = ?" - + " AND initialization_state = 'PREPARED'", - operationId, - ISSUER); - if (claimed != 1) { - throw conflict("Original initializer first-create permit was not uniquely claimed"); - } - return true; - } - if ("INITIALIZING".equals(state) || "OPEN_CONFIRMED".equals(state)) return false; - throw conflict("Original initializer has an unknown or non-admitting durable state"); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + CanonicalGameplayIssuerAdmissionControlValue control = + CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( + transaction, anchor, current); + if (!control.liveBarrierEpoch().equals(value.admissionEpoch()) + || !control.currentOperationId().equals(anchor.bootstrapOperationId())) { + throw conflict("Original initializer no longer belongs to the current OPEN live control"); + } + if (assignment != null) { + requireCurrentTagMapping( + transaction, assignment.tenantId(), assignment.tenantGameplayTag()); + requireCurrentRequestTarget( + transaction, prepared.requestOperationId(), assignment, current); + } + Record saved = + transaction.fetchSingle( + "SELECT * FROM " + + INITIALIZER + + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + operationId, + ISSUER); + readFrozenInitializer(transaction, saved, prepared.assignment(), anchor, control, current); + requirePersistedInitializer(saved, value); + String state = saved.get("initialization_state", String.class); + if ("PREPARED".equals(state)) { + Record origin = + transaction.fetchOne( + "SELECT transition.status AS transition_status FROM " + + LOCAL_OPERATION + + " operation JOIN game_session_canonical_binding_transition transition" + + " ON transition.transition_id = operation.transition_id" + + " WHERE operation.operation_id = ? AND operation.issuer_id = ?" + + " FOR SHARE OF operation, transition", + operationId, + ISSUER); + if (origin == null) { + throw conflict("Original initializer lost its persisted local-operation provenance"); + } + if ("ABORTED".equals(origin.get("transition_status", String.class))) { + return false; + } + if (!List.of("PROVISIONAL", "COMMITTED") + .contains(origin.get("transition_status", String.class))) { + throw conflict("Original initializer source is no longer an eligible first NEW"); + } + int claimed = + transaction.execute( + "UPDATE " + + INITIALIZER + + " SET initialization_state = 'INITIALIZING'" + + " WHERE operation_id = ? AND issuer_id = ?" + + " AND initialization_state = 'PREPARED'", + operationId, + ISSUER); + if (claimed != 1) { + throw conflict("Original initializer first-create permit was not uniquely claimed"); + } + return true; + } + if ("INITIALIZING".equals(state) || "OPEN_CONFIRMED".equals(state)) return false; + throw conflict("Original initializer has an unknown or non-admitting durable state"); + }); } private UUID transitionForLocalOperation(UUID operationId) { @@ -874,13 +854,12 @@ private UUID transitionForLocalOperation(UUID operationId) { private CanonicalGameplayIssuerInstalledAnchor readInstalledAnchor( CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - return CanonicalGameplayIssuerBootstrapCoverageRepository - .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + return CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + }); } private CanonicalGameplayIssuerAdmissionControlValue readCurrentControl( @@ -978,13 +957,12 @@ private void requireNoAmbientTransaction() { throw conflict("Issuer tenant barrier owner cannot join an ambient SQL transaction"); } try { - dsl.connectionResult( - connection -> { - if (!connection.getAutoCommit()) { - throw conflict("Issuer tenant barrier owner cannot join a jOOQ transaction"); - } - return Boolean.TRUE; - }); + dsl.connectionResult(connection -> { + if (!connection.getAutoCommit()) { + throw conflict("Issuer tenant barrier owner cannot join a jOOQ transaction"); + } + return Boolean.TRUE; + }); } catch (RuntimeException failure) { if (failure instanceof CanonicalGameplayBindingInventoryConflictException) throw failure; throw new CanonicalGameplayBindingInventoryConflictException( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierValue.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierValue.java index 1c17f78e85..e2b9a82bd0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierValue.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierValue.java @@ -143,32 +143,31 @@ static final class Initializer { } private byte[] encodeTarget() { - return encode( - out -> { - writeText(out, TARGET_ENCODING); - writeText(out, issuerId); - writeUuid(out, tenantId); - writeUuid(out, playableStateNamespaceId); - writeText(out, tenantGameplayTag); - writeUuid(out, operationId); - writeBigInteger(out, admissionEpoch); - writeUuid(out, transitionId); - writeUuid(out, accountId); - writeBytes(out, bindingRefBytes); - writeBytes(out, reservationBytes); - writeText(out, reservationDigest); - writeBytes(out, anchorBytes); - writeText(out, anchorDigest); - writeBigInteger(out, accountIssuerAuthGeneration); - writeBytes(out, accountCheckpointBytes); - writeText(out, accountCheckpointDigest); - writeNullableBytes(out, accountSourceEventBytes); - writeNullableText(out, accountSourceEventDigest); - writeBytes(out, incarnationBytes); - writeText(out, incarnationDigest); - writeBytes(out, registeredTargetBytes); - writeText(out, registeredTargetDigest); - }); + return encode(out -> { + writeText(out, TARGET_ENCODING); + writeText(out, issuerId); + writeUuid(out, tenantId); + writeUuid(out, playableStateNamespaceId); + writeText(out, tenantGameplayTag); + writeUuid(out, operationId); + writeBigInteger(out, admissionEpoch); + writeUuid(out, transitionId); + writeUuid(out, accountId); + writeBytes(out, bindingRefBytes); + writeBytes(out, reservationBytes); + writeText(out, reservationDigest); + writeBytes(out, anchorBytes); + writeText(out, anchorDigest); + writeBigInteger(out, accountIssuerAuthGeneration); + writeBytes(out, accountCheckpointBytes); + writeText(out, accountCheckpointDigest); + writeNullableBytes(out, accountSourceEventBytes); + writeNullableText(out, accountSourceEventDigest); + writeBytes(out, incarnationBytes); + writeText(out, incarnationDigest); + writeBytes(out, registeredTargetBytes); + writeText(out, registeredTargetDigest); + }); } private static Initializer decode(byte[] bytes) { @@ -436,19 +435,18 @@ static CanonicalGameplayIssuerAdmissionBarrierValue decode(byte[] bytes) { } private byte[] encodeValue() { - return encode( - out -> { - writeText(out, VALUE_ENCODING); - writeText(out, issuerId); - writeUuid(out, tenantId); - writeUuid(out, playableStateNamespaceId); - writeText(out, tenantGameplayTag); - writeText(out, state.name()); - writeBigInteger(out, admissionEpoch); - writeUuid(out, ownerOperationId); - writeNullableBytes(out, initializer == null ? null : initializer.exactBytes()); - writeNullableText(out, initializer == null ? null : initializer.exactDigest()); - }); + return encode(out -> { + writeText(out, VALUE_ENCODING); + writeText(out, issuerId); + writeUuid(out, tenantId); + writeUuid(out, playableStateNamespaceId); + writeText(out, tenantGameplayTag); + writeText(out, state.name()); + writeBigInteger(out, admissionEpoch); + writeUuid(out, ownerOperationId); + writeNullableBytes(out, initializer == null ? null : initializer.exactBytes()); + writeNullableText(out, initializer == null ? null : initializer.exactDigest()); + }); } String issuerId() { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java index c6410fbccf..88a391bd95 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java @@ -93,85 +93,82 @@ CanonicalGameplayIssuerAdmissionControlValue beginCutoff( throw conflict("Issuer cutoff operation and request identities must be distinct"); } requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger snapshotRevision = - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - lockLayoutControl(transaction, anchor); - Record controlRow = - transaction.fetchOne( - "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); - if (controlRow == null) { - throw conflict("Issuer cutoff requires a positively installed live control row"); - } - CanonicalGameplayIssuerAdmissionControlValue control = loadControl(controlRow); - requireExactAnchorAndCurrentSource(control, anchor, currentState); - Record counter = - transaction.fetchOne( - "SELECT * FROM " + COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); - if (counter == null) throw conflict("The positive live issuer epoch counter is missing"); - requireCounterMatchesCurrent(transaction, control.liveBarrierEpoch()); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger snapshotRevision = + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + lockLayoutControl(transaction, anchor); + Record controlRow = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (controlRow == null) { + throw conflict("Issuer cutoff requires a positively installed live control row"); + } + CanonicalGameplayIssuerAdmissionControlValue control = loadControl(controlRow); + requireExactAnchorAndCurrentSource(control, anchor, currentState); + Record counter = + transaction.fetchOne( + "SELECT * FROM " + COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (counter == null) throw conflict("The positive live issuer epoch counter is missing"); + requireCounterMatchesCurrent(transaction, control.liveBarrierEpoch()); - Record priorOperation = - transaction.fetchOne( - "SELECT * FROM " + OPERATION + " WHERE operation_id = ? FOR UPDATE", - cutoffOperationId); - if (control.state() == CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING - && control.currentOperationId().equals(cutoffOperationId)) { - if (priorOperation == null - || !requestId.equals(uuid(priorOperation, "request_id")) - || !"CUTOFF".equals(text(priorOperation, "operation_kind")) - || !"CUTOFF_PENDING".equals(text(priorOperation, "operation_state"))) { - throw conflict("Issuer cutoff retry differs from its exact pending operation"); - } - verifyCutoffTargets(transaction, control); - return control; - } - if (control.state() != CanonicalGameplayIssuerAdmissionControlValue.State.OPEN - || control.currentOperationKind() - != CanonicalGameplayIssuerAdmissionControlValue.OperationKind - .INITIAL_ANCHOR_INSTALL - || !control.currentOperationId().equals(anchor.bootstrapOperationId()) - || priorOperation != null) { - throw conflict( - "Issuer live control cannot be reset, reopened, or replaced by this cutoff"); - } - requireInitialOperationCurrent(transaction, control); + Record priorOperation = + transaction.fetchOne( + "SELECT * FROM " + OPERATION + " WHERE operation_id = ? FOR UPDATE", + cutoffOperationId); + if (control.state() == CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING + && control.currentOperationId().equals(cutoffOperationId)) { + if (priorOperation == null + || !requestId.equals(uuid(priorOperation, "request_id")) + || !"CUTOFF".equals(text(priorOperation, "operation_kind")) + || !"CUTOFF_PENDING".equals(text(priorOperation, "operation_state"))) { + throw conflict("Issuer cutoff retry differs from its exact pending operation"); + } + verifyCutoffTargets(transaction, control); + return control; + } + if (control.state() != CanonicalGameplayIssuerAdmissionControlValue.State.OPEN + || control.currentOperationKind() + != CanonicalGameplayIssuerAdmissionControlValue.OperationKind.INITIAL_ANCHOR_INSTALL + || !control.currentOperationId().equals(anchor.bootstrapOperationId()) + || priorOperation != null) { + throw conflict("Issuer live control cannot be reset, reopened, or replaced by this cutoff"); + } + requireInitialOperationCurrent(transaction, control); - List rows = captureCutoffCohort(transaction, snapshotRevision); - Map> targets = groupTargets(rows); - Map tagByTarget = new TreeMap<>(); - for (TargetScope scope : targets.keySet()) { - tagByTarget.put(scope, requireCurrentTenantTagMapping(transaction, scope.tenantId())); - } + List rows = captureCutoffCohort(transaction, snapshotRevision); + Map> targets = groupTargets(rows); + Map tagByTarget = new TreeMap<>(); + for (TargetScope scope : targets.keySet()) { + tagByTarget.put(scope, requireCurrentTenantTagMapping(transaction, scope.tenantId())); + } - BigInteger priorEpoch = control.liveBarrierEpoch(); - Record allocated = - transaction.fetchOne( - "UPDATE " - + COUNTER - + " SET last_live_barrier_epoch = last_live_barrier_epoch + 1," - + " updated_at = CURRENT_TIMESTAMP" - + " WHERE issuer_id = ? AND last_live_barrier_epoch = ?" - + " RETURNING last_live_barrier_epoch", - ISSUER, - priorEpoch); - if (allocated == null) { - throw conflict("Issuer cutoff lost its serialized live epoch allocation"); - } - BigInteger cutoffEpoch = integer(allocated, "last_live_barrier_epoch"); - String cohortDigest = digestCohort(rows); - CanonicalGameplayIssuerAdmissionControlValue pending = - control.cutoffPending( - cutoffOperationId, cutoffEpoch, snapshotRevision, rows.size(), cohortDigest); - insertCutoffOperation(transaction, pending, requestId, priorEpoch); - updateControl(transaction, pending, control.liveBarrierEpoch()); - insertCohortRows(transaction, pending.currentOperationId(), rows); - insertCutoffTargets(transaction, pending, targets, tagByTarget); - verifyCutoffTargets(transaction, pending); - return pending; - }); + BigInteger priorEpoch = control.liveBarrierEpoch(); + Record allocated = + transaction.fetchOne( + "UPDATE " + + COUNTER + + " SET last_live_barrier_epoch = last_live_barrier_epoch + 1," + + " updated_at = CURRENT_TIMESTAMP" + + " WHERE issuer_id = ? AND last_live_barrier_epoch = ?" + + " RETURNING last_live_barrier_epoch", + ISSUER, + priorEpoch); + if (allocated == null) { + throw conflict("Issuer cutoff lost its serialized live epoch allocation"); + } + BigInteger cutoffEpoch = integer(allocated, "last_live_barrier_epoch"); + String cohortDigest = digestCohort(rows); + CanonicalGameplayIssuerAdmissionControlValue pending = + control.cutoffPending( + cutoffOperationId, cutoffEpoch, snapshotRevision, rows.size(), cohortDigest); + insertCutoffOperation(transaction, pending, requestId, priorEpoch); + updateControl(transaction, pending, control.liveBarrierEpoch()); + insertCohortRows(transaction, pending.currentOperationId(), rows); + insertCutoffTargets(transaction, pending, targets, tagByTarget); + verifyCutoffTargets(transaction, pending); + return pending; + }); } /** Publishes INSTALLED only after every captured tenant target has an exact CLOSED readback. */ @@ -183,72 +180,69 @@ CanonicalGameplayIssuerAdmissionControlValue completeCutoff( Objects.requireNonNull(anchor, "anchor"); Objects.requireNonNull(currentState, "currentState"); requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - lockLayoutControl(transaction, anchor); - Record controlRow = - transaction.fetchOne( - "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); - if (controlRow == null) throw conflict("Issuer cutoff control row is missing"); - CanonicalGameplayIssuerAdmissionControlValue control = loadControl(controlRow); - requireExactAnchorAndCurrentSource(control, anchor, currentState); - requireCounterMatchesCurrent(transaction, control.liveBarrierEpoch()); - if (!control.currentOperationId().equals(cutoffOperationId) - || control.state() - != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING - || control.currentOperationKind() - != CanonicalGameplayIssuerAdmissionControlValue.OperationKind.CUTOFF) { - if (control.currentOperationId().equals(cutoffOperationId) - && control.state() - == CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED) { - requireCutoffOperationCurrent(transaction, control); - verifyCutoffTargets(transaction, control); - return control; - } - throw conflict("The exact current cutoff is not pending completion"); - } + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + lockLayoutControl(transaction, anchor); + Record controlRow = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (controlRow == null) throw conflict("Issuer cutoff control row is missing"); + CanonicalGameplayIssuerAdmissionControlValue control = loadControl(controlRow); + requireExactAnchorAndCurrentSource(control, anchor, currentState); + requireCounterMatchesCurrent(transaction, control.liveBarrierEpoch()); + if (!control.currentOperationId().equals(cutoffOperationId) + || control.state() != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING + || control.currentOperationKind() + != CanonicalGameplayIssuerAdmissionControlValue.OperationKind.CUTOFF) { + if (control.currentOperationId().equals(cutoffOperationId) + && control.state() == CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED) { requireCutoffOperationCurrent(transaction, control); verifyCutoffTargets(transaction, control); - Record remaining = - transaction.fetchOne( - "SELECT EXISTS (SELECT 1 FROM " - + CUTOFF_TARGET - + " WHERE operation_id = ? AND issuer_id = ? AND target_state <> 'CLOSED')" - + " AS has_open_target", - cutoffOperationId, - ISSUER); - if (remaining == null - || Boolean.TRUE.equals(remaining.get("has_open_target", Boolean.class))) { - throw conflict( - "Every frozen issuer tenant target must read back CLOSED before installation"); - } - CanonicalGameplayIssuerAdmissionControlValue installed = control.installed(); - int updatedOperation = - transaction.execute( - "UPDATE " - + OPERATION - + " SET operation_state = 'INSTALLED', installed_at = CURRENT_TIMESTAMP" - + " WHERE operation_id = ? AND issuer_id = ? AND operation_kind = 'CUTOFF'" - + " AND operation_state = 'CUTOFF_PENDING' AND live_barrier_epoch = ?" - + " AND prior_live_barrier_epoch = ?", - cutoffOperationId, - ISSUER, - control.liveBarrierEpoch(), - control.liveBarrierEpoch().subtract(BigInteger.ONE)); - if (updatedOperation != 1) - throw conflict("Issuer cutoff operation changed before installation"); - updateControl(transaction, installed, control.liveBarrierEpoch()); - Record saved = - transaction.fetchOne( - "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); - if (saved == null - || !Arrays.equals(loadControl(saved).exactBytes(), installed.exactBytes())) { - throw conflict("Installed issuer cutoff did not read back exactly"); - } - return installed; - }); + return control; + } + throw conflict("The exact current cutoff is not pending completion"); + } + requireCutoffOperationCurrent(transaction, control); + verifyCutoffTargets(transaction, control); + Record remaining = + transaction.fetchOne( + "SELECT EXISTS (SELECT 1 FROM " + + CUTOFF_TARGET + + " WHERE operation_id = ? AND issuer_id = ? AND target_state <> 'CLOSED')" + + " AS has_open_target", + cutoffOperationId, + ISSUER); + if (remaining == null + || Boolean.TRUE.equals(remaining.get("has_open_target", Boolean.class))) { + throw conflict( + "Every frozen issuer tenant target must read back CLOSED before installation"); + } + CanonicalGameplayIssuerAdmissionControlValue installed = control.installed(); + int updatedOperation = + transaction.execute( + "UPDATE " + + OPERATION + + " SET operation_state = 'INSTALLED', installed_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND issuer_id = ? AND operation_kind = 'CUTOFF'" + + " AND operation_state = 'CUTOFF_PENDING' AND live_barrier_epoch = ?" + + " AND prior_live_barrier_epoch = ?", + cutoffOperationId, + ISSUER, + control.liveBarrierEpoch(), + control.liveBarrierEpoch().subtract(BigInteger.ONE)); + if (updatedOperation != 1) + throw conflict("Issuer cutoff operation changed before installation"); + updateControl(transaction, installed, control.liveBarrierEpoch()); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (saved == null + || !Arrays.equals(loadControl(saved).exactBytes(), installed.exactBytes())) { + throw conflict("Installed issuer cutoff did not read back exactly"); + } + return installed; + }); } /** Revalidates a requested CLOSED key against the complete frozen cutoff cohort. */ @@ -361,27 +355,25 @@ private static List captureCutoffCohort( } return transaction .fetch(sql, binds.toArray()) - .map( - row -> { - String json = text(row, "source_row_json"); - String digest = - CanonicalGameplayIssuerAdmissionControlValue.sha256( - json.getBytes(StandardCharsets.UTF_8)); - BigInteger revision = integer(row, "source_revision"); - if (revision.signum() <= 0 || revision.compareTo(snapshotRevision) > 0) { - throw conflict( - "Issuer cutoff cohort contains a source outside its locked snapshot"); - } - return new CohortRow( - text(row, "source_kind"), - text(row, "source_key"), - revision, - json, - uuid(row, "tenant_id"), - uuid(row, "playable_state_namespace_id"), - uuid(row, "transition_id"), - digest); - }); + .map(row -> { + String json = text(row, "source_row_json"); + String digest = + CanonicalGameplayIssuerAdmissionControlValue.sha256( + json.getBytes(StandardCharsets.UTF_8)); + BigInteger revision = integer(row, "source_revision"); + if (revision.signum() <= 0 || revision.compareTo(snapshotRevision) > 0) { + throw conflict("Issuer cutoff cohort contains a source outside its locked snapshot"); + } + return new CohortRow( + text(row, "source_kind"), + text(row, "source_key"), + revision, + json, + uuid(row, "tenant_id"), + uuid(row, "playable_state_namespace_id"), + uuid(row, "transition_id"), + digest); + }); } private static void requireNoFutureCutoffRows( @@ -637,26 +629,24 @@ private static List verifyFrozenCohort( + " END AS source) scope ORDER BY c.row_ordinal", control.currentOperationId(), ISSUER) - .map( - row -> { - String json = text(row, "source_row_json"); - String storedDigest = text(row, "source_row_digest"); - if (!CanonicalGameplayIssuerAdmissionControlValue.sha256( - json.getBytes(StandardCharsets.UTF_8)) - .equals(storedDigest)) { - throw conflict( - "Issuer cutoff cohort source digest differs from its stored JSON"); - } - return new CohortRow( - text(row, "source_kind"), - text(row, "source_key"), - integer(row, "source_inventory_revision"), - json, - uuid(row, "tenant_id"), - uuid(row, "playable_state_namespace_id"), - null, - storedDigest); - }); + .map(row -> { + String json = text(row, "source_row_json"); + String storedDigest = text(row, "source_row_digest"); + if (!CanonicalGameplayIssuerAdmissionControlValue.sha256( + json.getBytes(StandardCharsets.UTF_8)) + .equals(storedDigest)) { + throw conflict("Issuer cutoff cohort source digest differs from its stored JSON"); + } + return new CohortRow( + text(row, "source_kind"), + text(row, "source_key"), + integer(row, "source_inventory_revision"), + json, + uuid(row, "tenant_id"), + uuid(row, "playable_state_namespace_id"), + null, + storedDigest); + }); for (int index = 0; index < rows.size(); index++) { if (rows.get(index).sourceRevision().compareTo(control.inventorySnapshotRevision()) > 0) { throw conflict("Issuer cutoff cohort row is newer than its frozen inventory snapshot"); @@ -863,14 +853,12 @@ private static String digestCohort(List rows) { MessageDigest digest = sha256Digest(); rows.stream() .sorted(Comparator.comparing(CohortRow::sourceKind).thenComparing(CohortRow::sourceKey)) - .forEach( - row -> { - updateFramed(digest, row.sourceKind().getBytes(StandardCharsets.UTF_8)); - updateFramed(digest, row.sourceKey().getBytes(StandardCharsets.UTF_8)); - updateFramed( - digest, row.sourceRevision().toString().getBytes(StandardCharsets.US_ASCII)); - updateFramed(digest, row.sourceDigest().getBytes(StandardCharsets.US_ASCII)); - }); + .forEach(row -> { + updateFramed(digest, row.sourceKind().getBytes(StandardCharsets.UTF_8)); + updateFramed(digest, row.sourceKey().getBytes(StandardCharsets.UTF_8)); + updateFramed(digest, row.sourceRevision().toString().getBytes(StandardCharsets.US_ASCII)); + updateFramed(digest, row.sourceDigest().getBytes(StandardCharsets.US_ASCII)); + }); return "sha256:" + HexFormat.of().formatHex(digest.digest()); } @@ -878,12 +866,11 @@ private static String digestTargetSource(List rows) { MessageDigest digest = sha256Digest(); rows.stream() .sorted(Comparator.comparing(CohortRow::sourceKind).thenComparing(CohortRow::sourceKey)) - .forEach( - row -> { - updateFramed(digest, row.sourceKind().getBytes(StandardCharsets.UTF_8)); - updateFramed(digest, row.sourceKey().getBytes(StandardCharsets.UTF_8)); - updateFramed(digest, row.sourceDigest().getBytes(StandardCharsets.US_ASCII)); - }); + .forEach(row -> { + updateFramed(digest, row.sourceKind().getBytes(StandardCharsets.UTF_8)); + updateFramed(digest, row.sourceKey().getBytes(StandardCharsets.UTF_8)); + updateFramed(digest, row.sourceDigest().getBytes(StandardCharsets.US_ASCII)); + }); return "sha256:" + HexFormat.of().formatHex(digest.digest()); } @@ -1282,13 +1269,12 @@ private void requireNoAmbientTransaction() { throw conflict("Issuer admission-control owner cannot join an ambient transaction"); } try { - dsl.connectionResult( - connection -> { - if (!connection.getAutoCommit()) { - throw conflict("Issuer admission-control owner cannot join a jOOQ transaction"); - } - return Boolean.TRUE; - }); + dsl.connectionResult(connection -> { + if (!connection.getAutoCommit()) { + throw conflict("Issuer admission-control owner cannot join a jOOQ transaction"); + } + return Boolean.TRUE; + }); } catch (RuntimeException failure) { if (failure instanceof CanonicalGameplayBindingInventoryConflictException) throw failure; throw new CanonicalGameplayBindingInventoryConflictException( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlValue.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlValue.java index 90a2d3b555..3040e5bb38 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlValue.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlValue.java @@ -272,30 +272,29 @@ static CanonicalGameplayIssuerAdmissionControlValue decode(byte[] bytes) { } private byte[] encode() { - return encode( - out -> { - writeText(out, ENCODING); - writeText(out, issuerId); - writeText(out, state.name()); - writeBigInteger(out, liveBarrierEpoch); - writeUuid(out, currentOperationId); - writeText(out, currentOperationKind.name()); - writeUuid(out, bootstrapOperationId); - writeUuid(out, bootstrapRequestId); - writeBigInteger(out, bootstrapControlEpoch); - writeBytes(out, anchorExactBytes); - writeText(out, anchorExactDigest); - writeBigInteger(out, accountIssuerAuthGeneration); - writeBytes(out, accountCheckpointBytes); - writeText(out, accountCheckpointDigest); - writeNullableBytes(out, accountSourceEventBytes); - writeNullableText(out, accountSourceEventDigest); - writeBytes(out, stableIncarnationBytes); - writeText(out, stableIncarnationDigest); - writeBigInteger(out, inventorySnapshotRevision); - out.writeLong(cohortRowCount); - writeText(out, cohortDigest); - }); + return encode(out -> { + writeText(out, ENCODING); + writeText(out, issuerId); + writeText(out, state.name()); + writeBigInteger(out, liveBarrierEpoch); + writeUuid(out, currentOperationId); + writeText(out, currentOperationKind.name()); + writeUuid(out, bootstrapOperationId); + writeUuid(out, bootstrapRequestId); + writeBigInteger(out, bootstrapControlEpoch); + writeBytes(out, anchorExactBytes); + writeText(out, anchorExactDigest); + writeBigInteger(out, accountIssuerAuthGeneration); + writeBytes(out, accountCheckpointBytes); + writeText(out, accountCheckpointDigest); + writeNullableBytes(out, accountSourceEventBytes); + writeNullableText(out, accountSourceEventDigest); + writeBytes(out, stableIncarnationBytes); + writeText(out, stableIncarnationDigest); + writeBigInteger(out, inventorySnapshotRevision); + out.writeLong(cohortRowCount); + writeText(out, cohortDigest); + }); } boolean matchesCurrentIssuerState( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java index 9f608b5bb4..21e77780b4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java @@ -58,55 +58,53 @@ CanonicalGameplayIssuerBindingLocalAcknowledgement acknowledge( CanonicalGameplayIssuerBindingLocalOperation operation = readback.operation(); var before = readCurrentIssuerState("before acknowledgement"); CanonicalGameplayIssuerBindingLocalAcknowledgement acknowledged = - dsl.transactionResult( - configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - var work = - projectionRepository.readPreparedPartitionWorkInTransaction( - transaction, operation, before); - requireCurrentIssuerSource(operation, before); - requireEligibleCandidate(work); - - Record existing = - transaction.fetchOne( - "SELECT * FROM " + ACKNOWLEDGEMENT + " WHERE operation_id = ? FOR UPDATE", - operation.operationId()); - if (existing != null) { - var prior = readAcknowledgement(transaction, existing); - requireSameOperation(prior.evidence(), operation); - requireSameCurrentSources(prior.evidence(), operation, before); - requireReadbackTargetStillMatches(prior.evidence(), readback); - return prior; - } - - if (!Arrays.equals(readback.sqlCurrentnessDigest(), work.sqlCurrentnessDigest())) { - throw unavailable( - "SQL issuer cohort changed after physical readback; retry the original operation"); - } - ReadbackProof proof = validateReadback(operation, work, readback, before); - // The independent transition generation advances only in this SQL transaction, - // after both the exact current SQL operation and private physical readback validate. - // Counter advancement and immutable receipt insertion commit or roll back together. - BigInteger acknowledgementGeneration = - allocateAcknowledgementGeneration(transaction, operation.anchor().issuerId()); - Evidence evidence = - buildEvidence(operation, readback, before, proof, acknowledgementGeneration); - var result = CanonicalGameplayIssuerBindingLocalAcknowledgement.create(evidence); - insert(transaction, result); - Record stored = - transaction.fetchOne( - "SELECT * FROM " + ACKNOWLEDGEMENT + " WHERE operation_id = ? FOR UPDATE", - operation.operationId()); - if (stored == null) throw unavailable("Durable issuer acknowledgement disappeared"); - var durable = readAcknowledgement(transaction, stored); - if (!Arrays.equals(result.exactBytes(), durable.exactBytes()) - || !result.digest().equals(durable.digest())) { - throw unavailable( - "Durable issuer acknowledgement readback differs from its source"); - } - return durable; - }); + dsl.transactionResult(configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + var work = + projectionRepository.readPreparedPartitionWorkInTransaction( + transaction, operation, before); + requireCurrentIssuerSource(operation, before); + requireEligibleCandidate(work); + + Record existing = + transaction.fetchOne( + "SELECT * FROM " + ACKNOWLEDGEMENT + " WHERE operation_id = ? FOR UPDATE", + operation.operationId()); + if (existing != null) { + var prior = readAcknowledgement(transaction, existing); + requireSameOperation(prior.evidence(), operation); + requireSameCurrentSources(prior.evidence(), operation, before); + requireReadbackTargetStillMatches(prior.evidence(), readback); + return prior; + } + + if (!Arrays.equals(readback.sqlCurrentnessDigest(), work.sqlCurrentnessDigest())) { + throw unavailable( + "SQL issuer cohort changed after physical readback; retry the original operation"); + } + ReadbackProof proof = validateReadback(operation, work, readback, before); + // The independent transition generation advances only in this SQL transaction, + // after both the exact current SQL operation and private physical readback validate. + // Counter advancement and immutable receipt insertion commit or roll back together. + BigInteger acknowledgementGeneration = + allocateAcknowledgementGeneration(transaction, operation.anchor().issuerId()); + Evidence evidence = + buildEvidence(operation, readback, before, proof, acknowledgementGeneration); + var result = CanonicalGameplayIssuerBindingLocalAcknowledgement.create(evidence); + insert(transaction, result); + Record stored = + transaction.fetchOne( + "SELECT * FROM " + ACKNOWLEDGEMENT + " WHERE operation_id = ? FOR UPDATE", + operation.operationId()); + if (stored == null) throw unavailable("Durable issuer acknowledgement disappeared"); + var durable = readAcknowledgement(transaction, stored); + if (!Arrays.equals(result.exactBytes(), durable.exactBytes()) + || !result.digest().equals(durable.digest())) { + throw unavailable("Durable issuer acknowledgement readback differs from its source"); + } + return durable; + }); var after = readCurrentIssuerState("after acknowledgement"); if (!sameCurrentIssuerState(before, after)) { throw unavailable( @@ -772,13 +770,12 @@ private static void requireNoAmbientSpringTransaction() { private void requireNoAmbientTransaction() { requireNoAmbientSpringTransaction(); try { - dsl.connectionResult( - connection -> { - if (!connection.getAutoCommit()) { - throw unavailable("Issuer acknowledgement owner cannot join a jOOQ transaction"); - } - return Boolean.TRUE; - }); + dsl.connectionResult(connection -> { + if (!connection.getAutoCommit()) { + throw unavailable("Issuer acknowledgement owner cannot join a jOOQ transaction"); + } + return Boolean.TRUE; + }); } catch (RuntimeException failure) { if (failure instanceof IllegalStateException state && state.getMessage() != null diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java index 7f25f9a590..5f2e6a42f0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepository.java @@ -120,97 +120,94 @@ CanonicalGameplayIssuerBindingLocalOperation readOriginalForIssuerRelease( currentIssuerStateSource.readFreshCurrentState(), "current issuer state source returned null"); CanonicalGameplayIssuerBindingLocalOperation operation = - dsl.transactionResult( - configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - // This reader invokes the installed-anchor source loader, whose snapshot contract - // starts with the global inventory clock. Keep the same clock-before-source order - // used by ordinary registration, abort retry, and release completion. - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - Record operationRow = - transaction.fetchOne( - "SELECT * FROM " + OPERATION + " WHERE issuer_id = ? AND transition_id = ?", - ISSUER, - abortSource.transition().transitionId()); - if (operationRow == null) { - throw conflict( - "Account-aborted first-NEW source has no original local issuer operation"); - } - CanonicalGameplayIssuerInstalledAnchor anchor = - CanonicalGameplayIssuerBootstrapCoverageRepository - .readInstalledAnchorForBindingPreparationInTransaction( - transaction, currentState); - byte[] exactOriginal = requireBytes(operationRow, "member_value_bytes"); - CanonicalGameplayIssuerMemberV2Value original; - try { - original = CanonicalGameplayIssuerMemberV2Codec.decode(exactOriginal); - } catch (RuntimeException malformed) { - throw conflict("Original local issuer operation is not canonical schema v2"); - } - CanonicalIssuerPartitionReservation reservation = original.reservation(); - var proof = - CanonicalGameplayIssuerBootstrapCoverageRepository - .readInstalledAnchorPartitionProof( - transaction, anchor, reservation.partitionId()); - AccountControlSnapshot accountControl = - readCapturedAccountControl( - operationRow, - abortSource.candidate().identity().accountId(), - abortSource.transition().accountCoverageEvidence()); - Request request = - new Request( - requireUuid(operationRow, "request_id"), - abortSource.transition().transitionId(), - abortSource.candidate().identity(), - null, - null); - requireSameStoredOperation( + dsl.transactionResult(configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + // This reader invokes the installed-anchor source loader, whose snapshot contract + // starts with the global inventory clock. Keep the same clock-before-source order + // used by ordinary registration, abort retry, and release completion. + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + Record operationRow = + transaction.fetchOne( + "SELECT * FROM " + OPERATION + " WHERE issuer_id = ? AND transition_id = ?", + ISSUER, + abortSource.transition().transitionId()); + if (operationRow == null) { + throw conflict( + "Account-aborted first-NEW source has no original local issuer operation"); + } + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, currentState); + byte[] exactOriginal = requireBytes(operationRow, "member_value_bytes"); + CanonicalGameplayIssuerMemberV2Value original; + try { + original = CanonicalGameplayIssuerMemberV2Codec.decode(exactOriginal); + } catch (RuntimeException malformed) { + throw conflict("Original local issuer operation is not canonical schema v2"); + } + CanonicalIssuerPartitionReservation reservation = original.reservation(); + var proof = + CanonicalGameplayIssuerBootstrapCoverageRepository.readInstalledAnchorPartitionProof( + transaction, anchor, reservation.partitionId()); + AccountControlSnapshot accountControl = + readCapturedAccountControl( operationRow, - request, - abortSource.transition(), + abortSource.candidate().identity().accountId(), + abortSource.transition().accountCoverageEvidence()); + Request request = + new Request( + requireUuid(operationRow, "request_id"), + abortSource.transition().transitionId(), + abortSource.candidate().identity(), + null, + null); + requireSameStoredOperation( + operationRow, + request, + abortSource.transition(), + reservation, + anchor, + proof, + currentState, + accountControl, + true); + CanonicalGameplayIssuerMemberV2Value expected = + createMemberValue( + request.candidate(), + abortSource.transition().bindingGeneration(), reservation, anchor, - proof, - currentState, - accountControl, - true); - CanonicalGameplayIssuerMemberV2Value expected = - createMemberValue( - request.candidate(), - abortSource.transition().bindingGeneration(), - reservation, - anchor, - currentState.incarnation(), - requireUuid(operationRow, "operation_id"), - readPositive(operationRow, "operation_fence"), - readPositive(operationRow, "local_member_generation")); - if (!expected.equals(original) - || !Arrays.equals( - exactOriginal, CanonicalGameplayIssuerMemberV2Codec.encode(expected))) { - throw conflict( - "Original issuer member differs from its exact aborted source or anchor"); - } - try { - return new CanonicalGameplayIssuerBindingLocalOperation( - request, - requireUuid(operationRow, "candidate_account_index_fence"), - abortSource.transition(), - readPositive(operationRow, "local_inventory_snapshot_revision"), - reservation, - anchor, - proof, - expected, - requireUuid(operationRow, "operation_id"), - readPositive(operationRow, "operation_fence"), - readPositive(operationRow, "local_member_generation"), - exactOriginal, - requireText(operationRow, "member_value_digest"), - CanonicalGameplayIssuerBindingLocalOperation.Status.valueOf( - requireText(operationRow, "member_status"))); - } catch (RuntimeException malformed) { - throw conflict("Original local issuer operation metadata is malformed"); - } - }); + currentState.incarnation(), + requireUuid(operationRow, "operation_id"), + readPositive(operationRow, "operation_fence"), + readPositive(operationRow, "local_member_generation")); + if (!expected.equals(original) + || !Arrays.equals( + exactOriginal, CanonicalGameplayIssuerMemberV2Codec.encode(expected))) { + throw conflict( + "Original issuer member differs from its exact aborted source or anchor"); + } + try { + return new CanonicalGameplayIssuerBindingLocalOperation( + request, + requireUuid(operationRow, "candidate_account_index_fence"), + abortSource.transition(), + readPositive(operationRow, "local_inventory_snapshot_revision"), + reservation, + anchor, + proof, + expected, + requireUuid(operationRow, "operation_id"), + readPositive(operationRow, "operation_fence"), + readPositive(operationRow, "local_member_generation"), + exactOriginal, + requireText(operationRow, "member_value_digest"), + CanonicalGameplayIssuerBindingLocalOperation.Status.valueOf( + requireText(operationRow, "member_status"))); + } catch (RuntimeException malformed) { + throw conflict("Original local issuer operation metadata is malformed"); + } + }); CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState after = Objects.requireNonNull( currentIssuerStateSource.readFreshCurrentState(), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java index ec49a2dbeb..d7f01e6c0e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java @@ -80,42 +80,39 @@ java.util.Optional prepareNeverAdmittedCapacityMutationWo Objects.requireNonNull(target, "target"); requireNoAmbientTransaction(); boolean reconcileAdd = - dsl.transactionResult( - configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - lockInventoryClock(transaction); - var source = - CanonicalGameplayBindingInventoryRepository.readIssuerCleanupSourceInTransaction( - transaction, target.request().transitionId(), true); - if (!source.neverAdmitted()) - throw unavailable("Capacity cleanup requires a negative terminal"); - Record release = - transaction.fetchOne( - "SELECT * FROM " - + ISSUER_LOCAL_RELEASE - + " WHERE transition_id = ? FOR UPDATE", - target.request().transitionId()); - if (release != null) { - // An exact durable release has already taken over the original capacity intent. - // Replaying ADD would compare its old revision with a later release/retirement. - CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.readOperation( - transaction, - release, - source, - CanonicalGameplayIssuerOriginalMemberSource.ordinary(target)); - return false; - } - Record existing = - transaction.fetchOne( - "SELECT mutation_kind FROM game_session_canonical_issuer_partition_mutation" - + " WHERE owner_operation_id = ? AND mutation_kind IN ('ADD_CAPACITY', 'ADD_BINDING')", - target.operationId()); - if (existing == null) return false; - if (!"ADD_CAPACITY".equals(existing.get("mutation_kind", String.class))) { - throw unavailable("Never-admitted cleanup cannot adopt an issued binding mutation"); - } - return true; - }); + dsl.transactionResult(configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + lockInventoryClock(transaction); + var source = + CanonicalGameplayBindingInventoryRepository.readIssuerCleanupSourceInTransaction( + transaction, target.request().transitionId(), true); + if (!source.neverAdmitted()) + throw unavailable("Capacity cleanup requires a negative terminal"); + Record release = + transaction.fetchOne( + "SELECT * FROM " + ISSUER_LOCAL_RELEASE + " WHERE transition_id = ? FOR UPDATE", + target.request().transitionId()); + if (release != null) { + // An exact durable release has already taken over the original capacity intent. + // Replaying ADD would compare its old revision with a later release/retirement. + CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.readOperation( + transaction, + release, + source, + CanonicalGameplayIssuerOriginalMemberSource.ordinary(target)); + return false; + } + Record existing = + transaction.fetchOne( + "SELECT mutation_kind FROM game_session_canonical_issuer_partition_mutation" + + " WHERE owner_operation_id = ? AND mutation_kind IN ('ADD_CAPACITY', 'ADD_BINDING')", + target.operationId()); + if (existing == null) return false; + if (!"ADD_CAPACITY".equals(existing.get("mutation_kind", String.class))) { + throw unavailable("Never-admitted cleanup cannot adopt an issued binding mutation"); + } + return true; + }); if (!reconcileAdd) return java.util.Optional.empty(); return java.util.Optional.of( readPreparedPartitionWork( @@ -136,22 +133,21 @@ private PreparedPartitionWork readPreparedPartitionWork( var before = readCurrentIssuerState(); requireCurrentSourceMatches(target.anchor(), before); PreparedPartitionWork work = - dsl.transactionResult( - configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - lockInventoryClock(transaction); - CanonicalGameplayIssuerInstalledAnchor anchor = - CanonicalGameplayIssuerBootstrapCoverageRepository - .readInstalledAnchorForBindingPreparationInTransaction(transaction, before); - requireSameAnchor(target.anchor(), anchor); - return prepareInTransaction( - transaction, - target, - anchor, - before, - prepareAddMutation, - requireCurrentTargetAccountControl); - }); + dsl.transactionResult(configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + lockInventoryClock(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, before); + requireSameAnchor(target.anchor(), anchor); + return prepareInTransaction( + transaction, + target, + anchor, + before, + prepareAddMutation, + requireCurrentTargetAccountControl); + }); var after = readCurrentIssuerState(); requireSameCurrentIssuerState(before, after); requireCurrentSourceMatches(work.anchor(), after); @@ -201,10 +197,9 @@ void completePhysicalMutation( Objects.requireNonNull(mutation, "mutation"); Objects.requireNonNull(exactReadbackFieldSetBytes, "exactReadbackFieldSetBytes"); requireNoAmbientTransaction(); - dsl.transaction( - configuration -> - CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( - org.jooq.impl.DSL.using(configuration), mutation, exactReadbackFieldSetBytes)); + dsl.transaction(configuration -> + CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( + org.jooq.impl.DSL.using(configuration), mutation, exactReadbackFieldSetBytes)); } private PreparedPartitionWork prepareInTransaction( @@ -463,19 +458,17 @@ private PreparedPartitionWork prepareInTransaction( private static int countCapacity(Map fields) { return (int) fields.entrySet().stream() - .filter( - entry -> - entry - .getKey() - .startsWith( - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec - .RESERVATION_FIELD_PREFIX)) - .filter( - entry -> - CanonicalGameplayIssuerMemberV2Codec.decode(entry.getValue()) - .reservation() - .lifecycle() - != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) + .filter(entry -> + entry + .getKey() + .startsWith( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec + .RESERVATION_FIELD_PREFIX)) + .filter(entry -> + CanonicalGameplayIssuerMemberV2Codec.decode(entry.getValue()) + .reservation() + .lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) .count(); } @@ -1825,11 +1818,10 @@ int effectiveBaselineCapacityCount() { int effectiveBaselineReservationCount() { return (int) baselineFields.keySet().stream() - .filter( - field -> - field.startsWith( - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec - .RESERVATION_FIELD_PREFIX)) + .filter(field -> + field.startsWith( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec + .RESERVATION_FIELD_PREFIX)) .count(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java index 2b8d62a0c4..f91ef1f827 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java @@ -280,30 +280,24 @@ private byte[] readExactPhysicalState( int registeredCapacityCount = Math.toIntExact( work.localEntries().stream() - .filter( - entry -> - entry - .memberValue() - .reservation() - .partitionId() - .equals( - work.targetOperation() - .memberValue() - .reservation() - .partitionId()) - && entry.countsTowardCapacity()) - .count()); - int registeredReservationCount = - Math.toIntExact( - work.localEntries().stream() - .filter( - entry -> - entry + .filter(entry -> + entry .memberValue() .reservation() .partitionId() .equals( - work.targetSource().memberValue().reservation().partitionId())) + work.targetOperation().memberValue().reservation().partitionId()) + && entry.countsTowardCapacity()) + .count()); + int registeredReservationCount = + Math.toIntExact( + work.localEntries().stream() + .filter(entry -> + entry + .memberValue() + .reservation() + .partitionId() + .equals(work.targetSource().memberValue().reservation().partitionId())) .count()); if (BigInteger.valueOf(physicalCapacityCount).compareTo(work.anchor().partitionCapacity()) > 0 || physicalCapacityCount < baselineCapacityCount + (target.countsTowardCapacity() ? 1 : 0) @@ -377,13 +371,12 @@ private static byte[][] scriptArguments( } List entries = work.localEntries().stream() - .filter( - entry -> - entry - .memberValue() - .reservation() - .partitionId() - .equals(work.targetSource().memberValue().reservation().partitionId())) + .filter(entry -> + entry + .memberValue() + .reservation() + .partitionId() + .equals(work.targetSource().memberValue().reservation().partitionId())) .sorted(java.util.Comparator.comparing(entry -> entry.operationId().toString())) .toList(); arguments.add(ascii(Integer.toString(entries.size()))); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java index 974604d21b..73963265d8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.java @@ -56,92 +56,89 @@ CanonicalGameplayIssuerBindingLocalReleaseOperation prepareOrResume(UUID transit var issuerStateBefore = readCurrentIssuerState(); var original = originalSources.read(sourceBefore); var operation = - dsl.transactionResult( - configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - BigInteger currentRevision = - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - var source = - CanonicalGameplayBindingInventoryRepository.readIssuerCleanupSourceInTransaction( - transaction, transitionId, true); - requireSameAbortSource(sourceBefore, source); - Record existing = - transaction.fetchOne( - "SELECT * FROM " + RELEASE + " WHERE transition_id = ? FOR UPDATE", - transitionId); - if (existing != null) return readOperation(transaction, existing, source, original); - if (source.reservation().lifecycle() - != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING - || !sameOperationSource(original, source)) { - throw conflict("Issuer release requires its exact pending local registration"); - } - BigInteger priorRevision = source.transition().inventoryRevision(); - if (currentRevision.compareTo(priorRevision) < 0) { - throw conflict( - "Inventory clock regressed behind the retained Account-abort source"); - } - BigInteger sourceRevision = currentRevision.add(BigInteger.ONE); - requireCounterLimit(sourceRevision, "releasePreparationInventoryRevision"); - advanceAbortSourceRevision( - transaction, source, priorRevision, sourceRevision, currentRevision); - source = - CanonicalGameplayBindingInventoryRepository.readIssuerCleanupSourceInTransaction( - transaction, transitionId, false); - var counters = - CanonicalGameplayIssuerBindingLocalOperationRepository.allocateLocalCounters( - transaction, - original.anchor(), - withLifecycleAndRevision( - original.reservation(), - CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING, - sourceRevision)); - UUID releaseId = freshNonNilUuid(); - var releasedValue = - createReleasedValue( - original.memberValue(), - sourceRevision, - releaseId, - counters.operationFence(), - counters.localMemberGeneration()); - byte[] releasedBytes = CanonicalGameplayIssuerMemberV2Codec.encode(releasedValue); - byte[] originalBytes = original.exactMemberValueBytes(); - insertRelease( + dsl.transactionResult(configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + BigInteger currentRevision = + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + var source = + CanonicalGameplayBindingInventoryRepository.readIssuerCleanupSourceInTransaction( + transaction, transitionId, true); + requireSameAbortSource(sourceBefore, source); + Record existing = + transaction.fetchOne( + "SELECT * FROM " + RELEASE + " WHERE transition_id = ? FOR UPDATE", transitionId); + if (existing != null) return readOperation(transaction, existing, source, original); + if (source.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING + || !sameOperationSource(original, source)) { + throw conflict("Issuer release requires its exact pending local registration"); + } + BigInteger priorRevision = source.transition().inventoryRevision(); + if (currentRevision.compareTo(priorRevision) < 0) { + throw conflict("Inventory clock regressed behind the retained Account-abort source"); + } + BigInteger sourceRevision = currentRevision.add(BigInteger.ONE); + requireCounterLimit(sourceRevision, "releasePreparationInventoryRevision"); + advanceAbortSourceRevision( + transaction, source, priorRevision, sourceRevision, currentRevision); + source = + CanonicalGameplayBindingInventoryRepository.readIssuerCleanupSourceInTransaction( + transaction, transitionId, false); + var counters = + CanonicalGameplayIssuerBindingLocalOperationRepository.allocateLocalCounters( transaction, - source, - original, + original.anchor(), + withLifecycleAndRevision( + original.reservation(), + CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING, + sourceRevision)); + UUID releaseId = freshNonNilUuid(); + var releasedValue = + createReleasedValue( + original.memberValue(), + sourceRevision, releaseId, counters.operationFence(), - counters.localMemberGeneration(), - sourceRevision, - originalBytes, - releasedBytes); - Record saved = - transaction.fetchOne( - "SELECT * FROM " + RELEASE + " WHERE operation_id = ? FOR UPDATE", releaseId); - if (saved == null) throw conflict("Issuer release operation was not retained"); - byte[] mutationIntent = - CanonicalGameplayIssuerPartitionMutationRepository.encodeIntendedChange( - CanonicalGameplayIssuerPartitionMutation.Kind.RELEASE, - releaseId, - original.reservation().partitionId(), - original.operationId().toString().getBytes(StandardCharsets.US_ASCII), - source - .reservation() - .reservationId() - .toString() - .getBytes(StandardCharsets.US_ASCII), - source.transition().bindingRef().bytes(), - originalBytes, - releasedBytes, - sourceRevision.toString().getBytes(StandardCharsets.US_ASCII)); - CanonicalGameplayIssuerPartitionMutationRepository.prepareInTransaction( - transaction, + counters.localMemberGeneration()); + byte[] releasedBytes = CanonicalGameplayIssuerMemberV2Codec.encode(releasedValue); + byte[] originalBytes = original.exactMemberValueBytes(); + insertRelease( + transaction, + source, + original, + releaseId, + counters.operationFence(), + counters.localMemberGeneration(), + sourceRevision, + originalBytes, + releasedBytes); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + RELEASE + " WHERE operation_id = ? FOR UPDATE", releaseId); + if (saved == null) throw conflict("Issuer release operation was not retained"); + byte[] mutationIntent = + CanonicalGameplayIssuerPartitionMutationRepository.encodeIntendedChange( CanonicalGameplayIssuerPartitionMutation.Kind.RELEASE, releaseId, original.reservation().partitionId(), - mutationIntent); - return readOperation(transaction, saved, source, original); - }); + original.operationId().toString().getBytes(StandardCharsets.US_ASCII), + source + .reservation() + .reservationId() + .toString() + .getBytes(StandardCharsets.US_ASCII), + source.transition().bindingRef().bytes(), + originalBytes, + releasedBytes, + sourceRevision.toString().getBytes(StandardCharsets.US_ASCII)); + CanonicalGameplayIssuerPartitionMutationRepository.prepareInTransaction( + transaction, + CanonicalGameplayIssuerPartitionMutation.Kind.RELEASE, + releaseId, + original.reservation().partitionId(), + mutationIntent); + return readOperation(transaction, saved, source, original); + }); requireSameCurrentIssuerState(issuerStateBefore, readCurrentIssuerState()); requireSameAbortIdentity( sourceBefore, inventoryRepository.readIssuerCleanupSource(transitionId)); @@ -158,30 +155,27 @@ CanonicalGameplayIssuerBindingLocalReleaseOperation readCommittedRelease(UUID tr var issuerStateBefore = readCurrentIssuerState(); CanonicalGameplayIssuerOriginalMemberSource original = originalSources.read(sourceBefore); CanonicalGameplayIssuerBindingLocalReleaseOperation committed = - dsl.transactionResult( - configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - CanonicalGameplayIssuerCleanupSource source = - CanonicalGameplayBindingInventoryRepository.readIssuerCleanupSourceInTransaction( - transaction, transitionId, false); - requireSameAbortSource(sourceBefore, source); - Record existing = - transaction.fetchOne( - "SELECT * FROM " + RELEASE + " WHERE transition_id = ?", transitionId); - if (existing == null) { - throw conflict( - "Physical retirement requires an existing committed release receipt"); - } - CanonicalGameplayIssuerBindingLocalReleaseOperation operation = - readOperation(transaction, existing, source, original); - if (operation.status() - != CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED) { - throw conflict( - "Physical retirement requires a committed original RELEASED receipt"); - } - return operation; - }); + dsl.transactionResult(configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + CanonicalGameplayIssuerCleanupSource source = + CanonicalGameplayBindingInventoryRepository.readIssuerCleanupSourceInTransaction( + transaction, transitionId, false); + requireSameAbortSource(sourceBefore, source); + Record existing = + transaction.fetchOne( + "SELECT * FROM " + RELEASE + " WHERE transition_id = ?", transitionId); + if (existing == null) { + throw conflict("Physical retirement requires an existing committed release receipt"); + } + CanonicalGameplayIssuerBindingLocalReleaseOperation operation = + readOperation(transaction, existing, source, original); + if (operation.status() + != CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED) { + throw conflict("Physical retirement requires a committed original RELEASED receipt"); + } + return operation; + }); requireSameCurrentIssuerState(issuerStateBefore, readCurrentIssuerState()); requireSameAbortSource( committed.cleanupSource(), inventoryRepository.readIssuerCleanupSource(transitionId)); @@ -202,183 +196,179 @@ CanonicalGameplayIssuerBindingLocalReleaseOperation completeWithReadback( String readbackDigest = CanonicalGameplayIssuerMemberV2Codec.sha256(readbackBytes); var issuerStateBefore = readCurrentIssuerState(); var completed = - dsl.transactionResult( - configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - BigInteger currentRevision = - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - UUID transitionId = expected.cleanupSource().transition().transitionId(); - var source = - CanonicalGameplayBindingInventoryRepository.readIssuerCleanupSourceInTransaction( - transaction, transitionId, true); - requireExactReleaseSource(expected, source); - Record releaseRow = - transaction.fetchOne( - "SELECT * FROM " + RELEASE + " WHERE operation_id = ? FOR UPDATE", - expected.operationId()); - if (releaseRow == null) throw conflict("SQL issuer release operation disappeared"); - var current = - readOperation(transaction, releaseRow, source, expected.originalSource()); - requireSameOperation(expected, current); - if (current.status() - == CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED) { - verifyReadbackMatchesOperation(current, readbackBytes, readbackDigest); - CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( - transaction, current.physicalMutation(), readbackBytes); - return current; - } - if (source.reservation().lifecycle() - != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING) { - throw conflict( - "Pending issuer release no longer has its exact RELEASE_PENDING source"); - } - if (currentRevision.compareTo(current.sourceInventoryRevision()) < 0) { - throw conflict( - "Inventory clock regressed behind the durable issuer release preparation"); - } - verifyReadbackMatchesOperation(current, readbackBytes, readbackDigest); - CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( - transaction, current.physicalMutation(), readbackBytes); - BigInteger completionRevision = currentRevision.add(BigInteger.ONE); - requireCounterLimit(completionRevision, "completionInventoryRevision"); - requireOne( - transaction.execute( - "UPDATE " - + RELEASE - + " SET status = 'RELEASED', physical_readback_field_set_bytes = ?," - + " physical_readback_field_set_digest = ?, completion_inventory_revision = ?," - + " completed_at = CURRENT_TIMESTAMP WHERE operation_id = ?" - + " AND status = 'PENDING_PHYSICAL_PROOF' AND source_inventory_revision = ?", - readbackBytes, - readbackDigest, - decimal(completionRevision), - current.operationId(), - decimal(current.sourceInventoryRevision())), - "Issuer release completion lost its guarded SQL operation compare-and-set"); - requireOne( - transaction.execute( - "UPDATE " - + ISSUER_OBLIGATION - + " SET status = 'RELEASED', local_release_operation_id = ?, inventory_revision = ?" - + " WHERE transition_id = ? AND binding_ref = ? AND reservation_id = ?" - + " AND status = 'REQUIRED' AND local_release_operation_id IS NULL" - + " AND inventory_revision = ?", - current.operationId(), - decimal(completionRevision), - transitionId, - source.transition().bindingRef().bytes(), - source.reservation().reservationId(), - decimal(current.sourceInventoryRevision())), - "Physical issuer release lost its exact local V29 obligation compare-and-set"); - requireOne( - transaction.execute( - "UPDATE " - + RESERVATION - + " SET lifecycle = 'RELEASED', inventory_revision = ?" - + " WHERE reservation_id = ? AND transition_id = ? AND lifecycle = 'RELEASE_PENDING'" - + " AND inventory_revision = ? AND binding_ref = ? AND binding_generation = ?" - + " AND reservation_fence = ? AND issuer_coverage_operation_id = ?" - + " AND issuer_coverage_operation_fence = ? AND coverage_fence = ?" - + " AND inventory_snapshot_revision = ? AND account_id = ? AND tenant_id = ?" - + " AND playable_state_namespace_id = ? AND character_id = ?" - + " AND game_instance_id = ? AND runtime_game_instance_id = ? AND session_id = ?" - + " AND region_id = ? AND region_epoch = ? AND issuer_id = ? AND issuer_auth_generation = ?", - decimal(completionRevision), - source.reservation().reservationId(), - transitionId, - decimal(current.sourceInventoryRevision()), - source.transition().bindingRef().bytes(), - decimal(source.transition().bindingGeneration()), - source.reservation().reservationFence(), - source.reservation().issuerCoverageOperationId(), - decimal(source.reservation().issuerCoverageOperationFence()), - decimal(source.reservation().coverageFence()), - decimal(source.reservation().inventorySnapshotRevision()), - source.candidate().identity().accountId(), - source.candidate().identity().tenantId(), - source.candidate().identity().playableStateNamespaceId(), - source.candidate().identity().characterId(), - source.candidate().identity().gameInstanceId(), - source.candidate().identity().runtimeGameInstanceId(), - source.candidate().identity().sessionId(), - source.candidate().identity().regionId(), - decimal(source.candidate().identity().regionEpoch()), - source.candidate().identity().issuerId(), - decimal(source.candidate().identity().issuerAuthGeneration())), - "Issuer release lost its exact original reservation compare-and-set"); - requireOne( - transaction.execute( - "UPDATE " - + INVENTORY - + " SET inventory_revision = ?" - + " WHERE binding_ref = ? AND transition_id = ?" - + " AND lifecycle = 'TERMINAL_UNRESOLVED' AND inventory_revision = ?" - + " AND binding_generation = ? AND issuer_reservation_id = ?", - decimal(completionRevision), - source.transition().bindingRef().bytes(), - transitionId, - decimal(current.sourceInventoryRevision()), - decimal(source.transition().bindingGeneration()), - source.reservation().reservationId()), - "Issuer release lost its retained unresolved candidate compare-and-set"); - requireOne( - transaction.execute( - "UPDATE " - + TRANSITION - + " SET inventory_revision = ?" - + " WHERE transition_id = ? AND status = 'ABORTED'" - + " AND COALESCE(admission_orphan_cleanup_id, original_new_abandonment_orphan_cleanup_id) = ? AND inventory_revision = ?" - + " AND candidate_binding_ref = ? AND candidate_binding_generation = ?" - + " AND issuer_reservation_id = ?", - decimal(completionRevision), - transitionId, - source.orphanCleanupId(), - decimal(current.sourceInventoryRevision()), - source.transition().bindingRef().bytes(), - decimal(source.transition().bindingGeneration()), - source.reservation().reservationId()), - "Issuer release lost its immutable Account-abort source revision compare-and-set"); - requireOne( - transaction.execute( - "UPDATE " - + ACCOUNT_OBLIGATION - + " SET inventory_revision = ?" - + " WHERE transition_id = ? AND inventory_revision = ?", - decimal(completionRevision), - transitionId, - decimal(current.sourceInventoryRevision())), - "Issuer release lost its retained Account obligation revision compare-and-set"); - requireOne( - transaction.execute( - "UPDATE " - + REGION_OBLIGATION - + " SET inventory_revision = ?" - + " WHERE transition_id = ? AND inventory_revision = ?", - decimal(completionRevision), - transitionId, - decimal(current.sourceInventoryRevision())), - "Issuer release lost its retained region obligation revision compare-and-set"); - requireOne( - transaction.execute( - "UPDATE " - + INVENTORY_CLOCK - + " SET inventory_revision = ?" - + " WHERE singleton_id = 1 AND inventory_revision = ?", - decimal(completionRevision), - decimal(currentRevision)), - "Issuer release lost the current inventory-clock compare-and-set"); - var completedSource = - CanonicalGameplayBindingInventoryRepository.readIssuerCleanupSourceInTransaction( - transaction, transitionId, false); - Record completedRow = - transaction.fetchOne( - "SELECT * FROM " + RELEASE + " WHERE operation_id = ?", - expected.operationId()); - if (completedRow == null) - throw conflict("Released issuer operation disappeared after completion"); - return readOperation( - transaction, completedRow, completedSource, expected.originalSource()); - }); + dsl.transactionResult(configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + BigInteger currentRevision = + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + UUID transitionId = expected.cleanupSource().transition().transitionId(); + var source = + CanonicalGameplayBindingInventoryRepository.readIssuerCleanupSourceInTransaction( + transaction, transitionId, true); + requireExactReleaseSource(expected, source); + Record releaseRow = + transaction.fetchOne( + "SELECT * FROM " + RELEASE + " WHERE operation_id = ? FOR UPDATE", + expected.operationId()); + if (releaseRow == null) throw conflict("SQL issuer release operation disappeared"); + var current = readOperation(transaction, releaseRow, source, expected.originalSource()); + requireSameOperation(expected, current); + if (current.status() + == CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED) { + verifyReadbackMatchesOperation(current, readbackBytes, readbackDigest); + CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( + transaction, current.physicalMutation(), readbackBytes); + return current; + } + if (source.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASE_PENDING) { + throw conflict("Pending issuer release no longer has its exact RELEASE_PENDING source"); + } + if (currentRevision.compareTo(current.sourceInventoryRevision()) < 0) { + throw conflict( + "Inventory clock regressed behind the durable issuer release preparation"); + } + verifyReadbackMatchesOperation(current, readbackBytes, readbackDigest); + CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( + transaction, current.physicalMutation(), readbackBytes); + BigInteger completionRevision = currentRevision.add(BigInteger.ONE); + requireCounterLimit(completionRevision, "completionInventoryRevision"); + requireOne( + transaction.execute( + "UPDATE " + + RELEASE + + " SET status = 'RELEASED', physical_readback_field_set_bytes = ?," + + " physical_readback_field_set_digest = ?, completion_inventory_revision = ?," + + " completed_at = CURRENT_TIMESTAMP WHERE operation_id = ?" + + " AND status = 'PENDING_PHYSICAL_PROOF' AND source_inventory_revision = ?", + readbackBytes, + readbackDigest, + decimal(completionRevision), + current.operationId(), + decimal(current.sourceInventoryRevision())), + "Issuer release completion lost its guarded SQL operation compare-and-set"); + requireOne( + transaction.execute( + "UPDATE " + + ISSUER_OBLIGATION + + " SET status = 'RELEASED', local_release_operation_id = ?, inventory_revision = ?" + + " WHERE transition_id = ? AND binding_ref = ? AND reservation_id = ?" + + " AND status = 'REQUIRED' AND local_release_operation_id IS NULL" + + " AND inventory_revision = ?", + current.operationId(), + decimal(completionRevision), + transitionId, + source.transition().bindingRef().bytes(), + source.reservation().reservationId(), + decimal(current.sourceInventoryRevision())), + "Physical issuer release lost its exact local V29 obligation compare-and-set"); + requireOne( + transaction.execute( + "UPDATE " + + RESERVATION + + " SET lifecycle = 'RELEASED', inventory_revision = ?" + + " WHERE reservation_id = ? AND transition_id = ? AND lifecycle = 'RELEASE_PENDING'" + + " AND inventory_revision = ? AND binding_ref = ? AND binding_generation = ?" + + " AND reservation_fence = ? AND issuer_coverage_operation_id = ?" + + " AND issuer_coverage_operation_fence = ? AND coverage_fence = ?" + + " AND inventory_snapshot_revision = ? AND account_id = ? AND tenant_id = ?" + + " AND playable_state_namespace_id = ? AND character_id = ?" + + " AND game_instance_id = ? AND runtime_game_instance_id = ? AND session_id = ?" + + " AND region_id = ? AND region_epoch = ? AND issuer_id = ? AND issuer_auth_generation = ?", + decimal(completionRevision), + source.reservation().reservationId(), + transitionId, + decimal(current.sourceInventoryRevision()), + source.transition().bindingRef().bytes(), + decimal(source.transition().bindingGeneration()), + source.reservation().reservationFence(), + source.reservation().issuerCoverageOperationId(), + decimal(source.reservation().issuerCoverageOperationFence()), + decimal(source.reservation().coverageFence()), + decimal(source.reservation().inventorySnapshotRevision()), + source.candidate().identity().accountId(), + source.candidate().identity().tenantId(), + source.candidate().identity().playableStateNamespaceId(), + source.candidate().identity().characterId(), + source.candidate().identity().gameInstanceId(), + source.candidate().identity().runtimeGameInstanceId(), + source.candidate().identity().sessionId(), + source.candidate().identity().regionId(), + decimal(source.candidate().identity().regionEpoch()), + source.candidate().identity().issuerId(), + decimal(source.candidate().identity().issuerAuthGeneration())), + "Issuer release lost its exact original reservation compare-and-set"); + requireOne( + transaction.execute( + "UPDATE " + + INVENTORY + + " SET inventory_revision = ?" + + " WHERE binding_ref = ? AND transition_id = ?" + + " AND lifecycle = 'TERMINAL_UNRESOLVED' AND inventory_revision = ?" + + " AND binding_generation = ? AND issuer_reservation_id = ?", + decimal(completionRevision), + source.transition().bindingRef().bytes(), + transitionId, + decimal(current.sourceInventoryRevision()), + decimal(source.transition().bindingGeneration()), + source.reservation().reservationId()), + "Issuer release lost its retained unresolved candidate compare-and-set"); + requireOne( + transaction.execute( + "UPDATE " + + TRANSITION + + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND status = 'ABORTED'" + + " AND COALESCE(admission_orphan_cleanup_id, original_new_abandonment_orphan_cleanup_id) = ? AND inventory_revision = ?" + + " AND candidate_binding_ref = ? AND candidate_binding_generation = ?" + + " AND issuer_reservation_id = ?", + decimal(completionRevision), + transitionId, + source.orphanCleanupId(), + decimal(current.sourceInventoryRevision()), + source.transition().bindingRef().bytes(), + decimal(source.transition().bindingGeneration()), + source.reservation().reservationId()), + "Issuer release lost its immutable Account-abort source revision compare-and-set"); + requireOne( + transaction.execute( + "UPDATE " + + ACCOUNT_OBLIGATION + + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND inventory_revision = ?", + decimal(completionRevision), + transitionId, + decimal(current.sourceInventoryRevision())), + "Issuer release lost its retained Account obligation revision compare-and-set"); + requireOne( + transaction.execute( + "UPDATE " + + REGION_OBLIGATION + + " SET inventory_revision = ?" + + " WHERE transition_id = ? AND inventory_revision = ?", + decimal(completionRevision), + transitionId, + decimal(current.sourceInventoryRevision())), + "Issuer release lost its retained region obligation revision compare-and-set"); + requireOne( + transaction.execute( + "UPDATE " + + INVENTORY_CLOCK + + " SET inventory_revision = ?" + + " WHERE singleton_id = 1 AND inventory_revision = ?", + decimal(completionRevision), + decimal(currentRevision)), + "Issuer release lost the current inventory-clock compare-and-set"); + var completedSource = + CanonicalGameplayBindingInventoryRepository.readIssuerCleanupSourceInTransaction( + transaction, transitionId, false); + Record completedRow = + transaction.fetchOne( + "SELECT * FROM " + RELEASE + " WHERE operation_id = ?", expected.operationId()); + if (completedRow == null) + throw conflict("Released issuer operation disappeared after completion"); + return readOperation( + transaction, completedRow, completedSource, expected.originalSource()); + }); requireSameCurrentIssuerState(issuerStateBefore, readCurrentIssuerState()); CanonicalGameplayIssuerCleanupSource sourceAfter = inventoryRepository.readIssuerCleanupSource( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java index d06f72ba9d..0ba2b2b62e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.java @@ -241,26 +241,23 @@ private byte[] readExactPhysicalState( int registeredReservations = Math.toIntExact( work.localEntries().stream() - .filter( - entry -> - entry - .memberValue() - .reservation() - .partitionId() - .equals(operation.releasedMemberValue().reservation().partitionId())) + .filter(entry -> + entry + .memberValue() + .reservation() + .partitionId() + .equals(operation.releasedMemberValue().reservation().partitionId())) .count()); int registeredBindings = Math.toIntExact( work.localEntries().stream() - .filter( - entry -> - entry - .memberValue() - .reservation() - .partitionId() - .equals( - operation.releasedMemberValue().reservation().partitionId()) - && entry.bindingPresent()) + .filter(entry -> + entry + .memberValue() + .reservation() + .partitionId() + .equals(operation.releasedMemberValue().reservation().partitionId()) + && entry.bindingPresent()) .count()); if (BigInteger.valueOf(physicalCapacity).compareTo(work.anchor().partitionCapacity()) > 0 || BigInteger.valueOf(physicalCapacity).compareTo(work.partitionCapacity()) > 0 @@ -297,13 +294,12 @@ private static byte[][] scriptArguments( } List entries = work.localEntries().stream() - .filter( - entry -> - entry - .memberValue() - .reservation() - .partitionId() - .equals(operation.releasedMemberValue().reservation().partitionId())) + .filter(entry -> + entry + .memberValue() + .reservation() + .partitionId() + .equals(operation.releasedMemberValue().reservation().partitionId())) .sorted(java.util.Comparator.comparing(entry -> entry.operationId().toString())) .toList(); args.add(ascii(Integer.toString(entries.size()))); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java index 53b9993dfd..a90376e2bc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementOperationRepository.java @@ -56,51 +56,47 @@ CanonicalGameplayIssuerBindingLocalRetirementOperation prepareOrResume(UUID tran var before = readCurrentIssuerState(); requireSourceMatchesRelease(release.cleanupSource(), release); CanonicalGameplayIssuerBindingLocalRetirementOperation prepared = - dsl.transactionResult( - configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - CanonicalGameplayIssuerCleanupSource currentSource = - CanonicalGameplayBindingInventoryRepository.readIssuerCleanupSourceInTransaction( - transaction, transitionId, true); - requireSameReleaseSource(release.cleanupSource(), currentSource, release); - requireExactCommittedReleaseRow(transaction, release); - protectCurrentReferences(transaction, release); - BigInteger partitionId = release.releasedMemberValue().reservation().partitionId(); - Record existing = - transaction.fetchOne( - "SELECT * FROM " + RETIREMENT + " WHERE release_operation_id = ? FOR UPDATE", - release.operationId()); - if (existing != null) return readOperation(transaction, existing, release); + dsl.transactionResult(configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerCleanupSource currentSource = + CanonicalGameplayBindingInventoryRepository.readIssuerCleanupSourceInTransaction( + transaction, transitionId, true); + requireSameReleaseSource(release.cleanupSource(), currentSource, release); + requireExactCommittedReleaseRow(transaction, release); + protectCurrentReferences(transaction, release); + BigInteger partitionId = release.releasedMemberValue().reservation().partitionId(); + Record existing = + transaction.fetchOne( + "SELECT * FROM " + RETIREMENT + " WHERE release_operation_id = ? FOR UPDATE", + release.operationId()); + if (existing != null) return readOperation(transaction, existing, release); - CanonicalGameplayIssuerPartitionMutationRepository.PartitionMutationHead head = - CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( - transaction, - release.originalSource().anchor().bootstrapOperationId(), - partitionId); - if (head.pendingMutationId() != null) { - throw conflict("Another same-partition mutation is unresolved before retirement"); - } - UUID retirementId = freshNonNilUuid(); - byte[] intendedChange = encodeRetirementIntent(retirementId, release); - CanonicalGameplayIssuerPartitionMutation mutation = - CanonicalGameplayIssuerPartitionMutationRepository.prepareInTransaction( - transaction, - CanonicalGameplayIssuerPartitionMutation.Kind.RETIRE, - retirementId, - partitionId, - intendedChange); - insertRetirement(transaction, retirementId, release, mutation); - Record saved = - transaction.fetchOne( - "SELECT * FROM " - + RETIREMENT - + " WHERE retirement_operation_id = ? FOR UPDATE", - retirementId); - if (saved == null) - throw conflict("Pending issuer retirement intent was not retained"); - return readOperation(transaction, saved, release); - }); + CanonicalGameplayIssuerPartitionMutationRepository.PartitionMutationHead head = + CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( + transaction, + release.originalSource().anchor().bootstrapOperationId(), + partitionId); + if (head.pendingMutationId() != null) { + throw conflict("Another same-partition mutation is unresolved before retirement"); + } + UUID retirementId = freshNonNilUuid(); + byte[] intendedChange = encodeRetirementIntent(retirementId, release); + CanonicalGameplayIssuerPartitionMutation mutation = + CanonicalGameplayIssuerPartitionMutationRepository.prepareInTransaction( + transaction, + CanonicalGameplayIssuerPartitionMutation.Kind.RETIRE, + retirementId, + partitionId, + intendedChange); + insertRetirement(transaction, retirementId, release, mutation); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + RETIREMENT + " WHERE retirement_operation_id = ? FOR UPDATE", + retirementId); + if (saved == null) throw conflict("Pending issuer retirement intent was not retained"); + return readOperation(transaction, saved, release); + }); requireSameCurrentIssuerState( before, readCurrentIssuerState(), prepared.release().originalSource().anchor()); CanonicalGameplayIssuerBindingLocalReleaseOperation after = @@ -113,28 +109,27 @@ CanonicalGameplayIssuerBindingLocalRetirementOperation prepareOrResume(UUID tran private CanonicalGameplayIssuerBindingLocalRetirementOperation readCompletedRetirement( UUID transitionId) { requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - // The release has a unique transition key; its operation is the retirement's unique - // release key. Resolve those two point identities instead of filtering retained history. - Record release = - transaction.fetchOne( - "SELECT operation_id FROM " - + RELEASE - + " WHERE transition_id = ? AND issuer_id = ? AND status = 'RELEASED'", - transitionId, - ISSUER); - if (release == null) return null; - Record retirement = - transaction.fetchOne( - "SELECT * FROM " - + RETIREMENT - + " WHERE release_operation_id = ? AND status = 'RETIRED'", - uuid(release, "operation_id")); - if (retirement == null) return null; - return readCompletedRetirementInTransaction(transaction, retirement); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + // The release has a unique transition key; its operation is the retirement's unique + // release key. Resolve those two point identities instead of filtering retained history. + Record release = + transaction.fetchOne( + "SELECT operation_id FROM " + + RELEASE + + " WHERE transition_id = ? AND issuer_id = ? AND status = 'RELEASED'", + transitionId, + ISSUER); + if (release == null) return null; + Record retirement = + transaction.fetchOne( + "SELECT * FROM " + + RETIREMENT + + " WHERE release_operation_id = ? AND status = 'RETIRED'", + uuid(release, "operation_id")); + if (retirement == null) return null; + return readCompletedRetirementInTransaction(transaction, retirement); + }); } static CanonicalGameplayIssuerBindingLocalRetirementOperation @@ -459,58 +454,55 @@ CanonicalGameplayIssuerBindingLocalRetirementOperation completeWithReadback( } var before = readCurrentIssuerState(); CanonicalGameplayIssuerBindingLocalRetirementOperation completed = - dsl.transactionResult( - configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - CanonicalGameplayIssuerBindingLocalReleaseOperation release = expected.release(); - CanonicalGameplayIssuerCleanupSource source = - CanonicalGameplayBindingInventoryRepository.readIssuerCleanupSourceInTransaction( - transaction, release.cleanupSource().transition().transitionId(), true); - requireSameReleaseSource(release.cleanupSource(), source, release); - requireExactCommittedReleaseRow(transaction, release); - protectCurrentReferences(transaction, release); - Record row = - transaction.fetchOne( - "SELECT * FROM " - + RETIREMENT - + " WHERE retirement_operation_id = ? FOR UPDATE", - expected.operationId()); - if (row == null) throw conflict("Pending issuer retirement disappeared"); - CanonicalGameplayIssuerBindingLocalRetirementOperation current = - readOperation(transaction, row, release); - requireSameRetirement(expected, current); - if (current.status() - == CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED) { - verifyExactAbsence(current, exactBytes, exactDigest); - CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( - transaction, current.physicalMutation(), exactBytes); - return current; - } - CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( - transaction, current.physicalMutation(), exactBytes); - int updated = - transaction.execute( - "UPDATE " - + RETIREMENT - + " SET status = 'RETIRED', exact_absence_readback_field_set_bytes = ?" - + ", exact_absence_readback_field_set_digest = ?, completed_at = CURRENT_TIMESTAMP" - + " WHERE retirement_operation_id = ? AND status = 'PENDING_PHYSICAL_PROOF'" - + " AND physical_mutation_id = ? AND expected_revision = ? AND successor_revision = ?", - exactBytes, - exactDigest, - current.operationId(), - current.physicalMutation().mutationId(), - current.physicalMutation().expectedRevision(), - current.physicalMutation().successorRevision()); - if (updated != 1) throw conflict("Issuer retirement proof compare-and-set refused"); - Record saved = - transaction.fetchOne( - "SELECT * FROM " + RETIREMENT + " WHERE retirement_operation_id = ?", - current.operationId()); - if (saved == null) throw conflict("Committed issuer retirement proof is unreadable"); - return readOperation(transaction, saved, release); - }); + dsl.transactionResult(configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerBindingLocalReleaseOperation release = expected.release(); + CanonicalGameplayIssuerCleanupSource source = + CanonicalGameplayBindingInventoryRepository.readIssuerCleanupSourceInTransaction( + transaction, release.cleanupSource().transition().transitionId(), true); + requireSameReleaseSource(release.cleanupSource(), source, release); + requireExactCommittedReleaseRow(transaction, release); + protectCurrentReferences(transaction, release); + Record row = + transaction.fetchOne( + "SELECT * FROM " + RETIREMENT + " WHERE retirement_operation_id = ? FOR UPDATE", + expected.operationId()); + if (row == null) throw conflict("Pending issuer retirement disappeared"); + CanonicalGameplayIssuerBindingLocalRetirementOperation current = + readOperation(transaction, row, release); + requireSameRetirement(expected, current); + if (current.status() + == CanonicalGameplayIssuerBindingLocalRetirementOperation.Status.RETIRED) { + verifyExactAbsence(current, exactBytes, exactDigest); + CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( + transaction, current.physicalMutation(), exactBytes); + return current; + } + CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( + transaction, current.physicalMutation(), exactBytes); + int updated = + transaction.execute( + "UPDATE " + + RETIREMENT + + " SET status = 'RETIRED', exact_absence_readback_field_set_bytes = ?" + + ", exact_absence_readback_field_set_digest = ?, completed_at = CURRENT_TIMESTAMP" + + " WHERE retirement_operation_id = ? AND status = 'PENDING_PHYSICAL_PROOF'" + + " AND physical_mutation_id = ? AND expected_revision = ? AND successor_revision = ?", + exactBytes, + exactDigest, + current.operationId(), + current.physicalMutation().mutationId(), + current.physicalMutation().expectedRevision(), + current.physicalMutation().successorRevision()); + if (updated != 1) throw conflict("Issuer retirement proof compare-and-set refused"); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + RETIREMENT + " WHERE retirement_operation_id = ?", + current.operationId()); + if (saved == null) throw conflict("Committed issuer retirement proof is unreadable"); + return readOperation(transaction, saved, release); + }); requireSameCurrentIssuerState( before, readCurrentIssuerState(), completed.release().originalSource().anchor()); return completed; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java index f984c813e5..7f1e82ce0a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRetirementRedisOwner.java @@ -244,14 +244,12 @@ private static byte[][] scriptArguments( } List entries = work.localEntries().stream() - .filter( - entry -> - entry - .memberValue() - .reservation() - .partitionId() - .equals( - operation.release().releasedMemberValue().reservation().partitionId())) + .filter(entry -> + entry + .memberValue() + .reservation() + .partitionId() + .equals(operation.release().releasedMemberValue().reservation().partitionId())) .sorted(Comparator.comparing(entry -> entry.operationId().toString())) .toList(); args.add(ascii(Integer.toString(entries.size()))); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java index ad0e3fe074..d5d03a50f3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageRepository.java @@ -57,101 +57,96 @@ void recordPartitionProof(CanonicalGameplayIssuerBootstrapPartitionRedisOwner.Re CanonicalGameplayIssuerBootstrapPartitionWork work = readback.work(); requireNoAmbientTransaction(); ProofInput input = proofInput(readback); - dsl.transaction( - configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - CanonicalGameplayIssuerPartitionBuildPlan currentPlan = - new CanonicalGameplayIssuerPartitionBuildRepository(transaction) - .readPreparedPlanInTransaction( - transaction, - work.buildPlan().bootstrapIntent().operationId(), - work.buildPlan().bootstrapIntent().requestId()); - requireSamePlan(currentPlan, work.buildPlan()); - requireProofContext(input, currentPlan); - Record existing = - transaction.fetchOne( - "SELECT * FROM " - + PROOF - + " WHERE bootstrap_operation_id = ? AND partition_id = ? FOR UPDATE", - currentPlan.bootstrapIntent().operationId(), - input.partitionId()); - if (existing != null) { - requireSameProof(existing, input); - CanonicalGameplayIssuerPartitionMutationRepository - .recordInitialPhysicalReadbackInTransaction( - transaction, - work.buildPlan().bootstrapIntent().operationId(), - input.partitionId(), - work.initialPhysicalRevision(), - input.fieldSetBytes()); - return; - } - int inserted = - transaction.execute( - "INSERT INTO " - + PROOF - + " (" - + "build_operation_id, bootstrap_operation_id, bootstrap_request_id, issuer_id, " - + "build_plan_digest, bootstrap_operation_fence, bootstrap_coverage_fence, " - + "issuer_inventory_snapshot_revision, layout_version, partition_count, " - + "partition_capacity, mapping_identity, layout_descriptor_bytes, " - + "layout_descriptor_digest, source_checkpoint_bytes, source_checkpoint_digest, " - + "source_event_bytes, source_event_digest, incarnation_bytes, incarnation_digest, " - + "partition_id, initial_physical_mutation_revision, exact_metadata_bytes, " - + "exact_physical_field_set_bytes, " - + "exact_physical_field_set_digest, physical_field_count, physical_reservation_count, " - + "physical_binding_count, physical_counted_capacity_count, " - + "planned_aggregate_capacity_count, proof_state) VALUES (" - + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'EXACT_PHYSICAL_READBACK')", - input.buildOperationId(), - input.bootstrapOperationId(), - input.bootstrapRequestId(), - ISSUER, - input.planDigest(), - input.operationFence(), - input.coverageFence(), - input.snapshotRevision(), - input.layoutVersion(), - input.partitionCount(), - input.partitionCapacity(), - input.mappingIdentity(), - input.layoutDescriptorBytes(), - input.layoutDescriptorDigest(), - input.sourceCheckpointBytes(), - input.sourceCheckpointDigest(), - input.sourceEventBytes(), - input.sourceEventDigest(), - input.incarnationBytes(), - input.incarnationDigest(), - input.partitionId(), - input.initialPhysicalRevision(), - input.metadataBytes(), - input.fieldSetBytes(), - input.fieldSetDigest(), - input.fieldCount(), - input.reservationCount(), - input.bindingCount(), - input.countedCapacityCount(), - input.aggregateCountedCapacity()); - if (inserted != 1) throw conflict("Exact partition proof did not persist"); - Record saved = - transaction.fetchOne( - "SELECT * FROM " - + PROOF - + " WHERE bootstrap_operation_id = ? AND partition_id = ?", - input.bootstrapOperationId(), - input.partitionId()); - if (saved == null) - throw conflict("Exact partition proof is unreadable after persistence"); - requireSameProof(saved, input); - CanonicalGameplayIssuerPartitionMutationRepository - .recordInitialPhysicalReadbackInTransaction( + dsl.transaction(configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayIssuerPartitionBuildPlan currentPlan = + new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readPreparedPlanInTransaction( transaction, work.buildPlan().bootstrapIntent().operationId(), - input.partitionId(), - work.initialPhysicalRevision(), - input.fieldSetBytes()); - }); + work.buildPlan().bootstrapIntent().requestId()); + requireSamePlan(currentPlan, work.buildPlan()); + requireProofContext(input, currentPlan); + Record existing = + transaction.fetchOne( + "SELECT * FROM " + + PROOF + + " WHERE bootstrap_operation_id = ? AND partition_id = ? FOR UPDATE", + currentPlan.bootstrapIntent().operationId(), + input.partitionId()); + if (existing != null) { + requireSameProof(existing, input); + CanonicalGameplayIssuerPartitionMutationRepository + .recordInitialPhysicalReadbackInTransaction( + transaction, + work.buildPlan().bootstrapIntent().operationId(), + input.partitionId(), + work.initialPhysicalRevision(), + input.fieldSetBytes()); + return; + } + int inserted = + transaction.execute( + "INSERT INTO " + + PROOF + + " (" + + "build_operation_id, bootstrap_operation_id, bootstrap_request_id, issuer_id, " + + "build_plan_digest, bootstrap_operation_fence, bootstrap_coverage_fence, " + + "issuer_inventory_snapshot_revision, layout_version, partition_count, " + + "partition_capacity, mapping_identity, layout_descriptor_bytes, " + + "layout_descriptor_digest, source_checkpoint_bytes, source_checkpoint_digest, " + + "source_event_bytes, source_event_digest, incarnation_bytes, incarnation_digest, " + + "partition_id, initial_physical_mutation_revision, exact_metadata_bytes, " + + "exact_physical_field_set_bytes, " + + "exact_physical_field_set_digest, physical_field_count, physical_reservation_count, " + + "physical_binding_count, physical_counted_capacity_count, " + + "planned_aggregate_capacity_count, proof_state) VALUES (" + + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'EXACT_PHYSICAL_READBACK')", + input.buildOperationId(), + input.bootstrapOperationId(), + input.bootstrapRequestId(), + ISSUER, + input.planDigest(), + input.operationFence(), + input.coverageFence(), + input.snapshotRevision(), + input.layoutVersion(), + input.partitionCount(), + input.partitionCapacity(), + input.mappingIdentity(), + input.layoutDescriptorBytes(), + input.layoutDescriptorDigest(), + input.sourceCheckpointBytes(), + input.sourceCheckpointDigest(), + input.sourceEventBytes(), + input.sourceEventDigest(), + input.incarnationBytes(), + input.incarnationDigest(), + input.partitionId(), + input.initialPhysicalRevision(), + input.metadataBytes(), + input.fieldSetBytes(), + input.fieldSetDigest(), + input.fieldCount(), + input.reservationCount(), + input.bindingCount(), + input.countedCapacityCount(), + input.aggregateCountedCapacity()); + if (inserted != 1) throw conflict("Exact partition proof did not persist"); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + PROOF + " WHERE bootstrap_operation_id = ? AND partition_id = ?", + input.bootstrapOperationId(), + input.partitionId()); + if (saved == null) throw conflict("Exact partition proof is unreadable after persistence"); + requireSameProof(saved, input); + CanonicalGameplayIssuerPartitionMutationRepository.recordInitialPhysicalReadbackInTransaction( + transaction, + work.buildPlan().bootstrapIntent().operationId(), + input.partitionId(), + work.initialPhysicalRevision(), + input.fieldSetBytes()); + }); } Optional readInstalledAnchor( @@ -162,31 +157,29 @@ Optional readInstalledAnchor( Objects.requireNonNull(bootstrapRequestId, "bootstrapRequestId"); Objects.requireNonNull(currentState, "currentState"); requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - Record anchorProbe = - transaction.fetchOne( - "SELECT issuer_id FROM " + ANCHOR + " WHERE issuer_id = ?", ISSUER); - if (anchorProbe == null) return Optional.empty(); - CanonicalGameplayIssuerPartitionBuildRepository buildRepository = - new CanonicalGameplayIssuerPartitionBuildRepository(transaction); - CanonicalGameplayIssuerPartitionBuildPlan plan = - buildRepository.readInstalledPlanForAnchorInTransaction( - transaction, bootstrapOperationId, bootstrapRequestId); - requireCurrentState(currentState, plan.bootstrapIntent()); - Record row = - transaction.fetchOne( - "SELECT * FROM " + ANCHOR + " WHERE issuer_id = ? FOR UPDATE", ISSUER); - if (row == null) return Optional.empty(); - CanonicalGameplayIssuerInstalledAnchor installed = loadAnchor(row); - requireAnchorMatchesPlan(installed, plan, currentState); - requireProofSummaryMatchesAnchor( - verifyCompleteProof(transaction, plan, installed.incarnationBytes()), installed); - requireCounterCoversAnchor(transaction, installed); - return Optional.of(installed); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + Record anchorProbe = + transaction.fetchOne("SELECT issuer_id FROM " + ANCHOR + " WHERE issuer_id = ?", ISSUER); + if (anchorProbe == null) return Optional.empty(); + CanonicalGameplayIssuerPartitionBuildRepository buildRepository = + new CanonicalGameplayIssuerPartitionBuildRepository(transaction); + CanonicalGameplayIssuerPartitionBuildPlan plan = + buildRepository.readInstalledPlanForAnchorInTransaction( + transaction, bootstrapOperationId, bootstrapRequestId); + requireCurrentState(currentState, plan.bootstrapIntent()); + Record row = + transaction.fetchOne( + "SELECT * FROM " + ANCHOR + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (row == null) return Optional.empty(); + CanonicalGameplayIssuerInstalledAnchor installed = loadAnchor(row); + requireAnchorMatchesPlan(installed, plan, currentState); + requireProofSummaryMatchesAnchor( + verifyCompleteProof(transaction, plan, installed.incarnationBytes()), installed); + requireCounterCoversAnchor(transaction, installed); + return Optional.of(installed); + }); } /** @@ -450,27 +443,24 @@ void verifyExistingPartitionProof( CanonicalGameplayIssuerBootstrapPartitionWork work = readback.work(); ProofInput input = proofInput(readback); requireNoAmbientTransaction(); - dsl.transaction( - configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - CanonicalGameplayIssuerPartitionBuildPlan currentPlan = - new CanonicalGameplayIssuerPartitionBuildRepository(transaction) - .readPreparedPlanInTransaction( - transaction, - work.buildPlan().bootstrapIntent().operationId(), - work.buildPlan().bootstrapIntent().requestId()); - requireSamePlan(currentPlan, work.buildPlan()); - requireProofContext(input, currentPlan); - Record row = - transaction.fetchOne( - "SELECT * FROM " - + PROOF - + " WHERE bootstrap_operation_id = ? AND partition_id = ?", - input.bootstrapOperationId(), - input.partitionId()); - if (row == null) throw conflict("Installed anchor is missing an exact partition proof"); - requireSameProof(row, input); - }); + dsl.transaction(configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayIssuerPartitionBuildPlan currentPlan = + new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readPreparedPlanInTransaction( + transaction, + work.buildPlan().bootstrapIntent().operationId(), + work.buildPlan().bootstrapIntent().requestId()); + requireSamePlan(currentPlan, work.buildPlan()); + requireProofContext(input, currentPlan); + Record row = + transaction.fetchOne( + "SELECT * FROM " + PROOF + " WHERE bootstrap_operation_id = ? AND partition_id = ?", + input.bootstrapOperationId(), + input.partitionId()); + if (row == null) throw conflict("Installed anchor is missing an exact partition proof"); + requireSameProof(row, input); + }); } CanonicalGameplayIssuerInstalledAnchor installInitialAnchor( @@ -481,111 +471,108 @@ CanonicalGameplayIssuerInstalledAnchor installInitialAnchor( Objects.requireNonNull(bootstrapRequestId, "bootstrapRequestId"); Objects.requireNonNull(currentState, "currentState"); requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - CanonicalGameplayIssuerPartitionBuildRepository buildRepository = - new CanonicalGameplayIssuerPartitionBuildRepository(transaction); - Record anchorProbe = - transaction.fetchOne( - "SELECT issuer_id FROM " + ANCHOR + " WHERE issuer_id = ?", ISSUER); - CanonicalGameplayIssuerPartitionBuildPlan plan = - anchorProbe == null - ? buildRepository.readPreparedPlanInTransaction( - transaction, bootstrapOperationId, bootstrapRequestId) - : buildRepository.readInstalledPlanForAnchorInTransaction( - transaction, bootstrapOperationId, bootstrapRequestId); - CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); - requireCurrentState(currentState, intent); - Record existing = - transaction.fetchOne( - "SELECT * FROM " + ANCHOR + " WHERE issuer_id = ? FOR UPDATE", ISSUER); - if (existing != null) { - CanonicalGameplayIssuerInstalledAnchor installed = loadAnchor(existing); - requireAnchorMatchesPlan(installed, plan, currentState); - requireProofSummaryMatchesAnchor( - verifyCompleteProof(transaction, plan, installed.incarnationBytes()), installed); - requireCounterCoversAnchor(transaction, installed); - return installed; - } + return dsl.transactionResult(configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerPartitionBuildRepository buildRepository = + new CanonicalGameplayIssuerPartitionBuildRepository(transaction); + Record anchorProbe = + transaction.fetchOne("SELECT issuer_id FROM " + ANCHOR + " WHERE issuer_id = ?", ISSUER); + CanonicalGameplayIssuerPartitionBuildPlan plan = + anchorProbe == null + ? buildRepository.readPreparedPlanInTransaction( + transaction, bootstrapOperationId, bootstrapRequestId) + : buildRepository.readInstalledPlanForAnchorInTransaction( + transaction, bootstrapOperationId, bootstrapRequestId); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + requireCurrentState(currentState, intent); + Record existing = + transaction.fetchOne( + "SELECT * FROM " + ANCHOR + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (existing != null) { + CanonicalGameplayIssuerInstalledAnchor installed = loadAnchor(existing); + requireAnchorMatchesPlan(installed, plan, currentState); + requireProofSummaryMatchesAnchor( + verifyCompleteProof(transaction, plan, installed.incarnationBytes()), installed); + requireCounterCoversAnchor(transaction, installed); + return installed; + } - ProofSummary proof = - verifyCompleteProof( - transaction, - plan, - CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation( - currentState.incarnation())); - BigInteger generation = allocateGlobalCoverageGeneration(transaction); - CanonicalGameplayIssuerInstalledAnchor anchor = - createAnchor(plan, currentState, generation, proof); - int inserted = - transaction.execute( - "INSERT INTO " - + ANCHOR - + " (" - + "issuer_id, bootstrap_operation_id, bootstrap_request_id, build_operation_id, " - + "build_plan_digest, control_epoch, issuer_coverage_operation_id, operation_fence, " - + "coverage_fence, issuer_inventory_snapshot_revision, layout_version, partition_count, " - + "partition_capacity, mapping_identity, layout_descriptor_bytes, layout_descriptor_digest, " - + "issuer_auth_generation, source_checkpoint_bytes, source_checkpoint_digest, " - + "source_event_bytes, source_event_digest, incarnation_bytes, incarnation_digest, " - + "global_coverage_generation, partition_proof_count, physical_reservation_count, " - + "physical_binding_count, aggregate_counted_capacity, partition_proof_root_digest, " - + "exact_anchor_bytes, exact_anchor_digest, anchor_state) " - + "SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'INITIAL_INSTALLED' " - + "FROM " - + CONTROL - + " c WHERE c.issuer_id = ? AND c.state = 'INITIAL_BOOTSTRAP_INTENT' " - + "AND c.control_epoch = ? AND c.current_operation_id = ? " - + "AND c.current_operation_fence = ? AND c.current_coverage_fence = ? " - + "AND NOT EXISTS (SELECT 1 FROM " - + ANCHOR - + " a WHERE a.issuer_id = c.issuer_id)", - anchor.issuerId(), - anchor.bootstrapOperationId(), - anchor.bootstrapRequestId(), - plan.buildOperationId(), - plan.planDigest(), - anchor.controlEpoch(), - anchor.issuerCoverageOperationId(), - anchor.operationFence(), - anchor.coverageFence(), - anchor.issuerInventorySnapshotRevision(), - anchor.layoutVersion(), - anchor.partitionCount(), - anchor.partitionCapacity(), - anchor.mappingIdentity(), - anchor.layoutDescriptorBytes(), - anchor.layoutDescriptorDigest(), - anchor.issuerAuthGeneration(), - anchor.sourceCheckpointBytes(), - anchor.sourceCheckpointDigest(), - anchor.sourceEventBytes(), - anchor.sourceEventDigest(), - anchor.incarnationBytes(), - anchor.incarnationDigest(), - anchor.globalCoverageGeneration(), - anchor.partitionProofCount(), - anchor.physicalReservationCount(), - anchor.physicalBindingCount(), - anchor.aggregateCountedCapacity(), - anchor.partitionProofRootDigest(), - anchor.exactAnchorBytes(), - anchor.exactAnchorDigest(), - ISSUER, - intent.controlEpoch(), - intent.operationId(), - intent.operationFence(), - intent.coverageFence()); - if (inserted != 1) throw conflict("Exact initial issuer anchor compare-and-set refused"); - Record saved = - transaction.fetchOne("SELECT * FROM " + ANCHOR + " WHERE issuer_id = ?", ISSUER); - if (saved == null) throw conflict("Installed issuer anchor is unreadable after its CAS"); - CanonicalGameplayIssuerInstalledAnchor result = loadAnchor(saved); - requireSameAnchor(result, anchor); - return result; - }); + ProofSummary proof = + verifyCompleteProof( + transaction, + plan, + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(currentState.incarnation())); + BigInteger generation = allocateGlobalCoverageGeneration(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + createAnchor(plan, currentState, generation, proof); + int inserted = + transaction.execute( + "INSERT INTO " + + ANCHOR + + " (" + + "issuer_id, bootstrap_operation_id, bootstrap_request_id, build_operation_id, " + + "build_plan_digest, control_epoch, issuer_coverage_operation_id, operation_fence, " + + "coverage_fence, issuer_inventory_snapshot_revision, layout_version, partition_count, " + + "partition_capacity, mapping_identity, layout_descriptor_bytes, layout_descriptor_digest, " + + "issuer_auth_generation, source_checkpoint_bytes, source_checkpoint_digest, " + + "source_event_bytes, source_event_digest, incarnation_bytes, incarnation_digest, " + + "global_coverage_generation, partition_proof_count, physical_reservation_count, " + + "physical_binding_count, aggregate_counted_capacity, partition_proof_root_digest, " + + "exact_anchor_bytes, exact_anchor_digest, anchor_state) " + + "SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'INITIAL_INSTALLED' " + + "FROM " + + CONTROL + + " c WHERE c.issuer_id = ? AND c.state = 'INITIAL_BOOTSTRAP_INTENT' " + + "AND c.control_epoch = ? AND c.current_operation_id = ? " + + "AND c.current_operation_fence = ? AND c.current_coverage_fence = ? " + + "AND NOT EXISTS (SELECT 1 FROM " + + ANCHOR + + " a WHERE a.issuer_id = c.issuer_id)", + anchor.issuerId(), + anchor.bootstrapOperationId(), + anchor.bootstrapRequestId(), + plan.buildOperationId(), + plan.planDigest(), + anchor.controlEpoch(), + anchor.issuerCoverageOperationId(), + anchor.operationFence(), + anchor.coverageFence(), + anchor.issuerInventorySnapshotRevision(), + anchor.layoutVersion(), + anchor.partitionCount(), + anchor.partitionCapacity(), + anchor.mappingIdentity(), + anchor.layoutDescriptorBytes(), + anchor.layoutDescriptorDigest(), + anchor.issuerAuthGeneration(), + anchor.sourceCheckpointBytes(), + anchor.sourceCheckpointDigest(), + anchor.sourceEventBytes(), + anchor.sourceEventDigest(), + anchor.incarnationBytes(), + anchor.incarnationDigest(), + anchor.globalCoverageGeneration(), + anchor.partitionProofCount(), + anchor.physicalReservationCount(), + anchor.physicalBindingCount(), + anchor.aggregateCountedCapacity(), + anchor.partitionProofRootDigest(), + anchor.exactAnchorBytes(), + anchor.exactAnchorDigest(), + ISSUER, + intent.controlEpoch(), + intent.operationId(), + intent.operationFence(), + intent.coverageFence()); + if (inserted != 1) throw conflict("Exact initial issuer anchor compare-and-set refused"); + Record saved = + transaction.fetchOne("SELECT * FROM " + ANCHOR + " WHERE issuer_id = ?", ISSUER); + if (saved == null) throw conflict("Installed issuer anchor is unreadable after its CAS"); + CanonicalGameplayIssuerInstalledAnchor result = loadAnchor(saved); + requireSameAnchor(result, anchor); + return result; + }); } private CanonicalGameplayIssuerInstalledAnchor createAnchor( @@ -1286,11 +1273,10 @@ static byte[] encodeFieldSet(Map fields) { if (entries.isEmpty() || entries.size() > MAX_LOCAL_PHYSICAL_FIELD_COUNT) { throw conflict("Physical field proof count is outside its bound"); } - entries.sort( - (left, right) -> - compareUnsigned( - left.getKey().getBytes(StandardCharsets.UTF_8), - right.getKey().getBytes(StandardCharsets.UTF_8))); + entries.sort((left, right) -> + compareUnsigned( + left.getKey().getBytes(StandardCharsets.UTF_8), + right.getKey().getBytes(StandardCharsets.UTF_8))); try { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); try (DataOutputStream output = new DataOutputStream(bytes)) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java index 185aa9a592..7cd9a3d97a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepository.java @@ -52,15 +52,14 @@ CanonicalGameplayIssuerBootstrapMemberOperation beginOrResumePendingPhysicalProo Objects.requireNonNull(currentAccountCheckpoint, "currentAccountCheckpoint"); Objects.requireNonNull(stableIncarnation, "stableIncarnation"); requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> - beginOrResumeInTransaction( - org.jooq.impl.DSL.using(configuration), - bootstrapOperationId, - bootstrapRequestId, - workOrdinal, - currentAccountCheckpoint, - stableIncarnation)); + return dsl.transactionResult(configuration -> + beginOrResumeInTransaction( + org.jooq.impl.DSL.using(configuration), + bootstrapOperationId, + bootstrapRequestId, + workOrdinal, + currentAccountCheckpoint, + stableIncarnation)); } /** @@ -80,36 +79,35 @@ CanonicalGameplayIssuerBootstrapPartitionWork preparePartitionWork( Objects.requireNonNull(currentAccountCheckpoint, "currentAccountCheckpoint"); Objects.requireNonNull(stableIncarnation, "stableIncarnation"); requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = org.jooq.impl.DSL.using(configuration); - CanonicalGameplayIssuerPartitionBuildRepository buildRepository = - new CanonicalGameplayIssuerPartitionBuildRepository(transaction); - CanonicalGameplayIssuerPartitionBuildPlan plan = - buildRepository.readPreparedPlanInTransaction( - transaction, bootstrapOperationId, bootstrapRequestId); - CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); - if (partitionId.signum() < 0 - || partitionId.compareTo(intent.layoutDescriptor().partitionCount()) >= 0) { - throw conflict("Requested partition is outside the exact prepared bootstrap layout"); - } - UUID initialPhysicalRevision = - CanonicalGameplayIssuerPartitionMutationRepository.ensureInitialRevisionInTransaction( - transaction, bootstrapOperationId, partitionId); - requireCurrentAccountCheckpoint(currentAccountCheckpoint, intent.sourceCheckpoint()); - CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation = stableIncarnation.value(); - List operations = new ArrayList<>(); - for (CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work : plan.memberWorks()) { - if (!work.plannedPartitionId().equals(partitionId)) continue; - CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared = - buildRepository.readPreparedMemberWorkFromVerifiedPlan(plan, work.workOrdinal()); - operations.add( - beginOrResumePreparedInTransaction( - transaction, prepared, currentAccountCheckpoint, incarnation)); - } - return new CanonicalGameplayIssuerBootstrapPartitionWork( - plan, partitionId, initialPhysicalRevision, operations, incarnation); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayIssuerPartitionBuildRepository buildRepository = + new CanonicalGameplayIssuerPartitionBuildRepository(transaction); + CanonicalGameplayIssuerPartitionBuildPlan plan = + buildRepository.readPreparedPlanInTransaction( + transaction, bootstrapOperationId, bootstrapRequestId); + CanonicalGameplayIssuerLayoutBootstrapIntent intent = plan.bootstrapIntent(); + if (partitionId.signum() < 0 + || partitionId.compareTo(intent.layoutDescriptor().partitionCount()) >= 0) { + throw conflict("Requested partition is outside the exact prepared bootstrap layout"); + } + UUID initialPhysicalRevision = + CanonicalGameplayIssuerPartitionMutationRepository.ensureInitialRevisionInTransaction( + transaction, bootstrapOperationId, partitionId); + requireCurrentAccountCheckpoint(currentAccountCheckpoint, intent.sourceCheckpoint()); + CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation = stableIncarnation.value(); + List operations = new ArrayList<>(); + for (CanonicalGameplayIssuerPartitionBuildPlan.MemberWork work : plan.memberWorks()) { + if (!work.plannedPartitionId().equals(partitionId)) continue; + CanonicalGameplayIssuerPartitionBuildRepository.PreparedMemberWork prepared = + buildRepository.readPreparedMemberWorkFromVerifiedPlan(plan, work.workOrdinal()); + operations.add( + beginOrResumePreparedInTransaction( + transaction, prepared, currentAccountCheckpoint, incarnation)); + } + return new CanonicalGameplayIssuerBootstrapPartitionWork( + plan, partitionId, initialPhysicalRevision, operations, incarnation); + }); } private static CanonicalGameplayIssuerBootstrapMemberOperation beginOrResumeInTransaction( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java index e80b4b8124..217dc564af 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerInstalledAnchor.java @@ -163,62 +163,60 @@ public final class CanonicalGameplayIssuerInstalledAnchor { static byte[] encodeIncarnation(CanonicalGameplayIssuerMemberV2Value.Incarnation incarnation) { Objects.requireNonNull(incarnation, "incarnation"); var deployment = incarnation.targetDeploymentEvidence(); - return encode( - output -> { - writeText(output, "canonical-stable-issuer-incarnation/v1"); - writeText(output, incarnation.attestorBinding()); - writeText(output, incarnation.acceptedAttestationDigest()); - writeText(output, deployment.deploymentIdentity()); - writeText(output, deployment.deploymentGeneration()); - output.writeInt(deployment.canonicalNodeSet().size()); - for (String node : deployment.canonicalNodeSet()) writeText(output, node); - writeText(output, deployment.redisBuildIdentity()); - writeText(output, deployment.luaScriptRegistryVersion()); - writeText(output, deployment.luaScriptRegistryDigest()); - writeText(output, deployment.startupState()); - writeText(output, deployment.bootGeneration()); - writeText(output, deployment.startupGeneration()); - writeText(output, deployment.storageGeneration()); - writeText(output, deployment.aofGeneration()); - writeText(output, incarnation.coordOpsRoAclDigest()); - writeText(output, incarnation.coordRedisConfigObservedDigest()); - }); + return encode(output -> { + writeText(output, "canonical-stable-issuer-incarnation/v1"); + writeText(output, incarnation.attestorBinding()); + writeText(output, incarnation.acceptedAttestationDigest()); + writeText(output, deployment.deploymentIdentity()); + writeText(output, deployment.deploymentGeneration()); + output.writeInt(deployment.canonicalNodeSet().size()); + for (String node : deployment.canonicalNodeSet()) writeText(output, node); + writeText(output, deployment.redisBuildIdentity()); + writeText(output, deployment.luaScriptRegistryVersion()); + writeText(output, deployment.luaScriptRegistryDigest()); + writeText(output, deployment.startupState()); + writeText(output, deployment.bootGeneration()); + writeText(output, deployment.startupGeneration()); + writeText(output, deployment.storageGeneration()); + writeText(output, deployment.aofGeneration()); + writeText(output, incarnation.coordOpsRoAclDigest()); + writeText(output, incarnation.coordRedisConfigObservedDigest()); + }); } private byte[] encodeExactAnchor() { - return encode( - output -> { - writeText(output, ENCODING); - writeText(output, bootstrapOperationId.toString()); - writeText(output, bootstrapRequestId.toString()); - writeText(output, buildOperationId.toString()); - writeText(output, buildPlanDigest); - writeText(output, issuerId); - writeBigInteger(output, controlEpoch); - writeText(output, issuerCoverageOperationId.toString()); - writeBigInteger(output, operationFence); - writeBigInteger(output, coverageFence); - writeBigInteger(output, issuerInventorySnapshotRevision); - writeBigInteger(output, layoutVersion); - writeBigInteger(output, partitionCount); - writeBigInteger(output, partitionCapacity); - writeText(output, mappingIdentity); - writeBytes(output, layoutDescriptorBytes); - writeText(output, layoutDescriptorDigest); - writeBigInteger(output, issuerAuthGeneration); - writeBytes(output, sourceCheckpointBytes); - writeText(output, sourceCheckpointDigest); - writeNullableBytes(output, sourceEventBytes); - writeNullableText(output, sourceEventDigest); - writeBytes(output, incarnationBytes); - writeText(output, incarnationDigest); - writeBigInteger(output, globalCoverageGeneration); - output.writeLong(partitionProofCount); - output.writeLong(physicalReservationCount); - output.writeLong(physicalBindingCount); - writeBigInteger(output, aggregateCountedCapacity); - writeText(output, partitionProofRootDigest); - }); + return encode(output -> { + writeText(output, ENCODING); + writeText(output, bootstrapOperationId.toString()); + writeText(output, bootstrapRequestId.toString()); + writeText(output, buildOperationId.toString()); + writeText(output, buildPlanDigest); + writeText(output, issuerId); + writeBigInteger(output, controlEpoch); + writeText(output, issuerCoverageOperationId.toString()); + writeBigInteger(output, operationFence); + writeBigInteger(output, coverageFence); + writeBigInteger(output, issuerInventorySnapshotRevision); + writeBigInteger(output, layoutVersion); + writeBigInteger(output, partitionCount); + writeBigInteger(output, partitionCapacity); + writeText(output, mappingIdentity); + writeBytes(output, layoutDescriptorBytes); + writeText(output, layoutDescriptorDigest); + writeBigInteger(output, issuerAuthGeneration); + writeBytes(output, sourceCheckpointBytes); + writeText(output, sourceCheckpointDigest); + writeNullableBytes(output, sourceEventBytes); + writeNullableText(output, sourceEventDigest); + writeBytes(output, incarnationBytes); + writeText(output, incarnationDigest); + writeBigInteger(output, globalCoverageGeneration); + output.writeLong(partitionProofCount); + output.writeLong(physicalReservationCount); + output.writeLong(physicalBindingCount); + writeBigInteger(output, aggregateCountedCapacity); + writeText(output, partitionProofRootDigest); + }); } public UUID bootstrapOperationId() { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java index 00c056826b..3ad9ad5eb4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepository.java @@ -66,95 +66,92 @@ CanonicalGameplayIssuerLayoutBootstrapIntent beginInitialBootstrapIntent( ? null : sha256(sourceCheckpoint.latestEventBytes()); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - - // This is the same first lock as binding preparation. It serializes the immutable - // inventory cut with every canonical source row that follows this clock. - BigInteger snapshotRevision = lockInventoryRevision(transaction); - Record existingControl = lockControl(transaction, descriptor.issuerId()); - if (existingControl != null) { - UUID currentOperationId = - Objects.requireNonNull( - existingControl.get("current_operation_id", UUID.class), - "issuer bootstrap control operation id"); - Record existingIntent = lockIntent(transaction, currentOperationId); - if (existingIntent == null) { - throw conflict("Issuer bootstrap control lost its original intent row"); - } - CanonicalGameplayIssuerLayoutBootstrapIntent prior = - loadAndRequireCurrent(transaction, existingControl, existingIntent); - if (!prior.requestId().equals(requestId)) { - throw conflict( - "A different initial issuer-layout bootstrap already owns this issuer"); - } - requireSameTrustedInputs( - prior, - descriptor, - sourceCheckpoint, - descriptorDigest, - checkpointDigest, - sourceEventDigest); - return prior; - } - - Record priorIntent = - transaction.fetchOne( - "SELECT operation_id FROM " + INTENT + " WHERE issuer_id = ?", - descriptor.issuerId()); - if (priorIntent != null) { - throw conflict("Issuer bootstrap intent exists without its positive control row"); - } - - CanonicalGameplayLegacyMigrationDisposition legacy = - readVerifiedLegacyDisposition(transaction, snapshotRevision, true); - requireNoFutureInventoryRows(transaction, snapshotRevision); - List sourceRows = captureCohort(transaction, snapshotRevision); - List cohortRows = - freezeCohort(sourceRows); - String cohortDigest = digestCohort(cohortRows); - - UUID operationId = randomNonNilUuid(); - while (operationId.equals(requestId)) operationId = randomNonNilUuid(); - // The only operation in this migration is the initial intent. The first durable epoch - // is positive; operationFence and coverageFence consume distinct ordered values. - BigInteger operationFence = BigInteger.ONE; - BigInteger coverageFence = BigInteger.TWO; - BigInteger controlEpoch = operationFence; - - insertIntent( - transaction, - operationId, - requestId, - descriptor, - descriptorDigest, - sourceCheckpoint, - checkpointDigest, - sourceEventDigest, - snapshotRevision, - controlEpoch, - operationFence, - coverageFence, - legacy, - cohortRows, - cohortDigest); - insertCohort(transaction, operationId, descriptor.issuerId(), cohortRows); - insertControl( - transaction, - descriptor.issuerId(), - operationId, - controlEpoch, - operationFence, - coverageFence); - - Record savedControl = lockControl(transaction, descriptor.issuerId()); - Record savedIntent = lockIntent(transaction, operationId); - if (savedControl == null || savedIntent == null) { - throw conflict("Persisted initial issuer-bootstrap intent is incomplete"); - } - return loadAndRequireCurrent(transaction, savedControl, savedIntent); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + + // This is the same first lock as binding preparation. It serializes the immutable + // inventory cut with every canonical source row that follows this clock. + BigInteger snapshotRevision = lockInventoryRevision(transaction); + Record existingControl = lockControl(transaction, descriptor.issuerId()); + if (existingControl != null) { + UUID currentOperationId = + Objects.requireNonNull( + existingControl.get("current_operation_id", UUID.class), + "issuer bootstrap control operation id"); + Record existingIntent = lockIntent(transaction, currentOperationId); + if (existingIntent == null) { + throw conflict("Issuer bootstrap control lost its original intent row"); + } + CanonicalGameplayIssuerLayoutBootstrapIntent prior = + loadAndRequireCurrent(transaction, existingControl, existingIntent); + if (!prior.requestId().equals(requestId)) { + throw conflict("A different initial issuer-layout bootstrap already owns this issuer"); + } + requireSameTrustedInputs( + prior, + descriptor, + sourceCheckpoint, + descriptorDigest, + checkpointDigest, + sourceEventDigest); + return prior; + } + + Record priorIntent = + transaction.fetchOne( + "SELECT operation_id FROM " + INTENT + " WHERE issuer_id = ?", descriptor.issuerId()); + if (priorIntent != null) { + throw conflict("Issuer bootstrap intent exists without its positive control row"); + } + + CanonicalGameplayLegacyMigrationDisposition legacy = + readVerifiedLegacyDisposition(transaction, snapshotRevision, true); + requireNoFutureInventoryRows(transaction, snapshotRevision); + List sourceRows = captureCohort(transaction, snapshotRevision); + List cohortRows = + freezeCohort(sourceRows); + String cohortDigest = digestCohort(cohortRows); + + UUID operationId = randomNonNilUuid(); + while (operationId.equals(requestId)) operationId = randomNonNilUuid(); + // The only operation in this migration is the initial intent. The first durable epoch + // is positive; operationFence and coverageFence consume distinct ordered values. + BigInteger operationFence = BigInteger.ONE; + BigInteger coverageFence = BigInteger.TWO; + BigInteger controlEpoch = operationFence; + + insertIntent( + transaction, + operationId, + requestId, + descriptor, + descriptorDigest, + sourceCheckpoint, + checkpointDigest, + sourceEventDigest, + snapshotRevision, + controlEpoch, + operationFence, + coverageFence, + legacy, + cohortRows, + cohortDigest); + insertCohort(transaction, operationId, descriptor.issuerId(), cohortRows); + insertControl( + transaction, + descriptor.issuerId(), + operationId, + controlEpoch, + operationFence, + coverageFence); + + Record savedControl = lockControl(transaction, descriptor.issuerId()); + Record savedIntent = lockIntent(transaction, operationId); + if (savedControl == null || savedIntent == null) { + throw conflict("Persisted initial issuer-bootstrap intent is incomplete"); + } + return loadAndRequireCurrent(transaction, savedControl, savedIntent); + }); } /** @@ -180,157 +177,151 @@ CanonicalGameplayIssuerLayoutBootstrapIntent supersedeStaleInitialBootstrapInten sourceCheckpoint.latestEventBytes() == null ? null : sha256(sourceCheckpoint.latestEventBytes()); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger snapshotRevision = lockInventoryRevision(transaction); - Record control = lockControl(transaction, descriptor.issuerId()); - if (control == null) - throw conflict("Initial bootstrap supersession requires current control"); - UUID currentId = control.get("current_operation_id", UUID.class); - Record currentRow = lockIntent(transaction, currentId); - if (currentRow == null) throw conflict("Current initial bootstrap intent is missing"); - var current = loadAndRequireCurrent(transaction, control, currentRow); - if (transaction.fetchExists( + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger snapshotRevision = lockInventoryRevision(transaction); + Record control = lockControl(transaction, descriptor.issuerId()); + if (control == null) + throw conflict("Initial bootstrap supersession requires current control"); + UUID currentId = control.get("current_operation_id", UUID.class); + Record currentRow = lockIntent(transaction, currentId); + if (currentRow == null) throw conflict("Current initial bootstrap intent is missing"); + var current = loadAndRequireCurrent(transaction, control, currentRow); + if (transaction.fetchExists( + DSL.selectOne() + .from("game_session_canonical_issuer_installed_anchor") + .where(DSL.field("issuer_id").eq(descriptor.issuerId())))) { + throw conflict("An installed issuer anchor forbids initial bootstrap supersession"); + } + if (!expectedOldOperationId.equals(currentId)) { + Record replay = + transaction.fetchOne( + "SELECT * FROM game_session_canonical_issuer_bootstrap_supersession" + + " WHERE old_operation_id = ? AND new_operation_id = ?", + expectedOldOperationId, + currentId); + if (replay == null + || !current.requestId().equals(newRequestId) + || !current + .inventorySnapshotRevision() + .equals(readBigInteger(replay, "new_inventory_revision"))) { + throw conflict("Expected original initial bootstrap is no longer current"); + } + requireSameTrustedInputs( + current, + descriptor, + sourceCheckpoint, + descriptorDigest, + checkpointDigest, + sourceEventDigest); + return current; + } + if (newRequestId.equals(expectedOldOperationId) + || newRequestId.equals(current.requestId()) + || transaction.fetchExists( DSL.selectOne() - .from("game_session_canonical_issuer_installed_anchor") - .where(DSL.field("issuer_id").eq(descriptor.issuerId())))) { - throw conflict("An installed issuer anchor forbids initial bootstrap supersession"); - } - if (!expectedOldOperationId.equals(currentId)) { - Record replay = - transaction.fetchOne( - "SELECT * FROM game_session_canonical_issuer_bootstrap_supersession" - + " WHERE old_operation_id = ? AND new_operation_id = ?", - expectedOldOperationId, - currentId); - if (replay == null - || !current.requestId().equals(newRequestId) - || !current - .inventorySnapshotRevision() - .equals(readBigInteger(replay, "new_inventory_revision"))) { - throw conflict("Expected original initial bootstrap is no longer current"); - } - requireSameTrustedInputs( - current, - descriptor, - sourceCheckpoint, - descriptorDigest, - checkpointDigest, - sourceEventDigest); - return current; - } - if (newRequestId.equals(expectedOldOperationId) - || newRequestId.equals(current.requestId()) - || transaction.fetchExists( - DSL.selectOne() - .from(INTENT) - .where( - DSL.field("request_id") - .eq(newRequestId) - .or(DSL.field("operation_id").eq(newRequestId))))) { - throw conflict("Initial bootstrap supersession requires a fresh distinct request"); - } - if (snapshotRevision.compareTo(current.inventorySnapshotRevision()) <= 0) { - throw conflict("Initial bootstrap supersession requires strictly newer inventory"); - } - if (descriptor.layoutVersion().compareTo(current.layoutDescriptor().layoutVersion()) - <= 0) { - throw conflict( - "Initial bootstrap supersession requires a strictly newer layout version"); - } - var legacy = readVerifiedLegacyDisposition(transaction, snapshotRevision, true); - requireNoFutureInventoryRows(transaction, snapshotRevision); - var rows = freezeCohort(captureCohort(transaction, snapshotRevision)); - BigInteger previousLastFence = readBigInteger(control, "last_issued_fence"); - BigInteger operationFence = previousLastFence.add(BigInteger.ONE); - BigInteger coverageFence = operationFence.add(BigInteger.ONE); - UUID operationId = randomNonNilUuid(); - while (operationId.equals(newRequestId) || operationId.equals(expectedOldOperationId)) { - operationId = randomNonNilUuid(); - } - insertIntent( - transaction, - operationId, - newRequestId, - descriptor, - descriptorDigest, - sourceCheckpoint, - checkpointDigest, - sourceEventDigest, - snapshotRevision, - operationFence, - operationFence, - coverageFence, - legacy, - rows, - digestCohort(rows)); - insertCohort(transaction, operationId, descriptor.issuerId(), rows); + .from(INTENT) + .where( + DSL.field("request_id") + .eq(newRequestId) + .or(DSL.field("operation_id").eq(newRequestId))))) { + throw conflict("Initial bootstrap supersession requires a fresh distinct request"); + } + if (snapshotRevision.compareTo(current.inventorySnapshotRevision()) <= 0) { + throw conflict("Initial bootstrap supersession requires strictly newer inventory"); + } + if (descriptor.layoutVersion().compareTo(current.layoutDescriptor().layoutVersion()) <= 0) { + throw conflict("Initial bootstrap supersession requires a strictly newer layout version"); + } + var legacy = readVerifiedLegacyDisposition(transaction, snapshotRevision, true); + requireNoFutureInventoryRows(transaction, snapshotRevision); + var rows = freezeCohort(captureCohort(transaction, snapshotRevision)); + BigInteger previousLastFence = readBigInteger(control, "last_issued_fence"); + BigInteger operationFence = previousLastFence.add(BigInteger.ONE); + BigInteger coverageFence = operationFence.add(BigInteger.ONE); + UUID operationId = randomNonNilUuid(); + while (operationId.equals(newRequestId) || operationId.equals(expectedOldOperationId)) { + operationId = randomNonNilUuid(); + } + insertIntent( + transaction, + operationId, + newRequestId, + descriptor, + descriptorDigest, + sourceCheckpoint, + checkpointDigest, + sourceEventDigest, + snapshotRevision, + operationFence, + operationFence, + coverageFence, + legacy, + rows, + digestCohort(rows)); + insertCohort(transaction, operationId, descriptor.issuerId(), rows); + transaction.execute( + "INSERT INTO game_session_canonical_issuer_bootstrap_supersession" + + " (issuer_id, old_operation_id, new_operation_id, old_inventory_revision," + + " new_inventory_revision, old_operation_fence, old_coverage_fence," + + " previous_last_issued_fence, new_operation_fence, new_coverage_fence)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + descriptor.issuerId(), + expectedOldOperationId, + operationId, + decimal(current.inventorySnapshotRevision()), + decimal(snapshotRevision), + decimal(current.operationFence()), + decimal(current.coverageFence()), + decimal(previousLastFence), + decimal(operationFence), + decimal(coverageFence)); + int changed = transaction.execute( - "INSERT INTO game_session_canonical_issuer_bootstrap_supersession" - + " (issuer_id, old_operation_id, new_operation_id, old_inventory_revision," - + " new_inventory_revision, old_operation_fence, old_coverage_fence," - + " previous_last_issued_fence, new_operation_fence, new_coverage_fence)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "UPDATE " + + CONTROL + + " SET control_epoch = ?, last_issued_fence = ?, current_operation_id = ?," + + " current_operation_fence = ?, current_coverage_fence = ?," + + " updated_at = CURRENT_TIMESTAMP WHERE issuer_id = ?" + + " AND current_operation_id = ? AND control_epoch = ?" + + " AND current_operation_fence = ? AND current_coverage_fence = ?" + + " AND last_issued_fence = ? AND state = 'INITIAL_BOOTSTRAP_INTENT'", + decimal(operationFence), + decimal(coverageFence), + operationId, + decimal(operationFence), + decimal(coverageFence), descriptor.issuerId(), expectedOldOperationId, - operationId, - decimal(current.inventorySnapshotRevision()), - decimal(snapshotRevision), + decimal(current.controlEpoch()), decimal(current.operationFence()), decimal(current.coverageFence()), - decimal(previousLastFence), - decimal(operationFence), - decimal(coverageFence)); - int changed = - transaction.execute( - "UPDATE " - + CONTROL - + " SET control_epoch = ?, last_issued_fence = ?, current_operation_id = ?," - + " current_operation_fence = ?, current_coverage_fence = ?," - + " updated_at = CURRENT_TIMESTAMP WHERE issuer_id = ?" - + " AND current_operation_id = ? AND control_epoch = ?" - + " AND current_operation_fence = ? AND current_coverage_fence = ?" - + " AND last_issued_fence = ? AND state = 'INITIAL_BOOTSTRAP_INTENT'", - decimal(operationFence), - decimal(coverageFence), - operationId, - decimal(operationFence), - decimal(coverageFence), - descriptor.issuerId(), - expectedOldOperationId, - decimal(current.controlEpoch()), - decimal(current.operationFence()), - decimal(current.coverageFence()), - decimal(previousLastFence)); - if (changed != 1) - throw conflict("Initial bootstrap supersession lost exact current control"); - return loadAndRequireCurrent( - transaction, - Objects.requireNonNull(lockControl(transaction, descriptor.issuerId())), - Objects.requireNonNull(lockIntent(transaction, operationId))); - }); + decimal(previousLastFence)); + if (changed != 1) throw conflict("Initial bootstrap supersession lost exact current control"); + return loadAndRequireCurrent( + transaction, + Objects.requireNonNull(lockControl(transaction, descriptor.issuerId())), + Objects.requireNonNull(lockIntent(transaction, operationId))); + }); } /** Reads the exact persisted pending intent and its frozen cohort by owner-allocated ID. */ CanonicalGameplayIssuerLayoutBootstrapIntent readCurrentInitialBootstrapIntent(UUID operationId) { requireNonNil(operationId, "operationId"); requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - Record intent = - transaction.fetchOne( - "SELECT * FROM " + INTENT + " WHERE operation_id = ?", operationId); - if (intent == null) throw conflict("Exact initial issuer-bootstrap intent is missing"); - String issuerId = Objects.requireNonNull(intent.get("issuer_id", String.class)); - Record control = readControl(transaction, issuerId); - if (control == null) { - throw conflict("Initial issuer-bootstrap intent lost its positive control row"); - } - return loadAndRequireCurrent(transaction, control, intent); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + Record intent = + transaction.fetchOne("SELECT * FROM " + INTENT + " WHERE operation_id = ?", operationId); + if (intent == null) throw conflict("Exact initial issuer-bootstrap intent is missing"); + String issuerId = Objects.requireNonNull(intent.get("issuer_id", String.class)); + Record control = readControl(transaction, issuerId); + if (control == null) { + throw conflict("Initial issuer-bootstrap intent lost its positive control row"); + } + return loadAndRequireCurrent(transaction, control, intent); + }); } private static void requireTrustedInputScopes( @@ -460,24 +451,22 @@ private static CanonicalGameplayIssuerLayoutBootstrapIntent loadAndRequireCurren .fetch( "SELECT * FROM " + COHORT + " WHERE operation_id = ? ORDER BY row_ordinal", operationId) - .map( - row -> { - String sourceJson = - Objects.requireNonNull(row.get("source_row_json", String.class)); - String sourceDigest = - Objects.requireNonNull(row.get("source_row_digest", String.class)); - if (!sha256(sourceJson.getBytes(StandardCharsets.UTF_8)).equals(sourceDigest)) { - throw conflict("Stored issuer cohort source-row digest is invalid"); - } - return new CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow( - Objects.requireNonNull(row.get("row_ordinal", Long.class)), - CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.valueOf( - Objects.requireNonNull(row.get("source_kind", String.class))), - Objects.requireNonNull(row.get("source_key", String.class)), - readBigInteger(row, "source_inventory_revision"), - sourceJson, - sourceDigest); - }); + .map(row -> { + String sourceJson = Objects.requireNonNull(row.get("source_row_json", String.class)); + String sourceDigest = + Objects.requireNonNull(row.get("source_row_digest", String.class)); + if (!sha256(sourceJson.getBytes(StandardCharsets.UTF_8)).equals(sourceDigest)) { + throw conflict("Stored issuer cohort source-row digest is invalid"); + } + return new CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow( + Objects.requireNonNull(row.get("row_ordinal", Long.class)), + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.valueOf( + Objects.requireNonNull(row.get("source_kind", String.class))), + Objects.requireNonNull(row.get("source_key", String.class)), + readBigInteger(row, "source_inventory_revision"), + sourceJson, + sourceDigest); + }); if (cohortRows.stream() .anyMatch(row -> row.sourceInventoryRevision().compareTo(snapshotRevision) > 0) || cohortRows.size() != readLong(intent, "cohort_row_count")) { @@ -559,14 +548,13 @@ private static List captureCohort( .fetch( CanonicalGameplayIssuerCohortSql.cohortSql(), CanonicalGameplayIssuerCohortSql.cohortBindings(ISSUER, decimal(snapshotRevision))) - .map( - row -> - new CohortSourceRow( - CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.valueOf( - Objects.requireNonNull(row.get("source_kind", String.class))), - Objects.requireNonNull(row.get("source_key", String.class)), - readBigInteger(row, "source_revision"), - Objects.requireNonNull(row.get("source_row_json", String.class)))); + .map(row -> + new CohortSourceRow( + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.valueOf( + Objects.requireNonNull(row.get("source_kind", String.class))), + Objects.requireNonNull(row.get("source_key", String.class)), + readBigInteger(row, "source_revision"), + Objects.requireNonNull(row.get("source_row_json", String.class)))); } private static List freezeCohort( @@ -599,17 +587,14 @@ private static String digestCohort( .sorted( Comparator.comparingLong( CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::rowOrdinal)) - .forEach( - row -> { - updateFramed( - digest, Long.toString(row.rowOrdinal()).getBytes(StandardCharsets.US_ASCII)); - updateFramed(digest, row.kind().name().getBytes(StandardCharsets.UTF_8)); - updateFramed(digest, row.sourceKey().getBytes(StandardCharsets.UTF_8)); - updateFramed( - digest, - row.sourceInventoryRevision().toString().getBytes(StandardCharsets.US_ASCII)); - updateFramed(digest, row.sourceRowDigest().getBytes(StandardCharsets.US_ASCII)); - }); + .forEach(row -> { + updateFramed(digest, Long.toString(row.rowOrdinal()).getBytes(StandardCharsets.US_ASCII)); + updateFramed(digest, row.kind().name().getBytes(StandardCharsets.UTF_8)); + updateFramed(digest, row.sourceKey().getBytes(StandardCharsets.UTF_8)); + updateFramed( + digest, row.sourceInventoryRevision().toString().getBytes(StandardCharsets.US_ASCII)); + updateFramed(digest, row.sourceRowDigest().getBytes(StandardCharsets.US_ASCII)); + }); return "sha256:" + HexFormat.of().formatHex(digest.digest()); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerOriginalMemberSourceRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerOriginalMemberSourceRepository.java index e6eb3d8820..2df29f1e5e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerOriginalMemberSourceRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerOriginalMemberSourceRepository.java @@ -31,36 +31,35 @@ CanonicalGameplayIssuerOriginalMemberSource read(CanonicalGameplayIssuerCleanupS if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); var before = Objects.requireNonNull(currentSource.readFreshCurrentState()); var original = - dsl.transactionResult( - configuration -> { - var transaction = org.jooq.impl.DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - var anchor = - CanonicalGameplayIssuerBootstrapCoverageRepository - .readInstalledAnchorForBindingPreparationInTransaction(transaction, before); - var local = - transaction.fetchOne( - "SELECT operation_id FROM game_session_canonical_issuer_binding_local_operation WHERE reservation_id = ?", - source.reservation().reservationId()); - var bootstrap = - transaction.fetchOne( - "SELECT * FROM game_session_canonical_issuer_bootstrap_member_operation WHERE bootstrap_operation_id = ? AND reservation_id = ?", - anchor.bootstrapOperationId(), - source.reservation().reservationId()); - if (local != null && bootstrap != null) throw unavailable(); - if (local != null) return null; - if (bootstrap == null || !source.neverAdmitted()) throw unavailable(); - var result = readInstalledInTransaction(transaction, anchor, before, bootstrap); - if (!result.reservation().owner().equals(source.reservation().owner()) - || !result - .reservation() - .bindingGeneration() - .equals(source.reservation().bindingGeneration()) - || !result.transitionId().equals(source.transition().transitionId()) - || !sameFrozenReservation(result.reservation(), source.reservation())) - throw unavailable(); - return result; - }); + dsl.transactionResult(configuration -> { + var transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + var anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, before); + var local = + transaction.fetchOne( + "SELECT operation_id FROM game_session_canonical_issuer_binding_local_operation WHERE reservation_id = ?", + source.reservation().reservationId()); + var bootstrap = + transaction.fetchOne( + "SELECT * FROM game_session_canonical_issuer_bootstrap_member_operation WHERE bootstrap_operation_id = ? AND reservation_id = ?", + anchor.bootstrapOperationId(), + source.reservation().reservationId()); + if (local != null && bootstrap != null) throw unavailable(); + if (local != null) return null; + if (bootstrap == null || !source.neverAdmitted()) throw unavailable(); + var result = readInstalledInTransaction(transaction, anchor, before, bootstrap); + if (!result.reservation().owner().equals(source.reservation().owner()) + || !result + .reservation() + .bindingGeneration() + .equals(source.reservation().bindingGeneration()) + || !result.transitionId().equals(source.transition().transitionId()) + || !sameFrozenReservation(result.reservation(), source.reservation())) + throw unavailable(); + return result; + }); var after = Objects.requireNonNull(currentSource.readFreshCurrentState()); if (original == null) { return CanonicalGameplayIssuerOriginalMemberSource.ordinary( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java index c313f550cd..a5f12843e3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepository.java @@ -81,10 +81,8 @@ CanonicalGameplayIssuerPartitionBuildPlan prepareInitialBuildPlan( throw conflict("Bootstrap operation and request identities must be distinct"); } requireNoAmbientTransaction(); - return dsl.transactionResult( - configuration -> - prepareInTransaction( - DSL.using(configuration), bootstrapOperationId, bootstrapRequestId)); + return dsl.transactionResult(configuration -> + prepareInTransaction(DSL.using(configuration), bootstrapOperationId, bootstrapRequestId)); } private CanonicalGameplayIssuerPartitionBuildPlan prepareInTransaction( @@ -516,33 +514,32 @@ private static List readStoredCohort( .fetch( "SELECT * FROM " + BOOTSTRAP_COHORT + " WHERE operation_id = ? ORDER BY row_ordinal", operationId) - .map( - row -> { - String sourceJson = requireText(row, "source_row_json"); - String digest = requireText(row, "source_row_digest"); - if (!sha256(sourceJson.getBytes(StandardCharsets.UTF_8)).equals(digest)) { - throw conflict("Frozen bootstrap cohort contains a changed source-row digest"); - } - if (!operationId.equals(row.get("operation_id", UUID.class)) - || !ISSUER.equals(row.get("issuer_id", String.class))) { - throw conflict("Frozen bootstrap cohort row lost its exact owner linkage"); - } - CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow cohortRow; - try { - cohortRow = - new CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow( - requireLong(row, "row_ordinal"), - CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.valueOf( - requireText(row, "source_kind")), - requireText(row, "source_key"), - readBigInteger(row, "source_inventory_revision"), - sourceJson, - digest); - } catch (RuntimeException malformed) { - throw conflict("Frozen bootstrap cohort row is malformed"); - } - return new IssuerCohortSourceRow(cohortRow); - }); + .map(row -> { + String sourceJson = requireText(row, "source_row_json"); + String digest = requireText(row, "source_row_digest"); + if (!sha256(sourceJson.getBytes(StandardCharsets.UTF_8)).equals(digest)) { + throw conflict("Frozen bootstrap cohort contains a changed source-row digest"); + } + if (!operationId.equals(row.get("operation_id", UUID.class)) + || !ISSUER.equals(row.get("issuer_id", String.class))) { + throw conflict("Frozen bootstrap cohort row lost its exact owner linkage"); + } + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow cohortRow; + try { + cohortRow = + new CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow( + requireLong(row, "row_ordinal"), + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.valueOf( + requireText(row, "source_kind")), + requireText(row, "source_key"), + readBigInteger(row, "source_inventory_revision"), + sourceJson, + digest); + } catch (RuntimeException malformed) { + throw conflict("Frozen bootstrap cohort row is malformed"); + } + return new IssuerCohortSourceRow(cohortRow); + }); } private static CanonicalGameplayLegacyMigrationDisposition persistedLegacyDisposition( @@ -588,32 +585,30 @@ private static List captureCurrentCohort( .fetch( CanonicalGameplayIssuerCohortSql.cohortSql(), CanonicalGameplayIssuerCohortSql.cohortBindings(ISSUER, decimal(snapshotRevision))) - .map( - row -> { - String sourceJson = requireText(row, "source_row_json"); - String sourceKey = requireText(row, "source_key"); - BigInteger sourceRevision = readBigInteger(row, "source_revision"); - CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind kind; - try { - kind = - CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.valueOf( - requireText(row, "source_kind")); - } catch (RuntimeException malformed) { - throw conflict("Current issuer inventory contains an unsupported source family"); - } - if (sourceRevision.compareTo(snapshotRevision) > 0) { - throw conflict( - "Current issuer inventory source is newer than its bootstrap snapshot"); - } - return new IssuerCohortSourceRow( - new CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow( - 0L, - kind, - sourceKey, - sourceRevision, - sourceJson, - sha256(sourceJson.getBytes(StandardCharsets.UTF_8)))); - }); + .map(row -> { + String sourceJson = requireText(row, "source_row_json"); + String sourceKey = requireText(row, "source_key"); + BigInteger sourceRevision = readBigInteger(row, "source_revision"); + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind kind; + try { + kind = + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.valueOf( + requireText(row, "source_kind")); + } catch (RuntimeException malformed) { + throw conflict("Current issuer inventory contains an unsupported source family"); + } + if (sourceRevision.compareTo(snapshotRevision) > 0) { + throw conflict("Current issuer inventory source is newer than its bootstrap snapshot"); + } + return new IssuerCohortSourceRow( + new CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow( + 0L, + kind, + sourceKey, + sourceRevision, + sourceJson, + sha256(sourceJson.getBytes(StandardCharsets.UTF_8)))); + }); } private static void requireCurrentCohortMatches( @@ -775,13 +770,12 @@ private static DerivedPlan derivePlan( for (var entry : bindings.entrySet()) { List rows = entry.getValue(); if (rows.size() != 1) { - rows.forEach( - row -> - blockers.add( - new PlanBlocker( - row.rowOrdinal(), - CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode - .CONFLICTING_RESERVATION_LINK))); + rows.forEach(row -> + blockers.add( + new PlanBlocker( + row.rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .CONFLICTING_RESERVATION_LINK))); continue; } BindingSource binding = rows.get(0); @@ -859,30 +853,26 @@ private static DerivedPlan derivePlan( List planned = initialLayoutReservations.stream() - .map( - reservation -> { - Long bindingOrdinal = - bindingOrdinalByReservation.get(reservation.reservationId()); - String bindingDigest = - bindingOrdinal == null - ? null - : byOrdinal.get(bindingOrdinal).sourceRowDigest(); - BigInteger partitionId; - try { - partitionId = - CanonicalGameplayBindingRef.fromExactBytes(reservation.bindingRef()) - .partitionId(intent.layoutDescriptor().partitionCount()); - } catch (RuntimeException malformed) { - blockers.add( - new PlanBlocker( - reservation.rowOrdinal(), - CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode - .UNREPRESENTABLE_RESERVATION)); - return null; - } - return new PlannedReservation( - reservation, bindingOrdinal, bindingDigest, partitionId); - }) + .map(reservation -> { + Long bindingOrdinal = bindingOrdinalByReservation.get(reservation.reservationId()); + String bindingDigest = + bindingOrdinal == null ? null : byOrdinal.get(bindingOrdinal).sourceRowDigest(); + BigInteger partitionId; + try { + partitionId = + CanonicalGameplayBindingRef.fromExactBytes(reservation.bindingRef()) + .partitionId(intent.layoutDescriptor().partitionCount()); + } catch (RuntimeException malformed) { + blockers.add( + new PlanBlocker( + reservation.rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .UNREPRESENTABLE_RESERVATION)); + return null; + } + return new PlannedReservation( + reservation, bindingOrdinal, bindingDigest, partitionId); + }) .filter(Objects::nonNull) .toList(); requireIssuerSourceLinks( @@ -902,13 +892,12 @@ private static DerivedPlan derivePlan( physicallyOversizedPartitions.add(entry.getKey()); entry .getValue() - .forEach( - item -> - blockers.add( - new PlanBlocker( - item.reservation().rowOrdinal(), - CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode - .PARTITION_CAPACITY_EXCEEDED))); + .forEach(item -> + blockers.add( + new PlanBlocker( + item.reservation().rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .PARTITION_CAPACITY_EXCEEDED))); } } Map> countedByPartition = new HashMap<>(); @@ -927,13 +916,12 @@ private static DerivedPlan derivePlan( && BigInteger.valueOf(partitionReservations.size()) .compareTo(intent.layoutDescriptor().partitionCapacity()) > 0) { - partitionReservations.forEach( - item -> - blockers.add( - new PlanBlocker( - item.reservation().rowOrdinal(), - CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode - .PARTITION_CAPACITY_EXCEEDED))); + partitionReservations.forEach(item -> + blockers.add( + new PlanBlocker( + item.reservation().rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .PARTITION_CAPACITY_EXCEEDED))); } } BigInteger aggregateCapacity = @@ -942,13 +930,12 @@ private static DerivedPlan derivePlan( .partitionCount() .multiply(intent.layoutDescriptor().partitionCapacity()); if (BigInteger.valueOf(countedReservations.size()).compareTo(aggregateCapacity) > 0) { - countedReservations.forEach( - item -> - blockers.add( - new PlanBlocker( - item.reservation().rowOrdinal(), - CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode - .AGGREGATE_CAPACITY_EXCEEDED))); + countedReservations.forEach(item -> + blockers.add( + new PlanBlocker( + item.reservation().rowOrdinal(), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .AGGREGATE_CAPACITY_EXCEEDED))); } blockers.sort( Comparator.comparingLong(PlanBlocker::sourceRowOrdinal) @@ -961,9 +948,8 @@ static List assignCanoni List sortedRows = currentRows.stream() .sorted( - Comparator.comparing( - (CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow row) -> - row.kind().name()) + Comparator.comparing((CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow row) -> + row.kind().name()) .thenComparing( CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey)) .toList(); @@ -1162,15 +1148,14 @@ private static List toBlocker List blockers, List cohort) { return java.util.stream.IntStream.range(0, blockers.size()) - .mapToObj( - index -> { - PlanBlocker blocker = blockers.get(index); - return new CanonicalGameplayIssuerPartitionBuildPlan.Blocker( - index, - blocker.sourceRowOrdinal(), - cohort.get((int) blocker.sourceRowOrdinal()).sourceRowDigest(), - blocker.code()); - }) + .mapToObj(index -> { + PlanBlocker blocker = blockers.get(index); + return new CanonicalGameplayIssuerPartitionBuildPlan.Blocker( + index, + blocker.sourceRowOrdinal(), + cohort.get((int) blocker.sourceRowOrdinal()).sourceRowDigest(), + blocker.code()); + }) .toList(); } @@ -1431,25 +1416,24 @@ private static CanonicalGameplayIssuerPartitionBuildPlan loadAndRequireExactPlan + BUILD_COHORT + " WHERE build_operation_id = ? ORDER BY source_row_ordinal", buildOperationId) - .map( - row -> { - String raw = requireText(row, "source_row_json"); - String digest = requireText(row, "source_row_digest"); - if (!sha256(raw.getBytes(StandardCharsets.UTF_8)).equals(digest) - || !intent.operationId().equals(row.get("source_operation_id", UUID.class)) - || !intent.issuerId().equals(row.get("issuer_id", String.class))) { - throw conflict("Build plan cohort row lost its exact bootstrap source link"); - } - return new IssuerCohortSourceRow( - new CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow( - requireLong(row, "source_row_ordinal"), - CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.valueOf( - requireText(row, "source_kind")), - requireText(row, "source_key"), - readBigInteger(row, "source_inventory_revision"), - raw, - digest)); - }); + .map(row -> { + String raw = requireText(row, "source_row_json"); + String digest = requireText(row, "source_row_digest"); + if (!sha256(raw.getBytes(StandardCharsets.UTF_8)).equals(digest) + || !intent.operationId().equals(row.get("source_operation_id", UUID.class)) + || !intent.issuerId().equals(row.get("issuer_id", String.class))) { + throw conflict("Build plan cohort row lost its exact bootstrap source link"); + } + return new IssuerCohortSourceRow( + new CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow( + requireLong(row, "source_row_ordinal"), + CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.valueOf( + requireText(row, "source_kind")), + requireText(row, "source_key"), + readBigInteger(row, "source_inventory_revision"), + raw, + digest)); + }); requireSameCohort(intent.cohortRows(), planRows); if (!intent.cohortDigest().equals(header.get("cohort_digest", String.class)) || planRows.size() != requireLong(header, "cohort_row_count")) { @@ -1463,21 +1447,18 @@ private static CanonicalGameplayIssuerPartitionBuildPlan loadAndRequireExactPlan + MEMBER_WORK + " WHERE build_operation_id = ? ORDER BY work_ordinal", buildOperationId) - .map( - row -> { - if (!intent.operationId().equals(row.get("bootstrap_operation_id", UUID.class)) - || !intent.issuerId().equals(row.get("issuer_id", String.class))) { - throw conflict("Member work lost its exact bootstrap plan linkage"); - } - CanonicalGameplayIssuerPartitionBuildPlan.MemberWork memberWork = - toMemberWork(row); - Boolean counted = row.get("counts_toward_capacity", Boolean.class); - if (!Objects.equals(counted, memberWork.countsTowardCapacity())) { - throw conflict( - "Member work capacity classification differs from its lifecycle"); - } - return memberWork; - }); + .map(row -> { + if (!intent.operationId().equals(row.get("bootstrap_operation_id", UUID.class)) + || !intent.issuerId().equals(row.get("issuer_id", String.class))) { + throw conflict("Member work lost its exact bootstrap plan linkage"); + } + CanonicalGameplayIssuerPartitionBuildPlan.MemberWork memberWork = toMemberWork(row); + Boolean counted = row.get("counts_toward_capacity", Boolean.class); + if (!Objects.equals(counted, memberWork.countsTowardCapacity())) { + throw conflict("Member work capacity classification differs from its lifecycle"); + } + return memberWork; + }); if (work.size() != requireLong(header, "member_work_count") || work.size() != derived.reservations().size()) { throw conflict("Build plan member work is incomplete or contains unplanned reservations"); @@ -1497,14 +1478,13 @@ private static CanonicalGameplayIssuerPartitionBuildPlan loadAndRequireExactPlan + BUILD_BLOCKER + " WHERE build_operation_id = ? ORDER BY blocker_ordinal", buildOperationId) - .map( - row -> - new CanonicalGameplayIssuerPartitionBuildPlan.Blocker( - requireLong(row, "blocker_ordinal"), - requireLong(row, "source_row_ordinal"), - requireText(row, "source_row_digest"), - CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode.valueOf( - requireText(row, "blocker_code")))); + .map(row -> + new CanonicalGameplayIssuerPartitionBuildPlan.Blocker( + requireLong(row, "blocker_ordinal"), + requireLong(row, "source_row_ordinal"), + requireText(row, "source_row_digest"), + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode.valueOf( + requireText(row, "blocker_code")))); List expectedBlockers = toBlockers(derived.blockers(), intent.cohortRows()); if (!sameBlockers(blockers, expectedBlockers) @@ -1800,14 +1780,13 @@ private static String digestCohortRows( .sorted( Comparator.comparingLong( CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::rowOrdinal)) - .forEach( - row -> { - frame(digest, Long.toString(row.rowOrdinal())); - frame(digest, row.kind().name()); - frame(digest, row.sourceKey()); - frame(digest, row.sourceInventoryRevision().toString()); - frame(digest, row.sourceRowDigest()); - }); + .forEach(row -> { + frame(digest, Long.toString(row.rowOrdinal())); + frame(digest, row.kind().name()); + frame(digest, row.sourceKey()); + frame(digest, row.sourceInventoryRevision().toString()); + frame(digest, row.sourceRowDigest()); + }); return "sha256:" + HexFormat.of().formatHex(digest.digest()); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationRepository.java index 65eff3f7b3..fb55cc5299 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationRepository.java @@ -89,43 +89,42 @@ CanonicalGameplayLegacyMigrationOperation begin( requireNonNil(cohortId, "cohortId"); requireNonNil(legacyWriterFence, "legacyWriterFence"); Objects.requireNonNull(storageIdentity, "storageIdentity"); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - Record existing = - transaction.fetchOne( - "SELECT * FROM " + OPERATION + " WHERE cohort_id = ? FOR UPDATE", cohortId); - if (existing != null) { - CanonicalGameplayLegacyMigrationOperation operation = toOperation(existing); - if (!operation.legacyWriterFence().equals(legacyWriterFence) - || !operation.storageIdentity().equals(storageIdentity)) { - throw conflict( - "The cohort is already bound to a different retained writer/storage fence"); - } - if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.VERIFIED) { - requirePublishedDispositionMatches(transaction, operation); - } - return operation; - } - - Record disposition = - transaction.fetchOne( - "SELECT disposition_state FROM " - + LEGACY_DISPOSITION - + " WHERE singleton_id = 1 FOR UPDATE"); - if (disposition == null - || !"REQUIRED".equals(disposition.get("disposition_state", String.class))) { - throw conflict( - "Legacy migration can start only while the V31 disposition remains REQUIRED"); - } - - UUID operationId = UUID.randomUUID(); - if (operationId.equals(new UUID(0L, 0L))) { - throw new IllegalStateException("UUID generator returned nil migration operation id"); - } - insertOperation(transaction, operationId, cohortId, legacyWriterFence, storageIdentity); - return readOperation(transaction, operationId, false); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + Record existing = + transaction.fetchOne( + "SELECT * FROM " + OPERATION + " WHERE cohort_id = ? FOR UPDATE", cohortId); + if (existing != null) { + CanonicalGameplayLegacyMigrationOperation operation = toOperation(existing); + if (!operation.legacyWriterFence().equals(legacyWriterFence) + || !operation.storageIdentity().equals(storageIdentity)) { + throw conflict( + "The cohort is already bound to a different retained writer/storage fence"); + } + if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.VERIFIED) { + requirePublishedDispositionMatches(transaction, operation); + } + return operation; + } + + Record disposition = + transaction.fetchOne( + "SELECT disposition_state FROM " + + LEGACY_DISPOSITION + + " WHERE singleton_id = 1 FOR UPDATE"); + if (disposition == null + || !"REQUIRED".equals(disposition.get("disposition_state", String.class))) { + throw conflict( + "Legacy migration can start only while the V31 disposition remains REQUIRED"); + } + + UUID operationId = UUID.randomUUID(); + if (operationId.equals(new UUID(0L, 0L))) { + throw new IllegalStateException("UUID generator returned nil migration operation id"); + } + insertOperation(transaction, operationId, cohortId, legacyWriterFence, storageIdentity); + return readOperation(transaction, operationId, false); + }); } CanonicalGameplayLegacyMigrationOperation read(UUID operationId) { @@ -166,18 +165,15 @@ CanonicalGameplayLegacyMigrationOperation captureSnapshots( blockState = CanonicalGameplayLegacyMigrationOperation.State.BLOCKED; blockReason = "SOURCE_INVENTORY_INCOMPLETE"; } else if (source.entries().stream() - .anyMatch( - entry -> - entry.disposition() - == CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition - .CREDENTIAL_BEARING)) { + .anyMatch(entry -> + entry.disposition() + == CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition.CREDENTIAL_BEARING)) { blockState = CanonicalGameplayLegacyMigrationOperation.State.BLOCKED; blockReason = "CREDENTIAL_BEARING_SOURCE"; } else if (source.entries().stream() - .anyMatch( - entry -> - entry.disposition() - == CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition.UNKNOWN)) { + .anyMatch(entry -> + entry.disposition() + == CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition.UNKNOWN)) { blockState = CanonicalGameplayLegacyMigrationOperation.State.BLOCKED; blockReason = "UNKNOWN_SOURCE_RECORD"; } else if (!source.everyEntryIsReconciled()) { @@ -187,81 +183,79 @@ CanonicalGameplayLegacyMigrationOperation captureSnapshots( final CanonicalGameplayLegacyMigrationOperation.State finalBlockState = blockState; final String finalBlockReason = blockReason; String sourceDigest = digestSource(source); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"); - Record operationRow = lockOperation(transaction, operationId); - CanonicalGameplayLegacyMigrationOperation current = toOperation(operationRow); - if (current.state() == CanonicalGameplayLegacyMigrationOperation.State.VERIFIED - || current.state() == CanonicalGameplayLegacyMigrationOperation.State.BLOCKED) { - return current; - } - SnapshotJson snapshotJson = readCanonicalSnapshot(transaction); - if (!snapshotJson.revision().equals(canonical.inventoryRevision())) { - return block(transaction, operationId, "CANONICAL_SNAPSHOT_CHANGED"); - } - String canonicalDigest = sha256(snapshotJson.json()); - if (current.state() != CanonicalGameplayLegacyMigrationOperation.State.FENCED) { - if (!Objects.equals(current.sourceSnapshotDigest(), sourceDigest) - || !Objects.equals( - current.canonicalSnapshotRevision(), canonical.inventoryRevision()) - || !Objects.equals(current.canonicalSnapshotDigest(), canonicalDigest)) { - return block(transaction, operationId, "SNAPSHOT_CHANGED_ON_REPLAY"); - } - return current; - } - - BigInteger sourceRevision = - readBigInteger( - Objects.requireNonNull( - transaction.fetchOne( - "SELECT nextval('game_session_canonical_legacy_migration_source_revision_seq') AS revision"), - "legacy migration source revision sequence must exist"), - "revision"); - long ordinal = 0L; - List entries = - source.entries().stream() - .sorted( - Comparator.comparing( - CanonicalGameplayLegacyMigrationSourceSnapshot.Entry::sourceKeyDigest)) - .toList(); - for (CanonicalGameplayLegacyMigrationSourceSnapshot.Entry entry : entries) { - transaction.execute( - "INSERT INTO " - + SOURCE_ENTRY - + " (operation_id, row_ordinal, source_family, source_key_digest, disposition)" - + " VALUES (?, ?, ?, ?, ?)", - operationId, - ordinal++, - entry.family().name(), - entry.sourceKeyDigest(), - entry.disposition().name()); - } - - String nextState = finalBlockState == null ? "SNAPSHOTTED" : "BLOCKED"; - requireOne( - transaction.execute( - "UPDATE " - + OPERATION - + " SET state = ?, source_snapshot_revision = ?, source_snapshot_digest = ?," - + " source_snapshot_entry_count = ?, canonical_snapshot_revision = ?," - + " source_snapshot_families = ?::jsonb, canonical_snapshot_digest = ?, canonical_snapshot = ?::jsonb," - + " blocked_reason = ?, updated_at = CURRENT_TIMESTAMP" - + " WHERE operation_id = ? AND state = 'FENCED'", - nextState, - decimal(sourceRevision), - sourceDigest, - entries.size(), - decimal(canonical.inventoryRevision()), - familiesJson(source.scannedFamilies()), - canonicalDigest, - snapshotJson.json(), - finalBlockReason, - operationId), - "Migration operation changed while its snapshots were being staged"); - return readOperation(transaction, operationId, false); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"); + Record operationRow = lockOperation(transaction, operationId); + CanonicalGameplayLegacyMigrationOperation current = toOperation(operationRow); + if (current.state() == CanonicalGameplayLegacyMigrationOperation.State.VERIFIED + || current.state() == CanonicalGameplayLegacyMigrationOperation.State.BLOCKED) { + return current; + } + SnapshotJson snapshotJson = readCanonicalSnapshot(transaction); + if (!snapshotJson.revision().equals(canonical.inventoryRevision())) { + return block(transaction, operationId, "CANONICAL_SNAPSHOT_CHANGED"); + } + String canonicalDigest = sha256(snapshotJson.json()); + if (current.state() != CanonicalGameplayLegacyMigrationOperation.State.FENCED) { + if (!Objects.equals(current.sourceSnapshotDigest(), sourceDigest) + || !Objects.equals(current.canonicalSnapshotRevision(), canonical.inventoryRevision()) + || !Objects.equals(current.canonicalSnapshotDigest(), canonicalDigest)) { + return block(transaction, operationId, "SNAPSHOT_CHANGED_ON_REPLAY"); + } + return current; + } + + BigInteger sourceRevision = + readBigInteger( + Objects.requireNonNull( + transaction.fetchOne( + "SELECT nextval('game_session_canonical_legacy_migration_source_revision_seq') AS revision"), + "legacy migration source revision sequence must exist"), + "revision"); + long ordinal = 0L; + List entries = + source.entries().stream() + .sorted( + Comparator.comparing( + CanonicalGameplayLegacyMigrationSourceSnapshot.Entry::sourceKeyDigest)) + .toList(); + for (CanonicalGameplayLegacyMigrationSourceSnapshot.Entry entry : entries) { + transaction.execute( + "INSERT INTO " + + SOURCE_ENTRY + + " (operation_id, row_ordinal, source_family, source_key_digest, disposition)" + + " VALUES (?, ?, ?, ?, ?)", + operationId, + ordinal++, + entry.family().name(), + entry.sourceKeyDigest(), + entry.disposition().name()); + } + + String nextState = finalBlockState == null ? "SNAPSHOTTED" : "BLOCKED"; + requireOne( + transaction.execute( + "UPDATE " + + OPERATION + + " SET state = ?, source_snapshot_revision = ?, source_snapshot_digest = ?," + + " source_snapshot_entry_count = ?, canonical_snapshot_revision = ?," + + " source_snapshot_families = ?::jsonb, canonical_snapshot_digest = ?, canonical_snapshot = ?::jsonb," + + " blocked_reason = ?, updated_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND state = 'FENCED'", + nextState, + decimal(sourceRevision), + sourceDigest, + entries.size(), + decimal(canonical.inventoryRevision()), + familiesJson(source.scannedFamilies()), + canonicalDigest, + snapshotJson.json(), + finalBlockReason, + operationId), + "Migration operation changed while its snapshots were being staged"); + return readOperation(transaction, operationId, false); + }); } /** @@ -270,38 +264,36 @@ CanonicalGameplayLegacyMigrationOperation captureSnapshots( CanonicalGameplayLegacyMigrationOperation markRebuilt(UUID operationId) { requireNoAmbientTransaction(); requireNonNil(operationId, "operationId"); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"); - Record row = lockOperation(transaction, operationId); - CanonicalGameplayLegacyMigrationOperation operation = toOperation(row); - if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.BLOCKED - || operation.state() == CanonicalGameplayLegacyMigrationOperation.State.VERIFIED - || operation.state() - == CanonicalGameplayLegacyMigrationOperation.State.READBACK_VERIFIED) { - return operation; - } - if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.REBUILT) { - return operation; - } - if (operation.state() != CanonicalGameplayLegacyMigrationOperation.State.SNAPSHOTTED) { - throw conflict("Only a complete staged source and canonical snapshot may be rebuilt"); - } - requireStoredSnapshotsConsistent(transaction, operation); - String expectedProjectionDigest = - expectedActiveProjectionDigest(transaction, operationId); - requireOne( - transaction.execute( - "UPDATE " - + OPERATION - + " SET state = 'REBUILT', rebuild_digest = ?, updated_at = CURRENT_TIMESTAMP" - + " WHERE operation_id = ? AND state = 'SNAPSHOTTED'", - expectedProjectionDigest, - operationId), - "Migration operation changed before exact index rebuild was retained"); - return readOperation(transaction, operationId, false); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"); + Record row = lockOperation(transaction, operationId); + CanonicalGameplayLegacyMigrationOperation operation = toOperation(row); + if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.BLOCKED + || operation.state() == CanonicalGameplayLegacyMigrationOperation.State.VERIFIED + || operation.state() + == CanonicalGameplayLegacyMigrationOperation.State.READBACK_VERIFIED) { + return operation; + } + if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.REBUILT) { + return operation; + } + if (operation.state() != CanonicalGameplayLegacyMigrationOperation.State.SNAPSHOTTED) { + throw conflict("Only a complete staged source and canonical snapshot may be rebuilt"); + } + requireStoredSnapshotsConsistent(transaction, operation); + String expectedProjectionDigest = expectedActiveProjectionDigest(transaction, operationId); + requireOne( + transaction.execute( + "UPDATE " + + OPERATION + + " SET state = 'REBUILT', rebuild_digest = ?, updated_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND state = 'SNAPSHOTTED'", + expectedProjectionDigest, + operationId), + "Migration operation changed before exact index rebuild was retained"); + return readOperation(transaction, operationId, false); + }); } /** @@ -320,65 +312,63 @@ CanonicalGameplayLegacyMigrationOperation recordReadback( if (!actualCanonical.equals(canonical)) { return block(operationId, "CANONICAL_READBACK_NOT_FROM_OWNER_REPOSITORY"); } - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"); - Record row = lockOperation(transaction, operationId); - CanonicalGameplayLegacyMigrationOperation operation = toOperation(row); - if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.BLOCKED - || operation.state() == CanonicalGameplayLegacyMigrationOperation.State.VERIFIED) { - return operation; - } - if (operation.state() != CanonicalGameplayLegacyMigrationOperation.State.REBUILT - && operation.state() - != CanonicalGameplayLegacyMigrationOperation.State.READBACK_VERIFIED) { - throw conflict("Exact namespace readback is not available before rebuild"); - } - requireStoredSnapshotsConsistent(transaction, operation); - SnapshotJson snapshotJson = readCanonicalSnapshot(transaction); - if (!snapshotJson.revision().equals(canonical.inventoryRevision()) - || !snapshotJson.revision().equals(operation.canonicalSnapshotRevision()) - || !sha256(snapshotJson.json()).equals(operation.canonicalSnapshotDigest())) { - return block(transaction, operationId, "CANONICAL_SNAPSHOT_CHANGED_BEFORE_READBACK"); - } - - List expected = activeBindings(actualCanonical); - if (!sameRows(expected, readback.sessionRecords()) - || !sameRows(expected, readback.characterIndexRecords()) - || !readback.remainingLegacySourceKeyDigests().isEmpty() - || !readback.unexpectedNamespaceKeyDigests().isEmpty()) { - return block(transaction, operationId, "INDEX_READBACK_MISMATCH"); - } - - String readbackDigest = digestReadback(readback); - if (operation.state() - == CanonicalGameplayLegacyMigrationOperation.State.READBACK_VERIFIED) { - if (!operation.namespaceIndexReadbackDigest().equals(readbackDigest)) { - return block(transaction, operationId, "READBACK_CHANGED_ON_REPLAY"); - } - return operation; - } - BigInteger readbackRevision = - readBigInteger( - Objects.requireNonNull( - transaction.fetchOne( - "SELECT nextval('game_session_canonical_legacy_migration_readback_revision_seq') AS revision"), - "legacy migration readback revision sequence must exist"), - "revision"); - requireOne( - transaction.execute( - "UPDATE " - + OPERATION - + " SET state = 'READBACK_VERIFIED', namespace_index_readback_revision = ?," - + " namespace_index_readback_digest = ?, updated_at = CURRENT_TIMESTAMP" - + " WHERE operation_id = ? AND state = 'REBUILT'", - decimal(readbackRevision), - readbackDigest, - operationId), - "Migration operation changed before exact index readback was retained"); - return readOperation(transaction, operationId, false); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"); + Record row = lockOperation(transaction, operationId); + CanonicalGameplayLegacyMigrationOperation operation = toOperation(row); + if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.BLOCKED + || operation.state() == CanonicalGameplayLegacyMigrationOperation.State.VERIFIED) { + return operation; + } + if (operation.state() != CanonicalGameplayLegacyMigrationOperation.State.REBUILT + && operation.state() + != CanonicalGameplayLegacyMigrationOperation.State.READBACK_VERIFIED) { + throw conflict("Exact namespace readback is not available before rebuild"); + } + requireStoredSnapshotsConsistent(transaction, operation); + SnapshotJson snapshotJson = readCanonicalSnapshot(transaction); + if (!snapshotJson.revision().equals(canonical.inventoryRevision()) + || !snapshotJson.revision().equals(operation.canonicalSnapshotRevision()) + || !sha256(snapshotJson.json()).equals(operation.canonicalSnapshotDigest())) { + return block(transaction, operationId, "CANONICAL_SNAPSHOT_CHANGED_BEFORE_READBACK"); + } + + List expected = activeBindings(actualCanonical); + if (!sameRows(expected, readback.sessionRecords()) + || !sameRows(expected, readback.characterIndexRecords()) + || !readback.remainingLegacySourceKeyDigests().isEmpty() + || !readback.unexpectedNamespaceKeyDigests().isEmpty()) { + return block(transaction, operationId, "INDEX_READBACK_MISMATCH"); + } + + String readbackDigest = digestReadback(readback); + if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.READBACK_VERIFIED) { + if (!operation.namespaceIndexReadbackDigest().equals(readbackDigest)) { + return block(transaction, operationId, "READBACK_CHANGED_ON_REPLAY"); + } + return operation; + } + BigInteger readbackRevision = + readBigInteger( + Objects.requireNonNull( + transaction.fetchOne( + "SELECT nextval('game_session_canonical_legacy_migration_readback_revision_seq') AS revision"), + "legacy migration readback revision sequence must exist"), + "revision"); + requireOne( + transaction.execute( + "UPDATE " + + OPERATION + + " SET state = 'READBACK_VERIFIED', namespace_index_readback_revision = ?," + + " namespace_index_readback_digest = ?, updated_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND state = 'REBUILT'", + decimal(readbackRevision), + readbackDigest, + operationId), + "Migration operation changed before exact index readback was retained"); + return readOperation(transaction, operationId, false); + }); } /** @@ -391,87 +381,85 @@ CanonicalGameplayLegacyMigrationOperation publishVerified( requireNoAmbientTransaction(); requireNonNil(operationId, "operationId"); Objects.requireNonNull(cohort, "cohort"); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"); - Record row = lockOperation(transaction, operationId); - CanonicalGameplayLegacyMigrationOperation operation = toOperation(row); - requireSameCohort(operation, cohort); - cohort.requireStillFenced(operation.storageIdentity()); - if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.VERIFIED) { - requirePublishedDispositionMatches(transaction, operation); - return operation; - } - if (operation.state() - != CanonicalGameplayLegacyMigrationOperation.State.READBACK_VERIFIED) { - throw conflict("Only exact complete readback evidence may publish the V31 disposition"); - } + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"); + Record row = lockOperation(transaction, operationId); + CanonicalGameplayLegacyMigrationOperation operation = toOperation(row); + requireSameCohort(operation, cohort); + cohort.requireStillFenced(operation.storageIdentity()); + if (operation.state() == CanonicalGameplayLegacyMigrationOperation.State.VERIFIED) { + requirePublishedDispositionMatches(transaction, operation); + return operation; + } + if (operation.state() != CanonicalGameplayLegacyMigrationOperation.State.READBACK_VERIFIED) { + throw conflict("Only exact complete readback evidence may publish the V31 disposition"); + } - Record clock = - Objects.requireNonNull( - transaction.fetchOne( - "SELECT inventory_revision FROM " - + INVENTORY_CLOCK - + " WHERE singleton_id = 1 FOR UPDATE"), - "canonical inventory clock row must exist"); - BigInteger currentRevision = readBigInteger(clock, "inventory_revision"); - requireStoredSourceSnapshotConsistent(transaction, operation); - requireStoredCanonicalSnapshotConsistent(transaction, operation); - if (!currentRevision.equals(operation.canonicalSnapshotRevision())) { - throw conflict("Canonical inventory revision changed while migration fences were held"); - } - SnapshotJson currentSnapshot = readCanonicalSnapshot(transaction); - if (!currentSnapshot.revision().equals(currentRevision) - || !sha256(currentSnapshot.json()).equals(operation.canonicalSnapshotDigest())) { - throw conflict("Canonical durable inventory changed after staged readback"); - } - - BigInteger publicationRevision = currentRevision; - if (publicationRevision.signum() == 0) { - publicationRevision = BigInteger.ONE; - requireOne( - transaction.execute( - "UPDATE " - + INVENTORY_CLOCK - + " SET inventory_revision = ? WHERE singleton_id = 1 AND inventory_revision = 0", - decimal(publicationRevision)), - "Empty canonical snapshot could not acquire its owner publication revision"); - } - String evidenceDigest = digestEvidence(operation, publicationRevision); - requireOne( - transaction.execute( - "UPDATE " - + LEGACY_DISPOSITION - + " SET disposition_state = 'VERIFIED', cohort_id = ?, owner_operation_id = ?," - + " legacy_writer_fence = ?, source_snapshot_revision = ?," - + " canonical_inventory_revision = ?, namespace_index_readback_revision = ?," - + " evidence_digest = ? WHERE singleton_id = 1 AND disposition_state = 'REQUIRED'", - operation.cohortId(), - operation.operationId(), - operation.legacyWriterFence(), - decimal(operation.sourceSnapshotRevision()), - decimal(publicationRevision), - decimal(operation.namespaceIndexReadbackRevision()), - evidenceDigest), - "V31 disposition was already changed by a different migration owner"); - requireOne( - transaction.execute( - "UPDATE " - + OPERATION - + " SET state = 'VERIFIED', publication_inventory_revision = ?," - + " evidence_digest = ?, updated_at = CURRENT_TIMESTAMP" - + " WHERE operation_id = ? AND state = 'READBACK_VERIFIED'", - decimal(publicationRevision), - evidenceDigest, - operationId), - "Migration operation changed before atomic V31 publication"); - cohort.requireStillFenced(operation.storageIdentity()); - CanonicalGameplayLegacyMigrationOperation published = - readOperation(transaction, operationId, false); - requirePublishedDispositionMatches(transaction, published); - return published; - }); + Record clock = + Objects.requireNonNull( + transaction.fetchOne( + "SELECT inventory_revision FROM " + + INVENTORY_CLOCK + + " WHERE singleton_id = 1 FOR UPDATE"), + "canonical inventory clock row must exist"); + BigInteger currentRevision = readBigInteger(clock, "inventory_revision"); + requireStoredSourceSnapshotConsistent(transaction, operation); + requireStoredCanonicalSnapshotConsistent(transaction, operation); + if (!currentRevision.equals(operation.canonicalSnapshotRevision())) { + throw conflict("Canonical inventory revision changed while migration fences were held"); + } + SnapshotJson currentSnapshot = readCanonicalSnapshot(transaction); + if (!currentSnapshot.revision().equals(currentRevision) + || !sha256(currentSnapshot.json()).equals(operation.canonicalSnapshotDigest())) { + throw conflict("Canonical durable inventory changed after staged readback"); + } + + BigInteger publicationRevision = currentRevision; + if (publicationRevision.signum() == 0) { + publicationRevision = BigInteger.ONE; + requireOne( + transaction.execute( + "UPDATE " + + INVENTORY_CLOCK + + " SET inventory_revision = ? WHERE singleton_id = 1 AND inventory_revision = 0", + decimal(publicationRevision)), + "Empty canonical snapshot could not acquire its owner publication revision"); + } + String evidenceDigest = digestEvidence(operation, publicationRevision); + requireOne( + transaction.execute( + "UPDATE " + + LEGACY_DISPOSITION + + " SET disposition_state = 'VERIFIED', cohort_id = ?, owner_operation_id = ?," + + " legacy_writer_fence = ?, source_snapshot_revision = ?," + + " canonical_inventory_revision = ?, namespace_index_readback_revision = ?," + + " evidence_digest = ? WHERE singleton_id = 1 AND disposition_state = 'REQUIRED'", + operation.cohortId(), + operation.operationId(), + operation.legacyWriterFence(), + decimal(operation.sourceSnapshotRevision()), + decimal(publicationRevision), + decimal(operation.namespaceIndexReadbackRevision()), + evidenceDigest), + "V31 disposition was already changed by a different migration owner"); + requireOne( + transaction.execute( + "UPDATE " + + OPERATION + + " SET state = 'VERIFIED', publication_inventory_revision = ?," + + " evidence_digest = ?, updated_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND state = 'READBACK_VERIFIED'", + decimal(publicationRevision), + evidenceDigest, + operationId), + "Migration operation changed before atomic V31 publication"); + cohort.requireStillFenced(operation.storageIdentity()); + CanonicalGameplayLegacyMigrationOperation published = + readOperation(transaction, operationId, false); + requirePublishedDispositionMatches(transaction, published); + return published; + }); } CanonicalGameplayLegacyMigrationOperation block(UUID operationId, String reason) { @@ -582,15 +570,14 @@ private static CanonicalGameplayLegacyMigrationSourceSnapshot loadSourceSnapshot + SOURCE_ENTRY + " WHERE operation_id = ? ORDER BY row_ordinal", operationId) - .map( - row -> { - return new CanonicalGameplayLegacyMigrationSourceSnapshot.Entry( - CanonicalGameplayLegacyMigrationSourceSnapshot.Family.valueOf( - row.get("source_family", String.class)), - row.get("source_key_digest", String.class), - CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition.valueOf( - row.get("disposition", String.class))); - }); + .map(row -> { + return new CanonicalGameplayLegacyMigrationSourceSnapshot.Entry( + CanonicalGameplayLegacyMigrationSourceSnapshot.Family.valueOf( + row.get("source_family", String.class)), + row.get("source_key_digest", String.class), + CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition.valueOf( + row.get("disposition", String.class))); + }); Long storedEntryCount = operation.get("source_snapshot_entry_count", Long.class); if (!Objects.equals(storedEntryCount, (long) entries.size())) { throw conflict("Persisted legacy source inventory entry count is incomplete"); @@ -709,9 +696,8 @@ private static String expectedActiveProjectionDigest(DSLContext transaction, UUI private static List activeBindings( CanonicalGameplayBindingInventorySnapshot snapshot) { return snapshot.bindings().stream() - .filter( - binding -> - binding.lifecycle() == CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE) + .filter(binding -> + binding.lifecycle() == CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE) .sorted(Comparator.comparing(binding -> hex(binding.bindingRef().bytes()))) .toList(); } @@ -739,12 +725,11 @@ private static String digestSource(CanonicalGameplayLegacyMigrationSourceSnapsho .sorted( Comparator.comparing( CanonicalGameplayLegacyMigrationSourceSnapshot.Entry::sourceKeyDigest)) - .forEach( - entry -> { - append(framed, entry.family().name()); - append(framed, entry.sourceKeyDigest()); - append(framed, entry.disposition().name()); - }); + .forEach(entry -> { + append(framed, entry.family().name()); + append(framed, entry.sourceKeyDigest()); + append(framed, entry.disposition().name()); + }); return sha256(framed.toString()); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyRedisSource.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyRedisSource.java index 12c38bc445..1edb1306a8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyRedisSource.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyRedisSource.java @@ -89,15 +89,14 @@ public CanonicalGameplayLegacyMigrationSourceSnapshot captureEveryKnownFamily( } List entries = new ArrayList<>(); - first.forEach( - (key, family) -> - entries.add( - new CanonicalGameplayLegacyMigrationSourceSnapshot.Entry( - family, - digestKey(key), - family == CanonicalGameplayLegacyMigrationSourceSnapshot.Family.UNCLASSIFIED - ? CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition.UNKNOWN - : CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition.UNMAPPABLE))); + first.forEach((key, family) -> + entries.add( + new CanonicalGameplayLegacyMigrationSourceSnapshot.Entry( + family, + digestKey(key), + family == CanonicalGameplayLegacyMigrationSourceSnapshot.Family.UNCLASSIFIED + ? CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition.UNKNOWN + : CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition.UNMAPPABLE))); return new CanonicalGameplayLegacyMigrationSourceSnapshot(KNOWN_FAMILIES, entries); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java index 2664952edc..a5297ae81f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java @@ -231,12 +231,11 @@ private CanonicalGameplayMigrationDriverMain() {} static void launch(String[] args, java.io.PrintStream protocolOutput, java.io.PrintStream error) { ScheduledExecutorService deadline = - Executors.newSingleThreadScheduledExecutor( - task -> { - Thread thread = new Thread(task, "gs-migration-driver-deadline"); - thread.setDaemon(true); - return thread; - }); + Executors.newSingleThreadScheduledExecutor(task -> { + Thread thread = new Thread(task, "gs-migration-driver-deadline"); + thread.setDaemon(true); + return thread; + }); deadline.schedule( () -> { error.println( @@ -464,12 +463,11 @@ private static void requireCompletePackagedMigrationSources( List migrations) { if (migrations.size() != EXPECTED_MIGRATION_SCRIPTS.size() || migrations.stream() - .anyMatch( - migration -> - !expectedMigrationScriptName(migration.script()) - .equals(EXPECTED_MIGRATION_SCRIPTS.get(migration.version())) - || !"SQL".equals(migration.type()) - || migration.checksum() == null)) { + .anyMatch(migration -> + !expectedMigrationScriptName(migration.script()) + .equals(EXPECTED_MIGRATION_SCRIPTS.get(migration.version())) + || !"SQL".equals(migration.type()) + || migration.checksum() == null)) { throw new IllegalStateException("packaged migration source inventory was incomplete"); } } @@ -974,20 +972,18 @@ private Map readRedis() { } try { Map values = - redis.execute( - (RedisConnection connection) -> { - requireStandaloneRedisTopology(connection.serverCommands().info("cluster")); - Properties info = connection.serverCommands().info("server"); - String runId = info == null ? null : info.getProperty("run_id"); - Properties plainConfiguration = connection.serverCommands().getConfig("port"); - String plainPortText = - plainConfiguration == null ? null : plainConfiguration.getProperty("port"); - Properties tlsConfiguration = connection.serverCommands().getConfig("tls-port"); - String tlsPortText = - tlsConfiguration == null ? null : tlsConfiguration.getProperty("tls-port"); - return validatedRedisObservation( - runId, plainPortText, tlsPortText, trustCaDigest); - }); + redis.execute((RedisConnection connection) -> { + requireStandaloneRedisTopology(connection.serverCommands().info("cluster")); + Properties info = connection.serverCommands().info("server"); + String runId = info == null ? null : info.getProperty("run_id"); + Properties plainConfiguration = connection.serverCommands().getConfig("port"); + String plainPortText = + plainConfiguration == null ? null : plainConfiguration.getProperty("port"); + Properties tlsConfiguration = connection.serverCommands().getConfig("tls-port"); + String tlsPortText = + tlsConfiguration == null ? null : tlsConfiguration.getProperty("tls-port"); + return validatedRedisObservation(runId, plainPortText, tlsPortText, trustCaDigest); + }); if (values == null) { throw new IllegalStateException("Redis live observation was unavailable"); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java index 456833fdce..9ff629d367 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java @@ -118,19 +118,17 @@ final class CanonicalGameplayMigrationDriverProtocol implements AutoCloseable { .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) .enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS); reader = - Executors.newSingleThreadExecutor( - task -> { - Thread thread = new Thread(task, "gs-migration-driver-stdin"); - thread.setDaemon(true); - return thread; - }); + Executors.newSingleThreadExecutor(task -> { + Thread thread = new Thread(task, "gs-migration-driver-stdin"); + thread.setDaemon(true); + return thread; + }); writer = - Executors.newSingleThreadExecutor( - task -> { - Thread thread = new Thread(task, "gs-migration-driver-stdout"); - thread.setDaemon(true); - return thread; - }); + Executors.newSingleThreadExecutor(task -> { + Thread thread = new Thread(task, "gs-migration-driver-stdout"); + thread.setDaemon(true); + return thread; + }); } Initialization readInitialization() { @@ -293,15 +291,14 @@ private void writeFrame(Map value) { throw reject("migration driver protocol output could not be encoded"); } Future writing = - writer.submit( - () -> { - try { - output.write(frame); - output.flush(); - } catch (IOException failed) { - throw new java.io.UncheckedIOException(failed); - } - }); + writer.submit(() -> { + try { + output.write(frame); + output.flush(); + } catch (IOException failed) { + throw new java.io.UncheckedIOException(failed); + } + }); try { writing.get(outputFrameTimeout.toNanos(), TimeUnit.NANOSECONDS); } catch (TimeoutException timedOut) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java index c7b9291edb..481efe5998 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSession.java @@ -265,13 +265,12 @@ private static void requireTemplateOnlyHasTimePlaceholders(byte[] templateBytes) || !CONTINUITY_PLACEHOLDER.equals(requiredText(root, "continuityBindingExpiresAt"))) throw invalid(); root.propertyNames() - .forEach( - name -> { - if (!name.equals("admissionAt") && !name.equals("continuityBindingExpiresAt")) { - JsonNode value = root.get(name); - if (containsPlaceholder(value)) throw invalid(); - } - }); + .forEach(name -> { + if (!name.equals("admissionAt") && !name.equals("continuityBindingExpiresAt")) { + JsonNode value = root.get(name); + if (containsPlaceholder(value)) throw invalid(); + } + }); } catch (RuntimeException malformed) { throw invalid(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionReadRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionReadRepository.java index fead34a11f..8ec21fdd43 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionReadRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionReadRepository.java @@ -133,113 +133,108 @@ public FinalResult readActualOriginalFinalAdmission( private SourceSnapshot readCurrentSource(Selector selector) { requireNoAmbientTransaction(); SourceRows rows = - dsl.transactionResult( - configuration -> { - DSLContext tx = DSL.using(configuration); - tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); - Record transition = - tx.fetchOne( - "SELECT * FROM " + TRANSITION + " WHERE transition_id = ?", - selector.bindingDecisionId()); - if (transition == null) throw conflict("Original NEW transition is unavailable"); + dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + Record transition = + tx.fetchOne( + "SELECT * FROM " + TRANSITION + " WHERE transition_id = ?", + selector.bindingDecisionId()); + if (transition == null) throw conflict("Original NEW transition is unavailable"); - byte[] bindingRef = requiredBytes(transition, "candidate_binding_ref"); - Record candidateRow = - tx.fetchOne("SELECT * FROM " + INVENTORY + " WHERE binding_ref = ?", bindingRef); - Record reservationRow = - tx.fetchOne( - "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ?", - requiredUuid(transition, "issuer_reservation_id")); - byte[] candidateBytes = requiredBytes(transition, "original_new_candidate_bytes"); - CanonicalGameplayOriginalNewCandidate candidate = - CanonicalGameplayOriginalNewCandidate.parseCanonical(candidateBytes); - AccountGameplayAdmissionLeaseEvidence lease = - requireOriginalSources(selector, workloadNamespace, transition, candidate); - requireCandidateAndReservationRows( - transition, candidateRow, reservationRow, candidate); + byte[] bindingRef = requiredBytes(transition, "candidate_binding_ref"); + Record candidateRow = + tx.fetchOne("SELECT * FROM " + INVENTORY + " WHERE binding_ref = ?", bindingRef); + Record reservationRow = + tx.fetchOne( + "SELECT * FROM " + RESERVATION + " WHERE reservation_id = ?", + requiredUuid(transition, "issuer_reservation_id")); + byte[] candidateBytes = requiredBytes(transition, "original_new_candidate_bytes"); + CanonicalGameplayOriginalNewCandidate candidate = + CanonicalGameplayOriginalNewCandidate.parseCanonical(candidateBytes); + AccountGameplayAdmissionLeaseEvidence lease = + requireOriginalSources(selector, workloadNamespace, transition, candidate); + requireCandidateAndReservationRows(transition, candidateRow, reservationRow, candidate); - List accountRows = - tx.fetch( - "SELECT * FROM " - + ACCOUNT_OBLIGATION - + " WHERE transition_id = ? ORDER BY obligation_ordinal", - selector.bindingDecisionId()); - List accountRepairRows = - tx.fetch( - "SELECT * FROM " - + ACCOUNT_MEMBER_REPAIR - + " WHERE transition_id = ? AND obligation_ordinal = 0", - selector.bindingDecisionId()); - Record accountControlRow = - tx.fetchOne( - "SELECT * FROM " + ACCOUNT_COVERAGE_CONTROL + " WHERE account_id = ?", - candidate.bindingIdentity().accountId()); - List issuerObligationRows = - tx.fetch( - "SELECT * FROM " - + ISSUER_OBLIGATION - + " WHERE transition_id = ? AND binding_ref = ?", - selector.bindingDecisionId(), - bindingRef); - Record regionRow = - tx.fetchOne( - "SELECT * FROM " + REGION_OBLIGATION + " WHERE transition_id = ?", - selector.bindingDecisionId()); - List issuerAckRows = - tx.fetch( - "SELECT * FROM " - + ISSUER_ACK - + " WHERE transition_id = ? AND binding_ref = ?", - selector.bindingDecisionId(), - bindingRef); - Record tagRow = - tx.fetchOne( - "SELECT allocation_version, tenant_gameplay_tag FROM " - + TENANT_TAG - + " WHERE tenant_id = ?", - candidate.bindingIdentity().tenantId()); + List accountRows = + tx.fetch( + "SELECT * FROM " + + ACCOUNT_OBLIGATION + + " WHERE transition_id = ? ORDER BY obligation_ordinal", + selector.bindingDecisionId()); + List accountRepairRows = + tx.fetch( + "SELECT * FROM " + + ACCOUNT_MEMBER_REPAIR + + " WHERE transition_id = ? AND obligation_ordinal = 0", + selector.bindingDecisionId()); + Record accountControlRow = + tx.fetchOne( + "SELECT * FROM " + ACCOUNT_COVERAGE_CONTROL + " WHERE account_id = ?", + candidate.bindingIdentity().accountId()); + List issuerObligationRows = + tx.fetch( + "SELECT * FROM " + + ISSUER_OBLIGATION + + " WHERE transition_id = ? AND binding_ref = ?", + selector.bindingDecisionId(), + bindingRef); + Record regionRow = + tx.fetchOne( + "SELECT * FROM " + REGION_OBLIGATION + " WHERE transition_id = ?", + selector.bindingDecisionId()); + List issuerAckRows = + tx.fetch( + "SELECT * FROM " + ISSUER_ACK + " WHERE transition_id = ? AND binding_ref = ?", + selector.bindingDecisionId(), + bindingRef); + Record tagRow = + tx.fetchOne( + "SELECT allocation_version, tenant_gameplay_tag FROM " + + TENANT_TAG + + " WHERE tenant_id = ?", + candidate.bindingIdentity().tenantId()); - requireAccountAcknowledgement( - accountRows, accountRepairRows, accountControlRow, candidate, transition); - requireIssuerObligation(issuerObligationRows, candidate, transition); - requireRegionAcknowledgement(regionRow, candidate, transition); - requirePersistedTag(tagRow); - if (issuerAckRows.size() != 1) { - throw conflict("Exact original NEW issuer acknowledgement is unavailable"); - } - UUID issuerAckOperationId = requiredUuid(issuerAckRows.getFirst(), "operation_id"); - String sourceFingerprint = - fingerprint( - Map.ofEntries( - Map.entry("transition", rowFields("transition", transition)), - Map.entry("candidate", rowFields("candidate", candidateRow)), - Map.entry("reservation", rowFields("reservation", reservationRow)), - Map.entry("account", rowFields("account", accountRows.getFirst())), - Map.entry( - "accountRepair", - rowFields("accountRepair", accountRepairRows.getFirst())), - Map.entry( - "accountControl", rowFields("accountControl", accountControlRow)), - Map.entry( - "issuerObligation", - rowFields("issuerObligation", issuerObligationRows.getFirst())), - Map.entry("region", rowFields("region", regionRow)), - Map.entry("issuerAck", rowFields("issuerAck", issuerAckRows.getFirst())), - Map.entry("tenantTag", rowFields("tenantTag", tagRow)), - Map.entry( - "candidateBytes", Base64.getEncoder().encodeToString(candidateBytes)), - Map.entry("leaseSha256", lease.sha256()))); - wipe(candidateBytes); - return new SourceRows( - candidate, - issuerAckOperationId, - sourceFingerprint, - new FinalReceipt( - requiredText(transition, "original_new_final_session_sha256"), - requiredLong(transition, "original_new_admission_at_ms"), - requiredLong(transition, "original_new_continuity_expires_at_ms"), - requiredLong(transition, "original_new_session_duration_ms"))); - }); + requireAccountAcknowledgement( + accountRows, accountRepairRows, accountControlRow, candidate, transition); + requireIssuerObligation(issuerObligationRows, candidate, transition); + requireRegionAcknowledgement(regionRow, candidate, transition); + requirePersistedTag(tagRow); + if (issuerAckRows.size() != 1) { + throw conflict("Exact original NEW issuer acknowledgement is unavailable"); + } + UUID issuerAckOperationId = requiredUuid(issuerAckRows.getFirst(), "operation_id"); + String sourceFingerprint = + fingerprint( + Map.ofEntries( + Map.entry("transition", rowFields("transition", transition)), + Map.entry("candidate", rowFields("candidate", candidateRow)), + Map.entry("reservation", rowFields("reservation", reservationRow)), + Map.entry("account", rowFields("account", accountRows.getFirst())), + Map.entry( + "accountRepair", + rowFields("accountRepair", accountRepairRows.getFirst())), + Map.entry("accountControl", rowFields("accountControl", accountControlRow)), + Map.entry( + "issuerObligation", + rowFields("issuerObligation", issuerObligationRows.getFirst())), + Map.entry("region", rowFields("region", regionRow)), + Map.entry("issuerAck", rowFields("issuerAck", issuerAckRows.getFirst())), + Map.entry("tenantTag", rowFields("tenantTag", tagRow)), + Map.entry( + "candidateBytes", Base64.getEncoder().encodeToString(candidateBytes)), + Map.entry("leaseSha256", lease.sha256()))); + wipe(candidateBytes); + return new SourceRows( + candidate, + issuerAckOperationId, + sourceFingerprint, + new FinalReceipt( + requiredText(transition, "original_new_final_session_sha256"), + requiredLong(transition, "original_new_admission_at_ms"), + requiredLong(transition, "original_new_continuity_expires_at_ms"), + requiredLong(transition, "original_new_session_duration_ms"))); + }); requireNoAmbientTransaction(); CanonicalGameplayIssuerBindingLocalAcknowledgement issuerAck = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java index f6f8288d66..ea4704a645 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepository.java @@ -74,105 +74,101 @@ TimelinePreparation prepareInitialTimeline( evidence, worldRequest, resolvedRegion, source, incarnation, absenceProof.digest()); try { TimelinePreparation prepared = - dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - lockRegionScope(transaction, inputs.tenantRegionTag()); - Record existingStatus = - transaction.fetchOne( - "SELECT * FROM " - + TABLE - + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?" - + " FOR UPDATE", - source.tenantId(), - source.gameInstanceId(), - source.regionId()); - if (existingStatus != null) throw unavailable(); - Record existingTransition = - transaction.fetchOne( - "SELECT * FROM " - + PREPARATION_TABLE - + " WHERE transition_id = ? FOR UPDATE", - evidence.transition().transitionId()); - if (existingTransition != null) { - TimelinePreparation current = toTimelinePreparation(existingTransition); - if (!matchesPreparation(current, evidence, inputs, source) - || current.phase == TimelinePreparationPhase.INSTALLED) { - throw unavailable(); - } - return current; - } - Record existingScope = - transaction.fetchOne( - "SELECT initialization_operation_id FROM " - + PREPARATION_TABLE - + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?" - + " FOR UPDATE", - source.tenantId(), - source.gameInstanceId(), - source.regionId()); - if (existingScope != null) throw unavailable(); - UUID operationId = UUID.randomUUID(); - transaction.execute( - "INSERT INTO " + dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + lockRegionScope(transaction, inputs.tenantRegionTag()); + Record existingStatus = + transaction.fetchOne( + "SELECT * FROM " + + TABLE + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?" + + " FOR UPDATE", + source.tenantId(), + source.gameInstanceId(), + source.regionId()); + if (existingStatus != null) throw unavailable(); + Record existingTransition = + transaction.fetchOne( + "SELECT * FROM " + PREPARATION_TABLE + " WHERE transition_id = ? FOR UPDATE", + evidence.transition().transitionId()); + if (existingTransition != null) { + TimelinePreparation current = toTimelinePreparation(existingTransition); + if (!matchesPreparation(current, evidence, inputs, source) + || current.phase == TimelinePreparationPhase.INSTALLED) { + throw unavailable(); + } + return current; + } + Record existingScope = + transaction.fetchOne( + "SELECT initialization_operation_id FROM " + PREPARATION_TABLE - + " (initialization_operation_id, transition_id, account_id, tenant_id," - + " playable_state_namespace_id, character_id, playable_state_scope," - + " game_instance_id, runtime_game_instance_id, binding_ref, session_id," - + " binding_generation, canonical_region_id, region_id, tenant_region_tag," - + " lifecycle_epoch, lifecycle_row_version, capture_id," - + " lifecycle_request_bytes, graph_sha256, preparation_input_digest," - + " assignment_uuid, assignment_intent_digest, world_source_digest," - + " preparation_digest, stable_incarnation_scope_bytes," - + " stable_incarnation_source_bytes, stable_incarnation_qualification_bytes," - + " stable_incarnation_digest," - + " timeline_preimage_state, timeline_absence_proof_digest, region_epoch," - + " last_committed_tick_id, phase, created_at, updated_at, entity_created_origin)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'ABSENT', ?, 1, -1, 'PREPARED', ?, ?, CAST(? AS jsonb))", - operationId, - evidence.transition().transitionId(), - evidence.candidate().identity().accountId(), - evidence.candidate().identity().tenantId(), - evidence.candidate().identity().playableStateNamespaceId(), - evidence.candidate().identity().characterId(), - evidence.candidate().identity().playableStateScope(), - evidence.candidate().identity().gameInstanceId(), - evidence.candidate().identity().runtimeGameInstanceId(), - evidence.candidate().bindingRef().bytes(), - evidence.candidate().identity().sessionId(), - new BigDecimal(evidence.candidate().bindingGeneration()), - source.canonicalRegionId(), - source.regionId(), - inputs.tenantRegionTag(), - source.lifecycleEpoch(), - source.lifecycleRowVersion(), - source.captureId(), - source.lifecycleRequest().canonicalBytes(), - source.graphSha256(), - source.preparationInputDigest(), - CanonicalGameplayActorOrigins.assignmentId(inputs.actorOrigin()), - CanonicalGameplayActorOrigins.assignmentDigest(inputs.actorOrigin()), - inputs.worldSourceDigest(), - inputs.preparationDigest(), - inputs.incarnationScopeBytes(), - inputs.incarnationSourceBytes(), - inputs.incarnationQualificationBytes(), - inputs.incarnationDigest(), - inputs.absenceProofDigest(), - java.sql.Timestamp.from(now), - java.sql.Timestamp.from(now), - CanonicalGameplayActorOrigins.creationJson(inputs.actorOrigin())); - Record inserted = - transaction.fetchOne( - "SELECT * FROM " + PREPARATION_TABLE + " WHERE transition_id = ?", - evidence.transition().transitionId()); - TimelinePreparation result = - inserted == null ? null : toTimelinePreparation(inserted); - if (result == null || !matchesPreparation(result, evidence, inputs, source)) { - throw unavailable(); - } - return result; - }); + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?" + + " FOR UPDATE", + source.tenantId(), + source.gameInstanceId(), + source.regionId()); + if (existingScope != null) throw unavailable(); + UUID operationId = UUID.randomUUID(); + transaction.execute( + "INSERT INTO " + + PREPARATION_TABLE + + " (initialization_operation_id, transition_id, account_id, tenant_id," + + " playable_state_namespace_id, character_id, playable_state_scope," + + " game_instance_id, runtime_game_instance_id, binding_ref, session_id," + + " binding_generation, canonical_region_id, region_id, tenant_region_tag," + + " lifecycle_epoch, lifecycle_row_version, capture_id," + + " lifecycle_request_bytes, graph_sha256, preparation_input_digest," + + " assignment_uuid, assignment_intent_digest, world_source_digest," + + " preparation_digest, stable_incarnation_scope_bytes," + + " stable_incarnation_source_bytes, stable_incarnation_qualification_bytes," + + " stable_incarnation_digest," + + " timeline_preimage_state, timeline_absence_proof_digest, region_epoch," + + " last_committed_tick_id, phase, created_at, updated_at, entity_created_origin)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'ABSENT', ?, 1, -1, 'PREPARED', ?, ?, CAST(? AS jsonb))", + operationId, + evidence.transition().transitionId(), + evidence.candidate().identity().accountId(), + evidence.candidate().identity().tenantId(), + evidence.candidate().identity().playableStateNamespaceId(), + evidence.candidate().identity().characterId(), + evidence.candidate().identity().playableStateScope(), + evidence.candidate().identity().gameInstanceId(), + evidence.candidate().identity().runtimeGameInstanceId(), + evidence.candidate().bindingRef().bytes(), + evidence.candidate().identity().sessionId(), + new BigDecimal(evidence.candidate().bindingGeneration()), + source.canonicalRegionId(), + source.regionId(), + inputs.tenantRegionTag(), + source.lifecycleEpoch(), + source.lifecycleRowVersion(), + source.captureId(), + source.lifecycleRequest().canonicalBytes(), + source.graphSha256(), + source.preparationInputDigest(), + CanonicalGameplayActorOrigins.assignmentId(inputs.actorOrigin()), + CanonicalGameplayActorOrigins.assignmentDigest(inputs.actorOrigin()), + inputs.worldSourceDigest(), + inputs.preparationDigest(), + inputs.incarnationScopeBytes(), + inputs.incarnationSourceBytes(), + inputs.incarnationQualificationBytes(), + inputs.incarnationDigest(), + inputs.absenceProofDigest(), + java.sql.Timestamp.from(now), + java.sql.Timestamp.from(now), + CanonicalGameplayActorOrigins.creationJson(inputs.actorOrigin())); + Record inserted = + transaction.fetchOne( + "SELECT * FROM " + PREPARATION_TABLE + " WHERE transition_id = ?", + evidence.transition().transitionId()); + TimelinePreparation result = inserted == null ? null : toTimelinePreparation(inserted); + if (result == null || !matchesPreparation(result, evidence, inputs, source)) { + throw unavailable(); + } + return result; + }); if (find(source).isPresent()) throw unavailable(); return prepared; } catch (RuntimeException failure) { @@ -277,45 +273,44 @@ Optional beginInitialTimeline( requireNoAmbientTransaction(); Objects.requireNonNull(preparation, "preparation"); Objects.requireNonNull(now, "now"); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - lockRegionScope(transaction, preparation.tenantRegionTag); - if (transaction.fetchOne( - "SELECT 1 FROM " - + TABLE - + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ? FOR UPDATE", - preparation.source.tenantId(), - preparation.source.gameInstanceId(), - preparation.source.regionId()) - != null) { - throw unavailable(); - } - Record row = - transaction.fetchOne( - "SELECT * FROM " - + PREPARATION_TABLE - + " WHERE initialization_operation_id = ? FOR UPDATE", - preparation.operationId); - if (row == null) throw unavailable(); - TimelinePreparation current = toTimelinePreparation(row); - if (!samePreparation(preparation, current)) throw unavailable(); - if (current.phase == TimelinePreparationPhase.INSTALLED) { - return Optional.empty(); - } - if (current.phase != TimelinePreparationPhase.PREPARED) return Optional.empty(); - int updated = - transaction.execute( - "UPDATE " - + PREPARATION_TABLE - + " SET phase = 'INITIALIZING', updated_at = ?" - + " WHERE initialization_operation_id = ? AND phase = 'PREPARED'", - java.sql.Timestamp.from(now), - current.operationId); - if (updated != 1) throw unavailable(); - return Optional.of( - new InitialInitializationPermit(current.operationId, current.sourceDigest())); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + lockRegionScope(transaction, preparation.tenantRegionTag); + if (transaction.fetchOne( + "SELECT 1 FROM " + + TABLE + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ? FOR UPDATE", + preparation.source.tenantId(), + preparation.source.gameInstanceId(), + preparation.source.regionId()) + != null) { + throw unavailable(); + } + Record row = + transaction.fetchOne( + "SELECT * FROM " + + PREPARATION_TABLE + + " WHERE initialization_operation_id = ? FOR UPDATE", + preparation.operationId); + if (row == null) throw unavailable(); + TimelinePreparation current = toTimelinePreparation(row); + if (!samePreparation(preparation, current)) throw unavailable(); + if (current.phase == TimelinePreparationPhase.INSTALLED) { + return Optional.empty(); + } + if (current.phase != TimelinePreparationPhase.PREPARED) return Optional.empty(); + int updated = + transaction.execute( + "UPDATE " + + PREPARATION_TABLE + + " SET phase = 'INITIALIZING', updated_at = ?" + + " WHERE initialization_operation_id = ? AND phase = 'PREPARED'", + java.sql.Timestamp.from(now), + current.operationId); + if (updated != 1) throw unavailable(); + return Optional.of( + new InitialInitializationPermit(current.operationId, current.sourceDigest())); + }); } TimelinePreparation markRedisInitialized( @@ -366,81 +361,78 @@ private TimelinePreparation updatePreparationAfterRedis( CanonicalGameplayRegionRuntimeStatus expectedInstalled, Instant now) { try { - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - lockRegionScope(transaction, preparation.tenantRegionTag); - Record currentStatus = - transaction.fetchOne( - "SELECT * FROM " - + TABLE - + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ? FOR UPDATE", - preparation.source.tenantId(), - preparation.source.gameInstanceId(), - preparation.source.regionId()); - Record row = + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + lockRegionScope(transaction, preparation.tenantRegionTag); + Record currentStatus = + transaction.fetchOne( + "SELECT * FROM " + + TABLE + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ? FOR UPDATE", + preparation.source.tenantId(), + preparation.source.gameInstanceId(), + preparation.source.regionId()); + Record row = + transaction.fetchOne( + "SELECT * FROM " + + PREPARATION_TABLE + + " WHERE initialization_operation_id = ? FOR UPDATE", + preparation.operationId); + if (row == null) throw unavailable(); + TimelinePreparation current = toTimelinePreparation(row); + if (!samePreparation(preparation, current)) throw unavailable(); + String expectedMetaDigest = + CanonicalGameplayRegionBindingBridgeProofs.initialMetaDigest( + current.tenantRegionTag, current.operationId, current.sourceDigest()); + if (!expectedMetaDigest.equals(redisMetaDigest) + || current.redisMetaDigest != null + && !current.redisMetaDigest.equals(redisMetaDigest)) { + throw unavailable(); + } + String nextPhase; + if (executorFence == null) { + if (currentStatus != null + || (current.phase != TimelinePreparationPhase.INITIALIZING + && current.phase != TimelinePreparationPhase.REDIS_INITIALIZED)) { + throw unavailable(); + } + nextPhase = "REDIS_INITIALIZED"; + } else { + if (currentStatus == null + || (current.phase != TimelinePreparationPhase.REDIS_INITIALIZED + && current.phase != TimelinePreparationPhase.INSTALLED)) { + throw unavailable(); + } + CanonicalGameplayRegionRuntimeStatus status = toStatus(currentStatus); + if (!status.equals(expectedInstalled) + || !matchesSource(status, preparation.source) + || status.executorFence().longValueExact() != executorFence + || !status.leaseTokenCorrelation().equals(leaseTokenCorrelation)) { + throw unavailable(); + } + nextPhase = "INSTALLED"; + } + int updated = + transaction.execute( + "UPDATE " + + PREPARATION_TABLE + + " SET phase = ?, lease_token_correlation = ?, executor_fence = ?," + + " redis_meta_digest = ?, updated_at = ?" + + " WHERE initialization_operation_id = ?", + nextPhase, + leaseTokenCorrelation, + executorFence, + redisMetaDigest, + java.sql.Timestamp.from(now), + current.operationId); + if (updated != 1) throw unavailable(); + return toTimelinePreparation( + Objects.requireNonNull( transaction.fetchOne( - "SELECT * FROM " - + PREPARATION_TABLE - + " WHERE initialization_operation_id = ? FOR UPDATE", - preparation.operationId); - if (row == null) throw unavailable(); - TimelinePreparation current = toTimelinePreparation(row); - if (!samePreparation(preparation, current)) throw unavailable(); - String expectedMetaDigest = - CanonicalGameplayRegionBindingBridgeProofs.initialMetaDigest( - current.tenantRegionTag, current.operationId, current.sourceDigest()); - if (!expectedMetaDigest.equals(redisMetaDigest) - || current.redisMetaDigest != null - && !current.redisMetaDigest.equals(redisMetaDigest)) { - throw unavailable(); - } - String nextPhase; - if (executorFence == null) { - if (currentStatus != null - || (current.phase != TimelinePreparationPhase.INITIALIZING - && current.phase != TimelinePreparationPhase.REDIS_INITIALIZED)) { - throw unavailable(); - } - nextPhase = "REDIS_INITIALIZED"; - } else { - if (currentStatus == null - || (current.phase != TimelinePreparationPhase.REDIS_INITIALIZED - && current.phase != TimelinePreparationPhase.INSTALLED)) { - throw unavailable(); - } - CanonicalGameplayRegionRuntimeStatus status = toStatus(currentStatus); - if (!status.equals(expectedInstalled) - || !matchesSource(status, preparation.source) - || status.executorFence().longValueExact() != executorFence - || !status.leaseTokenCorrelation().equals(leaseTokenCorrelation)) { - throw unavailable(); - } - nextPhase = "INSTALLED"; - } - int updated = - transaction.execute( - "UPDATE " - + PREPARATION_TABLE - + " SET phase = ?, lease_token_correlation = ?, executor_fence = ?," - + " redis_meta_digest = ?, updated_at = ?" - + " WHERE initialization_operation_id = ?", - nextPhase, - leaseTokenCorrelation, - executorFence, - redisMetaDigest, - java.sql.Timestamp.from(now), - current.operationId); - if (updated != 1) throw unavailable(); - return toTimelinePreparation( - Objects.requireNonNull( - transaction.fetchOne( - "SELECT * FROM " - + PREPARATION_TABLE - + " WHERE initialization_operation_id = ?", - current.operationId), - "region timeline preparation must survive phase readback")); - }); + "SELECT * FROM " + PREPARATION_TABLE + " WHERE initialization_operation_id = ?", + current.operationId), + "region timeline preparation must survive phase readback")); + }); } catch (RuntimeException failure) { throw unavailable(failure); } @@ -696,131 +688,128 @@ CanonicalGameplayRegionRuntimeStatus installOwner( if (prior != null && !expectedTag.equals(prior.tenantRegionTag())) throw unavailable(); try { - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - lockRegionScope(transaction, expectedTag); - Record currentRow = - transaction.fetchOne( - "SELECT * FROM " - + TABLE - + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ? FOR UPDATE", - source.tenantId(), - source.gameInstanceId(), - source.regionId()); - CanonicalGameplayRegionRuntimeStatus current = - currentRow == null ? null : toStatus(currentRow); - if (current != null) { - if (!matchesSource(current, source) - || !expectedTag.equals(current.tenantRegionTag())) { - throw unavailable(); - } - if (current.leaseTokenCorrelation().equals(leaseTokenCorrelation)) { - if (matchesLeaseGeneration( - current, - expectedRegionEpoch, - leaseTokenCorrelation, - ownerService, - ownerInstanceId)) { - return current; - } - throw unavailable(); - } - if (prior == null || !current.equals(prior)) throw unavailable(); - } else if (prior != null || expectedRegionEpoch != 1L) { - throw unavailable(); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + lockRegionScope(transaction, expectedTag); + Record currentRow = + transaction.fetchOne( + "SELECT * FROM " + + TABLE + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ? FOR UPDATE", + source.tenantId(), + source.gameInstanceId(), + source.regionId()); + CanonicalGameplayRegionRuntimeStatus current = + currentRow == null ? null : toStatus(currentRow); + if (current != null) { + if (!matchesSource(current, source) || !expectedTag.equals(current.tenantRegionTag())) { + throw unavailable(); + } + if (current.leaseTokenCorrelation().equals(leaseTokenCorrelation)) { + if (matchesLeaseGeneration( + current, + expectedRegionEpoch, + leaseTokenCorrelation, + ownerService, + ownerInstanceId)) { + return current; } + throw unavailable(); + } + if (prior == null || !current.equals(prior)) throw unavailable(); + } else if (prior != null || expectedRegionEpoch != 1L) { + throw unavailable(); + } - Record fenceRow = - transaction.fetchOne("SELECT nextval('" + FENCE_SEQUENCE + "') AS fence"); - Long fence = fenceRow == null ? null : fenceRow.get("fence", Long.class); - if (fence == null || fence <= 0L) throw unavailable(); - Record installed; - if (current == null) { - if (expectedRegionEpoch != 1L) throw unavailable(); - installed = - transaction.fetchOne( - "INSERT INTO " - + TABLE - + " (tenant_id, game_instance_id, canonical_region_id, region_id," - + " tenant_region_tag, lifecycle_epoch, lifecycle_row_version, capture_id," - + " lifecycle_request_bytes, graph_sha256, preparation_input_digest," - + " region_epoch, executor_fence," - + " lease_token_correlation, owner_service, owner_instance_id, paused," - + " last_committed_tick_id, updated_at)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, false, -1, ?)" - + " ON CONFLICT (tenant_id, game_instance_id, region_id) DO NOTHING" - + " RETURNING *", - source.tenantId(), - source.gameInstanceId(), - source.canonicalRegionId(), - source.regionId(), - expectedTag, - source.lifecycleEpoch(), - source.lifecycleRowVersion(), - source.captureId(), - source.lifecycleRequest().canonicalBytes(), - source.graphSha256(), - source.preparationInputDigest(), - fence, - leaseTokenCorrelation, - ownerService, - ownerInstanceId, - localDateTime(now)); - } else { - installed = - transaction.fetchOne( - "UPDATE " - + TABLE - + " SET executor_fence = ?, lease_token_correlation = ?," - + " owner_service = ?, owner_instance_id = ?, updated_at = ?" - + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?" - + " AND tenant_region_tag = ? AND canonical_region_id = ?" - + " AND lifecycle_epoch = ? AND lifecycle_row_version = ?" - + " AND capture_id = ? AND lifecycle_request_bytes = ?" - + " AND graph_sha256 = ?" - + " AND preparation_input_digest = ? AND region_epoch = ?" - + " AND executor_fence = ? AND lease_token_correlation = ?" - + " AND owner_service = ? AND owner_instance_id = ? AND paused = ?" - + " AND last_committed_tick_id = ?" - + " AND last_committed_tick_batch_id IS NOT DISTINCT FROM ?" - + " RETURNING *", - fence, - leaseTokenCorrelation, - ownerService, - ownerInstanceId, - localDateTime(now), - current.tenantId(), - current.gameInstanceId(), - current.regionId(), - current.tenantRegionTag(), - current.canonicalRegionId(), - current.lifecycleEpoch(), - current.lifecycleRowVersion(), - current.captureId(), - current.lifecycleRequest().canonicalBytes(), - current.graphSha256(), - current.preparationInputDigest(), - current.regionEpoch(), - current.executorFence().longValueExact(), - current.leaseTokenCorrelation(), - current.ownerService(), - current.ownerInstanceId(), - current.paused(), - current.lastCommittedTickId(), - current.lastCommittedTickBatchId()); - } - if (installed == null) throw unavailable(); - CanonicalGameplayRegionRuntimeStatus result = toStatus(installed); - if (!matchesSource(result, source) - || result.regionEpoch() != expectedRegionEpoch - || !result.executorFence().equals(BigInteger.valueOf(fence)) - || !result.leaseTokenCorrelation().equals(leaseTokenCorrelation) - || !result.tenantRegionTag().equals(expectedTag)) { - throw unavailable(); - } - return result; - }); + Record fenceRow = transaction.fetchOne("SELECT nextval('" + FENCE_SEQUENCE + "') AS fence"); + Long fence = fenceRow == null ? null : fenceRow.get("fence", Long.class); + if (fence == null || fence <= 0L) throw unavailable(); + Record installed; + if (current == null) { + if (expectedRegionEpoch != 1L) throw unavailable(); + installed = + transaction.fetchOne( + "INSERT INTO " + + TABLE + + " (tenant_id, game_instance_id, canonical_region_id, region_id," + + " tenant_region_tag, lifecycle_epoch, lifecycle_row_version, capture_id," + + " lifecycle_request_bytes, graph_sha256, preparation_input_digest," + + " region_epoch, executor_fence," + + " lease_token_correlation, owner_service, owner_instance_id, paused," + + " last_committed_tick_id, updated_at)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, false, -1, ?)" + + " ON CONFLICT (tenant_id, game_instance_id, region_id) DO NOTHING" + + " RETURNING *", + source.tenantId(), + source.gameInstanceId(), + source.canonicalRegionId(), + source.regionId(), + expectedTag, + source.lifecycleEpoch(), + source.lifecycleRowVersion(), + source.captureId(), + source.lifecycleRequest().canonicalBytes(), + source.graphSha256(), + source.preparationInputDigest(), + fence, + leaseTokenCorrelation, + ownerService, + ownerInstanceId, + localDateTime(now)); + } else { + installed = + transaction.fetchOne( + "UPDATE " + + TABLE + + " SET executor_fence = ?, lease_token_correlation = ?," + + " owner_service = ?, owner_instance_id = ?, updated_at = ?" + + " WHERE tenant_id = ? AND game_instance_id = ? AND region_id = ?" + + " AND tenant_region_tag = ? AND canonical_region_id = ?" + + " AND lifecycle_epoch = ? AND lifecycle_row_version = ?" + + " AND capture_id = ? AND lifecycle_request_bytes = ?" + + " AND graph_sha256 = ?" + + " AND preparation_input_digest = ? AND region_epoch = ?" + + " AND executor_fence = ? AND lease_token_correlation = ?" + + " AND owner_service = ? AND owner_instance_id = ? AND paused = ?" + + " AND last_committed_tick_id = ?" + + " AND last_committed_tick_batch_id IS NOT DISTINCT FROM ?" + + " RETURNING *", + fence, + leaseTokenCorrelation, + ownerService, + ownerInstanceId, + localDateTime(now), + current.tenantId(), + current.gameInstanceId(), + current.regionId(), + current.tenantRegionTag(), + current.canonicalRegionId(), + current.lifecycleEpoch(), + current.lifecycleRowVersion(), + current.captureId(), + current.lifecycleRequest().canonicalBytes(), + current.graphSha256(), + current.preparationInputDigest(), + current.regionEpoch(), + current.executorFence().longValueExact(), + current.leaseTokenCorrelation(), + current.ownerService(), + current.ownerInstanceId(), + current.paused(), + current.lastCommittedTickId(), + current.lastCommittedTickBatchId()); + } + if (installed == null) throw unavailable(); + CanonicalGameplayRegionRuntimeStatus result = toStatus(installed); + if (!matchesSource(result, source) + || result.regionEpoch() != expectedRegionEpoch + || !result.executorFence().equals(BigInteger.valueOf(fence)) + || !result.leaseTokenCorrelation().equals(leaseTokenCorrelation) + || !result.tenantRegionTag().equals(expectedTag)) { + throw unavailable(); + } + return result; + }); } catch (RuntimeException failure) { throw unavailable(failure); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java index cea66414b9..80805e417a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferenceRepository.java @@ -560,55 +560,54 @@ public static boolean isSupersedingTarget( digest(targetBinding(request)), policy.batchSize()); return candidates.stream() - .map( - row -> { - java.util.UUID operation = - Objects.requireNonNull(row.get("operation_uuid", java.util.UUID.class)); - java.util.UUID fenceUuid = - Objects.requireNonNull(row.get("target_fence_uuid", java.util.UUID.class)); - java.util.UUID recovery = row.get("recovery_uuid", java.util.UUID.class); - if (recovery == null) { - recovery = java.util.UUID.randomUUID(); - dsl.execute( - "UPDATE game_session_canonical_roster_selection SET recovery_uuid = ?, recovery_started_at = clock_timestamp(), recovery_last_attempt_at = clock_timestamp() " - + "WHERE operation_uuid = ? AND recovery_uuid IS NULL AND terminal_outcome IS NULL", - recovery, - operation); - } else { - dsl.execute( - "UPDATE game_session_canonical_roster_selection SET recovery_last_attempt_at = GREATEST(recovery_last_attempt_at + interval '1 microsecond', clock_timestamp()) " - + "WHERE operation_uuid = ? AND recovery_uuid = ? AND terminal_outcome IS NULL", + .map(row -> { + java.util.UUID operation = + Objects.requireNonNull(row.get("operation_uuid", java.util.UUID.class)); + java.util.UUID fenceUuid = + Objects.requireNonNull(row.get("target_fence_uuid", java.util.UUID.class)); + java.util.UUID recovery = row.get("recovery_uuid", java.util.UUID.class); + if (recovery == null) { + recovery = java.util.UUID.randomUUID(); + dsl.execute( + "UPDATE game_session_canonical_roster_selection SET recovery_uuid = ?, recovery_started_at = clock_timestamp(), recovery_last_attempt_at = clock_timestamp() " + + "WHERE operation_uuid = ? AND recovery_uuid IS NULL AND terminal_outcome IS NULL", + recovery, + operation); + } else { + dsl.execute( + "UPDATE game_session_canonical_roster_selection SET recovery_last_attempt_at = GREATEST(recovery_last_attempt_at + interval '1 microsecond', clock_timestamp()) " + + "WHERE operation_uuid = ? AND recovery_uuid = ? AND terminal_outcome IS NULL", + operation, + recovery); + } + try { + byte[] originalBytes = + Objects.requireNonNull(row.get("original_request", byte[].class)); + var original = + decodeRetainedOriginal( + originalBytes, operation, - recovery); - } - try { - byte[] originalBytes = - Objects.requireNonNull(row.get("original_request", byte[].class)); - var original = - decodeRetainedOriginal( - originalBytes, - operation, - fenceUuid, - row.get("fence_target_fence_uuid", java.util.UUID.class), - row.get("owner_fence", Long.class), - row.get("fence_owner_fence", Long.class), - row.get("fence_target_binding", byte[].class), - row.get("fence_target_binding_digest", String.class)); - return net.firedevops.firemud.common.world.CanonicalGameplayRosterRecoveryEvidence - .requireRequest( - net.firedevops.firemud.entitymanagement.v1 - .CanonicalGameplayRosterRecoveryRequest.newBuilder() - .setSchemaVersion(1) - .setOriginalSelection(original) - .setRecoveryUuid(recovery.toString()) - .build()); - } catch (com.google.protobuf.InvalidProtocolBufferException - | IllegalArgumentException invalid) { - // The durable marker and attempt timestamp are scheduling state only. A malformed - // retained request remains protected and is never sent to the owner RPC. - return null; - } - }) + fenceUuid, + row.get("fence_target_fence_uuid", java.util.UUID.class), + row.get("owner_fence", Long.class), + row.get("fence_owner_fence", Long.class), + row.get("fence_target_binding", byte[].class), + row.get("fence_target_binding_digest", String.class)); + return net.firedevops.firemud.common.world.CanonicalGameplayRosterRecoveryEvidence + .requireRequest( + net.firedevops.firemud.entitymanagement.v1 + .CanonicalGameplayRosterRecoveryRequest.newBuilder() + .setSchemaVersion(1) + .setOriginalSelection(original) + .setRecoveryUuid(recovery.toString()) + .build()); + } catch (com.google.protobuf.InvalidProtocolBufferException + | IllegalArgumentException invalid) { + // The durable marker and attempt timestamp are scheduling state only. A malformed + // retained request remains protected and is never sent to the owner RPC. + return null; + } + }) .filter(Objects::nonNull) .toList(); } @@ -725,32 +724,31 @@ public java.util.List targetCandidates( afterOperation, afterOperation, limit) - .map( - row -> { - java.util.UUID operationUuid = - Objects.requireNonNull(row.get("operation_uuid", java.util.UUID.class)); - java.util.UUID fenceUuid = - Objects.requireNonNull(row.get("target_fence_uuid", java.util.UUID.class)); - String state = Objects.requireNonNull(row.get("fence_state", String.class)); - try { - return new TargetCandidate( - operationUuid, + .map(row -> { + java.util.UUID operationUuid = + Objects.requireNonNull(row.get("operation_uuid", java.util.UUID.class)); + java.util.UUID fenceUuid = + Objects.requireNonNull(row.get("target_fence_uuid", java.util.UUID.class)); + String state = Objects.requireNonNull(row.get("fence_state", String.class)); + try { + return new TargetCandidate( + operationUuid, + fenceUuid, + decodeRetainedOriginal( + Objects.requireNonNull(row.get("original_request", byte[].class)), + Objects.requireNonNull(row.get("operation_uuid", java.util.UUID.class)), + row.get("selection_target_fence_uuid", java.util.UUID.class), fenceUuid, - decodeRetainedOriginal( - Objects.requireNonNull(row.get("original_request", byte[].class)), - Objects.requireNonNull(row.get("operation_uuid", java.util.UUID.class)), - row.get("selection_target_fence_uuid", java.util.UUID.class), - fenceUuid, - row.get("selection_owner_fence", Long.class), - row.get("fence_owner_fence", Long.class), - row.get("target_binding", byte[].class), - row.get("target_binding_digest", String.class)), - state); - } catch (com.google.protobuf.InvalidProtocolBufferException - | IllegalArgumentException invalid) { - return TargetCandidate.invalid(operationUuid, fenceUuid, state); - } - }); + row.get("selection_owner_fence", Long.class), + row.get("fence_owner_fence", Long.class), + row.get("target_binding", byte[].class), + row.get("target_binding_digest", String.class)), + state); + } catch (com.google.protobuf.InvalidProtocolBufferException + | IllegalArgumentException invalid) { + return TargetCandidate.invalid(operationUuid, fenceUuid, state); + } + }); } /** diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java index a2f8a8312a..dd524a3bbd 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java @@ -45,32 +45,30 @@ public CanonicalGameplayTenantGameplayTagRepository( /** Loads or allocates a mapping only for the persisted candidate of this exact transition. */ public Assignment assignmentForTransition(UUID transitionId) { requireNonNil(transitionId, "transitionId"); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - // Issuer barrier claims take this clock before locking the mapping and source rows. - // Keep the same order so a retained claim cannot deadlock with tag resolution. - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - BindingTarget source = loadBindingTarget(transaction, transitionId); - requireTenantClaim(transaction, source.tenantId()); - return resolveMapping( - transaction, source, allocationVersion, tagFor(source.tenantId(), allocationVersion)); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + // Issuer barrier claims take this clock before locking the mapping and source rows. + // Keep the same order so a retained claim cannot deadlock with tag resolution. + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + BindingTarget source = loadBindingTarget(transaction, transitionId); + requireTenantClaim(transaction, source.tenantId()); + return resolveMapping( + transaction, source, allocationVersion, tagFor(source.tenantId(), allocationVersion)); + }); } /** Topology-only retained lookup for one irreversibly selected original negative continuation. */ Assignment assignmentForOriginalNewAbandonment(UUID transitionId, UUID abandonmentId) { requireNonNil(transitionId, "transitionId"); requireNonNil(abandonmentId, "abandonmentId"); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - BindingTarget source = loadBindingTarget(transaction, transitionId, abandonmentId); - requireTenantClaim(transaction, source.tenantId()); - return resolveMapping( - transaction, source, allocationVersion, tagFor(source.tenantId(), allocationVersion)); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + BindingTarget source = loadBindingTarget(transaction, transitionId, abandonmentId); + requireTenantClaim(transaction, source.tenantId()); + return resolveMapping( + transaction, source, allocationVersion, tagFor(source.tenantId(), allocationVersion)); + }); } /** @@ -82,154 +80,149 @@ public Assignment assignmentForBarrierTarget(UUID operationId, long targetOrdina if (targetOrdinal < 0) { throw new IllegalArgumentException("targetOrdinal must not be negative"); } - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - Record lockedControl = - transaction.fetchOne( - "SELECT control.account_id" - + " FROM game_session_canonical_account_admission_fence_intent intent" - + " JOIN game_session_canonical_account_coverage_control control" - + " ON control.account_id = intent.account_id" - + " WHERE intent.operation_id = ?" - + " AND intent.intent_state = 'ACQUISITION_INTENT'" - + " AND control.state = 'ACQUISITION_INTENT'" - + " AND control.current_operation_id IS NULL" - + " AND control.current_fence_intent_id = intent.operation_id" - + " AND control.current_operation_fence = intent.operation_fence" - + " AND control.last_operation_fence = intent.operation_fence" - + " AND control.account_admission_fence = intent.planned_account_admission_fence" - + " AND control.inventory_snapshot_revision = intent.inventory_snapshot_revision" - + " AND control.coverage_fence IS NULL AND control.coverage_generation IS NULL" - + " FOR UPDATE OF control", - operationId); - if (lockedControl == null) { - throw conflict("The exact current acquisition-intent barrier target is unavailable"); - } - Record row = - transaction.fetchOne( - "SELECT target.operation_id, target.target_ordinal, target.account_id," - + " target.tenant_id, target.playable_state_namespace_id" - + " FROM game_session_canonical_account_admission_fence_intent_barrier_target target" - + " JOIN game_session_canonical_account_admission_fence_intent intent" - + " ON intent.operation_id = target.operation_id" - + " AND intent.account_id = target.account_id" - + " JOIN game_session_canonical_account_coverage_control control" - + " ON control.account_id = intent.account_id" - + " WHERE target.operation_id = ? AND target.target_ordinal = ?" - + " AND target.target_state = 'REQUIRED'" - + " AND intent.intent_state = 'ACQUISITION_INTENT'" - + " AND control.state = 'ACQUISITION_INTENT'" - + " AND control.current_operation_id IS NULL" - + " AND control.current_fence_intent_id = intent.operation_id" - + " AND control.current_operation_fence = intent.operation_fence" - + " AND control.last_operation_fence = intent.operation_fence" - + " AND control.account_admission_fence = intent.planned_account_admission_fence" - + " AND control.inventory_snapshot_revision = intent.inventory_snapshot_revision" - + " AND control.coverage_fence IS NULL AND control.coverage_generation IS NULL" - + " FOR SHARE OF target, intent", - operationId, - targetOrdinal); - if (row == null) { - throw conflict("The exact current acquisition-intent barrier target is unavailable"); - } - BarrierTarget source = - new BarrierTarget( - requiredUuid(row, "operation_id"), - requiredLong(row, "target_ordinal"), - requiredUuid(row, "account_id"), - requiredUuid(row, "tenant_id"), - requiredUuid(row, "playable_state_namespace_id")); - requireTenantClaim(transaction, source.tenantId()); - return resolveMapping( - transaction, source, allocationVersion, tagFor(source.tenantId(), allocationVersion)); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + Record lockedControl = + transaction.fetchOne( + "SELECT control.account_id" + + " FROM game_session_canonical_account_admission_fence_intent intent" + + " JOIN game_session_canonical_account_coverage_control control" + + " ON control.account_id = intent.account_id" + + " WHERE intent.operation_id = ?" + + " AND intent.intent_state = 'ACQUISITION_INTENT'" + + " AND control.state = 'ACQUISITION_INTENT'" + + " AND control.current_operation_id IS NULL" + + " AND control.current_fence_intent_id = intent.operation_id" + + " AND control.current_operation_fence = intent.operation_fence" + + " AND control.last_operation_fence = intent.operation_fence" + + " AND control.account_admission_fence = intent.planned_account_admission_fence" + + " AND control.inventory_snapshot_revision = intent.inventory_snapshot_revision" + + " AND control.coverage_fence IS NULL AND control.coverage_generation IS NULL" + + " FOR UPDATE OF control", + operationId); + if (lockedControl == null) { + throw conflict("The exact current acquisition-intent barrier target is unavailable"); + } + Record row = + transaction.fetchOne( + "SELECT target.operation_id, target.target_ordinal, target.account_id," + + " target.tenant_id, target.playable_state_namespace_id" + + " FROM game_session_canonical_account_admission_fence_intent_barrier_target target" + + " JOIN game_session_canonical_account_admission_fence_intent intent" + + " ON intent.operation_id = target.operation_id" + + " AND intent.account_id = target.account_id" + + " JOIN game_session_canonical_account_coverage_control control" + + " ON control.account_id = intent.account_id" + + " WHERE target.operation_id = ? AND target.target_ordinal = ?" + + " AND target.target_state = 'REQUIRED'" + + " AND intent.intent_state = 'ACQUISITION_INTENT'" + + " AND control.state = 'ACQUISITION_INTENT'" + + " AND control.current_operation_id IS NULL" + + " AND control.current_fence_intent_id = intent.operation_id" + + " AND control.current_operation_fence = intent.operation_fence" + + " AND control.last_operation_fence = intent.operation_fence" + + " AND control.account_admission_fence = intent.planned_account_admission_fence" + + " AND control.inventory_snapshot_revision = intent.inventory_snapshot_revision" + + " AND control.coverage_fence IS NULL AND control.coverage_generation IS NULL" + + " FOR SHARE OF target, intent", + operationId, + targetOrdinal); + if (row == null) { + throw conflict("The exact current acquisition-intent barrier target is unavailable"); + } + BarrierTarget source = + new BarrierTarget( + requiredUuid(row, "operation_id"), + requiredLong(row, "target_ordinal"), + requiredUuid(row, "account_id"), + requiredUuid(row, "tenant_id"), + requiredUuid(row, "playable_state_namespace_id")); + requireTenantClaim(transaction, source.tenantId()); + return resolveMapping( + transaction, source, allocationVersion, tagFor(source.tenantId(), allocationVersion)); + }); } /** Resolves topology only for the persisted exact original-attempt INITIAL target. */ Assignment assignmentForInitialBarrierTarget(UUID originalRequestId) { requireNonNil(originalRequestId, "originalRequestId"); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - // Match the initializer owner: inventory clock, account control, initializer/target. - Record inventoryClock = - transaction.fetchOne( - "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock" - + " WHERE singleton_id = 1 FOR UPDATE"); - if (inventoryClock == null) - throw conflict("Canonical binding inventory clock is missing"); - Record locator = - transaction.fetchOne( - "SELECT account_id FROM game_session_canonical_initial_account_barrier_initializer" - + " WHERE original_request_id = ?", - originalRequestId); - if (locator == null) throw conflict("Exact original INITIAL account target is missing"); - UUID locatedAccountId = requiredUuid(locator, "account_id"); - Record control = - transaction.fetchOne( - "SELECT account_id FROM game_session_canonical_account_coverage_control" - + " WHERE account_id = ? FOR UPDATE", - locatedAccountId); - if (control == null) throw conflict("Account coverage control row is missing"); - Record row = - transaction.fetchOne( - "SELECT i.initializer_id, i.account_id, i.source_control_epoch," - + " t.target_ordinal, t.tenant_id," - + " t.playable_state_namespace_id, t.target_state, control.state AS control_state," - + " control.last_operation_fence, control.current_operation_id," - + " control.current_fence_intent_id, control.current_operation_fence," - + " control.account_admission_fence, control.historical_account_admission_fence," - + " control.coverage_fence, control.inventory_snapshot_revision," - + " control.coverage_generation" - + " FROM game_session_canonical_initial_account_barrier_initializer i" - + " JOIN game_session_canonical_initial_account_barrier_target t" - + " ON t.initializer_id = i.initializer_id" - + " AND t.original_request_id = i.original_request_id" - + " JOIN game_session_canonical_account_coverage_control control" - + " ON control.account_id = i.account_id" - + " WHERE i.original_request_id = ? AND t.target_ordinal = 0" - + " FOR UPDATE OF i, t, control", - originalRequestId); - if (row == null - || !"NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(row.get("control_state", String.class)) - || row.get("last_operation_fence", java.math.BigDecimal.class) == null - || row.get("last_operation_fence", java.math.BigDecimal.class) - .toBigIntegerExact() - .signum() - < 0 - || row.get("source_control_epoch", java.math.BigDecimal.class) == null - || !row.get("source_control_epoch", java.math.BigDecimal.class) + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + // Match the initializer owner: inventory clock, account control, initializer/target. + Record inventoryClock = + transaction.fetchOne( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id = 1 FOR UPDATE"); + if (inventoryClock == null) throw conflict("Canonical binding inventory clock is missing"); + Record locator = + transaction.fetchOne( + "SELECT account_id FROM game_session_canonical_initial_account_barrier_initializer" + + " WHERE original_request_id = ?", + originalRequestId); + if (locator == null) throw conflict("Exact original INITIAL account target is missing"); + UUID locatedAccountId = requiredUuid(locator, "account_id"); + Record control = + transaction.fetchOne( + "SELECT account_id FROM game_session_canonical_account_coverage_control" + + " WHERE account_id = ? FOR UPDATE", + locatedAccountId); + if (control == null) throw conflict("Account coverage control row is missing"); + Record row = + transaction.fetchOne( + "SELECT i.initializer_id, i.account_id, i.source_control_epoch," + + " t.target_ordinal, t.tenant_id," + + " t.playable_state_namespace_id, t.target_state, control.state AS control_state," + + " control.last_operation_fence, control.current_operation_id," + + " control.current_fence_intent_id, control.current_operation_fence," + + " control.account_admission_fence, control.historical_account_admission_fence," + + " control.coverage_fence, control.inventory_snapshot_revision," + + " control.coverage_generation" + + " FROM game_session_canonical_initial_account_barrier_initializer i" + + " JOIN game_session_canonical_initial_account_barrier_target t" + + " ON t.initializer_id = i.initializer_id" + + " AND t.original_request_id = i.original_request_id" + + " JOIN game_session_canonical_account_coverage_control control" + + " ON control.account_id = i.account_id" + + " WHERE i.original_request_id = ? AND t.target_ordinal = 0" + + " FOR UPDATE OF i, t, control", + originalRequestId); + if (row == null + || !"NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(row.get("control_state", String.class)) + || row.get("last_operation_fence", java.math.BigDecimal.class) == null + || row.get("last_operation_fence", java.math.BigDecimal.class) .toBigIntegerExact() - .equals( - row.get("last_operation_fence", java.math.BigDecimal.class) - .toBigIntegerExact()) - || row.get("current_operation_id", UUID.class) != null - || row.get("current_fence_intent_id", UUID.class) != null - || row.get("current_operation_fence") != null - || row.get("account_admission_fence", UUID.class) != null - || row.get("historical_account_admission_fence", UUID.class) != null - || row.get("coverage_fence", UUID.class) != null - || row.get("inventory_snapshot_revision") != null - || row.get("coverage_generation") != null) { - throw conflict( - "The exact INITIAL target or its positive NO_ACTIVE control is unavailable"); - } - UUID initializerId = requiredUuid(row, "initializer_id"); - UUID accountId = requiredUuid(row, "account_id"); - UUID tenantId = requiredUuid(row, "tenant_id"); - UUID namespaceId = requiredUuid(row, "playable_state_namespace_id"); - if (requiredLong(row, "target_ordinal") != 0L - || !Set.of("NEVER_DISPATCHED", "DISPATCH_POSSIBLE", "OPEN_INSTALLED") - .contains(requiredString(row, "target_state"))) { - throw conflict("The INITIAL target state is not a retained original-attempt state"); - } - requireTenantClaim(transaction, tenantId); - InitialTarget source = - new InitialTarget(initializerId, originalRequestId, accountId, tenantId, namespaceId); - return resolveMapping( - transaction, source, allocationVersion, tagFor(tenantId, allocationVersion)); - }); + .signum() + < 0 + || row.get("source_control_epoch", java.math.BigDecimal.class) == null + || !row.get("source_control_epoch", java.math.BigDecimal.class) + .toBigIntegerExact() + .equals( + row.get("last_operation_fence", java.math.BigDecimal.class).toBigIntegerExact()) + || row.get("current_operation_id", UUID.class) != null + || row.get("current_fence_intent_id", UUID.class) != null + || row.get("current_operation_fence") != null + || row.get("account_admission_fence", UUID.class) != null + || row.get("historical_account_admission_fence", UUID.class) != null + || row.get("coverage_fence", UUID.class) != null + || row.get("inventory_snapshot_revision") != null + || row.get("coverage_generation") != null) { + throw conflict("The exact INITIAL target or its positive NO_ACTIVE control is unavailable"); + } + UUID initializerId = requiredUuid(row, "initializer_id"); + UUID accountId = requiredUuid(row, "account_id"); + UUID tenantId = requiredUuid(row, "tenant_id"); + UUID namespaceId = requiredUuid(row, "playable_state_namespace_id"); + if (requiredLong(row, "target_ordinal") != 0L + || !Set.of("NEVER_DISPATCHED", "DISPATCH_POSSIBLE", "OPEN_INSTALLED") + .contains(requiredString(row, "target_state"))) { + throw conflict("The INITIAL target state is not a retained original-attempt state"); + } + requireTenantClaim(transaction, tenantId); + InitialTarget source = + new InitialTarget(initializerId, originalRequestId, accountId, tenantId, namespaceId); + return resolveMapping( + transaction, source, allocationVersion, tagFor(tenantId, allocationVersion)); + }); } /** @@ -242,14 +235,13 @@ Assignment assignmentForTransitionWithCandidate( requireNonNil(transitionId, "transitionId"); requirePositive(candidateVersion, "candidateVersion"); requireCanonicalTag(candidateTag); - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - BindingTarget source = loadBindingTarget(transaction, transitionId); - requireTenantClaim(transaction, source.tenantId()); - return resolveMapping(transaction, source, candidateVersion, candidateTag); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + BindingTarget source = loadBindingTarget(transaction, transitionId); + requireTenantClaim(transaction, source.tenantId()); + return resolveMapping(transaction, source, candidateVersion, candidateTag); + }); } private BindingTarget loadBindingTarget(DSLContext transaction, UUID transitionId) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalHumanRuntimeCompletionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalHumanRuntimeCompletionRepository.java index dc71afde6c..c7f1522e5b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalHumanRuntimeCompletionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalHumanRuntimeCompletionRepository.java @@ -253,18 +253,15 @@ private void lockTarget(CanonicalInitialAdmissionRequest request) { private void requireWritableReadCommittedTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isCurrentTransactionReadOnly() - || dsl.connectionResult( - connection -> { - try { - return connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() - != Connection.TRANSACTION_READ_COMMITTED; - } catch (java.sql.SQLException exception) { - throw new IllegalStateException( - "Unable to inspect completion transaction", exception); - } - })) { + || dsl.connectionResult(connection -> { + try { + return connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED; + } catch (java.sql.SQLException exception) { + throw new IllegalStateException("Unable to inspect completion transaction", exception); + } + })) { throw new IllegalStateException( "Human runtime completion requires a writable READ COMMITTED transaction"); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java index cf9894c9fb..9acc20f3b8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java @@ -513,18 +513,17 @@ private void requireWritableReadCommittedOwnerTransaction() { throw new IllegalStateException( "Canonical initial-admission intent mutation requires a writable owner transaction"); } - dsl.connectionResult( - connection -> { - if (connection.getAutoCommit()) { - throw new IllegalStateException( - "Canonical initial-admission intent DSL connection must join the owner transaction"); - } - if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new IllegalStateException( - "Canonical initial-admission intent mutation requires READ COMMITTED isolation"); - } - return null; - }); + dsl.connectionResult(connection -> { + if (connection.getAutoCommit()) { + throw new IllegalStateException( + "Canonical initial-admission intent DSL connection must join the owner transaction"); + } + if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Canonical initial-admission intent mutation requires READ COMMITTED isolation"); + } + return null; + }); Record readOnly = dsl.fetchOne("SHOW transaction_read_only"); if (readOnly == null || !"off".equalsIgnoreCase(readOnly.get(0, String.class).trim())) { throw new IllegalStateException( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java index c3d77d9443..82b8b8648d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java @@ -452,10 +452,9 @@ public CurrentOpenSnapshot readCurrentOpenSnapshotForRealm( CanonicalInitialAdmissionOwnerProof proof = read(targetNamespace, requestId) - .orElseThrow( - () -> - new CanonicalInitialAdmissionReconciliationRequiredException( - "Current canonical OPEN pointer has no durable owner attempt")); + .orElseThrow(() -> + new CanonicalInitialAdmissionReconciliationRequiredException( + "Current canonical OPEN pointer has no durable owner attempt")); if (!proof.provesCommit() || !before.matches(proof)) { throw new CanonicalInitialAdmissionReconciliationRequiredException( "Current canonical OPEN pointer does not match its exact committed owner proof"); @@ -533,18 +532,17 @@ public CurrentOpenSnapshot lockExactCurrentOpenSnapshot(CurrentOpenSnapshot qual throw new IllegalStateException( "Exact current OPEN lock requires a joined writable READ COMMITTED owner transaction"); } - dsl.connectionResult( - connection -> { - if (connection.getAutoCommit()) { - throw new IllegalStateException( - "Exact current OPEN lock requires the DSL connection to join the owner transaction"); - } - if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new IllegalStateException( - "Exact current OPEN lock requires READ COMMITTED isolation"); - } - return null; - }); + dsl.connectionResult(connection -> { + if (connection.getAutoCommit()) { + throw new IllegalStateException( + "Exact current OPEN lock requires the DSL connection to join the owner transaction"); + } + if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Exact current OPEN lock requires READ COMMITTED isolation"); + } + return null; + }); if (!"off" .equalsIgnoreCase( dsl.fetchSingle("SHOW transaction_read_only").get(0, String.class).trim())) { @@ -817,10 +815,9 @@ private void requireTerminalProtectionReplay( AccountInitialAdmissionProtectionBindingRepository.RetainedProtection retained = protectionRepository() .read(attempt.targetNamespace(), attempt.initialAdmissionRequestId()) - .orElseThrow( - () -> - new CanonicalInitialAdmissionConflictException( - "Terminal admission has no complete protected association")); + .orElseThrow(() -> + new CanonicalInitialAdmissionConflictException( + "Terminal admission has no complete protected association")); if (!java.util.Arrays.equals( retained.protection().canonicalBytes(), protection.canonicalBytes())) { throw new CanonicalInitialAdmissionConflictException( @@ -1040,15 +1037,14 @@ private void requireWritableReadCommittedOwnerTransaction() { throw new IllegalStateException( "Canonical initial-admission owner mutation requires a writable transaction"); } - dsl.connectionResult( - connection -> { - if (connection.getAutoCommit() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new IllegalStateException( - "Canonical initial-admission owner mutation requires READ COMMITTED isolation"); - } - return null; - }); + dsl.connectionResult(connection -> { + if (connection.getAutoCommit() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Canonical initial-admission owner mutation requires READ COMMITTED isolation"); + } + return null; + }); Record isolation = dsl.fetchOne( "SELECT current_setting('transaction_isolation') AS isolation, " @@ -1243,16 +1239,15 @@ private void verifyCommittedReadback( } String expectedProof = protectedTerminalProofDigest(attempt) - .orElseGet( - () -> - commitProofDigest( - attempt, - attempt.pointerVersion(), - attempt.auditEventId(), - attempt.terminalAt(), - attempt.priorPointerRequestId(), - attempt.priorPointerRequestDigest(), - attempt.priorPointerAuditEventId())); + .orElseGet(() -> + commitProofDigest( + attempt, + attempt.pointerVersion(), + attempt.auditEventId(), + attempt.terminalAt(), + attempt.priorPointerRequestId(), + attempt.priorPointerRequestDigest(), + attempt.priorPointerAuditEventId())); if (!expectedProof.equals(attempt.commitProofDigest())) { throw new CanonicalInitialAdmissionReconciliationRequiredException( "Committed initial-admission proof digest does not match the durable result"); @@ -1281,15 +1276,14 @@ private void verifyAbortReadback(Attempt attempt) { } String expectedProof = protectedTerminalProofDigest(attempt) - .orElseGet( - () -> - abortProofDigest( - attempt, - attempt.abortReason(), - attempt.terminalAt(), - attempt.priorPointerRequestId(), - attempt.priorPointerRequestDigest(), - attempt.priorPointerAuditEventId())); + .orElseGet(() -> + abortProofDigest( + attempt, + attempt.abortReason(), + attempt.terminalAt(), + attempt.priorPointerRequestId(), + attempt.priorPointerRequestDigest(), + attempt.priorPointerAuditEventId())); if (!expectedProof.equals(attempt.abortProofDigest())) { throw new CanonicalInitialAdmissionReconciliationRequiredException( "Durable ABORTED proof digest does not match the fenced result"); @@ -1328,10 +1322,9 @@ private void verifyOriginalClosedOrigin(Attempt attempt, boolean ownerLocked) { attempt.targetNamespace(), attempt.priorPointerRequestId()) : pointerRepository.readOriginalClosedOrigin( attempt.targetNamespace(), attempt.priorPointerRequestId())) - .orElseThrow( - () -> - new CanonicalInitialAdmissionReconciliationRequiredException( - "Immutable original CLOSED request/event evidence is unavailable")); + .orElseThrow(() -> + new CanonicalInitialAdmissionReconciliationRequiredException( + "Immutable original CLOSED request/event evidence is unavailable")); if (!origin.canonicalTenantId().equals(attempt.canonicalTenantId()) || !origin.realmId().equals(attempt.realmId()) || !origin.requestDigest().equals(attempt.priorPointerRequestDigest()) @@ -1367,10 +1360,9 @@ private CanonicalRealmCatalogSnapshot readExactCatalog(CanonicalInitialAdmission CanonicalRealmCatalogSnapshot catalog = catalogRepository .readByRealm(request.targetNamespace(), request.canonicalTenantId(), request.realmId()) - .orElseThrow( - () -> - new CanonicalInitialAdmissionReconciliationRequiredException( - "Exact canonical realm catalog is unavailable for owner readback")); + .orElseThrow(() -> + new CanonicalInitialAdmissionReconciliationRequiredException( + "Exact canonical realm catalog is unavailable for owner readback")); requireRequestMatchesCatalog(request, catalog); return catalog; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java index ce8ff2ccc6..babff433dc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/DirectTextAuthenticatedLobbyRepository.java @@ -191,31 +191,28 @@ public void recordPositiveReply( public DirectTextAuthenticatedLobbyScope readCommittedScope( DirectTextAuthenticatedLobbyScope expected) { requireNoTransaction(); - return dsl.connectionResult( - connection -> { - requireConnection(connection, false); - var result = - requiredScope(DSL.using(connection, SQLDialect.POSTGRES), expected.recordId()); - requireExact(expected, result); - return result; - }); + return dsl.connectionResult(connection -> { + requireConnection(connection, false); + var result = requiredScope(DSL.using(connection, SQLDialect.POSTGRES), expected.recordId()); + requireExact(expected, result); + return result; + }); } public DirectTextAuthenticatedLobbyJoin readCommittedJoin( DirectTextAuthenticatedLobbyJoin expected) { requireNoTransaction(); - return dsl.connectionResult( - connection -> { - requireConnection(connection, false); - var reader = DSL.using(connection, SQLDialect.POSTGRES); - var scope = requiredScope(reader, expected.scope().recordId()); - requireExact(expected.scope(), scope); - Record row = joinRow(reader, scope.recordId()); - if (row == null) throw unavailable(); - var result = decodeJoin(scope, row); - requireSameRequest(expected, result); - return result; - }); + return dsl.connectionResult(connection -> { + requireConnection(connection, false); + var reader = DSL.using(connection, SQLDialect.POSTGRES); + var scope = requiredScope(reader, expected.scope().recordId()); + requireExact(expected.scope(), scope); + Record row = joinRow(reader, scope.recordId()); + if (row == null) throw unavailable(); + var result = decodeJoin(scope, row); + requireSameRequest(expected, result); + return result; + }); } private void lockOriginal( @@ -318,11 +315,10 @@ private void requireMutation() { || !Integer.valueOf(Connection.TRANSACTION_READ_COMMITTED) .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) throw unavailable(); - dsl.connectionResult( - connection -> { - requireConnection(connection, true); - return null; - }); + dsl.connectionResult(connection -> { + requireConnection(connection, true); + return null; + }); } private static void requireConnection(Connection connection, boolean mutation) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameInstanceRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameInstanceRepository.java index 84907ee1a3..a00922af53 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameInstanceRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameInstanceRepository.java @@ -248,199 +248,193 @@ public ScriptPinMutationResult applyScriptPin( validatedBaseVersionId, null, false); - return dsl.transactionResult( - configuration -> { - DSLContext tx = DSL.using(configuration); - Optional replay = - ledger.replayExistingOperation(tx, tenantId, gameInstanceId, controlPlaneRequestId); - if (replay.isPresent()) { - return replay.get(); - } - - Record current = - tx.select(SELECT_FIELDS) - .from(GAME_INSTANCES) - .where( - GAME_INSTANCES - .ID - .eq(gameInstanceId) - .and(GAME_INSTANCES.TENANT_ID.eq(tenantId))) - .forUpdate() - .fetchOne(); - if (current == null) { - throw new IllegalArgumentException("Game instance not found"); - } - // Different request IDs serialize on the instance row. Recheck the operation after - // taking that lock so an identical concurrent request replays the winner's result - // instead of racing its primary-key insert. - replay = - ledger.replayExistingOperation(tx, tenantId, gameInstanceId, controlPlaneRequestId); - if (replay.isPresent()) { - return replay.get(); - } - String previousPatch = normalizePatch(current.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)); - Long previousBaseVersionId = current.get(GAME_INSTANCES.SCRIPT_PATCH_BASE_VERSION_ID); - Long previousEpoch = current.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH); - String previousRequestId = - current.get(GAME_INSTANCES.SCRIPT_PATCH_PINNED_CONTROL_PLANE_REQUEST_ID); - ScriptPinTupleCoherence.requireCoherent(previousPatch, previousEpoch, previousRequestId); - String effectiveOperationKind = - effectiveOperationKind(operationKind, targetScriptPatchVersion, previousPatch); - String effectiveMutationDigest = - mutationDigest( - tenantId, - gameInstanceId, - effectiveOperationKind, - targetScriptPatchVersion, - actorPrincipal, - reason, - expectedPinKind, - expectedScriptPinEpoch); - - Long lockedRuntimeVersionId = - RuntimeVersionIdResolver.resolve( - current.get(GAME_INSTANCES.VERSION_ID), - current.get(GAME_INSTANCES.RUNTIME_VERSION)); - if (lockedRuntimeVersionId == null - || !validatedBaseVersionId.equals(lockedRuntimeVersionId)) { - String errorCode = - lockedRuntimeVersionId == null - ? "SCRIPT_PATCH_AUTHORITY_UNAVAILABLE" - : "SCRIPT_PATCH_BASE_VERSION_MISMATCH"; - ScriptPinMutationResult result = - new ScriptPinMutationResult( - previousPatch, - previousEpoch, - previousPatch, - previousEpoch, - controlPlaneRequestId, - errorCode, - previousBaseVersionId, - previousBaseVersionId); - insertOperation( - tx, - tenantId, - gameInstanceId, - effectiveOperationKind, - targetScriptPatchVersion, - validatedBaseVersionId, - expectedPinKind, - expectedScriptPinEpoch, - actorPrincipal, - reason, - effectiveMutationDigest, - result); - return result; - } - - long currentEpoch = previousEpoch == null ? 0L : previousEpoch; - if (!expectedPinMatches( - expectedPinKind, expectedScriptPinEpoch, previousPatch, previousEpoch)) { - ScriptPinMutationResult result = - new ScriptPinMutationResult( - previousPatch, - previousEpoch, - previousPatch, - previousEpoch, - controlPlaneRequestId, - "SCRIPT_PIN_EXPECTATION_FAILED", - previousBaseVersionId, - previousBaseVersionId); - insertOperation( - tx, - tenantId, - gameInstanceId, - effectiveOperationKind, - targetScriptPatchVersion, - validatedBaseVersionId, - expectedPinKind, - expectedScriptPinEpoch, - actorPrincipal, - reason, - effectiveMutationDigest, - result); - return result; - } - - if (currentEpoch == Long.MAX_VALUE) { - ScriptPinMutationResult result = - new ScriptPinMutationResult( - previousPatch, - previousEpoch, - previousPatch, - previousEpoch, - controlPlaneRequestId, - "SCRIPT_PIN_EPOCH_EXHAUSTED", - previousBaseVersionId, - previousBaseVersionId); - insertOperation( - tx, - tenantId, - gameInstanceId, - effectiveOperationKind, - targetScriptPatchVersion, - validatedBaseVersionId, - expectedPinKind, - expectedScriptPinEpoch, - actorPrincipal, - reason, - effectiveMutationDigest, - result); - return result; - } - - long resultingEpoch = currentEpoch + 1L; - long currentRowVersion = - current.get(GAME_INSTANCES.ROW_VERSION) == null - ? 0L - : current.get(GAME_INSTANCES.ROW_VERSION); - int updated = - tx.update(GAME_INSTANCES) - .set(GAME_INSTANCES.SCRIPT_PATCH_VERSION, targetScriptPatchVersion) - .set(GAME_INSTANCES.SCRIPT_PATCH_BASE_VERSION_ID, validatedBaseVersionId) - .set(GAME_INSTANCES.SCRIPT_PIN_EPOCH, resultingEpoch) - .set(GAME_INSTANCES.SCRIPT_PATCH_PINNED_AT, toLocalDateTime(Instant.now())) - .set(GAME_INSTANCES.SCRIPT_PATCH_PINNED_BY, actorPrincipal) - .set(GAME_INSTANCES.SCRIPT_PATCH_PINNED_REASON, reason) - .set( - GAME_INSTANCES.SCRIPT_PATCH_PINNED_CONTROL_PLANE_REQUEST_ID, - controlPlaneRequestId) - .set(GAME_INSTANCES.ROW_VERSION, currentRowVersion + 1L) - .where( - GAME_INSTANCES - .ID - .eq(gameInstanceId) - .and(GAME_INSTANCES.TENANT_ID.eq(tenantId)) - .and(GAME_INSTANCES.ROW_VERSION.eq(currentRowVersion))) - .execute(); - if (updated != 1) { - throw new IllegalStateException("Failed to update game_instance id=" + gameInstanceId); - } - ScriptPinMutationResult result = - new ScriptPinMutationResult( - previousPatch, - previousEpoch, - targetScriptPatchVersion, - resultingEpoch, - controlPlaneRequestId, - null, - previousBaseVersionId, - validatedBaseVersionId); - insertOperation( - tx, + return dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + Optional replay = + ledger.replayExistingOperation(tx, tenantId, gameInstanceId, controlPlaneRequestId); + if (replay.isPresent()) { + return replay.get(); + } + + Record current = + tx.select(SELECT_FIELDS) + .from(GAME_INSTANCES) + .where( + GAME_INSTANCES.ID.eq(gameInstanceId).and(GAME_INSTANCES.TENANT_ID.eq(tenantId))) + .forUpdate() + .fetchOne(); + if (current == null) { + throw new IllegalArgumentException("Game instance not found"); + } + // Different request IDs serialize on the instance row. Recheck the operation after + // taking that lock so an identical concurrent request replays the winner's result + // instead of racing its primary-key insert. + replay = ledger.replayExistingOperation(tx, tenantId, gameInstanceId, controlPlaneRequestId); + if (replay.isPresent()) { + return replay.get(); + } + String previousPatch = normalizePatch(current.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)); + Long previousBaseVersionId = current.get(GAME_INSTANCES.SCRIPT_PATCH_BASE_VERSION_ID); + Long previousEpoch = current.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH); + String previousRequestId = + current.get(GAME_INSTANCES.SCRIPT_PATCH_PINNED_CONTROL_PLANE_REQUEST_ID); + ScriptPinTupleCoherence.requireCoherent(previousPatch, previousEpoch, previousRequestId); + String effectiveOperationKind = + effectiveOperationKind(operationKind, targetScriptPatchVersion, previousPatch); + String effectiveMutationDigest = + mutationDigest( tenantId, gameInstanceId, effectiveOperationKind, targetScriptPatchVersion, - validatedBaseVersionId, - expectedPinKind, - expectedScriptPinEpoch, actorPrincipal, reason, - effectiveMutationDigest, - result); - return result; - }); + expectedPinKind, + expectedScriptPinEpoch); + + Long lockedRuntimeVersionId = + RuntimeVersionIdResolver.resolve( + current.get(GAME_INSTANCES.VERSION_ID), current.get(GAME_INSTANCES.RUNTIME_VERSION)); + if (lockedRuntimeVersionId == null + || !validatedBaseVersionId.equals(lockedRuntimeVersionId)) { + String errorCode = + lockedRuntimeVersionId == null + ? "SCRIPT_PATCH_AUTHORITY_UNAVAILABLE" + : "SCRIPT_PATCH_BASE_VERSION_MISMATCH"; + ScriptPinMutationResult result = + new ScriptPinMutationResult( + previousPatch, + previousEpoch, + previousPatch, + previousEpoch, + controlPlaneRequestId, + errorCode, + previousBaseVersionId, + previousBaseVersionId); + insertOperation( + tx, + tenantId, + gameInstanceId, + effectiveOperationKind, + targetScriptPatchVersion, + validatedBaseVersionId, + expectedPinKind, + expectedScriptPinEpoch, + actorPrincipal, + reason, + effectiveMutationDigest, + result); + return result; + } + + long currentEpoch = previousEpoch == null ? 0L : previousEpoch; + if (!expectedPinMatches( + expectedPinKind, expectedScriptPinEpoch, previousPatch, previousEpoch)) { + ScriptPinMutationResult result = + new ScriptPinMutationResult( + previousPatch, + previousEpoch, + previousPatch, + previousEpoch, + controlPlaneRequestId, + "SCRIPT_PIN_EXPECTATION_FAILED", + previousBaseVersionId, + previousBaseVersionId); + insertOperation( + tx, + tenantId, + gameInstanceId, + effectiveOperationKind, + targetScriptPatchVersion, + validatedBaseVersionId, + expectedPinKind, + expectedScriptPinEpoch, + actorPrincipal, + reason, + effectiveMutationDigest, + result); + return result; + } + + if (currentEpoch == Long.MAX_VALUE) { + ScriptPinMutationResult result = + new ScriptPinMutationResult( + previousPatch, + previousEpoch, + previousPatch, + previousEpoch, + controlPlaneRequestId, + "SCRIPT_PIN_EPOCH_EXHAUSTED", + previousBaseVersionId, + previousBaseVersionId); + insertOperation( + tx, + tenantId, + gameInstanceId, + effectiveOperationKind, + targetScriptPatchVersion, + validatedBaseVersionId, + expectedPinKind, + expectedScriptPinEpoch, + actorPrincipal, + reason, + effectiveMutationDigest, + result); + return result; + } + + long resultingEpoch = currentEpoch + 1L; + long currentRowVersion = + current.get(GAME_INSTANCES.ROW_VERSION) == null + ? 0L + : current.get(GAME_INSTANCES.ROW_VERSION); + int updated = + tx.update(GAME_INSTANCES) + .set(GAME_INSTANCES.SCRIPT_PATCH_VERSION, targetScriptPatchVersion) + .set(GAME_INSTANCES.SCRIPT_PATCH_BASE_VERSION_ID, validatedBaseVersionId) + .set(GAME_INSTANCES.SCRIPT_PIN_EPOCH, resultingEpoch) + .set(GAME_INSTANCES.SCRIPT_PATCH_PINNED_AT, toLocalDateTime(Instant.now())) + .set(GAME_INSTANCES.SCRIPT_PATCH_PINNED_BY, actorPrincipal) + .set(GAME_INSTANCES.SCRIPT_PATCH_PINNED_REASON, reason) + .set( + GAME_INSTANCES.SCRIPT_PATCH_PINNED_CONTROL_PLANE_REQUEST_ID, + controlPlaneRequestId) + .set(GAME_INSTANCES.ROW_VERSION, currentRowVersion + 1L) + .where( + GAME_INSTANCES + .ID + .eq(gameInstanceId) + .and(GAME_INSTANCES.TENANT_ID.eq(tenantId)) + .and(GAME_INSTANCES.ROW_VERSION.eq(currentRowVersion))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("Failed to update game_instance id=" + gameInstanceId); + } + ScriptPinMutationResult result = + new ScriptPinMutationResult( + previousPatch, + previousEpoch, + targetScriptPatchVersion, + resultingEpoch, + controlPlaneRequestId, + null, + previousBaseVersionId, + validatedBaseVersionId); + insertOperation( + tx, + tenantId, + gameInstanceId, + effectiveOperationKind, + targetScriptPatchVersion, + validatedBaseVersionId, + expectedPinKind, + expectedScriptPinEpoch, + actorPrincipal, + reason, + effectiveMutationDigest, + result); + return result; + }); } /** @@ -502,75 +496,70 @@ public ScriptPinMutationResult recordScriptPinFailure( validatedBaseVersionId, errorCode, true); - return dsl.transactionResult( - configuration -> { - DSLContext tx = DSL.using(configuration); - Optional replay = - ledger.replayExistingOperation(tx, tenantId, gameInstanceId, controlPlaneRequestId); - if (replay.isPresent()) { - return replay.get(); - } - Record current = - tx.select(SELECT_FIELDS) - .from(GAME_INSTANCES) - .where( - GAME_INSTANCES - .ID - .eq(gameInstanceId) - .and(GAME_INSTANCES.TENANT_ID.eq(tenantId))) - .forUpdate() - .fetchOne(); - if (current == null) { - throw new IllegalArgumentException("Game instance not found"); - } - replay = - ledger.replayExistingOperation(tx, tenantId, gameInstanceId, controlPlaneRequestId); - if (replay.isPresent()) { - return replay.get(); - } - String previousPatch = normalizePatch(current.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)); - Long previousBaseVersionId = current.get(GAME_INSTANCES.SCRIPT_PATCH_BASE_VERSION_ID); - Long previousEpoch = current.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH); - String previousRequestId = - current.get(GAME_INSTANCES.SCRIPT_PATCH_PINNED_CONTROL_PLANE_REQUEST_ID); - ScriptPinTupleCoherence.requireCoherent(previousPatch, previousEpoch, previousRequestId); - String effectiveOperationKind = - effectiveOperationKind(operationKind, targetScriptPatchVersion, previousPatch); - String effectiveMutationDigest = - mutationDigest( - tenantId, - gameInstanceId, - effectiveOperationKind, - targetScriptPatchVersion, - actorPrincipal, - reason, - expectedPinKind, - expectedScriptPinEpoch); - ScriptPinMutationResult result = - new ScriptPinMutationResult( - previousPatch, - previousEpoch, - previousPatch, - previousEpoch, - controlPlaneRequestId, - errorCode, - previousBaseVersionId, - previousBaseVersionId); - insertOperation( - tx, + return dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + Optional replay = + ledger.replayExistingOperation(tx, tenantId, gameInstanceId, controlPlaneRequestId); + if (replay.isPresent()) { + return replay.get(); + } + Record current = + tx.select(SELECT_FIELDS) + .from(GAME_INSTANCES) + .where( + GAME_INSTANCES.ID.eq(gameInstanceId).and(GAME_INSTANCES.TENANT_ID.eq(tenantId))) + .forUpdate() + .fetchOne(); + if (current == null) { + throw new IllegalArgumentException("Game instance not found"); + } + replay = ledger.replayExistingOperation(tx, tenantId, gameInstanceId, controlPlaneRequestId); + if (replay.isPresent()) { + return replay.get(); + } + String previousPatch = normalizePatch(current.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)); + Long previousBaseVersionId = current.get(GAME_INSTANCES.SCRIPT_PATCH_BASE_VERSION_ID); + Long previousEpoch = current.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH); + String previousRequestId = + current.get(GAME_INSTANCES.SCRIPT_PATCH_PINNED_CONTROL_PLANE_REQUEST_ID); + ScriptPinTupleCoherence.requireCoherent(previousPatch, previousEpoch, previousRequestId); + String effectiveOperationKind = + effectiveOperationKind(operationKind, targetScriptPatchVersion, previousPatch); + String effectiveMutationDigest = + mutationDigest( tenantId, gameInstanceId, effectiveOperationKind, targetScriptPatchVersion, - validatedBaseVersionId, - expectedPinKind, - expectedScriptPinEpoch, actorPrincipal, reason, - effectiveMutationDigest, - result); - return result; - }); + expectedPinKind, + expectedScriptPinEpoch); + ScriptPinMutationResult result = + new ScriptPinMutationResult( + previousPatch, + previousEpoch, + previousPatch, + previousEpoch, + controlPlaneRequestId, + errorCode, + previousBaseVersionId, + previousBaseVersionId); + insertOperation( + tx, + tenantId, + gameInstanceId, + effectiveOperationKind, + targetScriptPatchVersion, + validatedBaseVersionId, + expectedPinKind, + expectedScriptPinEpoch, + actorPrincipal, + reason, + effectiveMutationDigest, + result); + return result; + }); } public void deleteById(Long id) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepository.java index 287ab21208..ae45372427 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepository.java @@ -56,11 +56,10 @@ public Optional readByOriginalOperation( "Authored-core retention read differs from configured Game Session workload namespace"); } Optional result = - readTransaction.execute( - status -> { - Record row = select(targetNamespace, controlPlaneRequestId); - return row == null ? Optional.empty() : Optional.of(snapshot(row)); - }); + readTransaction.execute(status -> { + Record row = select(targetNamespace, controlPlaneRequestId); + return row == null ? Optional.empty() : Optional.of(snapshot(row)); + }); return Objects.requireNonNull(result, "Authored-core retention read returned no result"); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java index 2aa80bd5b0..f8cd0f8a2b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepository.java @@ -69,10 +69,9 @@ public PreparedInitialClosed prepareInitialClosed( CanonicalRealmCatalogSnapshot catalog = catalogRepository .readByRequest(request.targetNamespace(), request.catalogCreationRequestId()) - .orElseThrow( - () -> - new InvalidCanonicalClosedPointerEvidenceException( - "Exact committed initial catalog request is missing")); + .orElseThrow(() -> + new InvalidCanonicalClosedPointerEvidenceException( + "Exact committed initial catalog request is missing")); requireExactInitialCatalog(request, catalog); return new PreparedInitialClosed(request, catalog, requestDigest(request, catalog)); } @@ -208,10 +207,9 @@ public PreparedExpectedClosed prepareExpectedClosed( CanonicalClosedAdmissionPointerSnapshot origin = readByRequest(targetNamespace, originalRequestId) - .orElseThrow( - () -> - new InvalidCanonicalClosedPointerEvidenceException( - "Exact original committed canonical CLOSED origin is missing")); + .orElseThrow(() -> + new InvalidCanonicalClosedPointerEvidenceException( + "Exact original committed canonical CLOSED origin is missing")); requireExpectedVersions(origin, expectedPointerVersion, expectedCatalogRevision); return new PreparedExpectedClosed(origin, expectedPointerVersion, expectedCatalogRevision); } @@ -267,10 +265,9 @@ public Optional readOriginalClosedOrigi CanonicalRealmCatalogSnapshot catalog = catalogRepository .readByRequest(targetNamespace, request.catalogCreationRequestId()) - .orElseThrow( - () -> - new InvalidCanonicalClosedPointerEvidenceException( - "Canonical CLOSED origin lost its exact catalog evidence")); + .orElseThrow(() -> + new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED origin lost its exact catalog evidence")); return Optional.of( verifyOrigin(targetNamespace, originalRequestId, outcome, catalog, null, false)); } catch (InvalidCanonicalClosedPointerEvidenceException @@ -348,10 +345,9 @@ CanonicalClosedAdmissionPointerSnapshot lockOriginalClosedOriginForRealm( UUID originalRequestId = required(outcomes.getFirst(), "request_id", UUID.class); CanonicalClosedAdmissionPointerSnapshot origin = lockOriginalClosedOrigin(targetNamespace, originalRequestId) - .orElseThrow( - () -> - new InvalidCanonicalClosedPointerEvidenceException( - "Exact historical original CLOSED request outcome is missing")); + .orElseThrow(() -> + new InvalidCanonicalClosedPointerEvidenceException( + "Exact historical original CLOSED request outcome is missing")); if (!targetNamespace.equals(origin.targetNamespace()) || !canonicalTenantId.equals(origin.canonicalTenantId()) || !realmId.equals(origin.realmId())) { @@ -571,10 +567,9 @@ public Optional readByRequest( CanonicalRealmCatalogSnapshot catalog = catalogRepository .readByRequest(targetNamespace, request.catalogCreationRequestId()) - .orElseThrow( - () -> - new InvalidCanonicalClosedPointerEvidenceException( - "Canonical CLOSED pointer outcome lost its catalog reference")); + .orElseThrow(() -> + new InvalidCanonicalClosedPointerEvidenceException( + "Canonical CLOSED pointer outcome lost its catalog reference")); Record pointer = findCanonicalPointer(request); return Optional.of(verifyOrigin(targetNamespace, requestId, outcome, catalog, pointer)); } catch (InvalidCanonicalClosedPointerEvidenceException @@ -1054,18 +1049,17 @@ private void requireWritableOwnerTransaction() { throw new IllegalStateException( "Canonical CLOSED pointer creation requires a read-write transaction"); } - dsl.connectionResult( - connection -> { - if (connection.getAutoCommit()) { - throw new IllegalStateException( - "Canonical CLOSED pointer DSL connection must join the owner transaction"); - } - if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new IllegalStateException( - "Canonical CLOSED pointer creation requires READ COMMITTED isolation"); - } - return null; - }); + dsl.connectionResult(connection -> { + if (connection.getAutoCommit()) { + throw new IllegalStateException( + "Canonical CLOSED pointer DSL connection must join the owner transaction"); + } + if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Canonical CLOSED pointer creation requires READ COMMITTED isolation"); + } + return null; + }); Record isolationRow = dsl.fetchOne("SHOW transaction_isolation"); if (isolationRow == null || !"read committed".equalsIgnoreCase(isolationRow.get(0, String.class).trim())) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java index 6c37a0458d..5cec8678f3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalInstanceLaunchRepository.java @@ -67,61 +67,57 @@ public FixtureCanonicalInstanceLaunch createVerifiedFixtureStartingLaunch( FixtureCanonicalRealmCatalog catalog = catalogRepository.establishVerifiedFixtureRealm(evidence); FixtureCanonicalInstanceLaunch committed = - writeTransaction.execute( - status -> { - requireOwnerTransaction(); - dsl.execute( - "SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", - "canonical-launch:" - + workloadNamespace - + ":" - + descriptor.controlPlaneRequestId()); - FixtureCanonicalRealmCatalog actual = - catalogRepository.readVerifiedFixtureRealmInOwnerTransaction(evidence); - if (!catalog.equals(actual)) { - throw new InvalidCanonicalInstanceLaunchException( - "Fixture catalog changed before STARTING"); - } - Record existing = - readLaunchRowByOperationInTransaction(descriptor.controlPlaneRequestId(), true); - if (existing != null) return readFixtureLaunch(existing, evidence, actual, false); - if (dsl.fetchOne( - "SELECT id FROM game_instances WHERE tenant_id = ? AND run_owned_start_request_id = ? FOR UPDATE", - actual.association().gameSessionTenantId(), - descriptor.controlPlaneRequestId()) - != null) { - throw new InvalidCanonicalInstanceLaunchException( - "Runtime identity has no exact immutable fixture association"); - } - UUID instanceUuid = newNonNilUuid(); - Record runtime = - dsl.fetchOne( - "INSERT INTO game_instances (tenant_id, runtime_version, owner_account_id, status, row_version," - + " game_instance_uuid, game_template_id, launch_descriptor_id, version_id, release_bundle_id," - + " generation_config_revision, version_state_epoch, run_owned_start_request_id," - + " run_owned_start_request_digest, run_owned_start_published_release_bundle_ref)" - + " VALUES (?, ?, ?, 'STARTING', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id", - actual.association().gameSessionTenantId(), - Long.toString(descriptor.versionId()), - evidence.fixtureCapability().ownerAccountId(), - instanceUuid, - descriptor.gameTemplateId(), - descriptor.launchDescriptorId(), - descriptor.versionId(), - descriptor.releaseBundleId(), - descriptor.generationConfigRevision(), - descriptor.versionStateEpoch(), - descriptor.controlPlaneRequestId(), - evidence.fixtureRuntimeRequestDigest(), - descriptor.publishedReleaseBundleRef()); - long instanceId = required(runtime, "id", Long.class); - insertFixtureAssociation(evidence, descriptor, actual, instanceId, instanceUuid); - return readFixtureLaunch( - readLaunchRowByOperationInTransaction(descriptor.controlPlaneRequestId(), false), - evidence, - actual, - true); - }); + writeTransaction.execute(status -> { + requireOwnerTransaction(); + dsl.execute( + "SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", + "canonical-launch:" + workloadNamespace + ":" + descriptor.controlPlaneRequestId()); + FixtureCanonicalRealmCatalog actual = + catalogRepository.readVerifiedFixtureRealmInOwnerTransaction(evidence); + if (!catalog.equals(actual)) { + throw new InvalidCanonicalInstanceLaunchException( + "Fixture catalog changed before STARTING"); + } + Record existing = + readLaunchRowByOperationInTransaction(descriptor.controlPlaneRequestId(), true); + if (existing != null) return readFixtureLaunch(existing, evidence, actual, false); + if (dsl.fetchOne( + "SELECT id FROM game_instances WHERE tenant_id = ? AND run_owned_start_request_id = ? FOR UPDATE", + actual.association().gameSessionTenantId(), + descriptor.controlPlaneRequestId()) + != null) { + throw new InvalidCanonicalInstanceLaunchException( + "Runtime identity has no exact immutable fixture association"); + } + UUID instanceUuid = newNonNilUuid(); + Record runtime = + dsl.fetchOne( + "INSERT INTO game_instances (tenant_id, runtime_version, owner_account_id, status, row_version," + + " game_instance_uuid, game_template_id, launch_descriptor_id, version_id, release_bundle_id," + + " generation_config_revision, version_state_epoch, run_owned_start_request_id," + + " run_owned_start_request_digest, run_owned_start_published_release_bundle_ref)" + + " VALUES (?, ?, ?, 'STARTING', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id", + actual.association().gameSessionTenantId(), + Long.toString(descriptor.versionId()), + evidence.fixtureCapability().ownerAccountId(), + instanceUuid, + descriptor.gameTemplateId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + descriptor.releaseBundleId(), + descriptor.generationConfigRevision(), + descriptor.versionStateEpoch(), + descriptor.controlPlaneRequestId(), + evidence.fixtureRuntimeRequestDigest(), + descriptor.publishedReleaseBundleRef()); + long instanceId = required(runtime, "id", Long.class); + insertFixtureAssociation(evidence, descriptor, actual, instanceId, instanceUuid); + return readFixtureLaunch( + readLaunchRowByOperationInTransaction(descriptor.controlPlaneRequestId(), false), + evidence, + actual, + true); + }); Objects.requireNonNull(committed, "Fixture launch transaction returned no result"); FixtureCanonicalInstanceLaunch independent = readVerifiedFixtureLaunch(evidence); if (independent.gameInstanceId() != committed.gameInstanceId() @@ -137,14 +133,13 @@ public FixtureCanonicalInstanceLaunch readVerifiedFixtureLaunch( requireNoActiveOwnerTransaction(); evidence.requireVerifiedFixture(); return Objects.requireNonNull( - readTransaction.execute( - status -> - readFixtureLaunch( - readLaunchRowByOperationInTransaction( - evidence.fixtureCapability().operationId(), false), - evidence, - catalogRepository.readVerifiedFixtureRealmInOwnerTransaction(evidence), - false)), + readTransaction.execute(status -> + readFixtureLaunch( + readLaunchRowByOperationInTransaction( + evidence.fixtureCapability().operationId(), false), + evidence, + catalogRepository.readVerifiedFixtureRealmInOwnerTransaction(evidence), + false)), "Fixture launch independent read returned no result"); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalLaunchPreparationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalLaunchPreparationRepository.java index 726ccc4196..d6ead75d19 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalLaunchPreparationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalLaunchPreparationRepository.java @@ -532,15 +532,14 @@ private void requireWritableReadCommittedOwnerTransaction() { throw new IllegalStateException( "Launch preparation persistence requires a writable owner transaction"); } - dsl.connectionResult( - connection -> { - if (connection.getAutoCommit() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new IllegalStateException( - "Launch preparation persistence requires the owner READ COMMITTED connection"); - } - return null; - }); + dsl.connectionResult(connection -> { + if (connection.getAutoCommit() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Launch preparation persistence requires the owner READ COMMITTED connection"); + } + return null; + }); Record isolation = dsl.fetchOne("SHOW transaction_isolation"); if (isolation == null || !"read committed".equalsIgnoreCase(isolation.get(0, String.class).trim())) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java index bb1242d251..d1fb903e80 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepository.java @@ -1234,18 +1234,17 @@ private void requireWritableOwnerTransaction() { throw new IllegalStateException( "Canonical realm catalog creation requires a read-write transaction"); } - dsl.connectionResult( - connection -> { - if (connection.getAutoCommit()) { - throw new IllegalStateException( - "Canonical realm catalog DSL connection must join the owner transaction"); - } - if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new IllegalStateException( - "Canonical realm catalog creation requires READ COMMITTED isolation"); - } - return null; - }); + dsl.connectionResult(connection -> { + if (connection.getAutoCommit()) { + throw new IllegalStateException( + "Canonical realm catalog DSL connection must join the owner transaction"); + } + if (connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Canonical realm catalog creation requires READ COMMITTED isolation"); + } + return null; + }); Record isolationRow = dsl.fetchOne("SHOW transaction_isolation"); if (isolationRow == null || !"read committed".equalsIgnoreCase(isolationRow.get(0, String.class).trim())) { @@ -1442,37 +1441,36 @@ public FixtureCanonicalRealmCatalog establishVerifiedFixtureRealm( "Fixture source differs from configured owner namespace"); } CanonicalRealmCatalogSnapshot committed = - writeTransaction.execute( - status -> { - FreshTenantAssociation association = - new GameSessionFreshTenantAssociationRepository(dsl) - .associateVerifiedFixtureInOwnerTransaction(evidence); - UUID requestId = UUID.fromString(evidence.fixtureCapability().operationId()); - IntakeReceipt intake = - new GameSessionAuthoredWorldSourceRepository(dsl) - .register(requestId, evidence.sourceEvidence()); - var cap = evidence.fixtureCapability(); - var request = - new CreateCanonicalRealmCatalogRequest( - requestId, - workloadNamespace, - association.canonicalTenantId(), - intake.operationId(), - cap.realmSlug(), - cap.realmDisplayName(), - cap.visible(), - cap.publicProductionRealm(), - cap.stateScope(), - cap.characterCreationPolicy(), - null, - null); - return createInitialPublicProduction( - new PreparedInitialPublicProduction( - request, - intake, - new FixturePolicy(evidence), - evidence.fixturePolicyRequestBytes())); - }); + writeTransaction.execute(status -> { + FreshTenantAssociation association = + new GameSessionFreshTenantAssociationRepository(dsl) + .associateVerifiedFixtureInOwnerTransaction(evidence); + UUID requestId = UUID.fromString(evidence.fixtureCapability().operationId()); + IntakeReceipt intake = + new GameSessionAuthoredWorldSourceRepository(dsl) + .register(requestId, evidence.sourceEvidence()); + var cap = evidence.fixtureCapability(); + var request = + new CreateCanonicalRealmCatalogRequest( + requestId, + workloadNamespace, + association.canonicalTenantId(), + intake.operationId(), + cap.realmSlug(), + cap.realmDisplayName(), + cap.visible(), + cap.publicProductionRealm(), + cap.stateScope(), + cap.characterCreationPolicy(), + null, + null); + return createInitialPublicProduction( + new PreparedInitialPublicProduction( + request, + intake, + new FixturePolicy(evidence), + evidence.fixturePolicyRequestBytes())); + }); Objects.requireNonNull(committed, "Fixture catalog owner returned no committed result"); return readVerifiedFixtureRealm(evidence); } @@ -1597,10 +1595,9 @@ private FreshTenantAssociation verifyStoredFreshAssociation( FreshTenantAssociation association = new GameSessionFreshTenantAssociationRepository(dsl) .readCanonicalTenantAssociationSnapshot(source.targetNamespace(), canonicalTenantId) - .orElseThrow( - () -> - new InvalidCatalogEvidenceException( - "Fresh canonical realm requires an existing complete Game Session tenant association")); + .orElseThrow(() -> + new InvalidCatalogEvidenceException( + "Fresh canonical realm requires an existing complete Game Session tenant association")); FreshTenantCreationEvidence creation = association.sourceEvidence(); if (!creation.targetNamespace().equals(source.targetNamespace()) || !creation.canonicalTenantId().equals(source.canonicalTenantId()) @@ -1636,10 +1633,8 @@ private static SelectedPolicy selectPolicy( } List publicPolicies = publishedSet.policies().stream() - .filter( - policy -> - policy.source().policy().visible() - && policy.source().policy().publicProduction()) + .filter(policy -> + policy.source().policy().visible() && policy.source().policy().publicProduction()) .toList(); if (publishedSet.policyCount() != publishedSet.policies().size() || publicPolicies.size() != 1) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCurrentPrivatePlaytestRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCurrentPrivatePlaytestRepository.java index 3c182ac723..e3aa13fe5b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCurrentPrivatePlaytestRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionCurrentPrivatePlaytestRepository.java @@ -180,10 +180,9 @@ public Optional readCurrent( preparations .readExact( targetNamespace, tenantId, worldSlug, realmSlug, selected.playtestLifecycleId()) - .orElseThrow( - () -> - new SourceUnavailableException( - "Current private preparation source is unavailable")); + .orElseThrow(() -> + new SourceUnavailableException( + "Current private preparation source is unavailable")); requireQualifiedPreparation(selected.request(), snapshot); return Optional.of(new Current(selected, snapshot)); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepository.java index e00bd95fdc..ee752953ea 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepository.java @@ -233,15 +233,14 @@ private void requireWritableReadCommittedOwnerTransaction() { throw new IllegalStateException( "Fresh tenant association requires a writable owner transaction"); } - dsl.connectionResult( - connection -> { - if (connection.getAutoCommit() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new IllegalStateException( - "Fresh tenant association requires writable READ COMMITTED isolation"); - } - return null; - }); + dsl.connectionResult(connection -> { + if (connection.getAutoCommit() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Fresh tenant association requires writable READ COMMITTED isolation"); + } + return null; + }); Record transaction = dsl.fetchOne( "SELECT current_setting('transaction_isolation') AS isolation, " @@ -381,11 +380,10 @@ public FreshTenantAssociation associateFreshTenant( } FreshTenantAssociation independentReadback = - readTransaction.execute( - status -> - readByCanonicalTenantIdInTransaction( - sourceEvidence.targetNamespace(), sourceEvidence.canonicalTenantId()) - .orElse(null)); + readTransaction.execute(status -> + readByCanonicalTenantIdInTransaction( + sourceEvidence.targetNamespace(), sourceEvidence.canonicalTenantId()) + .orElse(null)); if (independentReadback == null || !sourceEvidence.equals(independentReadback.sourceEvidence()) || !committed.equals(independentReadback)) { @@ -501,10 +499,9 @@ private FreshTenantAssociation commitAssociation( FreshTenantAssociation readback = readByCanonicalTenantIdInTransaction( sourceEvidence.targetNamespace(), sourceEvidence.canonicalTenantId()) - .orElseThrow( - () -> - new InvalidFreshTenantAssociationException( - "Game Session fresh tenant association did not read back in its owner transaction")); + .orElseThrow(() -> + new InvalidFreshTenantAssociationException( + "Game Session fresh tenant association did not read back in its owner transaction")); requireExactSource(sourceEvidence, readback.sourceEvidence()); return readback; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionInitialPlaytestLifecycleRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionInitialPlaytestLifecycleRepository.java index 5118ea0002..e6e081551e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionInitialPlaytestLifecycleRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionInitialPlaytestLifecycleRepository.java @@ -324,10 +324,9 @@ private SourceReference readSource(Request request, boolean lockSource) { } List targetPolicies = policy.policies().stream() - .filter( - candidate -> - candidate.source().policy().worldSlug().equals(request.worldSlug()) - && candidate.source().policy().realmSlug().equals(request.realmSlug())) + .filter(candidate -> + candidate.source().policy().worldSlug().equals(request.worldSlug()) + && candidate.source().policy().realmSlug().equals(request.realmSlug())) .toList(); if (targetPolicies.size() != 1) { throw new SourceUnavailableException( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivateFreshCatalogRevisionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivateFreshCatalogRevisionRepository.java index 12a7248c95..14418d369e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivateFreshCatalogRevisionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivateFreshCatalogRevisionRepository.java @@ -198,10 +198,8 @@ public Optional readCurrent(UUID realmId) { readByPreparation( required(current, "preparation_request_id", UUID.class), required(current, "playtest_lifecycle_id", UUID.class)) - .orElseThrow( - () -> - new InvalidPrivateTargetException( - "Current catalog original evidence is absent")); + .orElseThrow(() -> + new InvalidPrivateTargetException("Current catalog original evidence is absent")); requireHead(current, result); return Optional.of(result); } @@ -249,9 +247,8 @@ private Preparation ownerPreparation(AdvanceRequest request) { preparations .readExactForPrivateCatalogTarget( request.preparationRequestId(), request.playtestLifecycleId()) - .orElseThrow( - () -> - new PreparationUnavailableException("Original revision preparation is absent")) + .orElseThrow(() -> + new PreparationUnavailableException("Original revision preparation is absent")) .preparation(); originals.readExactSourceCatalog(preparation); originals.readCompleteHumanPolicyEvidence(preparation); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivateFreshTargetRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivateFreshTargetRepository.java index 538dca396a..f426484cba 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivateFreshTargetRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivateFreshTargetRepository.java @@ -88,10 +88,9 @@ public Allocation allocate(Request request) { preparations .readExactForPrivateCatalogTarget( request.preparationRequestId(), request.playtestLifecycleId()) - .orElseThrow( - () -> - new PreparationUnavailableException( - "Exact retained FRESH preparation and lifecycle are unavailable")); + .orElseThrow(() -> + new PreparationUnavailableException( + "Exact retained FRESH preparation and lifecycle are unavailable")); Preparation preparation = snapshot.preparation(); CanonicalRealmCatalogSnapshot sourceCatalog = readExactSourceCatalog(preparation); IntakeReceipt intake = sourceCatalog.sourceIntakeReceipt(); @@ -728,15 +727,14 @@ void requireWritableSerializableOwnerTransaction() { throw new IllegalStateException( "Private FRESH target allocation requires a writable owner transaction"); } - dsl.connectionResult( - connection -> { - if (connection.getAutoCommit() - || connection.getTransactionIsolation() != Connection.TRANSACTION_SERIALIZABLE) { - throw new IllegalStateException( - "Private FRESH target allocation requires its owner SERIALIZABLE transaction"); - } - return null; - }); + dsl.connectionResult(connection -> { + if (connection.getAutoCommit() + || connection.getTransactionIsolation() != Connection.TRANSACTION_SERIALIZABLE) { + throw new IllegalStateException( + "Private FRESH target allocation requires its owner SERIALIZABLE transaction"); + } + return null; + }); Record isolationRow = dsl.fetchOne("SHOW transaction_isolation"); if (isolationRow == null || !"serializable".equalsIgnoreCase(isolationRow.get(0, String.class).trim())) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivatePreparationProtectionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivatePreparationProtectionRepository.java index 07122157e2..3a353f8566 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivatePreparationProtectionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivatePreparationProtectionRepository.java @@ -75,66 +75,65 @@ private Hold acquireTransaction(UUID requestId, Snapshot expected, byte[] expect requireLiveCaller(); try { return Objects.requireNonNull( - owner.execute( - status -> { - // A blocking lock would establish a SERIALIZABLE snapshot before waiting, - // consuming the source budget and potentially hiding the winner's committed row. - // Roll back a busy attempt and wait without retaining a transaction/connection. - Record locked = - dsl.fetchOne( - "SELECT pg_try_advisory_xact_lock(hashtextextended(?,0)) AS acquired", - "private-source-protection/" + requestId); - if (locked == null || !Boolean.TRUE.equals(locked.get("acquired", Boolean.class))) - throw new RequestContendedException(); - Record previous = byRequest(requestId); - if (previous != null) return requireExact(previous, expectedBytes); - var readRequest = - new PrivateWorldPreparationReadGrpcCodec.Request( - UUID.randomUUID(), expected.scope(), expected.preparation().requestId()); - Snapshot current = source.read(readRequest); - if (!Arrays.equals( - expectedBytes, PrivateWorldPreparationReadGrpcCodec.stableBytes(current))) - throw new ProtectionUnavailableException( - "Private source changed before protection"); - var runtime = current.runtimeAllocation(); - var selection = current.selection(); - var target = current.target(); - requireLiveCaller(); - Record inserted = - dsl.fetchOne( - "INSERT INTO " - + TABLE - + " (request_id,hold_id,source_read_request_id,target_namespace," - + "canonical_tenant_id,world_slug,realm_slug,realm_id,preparation_request_id,playtest_lifecycle_id," - + "runtime_allocation_request_id,game_instance_id,catalog_revision,catalog_request_id," - + "selection_head_revision,selection_request_id,source_bytes,source_digest,source_evidence)" - + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING RETURNING *", - requestId, - UUID.randomUUID(), - readRequest.readRequestId(), - current.scope().targetNamespace(), - current.scope().tenantId(), - current.scope().worldSlug(), - current.scope().realmSlug(), - target.realmId(), - current.preparation().requestId(), - current.preparation().lifecycleId(), - runtime.requestId(), - runtime.gameInstanceId(), - target.catalogRevision(), - target.creationRequestId(), - selection.headRevision(), - selection.requestId(), - expectedBytes, - PrivateWorldPreparationReadEvidence.sha256(expectedBytes), - PrivateWorldPreparationReadGrpcCodec.toResponse(readRequest, current) - .getCanonicalEvidence() - .toByteArray()); - if (inserted == null) - throw new ProtectionUnavailableException( - "Private runtime already has another source protection"); - return requireExact(inserted, expectedBytes); - })); + owner.execute(status -> { + // A blocking lock would establish a SERIALIZABLE snapshot before waiting, + // consuming the source budget and potentially hiding the winner's committed row. + // Roll back a busy attempt and wait without retaining a transaction/connection. + Record locked = + dsl.fetchOne( + "SELECT pg_try_advisory_xact_lock(hashtextextended(?,0)) AS acquired", + "private-source-protection/" + requestId); + if (locked == null || !Boolean.TRUE.equals(locked.get("acquired", Boolean.class))) + throw new RequestContendedException(); + Record previous = byRequest(requestId); + if (previous != null) return requireExact(previous, expectedBytes); + var readRequest = + new PrivateWorldPreparationReadGrpcCodec.Request( + UUID.randomUUID(), expected.scope(), expected.preparation().requestId()); + Snapshot current = source.read(readRequest); + if (!Arrays.equals( + expectedBytes, PrivateWorldPreparationReadGrpcCodec.stableBytes(current))) + throw new ProtectionUnavailableException( + "Private source changed before protection"); + var runtime = current.runtimeAllocation(); + var selection = current.selection(); + var target = current.target(); + requireLiveCaller(); + Record inserted = + dsl.fetchOne( + "INSERT INTO " + + TABLE + + " (request_id,hold_id,source_read_request_id,target_namespace," + + "canonical_tenant_id,world_slug,realm_slug,realm_id,preparation_request_id,playtest_lifecycle_id," + + "runtime_allocation_request_id,game_instance_id,catalog_revision,catalog_request_id," + + "selection_head_revision,selection_request_id,source_bytes,source_digest,source_evidence)" + + " VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING RETURNING *", + requestId, + UUID.randomUUID(), + readRequest.readRequestId(), + current.scope().targetNamespace(), + current.scope().tenantId(), + current.scope().worldSlug(), + current.scope().realmSlug(), + target.realmId(), + current.preparation().requestId(), + current.preparation().lifecycleId(), + runtime.requestId(), + runtime.gameInstanceId(), + target.catalogRevision(), + target.creationRequestId(), + selection.headRevision(), + selection.requestId(), + expectedBytes, + PrivateWorldPreparationReadEvidence.sha256(expectedBytes), + PrivateWorldPreparationReadGrpcCodec.toResponse(readRequest, current) + .getCanonicalEvidence() + .toByteArray()); + if (inserted == null) + throw new ProtectionUnavailableException( + "Private runtime already has another source protection"); + return requireExact(inserted, expectedBytes); + })); } catch (RequestContendedException busy) { // TransactionTemplate has already rolled back and released its connection. requireLiveCaller(); @@ -181,23 +180,22 @@ public Hold readCurrent(UUID requestId, UUID holdId, long fence) { uuid(holdId); if (fence <= 0) throw new IllegalArgumentException("Positive source hold fence required"); return Objects.requireNonNull( - owner.execute( - status -> { - Hold held = decode(byRequest(requestId)); - if (!held.holdId().equals(holdId) || held.fence() != fence) - throw new ProtectionUnavailableException("Private protection identity differs"); - Snapshot current = - source.read( - new PrivateWorldPreparationReadGrpcCodec.Request( - UUID.randomUUID(), - held.source().scope(), - held.source().preparation().requestId())); - if (!Arrays.equals( - PrivateWorldPreparationReadGrpcCodec.stableBytes(current), - PrivateWorldPreparationReadGrpcCodec.stableBytes(held.source()))) - throw new ProtectionUnavailableException("Protected private source changed"); - return held; - })); + owner.execute(status -> { + Hold held = decode(byRequest(requestId)); + if (!held.holdId().equals(holdId) || held.fence() != fence) + throw new ProtectionUnavailableException("Private protection identity differs"); + Snapshot current = + source.read( + new PrivateWorldPreparationReadGrpcCodec.Request( + UUID.randomUUID(), + held.source().scope(), + held.source().preparation().requestId())); + if (!Arrays.equals( + PrivateWorldPreparationReadGrpcCodec.stableBytes(current), + PrivateWorldPreparationReadGrpcCodec.stableBytes(held.source()))) + throw new ProtectionUnavailableException("Protected private source changed"); + return held; + })); } private Record byRequest(UUID requestId) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivateWorldPreparationBuildReader.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivateWorldPreparationBuildReader.java index f9fd439fa6..dcb57a0a8f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivateWorldPreparationBuildReader.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionPrivateWorldPreparationBuildReader.java @@ -102,10 +102,9 @@ public Build read(PrivateWorldPreparationReadGrpcCodec.Request request) { } List targetPolicies = policy.policies().stream() - .filter( - candidate -> - candidate.source().policy().worldSlug().equals(scope.worldSlug()) - && candidate.source().policy().realmSlug().equals(scope.realmSlug())) + .filter(candidate -> + candidate.source().policy().worldSlug().equals(scope.worldSlug()) + && candidate.source().policy().realmSlug().equals(scope.realmSlug())) .toList(); if (targetPolicies.size() != 1 || !targetPolicies.getFirst().equals(s.targetPolicy())) { throw new IllegalStateException("Retained Human build differs from selected private policy"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogRepository.java index 367881b050..270ebfe47a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogRepository.java @@ -52,29 +52,28 @@ public GameSessionRuntimeFamilyCatalogRepository( public Evidence capture(Request request) { requireIndependent(request); byte[] committed = - capture.execute( - status -> { - var catalog = currentCatalog(); - byte[] requestBytes = GameSessionRuntimeFamilyCatalogCodec.requestBytes(request); - var proposed = new Evidence(request, UUID.randomUUID(), catalog); - byte[] evidenceBytes = GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(proposed); - dsl.execute( - "INSERT INTO " - + table("game_session_runtime_family_catalog_snapshot") - + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," - + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)" - + " ON CONFLICT (read_request_id) DO NOTHING", - request.readRequestId(), - request.targetNamespace(), - requestBytes, - GameSessionRuntimeFamilyCatalog.sha256(requestBytes), - proposed.snapshotId(), - catalog.catalogEpoch(), - catalog.digest(), - evidenceBytes, - proposed.digest()); - return retained(request, catalog); - }); + capture.execute(status -> { + var catalog = currentCatalog(); + byte[] requestBytes = GameSessionRuntimeFamilyCatalogCodec.requestBytes(request); + var proposed = new Evidence(request, UUID.randomUUID(), catalog); + byte[] evidenceBytes = GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(proposed); + dsl.execute( + "INSERT INTO " + + table("game_session_runtime_family_catalog_snapshot") + + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," + + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)" + + " ON CONFLICT (read_request_id) DO NOTHING", + request.readRequestId(), + request.targetNamespace(), + requestBytes, + GameSessionRuntimeFamilyCatalog.sha256(requestBytes), + proposed.snapshotId(), + catalog.catalogEpoch(), + catalog.digest(), + evidenceBytes, + proposed.digest()); + return retained(request, catalog); + }); Evidence result = readExact(request); if (!Arrays.equals(committed, GameSessionRuntimeFamilyCatalogCodec.evidenceBytes(result))) throw new CatalogConflictException("Committed Game Session catalog readback changed"); @@ -87,10 +86,9 @@ public Evidence capture(Request request) { */ public Evidence readExact(Request request) { requireIndependent(request); - return readback.execute( - status -> - GameSessionRuntimeFamilyCatalogCodec.evidenceFromStored( - retained(request, currentCatalog()))); + return readback.execute(status -> + GameSessionRuntimeFamilyCatalogCodec.evidenceFromStored( + retained(request, currentCatalog()))); } private GameSessionRuntimeFamilyCatalog currentCatalog() { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepository.java index 2b7a3cab8d..9bc80e5098 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepository.java @@ -113,10 +113,9 @@ public PinnedLaunchDescriptorSnapshot pin( GameSessionStartSessionTemplateAssociationRepository.PinnedAssociationSnapshot association = associationRepository .findPinned(claim) - .orElseThrow( - () -> - new StartSessionLaunchDescriptorConflictException( - "An original template association pin is required before descriptor pinning")); + .orElseThrow(() -> + new StartSessionLaunchDescriptorConflictException( + "An original template association pin is required before descriptor pinning")); PreparedCandidate prepared = prepareCandidate(association, candidate); Record existing = selectPin(claim.targetNamespace(), claim.controlPlaneRequestId(), true); if (existing != null) { @@ -221,10 +220,9 @@ public PinnedLaunchDescriptorSnapshot pin( GameSessionStartSessionTemplateAssociationRepository.PinnedAssociationSnapshot association = associationRepository .findPinned(continuation) - .orElseThrow( - () -> - new StartSessionLaunchDescriptorConflictException( - "An existing template association pin is required before descriptor continuation")); + .orElseThrow(() -> + new StartSessionLaunchDescriptorConflictException( + "An existing template association pin is required before descriptor continuation")); PreparedCandidate prepared = prepareCandidate(association, candidate); Record existing = selectPin(continuation, true); association = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java index e4b976f038..493cd3dde2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java @@ -531,15 +531,14 @@ private void requireWritableReadCommittedOwnerTransaction() { throw new IllegalStateException( "StartSession owner attempt requires a writable READ COMMITTED owner transaction"); } - dsl.connectionResult( - connection -> { - if (connection.getAutoCommit() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new IllegalStateException( - "StartSession owner attempt requires a writable READ COMMITTED owner transaction"); - } - return null; - }); + dsl.connectionResult(connection -> { + if (connection.getAutoCommit() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "StartSession owner attempt requires a writable READ COMMITTED owner transaction"); + } + return null; + }); Record transaction = dsl.fetchOne( "SELECT current_setting('transaction_isolation') AS isolation, " diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java index 29bc485cac..6e1bb6e154 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java @@ -165,18 +165,16 @@ public GameplayAdmissionPointer updateExisting( } GameplayAdmissionPointer current = findByIdForUpdate(entity.getId()) - .orElseThrow( - () -> - new AdmissionPointerVersionMismatchException( - "Admission pointer no longer exists: id=" + entity.getId())); + .orElseThrow(() -> + new AdmissionPointerVersionMismatchException( + "Admission pointer no longer exists: id=" + entity.getId())); requireExpectedRevisions(current, expectedPointerVersion, expectedCatalogRevision); lockRuntimeTargets(current, entity); current = findByIdForUpdate(entity.getId()) - .orElseThrow( - () -> - new AdmissionPointerVersionMismatchException( - "Admission pointer no longer exists: id=" + entity.getId())); + .orElseThrow(() -> + new AdmissionPointerVersionMismatchException( + "Admission pointer no longer exists: id=" + entity.getId())); requireExpectedRevisions(current, expectedPointerVersion, expectedCatalogRevision); if (current.getPointerVersion() == null || current.getCatalogRevision() == null diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java index 7b1e6fc3df..ce3ddc2a60 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java @@ -511,18 +511,17 @@ private Optional insertAgainstCurrentAdmissionPointer( GameplayAdmissionPointer pointer = GameplayAdmissionPointer.GAMEPLAY_ADMISSION_POINTER; List values = Arrays.stream(fields) - .map( - field -> - field.equals(GAMEPLAY_COMMAND.WORLD_SLUG) - ? pointer.WORLD_SLUG - : field.equals(GAMEPLAY_COMMAND.REALM_SLUG) - ? pointer.REALM_SLUG - : field.equals(GAMEPLAY_COMMAND.POINTER_VERSION) - ? pointer.POINTER_VERSION - : field.equals(GAMEPLAY_COMMAND.PLAYABLE_STATE_SCOPE) - ? pointer.STATE_SCOPE - : (SelectFieldOrAsterisk) - DSL.val(record.get(field), field.getDataType())) + .map(field -> + field.equals(GAMEPLAY_COMMAND.WORLD_SLUG) + ? pointer.WORLD_SLUG + : field.equals(GAMEPLAY_COMMAND.REALM_SLUG) + ? pointer.REALM_SLUG + : field.equals(GAMEPLAY_COMMAND.POINTER_VERSION) + ? pointer.POINTER_VERSION + : field.equals(GAMEPLAY_COMMAND.PLAYABLE_STATE_SCOPE) + ? pointer.STATE_SCOPE + : (SelectFieldOrAsterisk) + DSL.val(record.get(field), field.getDataType())) .toList(); Condition pointerMatch = pointer diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepository.java index 77907b33d5..e95c394b72 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepository.java @@ -149,13 +149,12 @@ public InitialGameplayLoginJournalSnapshot recordDisposalReceipt( } retained .retainedReceipt() - .ifPresent( - previous -> { - if (!previous.disposalOperationId().equals(receipt.disposalOperationId()) - || previous.disposition() != Disposition.PENDING && !previous.equals(receipt)) { - throw new JournalConflictException(); - } - }); + .ifPresent(previous -> { + if (!previous.disposalOperationId().equals(receipt.disposalOperationId()) + || previous.disposition() != Disposition.PENDING && !previous.equals(receipt)) { + throw new JournalConflictException(); + } + }); if (!retained.retainedReceipt().filter(receipt::equals).isPresent()) { dsl.execute( "UPDATE " @@ -176,13 +175,12 @@ public Optional readCommitted( Objects.requireNonNull(coordinates, "coordinates"); requireNoTransaction(); Record row = - dsl.connectionResult( - connection -> { - requireConnection(connection, false); - return DSL.using(connection, SQLDialect.POSTGRES) - .fetchOne( - "SELECT * FROM " + TABLE + " WHERE request_id = ?", coordinates.requestId()); - }); + dsl.connectionResult(connection -> { + requireConnection(connection, false); + return DSL.using(connection, SQLDialect.POSTGRES) + .fetchOne( + "SELECT * FROM " + TABLE + " WHERE request_id = ?", coordinates.requestId()); + }); if (row == null) { return Optional.empty(); } @@ -199,23 +197,18 @@ public List readRetainedPage( throw new IllegalArgumentException("LOGIN journal page size must be between 1 and 128"); } requireNoTransaction(); - return dsl.connectionResult( - connection -> { - requireConnection(connection, false); - var reader = DSL.using(connection, SQLDialect.POSTGRES); - var rows = - afterRequestId.isPresent() - ? reader.fetch( - "SELECT * FROM " - + TABLE - + " WHERE request_id > ? ORDER BY request_id LIMIT ?", - afterRequestId.orElseThrow(), - limit) - : reader.fetch("SELECT * FROM " + TABLE + " ORDER BY request_id LIMIT ?", limit); - return rows.stream() - .map(InitialGameplayLoginCoordinationJournalRepository::decode) - .toList(); - }); + return dsl.connectionResult(connection -> { + requireConnection(connection, false); + var reader = DSL.using(connection, SQLDialect.POSTGRES); + var rows = + afterRequestId.isPresent() + ? reader.fetch( + "SELECT * FROM " + TABLE + " WHERE request_id > ? ORDER BY request_id LIMIT ?", + afterRequestId.orElseThrow(), + limit) + : reader.fetch("SELECT * FROM " + TABLE + " ORDER BY request_id LIMIT ?", limit); + return rows.stream().map(InitialGameplayLoginCoordinationJournalRepository::decode).toList(); + }); } private InitialGameplayLoginJournalSnapshot locked( @@ -301,11 +294,10 @@ private void requireMutation() { .equals(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())) { throw new JournalUnavailableException(); } - dsl.connectionResult( - connection -> { - requireConnection(connection, true); - return null; - }); + dsl.connectionResult(connection -> { + requireConnection(connection, true); + return null; + }); } private static void requireConnection(Connection connection, boolean mutation) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepository.java index 671ceecd1e..8624394ea5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepository.java @@ -189,12 +189,11 @@ public List findDistinctScopesAfter(HistoryScope after, int batchS PLAYER_COMMAND_HISTORY.GAME_INSTANCE_ID.asc(), PLAYER_COMMAND_HISTORY.CHARACTER_ID.asc()) .limit(batchSize) - .fetch( - record -> - new HistoryScope( - record.get(PLAYER_COMMAND_HISTORY.TENANT_ID), - record.get(PLAYER_COMMAND_HISTORY.GAME_INSTANCE_ID), - record.get(PLAYER_COMMAND_HISTORY.CHARACTER_ID))); + .fetch(record -> + new HistoryScope( + record.get(PLAYER_COMMAND_HISTORY.TENANT_ID), + record.get(PLAYER_COMMAND_HISTORY.GAME_INSTANCE_ID), + record.get(PLAYER_COMMAND_HISTORY.CHARACTER_ID))); } public void deleteByIds(Collection ids) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java index 655f56b7ed..a830586410 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/ResumeTranscriptEntryRepository.java @@ -161,11 +161,10 @@ public void updateByteSizes(Collection entries) { List updates = entries.stream() .filter(entry -> entry.getId() != null) - .map( - entry -> - dsl.update(RESUME_TRANSCRIPT_ENTRY) - .set(RESUME_TRANSCRIPT_ENTRY.BYTE_SIZE, entry.getByteSize()) - .where(RESUME_TRANSCRIPT_ENTRY.ID.eq(entry.getId()))) + .map(entry -> + dsl.update(RESUME_TRANSCRIPT_ENTRY) + .set(RESUME_TRANSCRIPT_ENTRY.BYTE_SIZE, entry.getByteSize()) + .where(RESUME_TRANSCRIPT_ENTRY.ID.eq(entry.getId()))) .toList(); if (!updates.isEmpty()) { dsl.batch(updates).execute(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/RuntimeRegionStatusRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/RuntimeRegionStatusRepository.java index a3a294e0a1..6b0070908b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/RuntimeRegionStatusRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/RuntimeRegionStatusRepository.java @@ -90,15 +90,13 @@ public RuntimeRegionStatus ensureBaseline(RuntimeRegionStatus entity) { .doNothing() .returning() .fetchOptional(this::toEntity); - return inserted.orElseGet( - () -> - findByTenantIdAndGameInstanceId(entity.getTenantId(), entity.getGameInstanceId()) - .orElseThrow( - () -> - new IllegalStateException( - ("Natural-key conflict did not yield runtime_region_status for " - + "tenantId=%d gameInstanceId=%d") - .formatted(entity.getTenantId(), entity.getGameInstanceId())))); + return inserted.orElseGet(() -> + findByTenantIdAndGameInstanceId(entity.getTenantId(), entity.getGameInstanceId()) + .orElseThrow(() -> + new IllegalStateException( + ("Natural-key conflict did not yield runtime_region_status for " + + "tenantId=%d gameInstanceId=%d") + .formatted(entity.getTenantId(), entity.getGameInstanceId())))); } public Optional claimObservedOwnership( @@ -166,10 +164,8 @@ public RuntimeRegionStatus advanceOwnershipEpoch(RuntimeRegionStatus entity) { .set(RUNTIME_REGION_STATUS.UPDATED_AT, toLocalDateTime(entity.getUpdatedAt())) .returning() .fetchOptional(this::toEntity) - .orElseThrow( - () -> - new IllegalStateException( - "Runtime ownership mutation did not return a committed row")); + .orElseThrow(() -> + new IllegalStateException("Runtime ownership mutation did not return a committed row")); } private Optional findById(Long id) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountInitialAdmissionSettlementReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountInitialAdmissionSettlementReadService.java index c5062bb97e..0f5902ed63 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountInitialAdmissionSettlementReadService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountInitialAdmissionSettlementReadService.java @@ -47,9 +47,8 @@ public AccountInitialAdmissionSettlementReadEvidence read( var retained = bindings .read(namespace, hold.request().initialAdmissionRequestId()) - .orElseThrow( - () -> - new SettlementUnavailableException("Exact protected admission is unavailable")); + .orElseThrow(() -> + new SettlementUnavailableException("Exact protected admission is unavailable")); var protection = retained.protection(); if (!Arrays.equals(protection.canonicalBytes(), expected.canonicalBytes())) { throw new SettlementUnavailableException( @@ -62,10 +61,8 @@ public AccountInitialAdmissionSettlementReadEvidence read( protection.request().originalTuple(), request.gameSessionOwnerAttemptId(), request.gameSessionOwnerFence()) - .orElseThrow( - () -> - new SettlementUnavailableException( - "Original StartSession owner is unavailable")); + .orElseThrow(() -> + new SettlementUnavailableException("Original StartSession owner is unavailable")); if (!original.ownerMutationId().equals(request.gameSessionOwnerMutationId()) || !original.leaseExpiresAt().equals(request.originalLeaseExpiresAt()) || !Arrays.equals( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java index 2180f6f7fa..6a235e2300 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwner.java @@ -96,9 +96,8 @@ public CanonicalGameplayRosterReferenceOwner( String authenticatedEntityUri) { requireOutsideTransaction(); return Objects.requireNonNull( - transactions.execute( - ignored -> - repository.confirmRetirementAcknowledgement(request, authenticatedEntityUri))); + transactions.execute(ignored -> + repository.confirmRetirementAcknowledgement(request, authenticatedEntityUri))); } public GetCanonicalGameplayRosterReferenceResponse begin( @@ -125,12 +124,11 @@ public GetCanonicalGameplayRosterReferenceResponse begin( } var qualified = requireCurrentTarget(request); return Objects.requireNonNull( - transactions.execute( - ignored -> { - var original = repository.begin(request); - admissionRepository.lockExactCurrentOpenSnapshot(qualified); - return original; - })); + transactions.execute(ignored -> { + var original = repository.begin(request); + admissionRepository.lockExactCurrentOpenSnapshot(qualified); + return original; + })); } public GetCanonicalGameplayRosterReferenceResponse read( @@ -231,12 +229,11 @@ public boolean retireTarget(GetCanonicalGameplayRosterReferenceRequest request) requireExactCurrentSnapshot(current, qualified); var recoveries = Objects.requireNonNull( - transactions.execute( - ignored -> { - repository.lockActiveTarget(request); - admissionRepository.lockExactCurrentOpenSnapshot(qualified); - return repository.beginRecoveries(request, current); - })); + transactions.execute(ignored -> { + repository.lockActiveTarget(request); + admissionRepository.lockExactCurrentOpenSnapshot(qualified); + return repository.beginRecoveries(request, current); + })); for (var recovery : recoveries) { try { var verified = recoveryClient.read(recovery); @@ -251,15 +248,14 @@ public boolean retireTarget(GetCanonicalGameplayRosterReferenceRequest request) } } return Boolean.TRUE.equals( - transactions.execute( - ignored -> { - repository.lockActiveTarget(request); - // This narrow local primitive locks and revalidates the actual pointer, terminal - // attempt, - // and catalog against the independently obtained snapshot. No suspended fence or RPC. - admissionRepository.lockExactCurrentOpenSnapshot(qualified); - return repository.sealTargetRetirement(request, current); - })); + transactions.execute(ignored -> { + repository.lockActiveTarget(request); + // This narrow local primitive locks and revalidates the actual pointer, terminal + // attempt, + // and catalog against the independently obtained snapshot. No suspended fence or RPC. + admissionRepository.lockExactCurrentOpenSnapshot(qualified); + return repository.sealTargetRetirement(request, current); + })); } private static String recoveryFailureKind(RuntimeException failure) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceRetentionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceRetentionService.java index cedee9799d..1ed288ffdc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceRetentionService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceRetentionService.java @@ -117,9 +117,8 @@ public synchronized void sweep() { try { int purged = Objects.requireNonNull( - transactions.execute( - ignored -> - repository.purgeConfirmedRetirementAcknowledgements(policy.batchSize()))); + transactions.execute(ignored -> + repository.purgeConfirmedRetirementAcknowledgements(policy.batchSize()))); metrics .counter( "firemud.canonical.roster.reference.transfer_cleanup", diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java index aec5373b07..e18b631222 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java @@ -99,10 +99,9 @@ public CanonicalPlayableTarget readCurrentTarget(UUID canonicalTenantId) { catalog = catalogRepository .readUniqueVisiblePublicProduction(targetNamespace, canonicalTenantId) - .orElseThrow( - () -> - new InvalidAuthorityException( - "Canonical public-production realm catalog is missing")); + .orElseThrow(() -> + new InvalidAuthorityException( + "Canonical public-production realm catalog is missing")); } catch (ReadUnavailableException | InvalidAuthorityException ex) { throw ex; } catch (DataAccessException ex) { @@ -150,10 +149,9 @@ private CanonicalPlayableTarget readTargetForCatalog(CanonicalRealmCatalogSnapsh catalog.tenantId(), catalog.realmId(), proof.canonicalGameInstanceId()) - .orElseThrow( - () -> - new InvalidAuthorityException( - "Canonical OPEN target has no owner-qualified launch association")); + .orElseThrow(() -> + new InvalidAuthorityException( + "Canonical OPEN target has no owner-qualified launch association")); } catch (DataAccessException ex) { throw new ReadUnavailableException("Canonical launch association read is unavailable", ex); } catch (InvalidAuthorityException | ReadUnavailableException ex) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java index 1fd447c38f..485904758b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPublishedPlayerRouteReadService.java @@ -384,10 +384,9 @@ private PublishedRealmEntryPolicyEvidence requirePublishedPreseededPolicy( var matches = complete.policies().stream() - .filter( - evidence -> - evidence.policy().worldSlug().equals(route.worldSlug()) - && evidence.policy().realmSlug().equals(route.realmSlug())) + .filter(evidence -> + evidence.policy().worldSlug().equals(route.worldSlug()) + && evidence.policy().realmSlug().equals(route.realmSlug())) .toList(); if (matches.size() != 1) { throw new InvalidAuthorityException("Published policy set lacks the exact current selector"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java index b805571c26..7851bda7bb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java @@ -129,13 +129,12 @@ private void deliverView( private void appendReplayableOutput( SessionContext recipient, PlayerOutput output, String rendered) { ReplayableScreenBufferEntries.fromRenderedOutput(output, outputProjector, rendered) - .ifPresent( - entry -> - screenBufferService.append( - recipient.tenantId(), - recipient.gameInstanceId(), - recipient.characterId(), - java.util.List.of(entry))); + .ifPresent(entry -> + screenBufferService.append( + recipient.tenantId(), + recipient.gameInstanceId(), + recipient.characterId(), + java.util.List.of(entry))); } private Optional resolveRecipient( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java index 331a4c61c5..aa5d687c45 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java @@ -161,10 +161,9 @@ private CanonicalLaunchPreparationSnapshot prepareInternal( CanonicalRealmCatalogSnapshot catalog = catalogRepository .readByRequest(workloadNamespace, request.catalogCreationRequestId()) - .orElseThrow( - () -> - new InvalidLaunchPreparationEvidenceException( - "Exact committed canonical realm catalog is missing")); + .orElseThrow(() -> + new InvalidLaunchPreparationEvidenceException( + "Exact committed canonical realm catalog is missing")); requireCatalogBinding(request, catalog); IntakeReceipt source = sourceRepository @@ -173,10 +172,9 @@ private CanonicalLaunchPreparationSnapshot prepareInternal( request.canonicalTenantId(), catalog.worldSlug(), workloadNamespace) - .orElseThrow( - () -> - new InvalidLaunchPreparationEvidenceException( - "Exact committed authored-world source intake is missing")); + .orElseThrow(() -> + new InvalidLaunchPreparationEvidenceException( + "Exact committed authored-world source intake is missing")); requireSourceBinding(request, catalog, source); AuthoredWorldLaunchDescriptorEvidence.Request descriptorRequest = @@ -199,19 +197,18 @@ private CanonicalLaunchPreparationSnapshot prepareInternal( } CanonicalLaunchPreparationSnapshot written = - ownerTransaction.execute( - status -> { - if (authorizedAttempt != null) { - AttemptSnapshot current = - Objects.requireNonNull(attemptRepository, "attempt repository is required") - .validateCurrentClaim(authorizedAttempt.claim()); - StartSessionPostAuthorizationExecutionTuple currentTuple = - validateAuthorizedAttempt(authorizedAttempt.claim(), request, current); - requireSameAuthorizedAttempt( - authorizedAttempt.snapshot(), authorizedAttempt.tuple(), current, currentTuple); - } - return preparationRepository.persistPrepared(request, catalog, source, readback); - }); + ownerTransaction.execute(status -> { + if (authorizedAttempt != null) { + AttemptSnapshot current = + Objects.requireNonNull(attemptRepository, "attempt repository is required") + .validateCurrentClaim(authorizedAttempt.claim()); + StartSessionPostAuthorizationExecutionTuple currentTuple = + validateAuthorizedAttempt(authorizedAttempt.claim(), request, current); + requireSameAuthorizedAttempt( + authorizedAttempt.snapshot(), authorizedAttempt.tuple(), current, currentTuple); + } + return preparationRepository.persistPrepared(request, catalog, source, readback); + }); if (written == null) { throw new InvalidLaunchPreparationEvidenceException( "Game Session owner transaction returned no launch preparation result"); @@ -338,10 +335,9 @@ public CompleteLaunchBindingEvidence readCompleteBinding( preparationRepository .readByControlPlaneRequestId( workloadNamespace, snapshot.request().controlPlaneRequestId()) - .orElseThrow( - () -> - new InvalidLaunchPreparationEvidenceException( - "Committed launch preparation is missing before complete binding read")); + .orElseThrow(() -> + new InvalidLaunchPreparationEvidenceException( + "Committed launch preparation is missing before complete binding read")); committed.requireValid(); if (!snapshot.equals(committed)) { throw new InvalidLaunchPreparationEvidenceException( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationService.java index d9f540580f..67c86f36ba 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationService.java @@ -81,20 +81,17 @@ public PinnedLaunchDescriptorSnapshot continueOriginalEvidence( } ContinuationPlan plan = - ownerTransaction.execute( - status -> { - EvidenceContinuation continuation = - attemptRepository.beginEvidenceContinuation(tuple); - PinnedAssociationSnapshot association = - associationRepository - .findPinned(continuation) - .orElseThrow( - () -> - new EvidenceContinuationUnavailableException( - "Original selection is missing; this attempt remains reconciliation-only")); - return new ContinuationPlan( - continuation, association, exactReplayRequest(association.result())); - }); + ownerTransaction.execute(status -> { + EvidenceContinuation continuation = attemptRepository.beginEvidenceContinuation(tuple); + PinnedAssociationSnapshot association = + associationRepository + .findPinned(continuation) + .orElseThrow(() -> + new EvidenceContinuationUnavailableException( + "Original selection is missing; this attempt remains reconciliation-only")); + return new ContinuationPlan( + continuation, association, exactReplayRequest(association.result())); + }); if (plan == null) { throw new IllegalStateException("StartSession continuation transaction returned no plan"); } @@ -118,18 +115,16 @@ public PinnedLaunchDescriptorSnapshot continueOriginalEvidence( requireSameAccountProjection(originalProjection, currentProjection); PinnedLaunchDescriptorSnapshot pinned = - ownerTransaction.execute( - status -> { - PinnedAssociationSnapshot current = - associationRepository - .findPinned(plan.continuation()) - .orElseThrow( - () -> - new EvidenceContinuationUnavailableException( - "Original selection disappeared during descriptor resolution")); - requireSameSelection(plan.association(), current); - return descriptorRepository.pin(plan.continuation(), resolved); - }); + ownerTransaction.execute(status -> { + PinnedAssociationSnapshot current = + associationRepository + .findPinned(plan.continuation()) + .orElseThrow(() -> + new EvidenceContinuationUnavailableException( + "Original selection disappeared during descriptor resolution")); + requireSameSelection(plan.association(), current); + return descriptorRepository.pin(plan.continuation(), resolved); + }); if (pinned == null) { throw new IllegalStateException("StartSession descriptor pin transaction returned no result"); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java index 1b32f2ef81..442e36397f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinator.java @@ -109,12 +109,11 @@ public AuthorizationResult authorize( AccountRedemptionProjection projection = redemption.projection(); AttemptSnapshot attached = - ownerTransaction.execute( - status -> { - AttemptSnapshot current = attemptRepository.validateCurrentClaim(claim); - requireSameCurrentAttempt(reservation.snapshot(), current, claim, tuple); - return attemptRepository.attachAccountRedemptionProjection(claim, projection); - }); + ownerTransaction.execute(status -> { + AttemptSnapshot current = attemptRepository.validateCurrentClaim(claim); + requireSameCurrentAttempt(reservation.snapshot(), current, claim, tuple); + return attemptRepository.attachAccountRedemptionProjection(claim, projection); + }); if (attached == null) { throw new IllegalStateException("Account projection attachment returned no owner snapshot"); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java index b60b27053a..a3d95cc5fe 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java @@ -86,27 +86,26 @@ public static SessionContext repairGenericBootstrapShell( return clearGenericBootstrapRouting(normalizedShell); } return singularCompletePointer(filteredRuntimePointers) - .map( - pointer -> - new SessionContext( - normalizedShell.sessionId(), - normalizedShell.tenantId(), - normalizedShell.accountId(), - normalizedShell.loginName(), - normalizedShell.characterId(), - normalizedShell.characterName(), - normalizedShell.gameInstanceId(), - normalizedShell.roomInstanceId(), - normalizedShell.jwt(), - normalizedShell.localeTag(), - normalizedShell.bootstrapGameInstanceId(), - pointer.worldSlug(), - pointer.realmSlug(), - pointer.pointerVersion(), - pointer.stateScope(), - normalizedShell.connectScopeId(), - normalizedShell.connectRequestId(), - normalizedShell.firstPartyConnectContext())) + .map(pointer -> + new SessionContext( + normalizedShell.sessionId(), + normalizedShell.tenantId(), + normalizedShell.accountId(), + normalizedShell.loginName(), + normalizedShell.characterId(), + normalizedShell.characterName(), + normalizedShell.gameInstanceId(), + normalizedShell.roomInstanceId(), + normalizedShell.jwt(), + normalizedShell.localeTag(), + normalizedShell.bootstrapGameInstanceId(), + pointer.worldSlug(), + pointer.realmSlug(), + pointer.pointerVersion(), + pointer.stateScope(), + normalizedShell.connectScopeId(), + normalizedShell.connectRequestId(), + normalizedShell.firstPartyConnectContext())) .orElse(clearGenericBootstrapRouting(normalizedShell)); } @@ -189,16 +188,15 @@ public static boolean matchesCurrentRuntimeTarget( String realmSlug, long pointerVersion) { return singularCompletePointer(pointers) - .map( - pointer -> - matchesCurrentRuntimeTarget( - List.of(pointer), - tenantId, - gameInstanceId, - worldSlug, - realmSlug, - pointerVersion, - pointer.stateScope())) + .map(pointer -> + matchesCurrentRuntimeTarget( + List.of(pointer), + tenantId, + gameInstanceId, + worldSlug, + realmSlug, + pointerVersion, + pointer.stateScope())) .orElse(false); } @@ -223,9 +221,8 @@ public static boolean matchesCurrentRuntimeTarget( return singularCompletePointer(pointers) .filter(pointer -> pointer.tenantId() == tenantId) .filter(pointer -> pointer.gameInstanceId() == gameInstanceId) - .filter( - pointer -> - sameRoutingIdentity(pointer.worldSlug(), pointer.realmSlug(), worldSlug, realmSlug)) + .filter(pointer -> + sameRoutingIdentity(pointer.worldSlug(), pointer.realmSlug(), worldSlug, realmSlug)) .filter(pointer -> pointer.pointerVersion() == pointerVersion) .filter( pointer -> normalizedPlayableStateScope.equals(normalizeScope(pointer.stateScope()))) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwner.java index 5dca04bfae..9faae5d6ba 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwner.java @@ -165,14 +165,13 @@ private static void requireReceipt( || !coordinates.callerContextId().equals(receipt.callerContextId())) { throw new JournalConflictException(); } - previous.ifPresent( - value -> { - if (!value.disposalOperationId().equals(receipt.disposalOperationId()) - || value.disposition() != InitialGameplayLoginDisposalResult.Disposition.PENDING - && !value.equals(receipt)) { - throw new JournalConflictException(); - } - }); + previous.ifPresent(value -> { + if (!value.disposalOperationId().equals(receipt.disposalOperationId()) + || value.disposition() != InitialGameplayLoginDisposalResult.Disposition.PENDING + && !value.equals(receipt)) { + throw new JournalConflictException(); + } + }); } private static void requireNoTransaction() { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java index 7ba5b8c1ff..b03adba0b5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyOwner.java @@ -129,9 +129,8 @@ public Observation join( custody, transport -> Boolean.TRUE.equals( - transaction.execute( - status -> - repository.claimDispatch(committed, verified, transport, clock)))); + transaction.execute(status -> + repository.claimDispatch(committed, verified, transport, clock)))); if (!claimed) return observe(committed, original, verified, custody); // An ambiguous claim COMMIT/readback throws before Account. The persisted possible state is @@ -146,12 +145,10 @@ public Observation join( custody, transport -> { possible.scope().requireCurrent(original, verified, transport, clock); - transaction.executeWithoutResult( - status -> { - var selected = repository.current(original, verified, transport, clock); - if (!selected.recordId().equals(possible.scope().recordId())) - throw unavailable(); - }); + transaction.executeWithoutResult(status -> { + var selected = repository.current(original, verified, transport, clock); + if (!selected.recordId().equals(possible.scope().recordId())) throw unavailable(); + }); var request = possible.request(); return account.joinPublicProductionMembership( request.getPlayerContext(), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java index 15090faf99..fb76cc12d6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java @@ -220,16 +220,15 @@ private boolean isCurrentPresence( return false; } return currentRuntimePointer(tenantId, presence.gameInstanceId(), currentRuntimePointers) - .map( - pointer -> - GameplayAdmissionPointerSnapshots.matchesCurrentRuntimeTarget( - List.of(pointer), - tenantId, - presence.gameInstanceId(), - routingBundle.worldSlug(), - routingBundle.realmSlug(), - routingBundle.pointerVersion(), - presence.playableStateScope())) + .map(pointer -> + GameplayAdmissionPointerSnapshots.matchesCurrentRuntimeTarget( + List.of(pointer), + tenantId, + presence.gameInstanceId(), + routingBundle.worldSlug(), + routingBundle.realmSlug(), + routingBundle.pointerVersion(), + presence.playableStateScope())) .orElse(false); } @@ -293,16 +292,15 @@ private GameplayAdmissionPointerSnapshot matchingCurrentRuntimePointer( } return currentRuntimePointer( recentState.tenantId(), recentState.gameInstanceId(), currentRuntimePointers) - .filter( - pointer -> - GameplayAdmissionPointerSnapshots.matchesCurrentRuntimeTarget( - List.of(pointer), - recentState.tenantId(), - recentState.gameInstanceId(), - routingBundle.worldSlug(), - routingBundle.realmSlug(), - routingBundle.pointerVersion(), - recentState.playableStateScope())) + .filter(pointer -> + GameplayAdmissionPointerSnapshots.matchesCurrentRuntimeTarget( + List.of(pointer), + recentState.tenantId(), + recentState.gameInstanceId(), + routingBundle.worldSlug(), + routingBundle.realmSlug(), + routingBundle.pointerVersion(), + recentState.playableStateScope())) .orElse(null); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisher.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisher.java index 5c364e5d2d..4e712fa14e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisher.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisher.java @@ -107,144 +107,139 @@ public AutomationScriptEventPublisher( @Override public void publishCommandEvent(SessionContext context, GameplayCommand command) { - submitBestEffort( - () -> { - PublishingScope scope = resolvePublishingScope(context, command); - if (scope == null) { - return; - } - TriggerScriptEventRequest request = - TriggerScriptEventRequestFactory.builder( - new TriggerScriptEventRequestFactory.CommonFields( - scope.tenantId(), - scope.gameInstanceId(), - scope.regionId(), - scope.regionEpoch(), - scope.entityId(), - "onCommand", - "v1", - scope.scriptPatchVersion(), - scope.scriptPatchBaseVersionId(), - scope.scriptPinEpoch(), - scope.scriptPinControlPlaneRequestId(), - command.getCommandId(), - false, - TriggerMode.TRIGGER_MODE_NORMAL, - scope.playableStateScope(), - "game-session:onCommand:" - + scope.gameInstanceId() - + ":" - + scope.regionEpoch() - + ":" - + command.getCommandId(), - commandPayload(context, command)), - scope.routingBundle()) - .build(); - logIfNotAdmitted( - client.triggerScriptEvent(request), - "onCommand", - scope.gameInstanceId(), - command.getCommandId()); - }); + submitBestEffort(() -> { + PublishingScope scope = resolvePublishingScope(context, command); + if (scope == null) { + return; + } + TriggerScriptEventRequest request = + TriggerScriptEventRequestFactory.builder( + new TriggerScriptEventRequestFactory.CommonFields( + scope.tenantId(), + scope.gameInstanceId(), + scope.regionId(), + scope.regionEpoch(), + scope.entityId(), + "onCommand", + "v1", + scope.scriptPatchVersion(), + scope.scriptPatchBaseVersionId(), + scope.scriptPinEpoch(), + scope.scriptPinControlPlaneRequestId(), + command.getCommandId(), + false, + TriggerMode.TRIGGER_MODE_NORMAL, + scope.playableStateScope(), + "game-session:onCommand:" + + scope.gameInstanceId() + + ":" + + scope.regionEpoch() + + ":" + + command.getCommandId(), + commandPayload(context, command)), + scope.routingBundle()) + .build(); + logIfNotAdmitted( + client.triggerScriptEvent(request), + "onCommand", + scope.gameInstanceId(), + command.getCommandId()); + }); } @Override public void publishSpawnEvent(SessionContext context, String spawnReason, String scriptEventId) { - submitBestEffort( - () -> { - if (!StringUtils.hasText(scriptEventId)) { - return; - } - PublishingScope scope = resolvePublishingScope(context); - if (scope == null) { - return; - } - publishLifecycleEvent( - scope, - "onSpawn", - scriptEventId, - "game-session:onSpawn:" - + scope.gameInstanceId() - + ":" - + scope.regionEpoch() - + ":" - + scriptEventId, - spawnPayload(spawnReason)); - }); + submitBestEffort(() -> { + if (!StringUtils.hasText(scriptEventId)) { + return; + } + PublishingScope scope = resolvePublishingScope(context); + if (scope == null) { + return; + } + publishLifecycleEvent( + scope, + "onSpawn", + scriptEventId, + "game-session:onSpawn:" + + scope.gameInstanceId() + + ":" + + scope.regionEpoch() + + ":" + + scriptEventId, + spawnPayload(spawnReason)); + }); } @Override public void publishRegionTransitionEvents( SessionContext previousContext, SessionContext currentContext, String effectId) { - submitBestEffort( - () -> { - if (previousContext == null || currentContext == null || !StringUtils.hasText(effectId)) { - return; - } - PublishingScope scope = resolvePublishingScope(currentContext); - if (scope == null) { - return; - } - String previousRoomId = canonicalPayloadRoomId(previousContext.roomInstanceId()); - String currentRoomId = canonicalPayloadRoomId(currentContext.roomInstanceId()); - if (!StringUtils.hasText(previousRoomId) - || !StringUtils.hasText(currentRoomId) - || previousRoomId.equals(currentRoomId)) { - return; - } - String payload = regionTransitionPayload(previousRoomId, currentRoomId); - publishRegionTransitionEvent(scope, effectId, "leave", "onLeaveRegion", payload); - publishRegionTransitionEvent(scope, effectId, "enter", "onEnterRegion", payload); - }); + submitBestEffort(() -> { + if (previousContext == null || currentContext == null || !StringUtils.hasText(effectId)) { + return; + } + PublishingScope scope = resolvePublishingScope(currentContext); + if (scope == null) { + return; + } + String previousRoomId = canonicalPayloadRoomId(previousContext.roomInstanceId()); + String currentRoomId = canonicalPayloadRoomId(currentContext.roomInstanceId()); + if (!StringUtils.hasText(previousRoomId) + || !StringUtils.hasText(currentRoomId) + || previousRoomId.equals(currentRoomId)) { + return; + } + String payload = regionTransitionPayload(previousRoomId, currentRoomId); + publishRegionTransitionEvent(scope, effectId, "leave", "onLeaveRegion", payload); + publishRegionTransitionEvent(scope, effectId, "enter", "onEnterRegion", payload); + }); } private void publishRegionTransitionEvent( PublishingScope scope, String effectId, String transition, String eventType, String payload) { - runBestEffort( - () -> - publishLifecycleEvent( - scope, - eventType, - effectId + ":" + transition, - "game-session:" - + eventType - + ":" - + scope.gameInstanceId() - + ":" - + scope.regionEpoch() - + ":" - + effectId, - payload)); + runBestEffort(() -> + publishLifecycleEvent( + scope, + eventType, + effectId + ":" + transition, + "game-session:" + + eventType + + ":" + + scope.gameInstanceId() + + ":" + + scope.regionEpoch() + + ":" + + effectId, + payload)); } @Override public void publishRegionExitEvent( SessionContext context, String scriptEventId, String exitReason) { - submitBestEffort( - () -> { - if (context == null || !StringUtils.hasText(scriptEventId)) { - return; - } - PublishingScope scope = resolvePublishingScope(context); - if (scope == null) { - return; - } - String previousRoomId = canonicalPayloadRoomId(context.roomInstanceId()); - if (!StringUtils.hasText(previousRoomId)) { - return; - } - publishLifecycleEvent( - scope, - "onLeaveRegion", - scriptEventId, - "game-session:onLeaveRegion:" - + scope.gameInstanceId() - + ":" - + scope.regionEpoch() - + ":" - + scriptEventId, - regionExitPayload(previousRoomId, exitReason)); - }); + submitBestEffort(() -> { + if (context == null || !StringUtils.hasText(scriptEventId)) { + return; + } + PublishingScope scope = resolvePublishingScope(context); + if (scope == null) { + return; + } + String previousRoomId = canonicalPayloadRoomId(context.roomInstanceId()); + if (!StringUtils.hasText(previousRoomId)) { + return; + } + publishLifecycleEvent( + scope, + "onLeaveRegion", + scriptEventId, + "game-session:onLeaveRegion:" + + scope.gameInstanceId() + + ":" + + scope.regionEpoch() + + ":" + + scriptEventId, + regionExitPayload(previousRoomId, exitReason)); + }); } private String commandPayload(SessionContext context, GameplayCommand command) { @@ -264,14 +259,13 @@ private String commandPayload(SessionContext context, GameplayCommand command) { .ifPresent( alias -> payload.append(",\"commandAlias\":\"").append(escape(alias)).append("\"")); resolveCommandMetadata(context, command) - .ifPresent( - metadata -> { - payload - .append(",\"actionCategory\":\"") - .append(metadata.actionCategory().name()) - .append("\",\"actionTags\":") - .append(actionTagsJson(metadata.actionTags())); - }); + .ifPresent(metadata -> { + payload + .append(",\"actionCategory\":\"") + .append(metadata.actionCategory().name()) + .append("\",\"actionTags\":") + .append(actionTagsJson(metadata.actionTags())); + }); return payload.append("}").toString(); } @@ -288,10 +282,9 @@ private Optional resolveCommandMetadata( } return textCommandMetadataResolver .resolve(command.getCommandName()) - .or( - () -> - textCommandMetadataResolver.resolve( - firstCommandToken(command.getCommandText()).orElse(null))); + .or(() -> + textCommandMetadataResolver.resolve( + firstCommandToken(command.getCommandText()).orElse(null))); } private Optional resolveBuiltInCommandAlias(GameplayCommand command) { @@ -500,13 +493,12 @@ private Optional resolveCurrentRegionScope( long tenantId, long gameInstanceId) { return runtimeRegionStatusRepository .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) - .map( - ownership -> - new PublishedRegionScope( - StringUtils.hasText(ownership.getRegionId()) - ? ownership.getRegionId() - : Long.toString(gameInstanceId), - ownership.getRegionEpoch())); + .map(ownership -> + new PublishedRegionScope( + StringUtils.hasText(ownership.getRegionId()) + ? ownership.getRegionId() + : Long.toString(gameInstanceId), + ownership.getRegionEpoch())); } private Optional resolvePublishedRegionScope(GameplayCommand command) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java index 5a9188b515..e71e8c6216 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayAdmissionDecisionReadGrpcService.java @@ -334,10 +334,9 @@ private CanonicalInitialAdmissionLaunchTarget readCurrentLaunch(CanonicalPlayabl route.canonicalTenantId(), route.realmId(), route.canonicalGameInstanceId()) - .orElseThrow( - () -> - new CanonicalPublishedPlayerRouteReadService.StaleAuthorityException( - "Current launch source is absent")); + .orElseThrow(() -> + new CanonicalPublishedPlayerRouteReadService.StaleAuthorityException( + "Current launch source is absent")); var association = launch.association(); if (!workloadNamespace.equals(association.targetNamespace()) || !route.canonicalTenantId().equals(association.canonicalTenantId()) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java index 5e3f2d9ce7..570d395ddb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java @@ -212,11 +212,10 @@ private GameplayCommand persistAcceptedCommand( sessionContext .map(SessionContext::characterId) .filter(id -> id > 0) - .ifPresent( - characterId -> { - gameplayCommand.setCharacterId(characterId); - gameplayCommand.setTargetEntityId(Long.toString(characterId)); - }); + .ifPresent(characterId -> { + gameplayCommand.setCharacterId(characterId); + gameplayCommand.setTargetEntityId(Long.toString(characterId)); + }); gameplayCommand.setCommandName(commandName(command)); if (authoredAdmission != null) { gameplayCommand.setCommandName(authoredAdmission.commandId()); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CurrentPrivatePlaytestLifecycleReadGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CurrentPrivatePlaytestLifecycleReadGrpcService.java index e02ed9fadf..526ef41f18 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CurrentPrivatePlaytestLifecycleReadGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CurrentPrivatePlaytestLifecycleReadGrpcService.java @@ -108,13 +108,12 @@ public void readCurrentPrivatePlaytestLifecycle( final Optional current; try { current = - ownerReadTransaction.execute( - status -> - repository.readCurrent( - selector.scope().targetNamespace(), - selector.scope().tenantId(), - selector.scope().worldSlug(), - selector.scope().realmSlug())); + ownerReadTransaction.execute(status -> + repository.readCurrent( + selector.scope().targetNamespace(), + selector.scope().tenantId(), + selector.scope().worldSlug(), + selector.scope().realmSlug())); if (current == null) { throw new IllegalStateException("Current private-playtest owner returned no result"); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java index 86e4582ed5..cebf7e7f23 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java @@ -61,10 +61,9 @@ private CanonicalInitialAdmissionOwnerProof requireRead( String targetNamespace, String requestId) { return repository .read(targetNamespace, requestId) - .orElseThrow( - () -> - new CanonicalInitialAdmissionRepository - .CanonicalInitialAdmissionReconciliationRequiredException( - "Initial-admission attempt has no durable owner result")); + .orElseThrow(() -> + new CanonicalInitialAdmissionRepository + .CanonicalInitialAdmissionReconciliationRequiredException( + "Initial-admission attempt has no durable owner result")); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java index ee2fecfdb9..0dbdf2c3c8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java @@ -46,21 +46,20 @@ public DatabaseGameplayCommandRecoveryService( @EventListener(ApplicationReadyEvent.class) public void convergeAcceptedButUnstagedCommandsOnStartup() { Instant acceptedBefore = Instant.now(); - gameplayCommandRecoveryExecutor.execute( - () -> { - try { - int recovered = convergeAcceptedButUnstagedCommands(acceptedBefore); - if (recovered > 0) { - logger.warn( - "Re-enqueued {} accepted gameplay command(s) that were not staged before startup", - recovered); - } - } catch (RuntimeException ex) { - logger.error( - "Unable to complete accepted gameplay command startup recovery; remaining commands stay retryable", - ex); - } - }); + gameplayCommandRecoveryExecutor.execute(() -> { + try { + int recovered = convergeAcceptedButUnstagedCommands(acceptedBefore); + if (recovered > 0) { + logger.warn( + "Re-enqueued {} accepted gameplay command(s) that were not staged before startup", + recovered); + } + } catch (RuntimeException ex) { + logger.error( + "Unable to complete accepted gameplay command startup recovery; remaining commands stay retryable", + ex); + } + }); } @Override diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java index 55758189af..84a8c1d7c5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java @@ -91,10 +91,9 @@ public InitialAdmissionBindAttempt beginIntent(InitialAdmissionBindRequest reque catalogRepository .findByTenantIdAndSelectors( request.tenantId(), request.worldSlug(), request.realmSlug()) - .orElseThrow( - () -> - new IllegalArgumentException( - "INITIAL_ADMISSION_CATALOG_NOT_FOUND: owner catalog row is missing")); + .orElseThrow(() -> + new IllegalArgumentException( + "INITIAL_ADMISSION_CATALOG_NOT_FOUND: owner catalog row is missing")); attemptRepository.lockAttemptAndRealm( request.tenantId(), request.initialAdmissionRequestId(), catalog.realmId()); @@ -392,10 +391,9 @@ private InitialAdmissionBindCatalog requireCatalogForAttempt( InitialAdmissionBindCatalog catalog = catalogRepository .findByTenantId(attempt.tenantId()) - .orElseThrow( - () -> - new IllegalStateException( - "INITIAL_ADMISSION_CATALOG_MISSING: durable attempt lost its owner catalog")); + .orElseThrow(() -> + new IllegalStateException( + "INITIAL_ADMISSION_CATALOG_MISSING: durable attempt lost its owner catalog")); if (!catalog.realmId().equals(attempt.realmId()) || !catalog.playableStateNamespaceId().equals(attempt.playableStateNamespaceId()) || catalog.catalogRevision() != attempt.catalogRevision() @@ -430,10 +428,9 @@ private void requireAttachedHold( private InitialAdmissionBindAttempt requireAttemptForUpdate(long tenantId, String requestId) { return attemptRepository .findByTenantAndRequestIdForUpdate(tenantId, requestId) - .orElseThrow( - () -> - new IllegalStateException( - "INITIAL_ADMISSION_INTENT_NOT_FOUND: durable GS intent is required first")); + .orElseThrow(() -> + new IllegalStateException( + "INITIAL_ADMISSION_INTENT_NOT_FOUND: durable GS intent is required first")); } private void requireSameCatalog( @@ -501,10 +498,9 @@ private void requireTargetMatchesCatalogAndRequest( GameInstance gameInstance = gameInstanceRepository .findByTenantIdAndGameInstanceIdForUpdate(request.tenantId(), request.gameInstanceId()) - .orElseThrow( - () -> - new IllegalArgumentException( - "GAME_INSTANCE_NOT_FOUND: initial admission target is not GS-owned")); + .orElseThrow(() -> + new IllegalArgumentException( + "GAME_INSTANCE_NOT_FOUND: initial admission target is not GS-owned")); if (!Objects.equals(gameInstance.getGameTemplateId(), catalog.gameTemplateId()) || !Objects.equals(gameInstance.getVersionId(), request.versionId())) { throw new IllegalArgumentException( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java index bdd527a7f1..c1a87ceb3f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleService.java @@ -66,10 +66,9 @@ public void recordDisconnected(long sessionId, AccountRecentPresenceDisposition sessionRoutingNormalizationService .resolveProjectedSessionContext(Long.toString(sessionId)) .filter(SessionContext::hasGameplayRegionBindingOrFalse) - .ifPresent( - context -> - scriptEventPublisher.publishRegionExitEvent( - context, disconnectEventId(context, disposition), disposition.name())); + .ifPresent(context -> + scriptEventPublisher.publishRegionExitEvent( + context, disconnectEventId(context, disposition), disposition.name())); } accountRecentPresenceService.recordDisconnect(sessionId, disposition); gameplayPresenceService.removeBySessionId(sessionId); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameAuthoredHelpReaderImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameAuthoredHelpReaderImpl.java index 263249153f..62c6ba9626 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameAuthoredHelpReaderImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameAuthoredHelpReaderImpl.java @@ -32,9 +32,8 @@ public Optional resolve(SessionContext context, String topic) { .filter(instance -> matchesAdmittedRuntime(context, instance)) .map(GameInstance::getGameTemplateId) .filter(templateId -> templateId != null && templateId > 0L) - .flatMap( - templateId -> - gameDesignClient.resolveAuthoredHelpTopic(context.tenantId(), templateId, topic)); + .flatMap(templateId -> + gameDesignClient.resolveAuthoredHelpTopic(context.tenantId(), templateId, topic)); } private boolean matchesAdmittedRuntime(SessionContext context, GameInstance instance) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java index 62844772ac..1aea70d4de 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java @@ -925,10 +925,9 @@ private GameInstance recordRunOwnedPreparingEpoch( GameInstance instance = repository .findByTenantIdAndGameInstanceIdForUpdate(request.tenantId(), gameInstanceId) - .orElseThrow( - () -> - new IllegalStateException( - "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_UNAVAILABLE: instance row is missing")); + .orElseThrow(() -> + new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_UNAVAILABLE: instance row is missing")); requireSameRunOwnedInitialLaunch(instance, request, descriptor, requestDigest); Long recordedEpoch = instance.getRunOwnedStartPreparingEpoch(); if (recordedEpoch != null) { @@ -956,10 +955,9 @@ private GameInstance reloadRunOwnedInitialLaunch( GameInstance instance = repository .findByTenantIdAndGameInstanceIdForUpdate(request.tenantId(), gameInstanceId) - .orElseThrow( - () -> - new IllegalStateException( - "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_UNAVAILABLE: instance row is missing")); + .orElseThrow(() -> + new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_UNAVAILABLE: instance row is missing")); requireSameRunOwnedInitialLaunch(instance, request, descriptor, requestDigest); return instance; }, @@ -975,10 +973,9 @@ private GameInstance completeRunOwnedInitialLaunch( GameInstance instance = repository .findByTenantIdAndGameInstanceIdForUpdate(request.tenantId(), gameInstanceId) - .orElseThrow( - () -> - new IllegalStateException( - "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_UNAVAILABLE: instance row is missing")); + .orElseThrow(() -> + new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_UNAVAILABLE: instance row is missing")); requireSameRunOwnedInitialLaunch(instance, request, descriptor, requestDigest); long expectedActiveEpoch = Math.addExact(requireRunOwnedPreparingEpoch(instance), 1L); if (activeEpoch != expectedActiveEpoch) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java index 6a7e1ab8ca..aef47cfe36 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java @@ -47,42 +47,38 @@ ListAdmissionPointersResponse listAdmissionPointers(List requestedTenantId .toList(); List auditKeys = pointers.stream() - .map( - pointer -> - new PointerAuditKey( - pointer.tenantId(), pointer.worldSlug(), pointer.realmSlug())) + .map(pointer -> + new PointerAuditKey(pointer.tenantId(), pointer.worldSlug(), pointer.realmSlug())) .distinct() .toList(); Map latestAudits = gameplayAdmissionPointerAuthorityService.findLatestPointerAudits(auditKeys); List entries = pointers.stream() - .map( - pointer -> { - PointerAuditKey key = - new PointerAuditKey( - pointer.tenantId(), pointer.worldSlug(), pointer.realmSlug()); - GameplayAdmissionPointerAuditEntry latestAudit = latestAudits.get(key); - if (latestAudit == null) { - throw new AdmissionPointerAuditUnavailableException( - "Admission pointer audit unavailable for current pointer " - + pointer.tenantId() - + ":" - + pointer.worldSlug() - + "/" - + pointer.realmSlug()); - } - if (!matchesCurrentPointer(pointer, latestAudit)) { - throw new AdmissionPointerAuditUnavailableException( - "Admission pointer audit does not match current pointer " - + pointer.tenantId() - + ":" - + pointer.worldSlug() - + "/" - + pointer.realmSlug()); - } - return toEntry(latestAudit); - }) + .map(pointer -> { + PointerAuditKey key = + new PointerAuditKey(pointer.tenantId(), pointer.worldSlug(), pointer.realmSlug()); + GameplayAdmissionPointerAuditEntry latestAudit = latestAudits.get(key); + if (latestAudit == null) { + throw new AdmissionPointerAuditUnavailableException( + "Admission pointer audit unavailable for current pointer " + + pointer.tenantId() + + ":" + + pointer.worldSlug() + + "/" + + pointer.realmSlug()); + } + if (!matchesCurrentPointer(pointer, latestAudit)) { + throw new AdmissionPointerAuditUnavailableException( + "Admission pointer audit does not match current pointer " + + pointer.tenantId() + + ":" + + pointer.worldSlug() + + "/" + + pointer.realmSlug()); + } + return toEntry(latestAudit); + }) .toList(); return ListAdmissionPointersResponse.newBuilder().addAllPointers(entries).build(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAuthoredActorCoreRetentionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAuthoredActorCoreRetentionService.java index 8461a029cb..cd09e0c1ff 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAuthoredActorCoreRetentionService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAuthoredActorCoreRetentionService.java @@ -100,10 +100,9 @@ public StoredSource retain( OriginalStartSessionAssociation originalLaunch = launches .readOriginalStartSessionAssociation(historicalRequest.associationSelector()) - .orElseThrow( - () -> - new IllegalStateException( - "Exact actual Game Session launch association is unavailable")); + .orElseThrow(() -> + new IllegalStateException( + "Exact actual Game Session launch association is unavailable")); requireLaunchMatchesHistorical(originalLaunch, historical, currentAttemptRequest); CanonicalGameInstanceLaunchAssociation launch = originalLaunch.association(); @@ -117,13 +116,12 @@ public StoredSource retain( candidate(launch, historical, firstAttempt, sourceReadRequestBytes, source); StoredSource committed = - retentionTransaction.execute( - status -> { - AttemptSnapshot finalAttempt = - readCurrentAttemptInOwnerTransaction(currentAttemptRequest); - requireSameLiveAttempt(firstAttempt, finalAttempt); - return retention.retainInOwnerTransaction(candidate); - }); + retentionTransaction.execute(status -> { + AttemptSnapshot finalAttempt = + readCurrentAttemptInOwnerTransaction(currentAttemptRequest); + requireSameLiveAttempt(firstAttempt, finalAttempt); + return retention.retainInOwnerTransaction(candidate); + }); if (committed == null) { throw new IllegalStateException("Authored-core retention transaction returned no row"); } @@ -131,10 +129,9 @@ public StoredSource retain( StoredSource independentReadback = retention .readByOriginalOperation(workloadNamespace, requestId) - .orElseThrow( - () -> - new IllegalStateException( - "Committed authored-core source retention is unavailable on independent readback")); + .orElseThrow(() -> + new IllegalStateException( + "Committed authored-core source retention is unavailable on independent readback")); requireSameStoredSource(candidate, committed, independentReadback); return independentReadback; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionCommandControlPlaneService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionCommandControlPlaneService.java index fa20fab5bb..e3d481004b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionCommandControlPlaneService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionCommandControlPlaneService.java @@ -174,12 +174,11 @@ public ValidateBuiltInCommandAliasResponse validateBuiltInCommandAlias( } return builtInTextCommandAliasResolver .resolve(alias) - .map( - normalized -> - ValidateBuiltInCommandAliasResponse.newBuilder() - .setSupported(true) - .setNormalizedAlias(normalized) - .build()) + .map(normalized -> + ValidateBuiltInCommandAliasResponse.newBuilder() + .setSupported(true) + .setNormalizedAlias(normalized) + .build()) .orElseGet(() -> ValidateBuiltInCommandAliasResponse.newBuilder().build()); } @@ -194,14 +193,13 @@ private EnqueueAutomationCommandIfAbsentResponse enqueueAutomationCommand( AutomationGameplayCommandAdmissionSupport.AdmissionRequest admissionRequest = toAutomationAdmissionRequest(request); AutomationGameplayCommandAdmissionSupport.DurableAdmission durableAdmission = - transactionOperations.execute( - status -> - AutomationGameplayCommandAdmissionSupport.admitIfAbsentDurably( - admissionRequest, - gameInstanceRepository, - gameplayCommandRepository, - runtimeRegionStatusRepository, - gameplayAdmissionPointerAuthorityService)); + transactionOperations.execute(status -> + AutomationGameplayCommandAdmissionSupport.admitIfAbsentDurably( + admissionRequest, + gameInstanceRepository, + gameplayCommandRepository, + runtimeRegionStatusRepository, + gameplayAdmissionPointerAuthorityService)); if (durableAdmission == null) { throw new IllegalStateException( "Gameplay command admission transaction returned no admission result"); @@ -603,16 +601,13 @@ private RemoteFollowupResultEntry toRemoteFollowupResultEntry( gameplayCommandRepository .findByTenantIdAndGameInstanceIdAndCommandId( result.getTenantId(), result.getTargetGameInstanceId(), resultCommandId) - .filter( - candidate -> - Objects.equals(candidate.getTenantId(), result.getTenantId()) - && Objects.equals( - candidate.getGameInstanceId(), result.getTargetGameInstanceId()) - && Objects.equals(candidate.getRegionId(), result.getTargetRegionId()) - && Objects.equals( - candidate.getRegionEpoch(), result.getTargetRegionEpoch()) - && Objects.equals( - candidate.getRemoteFollowupId(), result.getFollowupId())) + .filter(candidate -> + Objects.equals(candidate.getTenantId(), result.getTenantId()) + && Objects.equals( + candidate.getGameInstanceId(), result.getTargetGameInstanceId()) + && Objects.equals(candidate.getRegionId(), result.getTargetRegionId()) + && Objects.equals(candidate.getRegionEpoch(), result.getTargetRegionEpoch()) + && Objects.equals(candidate.getRemoteFollowupId(), result.getFollowupId())) .orElse(null); } if (targetCommand != null && targetCommand.getCommandId() != null) { @@ -660,19 +655,18 @@ private void applyCurrentRuntimeScope( long gameInstanceId, boolean originScope) { currentRuntimeBoundary(tenantId, gameInstanceId) - .ifPresent( - currentBoundary -> { - CurrentRuntimeScopeFieldEmitter.applyCurrentRuntimeScopeFields( - currentBoundary.gameInstanceId(), - currentBoundary.regionId(), - currentBoundary.regionEpoch(), - currentBoundary.playableStateScope(), - currentBoundary.worldSlug(), - currentBoundary.realmSlug(), - currentBoundary.pointerVersion(), - originScope, - CurrentRuntimeScopeFieldEmitter.writerFor(builder)); - }); + .ifPresent(currentBoundary -> { + CurrentRuntimeScopeFieldEmitter.applyCurrentRuntimeScopeFields( + currentBoundary.gameInstanceId(), + currentBoundary.regionId(), + currentBoundary.regionEpoch(), + currentBoundary.playableStateScope(), + currentBoundary.worldSlug(), + currentBoundary.realmSlug(), + currentBoundary.pointerVersion(), + originScope, + CurrentRuntimeScopeFieldEmitter.writerFor(builder)); + }); } private void applyCurrentRuntimeScope( @@ -681,19 +675,18 @@ private void applyCurrentRuntimeScope( long gameInstanceId, boolean originScope) { currentRuntimeBoundary(tenantId, gameInstanceId) - .ifPresent( - currentBoundary -> { - CurrentRuntimeScopeFieldEmitter.applyCurrentRuntimeScopeFields( - currentBoundary.gameInstanceId(), - currentBoundary.regionId(), - currentBoundary.regionEpoch(), - currentBoundary.playableStateScope(), - currentBoundary.worldSlug(), - currentBoundary.realmSlug(), - currentBoundary.pointerVersion(), - originScope, - CurrentRuntimeScopeFieldEmitter.writerFor(builder)); - }); + .ifPresent(currentBoundary -> { + CurrentRuntimeScopeFieldEmitter.applyCurrentRuntimeScopeFields( + currentBoundary.gameInstanceId(), + currentBoundary.regionId(), + currentBoundary.regionEpoch(), + currentBoundary.playableStateScope(), + currentBoundary.worldSlug(), + currentBoundary.realmSlug(), + currentBoundary.pointerVersion(), + originScope, + CurrentRuntimeScopeFieldEmitter.writerFor(builder)); + }); } private void applyCurrentRuntimeScope( @@ -702,48 +695,44 @@ private void applyCurrentRuntimeScope( long gameInstanceId, boolean originScope) { currentRuntimeBoundary(tenantId, gameInstanceId) - .ifPresent( - currentBoundary -> { - CurrentRuntimeScopeFieldEmitter.applyCurrentRuntimeScopeFields( - currentBoundary.gameInstanceId(), - currentBoundary.regionId(), - currentBoundary.regionEpoch(), - currentBoundary.playableStateScope(), - currentBoundary.worldSlug(), - currentBoundary.realmSlug(), - currentBoundary.pointerVersion(), - originScope, - CurrentRuntimeScopeFieldEmitter.writerFor(builder)); - }); + .ifPresent(currentBoundary -> { + CurrentRuntimeScopeFieldEmitter.applyCurrentRuntimeScopeFields( + currentBoundary.gameInstanceId(), + currentBoundary.regionId(), + currentBoundary.regionEpoch(), + currentBoundary.playableStateScope(), + currentBoundary.worldSlug(), + currentBoundary.realmSlug(), + currentBoundary.pointerVersion(), + originScope, + CurrentRuntimeScopeFieldEmitter.writerFor(builder)); + }); } private Optional currentRuntimeBoundary( long tenantId, long gameInstanceId) { return currentRuntimeOwnership(tenantId, gameInstanceId) - .map( - ownership -> { - GameInstance instance = getInstanceOrThrow(ownership.getGameInstanceId()); - CurrentRoutingAuthority authority = resolveCurrentRoutingAuthority(instance); - GameplayRoutingBundle routingBundle = authority.routingBundle(); - GameplayAdmissionPointerSnapshots.RoutingBundle normalizedRoutingBundle = - GameplayAdmissionPointerSnapshots.normalizeRoutingBundle( - routingBundle.worldSlug(), - routingBundle.realmSlug(), - routingBundle.pointerVersion()); - boolean singularRoutingAuthority = - authority.singularRoutingAuthority() && normalizedRoutingBundle != null; - return new CurrentRuntimeBoundary( - ownership.getGameInstanceId(), - ownership.getRegionId(), - ownership.getRegionEpoch(), - routingBundle.playableStateScope(), - singularRoutingAuthority, - normalizedRoutingBundle == null ? "" : normalizedRoutingBundle.worldSlug(), - normalizedRoutingBundle == null ? "" : normalizedRoutingBundle.realmSlug(), - normalizedRoutingBundle == null - ? null - : normalizedRoutingBundle.pointerVersion()); - }); + .map(ownership -> { + GameInstance instance = getInstanceOrThrow(ownership.getGameInstanceId()); + CurrentRoutingAuthority authority = resolveCurrentRoutingAuthority(instance); + GameplayRoutingBundle routingBundle = authority.routingBundle(); + GameplayAdmissionPointerSnapshots.RoutingBundle normalizedRoutingBundle = + GameplayAdmissionPointerSnapshots.normalizeRoutingBundle( + routingBundle.worldSlug(), + routingBundle.realmSlug(), + routingBundle.pointerVersion()); + boolean singularRoutingAuthority = + authority.singularRoutingAuthority() && normalizedRoutingBundle != null; + return new CurrentRuntimeBoundary( + ownership.getGameInstanceId(), + ownership.getRegionId(), + ownership.getRegionEpoch(), + routingBundle.playableStateScope(), + singularRoutingAuthority, + normalizedRoutingBundle == null ? "" : normalizedRoutingBundle.worldSlug(), + normalizedRoutingBundle == null ? "" : normalizedRoutingBundle.realmSlug(), + normalizedRoutingBundle == null ? null : normalizedRoutingBundle.pointerVersion()); + }); } private boolean isCurrentRoutingBundleStale( @@ -754,29 +743,27 @@ private boolean isCurrentRoutingBundleStale( String persistedRealmSlug, Long persistedPointerVersion) { return currentRuntimeBoundary(tenantId, gameInstanceId) - .map( - currentBoundary -> { - if (!currentBoundary.singularRoutingAuthority()) { - return hasPersistedRoutingBundleClaim( - persistedPlayableStateScope, - persistedWorldSlug, - persistedRealmSlug, - persistedPointerVersion); - } - return isRoutingBundleStale( - persistedPlayableStateScope, - persistedWorldSlug, - persistedRealmSlug, - persistedPointerVersion, - currentBoundary); - }) - .orElseGet( - () -> - hasPersistedRoutingBundleClaim( - persistedPlayableStateScope, - persistedWorldSlug, - persistedRealmSlug, - persistedPointerVersion)); + .map(currentBoundary -> { + if (!currentBoundary.singularRoutingAuthority()) { + return hasPersistedRoutingBundleClaim( + persistedPlayableStateScope, + persistedWorldSlug, + persistedRealmSlug, + persistedPointerVersion); + } + return isRoutingBundleStale( + persistedPlayableStateScope, + persistedWorldSlug, + persistedRealmSlug, + persistedPointerVersion, + currentBoundary); + }) + .orElseGet(() -> + hasPersistedRoutingBundleClaim( + persistedPlayableStateScope, + persistedWorldSlug, + persistedRealmSlug, + persistedPointerVersion)); } private static boolean hasPersistedRoutingBundleClaim( @@ -1646,30 +1633,28 @@ private GameplayCommandStatus toStatus(GameplayCommand command) { builder.setQueueSourceDueAtMs(command.getQueueSourceDueAtMs()); } currentRuntimeBoundary(command.getTenantId(), command.getGameInstanceId()) - .ifPresent( - currentBoundary -> { - if (currentBoundary.gameInstanceId() > 0) { - builder.setCurrentRuntimeGameInstanceId( - Long.toString(currentBoundary.gameInstanceId())); - } - if (currentBoundary.regionId() != null && !currentBoundary.regionId().isBlank()) { - builder.setCurrentRuntimeRegionId(currentBoundary.regionId()); - } - builder.setCurrentRuntimeRegionEpoch(currentBoundary.regionEpoch()); - if (currentBoundary.playableStateScope() != null) { - builder.setCurrentRuntimePlayableStateScope(currentBoundary.playableStateScope()); - } - if (currentBoundary.worldSlug() != null && !currentBoundary.worldSlug().isBlank()) { - builder.setCurrentRuntimeWorldSlug(currentBoundary.worldSlug()); - } - if (currentBoundary.realmSlug() != null && !currentBoundary.realmSlug().isBlank()) { - builder.setCurrentRuntimeRealmSlug(currentBoundary.realmSlug()); - } - if (currentBoundary.pointerVersion() != null - && currentBoundary.pointerVersion() > 0) { - builder.setCurrentRuntimePointerVersion(currentBoundary.pointerVersion()); - } - }); + .ifPresent(currentBoundary -> { + if (currentBoundary.gameInstanceId() > 0) { + builder.setCurrentRuntimeGameInstanceId( + Long.toString(currentBoundary.gameInstanceId())); + } + if (currentBoundary.regionId() != null && !currentBoundary.regionId().isBlank()) { + builder.setCurrentRuntimeRegionId(currentBoundary.regionId()); + } + builder.setCurrentRuntimeRegionEpoch(currentBoundary.regionEpoch()); + if (currentBoundary.playableStateScope() != null) { + builder.setCurrentRuntimePlayableStateScope(currentBoundary.playableStateScope()); + } + if (currentBoundary.worldSlug() != null && !currentBoundary.worldSlug().isBlank()) { + builder.setCurrentRuntimeWorldSlug(currentBoundary.worldSlug()); + } + if (currentBoundary.realmSlug() != null && !currentBoundary.realmSlug().isBlank()) { + builder.setCurrentRuntimeRealmSlug(currentBoundary.realmSlug()); + } + if (currentBoundary.pointerVersion() != null && currentBoundary.pointerVersion() > 0) { + builder.setCurrentRuntimePointerVersion(currentBoundary.pointerVersion()); + } + }); builder.setIsCurrentRuntimeRoutingBundleStale( isCurrentRoutingBundleStale( command.getTenantId(), @@ -1841,10 +1826,9 @@ private RemoteFollowup resolveRemoteFollowup( } return remoteFollowupRepository .findByTenantIdAndFollowupId(command.getTenantId(), followupId) - .filter( - followup -> - matchesFollowupCoordinator(followup, remoteCoordinator) - && Objects.equals(followup.getFollowupId(), followupId)) + .filter(followup -> + matchesFollowupCoordinator(followup, remoteCoordinator) + && Objects.equals(followup.getFollowupId(), followupId)) .orElse(null); } @@ -1876,10 +1860,9 @@ private GameplayCommand linkedTargetCommand( return gameplayCommandRepository .findByTenantIdAndGameInstanceIdAndRegionIdAndRegionEpochAndRemoteFollowupId( tenantId, targetGameInstanceId, targetRegionId, targetRegionEpoch, followupId) - .filter( - candidate -> - matchesTargetScope( - candidate, tenantId, targetGameInstanceId, targetRegionId, targetRegionEpoch)) + .filter(candidate -> + matchesTargetScope( + candidate, tenantId, targetGameInstanceId, targetRegionId, targetRegionEpoch)) .orElse(null); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index 2987f6e290..ac65510908 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -673,12 +673,11 @@ public void listGameplayWorlds( ListGameplayWorldsResponse.newBuilder() .addAllWorlds( gameplayWorldCatalog.publicWorldsFromAuthoritySnapshot().stream() - .map( - world -> - net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() - .setWorldSlug(world.slug()) - .setDisplayName(world.displayName()) - .build()) + .map(world -> + net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() + .setWorldSlug(world.slug()) + .setDisplayName(world.displayName()) + .build()) .toList()) .build(); responseObserver.onNext(response); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRemoteControlPlaneService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRemoteControlPlaneService.java index e35710e81f..3200cbb9d3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRemoteControlPlaneService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRemoteControlPlaneService.java @@ -241,15 +241,14 @@ ListRemoteCommandCoordinatorsResponse listRemoteCommandCoordinators( new HashMap<>(); ListRemoteCommandCoordinatorsResponse.Builder response = ListRemoteCommandCoordinatorsResponse.newBuilder(); - coordinators.forEach( - coordinator -> - response.addCoordinators( - toRemoteCoordinatorEntry( - coordinator, - followupsById.get(coordinator.getFollowupId()), - latestResultsByCoordinatorId.get(coordinator.getCoordinatorId()), - targetCommandsByFollowupId.get(coordinator.getFollowupId()), - runtimeBoundaryCache))); + coordinators.forEach(coordinator -> + response.addCoordinators( + toRemoteCoordinatorEntry( + coordinator, + followupsById.get(coordinator.getFollowupId()), + latestResultsByCoordinatorId.get(coordinator.getCoordinatorId()), + targetCommandsByFollowupId.get(coordinator.getFollowupId()), + runtimeBoundaryCache))); return response.build(); } @@ -405,14 +404,13 @@ ListRemoteFollowupsResponse listRemoteFollowups( Map> runtimeBoundaryCache = new HashMap<>(); ListRemoteFollowupsResponse.Builder response = ListRemoteFollowupsResponse.newBuilder(); - followups.forEach( - followup -> - response.addFollowups( - toRemoteFollowupEntry( - followup, - targetCommandsByFollowupId.get(followup.getFollowupId()), - coordinatorsByFollowupId.get(followup.getFollowupId()), - runtimeBoundaryCache))); + followups.forEach(followup -> + response.addFollowups( + toRemoteFollowupEntry( + followup, + targetCommandsByFollowupId.get(followup.getFollowupId()), + coordinatorsByFollowupId.get(followup.getFollowupId()), + runtimeBoundaryCache))); return response.build(); } @@ -491,22 +489,21 @@ ListRemoteFollowupResultsResponse listRemoteFollowupResults( new HashMap<>(); ListRemoteFollowupResultsResponse.Builder response = ListRemoteFollowupResultsResponse.newBuilder(); - results.forEach( - result -> { - RemoteCommandCoordinator coordinator = coordinatorsById.get(result.getCoordinatorId()); - if (!matchesCoordinatorScope(result, coordinator)) { - coordinator = null; - } - RemoteFollowup followup = followupsById.get(result.getFollowupId()); - if (!matchesCoordinatorScope(followup, result)) { - followup = null; - } - GameplayCommand targetCommand = - followup == null ? null : targetCommandsByFollowupId.get(followup.getFollowupId()); - response.addResults( - toRemoteFollowupResultEntry( - result, coordinator, followup, targetCommand, runtimeBoundaryCache)); - }); + results.forEach(result -> { + RemoteCommandCoordinator coordinator = coordinatorsById.get(result.getCoordinatorId()); + if (!matchesCoordinatorScope(result, coordinator)) { + coordinator = null; + } + RemoteFollowup followup = followupsById.get(result.getFollowupId()); + if (!matchesCoordinatorScope(followup, result)) { + followup = null; + } + GameplayCommand targetCommand = + followup == null ? null : targetCommandsByFollowupId.get(followup.getFollowupId()); + response.addResults( + toRemoteFollowupResultEntry( + result, coordinator, followup, targetCommand, runtimeBoundaryCache)); + }); return response.build(); } @@ -873,16 +870,13 @@ private RemoteFollowupResultEntry toRemoteFollowupResultEntry( gameplayCommandRepository .findByTenantIdAndGameInstanceIdAndCommandId( result.getTenantId(), result.getTargetGameInstanceId(), resultCommandId) - .filter( - candidate -> - Objects.equals(candidate.getTenantId(), result.getTenantId()) - && Objects.equals( - candidate.getGameInstanceId(), result.getTargetGameInstanceId()) - && Objects.equals(candidate.getRegionId(), result.getTargetRegionId()) - && Objects.equals( - candidate.getRegionEpoch(), result.getTargetRegionEpoch()) - && Objects.equals( - candidate.getRemoteFollowupId(), result.getFollowupId())) + .filter(candidate -> + Objects.equals(candidate.getTenantId(), result.getTenantId()) + && Objects.equals( + candidate.getGameInstanceId(), result.getTargetGameInstanceId()) + && Objects.equals(candidate.getRegionId(), result.getTargetRegionId()) + && Objects.equals(candidate.getRegionEpoch(), result.getTargetRegionEpoch()) + && Objects.equals(candidate.getRemoteFollowupId(), result.getFollowupId())) .orElse(null); } if (targetCommand != null && targetCommand.getCommandId() != null) { @@ -942,19 +936,18 @@ private void applyCurrentRuntimeScope( boolean originScope, Map> runtimeBoundaryCache) { cachedCurrentRuntimeBoundary(runtimeBoundaryCache, tenantId, gameInstanceId) - .ifPresent( - currentBoundary -> { - CurrentRuntimeScopeFieldEmitter.applyCurrentRuntimeScopeFields( - currentBoundary.gameInstanceId(), - currentBoundary.regionId(), - currentBoundary.regionEpoch(), - currentBoundary.playableStateScope(), - currentBoundary.worldSlug(), - currentBoundary.realmSlug(), - currentBoundary.pointerVersion(), - originScope, - CurrentRuntimeScopeFieldEmitter.writerFor(builder)); - }); + .ifPresent(currentBoundary -> { + CurrentRuntimeScopeFieldEmitter.applyCurrentRuntimeScopeFields( + currentBoundary.gameInstanceId(), + currentBoundary.regionId(), + currentBoundary.regionEpoch(), + currentBoundary.playableStateScope(), + currentBoundary.worldSlug(), + currentBoundary.realmSlug(), + currentBoundary.pointerVersion(), + originScope, + CurrentRuntimeScopeFieldEmitter.writerFor(builder)); + }); } private void applyCurrentRuntimeScope( @@ -964,19 +957,18 @@ private void applyCurrentRuntimeScope( boolean originScope, Map> runtimeBoundaryCache) { cachedCurrentRuntimeBoundary(runtimeBoundaryCache, tenantId, gameInstanceId) - .ifPresent( - currentBoundary -> { - CurrentRuntimeScopeFieldEmitter.applyCurrentRuntimeScopeFields( - currentBoundary.gameInstanceId(), - currentBoundary.regionId(), - currentBoundary.regionEpoch(), - currentBoundary.playableStateScope(), - currentBoundary.worldSlug(), - currentBoundary.realmSlug(), - currentBoundary.pointerVersion(), - originScope, - CurrentRuntimeScopeFieldEmitter.writerFor(builder)); - }); + .ifPresent(currentBoundary -> { + CurrentRuntimeScopeFieldEmitter.applyCurrentRuntimeScopeFields( + currentBoundary.gameInstanceId(), + currentBoundary.regionId(), + currentBoundary.regionEpoch(), + currentBoundary.playableStateScope(), + currentBoundary.worldSlug(), + currentBoundary.realmSlug(), + currentBoundary.pointerVersion(), + originScope, + CurrentRuntimeScopeFieldEmitter.writerFor(builder)); + }); } private void applyCurrentRuntimeScope( @@ -986,51 +978,47 @@ private void applyCurrentRuntimeScope( boolean originScope, Map> runtimeBoundaryCache) { cachedCurrentRuntimeBoundary(runtimeBoundaryCache, tenantId, gameInstanceId) - .ifPresent( - currentBoundary -> { - CurrentRuntimeScopeFieldEmitter.applyCurrentRuntimeScopeFields( - currentBoundary.gameInstanceId(), - currentBoundary.regionId(), - currentBoundary.regionEpoch(), - currentBoundary.playableStateScope(), - currentBoundary.worldSlug(), - currentBoundary.realmSlug(), - currentBoundary.pointerVersion(), - originScope, - CurrentRuntimeScopeFieldEmitter.writerFor(builder)); - }); + .ifPresent(currentBoundary -> { + CurrentRuntimeScopeFieldEmitter.applyCurrentRuntimeScopeFields( + currentBoundary.gameInstanceId(), + currentBoundary.regionId(), + currentBoundary.regionEpoch(), + currentBoundary.playableStateScope(), + currentBoundary.worldSlug(), + currentBoundary.realmSlug(), + currentBoundary.pointerVersion(), + originScope, + CurrentRuntimeScopeFieldEmitter.writerFor(builder)); + }); } private Optional currentRuntimeBoundary( long tenantId, long gameInstanceId) { return currentRuntimeOwnership(tenantId, gameInstanceId) - .map( - ownership -> { - GameInstance instance = getInstanceOrThrow(ownership.getGameInstanceId()); - if (!Objects.equals(instance.getTenantId(), tenantId)) { - throw new IllegalArgumentException("Game instance not found"); - } - CurrentRoutingAuthority authority = resolveCurrentRoutingAuthority(instance); - GameplayRoutingBundle routingBundle = authority.routingBundle(); - RoutingBundle normalizedRoutingBundle = - GameplayAdmissionPointerSnapshots.normalizeRoutingBundle( - routingBundle.worldSlug(), - routingBundle.realmSlug(), - routingBundle.pointerVersion()); - boolean singularRoutingAuthority = - authority.singularRoutingAuthority() && normalizedRoutingBundle != null; - return new CurrentRuntimeBoundary( - ownership.getGameInstanceId(), - ownership.getRegionId(), - ownership.getRegionEpoch(), - routingBundle.playableStateScope(), - singularRoutingAuthority, - normalizedRoutingBundle == null ? "" : normalizedRoutingBundle.worldSlug(), - normalizedRoutingBundle == null ? "" : normalizedRoutingBundle.realmSlug(), - normalizedRoutingBundle == null - ? null - : normalizedRoutingBundle.pointerVersion()); - }); + .map(ownership -> { + GameInstance instance = getInstanceOrThrow(ownership.getGameInstanceId()); + if (!Objects.equals(instance.getTenantId(), tenantId)) { + throw new IllegalArgumentException("Game instance not found"); + } + CurrentRoutingAuthority authority = resolveCurrentRoutingAuthority(instance); + GameplayRoutingBundle routingBundle = authority.routingBundle(); + RoutingBundle normalizedRoutingBundle = + GameplayAdmissionPointerSnapshots.normalizeRoutingBundle( + routingBundle.worldSlug(), + routingBundle.realmSlug(), + routingBundle.pointerVersion()); + boolean singularRoutingAuthority = + authority.singularRoutingAuthority() && normalizedRoutingBundle != null; + return new CurrentRuntimeBoundary( + ownership.getGameInstanceId(), + ownership.getRegionId(), + ownership.getRegionEpoch(), + routingBundle.playableStateScope(), + singularRoutingAuthority, + normalizedRoutingBundle == null ? "" : normalizedRoutingBundle.worldSlug(), + normalizedRoutingBundle == null ? "" : normalizedRoutingBundle.realmSlug(), + normalizedRoutingBundle == null ? null : normalizedRoutingBundle.pointerVersion()); + }); } private boolean isCurrentRoutingBundleStale( @@ -1042,29 +1030,27 @@ private boolean isCurrentRoutingBundleStale( String persistedRealmSlug, Long persistedPointerVersion) { return cachedCurrentRuntimeBoundary(runtimeBoundaryCache, tenantId, gameInstanceId) - .map( - currentBoundary -> { - if (!currentBoundary.singularRoutingAuthority()) { - return hasPersistedRoutingBundleClaim( - persistedPlayableStateScope, - persistedWorldSlug, - persistedRealmSlug, - persistedPointerVersion); - } - return isRoutingBundleStale( - persistedPlayableStateScope, - persistedWorldSlug, - persistedRealmSlug, - persistedPointerVersion, - currentBoundary); - }) - .orElseGet( - () -> - hasPersistedRoutingBundleClaim( - persistedPlayableStateScope, - persistedWorldSlug, - persistedRealmSlug, - persistedPointerVersion)); + .map(currentBoundary -> { + if (!currentBoundary.singularRoutingAuthority()) { + return hasPersistedRoutingBundleClaim( + persistedPlayableStateScope, + persistedWorldSlug, + persistedRealmSlug, + persistedPointerVersion); + } + return isRoutingBundleStale( + persistedPlayableStateScope, + persistedWorldSlug, + persistedRealmSlug, + persistedPointerVersion, + currentBoundary); + }) + .orElseGet(() -> + hasPersistedRoutingBundleClaim( + persistedPlayableStateScope, + persistedWorldSlug, + persistedRealmSlug, + persistedPointerVersion)); } private Optional cachedCurrentRuntimeBoundary( @@ -1973,10 +1959,9 @@ private Map followupMap( return Map.of(); } return remoteFollowupRepository.findByTenantIdAndFollowupIdIn(tenantId, distinctIds).stream() - .filter( - followup -> - coordinators.stream() - .anyMatch(coordinator -> matchesCoordinatorScope(followup, coordinator))) + .filter(followup -> + coordinators.stream() + .anyMatch(coordinator -> matchesCoordinatorScope(followup, coordinator))) .collect(Collectors.toMap(RemoteFollowup::getFollowupId, Function.identity())); } @@ -1991,9 +1976,8 @@ private Map followupMapForResults( return Map.of(); } return remoteFollowupRepository.findByTenantIdAndFollowupIdIn(tenantId, distinctIds).stream() - .filter( - followup -> - results.stream().anyMatch(result -> matchesCoordinatorScope(followup, result))) + .filter(followup -> + results.stream().anyMatch(result -> matchesCoordinatorScope(followup, result))) .collect(Collectors.toMap(RemoteFollowup::getFollowupId, Function.identity())); } @@ -2010,10 +1994,8 @@ private Map coordinatorByFollowupMap( return remoteCommandCoordinatorRepository .findByTenantIdAndFollowupIdIn(tenantId, distinctIds) .stream() - .filter( - coordinator -> - followups.stream() - .anyMatch(followup -> matchesCoordinatorScope(followup, coordinator))) + .filter(coordinator -> + followups.stream().anyMatch(followup -> matchesCoordinatorScope(followup, coordinator))) .collect(Collectors.toMap(RemoteCommandCoordinator::getFollowupId, Function.identity())); } @@ -2030,9 +2012,8 @@ private Map coordinatorMap( return remoteCommandCoordinatorRepository .findByTenantIdAndCoordinatorIdIn(tenantId, distinctIds) .stream() - .filter( - coordinator -> - results.stream().anyMatch(result -> matchesCoordinatorScope(result, coordinator))) + .filter(coordinator -> + results.stream().anyMatch(result -> matchesCoordinatorScope(result, coordinator))) .collect(Collectors.toMap(RemoteCommandCoordinator::getCoordinatorId, Function.identity())); } @@ -2042,10 +2023,9 @@ private Map latestResultMap( return Map.of(); } return remoteFollowupResultRepository.findForCoordinatorScopes(coordinators).stream() - .filter( - result -> - coordinators.stream() - .anyMatch(coordinator -> matchesCoordinatorScope(result, coordinator))) + .filter(result -> + coordinators.stream() + .anyMatch(coordinator -> matchesCoordinatorScope(result, coordinator))) .collect( Collectors.toMap( RemoteFollowupResult::getCoordinatorId, @@ -2065,11 +2045,10 @@ private Map targetCommandMap( return gameplayCommandRepository .findByTenantIdAndRemoteFollowupIdIn(tenantId, distinctIds) .stream() - .filter( - candidate -> { - RemoteFollowup followup = followupsById.get(candidate.getRemoteFollowupId()); - return followup != null && matchesTargetScope(candidate, tenantId, followup); - }) + .filter(candidate -> { + RemoteFollowup followup = followupsById.get(candidate.getRemoteFollowupId()); + return followup != null && matchesTargetScope(candidate, tenantId, followup); + }) .collect( Collectors.toMap( GameplayCommand::getRemoteFollowupId, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java index 0a876ed6f6..dca9c2059e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java @@ -352,10 +352,9 @@ private CurrentRoutingProjection resolveGameplayRouting(GameInstance instance) { GameplayRoutingBundle singularBundle = GameplayAdmissionPointerSnapshots.singularCompletePointer(pointers) .map(this::toGameplayRoutingBundle) - .orElseGet( - () -> - new GameplayRoutingBundle( - PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED, "", "", 0L)); + .orElseGet(() -> + new GameplayRoutingBundle( + PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED, "", "", 0L)); return new CurrentRoutingProjection(singularBundle, entries); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java index 2b9cc7f9c9..832f4040ef 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java @@ -86,29 +86,27 @@ public void recordConnected(SessionContext context) { public void recordActivity(long sessionId) { sessionRoutingNormalizationService .resolveProjectedSessionContext(Long.toString(sessionId)) - .ifPresent( - context -> { - GameplayPresence presence = - gameplayPresenceService.findConnectedBySessionId(sessionId).orElse(null); - RoutingSnapshot snapshot = routingSnapshot(context, presence); - write( - snapshot, - AccountRecentPresenceDisposition.TRANSPORT_LOSS, - currentTimeMillisSupplier.getAsLong()); - }); + .ifPresent(context -> { + GameplayPresence presence = + gameplayPresenceService.findConnectedBySessionId(sessionId).orElse(null); + RoutingSnapshot snapshot = routingSnapshot(context, presence); + write( + snapshot, + AccountRecentPresenceDisposition.TRANSPORT_LOSS, + currentTimeMillisSupplier.getAsLong()); + }); } @Override public void recordDisconnect(long sessionId, AccountRecentPresenceDisposition disposition) { sessionRoutingNormalizationService .resolveProjectedSessionContext(Long.toString(sessionId)) - .ifPresent( - context -> { - GameplayPresence presence = - gameplayPresenceService.findConnectedBySessionId(sessionId).orElse(null); - RoutingSnapshot snapshot = routingSnapshot(context, presence); - write(snapshot, disposition, currentTimeMillisSupplier.getAsLong()); - }); + .ifPresent(context -> { + GameplayPresence presence = + gameplayPresenceService.findConnectedBySessionId(sessionId).orElse(null); + RoutingSnapshot snapshot = routingSnapshot(context, presence); + write(snapshot, disposition, currentTimeMillisSupplier.getAsLong()); + }); } @Override diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImpl.java index 0bfde12332..e86a628c87 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImpl.java @@ -275,10 +275,9 @@ public void abandonFollowup( RemoteCommandCoordinator coordinator = remoteCommandCoordinatorRepository .findByTenantIdAndFollowupId(tenantId, followupId) - .orElseThrow( - () -> - new IllegalStateException( - "cannot persist scope-invalid remote result without its coordinator")); + .orElseThrow(() -> + new IllegalStateException( + "cannot persist scope-invalid remote result without its coordinator")); if (!hasCompleteRuntimeScope(coordinator)) { throw new IllegalStateException( "cannot persist scope-invalid remote result with incomplete coordinator scope"); @@ -514,10 +513,9 @@ private GameplayCommand linkedTargetCommand( return gameplayCommandRepository .findByTenantIdAndGameInstanceIdAndRegionIdAndRegionEpochAndRemoteFollowupId( tenantId, targetGameInstanceId, targetRegionId, targetRegionEpoch, followupId) - .filter( - candidate -> - matchesTargetScope( - candidate, tenantId, targetGameInstanceId, targetRegionId, targetRegionEpoch)) + .filter(candidate -> + matchesTargetScope( + candidate, tenantId, targetGameInstanceId, targetRegionId, targetRegionEpoch)) .orElse(null); } @@ -1675,14 +1673,13 @@ private void mirrorCoordinatorToCommand(RemoteCommandCoordinator coordinator, In coordinator.getTenantId(), coordinator.getOriginGameInstanceId(), coordinator.getCommandId()) - .filter( - candidate -> - matchesScope( - candidate, - coordinator.getTenantId(), - coordinator.getOriginGameInstanceId(), - coordinator.getOriginRegionId(), - coordinator.getOriginRegionEpoch())) + .filter(candidate -> + matchesScope( + candidate, + coordinator.getTenantId(), + coordinator.getOriginGameInstanceId(), + coordinator.getOriginRegionId(), + coordinator.getOriginRegionEpoch())) .orElse(null); GameplayCommand targetCommand = linkedTargetCommand( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java index 73f3749c8d..1550f568b6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java @@ -253,11 +253,8 @@ private Long executeRestorePendingProjectionScript(List keys, Object... private Object[] unwrapRestoreScriptArguments(Object[] arguments) { return java.util.Arrays.stream(arguments) - .map( - argument -> - argument instanceof RestoreQueuePayloadArgument payload - ? payload.value() - : argument) + .map(argument -> + argument instanceof RestoreQueuePayloadArgument payload ? payload.value() : argument) .toArray(); } @@ -347,12 +344,11 @@ private List redisOnlyEntries( .map(TickQueuedCommandEnvelope::commandId) .collect(java.util.stream.Collectors.toSet()); return pendingEntries.stream() - .filter( - entry -> - entry.commandId() != null - && !entry.commandId().isBlank() - && !sealedCommandIds.contains(entry.commandId()) - && !terminalizedCommandIds.contains(entry.commandId())) + .filter(entry -> + entry.commandId() != null + && !entry.commandId().isBlank() + && !sealedCommandIds.contains(entry.commandId()) + && !terminalizedCommandIds.contains(entry.commandId())) .toList(); } @@ -582,10 +578,8 @@ void markRemoteFollowupBatchAbandoned( Instant now = Instant.now(); BatchDrainState originalState = BatchDrainState.capture(batch); try { - transactionOperations.executeWithoutResult( - status -> - markRemoteFollowupBatchAbandonedInTransaction( - batch, now, failureCode, failureMessage)); + transactionOperations.executeWithoutResult(status -> + markRemoteFollowupBatchAbandonedInTransaction(batch, now, failureCode, failureMessage)); } catch (RuntimeException | Error ex) { originalState.restore(batch); throw ex; @@ -750,9 +744,8 @@ private void abandonUnfinishedRemoteFollowupEffects( String tickBatchId, Instant completedAt, String failureCode, String failureMessage) { List unfinishedEffects = tickEffectRepository.findByTickBatchId(tickBatchId).stream() - .filter( - effect -> - "STAGED".equals(effect.getStatus()) || "DRAINED".equals(effect.getStatus())) + .filter(effect -> + "STAGED".equals(effect.getStatus()) || "DRAINED".equals(effect.getStatus())) .toList(); for (TickEffect effect : unfinishedEffects) { effect.setStatus("ABANDONED"); @@ -823,11 +816,8 @@ private void recordRequeuedCommands(List commands, int fallback .collect( java.util.stream.Collectors.groupingBy( this::requeueMetricSource, java.util.stream.Collectors.counting())); - countsBySource.forEach( - (source, count) -> - meterRegistry - .counter("tick_requeued_action_total", "source", source) - .increment(count)); + countsBySource.forEach((source, count) -> + meterRegistry.counter("tick_requeued_action_total", "source", source).increment(count)); return; } if (fallbackCount > 0) { @@ -853,23 +843,22 @@ private String requeueMetricSource(GameplayCommand command) { private void executeDurableEffect(TickBatch batch, TickEffect effect) { if ("REMOTE_FOLLOWUP".equals(effect.getEffectType())) { - transactionOperations.executeWithoutResult( - status -> { - DurableRemoteFollowupExecutionService.DurableRemoteFollowupExecutionResult result = - durableRemoteFollowupExecutionService.execute(effect); - if ("RETRY_QUEUED".equals(result.effectStatus())) { - markEffectRetryable(effect, result.failureCode(), result.failureMessage()); - } else { - markEffectTerminal( - batch, - effect, - result.effectStatus(), - "COMPLETED", - "NOT_APPLIED", - result.failureCode(), - result.failureMessage()); - } - }); + transactionOperations.executeWithoutResult(status -> { + DurableRemoteFollowupExecutionService.DurableRemoteFollowupExecutionResult result = + durableRemoteFollowupExecutionService.execute(effect); + if ("RETRY_QUEUED".equals(result.effectStatus())) { + markEffectRetryable(effect, result.failureCode(), result.failureMessage()); + } else { + markEffectTerminal( + batch, + effect, + result.effectStatus(), + "COMPLETED", + "NOT_APPLIED", + result.failureCode(), + result.failureMessage()); + } + }); return; } if (effect.getCommandId() == null || effect.getCommandId().isBlank()) { @@ -946,16 +935,15 @@ private void markEffectTerminal( gameplayCommandRepository .findByTenantIdAndGameInstanceIdAndCommandId( batch.getTenantId(), batch.getGameInstanceId(), effect.getCommandId()) - .ifPresent( - command -> { - command.setExecutionOutcome(commandExecutionOutcome); - command.setGameplayResult(gameplayResult); - command.setCompletedAt(now); - command.setLastAttemptAt(now); - command.setFailureCode(failureCode); - command.setFailureMessage(truncate(failureMessage, 500)); - gameplayCommandRepository.save(command); - }); + .ifPresent(command -> { + command.setExecutionOutcome(commandExecutionOutcome); + command.setGameplayResult(gameplayResult); + command.setCompletedAt(now); + command.setLastAttemptAt(now); + command.setFailureCode(failureCode); + command.setFailureMessage(truncate(failureMessage, 500)); + gameplayCommandRepository.save(command); + }); } private void markEffectRetryable(TickEffect effect, String failureCode, String failureMessage) { @@ -997,9 +985,8 @@ private void updateGameplayCommands( boolean completed) { List commands = loadCommands(tenantId, gameInstanceId, entries).stream() - .filter( - command -> - commandMatchesScope(command, tenantId, gameInstanceId, regionId, regionEpoch)) + .filter(command -> + commandMatchesScope(command, tenantId, gameInstanceId, regionId, regionEpoch)) .toList(); if (commands.isEmpty()) { return; @@ -1058,14 +1045,13 @@ private List loadCommandsForEffects(TickBatch batch, List - commandMatchesScope( - command, - batch.getTenantId(), - batch.getGameInstanceId(), - batch.getRegionId(), - batch.getRegionEpoch())) + .filter(command -> + commandMatchesScope( + command, + batch.getTenantId(), + batch.getGameInstanceId(), + batch.getRegionId(), + batch.getRegionEpoch())) .toList(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickQueueControlService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickQueueControlService.java index 8cf78bc245..1a296dace2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickQueueControlService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickQueueControlService.java @@ -197,17 +197,16 @@ OwnershipSnapshot claimOwnership(Long tenantId, Long gameInstanceId, QueueLockLe RuntimeRegionStatus status = runtimeRegionStatusRepository .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) - .orElseGet( - () -> { - RuntimeRegionStatus created = new RuntimeRegionStatus(); - created.setTenantId(tenantId); - created.setGameInstanceId(gameInstanceId); - created.setRegionId(defaultCurrentBoundaryRegionId(gameInstanceId)); - created.setRegionEpoch(1L); - created.setExecutorFence(tickLease.token()); - created.setPaused(false); - return created; - }); + .orElseGet(() -> { + RuntimeRegionStatus created = new RuntimeRegionStatus(); + created.setTenantId(tenantId); + created.setGameInstanceId(gameInstanceId); + created.setRegionId(defaultCurrentBoundaryRegionId(gameInstanceId)); + created.setRegionEpoch(1L); + created.setExecutorFence(tickLease.token()); + created.setPaused(false); + return created; + }); RuntimeRegionStatus baseline; if (status.getId() == null) { status.setOwnerService(runtimeIdentity.service()); @@ -225,10 +224,8 @@ OwnershipSnapshot claimOwnership(Long tenantId, Long gameInstanceId, QueueLockLe runtimeIdentity.serviceInstanceId(), tickLease.token(), now) - .orElseThrow( - () -> - new StaleOwnershipException( - "Runtime ownership changed during lease-backed claim")); + .orElseThrow(() -> + new StaleOwnershipException("Runtime ownership changed during lease-backed claim")); tickLease.requireOwned(); return new OwnershipSnapshot( saved.getRegionId(), @@ -257,10 +254,9 @@ String queryState(Long sessionId) { maybeContext .map(SessionContext::tenantId) .filter(tenant -> tenant != null && tenant > 0) - .orElseThrow( - () -> - new IllegalArgumentException( - "No session context found for sessionId=" + sessionId)); + .orElseThrow(() -> + new IllegalArgumentException( + "No session context found for sessionId=" + sessionId)); Object state = redisTemplate.opsForValue().get(stateKey(tenantId, sessionId)); return state != null ? state.toString() : "{}"; } @@ -318,30 +314,27 @@ RuntimeRegionStatus requireRuntimeOwnership(Long tenantId, Long gameInstanceId, } return runtimeRegionStatusRepository .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) - .orElseThrow( - () -> - new StaleOwnershipException( - "Missing runtime ownership for tenantId=%d gameInstanceId=%d regionId=%s" - .formatted(tenantId, gameInstanceId, regionId))); + .orElseThrow(() -> + new StaleOwnershipException( + "Missing runtime ownership for tenantId=%d gameInstanceId=%d regionId=%s" + .formatted(tenantId, gameInstanceId, regionId))); } RuntimeRegionStatus advanceLastCommittedTickId(RuntimeRegionStatus expectedOwnership) { return runtimeRegionStatusRepository .advanceLastCommittedTickId(expectedOwnership) - .orElseThrow( - () -> - new StaleOwnershipException( - "Runtime ownership changed before tick progress could be committed")); + .orElseThrow(() -> + new StaleOwnershipException( + "Runtime ownership changed before tick progress could be committed")); } RuntimeRegionStatus commitDrainedBatch( RuntimeRegionStatus expectedOwnership, String tickBatchId) { return runtimeRegionStatusRepository .commitDrainedBatch(expectedOwnership, tickBatchId) - .orElseThrow( - () -> - new StaleOwnershipException( - "Runtime ownership changed before drained batch could be committed")); + .orElseThrow(() -> + new StaleOwnershipException( + "Runtime ownership changed before drained batch could be committed")); } String queueKey(Long tenantId, Long sessionId) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressService.java index b83e014d36..9944156b26 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressService.java @@ -199,12 +199,11 @@ void observeRemoteFollowupBacklog( ownership.regionId(), RemoteFollowupRuntimeServiceImpl.FOLLOWUP_SCHEDULED, ownership.lastCommittedTickId() + 1L) - .map( - followup -> - Math.max( - 0L, - (ownership.lastCommittedTickId() + 1L - followup.getDueTickId()) - * tickDurationMs)) + .map(followup -> + Math.max( + 0L, + (ownership.lastCommittedTickId() + 1L - followup.getDueTickId()) + * tickDurationMs)) .orElse(0L); String gaugeKey = tenantId + ":" + ownership.regionId(); remoteFollowupDueByTarget.compute( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickScheduler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickScheduler.java index fef86c5926..96aee61963 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickScheduler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickScheduler.java @@ -224,14 +224,13 @@ private ScheduleOutcome scheduleTick(GameInstance instance) { } try { scheduledCounter.increment(); - tickExecutor.execute( - () -> { - try { - tickService.processTick(instance.getTenantId(), instance.getId()); - } finally { - pendingOrRunningTicks.remove(key); - } - }); + tickExecutor.execute(() -> { + try { + tickService.processTick(instance.getTenantId(), instance.getId()); + } finally { + pendingOrRunningTicks.remove(key); + } + }); } catch (TaskRejectedException ex) { pendingOrRunningTicks.remove(key); rejectedCounter.increment(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickServiceImpl.java index afe085f510..94006978af 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickServiceImpl.java @@ -363,19 +363,17 @@ public void processTick(Long tenantId, Long queueTargetId) { int max = solo ? 1 : tickMaxCommands; String stageMode = solo ? "S" : "N"; lease.requireOwned(); - luaTimer.record( - () -> - executeFencedScript( - stageScript, - lease, - List.of( - tickQueueControlService.queueKey( - normalizedTenantId, normalizedQueueTargetId), - tickQueueControlService.pendingKey( - normalizedTenantId, normalizedQueueTargetId)), - "stage", - String.valueOf(max), - stageMode)); + luaTimer.record(() -> + executeFencedScript( + stageScript, + lease, + List.of( + tickQueueControlService.queueKey(normalizedTenantId, normalizedQueueTargetId), + tickQueueControlService.pendingKey( + normalizedTenantId, normalizedQueueTargetId)), + "stage", + String.valueOf(max), + stageMode)); TickStagingService.PendingEntriesReadResult stagedResult = tickStagingService.readPendingEntriesForReplay( normalizedTenantId, normalizedQueueTargetId); @@ -441,20 +439,19 @@ public void processTick(Long tenantId, Long queueTargetId) { } else { try { Object[] rollbackArguments = rollbackArguments(terminalizedBatchEntries); - luaTimer.record( - () -> - executeFencedScript( - rollbackScript, - lease, - List.of( - tickQueueControlService.pendingKey( - normalizedTenantId, normalizedQueueTargetId), - tickQueueControlService.queueKey( - normalizedTenantId, normalizedQueueTargetId), - tickQueueControlService.commandIndexKey( - normalizedTenantId, normalizedQueueTargetId)), - "rollback", - rollbackArguments)); + luaTimer.record(() -> + executeFencedScript( + rollbackScript, + lease, + List.of( + tickQueueControlService.pendingKey( + normalizedTenantId, normalizedQueueTargetId), + tickQueueControlService.queueKey( + normalizedTenantId, normalizedQueueTargetId), + tickQueueControlService.commandIndexKey( + normalizedTenantId, normalizedQueueTargetId)), + "rollback", + rollbackArguments)); rollbackSucceeded = true; } catch (RuntimeException rollbackFailure) { logger.error( @@ -533,15 +530,14 @@ private List mergeEntriesByCommandId( private void commitPending( TickQueueControlService.QueueLockLease lease, Long tenantId, Long queueTargetId) { - luaTimer.record( - () -> - executeFencedScript( - commitScript, - lease, - List.of( - tickQueueControlService.pendingKey(tenantId, queueTargetId), - tickQueueControlService.commandIndexKey(tenantId, queueTargetId)), - "commit")); + luaTimer.record(() -> + executeFencedScript( + commitScript, + lease, + List.of( + tickQueueControlService.pendingKey(tenantId, queueTargetId), + tickQueueControlService.commandIndexKey(tenantId, queueTargetId)), + "commit")); } private void requireResolvedPendingEntries( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java index 23e9986889..ffc5d9f6d0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java @@ -348,10 +348,9 @@ ReplayResolution resolveReplayBatchForTick( } ReplayResolution resolution = Objects.requireNonNull( - transactionOperations.execute( - status -> - resolveReplayBatchInTransaction( - tenantId, gameInstanceId, replayEntries, ownership)), + transactionOperations.execute(status -> + resolveReplayBatchInTransaction( + tenantId, gameInstanceId, replayEntries, ownership)), "Replay resolution transaction returned no result"); resolution = appendTerminalizedPendingEntries(resolution, terminalizedEntries); if (resolution.redisReconciliation() != null) { @@ -417,10 +416,9 @@ private ReplayResolution resolveReplayBatchForTickWithoutRedisReconciliation( TickQueueControlService.OwnershipSnapshot ownership) { ReplayResolution resolution = Objects.requireNonNull( - transactionOperations.execute( - status -> - resolveReplayBatchInTransaction( - tenantId, gameInstanceId, replayEntries, ownership)), + transactionOperations.execute(status -> + resolveReplayBatchInTransaction( + tenantId, gameInstanceId, replayEntries, ownership)), "Replay resolution transaction returned no result"); if (resolution.redisReconciliation() != null) { throw new IllegalStateException( @@ -705,50 +703,49 @@ BatchCreationResult createBatchForTick( batch.setRequiresSoloTick(requiresSoloTick); batch.setStagedAt(now); BatchCreationResult result = - transactionOperations.execute( - status -> { - List transactionSelections = - commandSelections(tenantId, gameInstanceId, entries); - requireExactCommandSetAndScope( - entries, transactionSelections, tenantId, gameInstanceId, ownership); - requireDurableModeAgreement(transactionSelections); - GameInstance lockedInstance = - requireAuthoritativeLocalAutomationPinTuple( - tenantId, gameInstanceId, transactionSelections); - requireCurrentStagingOwnership(tenantId, gameInstanceId, batch); - List acceptedSelections = - classifyFreshStageSelections(transactionSelections, lockedInstance, now); - List acceptedEntries = - acceptedSelections.stream().map(CommandSelection::entry).toList(); - java.util.Set acceptedCommandIds = - acceptedSelections.stream() - .map(selection -> selection.entry().commandId()) - .collect(java.util.stream.Collectors.toSet()); - List terminalizedEntries = - transactionSelections.stream() - .map(CommandSelection::entry) - .filter(entry -> !acceptedCommandIds.contains(entry.commandId())) - .toList(); - if (acceptedSelections.isEmpty()) { - logger.info( - "Terminalized all incomplete local Automation commands in tick staging " - + "tenantId={} gameInstanceId={}", - tenantId, - gameInstanceId); - return new BatchCreationResult(null, List.of(), terminalizedEntries); - } - batch.setCommandCount(acceptedEntries.size()); - batch.setExpectedEffectCount(acceptedEntries.size()); - String transactionManifest = - selectedWorkManifest(ownership.regionId(), acceptedSelections); - batch.setSelectedWorkManifestJson(transactionManifest); - batch.setSelectedWorkManifestDigest(shortHash(transactionManifest)); - TickBatch persistedBatch = tickBatchRepository.save(batch); - persistEffects(persistedBatch, gameInstanceId, now, acceptedSelections); - bumpGameplayCommandAttempts(commandsForSelections(acceptedSelections), now); - return new BatchCreationResult( - persistedBatch, List.copyOf(acceptedEntries), terminalizedEntries); - }); + transactionOperations.execute(status -> { + List transactionSelections = + commandSelections(tenantId, gameInstanceId, entries); + requireExactCommandSetAndScope( + entries, transactionSelections, tenantId, gameInstanceId, ownership); + requireDurableModeAgreement(transactionSelections); + GameInstance lockedInstance = + requireAuthoritativeLocalAutomationPinTuple( + tenantId, gameInstanceId, transactionSelections); + requireCurrentStagingOwnership(tenantId, gameInstanceId, batch); + List acceptedSelections = + classifyFreshStageSelections(transactionSelections, lockedInstance, now); + List acceptedEntries = + acceptedSelections.stream().map(CommandSelection::entry).toList(); + java.util.Set acceptedCommandIds = + acceptedSelections.stream() + .map(selection -> selection.entry().commandId()) + .collect(java.util.stream.Collectors.toSet()); + List terminalizedEntries = + transactionSelections.stream() + .map(CommandSelection::entry) + .filter(entry -> !acceptedCommandIds.contains(entry.commandId())) + .toList(); + if (acceptedSelections.isEmpty()) { + logger.info( + "Terminalized all incomplete local Automation commands in tick staging " + + "tenantId={} gameInstanceId={}", + tenantId, + gameInstanceId); + return new BatchCreationResult(null, List.of(), terminalizedEntries); + } + batch.setCommandCount(acceptedEntries.size()); + batch.setExpectedEffectCount(acceptedEntries.size()); + String transactionManifest = + selectedWorkManifest(ownership.regionId(), acceptedSelections); + batch.setSelectedWorkManifestJson(transactionManifest); + batch.setSelectedWorkManifestDigest(shortHash(transactionManifest)); + TickBatch persistedBatch = tickBatchRepository.save(batch); + persistEffects(persistedBatch, gameInstanceId, now, acceptedSelections); + bumpGameplayCommandAttempts(commandsForSelections(acceptedSelections), now); + return new BatchCreationResult( + persistedBatch, List.copyOf(acceptedEntries), terminalizedEntries); + }); TickBatch savedBatch = result.batch(); if (savedBatch == null) { return result; @@ -954,12 +951,11 @@ private TickBatch createRemoteFollowupBatch( batch.setSelectedWorkManifestDigest(shortHash(selectedWorkManifest)); batch.setStagedAt(now); TickBatch savedBatch = - transactionOperations.execute( - status -> { - TickBatch persistedBatch = tickBatchRepository.save(batch); - persistRemoteFollowupEffects(persistedBatch, now, followups); - return persistedBatch; - }); + transactionOperations.execute(status -> { + TickBatch persistedBatch = tickBatchRepository.save(batch); + persistRemoteFollowupEffects(persistedBatch, now, followups); + return persistedBatch; + }); logger.info( "Staged durable remote followup batch tickBatchId={} tenantId={} gameInstanceId={} followupCount={}", savedBatch.getTickBatchId(), @@ -1177,12 +1173,11 @@ private boolean hasComparisonEligibleLocalAutomationCommands( List selections, java.util.Set excludedCommandIds) { return localAutomationCommands(selections).stream() .filter(command -> !excludedCommandIds.contains(command.getCommandId())) - .anyMatch( - command -> - hasCompleteScriptPinTuple( - command.getScriptPatchVersion(), - command.getScriptPinEpoch(), - command.getScriptPinControlPlaneRequestId())); + .anyMatch(command -> + hasCompleteScriptPinTuple( + command.getScriptPatchVersion(), + command.getScriptPinEpoch(), + command.getScriptPinControlPlaneRequestId())); } private GameInstance requireAuthoritativeLocalAutomationPinTuple( @@ -1194,10 +1189,9 @@ private GameInstance requireAuthoritativeLocalAutomationPinTuple( GameInstance instance = gameInstanceRepository .findByTenantIdAndGameInstanceIdForUpdate(tenantId, gameInstanceId) - .orElseThrow( - () -> - new IllegalStateException( - "Authoritative game instance is unavailable for local Automation staging")); + .orElseThrow(() -> + new IllegalStateException( + "Authoritative game instance is unavailable for local Automation staging")); if (!Objects.equals(tenantId, instance.getTenantId())) { throw new IllegalStateException( "Authoritative game instance tenant does not match local Automation staging"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java index 60d5234f1d..d7ad0aec55 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiver.java @@ -70,16 +70,14 @@ public TextCommandInterpretationResult receive(WebSocketSession socket, TextComm || request.worldSelector() == null || request.worldSelector().isBlank()) yield failure("INVALID_ARGUMENT", "Usage: REALMS "); - yield connection.withLogin( - (original, result) -> { - if (connection.menu == null) - return failure("INVALID_ARGUMENT", "Run WORLDS before REALMS "); - connection.selectedScope = - required(lobbies) - .realms( - original, result, connection, connection.menu, request.worldSelector()); - return success(connection.selectedScope.publicTarget().realmDisplayName()); - }); + yield connection.withLogin((original, result) -> { + if (connection.menu == null) + return failure("INVALID_ARGUMENT", "Run WORLDS before REALMS "); + connection.selectedScope = + required(lobbies) + .realms(original, result, connection, connection.menu, request.worldSelector()); + return success(connection.selectedScope.publicTarget().realmDisplayName()); + }); } case JOIN -> { var request = command.joinRequestPayload().orElse(null); @@ -88,24 +86,23 @@ public TextCommandInterpretationResult receive(WebSocketSession socket, TextComm || request.worldSelector() == null || request.worldSelector().isBlank()) yield failure("INVALID_ARGUMENT", "Usage: JOIN "); - yield connection.withLogin( - (original, result) -> { - if (connection.menu == null || connection.selectedScope == null) - return failure( - "INVALID_ARGUMENT", "Run WORLDS and REALMS before JOIN "); - var selected = - required(selections) - .resolve(connection.menu, request.worldSelector()) - .orElseThrow(); - if (!selected.equals(connection.selectedScope.publicTarget())) - return failure( - "INVALID_ARGUMENT", "Use REALMS before JOIN of a different world"); - var observation = required(lobbies).join(original, result, connection); - if (observation.status() - != DirectTextAuthenticatedLobbyOwner.Status.COMPLETED_CURRENT_NON_ADMITTING - || observation.currentReply().isEmpty()) throw new IllegalStateException(); - return success("Joined public production realm"); - }); + yield connection.withLogin((original, result) -> { + if (connection.menu == null || connection.selectedScope == null) + return failure( + "INVALID_ARGUMENT", "Run WORLDS and REALMS before JOIN "); + var selected = + required(selections) + .resolve(connection.menu, request.worldSelector()) + .orElseThrow(); + if (!selected.equals(connection.selectedScope.publicTarget())) + return failure( + "INVALID_ARGUMENT", "Use REALMS before JOIN of a different world"); + var observation = required(lobbies).join(original, result, connection); + if (observation.status() + != DirectTextAuthenticatedLobbyOwner.Status.COMPLETED_CURRENT_NON_ADMITTING + || observation.currentReply().isEmpty()) throw new IllegalStateException(); + return success("Joined public production realm"); + }); } // LOGIN and JOIN are not admission. Until the canonical binding owner is qualified, the // retired numeric entitlement route must never be selected by this protected receiver. diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java index ea5812f051..741fdc5fb2 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessions.java @@ -163,18 +163,17 @@ public T withLogin( requireLive(); InitialGameplayLoginOwner.Outcome owned = outcome; if (owned == null) throw new LoginRequiredException(); - return owned.withOwnedPrivateResult( - result -> { - if (borrowed.putIfAbsent(Thread.currentThread(), result) != null) throw unavailable(); - try { - requireLive(); - T answer = action.apply(owned.coordinates(), result); - requireLive(); - return answer; - } finally { - borrowed.remove(Thread.currentThread(), result); - } - }); + return owned.withOwnedPrivateResult(result -> { + if (borrowed.putIfAbsent(Thread.currentThread(), result) != null) throw unavailable(); + try { + requireLive(); + T answer = action.apply(owned.coordinates(), result); + requireLive(); + return answer; + } finally { + borrowed.remove(Thread.currentThread(), result); + } + }); } finally { lifetime.readLock().unlock(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java index 051caf713f..0cd9cd441a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java @@ -193,16 +193,15 @@ public void afterConnectionClosed(WebSocketSession session, CloseStatus status) return; } parseNumericSessionId(resolveTransportSessionId(session)) - .ifPresent( - sessionId -> { - if (!activeTransportSessionRegistry.unregister(sessionId, session)) { - return; - } - firstPartyConnectContextRegistry.unregister(sessionId); - promptBurstCoordinator.evict(Long.toString(sessionId)); - gameplayPresenceLifecycleService.recordDisconnected( - sessionId, AccountRecentPresenceDisposition.TRANSPORT_LOSS); - }); + .ifPresent(sessionId -> { + if (!activeTransportSessionRegistry.unregister(sessionId, session)) { + return; + } + firstPartyConnectContextRegistry.unregister(sessionId); + promptBurstCoordinator.evict(Long.toString(sessionId)); + gameplayPresenceLifecycleService.recordDisconnected( + sessionId, AccountRecentPresenceDisposition.TRANSPORT_LOSS); + }); } @Override @@ -321,11 +320,10 @@ private boolean ownsActiveTransport(String sessionId, WebSocketSession session) try { return parseNumericSessionId(sessionId) .flatMap(activeTransportSessionRegistry::find) - .map( - registered -> - registered == session - || registered instanceof WebSocketSessionDecorator decorator - && decorator.getDelegate() == session) + .map(registered -> + registered == session + || registered instanceof WebSocketSessionDecorator decorator + && decorator.getDelegate() == session) .orElse(false); } catch (RuntimeException unavailable) { return false; @@ -528,11 +526,10 @@ private void recordGameplayActivity( return; } parseNumericSessionId(sessionId) - .ifPresent( - numericSessionId -> { - gameplayPresenceLifecycleService.recordActivity( - numericSessionId, interpretation.meaningfulGameplayActivity()); - }); + .ifPresent(numericSessionId -> { + gameplayPresenceLifecycleService.recordActivity( + numericSessionId, interpretation.meaningfulGameplayActivity()); + }); } private void maybeAppendToScreenBuffer( @@ -549,13 +546,12 @@ private void maybeAppendToScreenBuffer( } maybeContext .filter(SessionContext::hasGameplayIdentity) - .ifPresent( - context -> - screenBufferService.append( - context.tenantId(), - context.gameInstanceId(), - context.characterId(), - replayEntries)); + .ifPresent(context -> + screenBufferService.append( + context.tenantId(), + context.gameInstanceId(), + context.characterId(), + replayEntries)); } private void maybeRefreshReconnectLook( @@ -575,32 +571,28 @@ private void maybeRefreshReconnectLook( } maybeContext .filter(SessionContext::hasGameplayIdentity) - .ifPresent( - context -> { - try (GameplayLoggingContext ignored = GameplayLoggingContext.from(context)) { - // Private retained context stays closed until current generation, episode, - // and authorization evidence is qualified end to end. Retention is unchanged; - // reconnect recommendations and connect contexts alone are not replay authority. - String localeTag = resolveLocaleTag(session, sessionId); - PresentationProperties effectivePresentation = - settingsResolver.presentation(context); - PlayerOutput look = renderReconnectLook(sessionId); - if (look != null) { - sendProjectedOutput( - session, look, localeTag, effectivePresentation, "fresh LOOK"); - } - if (effectivePresentation.prompt().enabled() - && effectivePresentation.prompt().emitAfterReconnectRestore()) { - composePrompt(context) - .ifPresent( - prompt -> { - sendProjectedOutput( - session, prompt, localeTag, effectivePresentation, "fresh prompt"); - promptBurstCoordinator.recordPromptEmission(sessionId); - }); - } - } - }); + .ifPresent(context -> { + try (GameplayLoggingContext ignored = GameplayLoggingContext.from(context)) { + // Private retained context stays closed until current generation, episode, + // and authorization evidence is qualified end to end. Retention is unchanged; + // reconnect recommendations and connect contexts alone are not replay authority. + String localeTag = resolveLocaleTag(session, sessionId); + PresentationProperties effectivePresentation = settingsResolver.presentation(context); + PlayerOutput look = renderReconnectLook(sessionId); + if (look != null) { + sendProjectedOutput(session, look, localeTag, effectivePresentation, "fresh LOOK"); + } + if (effectivePresentation.prompt().enabled() + && effectivePresentation.prompt().emitAfterReconnectRestore()) { + composePrompt(context) + .ifPresent(prompt -> { + sendProjectedOutput( + session, prompt, localeTag, effectivePresentation, "fresh prompt"); + promptBurstCoordinator.recordPromptEmission(sessionId); + }); + } + } + }); } private void sendProjectedOutput( @@ -709,28 +701,27 @@ private void maybePersistLocaleTag(Optional maybeContext, String } maybeContext .filter(context -> !StringUtils.hasText(context.localeTag())) - .ifPresent( - context -> - sessionContextService.save( - new SessionContext( - context.sessionId(), - context.tenantId(), - context.accountId(), - context.loginName(), - context.characterId(), - context.characterName(), - context.gameInstanceId(), - context.roomInstanceId(), - context.jwt(), - localeTag, - context.bootstrapGameInstanceId(), - context.worldSlug(), - context.realmSlug(), - context.pointerVersion(), - context.playableStateScope(), - context.connectScopeId(), - context.connectRequestId(), - context.firstPartyConnectContext()))); + .ifPresent(context -> + sessionContextService.save( + new SessionContext( + context.sessionId(), + context.tenantId(), + context.accountId(), + context.loginName(), + context.characterId(), + context.characterName(), + context.gameInstanceId(), + context.roomInstanceId(), + context.jwt(), + localeTag, + context.bootstrapGameInstanceId(), + context.worldSlug(), + context.realmSlug(), + context.pointerVersion(), + context.playableStateScope(), + context.connectScopeId(), + context.connectRequestId(), + context.firstPartyConnectContext()))); } private PlayerOutput renderReconnectLook(String sessionId) { diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java index 207129bfd2..6d76dd8cb8 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/CommunicationWebSocketCrossServiceTest.java @@ -103,14 +103,13 @@ void websocketSayFlowReportsCanonicalTranscriptAndMetrics() throws Exception { assertThat(responses) .anyMatch(response -> response.contains(ChatTestFixtures.canonicalSayText())); assertThat(socialStub().lastRequest()) - .hasValueSatisfying( - request -> { - assertThat(request.getSenderId()).isEqualTo(ACCOUNT_UUID); - assertThat(request.getContent()).isEqualTo("hello travelers"); - assertThat(request.getType()) - .isEqualTo(net.firedevops.firemud.socialgroups.v1.ChatType.CHAT_TYPE_SAY); - assertThat(request.getEffectId()).isNotBlank(); - }); + .hasValueSatisfying(request -> { + assertThat(request.getSenderId()).isEqualTo(ACCOUNT_UUID); + assertThat(request.getContent()).isEqualTo("hello travelers"); + assertThat(request.getType()) + .isEqualTo(net.firedevops.firemud.socialgroups.v1.ChatType.CHAT_TYPE_SAY); + assertThat(request.getEffectId()).isNotBlank(); + }); GameplayAsyncAssertions.assertMetricEventually( gameSession().bean(io.micrometer.core.instrument.MeterRegistry.class), @@ -207,12 +206,11 @@ void websocketFriendsShowsCanonicalCrossGamePresence() throws Exception { assertThat(responses).hasSizeGreaterThanOrEqualTo(3); assertThat(responses) - .anyMatch( - response -> - response.contains( - "Sora [acct #" - + SORA_ACCOUNT_UUID - + "] - online in Demo World / Live Realm (idle)")); + .anyMatch(response -> + response.contains( + "Sora [acct #" + + SORA_ACCOUNT_UUID + + "] - online in Demo World / Live Realm (idle)")); GameplaySocialAssertions.assertListFriendsRequest( socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), ACCOUNT_UUID); } @@ -232,13 +230,12 @@ void websocketFriendsOnlineFiltersCanonicalRoster() throws Exception { + "] - online in Demo World / Live Realm (idle)"); assertThat(responses) - .anyMatch( - response -> - response.contains("Friends ONLINE [1/1]:") - && response.contains( - "1) Sora [acct #" - + SORA_ACCOUNT_UUID - + "] - online in Demo World / Live Realm (idle)")); + .anyMatch(response -> + response.contains("Friends ONLINE [1/1]:") + && response.contains( + "1) Sora [acct #" + + SORA_ACCOUNT_UUID + + "] - online in Demo World / Live Realm (idle)")); GameplaySocialAssertions.assertListFriendsRequest( socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), @@ -261,13 +258,12 @@ void websocketFriendsSharedFiltersCanonicalRoster() throws Exception { + "] - online in Demo World / Live Realm (idle)"); assertThat(responses) - .anyMatch( - response -> - response.contains("Friends SHARED [1/1]:") - && response.contains( - "1) Sora [acct #" - + SORA_ACCOUNT_UUID - + "] - online in Demo World / Live Realm (idle)")); + .anyMatch(response -> + response.contains("Friends SHARED [1/1]:") + && response.contains( + "1) Sora [acct #" + + SORA_ACCOUNT_UUID + + "] - online in Demo World / Live Realm (idle)")); GameplaySocialAssertions.assertListFriendsRequest( socialStub().lastFriendsRequest(), Long.toString(TENANT_ID), @@ -289,12 +285,11 @@ void freshGameplayBaselineReappliesConfiguredFriendPresenceBaseline() throws Exc "Sora [acct #" + SORA_ACCOUNT_UUID + "] - online in Demo World / Live Realm (idle)"); assertThat(responses) - .anyMatch( - response -> - response.contains( - "Sora [acct #" - + SORA_ACCOUNT_UUID - + "] - online in Demo World / Live Realm (idle)")); + .anyMatch(response -> + response.contains( + "Sora [acct #" + + SORA_ACCOUNT_UUID + + "] - online in Demo World / Live Realm (idle)")); } @Test diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java index 8ebb849be2..6045f1ee7e 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java @@ -95,14 +95,13 @@ void websocketQuickLookOmitsLongDescriptionButKeepsPrompt() throws Exception { assertThat(responses.get(0)).startsWith("OK LOGIN"); assertThat(responses.get(1)).startsWith("OK PLAY"); assertThat(responses) - .anyMatch( - response -> - response.startsWith("OK QUICKLOOK") - && response.contains("Room: Candle-lit Antechamber") - && response.contains("Short:") - && !response.contains("Long:") - && response.endsWith( - GameplayWebSocketScenarios.DEFAULT_DEMO_CHARACTER_NAME + "> ")); + .anyMatch(response -> + response.startsWith("OK QUICKLOOK") + && response.contains("Room: Candle-lit Antechamber") + && response.contains("Short:") + && !response.contains("Long:") + && response.endsWith( + GameplayWebSocketScenarios.DEFAULT_DEMO_CHARACTER_NAME + "> ")); } @Test @@ -135,10 +134,9 @@ void websocketStatusProjectsAuthoritativeActorStateThroughGameLogic() throws Exc client.awaitStartsWith("OK STATUS"); assertThat(client.responses()) - .anyMatch( - response -> - response.contains("Status:\n- armour_value: 12\n- health: 105/90") - && response.contains("Conditions:\n- blessed")); + .anyMatch(response -> + response.contains("Status:\n- armour_value: 12\n- health: 105/90") + && response.contains("Conditions:\n- blessed")); } } @@ -153,17 +151,15 @@ void websocketMovementReturnsDestinationLookAndPersistsRoomContext() throws Exce assertThat(responses.get(0)).startsWith("OK LOGIN"); assertThat(responses.get(1)).startsWith("OK PLAY"); assertThat(responses) - .anyMatch( - response -> - GameplayTranscriptMatchers.matchesCanonicalMoveRefreshWithOptionalPrompt( - LookTestFixtures.DESTINATION_ROOM_ID) - .test(response.trim())); + .anyMatch(response -> + GameplayTranscriptMatchers.matchesCanonicalMoveRefreshWithOptionalPrompt( + LookTestFixtures.DESTINATION_ROOM_ID) + .test(response.trim())); assertThat(responses) - .anyMatch( - response -> - GameplayTranscriptMatchers.matchesCanonicalLookWithOptionalPrompt( - LookTestFixtures.DESTINATION_ROOM_ID) - .test(response.trim())); + .anyMatch(response -> + GameplayTranscriptMatchers.matchesCanonicalLookWithOptionalPrompt( + LookTestFixtures.DESTINATION_ROOM_ID) + .test(response.trim())); assertThat(responses).anyMatch(response -> response.startsWith("ERROR INVALID_EXIT")); } @@ -178,11 +174,10 @@ void websocketReconnectAfterMoveKeepsDestinationRoomContext() throws Exception { assertThat(firstConnection).anyMatch(response -> response.startsWith("OK LOGIN")); assertThat(firstConnection).anyMatch(response -> response.startsWith("OK PLAY")); assertThat(firstConnection) - .anyMatch( - response -> - GameplayTranscriptMatchers.matchesCanonicalMoveOrLookWithOptionalPrompt( - LookTestFixtures.DESTINATION_ROOM_ID) - .test(response.trim())); + .anyMatch(response -> + GameplayTranscriptMatchers.matchesCanonicalMoveOrLookWithOptionalPrompt( + LookTestFixtures.DESTINATION_ROOM_ID) + .test(response.trim())); List reconnectLook = runLookAfterReconnect(sessionId, LookTestFixtures.DESTINATION_ROOM_ID); @@ -204,10 +199,9 @@ void websocketSecondConnectionTakesOverGameplayBinding() throws Exception { try (GameplayWebSocketDriver first = openReadySession(firstSessionId); GameplayWebSocketDriver second = openReadySession(secondSessionId)) { assertThat(first.responses()) - .anyMatch( - response -> - GameplayTranscriptMatchers.matchesCanonicalLookWithOptionalPrompt() - .test(response.trim())); + .anyMatch(response -> + GameplayTranscriptMatchers.matchesCanonicalLookWithOptionalPrompt() + .test(response.trim())); String combinedSecond = String.join("\n", second.responses()); assertThat(combinedSecond).contains("OK PLAY Entered world: demo"); @@ -240,11 +234,10 @@ void websocketMovedPlayerStaysInGameAcrossGameLogicRestart() throws Exception { .test(response.trim()), "destination move refresh"); assertThat(socket.responses()) - .anyMatch( - response -> - GameplayTranscriptMatchers.matchesCanonicalMoveRefreshWithOptionalPrompt( - LookTestFixtures.DESTINATION_ROOM_ID) - .test(response.trim())); + .anyMatch(response -> + GameplayTranscriptMatchers.matchesCanonicalMoveRefreshWithOptionalPrompt( + LookTestFixtures.DESTINATION_ROOM_ID) + .test(response.trim())); int gameLogicHttpPort = STACK.gameLogic().httpPort(); STACK.restartGameLogic(); @@ -262,14 +255,12 @@ void websocketMovedPlayerStaysInGameAcrossGameLogicRestart() throws Exception { .test(response.trim()), "destination look after restart"); assertThat(socket.responses()) - .matches( - responses -> - responses.stream() - .anyMatch( - response -> - GameplayTranscriptMatchers.matchesCanonicalLookWithOptionalPrompt( - LookTestFixtures.DESTINATION_ROOM_ID) - .test(response.trim()))); + .matches(responses -> + responses.stream() + .anyMatch(response -> + GameplayTranscriptMatchers.matchesCanonicalLookWithOptionalPrompt( + LookTestFixtures.DESTINATION_ROOM_ID) + .test(response.trim()))); } } @@ -286,11 +277,10 @@ void websocketReconnectDistinguishesActiveDenialFromInactiveRepair(boolean inact assertThat(firstConnection).anyMatch(response -> response.startsWith("OK LOGIN")); assertThat(firstConnection).anyMatch(response -> response.startsWith("OK PLAY")); assertThat(firstConnection) - .anyMatch( - response -> - GameplayTranscriptMatchers.matchesCanonicalMoveOrLookWithOptionalPrompt( - LookTestFixtures.DESTINATION_ROOM_ID) - .test(response.trim())); + .anyMatch(response -> + GameplayTranscriptMatchers.matchesCanonicalMoveOrLookWithOptionalPrompt( + LookTestFixtures.DESTINATION_ROOM_ID) + .test(response.trim())); if (inactive) { accountStub().setMembershipInactive(); @@ -318,11 +308,10 @@ void websocketReconnectAfterStaleSessionFreshEntersGameplay() throws Exception { assertThat(firstConnection).anyMatch(response -> response.startsWith("OK LOGIN")); assertThat(firstConnection).anyMatch(response -> response.startsWith("OK PLAY")); assertThat(firstConnection) - .anyMatch( - response -> - GameplayTranscriptMatchers.matchesCanonicalMoveOrLookWithOptionalPrompt( - LookTestFixtures.DESTINATION_ROOM_ID) - .test(response.trim())); + .anyMatch(response -> + GameplayTranscriptMatchers.matchesCanonicalMoveOrLookWithOptionalPrompt( + LookTestFixtures.DESTINATION_ROOM_ID) + .test(response.trim())); var contexts = gameSession().bean(net.firedevops.firemud.gamesession.service.SessionContextService.class); diff --git a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/MultiplayerLoadProofCrossServiceTest.java b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/MultiplayerLoadProofCrossServiceTest.java index 38927c2195..d24539457d 100644 --- a/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/MultiplayerLoadProofCrossServiceTest.java +++ b/services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/MultiplayerLoadProofCrossServiceTest.java @@ -70,28 +70,27 @@ void tenConcurrentPlayersCanLoginPlayAndLookAgainstRealCrossServiceStack() throw GameplayLoadScenarios.seedPlayers(STACK, TENANT_ID, 1L, ACCOUNT_ID_BASE, CLIENT_COUNT, 7L); URI uri = URI.create("ws://localhost:" + gameSession().port() + "/ws/game"); TimedResult> playerRuns = - timed( - () -> { - CountDownLatch start = new CountDownLatch(1); - ExecutorService executor = Executors.newFixedThreadPool(CLIENT_COUNT); - try { - List> futures = new ArrayList<>(); - for (GameplayLoadScenarios.PlayerSeed player : players) { - futures.add(executor.submit(() -> runPlayerSequence(uri, player, start))); - } - - start.countDown(); - - List results = new ArrayList<>(); - for (Future future : futures) { - results.add(future.get(COMMAND_WAIT.toSeconds(), TimeUnit.SECONDS)); - } - return results; - } finally { - executor.shutdownNow(); - executor.awaitTermination(5, TimeUnit.SECONDS); - } - }); + timed(() -> { + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(CLIENT_COUNT); + try { + List> futures = new ArrayList<>(); + for (GameplayLoadScenarios.PlayerSeed player : players) { + futures.add(executor.submit(() -> runPlayerSequence(uri, player, start))); + } + + start.countDown(); + + List results = new ArrayList<>(); + for (Future future : futures) { + results.add(future.get(COMMAND_WAIT.toSeconds(), TimeUnit.SECONDS)); + } + return results; + } finally { + executor.shutdownNow(); + executor.awaitTermination(5, TimeUnit.SECONDS); + } + }); assertCompletesWithin( "concurrent LOGIN -> PLAY -> LOOK entry", playerRuns.duration(), ENTRY_PHASE_BUDGET); @@ -99,28 +98,25 @@ void tenConcurrentPlayersCanLoginPlayAndLookAgainstRealCrossServiceStack() throw assertThat(results).hasSize(CLIENT_COUNT); assertThat(STACK.gameDesignStub().publishedReleaseBundleRequests()).isPositive(); assertThat(results) - .allSatisfy( - result -> { - assertThat(result.responses()) - .anyMatch(payload -> payload.startsWith("OK LOGIN")) - .anyMatch(payload -> payload.startsWith("OK PLAY")) - .anyMatch( - payload -> - payload.startsWith("OK LOOK") - && payload.contains("Room: Candle-lit Antechamber")); - assertThat(result.responses()).noneMatch(payload -> payload.startsWith("ERROR ")); - }); + .allSatisfy(result -> { + assertThat(result.responses()) + .anyMatch(payload -> payload.startsWith("OK LOGIN")) + .anyMatch(payload -> payload.startsWith("OK PLAY")) + .anyMatch(payload -> + payload.startsWith("OK LOOK") + && payload.contains("Room: Candle-lit Antechamber")); + assertThat(result.responses()).noneMatch(payload -> payload.startsWith("ERROR ")); + }); SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); for (GameplayLoadScenarios.PlayerSeed player : players) { assertThat(sessionContextService.findBySessionId(player.sessionId())) - .hasValueSatisfying( - context -> { - assertThat(context.tenantId()).isEqualTo(TENANT_ID); - assertThat(context.gameInstanceId()).isEqualTo(1L); - assertThat(context.characterId()).isEqualTo(player.accountId()); - assertThat(context.roomInstanceId()).isEqualTo(LookTestFixtures.ROOM_ID); - }); + .hasValueSatisfying(context -> { + assertThat(context.tenantId()).isEqualTo(TENANT_ID); + assertThat(context.gameInstanceId()).isEqualTo(1L); + assertThat(context.characterId()).isEqualTo(player.accountId()); + assertThat(context.roomInstanceId()).isEqualTo(LookTestFixtures.ROOM_ID); + }); } GameplayAsyncAssertions.assertMetricEventually( @@ -144,12 +140,11 @@ void tenConcurrentPlayersCanMoveNorthAfterConcurrentEntry() throws Exception { List connectedPlayers = readyPlayers.result(); try { TimedResult followUp = - timed( - () -> { - runConcurrentNorthMovement(connectedPlayers); - runConcurrentDestinationLook(connectedPlayers); - return null; - }); + timed(() -> { + runConcurrentNorthMovement(connectedPlayers); + runConcurrentDestinationLook(connectedPlayers); + return null; + }); assertCompletesWithin( "concurrent north movement plus destination LOOK churn", followUp.duration(), @@ -158,10 +153,9 @@ void tenConcurrentPlayersCanMoveNorthAfterConcurrentEntry() throws Exception { SessionContextService sessionContextService = gameSession().bean(SessionContextService.class); for (PlayerSessionDriver connectedPlayer : connectedPlayers) { assertThat(sessionContextService.findBySessionId(connectedPlayer.player().sessionId())) - .hasValueSatisfying( - context -> - assertThat(context.roomInstanceId()) - .isEqualTo(LookTestFixtures.DESTINATION_ROOM_ID)); + .hasValueSatisfying(context -> + assertThat(context.roomInstanceId()) + .isEqualTo(LookTestFixtures.DESTINATION_ROOM_ID)); } GameplayAsyncAssertions.assertMetricEventually( @@ -190,28 +184,25 @@ void tenConcurrentPlayersCanBroadcastSayAfterConcurrentEntry() throws Exception List connectedPlayers = readyPlayers.result(); try { TimedResult followUp = - timed( - () -> { - runConcurrentSayBurst(connectedPlayers); - return null; - }); + timed(() -> { + runConcurrentSayBurst(connectedPlayers); + return null; + }); assertCompletesWithin( "concurrent SAY broadcast burst", followUp.duration(), FOLLOW_UP_PHASE_BUDGET); - connectedPlayers.forEach( - connectedPlayer -> - assertThat(connectedPlayer.driver().responses()) - .noneMatch(payload -> payload.startsWith("ERROR "))); + connectedPlayers.forEach(connectedPlayer -> + assertThat(connectedPlayer.driver().responses()) + .noneMatch(payload -> payload.startsWith("ERROR "))); SocialGroupsStubServer socialStub = STACK.socialStub(); assertThat(socialStub.messageRequests()).hasSize(CLIENT_COUNT); assertThat(socialStub.messageRequests()) - .allSatisfy( - request -> { - assertThat(request.getTenantId()).isEqualTo(Long.toString(TENANT_ID)); - assertThat(request.getType()) - .isEqualTo(net.firedevops.firemud.socialgroups.v1.ChatType.CHAT_TYPE_SAY); - }); + .allSatisfy(request -> { + assertThat(request.getTenantId()).isEqualTo(Long.toString(TENANT_ID)); + assertThat(request.getType()) + .isEqualTo(net.firedevops.firemud.socialgroups.v1.ChatType.CHAT_TYPE_SAY); + }); assertThat( socialStub.messageRequests().stream() .map(request -> request.getContent()) @@ -324,11 +315,10 @@ private List runConcurrently(List items, ConcurrentTask task) List> futures = new ArrayList<>(); for (T item : items) { futures.add( - executor.submit( - () -> { - assertThat(start.await(COMMAND_WAIT.toSeconds(), TimeUnit.SECONDS)).isTrue(); - return task.run(item); - })); + executor.submit(() -> { + assertThat(start.await(COMMAND_WAIT.toSeconds(), TimeUnit.SECONDS)).isTrue(); + return task.run(item); + })); } start.countDown(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java index be39976aa0..36c648c872 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java @@ -220,47 +220,42 @@ void startSessionUsesRealHttpAndPersistencePath() throws Exception { anyString(), anyLong(), any())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse.newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setGameTemplateId(Long.toString(invocation.getArgument(2, Long.class))) - .setControlPlaneRequestId(invocation.getArgument(3, String.class)) - .setLaunchDescriptorId(invocation.getArgument(4, String.class)) - .setVersionId(Long.toString(invocation.getArgument(5, Long.class))) - .setReleaseBundleId( - Long.toString(invocation.getArgument(9, Long.class))) - .setGenerationConfigRevision(invocation.getArgument(8, String.class)) - .setPublishedReleaseBundleRef(invocation.getArgument(10, String.class)) - .setVersionStateEpoch(invocation.getArgument(11, Long.class)) - .setLifecycleEpoch(1L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) - .build()) - .build()); + .thenAnswer(invocation -> + net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse.newBuilder() + .setWorldInstance( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot + .newBuilder() + .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) + .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) + .setGameTemplateId(Long.toString(invocation.getArgument(2, Long.class))) + .setControlPlaneRequestId(invocation.getArgument(3, String.class)) + .setLaunchDescriptorId(invocation.getArgument(4, String.class)) + .setVersionId(Long.toString(invocation.getArgument(5, Long.class))) + .setReleaseBundleId(Long.toString(invocation.getArgument(9, Long.class))) + .setGenerationConfigRevision(invocation.getArgument(8, String.class)) + .setPublishedReleaseBundleRef(invocation.getArgument(10, String.class)) + .setVersionStateEpoch(invocation.getArgument(11, Long.class)) + .setLifecycleEpoch(1L) + .setStatus( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus + .WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) + .build()) + .build()); when(worldManagementClient.activatePreparedWorldInstance(anyLong(), anyLong(), anyLong())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse - .newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setLifecycleEpoch(invocation.getArgument(2, Long.class) + 1L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) - .build()) - .build()); + .thenAnswer(invocation -> + net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse + .newBuilder() + .setWorldInstance( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot + .newBuilder() + .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) + .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) + .setLifecycleEpoch(invocation.getArgument(2, Long.class) + 1L) + .setStatus( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus + .WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) + .build()) + .build()); StartSessionRequest request = new StartSessionRequest(42L, 7L, "cp-1", 100L); String responseBody = diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java index a5f4e7e47a..755425f887 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java @@ -167,11 +167,10 @@ void loginCallsAccountServiceAndReturnsOk() throws Exception { @SuppressWarnings("unchecked") private static void stubTransactionExecution(RedisTemplate redisTemplate) { when(redisTemplate.execute(org.mockito.Mockito.any(SessionCallback.class))) - .thenAnswer( - invocation -> { - SessionCallback callback = invocation.getArgument(0); - return callback.execute((RedisOperations) redisTemplate); - }); + .thenAnswer(invocation -> { + SessionCallback callback = invocation.getArgument(0); + return callback.execute((RedisOperations) redisTemplate); + }); when(redisTemplate.exec()).thenReturn(List.of("OK")); } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java index a0c873643b..e09fc88567 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/charactercreate/PlayerCreatedRosterOwnerCompositionIntegrationTest.java @@ -186,11 +186,9 @@ void actualCreatedTerminalCrossesAuthenticatedOwnersAndReplaysTheImmutableOrigin .containsExactly(originalBytes); // A caller-selected actor absent from the actual frozen menu cannot become a receipt. - assertThatThrownBy( - () -> - owners.roster.readSelectedPlayerCreatedCharacter( - replay, - context.toBuilder().setCharacterId(UUID.randomUUID().toString()).build())) + assertThatThrownBy(() -> + owners.roster.readSelectedPlayerCreatedCharacter( + replay, context.toBuilder().setCharacterId(UUID.randomUUID().toString()).build())) .isInstanceOf(IllegalArgumentException.class); assertThat(owners.gs.referenceOwner().read(menu.originalSelection()).toByteArray()) .containsExactly(originalBytes); @@ -299,16 +297,15 @@ void completeOneActorSelectionMeasuresActualCreatedOwnerEntrypoint() throws Exce assertThat(owners.gs.referenceOwner().retireTarget(originalRequest)).isFalse(); Awaitility.await() .atMost(Duration.ofSeconds(30)) - .untilAsserted( - () -> - assertThat( - owners - .gsDsl - .fetchSingle( - "SELECT s.terminal_at + f.minimum_retention_millis * interval '1 millisecond' <= clock_timestamp() FROM game_session_canonical_roster_selection s JOIN game_session_canonical_roster_target_fences f USING (target_fence_uuid) WHERE s.operation_uuid = ?", - UUID.fromString(originalRequest.getOperationUuid())) - .get(0, Boolean.class)) - .isTrue()); + .untilAsserted(() -> + assertThat( + owners + .gsDsl + .fetchSingle( + "SELECT s.terminal_at + f.minimum_retention_millis * interval '1 millisecond' <= clock_timestamp() FROM game_session_canonical_roster_selection s JOIN game_session_canonical_roster_target_fences f USING (target_fence_uuid) WHERE s.operation_uuid = ?", + UUID.fromString(originalRequest.getOperationUuid())) + .get(0, Boolean.class)) + .isTrue()); // Only the later successor reader is controlled. The original/fence/transfer SQL is real. assertThat(owners.retireWithControlledSuccessor(originalRequest)).isTrue(); var retired = owners.gs.referenceOwner().read(originalRequest); @@ -394,19 +391,16 @@ void completeOneActorSelectionMeasuresActualCreatedOwnerEntrypoint() throws Exce if (!maximum) { for (var deniedClient : List.of(owners.wrongRoleOriginalClient, owners.wrongNamespaceOriginalClient)) { - assertThatThrownBy( - () -> - deniedClient.acknowledgeCanonicalGameplayRosterRetirement( - acknowledgementRequest)) + assertThatThrownBy(() -> + deniedClient.acknowledgeCanonicalGameplayRosterRetirement(acknowledgementRequest)) .isInstanceOfSatisfying( StatusRuntimeException.class, failure -> assertThat(failure.getStatus().getCode()) .isEqualTo(Status.Code.PERMISSION_DENIED)); - assertThatThrownBy( - () -> - deniedClient.confirmCanonicalGameplayRosterRetirementAcknowledgement( - confirmationRequest)) + assertThatThrownBy(() -> + deniedClient.confirmCanonicalGameplayRosterRetirementAcknowledgement( + confirmationRequest)) .isInstanceOfSatisfying( StatusRuntimeException.class, failure -> @@ -437,12 +431,11 @@ void completeOneActorSelectionMeasuresActualCreatedOwnerEntrypoint() throws Exce .isEqualTo( CanonicalGameplayRosterRetirementEvidence.confirmationResponse(confirmationRequest)); Boolean recordedConfirmation = - entityTransactions.execute( - ignored -> - owners - .entity - .retentionRepository() - .recordRetirementConfirmation(transfer, confirmation)); + entityTransactions.execute(ignored -> + owners + .entity + .retentionRepository() + .recordRetirementConfirmation(transfer, confirmation)); assertThat(recordedConfirmation).isTrue(); assertThat( owners @@ -743,16 +736,15 @@ private int rpcCount(String method) { private void requireDeadline(String method, long seconds) { assertThat(rpcObservations.stream().filter(call -> call.method().equals(method)).toList()) .isNotEmpty() - .allSatisfy( - call -> { - assertThat(call.remainingMillis()).isPositive(); - assertThat(call.remainingMillis()) - .isLessThanOrEqualTo(TimeUnit.SECONDS.toMillis(seconds)); - if (seconds == 20) { - // The outer call reaches Entity with room for both nested owner RPCs. - assertThat(call.remainingMillis()).isGreaterThan(10_000L); - } - }); + .allSatisfy(call -> { + assertThat(call.remainingMillis()).isPositive(); + assertThat(call.remainingMillis()) + .isLessThanOrEqualTo(TimeUnit.SECONDS.toMillis(seconds)); + if (seconds == 20) { + // The outer call reaches Entity with room for both nested owner RPCs. + assertThat(call.remainingMillis()).isGreaterThan(10_000L); + } + }); } private PlayerExecutionContext context(UUID account) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientMtlsIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientMtlsIntegrationTest.java index 8e1462fdfd..396ceb9ad2 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientMtlsIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientMtlsIntegrationTest.java @@ -128,10 +128,9 @@ void wrongWorkloadAndNamespacePeersReceiveNoResolveRpc() throws Exception { assertThatThrownBy( () -> client.resolveCreation(CREATION_REQUEST_ID, expected.requestDigest())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(rpcStarts).hasValue(0); assertThat(applicationCalls).hasValue(0); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreIntegrationTest.java index a8fd808577..0dc656ffee 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreIntegrationTest.java @@ -198,11 +198,10 @@ void oneFreshCompositionRetainsPhysicalMenuWhileLaterUsesRestoreFreshSources() { var fixture = fixture(Clock.systemUTC()); var reads = new AtomicInteger(); var catalog = - GameplayWorldCatalog.forWorldSupplier( - () -> { - reads.incrementAndGet(); - return List.of(world(fixture.targets().get(1)), world(fixture.targets().get(0))); - }); + GameplayWorldCatalog.forWorldSupplier(() -> { + reads.incrementAndGet(); + return List.of(world(fixture.targets().get(1)), world(fixture.targets().get(0))); + }); var selection = new DirectTextWorldSelectionService(catalog, fixture.routes(), fixture.clock()); var store = store(selection, fixture.clock()); var transport = observation(); @@ -489,13 +488,12 @@ public Collection descriptors() { return List.of(mismatched); } })); - assertThatThrownBy( - () -> - new DirectTextWorldMenuRedisStore( - selection, - fixture.clock(), - () -> writer.connect(ByteArrayCodec.INSTANCE), - badCatalog)) + assertThatThrownBy(() -> + new DirectTextWorldMenuRedisStore( + selection, + fixture.clock(), + () -> writer.connect(ByteArrayCodec.INSTANCE), + badCatalog)) .isInstanceOf(IllegalStateException.class); assertThat(admin.get(key(transport))).isNull(); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/AccountInitialAdmissionSettlementPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/AccountInitialAdmissionSettlementPostgresIntegrationTest.java index fbac0a5e5e..4777b3e472 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/AccountInitialAdmissionSettlementPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/AccountInitialAdmissionSettlementPostgresIntegrationTest.java @@ -180,30 +180,27 @@ void retainedLegacyCommitRemainsReadableButCannotAcquireOrSettleUnrecordedAccoun presented.originalSourceCaptureReferenceBytes(), presented.originalSourceCaptureReferenceSha256(), presented.sourceEvidenceVector()); - assertThatThrownBy( - () -> - owner.read( - new AccountInitialAdmissionSettlementReadInput( - input.readRequestId(), changed))) + assertThatThrownBy(() -> + owner.read( + new AccountInitialAdmissionSettlementReadInput(input.readRequestId(), changed))) .isInstanceOf( AccountInitialAdmissionSettlementReadService.SettlementUnavailableException.class); // Installed terminal immutability must reject historical adoption, even with complete bytes. - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_session_canonical_initial_admission_attempt SET account_protection_evidence_version = 1, " - + "account_protection_id = ?, account_protection_fence = ?, original_owner_attempt_id = ?, " - + "original_owner_mutation_id = ?, original_owner_fence = ?, account_protection_evidence_bytes = ? " - + "WHERE target_namespace = ? AND initial_admission_request_id = ?", - presented.accountProtectionId(), - presented.accountProtectionFence(), - original.ownerAttemptId(), - original.ownerMutationId(), - original.ownerFence(), - presented.canonicalBytes(), - namespace, - legacy.initialAdmissionRequestId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_session_canonical_initial_admission_attempt SET account_protection_evidence_version = 1, " + + "account_protection_id = ?, account_protection_fence = ?, original_owner_attempt_id = ?, " + + "original_owner_mutation_id = ?, original_owner_fence = ?, account_protection_evidence_bytes = ? " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + presented.accountProtectionId(), + presented.accountProtectionFence(), + original.ownerAttemptId(), + original.ownerMutationId(), + original.ownerFence(), + presented.canonicalBytes(), + namespace, + legacy.initialAdmissionRequestId())) .isInstanceOfSatisfying( DataAccessException.class, failure -> assertThat(failure.sqlState()).isEqualTo("23514")); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java index c0458cafa3..55af10e019 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java @@ -93,31 +93,29 @@ void intentRetryRestartAndNewPrepareUseOneFrozenActualOwnerCohort() { CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.REGION_OBLIGATION); assertThat(intent.barrierTargets()) .singleElement() - .satisfies( - target -> { - assertThat(target.tenantId()).isEqualTo(TENANT_ID); - assertThat(target.playableStateNamespaceId()).isEqualTo(NAMESPACE_ID); - }); + .satisfies(target -> { + assertThat(target.tenantId()).isEqualTo(TENANT_ID); + assertThat(target.playableStateNamespaceId()).isEqualTo(NAMESPACE_ID); + }); assertNoInstalledOrCoverageClaim(testSchema.dsl(), intent); var originalCohortRow = intent.cohortRows().get(0); - assertThatThrownBy( - () -> - testSchema - .dsl() - .execute( - "INSERT INTO" - + " game_session_canonical_account_admission_fence_intent_cohort_row" - + " (operation_id, account_id, row_ordinal, source_kind, source_key," - + " tenant_id, playable_state_namespace_id, source_row)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, CAST(? AS jsonb))", - intent.operationId(), - intent.accountId(), - intent.cohortRows().size() + 1L, - originalCohortRow.kind().name(), - originalCohortRow.sourceKey(), - originalCohortRow.tenantId(), - originalCohortRow.playableStateNamespaceId(), - originalCohortRow.sourceRecordJson())) + assertThatThrownBy(() -> + testSchema + .dsl() + .execute( + "INSERT INTO" + + " game_session_canonical_account_admission_fence_intent_cohort_row" + + " (operation_id, account_id, row_ordinal, source_kind, source_key," + + " tenant_id, playable_state_namespace_id, source_row)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, CAST(? AS jsonb))", + intent.operationId(), + intent.accountId(), + intent.cohortRows().size() + 1L, + originalCohortRow.kind().name(), + originalCohortRow.sourceKey(), + originalCohortRow.tenantId(), + originalCohortRow.playableStateNamespaceId(), + originalCohortRow.sourceRecordJson())) .isInstanceOfSatisfying( org.jooq.exception.DataAccessException.class, failure -> assertThat(failure.sqlState()).isEqualTo("23505")); @@ -199,11 +197,10 @@ void intentCapturesEveryExistingTenantNamespaceForTheAccountOnly() { assertThat(otherAccountIntent.accountId()).isEqualTo(OTHER_ACCOUNT_ID); assertThat(otherAccountIntent.barrierTargets()) .singleElement() - .satisfies( - target -> { - assertThat(target.tenantId()).isEqualTo(OTHER_TENANT_ID); - assertThat(target.playableStateNamespaceId()).isEqualTo(OTHER_NAMESPACE_ID); - }); + .satisfies(target -> { + assertThat(target.tenantId()).isEqualTo(OTHER_TENANT_ID); + assertThat(target.playableStateNamespaceId()).isEqualTo(OTHER_NAMESPACE_ID); + }); assertThat(otherAccountIntent.cohortRows()) .filteredOn( row -> row.kind() == CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.BINDING) @@ -229,32 +226,28 @@ void pendingInitialAccountTargetIsFrozenIntoCutoffAndItsTargetSet() { .beginFenceIntent(ACCOUNT_ID, UUID.randomUUID()); assertThat(cutoff.cohortRows()) - .anySatisfy( - row -> { - assertThat(row.kind()) - .isEqualTo(CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIALIZER); - assertThat(row.sourceKey()).isEqualTo(initial.originalRequestId().toString()); - assertThat(row.sourceRecordJson()).contains(initial.initializerId().toString()); - }); + .anySatisfy(row -> { + assertThat(row.kind()) + .isEqualTo(CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIALIZER); + assertThat(row.sourceKey()).isEqualTo(initial.originalRequestId().toString()); + assertThat(row.sourceRecordJson()).contains(initial.initializerId().toString()); + }); assertThat(cutoff.cohortRows()) - .anySatisfy( - row -> { - assertThat(row.kind()) - .isEqualTo( - CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIAL_TARGET); - assertThat(row.sourceKey()).isEqualTo(initial.initializerId() + ":0"); - assertThat(row.tenantId()).isEqualTo(OTHER_TENANT_ID); - assertThat(row.playableStateNamespaceId()).isEqualTo(OTHER_NAMESPACE_ID); - }); + .anySatisfy(row -> { + assertThat(row.kind()) + .isEqualTo(CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIAL_TARGET); + assertThat(row.sourceKey()).isEqualTo(initial.initializerId() + ":0"); + assertThat(row.tenantId()).isEqualTo(OTHER_TENANT_ID); + assertThat(row.playableStateNamespaceId()).isEqualTo(OTHER_NAMESPACE_ID); + }); assertThat(cutoff.barrierTargets()) .extracting( CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget::tenantId, CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget::playableStateNamespaceId) .contains(org.assertj.core.groups.Tuple.tuple(OTHER_TENANT_ID, OTHER_NAMESPACE_ID)); - assertThatThrownBy( - () -> - insertControlledInitialTarget( - testSchema.dsl(), ACCOUNT_ID, TENANT_ID, OTHER_NAMESPACE_ID)) + assertThatThrownBy(() -> + insertControlledInitialTarget( + testSchema.dsl(), ACCOUNT_ID, TENANT_ID, OTHER_NAMESPACE_ID)) .isInstanceOfSatisfying( org.jooq.exception.DataAccessException.class, failure -> assertThat(failure.sqlState()).isEqualTo("23514")); @@ -275,16 +268,14 @@ void accountCutoffThatWinsInventoryClockOrderBlocksAnInitialTargetInsert() { .beginFenceIntent(ACCOUNT_ID, UUID.randomUUID()); assertThat(cutoff.cohortRows()) - .noneSatisfy( - row -> - assertThat(row.kind()) - .isIn( - CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIALIZER, - CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIAL_TARGET)); - assertThatThrownBy( - () -> - insertControlledInitialTarget( - testSchema.dsl(), ACCOUNT_ID, OTHER_TENANT_ID, OTHER_NAMESPACE_ID)) + .noneSatisfy(row -> + assertThat(row.kind()) + .isIn( + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIALIZER, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIAL_TARGET)); + assertThatThrownBy(() -> + insertControlledInitialTarget( + testSchema.dsl(), ACCOUNT_ID, OTHER_TENANT_ID, OTHER_NAMESPACE_ID)) .isInstanceOfSatisfying( org.jooq.exception.DataAccessException.class, failure -> assertThat(failure.sqlState()).isEqualTo("23514")); @@ -318,11 +309,10 @@ void initialSourceRequiresPresentNoActiveControlAndPreservesItsActualEpochInclud UUID.randomUUID(), UUID.randomUUID(), 17L); var login = mockLoginResult(original, UUID.randomUUID(), UUID.randomUUID()); - assertThatThrownBy( - () -> - new CanonicalGameplayAccountInitialBarrierInitializerRepository( - missingControlSchema.dsl()) - .beginOrRead(original, login, OTHER_TENANT_ID, OTHER_NAMESPACE_ID)) + assertThatThrownBy(() -> + new CanonicalGameplayAccountInitialBarrierInitializerRepository( + missingControlSchema.dsl()) + .beginOrRead(original, login, OTHER_TENANT_ID, OTHER_NAMESPACE_ID)) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("Account coverage control row is missing"); } finally { @@ -396,17 +386,15 @@ void preparationRacingIntentIsEitherCapturedOrRefused() throws Exception { var owner = new CanonicalGameplayAccountAdmissionBarrierRepository(testSchema.dsl()); CountDownLatch start = new CountDownLatch(1); Future prepareFuture = - executor.submit( - () -> { - start.await(); - return prepare(inventory, ACCOUNT_ID, OTHER_TENANT_ID, OTHER_NAMESPACE_ID, 2); - }); + executor.submit(() -> { + start.await(); + return prepare(inventory, ACCOUNT_ID, OTHER_TENANT_ID, OTHER_NAMESPACE_ID, 2); + }); Future intentFuture = - executor.submit( - () -> { - start.await(); - return owner.beginFenceIntent(ACCOUNT_ID, UUID.randomUUID()); - }); + executor.submit(() -> { + start.await(); + return owner.beginFenceIntent(ACCOUNT_ID, UUID.randomUUID()); + }); start.countDown(); var intent = intentFuture.get(30, TimeUnit.SECONDS); @@ -590,60 +578,59 @@ private static ControlledInitialTarget insertControlledInitialTarget( UUID tokenJti = UUID.randomUUID(); String accountEvidenceDigest = "sha256:" + "a".repeat(64); String sourceControlDigest = "sha256:" + "b".repeat(64); - dsl.transaction( - configuration -> { - var transaction = org.jooq.impl.DSL.using(configuration); - var inventoryClock = - transaction.fetchOne( - "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock" - + " WHERE singleton_id = 1 FOR UPDATE"); - var control = - transaction.fetchOne( - "SELECT state, last_operation_fence FROM" - + " game_session_canonical_account_coverage_control" - + " WHERE account_id = ? FOR UPDATE", - accountId); - if (inventoryClock == null || control == null) { - throw new IllegalStateException("Controlled source lacks positive SQL owners"); - } - transaction.execute( - "INSERT INTO game_session_initial_gameplay_login_journal" - + " (request_id, caller_context_id, expected_attempt_fence) VALUES (?, ?, 7)", - originalRequestId, - callerContextId); - transaction.execute( - "UPDATE game_session_initial_gameplay_login_journal" - + " SET verified_token_jti = ?, verified_token_sha256 = ?," - + " verified_token_generation = 1, verified_issuance_fence = 1" - + " WHERE request_id = ?", - tokenJti, - "c".repeat(64), - originalRequestId); - transaction.execute( - "INSERT INTO game_session_canonical_initial_account_barrier_initializer" - + " (initializer_id, original_request_id, original_caller_context_id," - + " original_attempt_fence, account_id, account_login_evidence_digest," - + " source_control_state, source_control_epoch, inventory_snapshot_revision," - + " source_control_digest) VALUES (?, ?, ?, 7, ?, ?, ?, 0, ?, ?)", - initializerId, - originalRequestId, - callerContextId, - accountId, - accountEvidenceDigest, - "NO_ACTIVE_ACCOUNT_WIDE_FLOW", - inventoryClock.get("inventory_revision"), - sourceControlDigest); - transaction.execute( - "INSERT INTO game_session_canonical_initial_account_barrier_target" - + " (initializer_id, original_request_id, account_id, target_ordinal, tenant_id," - + " playable_state_namespace_id, target_state)" - + " VALUES (?, ?, ?, 0, ?, ?, 'NEVER_DISPATCHED')", - initializerId, - originalRequestId, - accountId, - tenantId, - namespaceId); - }); + dsl.transaction(configuration -> { + var transaction = org.jooq.impl.DSL.using(configuration); + var inventoryClock = + transaction.fetchOne( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id = 1 FOR UPDATE"); + var control = + transaction.fetchOne( + "SELECT state, last_operation_fence FROM" + + " game_session_canonical_account_coverage_control" + + " WHERE account_id = ? FOR UPDATE", + accountId); + if (inventoryClock == null || control == null) { + throw new IllegalStateException("Controlled source lacks positive SQL owners"); + } + transaction.execute( + "INSERT INTO game_session_initial_gameplay_login_journal" + + " (request_id, caller_context_id, expected_attempt_fence) VALUES (?, ?, 7)", + originalRequestId, + callerContextId); + transaction.execute( + "UPDATE game_session_initial_gameplay_login_journal" + + " SET verified_token_jti = ?, verified_token_sha256 = ?," + + " verified_token_generation = 1, verified_issuance_fence = 1" + + " WHERE request_id = ?", + tokenJti, + "c".repeat(64), + originalRequestId); + transaction.execute( + "INSERT INTO game_session_canonical_initial_account_barrier_initializer" + + " (initializer_id, original_request_id, original_caller_context_id," + + " original_attempt_fence, account_id, account_login_evidence_digest," + + " source_control_state, source_control_epoch, inventory_snapshot_revision," + + " source_control_digest) VALUES (?, ?, ?, 7, ?, ?, ?, 0, ?, ?)", + initializerId, + originalRequestId, + callerContextId, + accountId, + accountEvidenceDigest, + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + inventoryClock.get("inventory_revision"), + sourceControlDigest); + transaction.execute( + "INSERT INTO game_session_canonical_initial_account_barrier_target" + + " (initializer_id, original_request_id, account_id, target_ordinal, tenant_id," + + " playable_state_namespace_id, target_state)" + + " VALUES (?, ?, ?, 0, ?, ?, 'NEVER_DISPATCHED')", + initializerId, + originalRequestId, + accountId, + tenantId, + namespaceId); + }); return new ControlledInitialTarget(initializerId, originalRequestId); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.java index 6e2887d8ca..e2455d8443 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.java @@ -96,11 +96,10 @@ void installsExactClosedBarrierRetriesAndFailsClosedOnLossConflictAndChangedInca try { TransactionSynchronizationManager.setActualTransactionActive(true); - assertThatThrownBy( - () -> - fixture - .owner(initialReceiver, redis) - .installAndRead(fixture.intent().operationId(), 0L)) + assertThatThrownBy(() -> + fixture + .owner(initialReceiver, redis) + .installAndRead(fixture.intent().operationId(), 0L)) .isInstanceOf(IllegalStateException.class); } finally { TransactionSynchronizationManager.clear(); @@ -108,11 +107,10 @@ void installsExactClosedBarrierRetriesAndFailsClosedOnLossConflictAndChangedInca assertThat(redis.admin().type(redisKey)).isEqualTo("none"); try { TransactionSynchronizationManager.initSynchronization(); - assertThatThrownBy( - () -> - fixture - .owner(initialReceiver, redis) - .installAndRead(fixture.intent().operationId(), 0L)) + assertThatThrownBy(() -> + fixture + .owner(initialReceiver, redis) + .installAndRead(fixture.intent().operationId(), 0L)) .isInstanceOf(IllegalStateException.class); } finally { TransactionSynchronizationManager.clearSynchronization(); @@ -169,12 +167,10 @@ void installsExactClosedBarrierRetriesAndFailsClosedOnLossConflictAndChangedInca equalEpochOpen.put("state", "OPEN"); redis.admin().del(List.of(redisKey).toArray(byte[][]::new)); redis.admin().hset(redisKey, encoded(equalEpochOpen)); - assertThatThrownBy( - () -> - fixture - .owner( - fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) - .installAndRead(fixture.intent().operationId(), 0L)) + assertThatThrownBy(() -> + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L)) .isInstanceOf(IllegalStateException.class); assertExactHash(redis.admin(), redisKey, equalEpochOpen); @@ -183,12 +179,10 @@ void installsExactClosedBarrierRetriesAndFailsClosedOnLossConflictAndChangedInca equalEpochConflictingOwner.put("ownerOperationId", UUID.randomUUID().toString()); redis.admin().del(List.of(redisKey).toArray(byte[][]::new)); redis.admin().hset(redisKey, encoded(equalEpochConflictingOwner)); - assertThatThrownBy( - () -> - fixture - .owner( - fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) - .installAndRead(fixture.intent().operationId(), 0L)) + assertThatThrownBy(() -> + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L)) .isInstanceOf(IllegalStateException.class); assertExactHash(redis.admin(), redisKey, equalEpochConflictingOwner); @@ -196,12 +190,10 @@ void installsExactClosedBarrierRetriesAndFailsClosedOnLossConflictAndChangedInca unknownField.put("operatorExtension", "preserve"); redis.admin().del(List.of(redisKey).toArray(byte[][]::new)); redis.admin().hset(redisKey, encoded(unknownField)); - assertThatThrownBy( - () -> - fixture - .owner( - fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) - .installAndRead(fixture.intent().operationId(), 0L)) + assertThatThrownBy(() -> + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L)) .isInstanceOf(IllegalStateException.class); assertThat(stringMap(redis.admin().hgetall(redisKey))).isEqualTo(unknownField); assertThat(redis.admin().type(redisKey)).isEqualTo("hash"); @@ -222,11 +214,10 @@ void installsExactClosedBarrierRetriesAndFailsClosedOnLossConflictAndChangedInca // The write may have happened, but changed protected evidence on the post-read observation // prevents an owner readback capability from being returned. The stored barrier stays closed. var changingReceiver = fixture.receiver(new ControlledSigner(fixture.keyPair(), true)); - assertThatThrownBy( - () -> - fixture - .owner(changingReceiver, redis) - .installAndRead(fixture.intent().operationId(), 0L)) + assertThatThrownBy(() -> + fixture + .owner(changingReceiver, redis) + .installAndRead(fixture.intent().operationId(), 0L)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("CLOSED account barrier is unavailable"); assertExactHash(redis.admin(), redisKey, installed.barrierFields()); @@ -236,24 +227,20 @@ void installsExactClosedBarrierRetriesAndFailsClosedOnLossConflictAndChangedInca new LinkedHashMap<>(barrierFields(fixture, assignment, initialProof, "11", "OPEN")); newerOpen.put("ownerOperationId", UUID.randomUUID().toString()); redis.admin().hset(redisKey, encoded(newerOpen)); - assertThatThrownBy( - () -> - fixture - .owner( - fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) - .installAndRead(fixture.intent().operationId(), 0L)) + assertThatThrownBy(() -> + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L)) .isInstanceOf(IllegalStateException.class); assertExactHash(redis.admin(), redisKey, newerOpen); // Wrong Redis type, foreign scope, and TTL-bearing hashes are non-mutating refusals. redis.admin().del(List.of(redisKey).toArray(byte[][]::new)); redis.admin().set(redisKey, ascii("operator-owned")); - assertThatThrownBy( - () -> - fixture - .owner( - fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) - .installAndRead(fixture.intent().operationId(), 0L)) + assertThatThrownBy(() -> + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L)) .isInstanceOf(IllegalStateException.class); assertThat(redis.admin().get(redisKey)).isEqualTo(ascii("operator-owned")); @@ -262,12 +249,10 @@ void installsExactClosedBarrierRetriesAndFailsClosedOnLossConflictAndChangedInca new LinkedHashMap<>(barrierFields(fixture, assignment, initialProof, "9", "CLOSED")); foreignScope.put("tenantId", UUID.randomUUID().toString()); redis.admin().hset(redisKey, encoded(foreignScope)); - assertThatThrownBy( - () -> - fixture - .owner( - fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) - .installAndRead(fixture.intent().operationId(), 0L)) + assertThatThrownBy(() -> + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L)) .isInstanceOf(IllegalStateException.class); assertExactHash(redis.admin(), redisKey, foreignScope); @@ -275,29 +260,23 @@ void installsExactClosedBarrierRetriesAndFailsClosedOnLossConflictAndChangedInca redis.admin().hset(redisKey, encoded(previousClosed)); redis.admin().pexpire(redisKey, 60_000L); Map expiringBefore = redis.admin().hgetall(redisKey); - assertThatThrownBy( - () -> - fixture - .owner( - fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) - .installAndRead(fixture.intent().operationId(), 0L)) + assertThatThrownBy(() -> + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L)) .isInstanceOf(IllegalStateException.class); assertThat(stringMap(redis.admin().hgetall(redisKey))).isEqualTo(stringMap(expiringBefore)); assertThat(redis.admin().pttl(redisKey)).isPositive(); - assertThatThrownBy( - () -> - fixture - .owner( - fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) - .installAndRead(UUID.randomUUID(), 0L)) + assertThatThrownBy(() -> + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(UUID.randomUUID(), 0L)) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - fixture - .owner( - fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) - .installAndRead(fixture.intent().operationId(), 1L)) + assertThatThrownBy(() -> + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 1L)) .isInstanceOf(IllegalStateException.class); } } @@ -345,12 +324,10 @@ void comparesVeryLargeFenceEpochsAsCanonicalDecimalStrings() throws Exception { new LinkedHashMap<>(barrierFields(fixture, assignment, proof, greaterEpoch, "OPEN")); newerOwner.put("ownerOperationId", UUID.randomUUID().toString()); redis.admin().hset(key, encoded(newerOwner)); - assertThatThrownBy( - () -> - fixture - .owner( - fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) - .installAndRead(fixture.intent().operationId(), 0L)) + assertThatThrownBy(() -> + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L)) .isInstanceOf(IllegalStateException.class); assertThat(stringMap(redis.admin().hgetall(key))).isEqualTo(newerOwner); assertThat(newerOwner.get("ownerFenceEpoch")).isEqualTo(greaterEpoch); @@ -397,12 +374,10 @@ void closesPriorOpenAtZeroFromPositiveControlAndRejectsPriorClosedAtZero() throw withPriorOperation(barrierFields(fixture, assignment, proof, "0", "CLOSED")); redis.admin().del(List.of(key).toArray(byte[][]::new)); redis.admin().hset(key, encoded(priorClosed)); - assertThatThrownBy( - () -> - fixture - .owner( - fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) - .installAndRead(fixture.intent().operationId(), 0L)) + assertThatThrownBy(() -> + fixture + .owner(fixture.receiver(new ControlledSigner(fixture.keyPair(), false)), redis) + .installAndRead(fixture.intent().operationId(), 0L)) .isInstanceOf(IllegalStateException.class); assertExactHash(redis.admin(), key, priorClosed); } @@ -441,15 +416,12 @@ void acceptsOneClosedReceiptAndExactRetryReturnsTheOriginalSqlPostimage() throws assertThat(closedReceiptCount(fixture, operationId)).isEqualTo(1L); assertThat(closedReceiptPostimage(fixture, operationId, 0L)).isEqualTo(originalPostimage); - assertThatThrownBy( - () -> - restartedSqlOwner.acceptClosedBarrierReadback( - UUID.randomUUID(), 0L, freshRetryReadback)) + assertThatThrownBy(() -> + restartedSqlOwner.acceptClosedBarrierReadback( + UUID.randomUUID(), 0L, freshRetryReadback)) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); - assertThatThrownBy( - () -> - restartedSqlOwner.acceptClosedBarrierReadback( - operationId, 1L, freshRetryReadback)) + assertThatThrownBy(() -> + restartedSqlOwner.acceptClosedBarrierReadback(operationId, 1L, freshRetryReadback)) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); assertThat(closedReceiptCount(fixture, operationId)).isEqualTo(1L); assertThat(closedReceiptPostimage(fixture, operationId, 0L)).isEqualTo(originalPostimage); @@ -549,37 +521,33 @@ void acceptsClosedReadbackAfterConcurrentPrepareCommitsWhileWaitingOnInventoryCl CountDownLatch releaseInventoryClock = new CountDownLatch(1); try (ExecutorService executor = Executors.newFixedThreadPool(3)) { Future clockHolder = - executor.submit( - () -> - fixture.dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - if (transaction.fetchOne( - "SELECT inventory_revision FROM" - + " game_session_canonical_binding_inventory_clock" - + " WHERE singleton_id = 1 FOR UPDATE") - == null) { - throw new IllegalStateException("Inventory clock row is missing"); - } - inventoryClockHeld.countDown(); - awaitLatch(releaseInventoryClock); - return Boolean.TRUE; - })); + executor.submit(() -> + fixture.dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + if (transaction.fetchOne( + "SELECT inventory_revision FROM" + + " game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id = 1 FOR UPDATE") + == null) { + throw new IllegalStateException("Inventory clock row is missing"); + } + inventoryClockHeld.countDown(); + awaitLatch(releaseInventoryClock); + return Boolean.TRUE; + })); try { assertThat(inventoryClockHeld.await(5, TimeUnit.SECONDS)).isTrue(); Future prepare = - executor.submit( - () -> - new CanonicalGameplayBindingInventoryRepository(prepareDsl) - .prepare(otherRequest)); + executor.submit(() -> + new CanonicalGameplayBindingInventoryRepository(prepareDsl) + .prepare(otherRequest)); awaitInventoryClockLockWait(fixture.dsl, prepareApplicationName); Future accepted = - executor.submit( - () -> - new CanonicalGameplayAccountAdmissionBarrierRepository( - acceptDsl, Clock.fixed(NOW, ZoneOffset.UTC)) - .acceptClosedBarrierReadback(operationId, 0L, readback)); + executor.submit(() -> + new CanonicalGameplayAccountAdmissionBarrierRepository( + acceptDsl, Clock.fixed(NOW, ZoneOffset.UTC)) + .acceptClosedBarrierReadback(operationId, 0L, readback)); awaitInventoryClockLockWait(fixture.dsl, acceptApplicationName); // PostgreSQL's row-lock queue releases the actual prepare first, then lets the receipt @@ -632,9 +600,8 @@ void expiredTrustedAcceptanceClockCannotReplaceAnExistingClosedReceipt() throws var expiredSqlOwner = new CanonicalGameplayAccountAdmissionBarrierRepository( fixture.dsl, Clock.fixed(NOW.plusSeconds(30), ZoneOffset.UTC)); - assertThatThrownBy( - () -> - expiredSqlOwner.acceptClosedBarrierReadback(operationId, 0L, nowExpiredReadback)) + assertThatThrownBy(() -> + expiredSqlOwner.acceptClosedBarrierReadback(operationId, 0L, nowExpiredReadback)) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("expired"); assertThat(closedReceiptCount(fixture, operationId)).isEqualTo(1L); @@ -818,29 +785,26 @@ void databaseRejectsReceiptUpdateDeleteAndTruncateWithoutChangingItsPostimage() String originalPostimage = closedReceiptPostimage(fixture, operationId, 0L); // created_at is outside the row CHECK constraints, so 23514 proves the immutable trigger. - assertThatThrownBy( - () -> - fixture.dsl.execute( - "UPDATE game_session_canonical_account_closed_barrier_receipt" - + " SET created_at = created_at + INTERVAL '1 second'" - + " WHERE operation_id = ? AND target_ordinal = 0", - operationId)) + assertThatThrownBy(() -> + fixture.dsl.execute( + "UPDATE game_session_canonical_account_closed_barrier_receipt" + + " SET created_at = created_at + INTERVAL '1 second'" + + " WHERE operation_id = ? AND target_ordinal = 0", + operationId)) .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")); assertThat(closedReceiptPostimage(fixture, operationId, 0L)).isEqualTo(originalPostimage); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "DELETE FROM game_session_canonical_account_closed_barrier_receipt" - + " WHERE operation_id = ? AND target_ordinal = 0", - operationId)) + assertThatThrownBy(() -> + fixture.dsl.execute( + "DELETE FROM game_session_canonical_account_closed_barrier_receipt" + + " WHERE operation_id = ? AND target_ordinal = 0", + operationId)) .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")); assertThat(closedReceiptPostimage(fixture, operationId, 0L)).isEqualTo(originalPostimage); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "TRUNCATE TABLE game_session_canonical_account_closed_barrier_receipt")) + assertThatThrownBy(() -> + fixture.dsl.execute( + "TRUNCATE TABLE game_session_canonical_account_closed_barrier_receipt")) .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")); assertThat(closedReceiptCount(fixture, operationId)).isEqualTo(1L); assertThat(closedReceiptPostimage(fixture, operationId, 0L)).isEqualTo(originalPostimage); @@ -944,11 +908,10 @@ private static Map withPriorOperation(Map fields private static Map stringMap(Map fields) { Map decoded = new LinkedHashMap<>(); - fields.forEach( - (field, value) -> - decoded.put( - new String(field, StandardCharsets.US_ASCII), - new String(value, StandardCharsets.US_ASCII))); + fields.forEach((field, value) -> + decoded.put( + new String(field, StandardCharsets.US_ASCII), + new String(value, StandardCharsets.US_ASCII))); return decoded; } @@ -1221,24 +1184,22 @@ private static CanonicalGameplayAccountAdmissionFenceIntent seedHistoricalV1028I identity.accountId(), identity.accountId(), identity.accountId()) - .map( - row -> - CanonicalGameplayAccountAdmissionFenceIntent.cohortRow( - row.get("row_ordinal", Long.class), - CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.valueOf( - row.get("source_kind", String.class)), - row.get("source_key", String.class), - row.get("tenant_id", UUID.class), - row.get("playable_state_namespace_id", UUID.class), - row.get("source_record_json", String.class))); + .map(row -> + CanonicalGameplayAccountAdmissionFenceIntent.cohortRow( + row.get("row_ordinal", Long.class), + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.valueOf( + row.get("source_kind", String.class)), + row.get("source_key", String.class), + row.get("tenant_id", UUID.class), + row.get("playable_state_namespace_id", UUID.class), + row.get("source_record_json", String.class))); if (rows.size() != 3 || rows.stream() - .anyMatch( - row -> - !identity.tenantId().equals(row.tenantId()) - || !identity - .playableStateNamespaceId() - .equals(row.playableStateNamespaceId()))) { + .anyMatch(row -> + !identity.tenantId().equals(row.tenantId()) + || !identity + .playableStateNamespaceId() + .equals(row.playableStateNamespaceId()))) { throw new IllegalStateException("Historical fixture must retain its three scoped sources"); } var target = diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwnerIntegrationTest.java index bdd7e88876..c86e64d17f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwnerIntegrationTest.java @@ -268,40 +268,35 @@ void acknowledgementLocksLeaseBoundRuntimeBeforeTransitionAgainstRuntimeMutation try (ExecutorService executor = Executors.newFixedThreadPool(2)) { Future runtimeMutation = - executor.submit( - () -> - testSchema - .dsl() - .transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - var runtime = - transaction.fetchOne( - "SELECT id FROM game_instances" - + " WHERE tenant_id = ? AND id = ? FOR UPDATE", - target.gameSessionTenantId(), - target.gameInstanceId()); - if (runtime == null) { - throw new IllegalStateException("Expected current runtime row"); - } - runtimeRowLocked.countDown(); - awaitLatch(allowRuntimeMutation); - return transaction.execute( - "UPDATE game_instances SET status = 'STOPPED'," - + " row_version = row_version + 1" - + " WHERE tenant_id = ? AND id = ?", - target.gameSessionTenantId(), - target.gameInstanceId()); - })); + executor.submit(() -> + testSchema + .dsl() + .transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + var runtime = + transaction.fetchOne( + "SELECT id FROM game_instances" + + " WHERE tenant_id = ? AND id = ? FOR UPDATE", + target.gameSessionTenantId(), + target.gameInstanceId()); + if (runtime == null) { + throw new IllegalStateException("Expected current runtime row"); + } + runtimeRowLocked.countDown(); + awaitLatch(allowRuntimeMutation); + return transaction.execute( + "UPDATE game_instances SET status = 'STOPPED'," + + " row_version = row_version + 1" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()); + })); try { assertThat(runtimeRowLocked.await(5, TimeUnit.SECONDS)).isTrue(); Future acknowledgement = - executor.submit( - () -> - fixture - .repository() - .acknowledgeAccountMemberRepair(operation, actualReadback)); + executor.submit(() -> + fixture.repository().acknowledgeAccountMemberRepair(operation, actualReadback)); awaitRuntimeRowLockWait(testSchema.dsl(), applicationName); allowRuntimeMutation.countDown(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java index 0f236999f3..e6dac85406 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java @@ -380,19 +380,18 @@ private CanonicalGameplayAdmissionAbortCompositionFixture( .candidateReservation() .reservationId(); originalSource = - dsl.transactionResult( - configuration -> { - var transaction = DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - var row = - transaction.fetchSingle( - "SELECT * FROM game_session_canonical_issuer_bootstrap_member_operation WHERE bootstrap_operation_id = ? AND reservation_id = ?", - installedAnchor.bootstrapOperationId(), - originalReservationId); - return CanonicalGameplayIssuerOriginalMemberSourceRepository - .readInstalledInTransaction( - transaction, installedAnchor, initialIssuerState, row); - }); + dsl.transactionResult(configuration -> { + var transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + var row = + transaction.fetchSingle( + "SELECT * FROM game_session_canonical_issuer_bootstrap_member_operation WHERE bootstrap_operation_id = ? AND reservation_id = ?", + installedAnchor.bootstrapOperationId(), + originalReservationId); + return CanonicalGameplayIssuerOriginalMemberSourceRepository + .readInstalledInTransaction( + transaction, installedAnchor, initialIssuerState, row); + }); } else { var request = new CanonicalGameplayIssuerBindingLocalOperation.Request( @@ -1064,20 +1063,19 @@ public CanonicalGameplayAdmissionAbortSource recordBootstrapAccountAbort( */ public void recordOriginalAccountAbortThenAdvanceControlBeforeCommit() { var source = repository.readFirstNewAdmissionAbortSource(transitionId); - dsl.transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - var transactionRepository = new CanonicalGameplayBindingInventoryRepository(transaction); - transactionRepository.recordFirstNewAccountAbort( - source, + dsl.transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + var transactionRepository = new CanonicalGameplayBindingInventoryRepository(transaction); + transactionRepository.recordFirstNewAccountAbort( + source, + UUID.nameUUIDFromBytes( + "original-controller-stale-control-cleanup".getBytes(StandardCharsets.UTF_8))); + new CanonicalGameplayAccountAdmissionBarrierRepository(transaction) + .beginFenceIntent( + identity.accountId(), UUID.nameUUIDFromBytes( - "original-controller-stale-control-cleanup".getBytes(StandardCharsets.UTF_8))); - new CanonicalGameplayAccountAdmissionBarrierRepository(transaction) - .beginFenceIntent( - identity.accountId(), - UUID.nameUUIDFromBytes( - "original-controller-stale-control-intent".getBytes(StandardCharsets.UTF_8))); - }); + "original-controller-stale-control-intent".getBytes(StandardCharsets.UTF_8))); + }); } /** Independent read under the same real GS role; retained ACK never implies physical removal. */ @@ -1479,27 +1477,24 @@ public void assertCompletedNegativeReleaseAndRetirementReplay() { negative.state(), negative.orphanCleanupId(), negative.negativeResolutionId())); - assertThatThrownBy( - () -> - CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.readOperation( - dsl, releaseRow, unresolvedSource, originalSource)) + assertThatThrownBy(() -> + CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.readOperation( + dsl, releaseRow, unresolvedSource, originalSource)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("phase differs"); - assertThatThrownBy( - () -> - new CanonicalGameplayAdmissionAbortSource( - source.transition(), - source.candidate(), - source.reservation(), - source.originalDecision(), - source.orphanCleanupId())) + assertThatThrownBy(() -> + new CanonicalGameplayAdmissionAbortSource( + source.transition(), + source.candidate(), + source.reservation(), + source.originalDecision(), + source.orphanCleanupId())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("not retained for exact cleanup"); releaseRow.set(releaseRow.field("completion_inventory_revision", BigDecimal.class), null); - assertThatThrownBy( - () -> - CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.readOperation( - dsl, releaseRow, source, originalSource)) + assertThatThrownBy(() -> + CanonicalGameplayIssuerBindingLocalReleaseOperationRepository.readOperation( + dsl, releaseRow, source, originalSource)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("phase differs"); } @@ -1550,13 +1545,12 @@ public BigInteger preparedLocalCountedReservations() { var work = localProjectionRepository.readPreparedPartitionWork(originalSource); return BigInteger.valueOf( work.localEntries().stream() - .filter( - entry -> - entry - .memberValue() - .reservation() - .partitionId() - .equals(originalSource.reservation().partitionId())) + .filter(entry -> + entry + .memberValue() + .reservation() + .partitionId() + .equals(originalSource.reservation().partitionId())) .filter( CanonicalGameplayIssuerBindingLocalProjectionRepository.LocalEntry ::countsTowardCapacity) @@ -1950,74 +1944,73 @@ static void seedHistoricalLeaseBoundProvisional( .isEqualTo( net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionSnapshot .Status.PREPARED); - dsl.transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - BigInteger currentRevision = - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - BigInteger nextRevision = currentRevision.add(BigInteger.ONE); - BigInteger priorRevision = prepared.inventoryRevision(); - assertThat( - transaction.fetchOne( - "SELECT id FROM game_instances" - + " WHERE tenant_id = ? AND id = ? AND game_instance_uuid = ? FOR UPDATE", - decision.targetEvidence().gameSessionTenantId(), - decision.targetEvidence().gameInstanceId(), - decision.targetEvidence().canonicalGameInstanceId())) - .isNotNull(); - assertThat( - seedHistoricalProvisionalTransition( - transaction, prepared, decision, priorRevision, nextRevision)) - .isOne(); - assertThat( - transaction.execute( - "UPDATE game_session_canonical_gameplay_binding_inventory" - + " SET lifecycle = 'PROVISIONAL', inventory_revision = ?" - + " WHERE binding_ref = ? AND transition_id = ?" - + " AND lifecycle = 'CANDIDATE_PREPARED'" - + " AND binding_generation = ? AND account_index_fence = ?" - + " AND account_index_state = 'REPAIR_REQUIRED'" - + " AND issuer_index_state = 'REPAIR_REQUIRED' AND inventory_revision = ?", - new BigDecimal(nextRevision), - prepared.bindingRef().bytes(), - prepared.transitionId(), - new BigDecimal(prepared.bindingGeneration()), - prepared.candidateAccountIndexFence(), - new BigDecimal(priorRevision))) - .isOne(); - for (String obligationTable : - List.of( - "game_session_canonical_binding_account_index_obligation", - "game_session_canonical_binding_issuer_index_obligation", - "game_session_canonical_binding_region_bridge_obligation")) { - assertThat( - transaction.execute( - "UPDATE " - + obligationTable - + " SET inventory_revision = ? WHERE transition_id = ? AND inventory_revision = ?", - new BigDecimal(nextRevision), - prepared.transitionId(), - new BigDecimal(priorRevision))) - .isOne(); - } - assertThat( - transaction.execute( - "UPDATE game_session_canonical_issuer_partition_reservation" - + " SET inventory_revision = ? WHERE reservation_id = ? AND transition_id = ?" - + " AND lifecycle = 'RESERVED' AND inventory_revision = ?", - new BigDecimal(nextRevision), - prepared.issuerReservationId(), - prepared.transitionId(), - new BigDecimal(priorRevision))) - .isOne(); - assertThat( - transaction.execute( - "UPDATE game_session_canonical_binding_inventory_clock" - + " SET inventory_revision = ? WHERE singleton_id = 1 AND inventory_revision = ?", - new BigDecimal(nextRevision), - new BigDecimal(currentRevision))) - .isOne(); - }); + dsl.transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger currentRevision = + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + BigInteger nextRevision = currentRevision.add(BigInteger.ONE); + BigInteger priorRevision = prepared.inventoryRevision(); + assertThat( + transaction.fetchOne( + "SELECT id FROM game_instances" + + " WHERE tenant_id = ? AND id = ? AND game_instance_uuid = ? FOR UPDATE", + decision.targetEvidence().gameSessionTenantId(), + decision.targetEvidence().gameInstanceId(), + decision.targetEvidence().canonicalGameInstanceId())) + .isNotNull(); + assertThat( + seedHistoricalProvisionalTransition( + transaction, prepared, decision, priorRevision, nextRevision)) + .isOne(); + assertThat( + transaction.execute( + "UPDATE game_session_canonical_gameplay_binding_inventory" + + " SET lifecycle = 'PROVISIONAL', inventory_revision = ?" + + " WHERE binding_ref = ? AND transition_id = ?" + + " AND lifecycle = 'CANDIDATE_PREPARED'" + + " AND binding_generation = ? AND account_index_fence = ?" + + " AND account_index_state = 'REPAIR_REQUIRED'" + + " AND issuer_index_state = 'REPAIR_REQUIRED' AND inventory_revision = ?", + new BigDecimal(nextRevision), + prepared.bindingRef().bytes(), + prepared.transitionId(), + new BigDecimal(prepared.bindingGeneration()), + prepared.candidateAccountIndexFence(), + new BigDecimal(priorRevision))) + .isOne(); + for (String obligationTable : + List.of( + "game_session_canonical_binding_account_index_obligation", + "game_session_canonical_binding_issuer_index_obligation", + "game_session_canonical_binding_region_bridge_obligation")) { + assertThat( + transaction.execute( + "UPDATE " + + obligationTable + + " SET inventory_revision = ? WHERE transition_id = ? AND inventory_revision = ?", + new BigDecimal(nextRevision), + prepared.transitionId(), + new BigDecimal(priorRevision))) + .isOne(); + } + assertThat( + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_reservation" + + " SET inventory_revision = ? WHERE reservation_id = ? AND transition_id = ?" + + " AND lifecycle = 'RESERVED' AND inventory_revision = ?", + new BigDecimal(nextRevision), + prepared.issuerReservationId(), + prepared.transitionId(), + new BigDecimal(priorRevision))) + .isOne(); + assertThat( + transaction.execute( + "UPDATE game_session_canonical_binding_inventory_clock" + + " SET inventory_revision = ? WHERE singleton_id = 1 AND inventory_revision = ?", + new BigDecimal(nextRevision), + new BigDecimal(currentRevision))) + .isOne(); + }); } private static int seedHistoricalProvisionalTransition( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepositoryIntegrationTest.java index 83dddafaac..b69d84fb34 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepositoryIntegrationTest.java @@ -152,13 +152,11 @@ void preparesFirstBindingOnlyBehindVerifiedDispositionAndRetainsNoPriorShape() { .isEqualTo(beforeLeaseFreeAttempt.inventoryRevision()); assertThat(afterLeaseFreeAttempt.bindings()) .singleElement() - .satisfies( - candidate -> - assertThat(candidate.lifecycle()) - .isEqualTo( - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventoryEntry.Lifecycle - .CANDIDATE_PREPARED)); + .satisfies(candidate -> + assertThat(candidate.lifecycle()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.Lifecycle.CANDIDATE_PREPARED)); var storedDecision = dsl.fetchOne( "SELECT admission_request_id, admission_lease_id" @@ -173,13 +171,11 @@ void preparesFirstBindingOnlyBehindVerifiedDispositionAndRetainsNoPriorShape() { .satisfies(obligation -> assertThat(obligation.expectedPriorGeneration()).isNull()); assertThat(repository.readSnapshot().bindings()) .singleElement() - .satisfies( - candidate -> - assertThat(candidate.lifecycle()) - .isEqualTo( - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventoryEntry.Lifecycle - .CANDIDATE_PREPARED)); + .satisfies(candidate -> + assertThat(candidate.lifecycle()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.Lifecycle.CANDIDATE_PREPARED)); } finally { dropSchema(schema); } @@ -207,13 +203,12 @@ void persistsFirstBindingAccountIndexReadbackWithoutPriorObligation() { .PRESENT_AWAITING_COVERAGE); assertThat(fixture.repository().readSnapshot().accountIndexObligations()) .singleElement() - .satisfies( - obligation -> - assertThat(obligation.projectionState()) - .isEqualTo( - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingAccountIndexObligation.ProjectionState - .PRESENT_AWAITING_COVERAGE)); + .satisfies(obligation -> + assertThat(obligation.projectionState()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingAccountIndexObligation.ProjectionState + .PRESENT_AWAITING_COVERAGE)); } finally { dropSchema(testSchema.schema()); } @@ -361,38 +356,35 @@ void acknowledgesOnlyTheFrozenNewBindingMemberAfterPhysicalRedisReadback() { var completed = fixture.repository().readSnapshot(); assertThat(completed.transitions()) .singleElement() - .satisfies( - transition -> - assertThat(transition.status()) - .isEqualTo(CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL)); + .satisfies(transition -> + assertThat(transition.status()) + .isEqualTo(CanonicalGameplayBindingTransitionSnapshot.Status.PROVISIONAL)); assertThat(completed.bindings()) .singleElement() - .satisfies( - candidate -> { - assertThat(candidate.lifecycle()) - .isEqualTo( - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL); - assertThat(candidate.accountIndexState()) - .isEqualTo( - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED); - }); + .satisfies(candidate -> { + assertThat(candidate.lifecycle()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.Lifecycle.PROVISIONAL); + assertThat(candidate.accountIndexState()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.IndexState.ACKNOWLEDGED); + }); assertThat(completed.accountIndexObligations()) .singleElement() - .satisfies( - obligation -> { - assertThat(obligation.status()) - .isEqualTo( - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingAccountIndexObligation.Status.ACKNOWLEDGED); - assertThat(obligation.projectionState()) - .isEqualTo( - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingAccountIndexObligation.ProjectionState - .PRESENT_AWAITING_COVERAGE); - assertThat(obligation.projectedMember()).isEqualTo(operation.member()); - }); + .satisfies(obligation -> { + assertThat(obligation.status()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingAccountIndexObligation.Status.ACKNOWLEDGED); + assertThat(obligation.projectionState()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingAccountIndexObligation.ProjectionState + .PRESENT_AWAITING_COVERAGE); + assertThat(obligation.projectedMember()).isEqualTo(operation.member()); + }); var controlAfter = Objects.requireNonNull( @@ -543,19 +535,18 @@ void memberRepairPreservesAnEarlierPresentObservationUntilActualAcknowledgement( assertThat(acknowledgement.member()).isEqualTo(member); assertThat(fixture.repository().readSnapshot().accountIndexObligations()) .singleElement() - .satisfies( - obligation -> { - assertThat(obligation.status()) - .isEqualTo( - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingAccountIndexObligation.Status.ACKNOWLEDGED); - assertThat(obligation.projectionState()) - .isEqualTo( - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingAccountIndexObligation.ProjectionState - .PRESENT_AWAITING_COVERAGE); - assertThat(obligation.projectedMember()).isEqualTo(member); - }); + .satisfies(obligation -> { + assertThat(obligation.status()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingAccountIndexObligation.Status.ACKNOWLEDGED); + assertThat(obligation.projectionState()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingAccountIndexObligation.ProjectionState + .PRESENT_AWAITING_COVERAGE); + assertThat(obligation.projectedMember()).isEqualTo(member); + }); } finally { if (redisFixture != null) { redisFixture.deleteAccountKey(ACCOUNT_ID); @@ -615,20 +606,18 @@ void changedNoActiveControlFenceRejectsRedisReadbackAcknowledgement() { var snapshot = fixture.repository().readSnapshot(); assertThat(snapshot.accountIndexObligations()) .singleElement() - .satisfies( - obligation -> - assertThat(obligation.status()) - .isEqualTo( - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED)); + .satisfies(obligation -> + assertThat(obligation.status()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingAccountIndexObligation.Status.REQUIRED)); assertThat(snapshot.bindings()) .singleElement() - .satisfies( - candidate -> - assertThat(candidate.accountIndexState()) - .isEqualTo( - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED)); + .satisfies(candidate -> + assertThat(candidate.accountIndexState()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.IndexState.REPAIR_REQUIRED)); var pending = Objects.requireNonNull( testSchema @@ -824,15 +813,14 @@ void leaseBoundRuntimeFenceTriggerRejectsRawAbortAfterAccountMemberProjection() RedisScriptCatalog.loadInstalled(getClass().getClassLoader())); redisOwner.projectAndRead(operation); - assertThatThrownBy( - () -> - testSchema - .dsl() - .execute( - "UPDATE game_session_canonical_binding_transition" - + " SET status = 'ABORTED' WHERE transition_id = ?" - + " AND status = 'PROVISIONAL'", - TRANSITION_ID)) + assertThatThrownBy(() -> + testSchema + .dsl() + .execute( + "UPDATE game_session_canonical_binding_transition" + + " SET status = 'ABORTED' WHERE transition_id = ?" + + " AND status = 'PROVISIONAL'", + TRANSITION_ID)) .isInstanceOfSatisfying( org.jooq.exception.DataAccessException.class, failure -> { @@ -952,36 +940,33 @@ void leaseBoundDecisionAndRuntimeMutationAcquireLocksInOneOrder() throws Excepti try (ExecutorService executor = Executors.newFixedThreadPool(2)) { try { Future runtimeMutation = - executor.submit( - () -> - testSchema - .dsl() - .transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - var runtime = - transaction.fetchOne( - "SELECT id FROM game_instances" - + " WHERE tenant_id = ? AND id = ? FOR UPDATE", - target.gameSessionTenantId(), - target.gameInstanceId()); - if (runtime == null) { - throw new IllegalStateException("Expected current runtime row"); - } - runtimeRowLocked.countDown(); - awaitLatch(allowRuntimeMutation); - return transaction.execute( - "UPDATE game_instances SET row_version = row_version + 1" - + " WHERE tenant_id = ? AND id = ?", - target.gameSessionTenantId(), - target.gameInstanceId()); - })); + executor.submit(() -> + testSchema + .dsl() + .transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + var runtime = + transaction.fetchOne( + "SELECT id FROM game_instances" + + " WHERE tenant_id = ? AND id = ? FOR UPDATE", + target.gameSessionTenantId(), + target.gameInstanceId()); + if (runtime == null) { + throw new IllegalStateException("Expected current runtime row"); + } + runtimeRowLocked.countDown(); + awaitLatch(allowRuntimeMutation); + return transaction.execute( + "UPDATE game_instances SET row_version = row_version + 1" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()); + })); assertThat(runtimeRowLocked.await(5, TimeUnit.SECONDS)).isTrue(); Future decisionAcquisition = - executor.submit( - () -> - fixture.repository().markProvisional(fixture.evidence(), fixture.decision())); + executor.submit(() -> + fixture.repository().markProvisional(fixture.evidence(), fixture.decision())); awaitBindingLockWait(testSchema.dsl(), applicationName); allowRuntimeMutation.countDown(); @@ -1005,31 +990,29 @@ void leaseBoundDecisionAndRuntimeMutationAcquireLocksInOneOrder() throws Excepti CountDownLatch projectionRuntimeRowLocked = new CountDownLatch(1); CountDownLatch allowFencedRuntimeMutation = new CountDownLatch(1); Future fencedRuntimeMutation = - executor.submit( - () -> - testSchema - .dsl() - .transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - var runtime = - transaction.fetchOne( - "SELECT id FROM game_instances" - + " WHERE tenant_id = ? AND id = ? FOR UPDATE", - target.gameSessionTenantId(), - target.gameInstanceId()); - if (runtime == null) { - throw new IllegalStateException("Expected current runtime row"); - } - projectionRuntimeRowLocked.countDown(); - awaitLatch(allowFencedRuntimeMutation); - return transaction.execute( - "UPDATE game_instances SET status = 'STOPPED'," - + " row_version = row_version + 1" - + " WHERE tenant_id = ? AND id = ?", - target.gameSessionTenantId(), - target.gameInstanceId()); - })); + executor.submit(() -> + testSchema + .dsl() + .transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + var runtime = + transaction.fetchOne( + "SELECT id FROM game_instances" + + " WHERE tenant_id = ? AND id = ? FOR UPDATE", + target.gameSessionTenantId(), + target.gameInstanceId()); + if (runtime == null) { + throw new IllegalStateException("Expected current runtime row"); + } + projectionRuntimeRowLocked.countDown(); + awaitLatch(allowFencedRuntimeMutation); + return transaction.execute( + "UPDATE game_instances SET status = 'STOPPED'," + + " row_version = row_version + 1" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()); + })); Future accountIndexReadback; try { assertThat(projectionRuntimeRowLocked.await(5, TimeUnit.SECONDS)).isTrue(); @@ -1038,11 +1021,10 @@ void leaseBoundDecisionAndRuntimeMutationAcquireLocksInOneOrder() throws Excepti String member = CanonicalGameplayAccountIndexMember.of(provisionalEvidence.candidate()).value(); accountIndexReadback = - executor.submit( - () -> - fixture - .repository() - .markCandidateAccountIndexPresent(provisionalEvidence, member)); + executor.submit(() -> + fixture + .repository() + .markCandidateAccountIndexPresent(provisionalEvidence, member)); awaitBindingLockWait(testSchema.dsl(), applicationName); } finally { allowFencedRuntimeMutation.countDown(); @@ -1154,20 +1136,17 @@ void advancesGenerationAtomicallyAndKeepsPriorControllerActiveUntilExternalCas() assertThat(snapshot.bindings()) .allSatisfy(row -> assertThat(row.identity().issuerId()).isEqualTo(ISSUER_ID)); assertThat(snapshot.bindings()) - .anySatisfy( - row -> - assertThat(row.lifecycle()) - .isEqualTo( - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE)); + .anySatisfy(row -> + assertThat(row.lifecycle()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE)); assertThat(snapshot.bindings()) - .anySatisfy( - row -> - assertThat(row.lifecycle()) - .isEqualTo( - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventoryEntry.Lifecycle - .CANDIDATE_PREPARED)); + .anySatisfy(row -> + assertThat(row.lifecycle()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.Lifecycle.CANDIDATE_PREPARED)); assertThat(snapshot.accountIndexObligations()).hasSize(2); assertThat(snapshot.accountIndexObligations().get(0).expectedPriorGeneration()) .isEqualTo(BigInteger.valueOf(5)); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java index 15774c510d..097129fdca 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingRuntimeTestFixtures.java @@ -134,11 +134,10 @@ public static RuntimeTarget seedRunningLaunch( CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(sourceEvidence); FreshGameSessionTenantAssociation tenantAssociation = java.util.Objects.requireNonNull( - transactions.execute( - status -> - new GameSessionFreshTenantAssociationRepository(dsl) - .associateFresh( - UUID.randomUUID(), targetNamespace, sourceReceipt, creationEvidence)), + transactions.execute(status -> + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + UUID.randomUUID(), targetNamespace, sourceReceipt, creationEvidence)), "fresh source-bound Game Session tenant association"); UUID catalogRequestId = UUID.randomUUID(); @@ -231,29 +230,27 @@ public static RuntimeTarget seedRunningLaunch( new GameSessionCanonicalStartingInstanceRepository(dsl, targetNamespace); StartingInstance startingInstance = java.util.Objects.requireNonNull( - transactions.execute( - status -> - startingRepository.createStarting( - tenantAssociation, - binding, - ownerAccountUuid, - controlPlaneRequestId, - originalTuple.mutationDigest(), - originalTuple)), + transactions.execute(status -> + startingRepository.createStarting( + tenantAssociation, + binding, + ownerAccountUuid, + controlPlaneRequestId, + originalTuple.mutationDigest(), + originalTuple)), "created canonical STARTING instance"); int consumerInputRows = java.util.Objects.requireNonNull( - transactions.execute( - status -> - dsl.execute( - // Controlled upstream World epoch inputs support only this downstream - // guard-consumer proof; they are not World ACTIVE, Human terminal, Account - // protection, or admission evidence. - "UPDATE game_instances SET status = 'RUNNING'," - + " row_version = row_version + 1, run_owned_start_preparing_epoch = 1," - + " run_owned_start_active_epoch = 2 WHERE tenant_id = ? AND id = ?", - tenantAssociation.legacyGameSessionTenantId(), - startingInstance.gameInstanceId())), + transactions.execute(status -> + dsl.execute( + // Controlled upstream World epoch inputs support only this downstream + // guard-consumer proof; they are not World ACTIVE, Human terminal, Account + // protection, or admission evidence. + "UPDATE game_instances SET status = 'RUNNING'," + + " row_version = row_version + 1, run_owned_start_preparing_epoch = 1," + + " run_owned_start_active_epoch = 2 WHERE tenant_id = ? AND id = ?", + tenantAssociation.legacyGameSessionTenantId(), + startingInstance.gameInstanceId())), "controlled runtime consumer input row count"); if (consumerInputRows != 1) { throw new IllegalStateException( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java index 04f1f08957..fea648c389 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayDecisionRuntimeFenceIntegrationTest.java @@ -121,70 +121,62 @@ void exactLeaseBoundCandidatePinsRuntimeAndRejectsTerminalTransition() { .isEqualTo("unrelated-runtime-update"); assertThat(unrelatedUpdateReadback.get("row_version", Long.class)).isEqualTo(2L); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_instances SET status = 'STOPPED'" - + " WHERE tenant_id = ? AND id = ?", - target.gameSessionTenantId(), - target.gameInstanceId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_instances SET status = 'STOPPED'" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) .hasMessageContaining("runtime row is fenced"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_instances SET version_id = version_id + 1" - + " WHERE tenant_id = ? AND id = ?", - target.gameSessionTenantId(), - target.gameInstanceId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_instances SET version_id = version_id + 1" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) .hasMessageContaining("runtime row is fenced"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_instances SET run_owned_start_request_id = 'replacement-start'" - + " WHERE tenant_id = ? AND id = ?", - target.gameSessionTenantId(), - target.gameInstanceId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_instances SET run_owned_start_request_id = 'replacement-start'" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) .hasMessageContaining("runtime row is fenced"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_instances SET run_owned_start_published_release_bundle_ref =" - + " 'replacement-release-ref' WHERE tenant_id = ? AND id = ?", - target.gameSessionTenantId(), - target.gameInstanceId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_instances SET run_owned_start_published_release_bundle_ref =" + + " 'replacement-release-ref' WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) .hasMessageContaining("runtime row is fenced"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_instances SET run_owned_start_active_epoch =" - + " run_owned_start_active_epoch + 1 WHERE tenant_id = ? AND id = ?", - target.gameSessionTenantId(), - target.gameInstanceId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_instances SET run_owned_start_active_epoch =" + + " run_owned_start_active_epoch + 1 WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) .hasMessageContaining("runtime row is fenced"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_instances SET row_version = row_version - 1" - + " WHERE tenant_id = ? AND id = ?", - target.gameSessionTenantId(), - target.gameInstanceId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_instances SET row_version = row_version - 1" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) .hasMessageContaining("runtime row is fenced"); - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM game_instances WHERE tenant_id = ? AND id = ?", - target.gameSessionTenantId(), - target.gameInstanceId())) + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM game_instances WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) .hasMessageContaining("runtime row is fenced"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_session_canonical_binding_transition" - + " SET status = 'ABORTED' WHERE transition_id = (" - + " SELECT transition_id FROM game_session_canonical_binding_transition" - + " WHERE candidate_binding_ref = ?)", - candidateRef)) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_session_canonical_binding_transition" + + " SET status = 'ABORTED' WHERE transition_id = (" + + " SELECT transition_id FROM game_session_canonical_binding_transition" + + " WHERE candidate_binding_ref = ?)", + candidateRef)) .hasMessageContaining("definitive first-NEW Account abort evidence"); assertThat( @@ -257,18 +249,17 @@ void freshSourceBoundRuntimeWithoutHumanCompletionCannotLoseRunOwnedLaunchProven // A fresh source-bound RUNNING row cannot be stripped of its run-owned launch association. // The V26 deferred guard rejects that impossible setup before V1044's lease-bound fence runs. - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_instances SET row_version = row_version + 1," - + " run_owned_start_request_id = NULL," - + " run_owned_start_request_digest = NULL," - + " run_owned_start_published_release_bundle_ref = NULL," - + " run_owned_start_preparing_epoch = NULL," - + " run_owned_start_active_epoch = NULL" - + " WHERE tenant_id = ? AND id = ?", - target.gameSessionTenantId(), - target.gameInstanceId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_instances SET row_version = row_version + 1," + + " run_owned_start_request_id = NULL," + + " run_owned_start_request_digest = NULL," + + " run_owned_start_published_release_bundle_ref = NULL," + + " run_owned_start_preparing_epoch = NULL," + + " run_owned_start_active_epoch = NULL" + + " WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId())) .hasMessageContaining( "Fresh Game Session instance requires one exact complete launch association"); @@ -745,17 +736,16 @@ private static void assertLaunchPreparationCatalogMismatchRejected( UUID canonicalTenantId, UUID sourceIntakeOperationId, UUID sourceIntakeRequestId) { - assertThatThrownBy( - () -> - insertLaunchPreparation( - dsl, - target, - realmId, - catalogCreationRequestId, - catalogRevision, - canonicalTenantId, - sourceIntakeOperationId, - sourceIntakeRequestId)) + assertThatThrownBy(() -> + insertLaunchPreparation( + dsl, + target, + realmId, + catalogCreationRequestId, + catalogRevision, + canonicalTenantId, + sourceIntakeOperationId, + sourceIntakeRequestId)) .hasMessageContaining("fk_gs_canonical_launch_preparation_catalog"); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java index 6aa935eb68..627b681611 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java @@ -72,15 +72,14 @@ void intentLedgerAcceptsAttemptWidthAndRejectsAnIdentityBeyond128Characters() { assertPendingIntent(dsl, intent128); Record originalIntent = readIntent(dsl, intent128); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_session_canonical_initial_admission_intent " - + "SET initial_admission_request_id = ? " - + "WHERE target_namespace = ? AND initial_admission_request_id = ?", - "r".repeat(129), - length128.targetNamespace(), - intent128.request().initialAdmissionRequestId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_session_canonical_initial_admission_intent " + + "SET initial_admission_request_id = ? " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + "r".repeat(129), + length128.targetNamespace(), + intent128.request().initialAdmissionRequestId())) .isInstanceOfSatisfying( DataAccessException.class, exception -> assertThat(exception.sqlState()).isEqualTo("22001")); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java index 38387b4fc1..7db05d3e1f 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java @@ -380,14 +380,13 @@ void firstOpenIsPersistedExactRetryIsReplayOnlyAndCutoffPreservesNewerClosedStat target.closedValue().initializer()); writePhysicalValue(target.key(), newerClosed); byte[] newerBytes = newerClosed.exactBytes(); - assertThatThrownBy( - () -> - state - .owner() - .closeAndRead( - cutoffOperationId, - target.closedValue().tenantId(), - target.closedValue().playableStateNamespaceId())) + assertThatThrownBy(() -> + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId())) .isInstanceOf(IllegalStateException.class); assertThat(administratorCommands.hget(bytes(target.key()), bytes("payload"))) .containsExactly(newerBytes); @@ -892,43 +891,32 @@ void cutoffRefusesChangedOrMissingFrozenEvidence(String corruption) { ? "gs_issuer_admission_cohort_guard" : "gs_issuer_admission_cutoff_target_guard"; RuntimeException rollback = new IllegalStateException("Controlled corruption rollback"); - assertThatThrownBy( - () -> - dsl.transaction( - configuration -> { - var transaction = DSL.using(configuration); - transaction.execute( - "ALTER TABLE " - + EVIDENCE_PREFIX - + family - + " DISABLE TRIGGER " - + trigger); - assertThat(transaction.execute(mutation, cutoffOperationId)).isPositive(); - String expectedMessage = - switch (corruption) { - case "SOURCE_BYTES" -> - "cohort source digest differs from its stored JSON"; - case "MISSING_SOURCE" -> - "cohort no longer matches its frozen complete digest"; - case "MISSING_TARGET" -> - "target set differs from its complete frozen cohort"; - case "TARGET_DIGEST" -> - "target differs from its immutable captured source"; - default -> throw new IllegalArgumentException(corruption); - }; - assertThatThrownBy( - () -> - new CanonicalGameplayIssuerAdmissionControlRepository(transaction) - .verifyCurrentCutoffTarget( - transaction, - pending, - target.closedValue().tenantId(), - target.closedValue().playableStateNamespaceId(), - target.closedValue().exactBytes())) - .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) - .hasMessageContaining(expectedMessage); - throw rollback; - })) + assertThatThrownBy(() -> + dsl.transaction(configuration -> { + var transaction = DSL.using(configuration); + transaction.execute( + "ALTER TABLE " + EVIDENCE_PREFIX + family + " DISABLE TRIGGER " + trigger); + assertThat(transaction.execute(mutation, cutoffOperationId)).isPositive(); + String expectedMessage = + switch (corruption) { + case "SOURCE_BYTES" -> "cohort source digest differs from its stored JSON"; + case "MISSING_SOURCE" -> "cohort no longer matches its frozen complete digest"; + case "MISSING_TARGET" -> "target set differs from its complete frozen cohort"; + case "TARGET_DIGEST" -> "target differs from its immutable captured source"; + default -> throw new IllegalArgumentException(corruption); + }; + assertThatThrownBy(() -> + new CanonicalGameplayIssuerAdmissionControlRepository(transaction) + .verifyCurrentCutoffTarget( + transaction, + pending, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId(), + target.closedValue().exactBytes())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining(expectedMessage); + throw rollback; + })) .isSameAs(rollback); assertThat(retainedEvidenceImage(dsl)).isEqualTo(before); assertThat( @@ -1324,30 +1312,28 @@ void liveIssuerCounterOnlyAdvanceFailsAtCommitAndRetainsOriginalAuthority(boolea var dsl = state.fixture().dsl(); var before = liveControlEvidenceImage(dsl); AtomicBoolean allocationExecuted = new AtomicBoolean(); - assertThatThrownBy( - () -> - dsl.transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - assertThat( - transaction.execute( - "UPDATE " - + EVIDENCE_PREFIX - + "epoch_counter" - + " SET last_live_barrier_epoch = last_live_barrier_epoch + 1")) - .isEqualTo(1); - assertThat( - transaction - .fetchSingle( - "SELECT counter.last_live_barrier_epoch - control.live_barrier_epoch FROM " - + EVIDENCE_PREFIX - + "epoch_counter counter JOIN " - + EVIDENCE_PREFIX - + "control control USING (issuer_id)") - .get(0, BigInteger.class)) - .isEqualTo(ONE); - allocationExecuted.set(true); - })) + assertThatThrownBy(() -> + dsl.transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + assertThat( + transaction.execute( + "UPDATE " + + EVIDENCE_PREFIX + + "epoch_counter" + + " SET last_live_barrier_epoch = last_live_barrier_epoch + 1")) + .isEqualTo(1); + assertThat( + transaction + .fetchSingle( + "SELECT counter.last_live_barrier_epoch - control.live_barrier_epoch FROM " + + EVIDENCE_PREFIX + + "epoch_counter counter JOIN " + + EVIDENCE_PREFIX + + "control control USING (issuer_id)") + .get(0, BigInteger.class)) + .isEqualTo(ONE); + allocationExecuted.set(true); + })) .hasStackTraceContaining("Live issuer admission epoch counter and control"); assertThat(allocationExecuted).isTrue(); assertThat(liveControlEvidenceImage(dsl)).isEqualTo(before); @@ -1380,11 +1366,10 @@ void liveIssuerGuardUpgradeRejectsIncompatibleRetainedEpochPair(boolean missingC } var before = liveControlEvidenceImage(dsl); var historyBefore = migrationHistoryImage(dsl); - assertThatThrownBy( - () -> - CanonicalGameplayAdmissionAbortCompositionFixture - .upgradeWithDefaultGameSessionMigrations( - MigrationVersion.fromVersion("1047.2"), dataSource)) + assertThatThrownBy(() -> + CanonicalGameplayAdmissionAbortCompositionFixture + .upgradeWithDefaultGameSessionMigrations( + MigrationVersion.fromVersion("1047.2"), dataSource)) .hasStackTraceContaining("Live issuer admission epoch counter and control"); assertThat(liveControlEvidenceImage(dsl)).isEqualTo(before); assertThat(migrationHistoryImage(dsl)).containsExactlyElementsOf(historyBefore); @@ -1520,39 +1505,36 @@ void callerOwnedJooqTransactionRefusesBeforeSourceOrRemoteDispatch() { var dsl = state.fixture().dsl(); var current = state.currentState().get(); var anchor = - dsl.transactionResult( - configuration -> { - var transaction = org.jooq.impl.DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - return CanonicalGameplayIssuerBootstrapCoverageRepository - .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); - }); + dsl.transactionResult(configuration -> { + var transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + return CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + }); AtomicBoolean sourceCalled = new AtomicBoolean(); CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource source = () -> { sourceCalled.set(true); return current; }; - dsl.transaction( - configuration -> { - var transaction = org.jooq.impl.DSL.using(configuration); - var repository = - new CanonicalGameplayIssuerAdmissionBarrierRepository( - transaction, - new CanonicalGameplayTenantGameplayTagRepository( - transaction, state.fixture().target().targetNamespace(), 1), - source); - assertThatThrownBy( - () -> repository.readPreparedInitializer(state.fixture().originalOperationId())) - .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) - .hasMessageContaining("jOOQ transaction"); - assertThatThrownBy( - () -> - new CanonicalGameplayIssuerAdmissionControlRepository(transaction) - .installInitialOpen(anchor, source)) - .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) - .hasMessageContaining("jOOQ transaction"); - }); + dsl.transaction(configuration -> { + var transaction = org.jooq.impl.DSL.using(configuration); + var repository = + new CanonicalGameplayIssuerAdmissionBarrierRepository( + transaction, + new CanonicalGameplayTenantGameplayTagRepository( + transaction, state.fixture().target().targetNamespace(), 1), + source); + assertThatThrownBy( + () -> repository.readPreparedInitializer(state.fixture().originalOperationId())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("jOOQ transaction"); + assertThatThrownBy(() -> + new CanonicalGameplayIssuerAdmissionControlRepository(transaction) + .installInitialOpen(anchor, source)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("jOOQ transaction"); + }); assertThat(sourceCalled).isFalse(); assertThat( dsl.fetchCount( @@ -1685,13 +1667,12 @@ private HistoricalAdmissionState prepareHistoricalAdmission( private static CanonicalGameplayIssuerInstalledAnchor readInstalledAnchor( DSLContext dsl, CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { - return dsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - return CanonicalGameplayIssuerBootstrapCoverageRepository - .readInstalledAnchorForBindingPreparationInTransaction(transaction, currentState); - }); + return dsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + return CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, currentState); + }); } private static List migrationHistoryImage(DSLContext dsl) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java index a321933d8e..c14ee64cbc 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java @@ -244,18 +244,17 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() .containsExactly(anchor.sourceEventBytes()); assertThat(sourceEventPair.get("anchor_source_event_digest", String.class)) .isEqualTo(anchor.sourceEventDigest()); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO game_session_canonical_issuer_binding_local_operation" - + " SELECT (jsonb_populate_record(NULL::" - + "game_session_canonical_issuer_binding_local_operation," - + " to_jsonb(operation) || jsonb_build_object('operation_id', ?::text," - + " 'anchor_source_event_digest', NULL))).*" - + " FROM game_session_canonical_issuer_binding_local_operation operation" - + " WHERE operation_id = ?", - UUID.randomUUID(), - first.operationId())) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO game_session_canonical_issuer_binding_local_operation" + + " SELECT (jsonb_populate_record(NULL::" + + "game_session_canonical_issuer_binding_local_operation," + + " to_jsonb(operation) || jsonb_build_object('operation_id', ?::text," + + " 'anchor_source_event_digest', NULL))).*" + + " FROM game_session_canonical_issuer_binding_local_operation operation" + + " WHERE operation_id = ?", + UUID.randomUUID(), + first.operationId())) .hasMessageContaining("chk_gs_issuer_binding_local_operation_source_event_pair"); assertThat(first.memberValue().incarnation()).isEqualTo(incarnation); assertThat(first.memberValue().memberOperation().coverageGeneration()) @@ -319,29 +318,24 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() assertThat(proofImage(dsl)).isEqualTo(installedProofImage); String beforeRefusals = localRegistrationImage(dsl); - assertThatThrownBy( - () -> - operationRepository.beginOrResumeOrdinaryNew( - request("changed-first-request", "first-new-transition", firstCandidate))) + assertThatThrownBy(() -> + operationRepository.beginOrResumeOrdinaryNew( + request("changed-first-request", "first-new-transition", firstCandidate))) .isInstanceOf(IllegalStateException.class); assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); - assertThatThrownBy( - () -> - operationRepository.beginOrResumeOrdinaryNew( - request("first-new-request", "other-transition", identity("changed-first")))) + assertThatThrownBy(() -> + operationRepository.beginOrResumeOrdinaryNew( + request("first-new-request", "other-transition", identity("changed-first")))) .isInstanceOf(IllegalStateException.class); assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); currentState.set( new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( checkpointShape(BigInteger.valueOf(8)), incarnation)); - assertThatThrownBy( - () -> - operationRepository.beginOrResumeOrdinaryNew( - request( - "moved-source-request", - "moved-source-transition", - identity("moved-source")))) + assertThatThrownBy(() -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "moved-source-request", "moved-source-transition", identity("moved-source")))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("source"); assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); @@ -350,33 +344,30 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() currentState.set( new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( intent.sourceCheckpoint(), stableIncarnation("moved-incarnation"))); - assertThatThrownBy( - () -> - operationRepository.beginOrResumeOrdinaryNew( - request( - "moved-incarnation-request", - "moved-incarnation-transition", - identity("moved-incarnation")))) + assertThatThrownBy(() -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "moved-incarnation-request", + "moved-incarnation-transition", + identity("moved-incarnation")))) .isInstanceOf(IllegalStateException.class); assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); currentState.set(initialState); - assertThatThrownBy( - () -> - operationRepository.beginOrResumeOrdinaryNew( - request( - "wrong-layout-request", - "wrong-layout-transition", - identityWithLayout("wrong-layout", BigInteger.TWO)))) + assertThatThrownBy(() -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "wrong-layout-request", + "wrong-layout-transition", + identityWithLayout("wrong-layout", BigInteger.TWO)))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("layout"); assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); var sameController = sameControllerDifferentBinding(firstCandidate, "same-controller"); - assertThatThrownBy( - () -> - operationRepository.beginOrResumeOrdinaryNew( - request("controller-request", "controller-transition", sameController))) + assertThatThrownBy(() -> + operationRepository.beginOrResumeOrdinaryNew( + request("controller-request", "controller-transition", sameController))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("controller"); assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); @@ -385,11 +376,9 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() new CanonicalGameplayAccountAdmissionBarrierRepository(dsl) .beginFenceIntent(firstCandidate.accountId(), UUID.randomUUID()); String accountFencedImage = localRegistrationImage(dsl); - assertThatThrownBy( - () -> - operationRepository.beginOrResumeOrdinaryNew( - request( - "account-fenced-request", "account-fenced-transition", fencedCandidate))) + assertThatThrownBy(() -> + operationRepository.beginOrResumeOrdinaryNew( + request("account-fenced-request", "account-fenced-transition", fencedCandidate))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("Account"); assertThat(localRegistrationImage(dsl)).isEqualTo(accountFencedImage); @@ -428,10 +417,9 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() assertThat(proofImage(dsl)).isEqualTo(installedProofImage); String beforeCapacityRefusal = localRegistrationImage(dsl); - assertThatThrownBy( - () -> - operationRepository.beginOrResumeOrdinaryNew( - request("capacity-request", "capacity-transition", identity("capacity-new")))) + assertThatThrownBy(() -> + operationRepository.beginOrResumeOrdinaryNew( + request("capacity-request", "capacity-transition", identity("capacity-new")))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("capacity"); assertThat(localRegistrationImage(dsl)).isEqualTo(beforeCapacityRefusal); @@ -530,13 +518,12 @@ void ordinaryNewPhysicalOperationBoundRefuses257thBeforePreparationAndRetainsExa String beforeRefusal = localRegistrationImage(dsl); String anchorBefore = anchorImage(dsl); String proofBefore = proofImage(dsl); - assertThatThrownBy( - () -> - repository.beginOrResumeOrdinaryNew( - request( - "physical-bound-request-256", - "physical-bound-transition-256", - identityWithLayout("physical-bound-256", LAYOUT_VERSION, capacity)))) + assertThatThrownBy(() -> + repository.beginOrResumeOrdinaryNew( + request( + "physical-bound-request-256", + "physical-bound-transition-256", + identityWithLayout("physical-bound-256", LAYOUT_VERSION, capacity)))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("physical owner bound"); assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusal); @@ -586,48 +573,47 @@ void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { // Controlled pre-upgrade SQL receipts exercise retention, immutability and the pending FK. // They do not claim an ordinary NEW producer, Redis mutation/readback or admission. The // bootstrap above uses the actual SQL/Redis owner with controlled Account/incarnation inputs. - dsl.transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - insertPreLineageMutation( - transaction, - committedId, - historicalOwnerId, - "ADD_CAPACITY", - initialRevision, - successor, - intended); - transaction.execute( - "UPDATE game_session_canonical_issuer_partition_mutation_head" - + " SET pending_mutation_id = ? WHERE issuer_id = ?", - committedId, - ISSUER); - transaction.execute( - "UPDATE game_session_canonical_issuer_partition_mutation" - + " SET status = 'COMMITTED', exact_readback_field_set_bytes = ?," - + " exact_readback_field_set_digest = ?, completed_at = CURRENT_TIMESTAMP WHERE mutation_id = ?", - readback, - digest(readback), - committedId); - transaction.execute( - "UPDATE game_session_canonical_issuer_partition_mutation_head" - + " SET current_revision = ?, pending_mutation_id = NULL WHERE issuer_id = ?", - successor, - ISSUER); - insertPreLineageMutation( - transaction, - pendingId, - historicalOwnerId, - "ADD_BINDING", - successor, - laterSuccessor, - intended); - transaction.execute( - "UPDATE game_session_canonical_issuer_partition_mutation_head" - + " SET pending_mutation_id = ? WHERE issuer_id = ?", - pendingId, - ISSUER); - }); + dsl.transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + insertPreLineageMutation( + transaction, + committedId, + historicalOwnerId, + "ADD_CAPACITY", + initialRevision, + successor, + intended); + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_mutation_head" + + " SET pending_mutation_id = ? WHERE issuer_id = ?", + committedId, + ISSUER); + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_mutation" + + " SET status = 'COMMITTED', exact_readback_field_set_bytes = ?," + + " exact_readback_field_set_digest = ?, completed_at = CURRENT_TIMESTAMP WHERE mutation_id = ?", + readback, + digest(readback), + committedId); + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_mutation_head" + + " SET current_revision = ?, pending_mutation_id = NULL WHERE issuer_id = ?", + successor, + ISSUER); + insertPreLineageMutation( + transaction, + pendingId, + historicalOwnerId, + "ADD_BINDING", + successor, + laterSuccessor, + intended); + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_mutation_head" + + " SET pending_mutation_id = ? WHERE issuer_id = ?", + pendingId, + ISSUER); + }); List beforeHistory = dsl.fetch( "SELECT to_jsonb(mutation)::text FROM game_session_canonical_issuer_partition_mutation mutation ORDER BY mutation_id") @@ -663,45 +649,42 @@ void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { "SELECT DISTINCT bootstrap_operation_id FROM game_session_canonical_issuer_partition_mutation") .getValues(0, UUID.class)) .containsExactly(anchor.bootstrapOperationId()); - dsl.transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - var head = - CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( - transaction, anchor.bootstrapOperationId(), BigInteger.ZERO); - assertThat(head.pendingMutationId()).isEqualTo(pendingId); - assertThat(head.currentRevision()).isEqualTo(successor); - var history = - List.of( - CanonicalGameplayIssuerPartitionMutationRepository.readInTransaction( - transaction, - CanonicalGameplayIssuerPartitionMutation.Kind.ADD_CAPACITY, - historicalOwnerId, - BigInteger.ZERO), - CanonicalGameplayIssuerPartitionMutationRepository.readInTransaction( - transaction, - CanonicalGameplayIssuerPartitionMutation.Kind.ADD_BINDING, - historicalOwnerId, - BigInteger.ZERO)); - assertThat(history).hasSize(2); - assertThat(history.stream().map(CanonicalGameplayIssuerPartitionMutation::status)) - .containsExactlyInAnyOrder( - CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED, - CanonicalGameplayIssuerPartitionMutation.Status.PENDING_PHYSICAL_PROOF); - }); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_session_canonical_issuer_partition_mutation SET bootstrap_operation_id = ? WHERE mutation_id = ?", - UUID.randomUUID(), - pendingId)) + dsl.transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + var head = + CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( + transaction, anchor.bootstrapOperationId(), BigInteger.ZERO); + assertThat(head.pendingMutationId()).isEqualTo(pendingId); + assertThat(head.currentRevision()).isEqualTo(successor); + var history = + List.of( + CanonicalGameplayIssuerPartitionMutationRepository.readInTransaction( + transaction, + CanonicalGameplayIssuerPartitionMutation.Kind.ADD_CAPACITY, + historicalOwnerId, + BigInteger.ZERO), + CanonicalGameplayIssuerPartitionMutationRepository.readInTransaction( + transaction, + CanonicalGameplayIssuerPartitionMutation.Kind.ADD_BINDING, + historicalOwnerId, + BigInteger.ZERO)); + assertThat(history).hasSize(2); + assertThat(history.stream().map(CanonicalGameplayIssuerPartitionMutation::status)) + .containsExactlyInAnyOrder( + CanonicalGameplayIssuerPartitionMutation.Status.COMMITTED, + CanonicalGameplayIssuerPartitionMutation.Status.PENDING_PHYSICAL_PROOF); + }); + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_session_canonical_issuer_partition_mutation SET bootstrap_operation_id = ? WHERE mutation_id = ?", + UUID.randomUUID(), + pendingId)) .hasMessageContaining("immutable"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_session_canonical_issuer_partition_mutation_head SET bootstrap_operation_id = ? WHERE issuer_id = ?", - UUID.randomUUID(), - ISSUER)) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_session_canonical_issuer_partition_mutation_head SET bootstrap_operation_id = ? WHERE issuer_id = ?", + UUID.randomUUID(), + ISSUER)) .hasMessageContaining("immutable"); assertThat( dsl.fetch( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java index 6db9cde1fd..c065539095 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java @@ -380,29 +380,24 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t assertThat(proofImage(dsl)).isEqualTo(installedProofImage); String beforeRefusals = localRegistrationImage(dsl); - assertThatThrownBy( - () -> - operationRepository.beginOrResumeOrdinaryNew( - request("changed-first-request", "first-new-transition", firstCandidate))) + assertThatThrownBy(() -> + operationRepository.beginOrResumeOrdinaryNew( + request("changed-first-request", "first-new-transition", firstCandidate))) .isInstanceOf(IllegalStateException.class); assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); - assertThatThrownBy( - () -> - operationRepository.beginOrResumeOrdinaryNew( - request("first-new-request", "other-transition", identity("changed-first")))) + assertThatThrownBy(() -> + operationRepository.beginOrResumeOrdinaryNew( + request("first-new-request", "other-transition", identity("changed-first")))) .isInstanceOf(IllegalStateException.class); assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); currentState.set( new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( checkpointShape(BigInteger.valueOf(8)), incarnation)); - assertThatThrownBy( - () -> - operationRepository.beginOrResumeOrdinaryNew( - request( - "moved-source-request", - "moved-source-transition", - identity("moved-source")))) + assertThatThrownBy(() -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "moved-source-request", "moved-source-transition", identity("moved-source")))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("source"); assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); @@ -411,33 +406,30 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t currentState.set( new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( intent.sourceCheckpoint(), stableIncarnation("moved-incarnation"))); - assertThatThrownBy( - () -> - operationRepository.beginOrResumeOrdinaryNew( - request( - "moved-incarnation-request", - "moved-incarnation-transition", - identity("moved-incarnation")))) + assertThatThrownBy(() -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "moved-incarnation-request", + "moved-incarnation-transition", + identity("moved-incarnation")))) .isInstanceOf(IllegalStateException.class); assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); currentState.set(initialState); - assertThatThrownBy( - () -> - operationRepository.beginOrResumeOrdinaryNew( - request( - "wrong-layout-request", - "wrong-layout-transition", - identityWithLayout("wrong-layout", BigInteger.TWO)))) + assertThatThrownBy(() -> + operationRepository.beginOrResumeOrdinaryNew( + request( + "wrong-layout-request", + "wrong-layout-transition", + identityWithLayout("wrong-layout", BigInteger.TWO)))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("layout"); assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); var sameController = sameControllerDifferentBinding(firstCandidate, "same-controller"); - assertThatThrownBy( - () -> - operationRepository.beginOrResumeOrdinaryNew( - request("controller-request", "controller-transition", sameController))) + assertThatThrownBy(() -> + operationRepository.beginOrResumeOrdinaryNew( + request("controller-request", "controller-transition", sameController))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("controller"); assertThat(localRegistrationImage(dsl)).isEqualTo(beforeRefusals); @@ -588,27 +580,26 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t .formatJSON()) .isEqualTo(acknowledgementCounterImageBeforeAmbientRefusals); - dsl.transaction( - configuration -> { - DSLContext callerTransaction = DSL.using(configuration); - var callerOwnedAcknowledgementRepository = - new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository( - callerTransaction, acknowledgementSource); - assertThatThrownBy( - () -> callerOwnedAcknowledgementRepository.acknowledge(acknowledgementReadback)) - .isInstanceOf(IllegalStateException.class) - .hasMessage( - "Issuer binding-local acknowledgement is unavailable: Issuer acknowledgement owner cannot join a jOOQ transaction"); - assertThat(acknowledgementSourceReads).hasValue(0); - assertThat(callerTransaction.fetch("SELECT * FROM " + ACKNOWLEDGEMENT_TABLE).formatJSON()) - .isEqualTo(acknowledgementImageBeforeAmbientRefusals); - assertThat( - callerTransaction - .fetch( - "SELECT * FROM game_session_canonical_issuer_binding_local_ack_gen_counter") - .formatJSON()) - .isEqualTo(acknowledgementCounterImageBeforeAmbientRefusals); - }); + dsl.transaction(configuration -> { + DSLContext callerTransaction = DSL.using(configuration); + var callerOwnedAcknowledgementRepository = + new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository( + callerTransaction, acknowledgementSource); + assertThatThrownBy( + () -> callerOwnedAcknowledgementRepository.acknowledge(acknowledgementReadback)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Issuer binding-local acknowledgement is unavailable: Issuer acknowledgement owner cannot join a jOOQ transaction"); + assertThat(acknowledgementSourceReads).hasValue(0); + assertThat(callerTransaction.fetch("SELECT * FROM " + ACKNOWLEDGEMENT_TABLE).formatJSON()) + .isEqualTo(acknowledgementImageBeforeAmbientRefusals); + assertThat( + callerTransaction + .fetch( + "SELECT * FROM game_session_canonical_issuer_binding_local_ack_gen_counter") + .formatJSON()) + .isEqualTo(acknowledgementCounterImageBeforeAmbientRefusals); + }); assertThat(dsl.fetch("SELECT * FROM " + ACKNOWLEDGEMENT_TABLE).formatJSON()) .isEqualTo(acknowledgementImageBeforeAmbientRefusals); assertThat( @@ -655,13 +646,12 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t "Expected owner-issued local ACK generation counter") .get("last_issued_binding_local_acknowledgement_generation", BigDecimal.class)) .isEqualTo(BigDecimal.ONE); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_session_canonical_issuer_binding_local_ack_gen_counter" - + " SET last_issued_binding_local_acknowledgement_generation = 3," - + " counter_version = counter_version + 1 WHERE issuer_id = ?", - ISSUER)) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_session_canonical_issuer_binding_local_ack_gen_counter" + + " SET last_issued_binding_local_acknowledgement_generation = 3," + + " counter_version = counter_version + 1 WHERE issuer_id = ?", + ISSUER)) .hasMessageContaining("must advance its own domain by one"); assertThat( Objects.requireNonNull( @@ -686,15 +676,14 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t assertThat(restartedAcknowledgementRepository.readHistorical(first.operationId()).exactBytes()) .containsExactly(issuerAcknowledgement.exactBytes()); var transactionLocalHistoricalReceipt = - dsl.transactionResult( - configuration -> { - DSLContext historicalQuery = DSL.using(configuration); - boolean autoCommit = - historicalQuery.connectionResult(connection -> connection.getAutoCommit()); - assertThat(autoCommit).isFalse(); - return CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.readHistorical( - historicalQuery, first.operationId()); - }); + dsl.transactionResult(configuration -> { + DSLContext historicalQuery = DSL.using(configuration); + boolean autoCommit = + historicalQuery.connectionResult(connection -> connection.getAutoCommit()); + assertThat(autoCommit).isFalse(); + return CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.readHistorical( + historicalQuery, first.operationId()); + }); assertThat(transactionLocalHistoricalReceipt.exactBytes()) .containsExactly(issuerAcknowledgement.exactBytes()); assertThat(transactionLocalHistoricalReceipt.digest()) @@ -710,20 +699,18 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t "Expected replay to retain the owner-issued ACK generation") .get("last_issued_binding_local_acknowledgement_generation", BigDecimal.class)) .isEqualTo(BigDecimal.ONE); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_session_canonical_issuer_binding_local_acknowledgement" - + " SET acknowledgement_bytes = ? WHERE operation_id = ?", - issuerAcknowledgement.exactBytes(), - first.operationId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_session_canonical_issuer_binding_local_acknowledgement" + + " SET acknowledgement_bytes = ? WHERE operation_id = ?", + issuerAcknowledgement.exactBytes(), + first.operationId())) .hasMessageContaining("issuer binding-local acknowledgements are immutable"); - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM game_session_canonical_issuer_binding_local_acknowledgement" - + " WHERE operation_id = ?", - first.operationId())) + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM game_session_canonical_issuer_binding_local_acknowledgement" + + " WHERE operation_id = ?", + first.operationId())) .hasMessageContaining("issuer binding-local acknowledgements are immutable"); assertThat(count(dsl, ACKNOWLEDGEMENT_TABLE)).isEqualTo(1L); currentState.set( @@ -738,10 +725,9 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t currentState.set(initialState); String beforeCapacityRefusal = localRegistrationImage(dsl); - assertThatThrownBy( - () -> - operationRepository.beginOrResumeOrdinaryNew( - request("capacity-request", "capacity-transition", identity("capacity-new")))) + assertThatThrownBy(() -> + operationRepository.beginOrResumeOrdinaryNew( + request("capacity-request", "capacity-transition", identity("capacity-new")))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("capacity"); assertThat(localRegistrationImage(dsl)).isEqualTo(beforeCapacityRefusal); @@ -837,11 +823,9 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t new CanonicalGameplayAccountAdmissionBarrierRepository(dsl) .beginFenceIntent(firstCandidate.accountId(), UUID.randomUUID()); String accountFencedImage = localRegistrationImage(dsl); - assertThatThrownBy( - () -> - operationRepository.beginOrResumeOrdinaryNew( - request( - "account-fenced-request", "account-fenced-transition", fencedCandidate))) + assertThatThrownBy(() -> + operationRepository.beginOrResumeOrdinaryNew( + request("account-fenced-request", "account-fenced-transition", fencedCandidate))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("Account"); assertThat(localRegistrationImage(dsl)).isEqualTo(accountFencedImage); @@ -1198,9 +1182,8 @@ private byte[][] malformedReleaseBaselineArguments(byte[] key, String malformedC Map baseline = new TreeMap<>(); administratorCommands .hgetall(key) - .forEach( - (field, value) -> - baseline.put(new String(field, StandardCharsets.UTF_8), value.clone())); + .forEach((field, value) -> + baseline.put(new String(field, StandardCharsets.UTF_8), value.clone())); assertThat(baseline).containsKey(METADATA_FIELD).containsKey(malformedCapacityField); ObjectNode malformedMember = @@ -1214,11 +1197,10 @@ private byte[][] malformedReleaseBaselineArguments(byte[] key, String malformedC arguments.add(ascii(PARTITION_COUNT.toString())); arguments.add(ascii(PARTITION_CAPACITY.toString())); arguments.add(ascii(Integer.toString(baseline.size()))); - baseline.forEach( - (field, value) -> { - arguments.add(field.getBytes(StandardCharsets.UTF_8)); - arguments.add(value); - }); + baseline.forEach((field, value) -> { + arguments.add(field.getBytes(StandardCharsets.UTF_8)); + arguments.add(value); + }); while (arguments.size() < 16) arguments.add(ascii("unused")); return arguments.toArray(byte[][]::new); } @@ -1245,11 +1227,10 @@ private Map hashImage(byte[] key) { Map image = new TreeMap<>(); administratorCommands .hgetall(key) - .forEach( - (field, value) -> - image.put( - Base64.getEncoder().encodeToString(field), - Base64.getEncoder().encodeToString(value))); + .forEach((field, value) -> + image.put( + Base64.getEncoder().encodeToString(field), + Base64.getEncoder().encodeToString(value))); return image; } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java index 6371488c11..e8caeab249 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java @@ -118,14 +118,13 @@ void installsOnlyAfterEveryPopulatedAndEmptyPartitionHasExactPhysicalProofAndRep String installedAnchorImage = anchorStorageImage(fixture.dsl()); String installedProofImage = proofStorageImage(fixture.dsl()); var installedPhysicalImage = physicalPartitionImages(fixture); - assertThatThrownBy( - () -> - new CanonicalGameplayIssuerLayoutBootstrapRepository(fixture.dsl()) - .supersedeStaleInitialBootstrapIntent( - fixture.intent().operationId(), - UUID.randomUUID(), - descriptor(PARTITION_COUNT, PARTITION_CAPACITY), - fixture.currentAccountCheckpoint())) + assertThatThrownBy(() -> + new CanonicalGameplayIssuerLayoutBootstrapRepository(fixture.dsl()) + .supersedeStaleInitialBootstrapIntent( + fixture.intent().operationId(), + UUID.randomUUID(), + descriptor(PARTITION_COUNT, PARTITION_CAPACITY), + fixture.currentAccountCheckpoint())) .hasMessageContaining("installed issuer anchor forbids"); assertThat(anchorStorageImage(fixture.dsl())).isEqualTo(installedAnchorImage); assertThat(proofStorageImage(fixture.dsl())).isEqualTo(installedProofImage); @@ -281,11 +280,10 @@ void freshPhysicalVerificationRefusesMissingPartitionWithoutRebuildingOrAllocati missingKeyArguments[0] = missingKey; administratorCommands.del(missingKeyArguments); - assertThatThrownBy( - () -> - owner(fixture, () -> current) - .verifyInstalledPhysicalCoverage( - fixture.intent().operationId(), fixture.requestId())) + assertThatThrownBy(() -> + owner(fixture, () -> current) + .verifyInstalledPhysicalCoverage( + fixture.intent().operationId(), fixture.requestId())) .isInstanceOf(IllegalStateException.class); assertThat(administratorCommands.type(missingKey)).isEqualTo("none"); assertThat( @@ -360,32 +358,28 @@ void installedOriginalRetryRejectsWrongTupleAndChangedSourceOrIncarnation() { String counterImage = coverageCounterImage(fixture.dsl()); List> physicalImage = physicalPartitionImages(fixture); - assertThatThrownBy( - () -> - owner(fixture, () -> current) - .completeInitialBootstrap(UUID.randomUUID(), fixture.requestId())) + assertThatThrownBy(() -> + owner(fixture, () -> current) + .completeInitialBootstrap(UUID.randomUUID(), fixture.requestId())) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - owner(fixture, () -> current) - .completeInitialBootstrap(fixture.intent().operationId(), UUID.randomUUID())) + assertThatThrownBy(() -> + owner(fixture, () -> current) + .completeInitialBootstrap(fixture.intent().operationId(), UUID.randomUUID())) .isInstanceOf(IllegalStateException.class); var changedSource = new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( checkpointShape(BigInteger.valueOf(8)), current.incarnation()); - assertThatThrownBy( - () -> - owner(fixture, () -> changedSource) - .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) + assertThatThrownBy(() -> + owner(fixture, () -> changedSource) + .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) .isInstanceOf(IllegalStateException.class); var changedIncarnation = new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( current.accountCheckpoint(), changedIncarnation(current.incarnation())); - assertThatThrownBy( - () -> - owner(fixture, () -> changedIncarnation) - .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) + assertThatThrownBy(() -> + owner(fixture, () -> changedIncarnation) + .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) .isInstanceOf(IllegalStateException.class); assertThat(anchorStorageImage(fixture.dsl())).isEqualTo(anchorImage); @@ -408,11 +402,10 @@ void movedAccountCheckpointOrStorageIncarnationLeavesNoCoverageGenerationOrPoint ? changedCheckpoint : sourceFixture.intent().sourceCheckpoint(), sourceIncarnation); - assertThatThrownBy( - () -> - owner(sourceFixture, changedAfterReadback) - .completeInitialBootstrap( - sourceFixture.intent().operationId(), sourceFixture.requestId())) + assertThatThrownBy(() -> + owner(sourceFixture, changedAfterReadback) + .completeInitialBootstrap( + sourceFixture.intent().operationId(), sourceFixture.requestId())) .isInstanceOf(IllegalStateException.class); assertNoInstalledCoverage(sourceFixture); assertThat(fixtureProofCount(sourceFixture)).isZero(); @@ -429,11 +422,10 @@ void movedAccountCheckpointOrStorageIncarnationLeavesNoCoverageGenerationOrPoint incarnationCalls.incrementAndGet() == 5 ? changedIncarnation : initialIncarnation); - assertThatThrownBy( - () -> - owner(incarnationFixture, changedIncarnationAfterReadback) - .completeInitialBootstrap( - incarnationFixture.intent().operationId(), incarnationFixture.requestId())) + assertThatThrownBy(() -> + owner(incarnationFixture, changedIncarnationAfterReadback) + .completeInitialBootstrap( + incarnationFixture.intent().operationId(), incarnationFixture.requestId())) .isInstanceOf(IllegalStateException.class); assertNoInstalledCoverage(incarnationFixture); assertThat(fixtureProofCount(incarnationFixture)).isZero(); @@ -446,10 +438,9 @@ void absentOrMalformedPartitionAndLegacyValueDoNotIssueCoverageGeneration() { administratorCommands.set(partitionKey, ascii("retained-wrong-type")); var current = currentState(fixture, stableIncarnation("wrong-type")); - assertThatThrownBy( - () -> - owner(fixture, () -> current) - .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) + assertThatThrownBy(() -> + owner(fixture, () -> current) + .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) .isInstanceOf(IllegalStateException.class); assertNoInstalledCoverage(fixture); assertThat(administratorCommands.type(partitionKey)).isEqualTo("string"); @@ -469,10 +460,9 @@ void finitePlanCapacityConflictDoesNotCreateAnyPartitionOrCoverageGeneration() { .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.BLOCKED); var current = currentState(fixture, stableIncarnation("capacity-conflict")); - assertThatThrownBy( - () -> - owner(fixture, () -> current) - .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) + assertThatThrownBy(() -> + owner(fixture, () -> current) + .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("blockers"); assertNoInstalledCoverage(fixture); @@ -531,10 +521,9 @@ private void assertPhysicalTupleConflict(boolean wrongNewAnchor) { expected.reservation().reservationId())), changedBytes); - assertThatThrownBy( - () -> - owner(fixture, () -> current) - .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) + assertThatThrownBy(() -> + owner(fixture, () -> current) + .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId())) .isInstanceOf(IllegalStateException.class); assertNoInstalledCoverage(fixture); assertThat(fixtureProofCount(fixture)).isZero(); @@ -852,11 +841,10 @@ private List> physicalPartitionImages(Fixture fixture) { partitionId = partitionId.add(BigInteger.ONE)) { Map raw = administratorCommands.hgetall(key(fixture, partitionId)); Map image = new LinkedHashMap<>(); - raw.forEach( - (field, value) -> - image.put( - Base64.getEncoder().encodeToString(field), - Base64.getEncoder().encodeToString(value))); + raw.forEach((field, value) -> + image.put( + Base64.getEncoder().encodeToString(field), + Base64.getEncoder().encodeToString(value))); images.add(Map.copyOf(image)); } return List.copyOf(images); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java index 76f3eeb7b8..f362a588ab 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapMemberOperationRepositoryIntegrationTest.java @@ -207,14 +207,13 @@ void actualPreparedPlanIssuesExactPendingV2OperationAndPreservesV1031RowsAcrossR .containsExactly(operation.exactMemberValueBytes()); assertThat(rowSnapshots(fixture.testSchema().dsl())).isEqualTo(retainedBefore); - assertThatThrownBy( - () -> - owner.beginOrResumePendingPhysicalProof( - fixture.intent().operationId(), - fixture.requestId(), - 0, - fixture.currentAccountCheckpoint(), - stableIncarnation("changed-incarnation"))) + assertThatThrownBy(() -> + owner.beginOrResumePendingPhysicalProof( + fixture.intent().operationId(), + fixture.requestId(), + 0, + fixture.currentAccountCheckpoint(), + stableIncarnation("changed-incarnation"))) .isInstanceOf(IllegalStateException.class); assertThat( rowImages( @@ -222,61 +221,54 @@ void actualPreparedPlanIssuesExactPendingV2OperationAndPreservesV1031RowsAcrossR "game_session_canonical_issuer_bootstrap_member_operation")) .hasSize(1); - assertThatThrownBy( - () -> - fixture - .testSchema() - .dsl() - .execute( - "UPDATE game_session_canonical_issuer_bootstrap_member_operation" - + " SET member_status = 'PHYSICAL_PROOF_COMPLETE' WHERE member_operation_id = ?", - operation.operationId())) + assertThatThrownBy(() -> + fixture + .testSchema() + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_bootstrap_member_operation" + + " SET member_status = 'PHYSICAL_PROOF_COMPLETE' WHERE member_operation_id = ?", + operation.operationId())) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - fixture - .testSchema() - .dsl() - .execute( - "DELETE FROM game_session_canonical_issuer_bootstrap_member_operation" - + " WHERE member_operation_id = ?", - operation.operationId())) + assertThatThrownBy(() -> + fixture + .testSchema() + .dsl() + .execute( + "DELETE FROM game_session_canonical_issuer_bootstrap_member_operation" + + " WHERE member_operation_id = ?", + operation.operationId())) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - fixture - .testSchema() - .dsl() - .execute("TRUNCATE game_session_canonical_issuer_bootstrap_member_operation")) + assertThatThrownBy(() -> + fixture + .testSchema() + .dsl() + .execute("TRUNCATE game_session_canonical_issuer_bootstrap_member_operation")) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - fixture - .testSchema() - .dsl() - .execute( - "UPDATE game_session_canonical_issuer_bootstrap_member_op_counter" - + " SET last_issued_operation_fence = last_issued_operation_fence + 1" - + " WHERE issuer_id = ?", - ISSUER)) + assertThatThrownBy(() -> + fixture + .testSchema() + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_bootstrap_member_op_counter" + + " SET last_issued_operation_fence = last_issued_operation_fence + 1" + + " WHERE issuer_id = ?", + ISSUER)) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - fixture - .testSchema() - .dsl() - .execute( - "DELETE FROM game_session_canonical_issuer_bootstrap_member_op_counter" - + " WHERE issuer_id = ?", - ISSUER)) + assertThatThrownBy(() -> + fixture + .testSchema() + .dsl() + .execute( + "DELETE FROM game_session_canonical_issuer_bootstrap_member_op_counter" + + " WHERE issuer_id = ?", + ISSUER)) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - fixture - .testSchema() - .dsl() - .execute( - "TRUNCATE game_session_canonical_issuer_bootstrap_member_op_counter")) + assertThatThrownBy(() -> + fixture + .testSchema() + .dsl() + .execute("TRUNCATE game_session_canonical_issuer_bootstrap_member_op_counter")) .isInstanceOf(DataAccessException.class); assertThat( rowImages( @@ -396,23 +388,21 @@ void wrongRequestCheckpointAndChangedFrozenSourceRefuseWithoutAllocatingCounters migrateRemaining(fixture.testSchema()); var owner = new CanonicalGameplayIssuerBootstrapMemberOperationRepository(fixture.testSchema().dsl()); - assertThatThrownBy( - () -> - owner.preparePartitionWork( - fixture.intent().operationId(), - UUID.randomUUID(), - fixture.partitionId(), - fixture.currentAccountCheckpoint(), - stableIncarnation("stable-a"))) + assertThatThrownBy(() -> + owner.preparePartitionWork( + fixture.intent().operationId(), + UUID.randomUUID(), + fixture.partitionId(), + fixture.currentAccountCheckpoint(), + stableIncarnation("stable-a"))) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - owner.preparePartitionWork( - fixture.intent().operationId(), - fixture.requestId(), - fixture.partitionId(), - sourceCheckpoint(BigInteger.valueOf(8)), - stableIncarnation("stable-a"))) + assertThatThrownBy(() -> + owner.preparePartitionWork( + fixture.intent().operationId(), + fixture.requestId(), + fixture.partitionId(), + sourceCheckpoint(BigInteger.valueOf(8)), + stableIncarnation("stable-a"))) .isInstanceOf(IllegalStateException.class); assertThat( fixture @@ -430,14 +420,13 @@ void wrongRequestCheckpointAndChangedFrozenSourceRefuseWithoutAllocatingCounters "UPDATE game_session_canonical_issuer_partition_reservation" + " SET coverage_fence = coverage_fence + 1 WHERE reservation_id = ?", fixture.preparedBinding().issuerReservationId()); - assertThatThrownBy( - () -> - owner.preparePartitionWork( - fixture.intent().operationId(), - fixture.requestId(), - fixture.partitionId(), - fixture.currentAccountCheckpoint(), - stableIncarnation("stable-a"))) + assertThatThrownBy(() -> + owner.preparePartitionWork( + fixture.intent().operationId(), + fixture.requestId(), + fixture.partitionId(), + fixture.currentAccountCheckpoint(), + stableIncarnation("stable-a"))) .isInstanceOf(IllegalStateException.class); assertThat( rowImages( @@ -464,16 +453,15 @@ void missingPlanMissingControlAndBlockedLayoutRefuseWithoutMemberOperation() { "gs_bootstrap_member_no_plan_", PARTITION_CAPACITY, LAYOUT_VERSION, false, false); try { migrateRemaining(missingPlan.testSchema()); - assertThatThrownBy( - () -> - new CanonicalGameplayIssuerBootstrapMemberOperationRepository( - missingPlan.testSchema().dsl()) - .preparePartitionWork( - missingPlan.intent().operationId(), - missingPlan.requestId(), - missingPlan.partitionId(), - missingPlan.currentAccountCheckpoint(), - stableIncarnation("stable-a"))) + assertThatThrownBy(() -> + new CanonicalGameplayIssuerBootstrapMemberOperationRepository( + missingPlan.testSchema().dsl()) + .preparePartitionWork( + missingPlan.intent().operationId(), + missingPlan.requestId(), + missingPlan.partitionId(), + missingPlan.currentAccountCheckpoint(), + stableIncarnation("stable-a"))) .isInstanceOf(IllegalStateException.class); assertNoIssuedRows(missingPlan.testSchema().dsl()); } finally { @@ -497,16 +485,15 @@ void missingPlanMissingControlAndBlockedLayoutRefuseWithoutMemberOperation() { .execute( "DELETE FROM game_session_canonical_issuer_layout_bootstrap_control WHERE issuer_id = ?", ISSUER); - assertThatThrownBy( - () -> - new CanonicalGameplayIssuerBootstrapMemberOperationRepository( - missingControl.testSchema().dsl()) - .preparePartitionWork( - missingControl.intent().operationId(), - missingControl.requestId(), - missingControl.partitionId(), - missingControl.currentAccountCheckpoint(), - stableIncarnation("stable-a"))) + assertThatThrownBy(() -> + new CanonicalGameplayIssuerBootstrapMemberOperationRepository( + missingControl.testSchema().dsl()) + .preparePartitionWork( + missingControl.intent().operationId(), + missingControl.requestId(), + missingControl.partitionId(), + missingControl.currentAccountCheckpoint(), + stableIncarnation("stable-a"))) .isInstanceOf(IllegalStateException.class); assertNoIssuedRows(missingControl.testSchema().dsl()); } finally { @@ -524,16 +511,15 @@ void missingPlanMissingControlAndBlockedLayoutRefuseWithoutMemberOperation() { assertThat(blockedLayout.plan().state()) .isEqualTo(CanonicalGameplayIssuerPartitionBuildPlan.State.BLOCKED); migrateRemaining(blockedLayout.testSchema()); - assertThatThrownBy( - () -> - new CanonicalGameplayIssuerBootstrapMemberOperationRepository( - blockedLayout.testSchema().dsl()) - .preparePartitionWork( - blockedLayout.intent().operationId(), - blockedLayout.requestId(), - blockedLayout.partitionId(), - blockedLayout.currentAccountCheckpoint(), - stableIncarnation("stable-a"))) + assertThatThrownBy(() -> + new CanonicalGameplayIssuerBootstrapMemberOperationRepository( + blockedLayout.testSchema().dsl()) + .preparePartitionWork( + blockedLayout.intent().operationId(), + blockedLayout.requestId(), + blockedLayout.partitionId(), + blockedLayout.currentAccountCheckpoint(), + stableIncarnation("stable-a"))) .isInstanceOf(IllegalStateException.class); assertNoIssuedRows(blockedLayout.testSchema().dsl()); } finally { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java index 6d10a68caa..7f90d3a2da 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapPartitionRedisOwnerIntegrationTest.java @@ -123,19 +123,17 @@ void buildsCompletePopulatedPartitionAndCountsReleasedOnlyAsRetainedEvidence() { assertThat(work.memberOperations()) .filteredOn(CanonicalGameplayIssuerBootstrapMemberOperation::expectedBindingPresent) .singleElement() - .satisfies( - operation -> - assertThat(operation.bindingLifecycle()) - .isEqualTo( - net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE)); + .satisfies(operation -> + assertThat(operation.bindingLifecycle()) + .isEqualTo( + net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.Lifecycle.ACTIVE)); assertThat(work.memberOperations()) .filteredOn(operation -> !operation.countsTowardCapacity()) .singleElement() - .satisfies( - operation -> - assertThat(operation.expectedMemberValue().reservation().lifecycle()) - .isEqualTo(CanonicalIssuerPartitionReservation.Lifecycle.RELEASED)); + .satisfies(operation -> + assertThat(operation.expectedMemberValue().reservation().lifecycle()) + .isEqualTo(CanonicalIssuerPartitionReservation.Lifecycle.RELEASED)); var active = work.memberOperations().stream() @@ -214,11 +212,10 @@ void candidatePreparedSourceRowRetainsCapacityWithoutCreatingPhysicalBinding() { partitionWork(fixture, fixture.partitionId()); var candidateOperation = work.memberOperations().stream() - .filter( - operation -> - operation.bindingLifecycle() - == net.firedevops.firemud.gamesession.binding - .CanonicalGameplayBindingInventoryEntry.Lifecycle.CANDIDATE_PREPARED) + .filter(operation -> + operation.bindingLifecycle() + == net.firedevops.firemud.gamesession.binding + .CanonicalGameplayBindingInventoryEntry.Lifecycle.CANDIDATE_PREPARED) .findFirst() .orElseThrow(); @@ -345,9 +342,8 @@ void malformedLegacyForeignAndExpiringPhysicalStateRefuseWithoutMutation() { administratorCommands.pexpire(expiringKey, 60_000); long ttlBefore = administratorCommands.pttl(expiringKey); - assertThatThrownBy( - () -> - owner(expiringWork, currentState(fixture, expiringWork)).buildAndRead(expiringWork)) + assertThatThrownBy(() -> + owner(expiringWork, currentState(fixture, expiringWork)).buildAndRead(expiringWork)) .isInstanceOf(IllegalStateException.class); assertThat(administratorCommands.pttl(expiringKey)).isPositive().isLessThanOrEqualTo(ttlBefore); assertThat(administratorCommands.hget(expiringKey, expiringField)) @@ -359,10 +355,8 @@ void malformedLegacyForeignAndExpiringPhysicalStateRefuseWithoutMutation() { byte[] wrongTypeKey = key(fixture, wrongTypePartition); byte[] wrongTypeValue = ascii("foreign-persistent-string"); administratorCommands.set(wrongTypeKey, wrongTypeValue); - assertThatThrownBy( - () -> - owner(wrongTypeWork, currentState(fixture, wrongTypeWork)) - .buildAndRead(wrongTypeWork)) + assertThatThrownBy(() -> + owner(wrongTypeWork, currentState(fixture, wrongTypeWork)).buildAndRead(wrongTypeWork)) .isInstanceOf(IllegalStateException.class); assertThat(administratorCommands.type(wrongTypeKey)).isEqualTo("string"); assertThat(administratorCommands.get(wrongTypeKey)).containsExactly(wrongTypeValue); @@ -908,11 +902,9 @@ private static byte[] resource(String name) throws Exception { private Map hashImage(byte[] key) { Map raw = administratorCommands.hgetall(key); Map image = new LinkedHashMap<>(); - raw.forEach( - (field, value) -> - image.put( - Base64.getEncoder().encodeToString(field), - Base64.getEncoder().encodeToString(value))); + raw.forEach((field, value) -> + image.put( + Base64.getEncoder().encodeToString(field), Base64.getEncoder().encodeToString(value))); return image; } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerIdentityMigrationPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerIdentityMigrationPostgresIntegrationTest.java index e4e505081c..021a60a9a4 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerIdentityMigrationPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerIdentityMigrationPostgresIntegrationTest.java @@ -212,19 +212,18 @@ void convertsIssuerStorageWithoutRelabelingLegacyRowsOrChangingEvidence() throws assertRecreatedIdentityChecksRemainValidated(dsl); assertLegacyIssuerValues(dsl); assertThatThrownBy(() -> new CanonicalGameplayBindingInventoryRepository(dsl).readSnapshot()) - .satisfies( - failure -> { - Throwable rootCause = failure; - while (rootCause.getCause() != null) { - rootCause = rootCause.getCause(); - } - assertThat(rootCause) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage( - "Unsupported issuer identity; expected exact Account issuer " - + "firemud-account-service; legacy UUID issuer identities require " - + "explicit recovery"); - }); + .satisfies(failure -> { + Throwable rootCause = failure; + while (rootCause.getCause() != null) { + rootCause = rootCause.getCause(); + } + assertThat(rootCause) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "Unsupported issuer identity; expected exact Account issuer " + + "firemud-account-service; legacy UUID issuer identities require " + + "explicit recovery"); + }); assertThat(rowSnapshots(dsl)).isEqualTo(beforeMigration); assertThat(historySnapshot(dsl).subList(0, historyBeforeMigration.size())) .containsExactlyElementsOf(historyBeforeMigration); @@ -644,16 +643,15 @@ private static void assertNonCanonicalIssuerWritesAreRejected(DSLContext dsl) { private static void assertRejectedIssuerWrite( DSLContext dsl, IssuerField field, String attemptedIssuer) { - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE " - + field.table() - + " SET " - + field.column() - + " = ? WHERE " - + field.where(), - parameters(attemptedIssuer, field.keys()))) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE " + + field.table() + + " SET " + + field.column() + + " = ? WHERE " + + field.where(), + parameters(attemptedIssuer, field.keys()))) .isInstanceOfSatisfying( DataAccessException.class, exception -> assertThat(exception.sqlState()).isEqualTo("23514")); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java index 7feab6e063..8cf9bf2e53 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java @@ -146,9 +146,8 @@ void pendingIntentFreezesActualInventoryAndExactInputsAcrossRetryAndRestart() { CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.ISSUER_OBLIGATION, CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.REGION_OBLIGATION); assertThat(intent.cohortRows()) - .filteredOn( - row -> - row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION) + .filteredOn(row -> + row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION) .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey) .contains(reservationOnlyId.toString()); @@ -288,10 +287,8 @@ void shapeOnlyMemberRoundTripPreservesPopulatedReservationTupleBesideBootstrapAn var reservationCohortRow = intent.cohortRows().stream() - .filter( - row -> - row.kind() - == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION) + .filter(row -> + row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION) .findFirst() .orElseThrow(); assertThat(reservationCohortRow.sourceKey()) @@ -300,9 +297,8 @@ void shapeOnlyMemberRoundTripPreservesPopulatedReservationTupleBesideBootstrapAn assertThat(frozenReadback.state()) .isEqualTo(CanonicalGameplayIssuerLayoutBootstrapIntent.State.INITIAL_BOOTSTRAP_INTENT); assertThat(frozenReadback.cohortRows()) - .filteredOn( - row -> - row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION) + .filteredOn(row -> + row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION) .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceRowDigest) .containsExactly(reservationCohortRow.sourceRowDigest()); assertThat(rowImages(testSchema.dsl(), "game_session_canonical_issuer_partition_reservation")) @@ -527,20 +523,18 @@ void preparationQueuedBeforeBootstrapIntentIsCapturedByTheIntent() throws Except + " WHERE singleton_id = 1 FOR UPDATE"); Future preparedFuture = - executor.submit( - () -> { - prepareStarted.countDown(); - return prepareActualBinding(inventory); - }); + executor.submit(() -> { + prepareStarted.countDown(); + return prepareActualBinding(inventory); + }); assertThat(prepareStarted.await(10, TimeUnit.SECONDS)).isTrue(); awaitInventoryClockWaiters(testSchema, 1); Future intentFuture = - executor.submit( - () -> { - intentStarted.countDown(); - return owner.beginInitialBootstrapIntent(requestId, descriptor, source); - }); + executor.submit(() -> { + intentStarted.countDown(); + return owner.beginInitialBootstrapIntent(requestId, descriptor, source); + }); assertThat(intentStarted.await(10, TimeUnit.SECONDS)).isTrue(); awaitInventoryClockWaiters(testSchema, 2); @@ -597,25 +591,23 @@ void bootstrapIntentQueuedBeforePreparationLeavesNoAllocatedRows() throws Except + " WHERE singleton_id = 1 FOR UPDATE"); Future intentFuture = - executor.submit( - () -> { - intentStarted.countDown(); - return owner.beginInitialBootstrapIntent(requestId, descriptor, source); - }); + executor.submit(() -> { + intentStarted.countDown(); + return owner.beginInitialBootstrapIntent(requestId, descriptor, source); + }); assertThat(intentStarted.await(10, TimeUnit.SECONDS)).isTrue(); awaitInventoryClockWaiters(testSchema, 1); Future prepareFuture = - executor.submit( - () -> { - prepareStarted.countDown(); - try { - return new PreparationAttempt( - prepareActualBinding(inventory, BLOCKED_CHARACTER_ID), null); - } catch (RuntimeException failure) { - return new PreparationAttempt(null, failure); - } - }); + executor.submit(() -> { + prepareStarted.countDown(); + try { + return new PreparationAttempt( + prepareActualBinding(inventory, BLOCKED_CHARACTER_ID), null); + } catch (RuntimeException failure) { + return new PreparationAttempt(null, failure); + } + }); assertThat(prepareStarted.await(10, TimeUnit.SECONDS)).isTrue(); awaitInventoryClockWaiters(testSchema, 2); @@ -797,10 +789,9 @@ void staleUninstalledIntentRequiresExplicitFreshLayoutAndPreservesOriginalHistor var newerLayout = descriptor(LAYOUT_VERSION.add(BigInteger.ONE), PARTITION_COUNT, PARTITION_CAPACITY); UUID replacementRequest = UUID.randomUUID(); - assertThatThrownBy( - () -> - owner.supersedeStaleInitialBootstrapIntent( - original.operationId(), replacementRequest, newerLayout, source)) + assertThatThrownBy(() -> + owner.supersedeStaleInitialBootstrapIntent( + original.operationId(), replacementRequest, newerLayout, source)) .hasMessageContaining("strictly newer inventory"); assertThat(rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_control")) .isEqualTo(originalControl); @@ -815,20 +806,17 @@ void staleUninstalledIntentRequiresExplicitFreshLayoutAndPreservesOriginalHistor assertThatThrownBy( () -> plans.prepareInitialBuildPlan(original.operationId(), original.requestId())) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - owner.supersedeStaleInitialBootstrapIntent( - original.operationId(), replacementRequest, layout, source)) + assertThatThrownBy(() -> + owner.supersedeStaleInitialBootstrapIntent( + original.operationId(), replacementRequest, layout, source)) .hasMessageContaining("strictly newer layout version"); - assertThatThrownBy( - () -> - owner.supersedeStaleInitialBootstrapIntent( - original.operationId(), original.requestId(), newerLayout, source)) + assertThatThrownBy(() -> + owner.supersedeStaleInitialBootstrapIntent( + original.operationId(), original.requestId(), newerLayout, source)) .hasMessageContaining("fresh distinct request"); - assertThatThrownBy( - () -> - owner.supersedeStaleInitialBootstrapIntent( - UUID.randomUUID(), replacementRequest, newerLayout, source)) + assertThatThrownBy(() -> + owner.supersedeStaleInitialBootstrapIntent( + UUID.randomUUID(), replacementRequest, newerLayout, source)) .hasMessageContaining("no longer current"); assertThat(rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_control")) .isEqualTo(originalControl); @@ -898,17 +886,16 @@ void staleUninstalledIntentRequiresExplicitFreshLayoutAndPreservesOriginalHistor plans.prepareInitialBuildPlan(replacement.operationId(), replacementRequest); List replacementControl = rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_control"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_session_canonical_issuer_layout_bootstrap_control" - + " SET current_operation_id = ?, control_epoch = ?, current_operation_fence = ?," - + " current_coverage_fence = ? WHERE issuer_id = ?", - original.operationId(), - new BigDecimal(original.controlEpoch()), - new BigDecimal(original.operationFence()), - new BigDecimal(original.coverageFence()), - ISSUER)) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_session_canonical_issuer_layout_bootstrap_control" + + " SET current_operation_id = ?, control_epoch = ?, current_operation_fence = ?," + + " current_coverage_fence = ? WHERE issuer_id = ?", + original.operationId(), + new BigDecimal(original.controlEpoch()), + new BigDecimal(original.operationFence()), + new BigDecimal(original.coverageFence()), + ISSUER)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("requires exact retained supersession lineage"); assertThat(rowImages(dsl, "game_session_canonical_issuer_layout_bootstrap_control")) @@ -938,33 +925,29 @@ void staleUninstalledIntentRequiresExplicitFreshLayoutAndPreservesOriginalHistor .isEqualTo(replacementControl); assertThat(rowImages(dsl, "game_session_canonical_issuer_bootstrap_supersession")) .isEqualTo(retainedRelation); - assertThatThrownBy( - () -> - restartedAfterProgress.supersedeStaleInitialBootstrapIntent( - original.operationId(), UUID.randomUUID(), newerLayout, source)) + assertThatThrownBy(() -> + restartedAfterProgress.supersedeStaleInitialBootstrapIntent( + original.operationId(), UUID.randomUUID(), newerLayout, source)) .hasMessageContaining("no longer current"); - assertThatThrownBy( - () -> - restartedAfterProgress.supersedeStaleInitialBootstrapIntent( - original.operationId(), - replacementRequest, - descriptor( - LAYOUT_VERSION.add(BigInteger.TWO), PARTITION_COUNT, PARTITION_CAPACITY), - source)) + assertThatThrownBy(() -> + restartedAfterProgress.supersedeStaleInitialBootstrapIntent( + original.operationId(), + replacementRequest, + descriptor( + LAYOUT_VERSION.add(BigInteger.TWO), PARTITION_COUNT, PARTITION_CAPACITY), + source)) .hasMessageContaining("changed its original trusted inputs"); - assertThatThrownBy( - () -> - restartedAfterProgress.supersedeStaleInitialBootstrapIntent( - original.operationId(), - replacementRequest, - newerLayout, - sourceCheckpoint(BigInteger.valueOf(8)))) + assertThatThrownBy(() -> + restartedAfterProgress.supersedeStaleInitialBootstrapIntent( + original.operationId(), + replacementRequest, + newerLayout, + sourceCheckpoint(BigInteger.valueOf(8)))) .hasMessageContaining("changed its original trusted inputs"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_session_canonical_issuer_bootstrap_supersession" - + " SET new_inventory_revision = new_inventory_revision")) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_session_canonical_issuer_bootstrap_supersession" + + " SET new_inventory_revision = new_inventory_revision")) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThatThrownBy( () -> dsl.execute("DELETE FROM game_session_canonical_issuer_bootstrap_supersession")) @@ -1124,27 +1107,23 @@ void retainedPhysicalWorkDoesNotStrandSupersedingLayoutOrOrdinaryNew() { original.operationId()) .get(0, Long.class)) .isEqualTo(1L); - assertThatThrownBy( - () -> - bootstrap.supersedeStaleInitialBootstrapIntent( - replacement.operationId(), - UUID.randomUUID(), + assertThatThrownBy(() -> + bootstrap.supersedeStaleInitialBootstrapIntent( + replacement.operationId(), + UUID.randomUUID(), + descriptor( + LAYOUT_VERSION.add(BigInteger.TWO), PARTITION_COUNT, PARTITION_CAPACITY), + source)) + .hasMessageContaining("installed issuer anchor forbids"); + assertThatThrownBy(() -> + new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl) + .supersedeStaleInitialBootstrapIntent( + original.operationId(), + replacement.requestId(), descriptor( - LAYOUT_VERSION.add(BigInteger.TWO), PARTITION_COUNT, PARTITION_CAPACITY), + LAYOUT_VERSION.add(BigInteger.ONE), PARTITION_COUNT, PARTITION_CAPACITY), source)) .hasMessageContaining("installed issuer anchor forbids"); - assertThatThrownBy( - () -> - new CanonicalGameplayIssuerLayoutBootstrapRepository(dsl) - .supersedeStaleInitialBootstrapIntent( - original.operationId(), - replacement.requestId(), - descriptor( - LAYOUT_VERSION.add(BigInteger.ONE), - PARTITION_COUNT, - PARTITION_CAPACITY), - source)) - .hasMessageContaining("installed issuer anchor forbids"); assertMalformedSupersessionRefusesOrdinaryNew(dsl, local, request, state); } finally { ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); @@ -1170,30 +1149,26 @@ private static void assertMalformedSupersessionRefusesOrdinaryNew( + " FROM game_session_canonical_issuer_layout_bootstrap_intent original" + " ORDER BY operation_fence DESC LIMIT 1", "UPDATE game_session_canonical_issuer_bootstrap_supersession SET old_operation_fence = old_operation_fence + 1")) { - assertThatThrownBy( - () -> - dsl.transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute( - "ALTER TABLE game_session_canonical_issuer_bootstrap_supersession DISABLE TRIGGER USER"); - if (corruption.startsWith("UPDATE")) { - transaction.execute( - "ALTER TABLE game_session_canonical_issuer_bootstrap_supersession" - + " DROP CONSTRAINT chk_gs_issuer_bootstrap_supersession"); - transaction.execute( - "ALTER TABLE game_session_canonical_issuer_bootstrap_supersession" - + " DROP CONSTRAINT fk_gs_issuer_bootstrap_supersession_old"); - } - transaction.execute(corruption); - // Invoke the exact anchor gate in this same transaction, without opening - // another connection. - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision( - transaction); - CanonicalGameplayIssuerBootstrapCoverageRepository - .readInstalledAnchorForBindingPreparationInTransaction( - transaction, state); - })) + assertThatThrownBy(() -> + dsl.transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute( + "ALTER TABLE game_session_canonical_issuer_bootstrap_supersession DISABLE TRIGGER USER"); + if (corruption.startsWith("UPDATE")) { + transaction.execute( + "ALTER TABLE game_session_canonical_issuer_bootstrap_supersession" + + " DROP CONSTRAINT chk_gs_issuer_bootstrap_supersession"); + transaction.execute( + "ALTER TABLE game_session_canonical_issuer_bootstrap_supersession" + + " DROP CONSTRAINT fk_gs_issuer_bootstrap_supersession_old"); + } + transaction.execute(corruption); + // Invoke the exact anchor gate in this same transaction, without opening + // another connection. + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, state); + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining( corruption.startsWith("UPDATE") @@ -1240,50 +1215,48 @@ private static void assertRelationOnlySupersessionCannotCommit( UUID replacementId = UUID.randomUUID(); BigInteger operationFence = original.coverageFence().add(BigInteger.ONE); BigInteger coverageFence = operationFence.add(BigInteger.ONE); - assertThatThrownBy( - () -> - dsl.transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute( - "INSERT INTO game_session_canonical_issuer_layout_bootstrap_intent" - + " SELECT (jsonb_populate_record(" - + " NULL::game_session_canonical_issuer_layout_bootstrap_intent," - + " to_jsonb(original) || jsonb_build_object(" - + " 'operation_id', ?::uuid, 'request_id', ?::uuid," - + " 'control_epoch', ?::numeric, 'operation_fence', ?::numeric," - + " 'coverage_fence', ?::numeric, 'inventory_snapshot_revision', ?::numeric," - + " 'layout_version', ?::numeric, 'layout_descriptor_bytes', ?::bytea," - + " 'layout_descriptor_digest', ?::text))).*" - + " FROM game_session_canonical_issuer_layout_bootstrap_intent original" - + " WHERE original.operation_id = ?", - replacementId, - UUID.randomUUID(), - new BigDecimal(operationFence), - new BigDecimal(operationFence), - new BigDecimal(coverageFence), - new BigDecimal(currentRevision), - new BigDecimal(layout.layoutVersion()), - layout.exactBytes(), - CanonicalGameplayIssuerMemberV2Codec.sha256(layout.exactBytes()), - original.operationId()); - transaction.execute( - "INSERT INTO game_session_canonical_issuer_bootstrap_supersession" - + " (issuer_id, old_operation_id, new_operation_id, old_inventory_revision," - + " new_inventory_revision, old_operation_fence, old_coverage_fence," - + " previous_last_issued_fence, new_operation_fence, new_coverage_fence)" - + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - ISSUER, - original.operationId(), - replacementId, - new BigDecimal(original.inventorySnapshotRevision()), - new BigDecimal(currentRevision), - new BigDecimal(original.operationFence()), - new BigDecimal(original.coverageFence()), - new BigDecimal(original.coverageFence()), - new BigDecimal(operationFence), - new BigDecimal(coverageFence)); - })) + assertThatThrownBy(() -> + dsl.transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute( + "INSERT INTO game_session_canonical_issuer_layout_bootstrap_intent" + + " SELECT (jsonb_populate_record(" + + " NULL::game_session_canonical_issuer_layout_bootstrap_intent," + + " to_jsonb(original) || jsonb_build_object(" + + " 'operation_id', ?::uuid, 'request_id', ?::uuid," + + " 'control_epoch', ?::numeric, 'operation_fence', ?::numeric," + + " 'coverage_fence', ?::numeric, 'inventory_snapshot_revision', ?::numeric," + + " 'layout_version', ?::numeric, 'layout_descriptor_bytes', ?::bytea," + + " 'layout_descriptor_digest', ?::text))).*" + + " FROM game_session_canonical_issuer_layout_bootstrap_intent original" + + " WHERE original.operation_id = ?", + replacementId, + UUID.randomUUID(), + new BigDecimal(operationFence), + new BigDecimal(operationFence), + new BigDecimal(coverageFence), + new BigDecimal(currentRevision), + new BigDecimal(layout.layoutVersion()), + layout.exactBytes(), + CanonicalGameplayIssuerMemberV2Codec.sha256(layout.exactBytes()), + original.operationId()); + transaction.execute( + "INSERT INTO game_session_canonical_issuer_bootstrap_supersession" + + " (issuer_id, old_operation_id, new_operation_id, old_inventory_revision," + + " new_inventory_revision, old_operation_fence, old_coverage_fence," + + " previous_last_issued_fence, new_operation_fence, new_coverage_fence)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + ISSUER, + original.operationId(), + replacementId, + new BigDecimal(original.inventorySnapshotRevision()), + new BigDecimal(currentRevision), + new BigDecimal(original.operationFence()), + new BigDecimal(original.coverageFence()), + new BigDecimal(original.coverageFence()), + new BigDecimal(operationFence), + new BigDecimal(coverageFence)); + })) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining("must move exact current control in the same transaction"); } @@ -1560,9 +1533,8 @@ private static void assertCapturedPreparationCohort( assertThat(intent.inventorySnapshotRevision()).isEqualTo(prepared.inventoryRevision()); assertThat(intent.cohortRows()).hasSize(6); assertThat(intent.cohortRows()) - .allSatisfy( - row -> - assertThat(row.sourceInventoryRevision()).isEqualTo(prepared.inventoryRevision())); + .allSatisfy(row -> + assertThat(row.sourceInventoryRevision()).isEqualTo(prepared.inventoryRevision())); assertThat(intent.cohortRows()) .filteredOn( row -> row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.BINDING) @@ -1574,30 +1546,24 @@ private static void assertCapturedPreparationCohort( .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey) .containsExactly(transitionId); assertThat(intent.cohortRows()) - .filteredOn( - row -> - row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION) + .filteredOn(row -> + row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION) .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey) .containsExactly(prepared.issuerReservationId().toString()); assertThat(intent.cohortRows()) - .filteredOn( - row -> - row.kind() - == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.ACCOUNT_OBLIGATION) + .filteredOn(row -> + row.kind() + == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.ACCOUNT_OBLIGATION) .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey) .containsExactly(transitionId + ":0"); assertThat(intent.cohortRows()) - .filteredOn( - row -> - row.kind() - == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.ISSUER_OBLIGATION) + .filteredOn(row -> + row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.ISSUER_OBLIGATION) .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey) .containsExactly(bindingRefHex + ":" + transitionId); assertThat(intent.cohortRows()) - .filteredOn( - row -> - row.kind() - == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.REGION_OBLIGATION) + .filteredOn(row -> + row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.REGION_OBLIGATION) .extracting(CanonicalGameplayIssuerLayoutBootstrapIntent.CohortRow::sourceKey) .containsExactly(transitionId); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java index c7b890448c..87619a7e73 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLifecycleProofFixtures.java @@ -526,11 +526,9 @@ protected static Map decodeFields(byte[] fieldSet) { protected static long capacityFieldCount(byte[] fieldSet) { return decodeFields(fieldSet).keySet().stream() - .filter( - field -> - field.startsWith( - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec - .RESERVATION_FIELD_PREFIX)) + .filter(field -> + field.startsWith( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.RESERVATION_FIELD_PREFIX)) .count(); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java index a94f2133dd..cafeb369d8 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java @@ -171,10 +171,9 @@ void unrelatedAccountNewAndOriginalIssuerCleanupSurviveAccountControlAdvance() { changedReservation, abort.originalDecision(), abort.orphanCleanupId()))) { - assertThatThrownBy( - () -> - inventoryRepository.recordFirstNewAccountAbort( - changedSource, changedSource.orphanCleanupId())) + assertThatThrownBy(() -> + inventoryRepository.recordFirstNewAccountAbort( + changedSource, changedSource.orphanCleanupId())) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("Retained first-NEW abort source changed during exact retry"); assertAbortRetryUnchanged.run(); @@ -264,11 +263,10 @@ void addCurrentnessRereadKeepsTheTargetAccountControlFenceWithoutPreparingAnothe .beginFenceIntent( originalMember.owner().accountId(), uuid("add-currentness-account-fence")); - assertThatThrownBy( - () -> - new CanonicalGameplayIssuerBindingLocalProjectionRepository( - fixture.dsl(), issuerStateSource) - .requireStillCurrent(preparedAdd)) + assertThatThrownBy(() -> + new CanonicalGameplayIssuerBindingLocalProjectionRepository( + fixture.dsl(), issuerStateSource) + .requireStillCurrent(preparedAdd)) .isInstanceOf(IllegalStateException.class); assertThat(physicalFieldSet(partitionKey)).isEqualTo(fieldsBeforeReread); assertThat(partitionMutationCount(fixture.dsl())).isEqualTo(mutationsBeforeReread); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java index fecf487e28..4f3a032457 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPartitionBuildRepositoryIntegrationTest.java @@ -189,23 +189,22 @@ void v1038PhysicalIssuerHistoryRejectsTruncateCascade() { fixture.intent().operationId(), initialRevision, initialRevision); - assertThatThrownBy( - () -> - testSchema - .dsl() - .execute( - "INSERT INTO game_session_canonical_issuer_partition_mutation" - + " (mutation_id, issuer_id, partition_id, mutation_kind, owner_operation_id," - + " expected_revision, successor_revision, exact_intended_change_bytes," - + " exact_intended_change_digest, status)" - + " VALUES (?, ?, 0, 'ADD_CAPACITY', ?, ?, ?, ?, ?, 'PENDING_PHYSICAL_PROOF')", - UUID.randomUUID(), - ISSUER, - UUID.randomUUID(), - initialRevision, - UUID.randomUUID(), - new byte[] {1}, - "sha256:" + "a".repeat(64))) + assertThatThrownBy(() -> + testSchema + .dsl() + .execute( + "INSERT INTO game_session_canonical_issuer_partition_mutation" + + " (mutation_id, issuer_id, partition_id, mutation_kind, owner_operation_id," + + " expected_revision, successor_revision, exact_intended_change_bytes," + + " exact_intended_change_digest, status)" + + " VALUES (?, ?, 0, 'ADD_CAPACITY', ?, ?, ?, ?, ?, 'PENDING_PHYSICAL_PROOF')", + UUID.randomUUID(), + ISSUER, + UUID.randomUUID(), + initialRevision, + UUID.randomUUID(), + new byte[] {1}, + "sha256:" + "a".repeat(64))) .isInstanceOfSatisfying( DataAccessException.class, exception -> assertThat(exception.sqlState()).isEqualTo("23514")); @@ -221,15 +220,14 @@ void v1038PhysicalIssuerHistoryRejectsTruncateCascade() { assertThat(mutationsBefore).isEmpty(); assertThat(retirementsBefore).isEmpty(); - assertThatThrownBy( - () -> - testSchema - .dsl() - .execute( - "TRUNCATE TABLE" - + " game_session_canonical_issuer_partition_mutation_head," - + " game_session_canonical_issuer_partition_mutation," - + " game_session_canonical_issuer_binding_local_retirement CASCADE")) + assertThatThrownBy(() -> + testSchema + .dsl() + .execute( + "TRUNCATE TABLE" + + " game_session_canonical_issuer_partition_mutation_head," + + " game_session_canonical_issuer_partition_mutation," + + " game_session_canonical_issuer_binding_local_retirement CASCADE")) .isInstanceOfSatisfying( DataAccessException.class, exception -> assertThat(exception.sqlState()).isEqualTo("23514")); @@ -298,19 +296,18 @@ void v1038RetainsLegacyBootstrapProofWithoutQualifyingCurrentRevision() { .containsExactlyElementsOf(legacyProofBefore); UUID historicalInitialRevision = UUID.randomUUID(); - assertThatThrownBy( - () -> - historicalSchema - .dsl() - .execute( - "INSERT INTO game_session_canonical_issuer_partition_mutation_head" - + " (issuer_id, partition_id, bootstrap_operation_id, initial_revision," - + " current_revision, state)" - + " VALUES (?, 0, ?, ?, ?, 'INITIAL_INSTALL_PENDING')", - ISSUER, - historicalFixture.intent().operationId(), - historicalInitialRevision, - historicalInitialRevision)) + assertThatThrownBy(() -> + historicalSchema + .dsl() + .execute( + "INSERT INTO game_session_canonical_issuer_partition_mutation_head" + + " (issuer_id, partition_id, bootstrap_operation_id, initial_revision," + + " current_revision, state)" + + " VALUES (?, 0, ?, ?, ?, 'INITIAL_INSTALL_PENDING')", + ISSUER, + historicalFixture.intent().operationId(), + historicalInitialRevision, + historicalInitialRevision)) .isInstanceOfSatisfying( DataAccessException.class, exception -> assertThat(exception.sqlState()).isEqualTo("P0001")); @@ -338,17 +335,15 @@ void v1038RetainsLegacyBootstrapProofWithoutQualifyingCurrentRevision() { newProofFixture.intent().operationId(), newInitialRevision, newInitialRevision); - assertThatThrownBy( - () -> - insertControlledBootstrapProof( - newProofSchema.dsl(), newProofFixture, newProofPlan, null)) + assertThatThrownBy(() -> + insertControlledBootstrapProof( + newProofSchema.dsl(), newProofFixture, newProofPlan, null)) .isInstanceOfSatisfying( DataAccessException.class, exception -> assertThat(exception.sqlState()).isEqualTo("23514")); - assertThatThrownBy( - () -> - insertControlledBootstrapProof( - newProofSchema.dsl(), newProofFixture, newProofPlan, UUID.randomUUID())) + assertThatThrownBy(() -> + insertControlledBootstrapProof( + newProofSchema.dsl(), newProofFixture, newProofPlan, UUID.randomUUID())) .isInstanceOfSatisfying( DataAccessException.class, exception -> { @@ -784,26 +779,24 @@ public void executeStart(ExecuteContext context) { })); DSLContext measuredReader = DSL.using(measuredConfiguration); var readPlan = - measuredReader.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - return new CanonicalGameplayIssuerPartitionBuildRepository(transaction) - .readPreparedPlanInTransaction( - transaction, fixture.intent().operationId(), fixture.requestId()); - }); + measuredReader.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + return new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readPreparedPlanInTransaction( + transaction, fixture.intent().operationId(), fixture.requestId()); + }); // Count all actual SQL executions, not query strings: even the complete owner read // must use fewer round trips than this cohort has rows. assertThat(plan.cohortRows().size()).isGreaterThan(24); assertThat(readQueries.get()).isPositive().isLessThan(plan.cohortRows().size()); readQueries.set(0); var member = - measuredReader.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - return new CanonicalGameplayIssuerPartitionBuildRepository(transaction) - .readPreparedMemberWorkInTransaction( - transaction, fixture.intent().operationId(), fixture.requestId(), 0); - }); + measuredReader.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + return new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readPreparedMemberWorkInTransaction( + transaction, fixture.intent().operationId(), fixture.requestId(), 0); + }); assertThat(member.work().memberOperationId()) .isEqualTo(plan.memberWorks().get(0).memberOperationId()); assertThat(readQueries.get()).isPositive().isLessThan(plan.cohortRows().size()); @@ -820,46 +813,38 @@ public void executeStart(ExecuteContext context) { .prepareInitialBuildPlan(fixture.intent().operationId(), fixture.requestId()); assertThat(retry.buildOperationId()).isEqualTo(plan.buildOperationId()); assertThat(retry.planDigest()).isEqualTo(plan.planDigest()); - assertThatThrownBy( - () -> - prepareSchema - .dsl() - .transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - assertThat( - transaction.execute( - "UPDATE game_session_canonical_issuer_partition_reservation" - + " SET coverage_fence = coverage_fence + 1" - + " WHERE reservation_id = ?", - fixture.reservationId())) - .isOne(); - new CanonicalGameplayIssuerPartitionBuildRepository(transaction) - .readPreparedPlanInTransaction( - transaction, - fixture.intent().operationId(), - fixture.requestId()); - })) + assertThatThrownBy(() -> + prepareSchema + .dsl() + .transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + assertThat( + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_reservation" + + " SET coverage_fence = coverage_fence + 1" + + " WHERE reservation_id = ?", + fixture.reservationId())) + .isOne(); + new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readPreparedPlanInTransaction( + transaction, fixture.intent().operationId(), fixture.requestId()); + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Current source row differs"); for (String changedKeys : List.of("ADD COLUMN unexpected_attribute text", "DROP COLUMN created_at")) { - assertThatThrownBy( - () -> - prepareSchema - .dsl() - .transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute( - "ALTER TABLE game_session_canonical_issuer_partition_reservation " - + changedKeys); - new CanonicalGameplayIssuerPartitionBuildRepository(transaction) - .readPreparedPlanInTransaction( - transaction, - fixture.intent().operationId(), - fixture.requestId()); - })) + assertThatThrownBy(() -> + prepareSchema + .dsl() + .transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute( + "ALTER TABLE game_session_canonical_issuer_partition_reservation " + + changedKeys); + new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readPreparedPlanInTransaction( + transaction, fixture.intent().operationId(), fixture.requestId()); + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Current source row differs"); } @@ -899,9 +884,8 @@ void exactOwnerRejectsMissingWrongRequestMissingControlAndChangedFrozenSources() () -> owner.prepareInitialBuildPlan(UUID.randomUUID(), fixture.requestId())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Exact pending issuer-bootstrap operation is missing"); - assertThatThrownBy( - () -> - owner.prepareInitialBuildPlan(fixture.intent().operationId(), UUID.randomUUID())) + assertThatThrownBy(() -> + owner.prepareInitialBuildPlan(fixture.intent().operationId(), UUID.randomUUID())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("request or exact current control tuple changed"); @@ -910,10 +894,8 @@ void exactOwnerRejectsMissingWrongRequestMissingControlAndChangedFrozenSources() .execute( "DELETE FROM game_session_canonical_issuer_layout_bootstrap_control WHERE issuer_id = ?", ISSUER); - assertThatThrownBy( - () -> - owner.prepareInitialBuildPlan( - fixture.intent().operationId(), fixture.requestId())) + assertThatThrownBy(() -> + owner.prepareInitialBuildPlan(fixture.intent().operationId(), fixture.requestId())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("lost its positive current control row"); } finally { @@ -949,26 +931,24 @@ void immutableBuildArtifactsRejectTruncateAndRetainTheirCompletePostimage() { assertThat(workBefore).isNotEmpty(); assertThat(blockersBefore).isNotEmpty(); - assertThatThrownBy( - () -> - testSchema - .dsl() - .execute( - "UPDATE game_session_canonical_issuer_partition_build_plan" - + " SET created_at = created_at + INTERVAL '1 second'")) + assertThatThrownBy(() -> + testSchema + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_partition_build_plan" + + " SET created_at = created_at + INTERVAL '1 second'")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("issuer partition build preparation artifacts are immutable"); - assertThatThrownBy( - () -> - testSchema - .dsl() - .execute( - "TRUNCATE TABLE" - + " game_session_canonical_issuer_partition_build_plan," - + " game_session_canonical_issuer_partition_build_cohort_row," - + " game_session_canonical_issuer_partition_build_member_work," - + " game_session_canonical_issuer_partition_build_blocker CASCADE")) + assertThatThrownBy(() -> + testSchema + .dsl() + .execute( + "TRUNCATE TABLE" + + " game_session_canonical_issuer_partition_build_plan," + + " game_session_canonical_issuer_partition_build_cohort_row," + + " game_session_canonical_issuer_partition_build_member_work," + + " game_session_canonical_issuer_partition_build_blocker CASCADE")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("artifacts are immutable"); @@ -1003,10 +983,8 @@ void changedLayoutCohortOrSourceCannotResumeAnOriginalPlan() { "UPDATE game_session_canonical_issuer_layout_bootstrap_intent" + " SET layout_version = layout_version + 1 WHERE operation_id = ?", fixture.intent().operationId()); - assertThatThrownBy( - () -> - owner.prepareInitialBuildPlan( - fixture.intent().operationId(), fixture.requestId())) + assertThatThrownBy(() -> + owner.prepareInitialBuildPlan(fixture.intent().operationId(), fixture.requestId())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("exact pending bootstrap layout or anchor link"); } finally { @@ -1023,10 +1001,9 @@ void changedLayoutCohortOrSourceCannotResumeAnOriginalPlan() { + " SET source_row_digest = ? WHERE operation_id = ? AND row_ordinal = 0", "sha256:" + "0".repeat(64), fixture.intent().operationId()); - assertThatThrownBy( - () -> - new CanonicalGameplayIssuerPartitionBuildRepository(cohortSchema.dsl()) - .prepareInitialBuildPlan(fixture.intent().operationId(), fixture.requestId())) + assertThatThrownBy(() -> + new CanonicalGameplayIssuerPartitionBuildRepository(cohortSchema.dsl()) + .prepareInitialBuildPlan(fixture.intent().operationId(), fixture.requestId())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("changed source-row digest"); } finally { @@ -1042,10 +1019,9 @@ void changedLayoutCohortOrSourceCannotResumeAnOriginalPlan() { "UPDATE game_session_canonical_issuer_partition_reservation" + " SET lifecycle = 'BOUND' WHERE reservation_id = ?", fixture.reservationId()); - assertThatThrownBy( - () -> - new CanonicalGameplayIssuerPartitionBuildRepository(sourceSchema.dsl()) - .prepareInitialBuildPlan(fixture.intent().operationId(), fixture.requestId())) + assertThatThrownBy(() -> + new CanonicalGameplayIssuerPartitionBuildRepository(sourceSchema.dsl()) + .prepareInitialBuildPlan(fixture.intent().operationId(), fixture.requestId())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Current source row differs"); } finally { @@ -1061,10 +1037,9 @@ void changedLayoutCohortOrSourceCannotResumeAnOriginalPlan() { "UPDATE game_session_canonical_issuer_layout_bootstrap_intent" + " SET source_checkpoint_bytes = convert_to('{}', 'UTF8') WHERE operation_id = ?", fixture.intent().operationId()); - assertThatThrownBy( - () -> - new CanonicalGameplayIssuerPartitionBuildRepository(checkpointSchema.dsl()) - .prepareInitialBuildPlan(fixture.intent().operationId(), fixture.requestId())) + assertThatThrownBy(() -> + new CanonicalGameplayIssuerPartitionBuildRepository(checkpointSchema.dsl()) + .prepareInitialBuildPlan(fixture.intent().operationId(), fixture.requestId())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("source checkpoint digest is invalid"); } finally { @@ -1225,57 +1200,48 @@ void retainedTerminalUnresolvedAndUnlinkedBoundReservationsBlockMemberIssuance() .toList()); var retainedBindingRow = plan.cohortRows().stream() - .filter( - row -> - row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.BINDING) + .filter(row -> + row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.BINDING) .findFirst() .orElseThrow(); assertThat(retainedBindingRow.sourceRowJson()).contains("TERMINAL_UNRESOLVED"); assertThat(plan.blockers()) - .anySatisfy( - blocker -> { - assertThat(blocker.sourceRowOrdinal()).isEqualTo(retainedBindingRow.rowOrdinal()); - assertThat(blocker.sourceRowDigest()) - .isEqualTo(retainedBindingRow.sourceRowDigest()); - assertThat(blocker.code()) - .isEqualTo( - CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode - .UNREPRESENTABLE_BINDING); - }); + .anySatisfy(blocker -> { + assertThat(blocker.sourceRowOrdinal()).isEqualTo(retainedBindingRow.rowOrdinal()); + assertThat(blocker.sourceRowDigest()).isEqualTo(retainedBindingRow.sourceRowDigest()); + assertThat(blocker.code()) + .isEqualTo( + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode.UNREPRESENTABLE_BINDING); + }); for (UUID reservationId : List.of(unlinkedBoundReservationId, unlinkedReleasePendingReservationId)) { var reservationRow = plan.cohortRows().stream() - .filter( - row -> - row.kind() - == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind - .RESERVATION - && row.sourceKey().equals(reservationId.toString())) + .filter(row -> + row.kind() + == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION + && row.sourceKey().equals(reservationId.toString())) .findFirst() .orElseThrow(); assertThat(plan.blockers()) - .anySatisfy( - blocker -> { - assertThat(blocker.sourceRowOrdinal()).isEqualTo(reservationRow.rowOrdinal()); - assertThat(blocker.sourceRowDigest()).isEqualTo(reservationRow.sourceRowDigest()); - assertThat(blocker.code()) - .isEqualTo( - CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode - .CONFLICTING_RESERVATION_LINK); - }); + .anySatisfy(blocker -> { + assertThat(blocker.sourceRowOrdinal()).isEqualTo(reservationRow.rowOrdinal()); + assertThat(blocker.sourceRowDigest()).isEqualTo(reservationRow.sourceRowDigest()); + assertThat(blocker.code()) + .isEqualTo( + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .CONFLICTING_RESERVATION_LINK); + }); } - assertThatThrownBy( - () -> - testSchema - .dsl() - .transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - return new CanonicalGameplayIssuerPartitionBuildRepository(transaction) - .readPreparedPlanInTransaction( - transaction, intent.operationId(), requestId); - })) + assertThatThrownBy(() -> + testSchema + .dsl() + .transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + return new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readPreparedPlanInTransaction( + transaction, intent.operationId(), requestId); + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining( "Blocked issuer partition build plan cannot issue member operations"); @@ -1481,36 +1447,35 @@ void initialBootstrapCountsNonterminalReservationCapacityAndExcludesReleasedRows .extracting(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::reservationLifecycle) .containsExactlyInAnyOrder("RESERVED", "RESERVED", "RESERVED", "RELEASED"); assertThat(plan.memberWorks()) - .allSatisfy( - work -> { - assertThat(work.originalPartitionId()) - .isEqualTo( - CanonicalGameplayBindingRef.fromExactBytes(work.bindingRef()) - .partitionId(partitionCount)); - assertThat(work.originalLayoutVersion()).isEqualTo(LAYOUT_VERSION); - assertThat(work.originalPartitionCount()).isEqualTo(partitionCount); - assertThat(work.originalPartitionCapacity()).isEqualTo(partitionCapacity); - assertThat(work.originalIssuerCoverageOperationId()) - .isNotEqualTo(work.plannedAnchorOperationId()); - assertThat(work.originalIssuerCoverageOperationFence()) - .isEqualTo(originalOperationFence) - .isNotEqualTo(intent.operationFence()); - assertThat(work.originalCoverageFence()) - .isEqualTo(originalCoverageFence) - .isNotEqualTo(intent.coverageFence()); - if (work.reservationId().equals(prepared.issuerReservationId())) { - assertThat(work.originalInventorySnapshotRevision()).isEqualTo(BigInteger.ONE); - } else { - assertThat(work.originalInventorySnapshotRevision()) - .isEqualTo(intent.inventorySnapshotRevision()); - } - assertThat(work.plannedPartitionId()).isEqualTo(work.originalPartitionId()); - assertThat(work.plannedAnchorOperationId()).isEqualTo(intent.operationId()); - assertThat(work.plannedAnchorOperationFence()).isEqualTo(intent.operationFence()); - assertThat(work.plannedAnchorCoverageFence()).isEqualTo(intent.coverageFence()); - assertThat(work.plannedAnchorInventorySnapshotRevision()) - .isEqualTo(intent.inventorySnapshotRevision()); - }); + .allSatisfy(work -> { + assertThat(work.originalPartitionId()) + .isEqualTo( + CanonicalGameplayBindingRef.fromExactBytes(work.bindingRef()) + .partitionId(partitionCount)); + assertThat(work.originalLayoutVersion()).isEqualTo(LAYOUT_VERSION); + assertThat(work.originalPartitionCount()).isEqualTo(partitionCount); + assertThat(work.originalPartitionCapacity()).isEqualTo(partitionCapacity); + assertThat(work.originalIssuerCoverageOperationId()) + .isNotEqualTo(work.plannedAnchorOperationId()); + assertThat(work.originalIssuerCoverageOperationFence()) + .isEqualTo(originalOperationFence) + .isNotEqualTo(intent.operationFence()); + assertThat(work.originalCoverageFence()) + .isEqualTo(originalCoverageFence) + .isNotEqualTo(intent.coverageFence()); + if (work.reservationId().equals(prepared.issuerReservationId())) { + assertThat(work.originalInventorySnapshotRevision()).isEqualTo(BigInteger.ONE); + } else { + assertThat(work.originalInventorySnapshotRevision()) + .isEqualTo(intent.inventorySnapshotRevision()); + } + assertThat(work.plannedPartitionId()).isEqualTo(work.originalPartitionId()); + assertThat(work.plannedAnchorOperationId()).isEqualTo(intent.operationId()); + assertThat(work.plannedAnchorOperationFence()).isEqualTo(intent.operationFence()); + assertThat(work.plannedAnchorCoverageFence()).isEqualTo(intent.coverageFence()); + assertThat(work.plannedAnchorInventorySnapshotRevision()) + .isEqualTo(intent.inventorySnapshotRevision()); + }); assertThat(plan.memberWorks()) .filteredOn(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::countsTowardCapacity) .hasSize(3); @@ -1688,25 +1653,19 @@ private static void assertPhysicalPartitionPlanBoundary( .extracting(CanonicalGameplayIssuerPartitionBuildPlan.Blocker::code) .containsOnly( CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode.PARTITION_CAPACITY_EXCEEDED); - assertThatThrownBy( - () -> - physicalOwner.preparePartitionWork( - intent.operationId(), - requestId, - BigInteger.ZERO, - checkpoint, - physicalBoundaryIncarnation())) + assertThatThrownBy(() -> + physicalOwner.preparePartitionWork( + intent.operationId(), + requestId, + BigInteger.ZERO, + checkpoint, + physicalBoundaryIncarnation())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining( "Blocked issuer partition build plan cannot issue member operations"); - assertThatThrownBy( - () -> - physicalOwner.beginOrResumePendingPhysicalProof( - intent.operationId(), - requestId, - 0, - checkpoint, - physicalBoundaryIncarnation())) + assertThatThrownBy(() -> + physicalOwner.beginOrResumePendingPhysicalProof( + intent.operationId(), requestId, 0, checkpoint, physicalBoundaryIncarnation())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining( "Blocked issuer partition build plan cannot issue member operations"); @@ -1775,11 +1734,9 @@ private static void assertBlockedInitialReservation( assertThat(plan.coverageGeneration()).isNull(); var originalReservation = fixture.intent().cohortRows().stream() - .filter( - row -> - row.kind() - == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION - && row.sourceKey().equals(fixture.extraReservationId().toString())) + .filter(row -> + row.kind() == CanonicalGameplayIssuerLayoutBootstrapIntent.CohortKind.RESERVATION + && row.sourceKey().equals(fixture.extraReservationId().toString())) .findFirst() .orElseThrow(); var retainedReservation = @@ -1791,14 +1748,13 @@ private static void assertBlockedInitialReservation( assertThat(retainedReservation.sourceRowDigest()) .isEqualTo(originalReservation.sourceRowDigest()); assertThat(plan.blockers()) - .anySatisfy( - blocker -> { - assertThat(blocker.sourceRowOrdinal()).isEqualTo(originalReservation.rowOrdinal()); - assertThat(blocker.code()) - .isEqualTo( - CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode - .CONFLICTING_RESERVATION_LINK); - }); + .anySatisfy(blocker -> { + assertThat(blocker.sourceRowOrdinal()).isEqualTo(originalReservation.rowOrdinal()); + assertThat(blocker.code()) + .isEqualTo( + CanonicalGameplayIssuerPartitionBuildPlan.BlockerCode + .CONFLICTING_RESERVATION_LINK); + }); assertThat(plan.memberWorks()) .extracting(CanonicalGameplayIssuerPartitionBuildPlan.MemberWork::reservationId) .contains(fixture.bindingReservationId()) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java index fe1f084da6..1c358ca059 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java @@ -93,63 +93,59 @@ public void executeStart(ExecuteContext context) { var observed = DSL.using( fixture.dsl().configuration().derive(new DefaultExecuteListenerProvider(listener))); - observed.transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - var anchor = - CanonicalGameplayIssuerBootstrapCoverageRepository - .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); - var plan = - new CanonicalGameplayIssuerPartitionBuildRepository(transaction) - .readInstalledPlanForAnchorInTransaction( - transaction, anchor.bootstrapOperationId(), anchor.bootstrapRequestId()); - var originals = - transaction.fetch( - "SELECT original.* FROM game_session_canonical_issuer_bootstrap_member_operation original" - + " WHERE bootstrap_operation_id = ? AND binding_lifecycle = 'CANDIDATE_PREPARED'" - + " ORDER BY work_ordinal", - anchor.bootstrapOperationId()); - assertThat(originals).hasSize(1); - proofReads.set(0); - var partitionProofs = - new CanonicalGameplayIssuerOriginalMemberSourceRepository.InstalledPartitionProofs( - transaction, anchor); - for (var row : originals) { - var original = - CanonicalGameplayIssuerOriginalMemberSourceRepository.readInstalledInTransaction( - transaction, anchor, current, row, plan, partitionProofs); - assertThat(original.operationId()) - .isEqualTo(row.get("member_operation_id", UUID.class)); + observed.transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + var anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + var plan = + new CanonicalGameplayIssuerPartitionBuildRepository(transaction) + .readInstalledPlanForAnchorInTransaction( + transaction, anchor.bootstrapOperationId(), anchor.bootstrapRequestId()); + var originals = + transaction.fetch( + "SELECT original.* FROM game_session_canonical_issuer_bootstrap_member_operation original" + + " WHERE bootstrap_operation_id = ? AND binding_lifecycle = 'CANDIDATE_PREPARED'" + + " ORDER BY work_ordinal", + anchor.bootstrapOperationId()); + assertThat(originals).hasSize(1); + proofReads.set(0); + var partitionProofs = + new CanonicalGameplayIssuerOriginalMemberSourceRepository.InstalledPartitionProofs( + transaction, anchor); + for (var row : originals) { + var original = CanonicalGameplayIssuerOriginalMemberSourceRepository.readInstalledInTransaction( transaction, anchor, current, row, plan, partitionProofs); - } - assertThat(proofReads.get()).isOne(); - - // Reusing the partition proof must never skip an individual member's byte check. - var corrupted = originals.get(0); - var digestField = - Objects.requireNonNull(corrupted.field("member_value_digest", String.class)); - String originalDigest = corrupted.get(digestField); - corrupted.set(digestField, "sha256:" + "0".repeat(64)); - assertThatThrownBy( - () -> - CanonicalGameplayIssuerOriginalMemberSourceRepository - .readInstalledInTransaction( - transaction, anchor, current, corrupted, plan, partitionProofs)) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("member value digest differs"); - corrupted.set(digestField, originalDigest); - - var freshProofs = - new CanonicalGameplayIssuerOriginalMemberSourceRepository.InstalledPartitionProofs( - transaction, anchor); - for (var row : originals) { - CanonicalGameplayIssuerOriginalMemberSourceRepository.readInstalledInTransaction( - transaction, anchor, current, row, plan, freshProofs); - } - assertThat(proofReads.get()).isEqualTo(2); - }); + assertThat(original.operationId()).isEqualTo(row.get("member_operation_id", UUID.class)); + CanonicalGameplayIssuerOriginalMemberSourceRepository.readInstalledInTransaction( + transaction, anchor, current, row, plan, partitionProofs); + } + assertThat(proofReads.get()).isOne(); + + // Reusing the partition proof must never skip an individual member's byte check. + var corrupted = originals.get(0); + var digestField = + Objects.requireNonNull(corrupted.field("member_value_digest", String.class)); + String originalDigest = corrupted.get(digestField); + corrupted.set(digestField, "sha256:" + "0".repeat(64)); + assertThatThrownBy(() -> + CanonicalGameplayIssuerOriginalMemberSourceRepository.readInstalledInTransaction( + transaction, anchor, current, corrupted, plan, partitionProofs)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("member value digest differs"); + corrupted.set(digestField, originalDigest); + + var freshProofs = + new CanonicalGameplayIssuerOriginalMemberSourceRepository.InstalledPartitionProofs( + transaction, anchor); + for (var row : originals) { + CanonicalGameplayIssuerOriginalMemberSourceRepository.readInstalledInTransaction( + transaction, anchor, current, row, plan, freshProofs); + } + assertThat(proofReads.get()).isEqualTo(2); + }); assertThat(physicalFieldSet(fixture.issuerPartitionKey())).isEqualTo(physicalBefore); } } @@ -266,17 +262,14 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc "operation_id", pendingAdd.physicalMutation().ownerOperationId()); byte[] partitionBeforeStaleReadback = physicalFieldSet(partitionKey); - assertThatThrownBy( - () -> - fixture - .dsl() - .transactionResult( - configuration -> - CanonicalGameplayIssuerPartitionMutationRepository - .completeInTransaction( - org.jooq.impl.DSL.using(configuration), - pendingAdd.physicalMutation(), - staleReadback))) + assertThatThrownBy(() -> + fixture + .dsl() + .transactionResult(configuration -> + CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( + org.jooq.impl.DSL.using(configuration), + pendingAdd.physicalMutation(), + staleReadback))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("exact current physical mutation revision"); assertThat(physicalFieldSet(partitionKey)).isEqualTo(partitionBeforeStaleReadback); @@ -387,39 +380,33 @@ void retiresOriginalReleasesAndContinuesPastThePhysicalHistoryBound() throws Exc // Exercise the actual SQL completion and automatic membership removal, then abort the // transaction. Physical absence alone must not make the original cease to be current. - assertThatThrownBy( - () -> - fixture - .dsl() - .transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision( - transaction); - CanonicalGameplayIssuerPartitionMutationRepository - .completeInTransaction( - transaction, - pendingOldestRetirement.physicalMutation(), - afterUncommittedRetirement); - assertThat( - transaction.execute( - "UPDATE game_session_canonical_issuer_binding_local_retirement" - + " SET status = 'RETIRED'," - + " exact_absence_readback_field_set_bytes = ?," - + " exact_absence_readback_field_set_digest = ?," - + " completed_at = CURRENT_TIMESTAMP" - + " WHERE retirement_operation_id = ?", - afterUncommittedRetirement, - CanonicalGameplayIssuerMemberV2Codec.sha256( - afterUncommittedRetirement), - pendingOldestRetirement.operationId())) - .isOne(); - assertThat(currentOperationIds(transaction)) - .containsExactlyInAnyOrder( - newerOperationId, neverProjectedOperationId); - throw new IllegalStateException( - "controlled retirement completion rollback"); - })) + assertThatThrownBy(() -> + fixture + .dsl() + .transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( + transaction, + pendingOldestRetirement.physicalMutation(), + afterUncommittedRetirement); + assertThat( + transaction.execute( + "UPDATE game_session_canonical_issuer_binding_local_retirement" + + " SET status = 'RETIRED'," + + " exact_absence_readback_field_set_bytes = ?," + + " exact_absence_readback_field_set_digest = ?," + + " completed_at = CURRENT_TIMESTAMP" + + " WHERE retirement_operation_id = ?", + afterUncommittedRetirement, + CanonicalGameplayIssuerMemberV2Codec.sha256( + afterUncommittedRetirement), + pendingOldestRetirement.operationId())) + .isOne(); + assertThat(currentOperationIds(transaction)) + .containsExactlyInAnyOrder(newerOperationId, neverProjectedOperationId); + throw new IllegalStateException("controlled retirement completion rollback"); + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("controlled retirement completion rollback"); assertThat(currentOperationIds(fixture.dsl())).isEqualTo(membershipBeforeRetirement); @@ -812,13 +799,12 @@ void retirementRequiresAndPreservesExactSeededBaselineSnapshot() throws Exceptio fixture.readPreparedPartitionWork(release.originalOperation()).baselineFields(); var baselineCapacity = baseline.entrySet().stream() - .filter( - entry -> - entry - .getKey() - .startsWith( - CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec - .RESERVATION_FIELD_PREFIX)) + .filter(entry -> + entry + .getKey() + .startsWith( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec + .RESERVATION_FIELD_PREFIX)) .findFirst() .orElseThrow(); byte[] baselineCapacityField = baselineCapacity.getKey().getBytes(StandardCharsets.US_ASCII); @@ -911,9 +897,8 @@ void postRetirementSqlRejectsUnaccountedCurrentReservationInAnotherPartition() t String retiredAuditBefore = retirementImage(fixture.dsl(), fixture.transitionId()); long reservationsBefore = reservationCount(fixture.dsl()); - assertThatThrownBy( - () -> - insertUnaccountedCurrentReservation(fixture, otherPartitionSeed, otherPartition)) + assertThatThrownBy(() -> + insertUnaccountedCurrentReservation(fixture, otherPartitionSeed, otherPartition)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining( "Installed issuer reservation requires exact bootstrap or current local-operation membership"); @@ -1134,22 +1119,20 @@ private void upgradeRetainedBootstrapAcrossAdditiveColumn( parent.fetch( "SELECT gs_require_issuer_reservation_current_membership(?)", baselineReservationId); - assertThatThrownBy( - () -> - parent.transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - assertThat( - transaction.execute( - "UPDATE game_session_canonical_issuer_partition_reservation" - + " SET coverage_fence = coverage_fence + 1" - + " WHERE reservation_id = ?", - baselineReservationId)) - .isOne(); - transaction.fetch( - "SELECT gs_require_issuer_reservation_current_membership(?)", - baselineReservationId); - })) + assertThatThrownBy(() -> + parent.transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + assertThat( + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_reservation" + + " SET coverage_fence = coverage_fence + 1" + + " WHERE reservation_id = ?", + baselineReservationId)) + .isOne(); + transaction.fetch( + "SELECT gs_require_issuer_reservation_current_membership(?)", + baselineReservationId); + })) .isInstanceOf(org.jooq.exception.DataAccessException.class) .rootCause() .isInstanceOf(org.postgresql.util.PSQLException.class) @@ -1209,48 +1192,45 @@ void bootstrapMembershipPreservesNativeAttributesAcrossSessionRenderingChanges() for (String byteaOutput : List.of("hex", "escape")) { fixture .dsl() - .transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - // LOCAL settings and the guard use this transaction's same owned connection. - transaction.execute("SET LOCAL TimeZone = '" + timeZone + "'"); - transaction.execute("SET LOCAL bytea_output = '" + byteaOutput + "'"); - var rendered = - transaction.fetchSingle( - "SELECT to_jsonb(created_at)::text, to_jsonb(binding_ref)::text FROM" - + " game_session_canonical_issuer_partition_reservation" - + " WHERE reservation_id = ?", - baselineReservationId); - timestampRenderings.put(timeZone, rendered.get(0, String.class)); - binaryRenderings.put(byteaOutput, rendered.get(1, String.class)); - transaction.fetch( - "SELECT gs_require_issuer_reservation_current_membership(?)", + .transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + // LOCAL settings and the guard use this transaction's same owned connection. + transaction.execute("SET LOCAL TimeZone = '" + timeZone + "'"); + transaction.execute("SET LOCAL bytea_output = '" + byteaOutput + "'"); + var rendered = + transaction.fetchSingle( + "SELECT to_jsonb(created_at)::text, to_jsonb(binding_ref)::text FROM" + + " game_session_canonical_issuer_partition_reservation" + + " WHERE reservation_id = ?", baselineReservationId); - }); + timestampRenderings.put(timeZone, rendered.get(0, String.class)); + binaryRenderings.put(byteaOutput, rendered.get(1, String.class)); + transaction.fetch( + "SELECT gs_require_issuer_reservation_current_membership(?)", + baselineReservationId); + }); } } assertThat(timestampRenderings.values()).doesNotHaveDuplicates(); assertThat(binaryRenderings.values()).doesNotHaveDuplicates(); - assertThatThrownBy( - () -> - fixture - .dsl() - .transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - transaction.execute("SET LOCAL TimeZone = 'Pacific/Auckland'"); - transaction.execute("SET LOCAL bytea_output = 'escape'"); - assertThat( - transaction.execute( - "UPDATE game_session_canonical_issuer_partition_reservation" - + " SET coverage_fence = coverage_fence + 1" - + " WHERE reservation_id = ?", - baselineReservationId)) - .isOne(); - transaction.fetch( - "SELECT gs_require_issuer_reservation_current_membership(?)", - baselineReservationId); - })) + assertThatThrownBy(() -> + fixture + .dsl() + .transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET LOCAL TimeZone = 'Pacific/Auckland'"); + transaction.execute("SET LOCAL bytea_output = 'escape'"); + assertThat( + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_reservation" + + " SET coverage_fence = coverage_fence + 1" + + " WHERE reservation_id = ?", + baselineReservationId)) + .isOne(); + transaction.fetch( + "SELECT gs_require_issuer_reservation_current_membership(?)", + baselineReservationId); + })) .isInstanceOf(org.jooq.exception.DataAccessException.class) .rootCause() .isInstanceOf(org.postgresql.util.PSQLException.class) @@ -1372,91 +1352,83 @@ void currentMembershipRejectsPrematureDeletionMutationTruncateAndDeferredSourceM List membershipBefore = currentOperationIds(fixture.dsl()); String originalBefore = localOperationImage(fixture.dsl(), originalId); String historyBefore = durableHistoryImage(fixture.dsl(), NIL_UUID); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "DELETE FROM game_session_canonical_issuer_current_local_operation WHERE operation_id = ?", - originalId)) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "DELETE FROM game_session_canonical_issuer_current_local_operation WHERE operation_id = ?", + originalId)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("exact committed original retirement"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "UPDATE game_session_canonical_issuer_current_local_operation" - + " SET partition_id = partition_id WHERE operation_id = ?", - originalId)) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_current_local_operation" + + " SET partition_id = partition_id WHERE operation_id = ?", + originalId)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("cannot be updated or truncated"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute("TRUNCATE game_session_canonical_issuer_current_local_operation")) + assertThatThrownBy(() -> + fixture + .dsl() + .execute("TRUNCATE game_session_canonical_issuer_current_local_operation")) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("cannot be updated or truncated"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "INSERT INTO game_session_canonical_issuer_current_local_operation" - + " (operation_id, issuer_id, anchor_bootstrap_operation_id, partition_id)" - + " SELECT operation_id, issuer_id, anchor_bootstrap_operation_id, partition_id + 1" - + " FROM game_session_canonical_issuer_binding_local_operation WHERE operation_id = ?", - originalId)) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "INSERT INTO game_session_canonical_issuer_current_local_operation" + + " (operation_id, issuer_id, anchor_bootstrap_operation_id, partition_id)" + + " SELECT operation_id, issuer_id, anchor_bootstrap_operation_id, partition_id + 1" + + " FROM game_session_canonical_issuer_binding_local_operation WHERE operation_id = ?", + originalId)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("exact unretired immutable source"); - assertThatThrownBy( - () -> - fixture - .dsl() - .transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - // The write itself succeeds; the reverse guard checks the committed - // postimage. - assertThat( - transaction.execute( - "UPDATE game_session_canonical_issuer_partition_reservation reservation" - + " SET coverage_fence = reservation.coverage_fence + 1" - + " FROM game_session_canonical_issuer_binding_local_operation original" - + " WHERE original.operation_id = ?" - + " AND reservation.reservation_id = original.reservation_id", - originalId)) - .isOne(); - })) + assertThatThrownBy(() -> + fixture + .dsl() + .transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + // The write itself succeeds; the reverse guard checks the committed + // postimage. + assertThat( + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_reservation reservation" + + " SET coverage_fence = reservation.coverage_fence + 1" + + " FROM game_session_canonical_issuer_binding_local_operation original" + + " WHERE original.operation_id = ?" + + " AND reservation.reservation_id = original.reservation_id", + originalId)) + .isOne(); + })) .isInstanceOf(org.jooq.exception.DataAccessException.class) .rootCause() .isInstanceOf(org.postgresql.util.PSQLException.class) .hasMessageContaining("exact installed local-operation source"); - assertThatThrownBy( - () -> - fixture - .dsl() - .transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - // A seeded bootstrap reservation is also bound to its complete frozen - // owner - // and coverage tuple, rather than being admitted by reservation - // identity alone. - assertThat( - transaction.execute( - "UPDATE game_session_canonical_issuer_partition_reservation reservation" - + " SET coverage_fence = reservation.coverage_fence + 1" - + " FROM game_session_canonical_issuer_installed_anchor anchor" - + " JOIN game_session_canonical_issuer_partition_build_cohort_row cohort" - + " ON cohort.build_operation_id = anchor.build_operation_id" - + " AND cohort.source_operation_id = anchor.bootstrap_operation_id" - + " AND cohort.issuer_id = anchor.issuer_id" - + " AND cohort.source_kind = 'RESERVATION'" - + " WHERE reservation.reservation_id::text = cohort.source_key")) - .isOne(); - })) + assertThatThrownBy(() -> + fixture + .dsl() + .transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + // A seeded bootstrap reservation is also bound to its complete frozen + // owner + // and coverage tuple, rather than being admitted by reservation + // identity alone. + assertThat( + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_reservation reservation" + + " SET coverage_fence = reservation.coverage_fence + 1" + + " FROM game_session_canonical_issuer_installed_anchor anchor" + + " JOIN game_session_canonical_issuer_partition_build_cohort_row cohort" + + " ON cohort.build_operation_id = anchor.build_operation_id" + + " AND cohort.source_operation_id = anchor.bootstrap_operation_id" + + " AND cohort.issuer_id = anchor.issuer_id" + + " AND cohort.source_kind = 'RESERVATION'" + + " WHERE reservation.reservation_id::text = cohort.source_key")) + .isOne(); + })) .isInstanceOf(org.jooq.exception.DataAccessException.class) .rootCause() .isInstanceOf(org.postgresql.util.PSQLException.class) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRetirementMutationLineageIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRetirementMutationLineageIntegrationTest.java index f830b5594c..cd3eb69b9c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRetirementMutationLineageIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRetirementMutationLineageIntegrationTest.java @@ -112,34 +112,30 @@ void rejectsWrongBootstrapAtPreparationAndCommitAndRetainsGenuineRetirement( assertRetiredInsertAtCreationIsRefused( fixture, pending.operationId(), pendingRow, retainedBefore, physicalBefore); - assertThatThrownBy( - () -> - fixture - .dsl() - .transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - // Only manufacture the malformed preimage as the disposable PG - // superuser. Restore normal triggers before the real INSERT. The - // expected refusal rolls back this deletion and lineage corruption. - transaction.execute("SET LOCAL session_replication_role = replica"); - assertThat( - transaction.execute( - "DELETE FROM " - + RETIREMENT - + " WHERE retirement_operation_id = ?", - pending.operationId())) - .isOne(); - corruptMutationLineage(transaction, pending, wrongBootstrapId); - transaction.execute("SET LOCAL session_replication_role = origin"); + assertThatThrownBy(() -> + fixture + .dsl() + .transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + // Only manufacture the malformed preimage as the disposable PG + // superuser. Restore normal triggers before the real INSERT. The + // expected refusal rolls back this deletion and lineage corruption. + transaction.execute("SET LOCAL session_replication_role = replica"); + assertThat( transaction.execute( - "INSERT INTO " - + RETIREMENT - + " SELECT (jsonb_populate_record(NULL::" - + RETIREMENT - + ", ?::jsonb)).*", - pendingRow); - })) + "DELETE FROM " + RETIREMENT + " WHERE retirement_operation_id = ?", + pending.operationId())) + .isOne(); + corruptMutationLineage(transaction, pending, wrongBootstrapId); + transaction.execute("SET LOCAL session_replication_role = origin"); + transaction.execute( + "INSERT INTO " + + RETIREMENT + + " SELECT (jsonb_populate_record(NULL::" + + RETIREMENT + + ", ?::jsonb)).*", + pendingRow); + })) .isInstanceOf(org.jooq.exception.DataAccessException.class) .rootCause() .isInstanceOfSatisfying( @@ -156,35 +152,31 @@ void rejectsWrongBootstrapAtPreparationAndCommitAndRetainsGenuineRetirement( byte[] retiredPhysical = physicalFieldSet(fixture.issuerPartitionKey()); assertThat(retiredPhysical).isNotEqualTo(physicalBefore); Map> beforeCommitRefusal = retainedRows(fixture.dsl(), true); - assertThatThrownBy( - () -> - fixture - .dsl() - .transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision( - transaction); - CanonicalGameplayIssuerPartitionMutationRepository - .completeInTransaction( - transaction, pending.physicalMutation(), retiredPhysical); - // All committed proof bytes and revisions are genuine. Corrupt only - // bootstrap lineage, then restore all guards for the real UPDATE. - transaction.execute("SET LOCAL session_replication_role = replica"); - corruptMutationLineage(transaction, pending, wrongBootstrapId); - transaction.execute("SET LOCAL session_replication_role = origin"); - transaction.execute( - "UPDATE " - + RETIREMENT - + " SET status = 'RETIRED'," - + " exact_absence_readback_field_set_bytes = ?," - + " exact_absence_readback_field_set_digest = ?," - + " completed_at = CURRENT_TIMESTAMP" - + " WHERE retirement_operation_id = ?", - retiredPhysical, - CanonicalGameplayIssuerMemberV2Codec.sha256(retiredPhysical), - pending.operationId()); - })) + assertThatThrownBy(() -> + fixture + .dsl() + .transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerPartitionMutationRepository.completeInTransaction( + transaction, pending.physicalMutation(), retiredPhysical); + // All committed proof bytes and revisions are genuine. Corrupt only + // bootstrap lineage, then restore all guards for the real UPDATE. + transaction.execute("SET LOCAL session_replication_role = replica"); + corruptMutationLineage(transaction, pending, wrongBootstrapId); + transaction.execute("SET LOCAL session_replication_role = origin"); + transaction.execute( + "UPDATE " + + RETIREMENT + + " SET status = 'RETIRED'," + + " exact_absence_readback_field_set_bytes = ?," + + " exact_absence_readback_field_set_digest = ?," + + " completed_at = CURRENT_TIMESTAMP" + + " WHERE retirement_operation_id = ?", + retiredPhysical, + CanonicalGameplayIssuerMemberV2Codec.sha256(retiredPhysical), + pending.operationId()); + })) .isInstanceOf(org.jooq.exception.DataAccessException.class) .rootCause() .isInstanceOfSatisfying( @@ -261,32 +253,28 @@ private void assertRetiredInsertAtCreationIsRefused( pendingRow) .get(0, String.class); - assertThatThrownBy( - () -> - fixture - .dsl() - .transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - // Replace only the existing pending preimage under disabled triggers; - // restore origin before testing the actual INSERT guard. - transaction.execute("SET LOCAL session_replication_role = replica"); - assertThat( - transaction.execute( - "DELETE FROM " - + RETIREMENT - + " WHERE retirement_operation_id = ?", - retirementOperationId)) - .isOne(); - transaction.execute("SET LOCAL session_replication_role = origin"); + assertThatThrownBy(() -> + fixture + .dsl() + .transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + // Replace only the existing pending preimage under disabled triggers; + // restore origin before testing the actual INSERT guard. + transaction.execute("SET LOCAL session_replication_role = replica"); + assertThat( transaction.execute( - "INSERT INTO " - + RETIREMENT - + " SELECT (jsonb_populate_record(NULL::" - + RETIREMENT - + ", ?::jsonb)).*", - forgedRetiredRow); - })) + "DELETE FROM " + RETIREMENT + " WHERE retirement_operation_id = ?", + retirementOperationId)) + .isOne(); + transaction.execute("SET LOCAL session_replication_role = origin"); + transaction.execute( + "INSERT INTO " + + RETIREMENT + + " SELECT (jsonb_populate_record(NULL::" + + RETIREMENT + + ", ?::jsonb)).*", + forgedRetiredRow); + })) .isInstanceOf(org.jooq.exception.DataAccessException.class) .rootCause() .isInstanceOfSatisfying( @@ -419,22 +407,21 @@ private static void recordInstalledNegativeTerminal( UUID cleanupId = UUID.randomUUID(); UUID resolutionId = UUID.randomUUID(); when(account.abortNeverAdmitted(anyString(), any(), any(), any())) - .thenAnswer( - invocation -> { - var source = fixture.abandonmentSource(); - // The actual closure and terminal SQL write run. A controlled incarnation change - // stops automatic issuer cleanup so this test can exercise its SQL boundaries. - fixture.moveIssuerIncarnation(); - return new AbortEvidence( - lease, - fixture.transitionId(), - source.abandonmentId(), - CanonicalGameplayIssuerMemberV2Codec.sha256(source.candidate().canonicalBytes()) - .substring(7), - source.closureDigest().substring(7), - cleanupId, - resolutionId); - }); + .thenAnswer(invocation -> { + var source = fixture.abandonmentSource(); + // The actual closure and terminal SQL write run. A controlled incarnation change + // stops automatic issuer cleanup so this test can exercise its SQL boundaries. + fixture.moveIssuerIncarnation(); + return new AbortEvidence( + lease, + fixture.transitionId(), + source.abandonmentId(), + CanonicalGameplayIssuerMemberV2Codec.sha256(source.candidate().canonicalBytes()) + .substring(7), + source.closureDigest().substring(7), + cleanupId, + resolutionId); + }); assertThatThrownBy( () -> fixture.neverAdmittedOwner(account).abort(fixture.transitionId(), "controlled")) .isInstanceOf(IllegalStateException.class); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationRepositoryIntegrationTest.java index fe30409062..867a784b97 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationRepositoryIntegrationTest.java @@ -117,10 +117,9 @@ void futureRevisionRowsBlockInsteadOfDisappearingFromTheCanonicalSnapshot() { assertThat(canonical.inventoryRevision()).isEqualTo(java.math.BigInteger.valueOf(7)); assertThat(canonical.bindings()).isEmpty(); - assertThatThrownBy( - () -> - repository.captureSnapshots( - operation.operationId(), emptyLegacySnapshot(), canonical)) + assertThatThrownBy(() -> + repository.captureSnapshots( + operation.operationId(), emptyLegacySnapshot(), canonical)) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("rows beyond the inventory clock"); assertThat(repository.read(operation.operationId()).state()) @@ -304,13 +303,12 @@ public CanonicalGameplayLegacyMigrationReadback readBackExact( assertThatThrownBy(owner::migrate) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) - .satisfies( - failure -> { - assertThat(failure.getCause()).isSameAs(originalFailure); - assertThat(originalFailure.getSuppressed()).hasSize(1); - assertThat(originalFailure.getSuppressed()[0]) - .hasMessageContaining("reject_owner_block_for_test"); - }); + .satisfies(failure -> { + assertThat(failure.getCause()).isSameAs(originalFailure); + assertThat(originalFailure.getSuppressed()).hasSize(1); + assertThat(originalFailure.getSuppressed()[0]) + .hasMessageContaining("reject_owner_block_for_test"); + }); UUID operationId = java.util.Objects.requireNonNull( dsl.fetchOne( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest.java index 4efe44e058..189d83ef3a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateRedisOwnerIntegrationTest.java @@ -152,13 +152,12 @@ void selectedAbandonmentRetainsTheExactOriginalAndExcludesEveryPositiveCandidate .hasMessageContaining("irreversibly abandoned"); assertThatThrownBy(() -> source.repository().beginAccountMemberRepair(TRANSITION_ID)) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); - assertThatThrownBy( - () -> - source - .dsl() - .execute( - "UPDATE game_session_canonical_binding_transition SET status = 'PROVISIONAL' WHERE transition_id = ?", - TRANSITION_ID)) + assertThatThrownBy(() -> + source + .dsl() + .execute( + "UPDATE game_session_canonical_binding_transition SET status = 'PROVISIONAL' WHERE transition_id = ?", + TRANSITION_ID)) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(admin.dbsize()).isZero(); } @@ -292,46 +291,45 @@ private void moveAccountControlAfterCandidateCreate(String nextControl) { UUID coverageFence = UUID.randomUUID(); source .dsl() - .transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - transaction.execute( - "INSERT INTO game_session_canonical_account_coverage_operation" - + " (operation_id, request_id, account_id, legacy_cohort_id, legacy_owner_operation_id," - + " legacy_writer_fence, legacy_source_snapshot_revision, legacy_canonical_inventory_revision," - + " legacy_namespace_index_readback_revision, legacy_evidence_digest, lifecycle, operation_fence," - + " coverage_fence, account_admission_fence, historical_account_admission_fence, resolved_scope_kind," - + " snapshot_state, inventory_snapshot_revision, coverage_generation, redis_member_count, redis_member_set_digest)" - + " SELECT ?, ?, ?, cohort_id, owner_operation_id, legacy_writer_fence, source_snapshot_revision," - + " canonical_inventory_revision, namespace_index_readback_revision, evidence_digest, ?, 1," - + " ?, ?, ?, 'ACCOUNT_WIDE', 'COMPLETE', ?, ?, ?, ?" - + " FROM game_session_canonical_binding_legacy_disposition WHERE singleton_id = 1", - operation, - UUID.randomUUID(), - source.identity().accountId(), - nextControl, - coverageFence, - historical ? null : admissionFence, - historical ? admissionFence : null, - historical ? snapshot : null, - historical ? generation : null, - historical ? 0L : null, - historical ? "sha256:" + "0".repeat(64) : null); - transaction.execute( - "UPDATE game_session_canonical_account_coverage_control SET state = ?," - + " last_operation_fence = 1, current_operation_id = ?, current_operation_fence = 1," - + " account_admission_fence = ?, historical_account_admission_fence = ?, coverage_fence = ?," - + " inventory_snapshot_revision = ?, coverage_generation = ? WHERE account_id = ?", - nextControl, - operation, - historical ? null : admissionFence, - historical ? admissionFence : null, - coverageFence, - historical ? snapshot : null, - historical ? generation : null, - source.identity().accountId()); - }); + .transaction(configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + transaction.execute( + "INSERT INTO game_session_canonical_account_coverage_operation" + + " (operation_id, request_id, account_id, legacy_cohort_id, legacy_owner_operation_id," + + " legacy_writer_fence, legacy_source_snapshot_revision, legacy_canonical_inventory_revision," + + " legacy_namespace_index_readback_revision, legacy_evidence_digest, lifecycle, operation_fence," + + " coverage_fence, account_admission_fence, historical_account_admission_fence, resolved_scope_kind," + + " snapshot_state, inventory_snapshot_revision, coverage_generation, redis_member_count, redis_member_set_digest)" + + " SELECT ?, ?, ?, cohort_id, owner_operation_id, legacy_writer_fence, source_snapshot_revision," + + " canonical_inventory_revision, namespace_index_readback_revision, evidence_digest, ?, 1," + + " ?, ?, ?, 'ACCOUNT_WIDE', 'COMPLETE', ?, ?, ?, ?" + + " FROM game_session_canonical_binding_legacy_disposition WHERE singleton_id = 1", + operation, + UUID.randomUUID(), + source.identity().accountId(), + nextControl, + coverageFence, + historical ? null : admissionFence, + historical ? admissionFence : null, + historical ? snapshot : null, + historical ? generation : null, + historical ? 0L : null, + historical ? "sha256:" + "0".repeat(64) : null); + transaction.execute( + "UPDATE game_session_canonical_account_coverage_control SET state = ?," + + " last_operation_fence = 1, current_operation_id = ?, current_operation_fence = 1," + + " account_admission_fence = ?, historical_account_admission_fence = ?, coverage_fence = ?," + + " inventory_snapshot_revision = ?, coverage_generation = ? WHERE account_id = ?", + nextControl, + operation, + historical ? null : admissionFence, + historical ? admissionFence : null, + coverageFence, + historical ? snapshot : null, + historical ? generation : null, + source.identity().accountId()); + }); } @org.junit.jupiter.api.Test @@ -512,12 +510,11 @@ void installsExactCandidateAndReadOnlyRetryRetainsTheSameProvisionalDecision() { source .repository() .readAdmissionDecision(TRANSITION_ID, source.decision().leaseEvidence())) - .satisfies( - stored -> { - assertThat(first.candidate().matchesOriginalDecision(stored)).isTrue(); - assertThat(stored.leaseEvidence().canonicalJson()) - .isEqualTo(source.decision().leaseEvidence().canonicalJson()); - }); + .satisfies(stored -> { + assertThat(first.candidate().matchesOriginalDecision(stored)).isTrue(); + assertThat(stored.leaseEvidence().canonicalJson()) + .isEqualTo(source.decision().leaseEvidence().canonicalJson()); + }); assertThat(admin.type(ascii(first.sessionKey()))).isEqualTo("string"); assertThat(admin.get(ascii(first.sessionKey()))).containsExactly(first.exactCandidateBytes()); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java index 09c5401071..c95cb6d0f7 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionCompositionFixture.java @@ -395,15 +395,14 @@ public void getPublishedRealmAdmissionOwnerRead( net.firedevops.firemud.common.gamedesign.RealmPolicyPublishedEvidenceCodec.decode(retained); var policies = published.policies().stream() - .map( - policy -> - new net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence( - policy.policyId(), - policy.source().commitId(), - policy.source().revisionId(), - policy.source().logicalRevisionId(), - policy.source().policy(), - policy.policyDigest())) + .map(policy -> + new net.firedevops.firemud.common.publication.PublishedRealmEntryPolicyEvidence( + policy.policyId(), + policy.source().commitId(), + policy.source().revisionId(), + policy.source().logicalRevisionId(), + policy.source().policy(), + policy.policyDigest())) .toList(); var complete = new net.firedevops.firemud.common.publication.PublishedRealmEntryPolicySetEvidence( @@ -467,19 +466,18 @@ public void getPublishedRealmAdmissionOwnerRead( var worldSelector = publishedRelease.worldStartLocationEvidence(); var participants = publishedRelease.participantDigests().stream() - .map( - participant -> - new net.firedevops.firemud.common.gamedesign - .AuthoredWorldReleaseAttestationEvidence.Participant( - participant.participantKey(), - participant.scopeValue(), - false, - null, - participant.appliedCommitId(), - participant.contentDigest(), - participant.digestSchemaVersion(), - participant.abilitySchemaDigest() != null, - participant.abilitySchemaDigest())) + .map(participant -> + new net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence + .Participant( + participant.participantKey(), + participant.scopeValue(), + false, + null, + participant.appliedCommitId(), + participant.contentDigest(), + participant.digestSchemaVersion(), + participant.abilitySchemaDigest() != null, + participant.abilitySchemaDigest())) .toList(); var release = net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence.create( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java index b4f9f14f53..13d1747494 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionOwnerIntegrationTest.java @@ -179,14 +179,13 @@ void requiredIssuerObligationDeleteRefusesExplicitlyAndRetainedCandidateStillFin String retainedRows = sqlImage(); Map retainedPhysical = physicalImage(); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "DELETE FROM game_session_canonical_binding_issuer_index_obligation" - + " WHERE transition_id = ?", - fixture.transitionId())) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "DELETE FROM game_session_canonical_binding_issuer_index_obligation" + + " WHERE transition_id = ?", + fixture.transitionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) .rootCause() .isInstanceOfSatisfying( @@ -238,21 +237,19 @@ void committedReceiptSurvivesDeleteRefusalAndClockUnavailabilityUntilCatchup() t Map retainedPhysical = physicalImage(); // The candidate BEFORE DELETE guard is the first refusal, before retained-child FKs. - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "DELETE FROM game_session_canonical_binding_transition WHERE transition_id = ?", - fixture.transitionId())) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "DELETE FROM game_session_canonical_binding_transition WHERE transition_id = ?", + fixture.transitionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) - .satisfies( - failure -> - assertGuardRefusal( - failure, - "23514", - "gs_original_new_candidate_retained", - "Original NEW candidate transition retention is held")); + .satisfies(failure -> + assertGuardRefusal( + failure, + "23514", + "gs_original_new_candidate_retained", + "Original NEW candidate transition retention is held")); assertThat( fixture .dsl() @@ -266,10 +263,8 @@ void committedReceiptSurvivesDeleteRefusalAndClockUnavailabilityUntilCatchup() t List.of(actual.admissionAtMillis() - 1L, actual.admissionAtMillis() - 5_001L, 0L)) { var unavailableReader = reader(Clock.fixed(Instant.ofEpochMilli(unobservableNow), ZoneOffset.UTC)); - assertThatThrownBy( - () -> - unavailableReader.readActualOriginalFinalAdmission( - credential.selector(), "test")) + assertThatThrownBy(() -> + unavailableReader.readActualOriginalFinalAdmission(credential.selector(), "test")) .isExactlyInstanceOf(IllegalStateException.class) .hasMessage("Current clock cannot observe the finalized original admission instant"); assertThat(sqlImage()).isEqualTo(retainedRows); @@ -372,68 +367,62 @@ private void assertSameNativeCandidateFinalizesCommitsReadsAndRecoversExactTimes assertThat(sqlImage()).isEqualTo(beforeCommitRows); // The native issuer receipt already exists, but provisional physical final readback is // insufficient to settle the issuer obligation before its matching SQL final commit. - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "UPDATE game_session_canonical_binding_issuer_index_obligation" - + " SET status = 'ACKNOWLEDGED', inventory_revision = inventory_revision + 1" - + " WHERE transition_id = ?", - fixture.transitionId())) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "UPDATE game_session_canonical_binding_issuer_index_obligation" + + " SET status = 'ACKNOWLEDGED', inventory_revision = inventory_revision + 1" + + " WHERE transition_id = ?", + fixture.transitionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) - .satisfies( - failure -> - assertGuardRefusal( - failure, - "23514", - "gs_original_new_issuer_obligation_source", - "Final issuer obligation requires matching committed original NEW and native acknowledgement")); + .satisfies(failure -> + assertGuardRefusal( + failure, + "23514", + "gs_original_new_issuer_obligation_source", + "Final issuer obligation requires matching committed original NEW and native acknowledgement")); assertThat(sqlImage()).isEqualTo(beforeCommitRows); // SQL cannot terminalize the genuine provisional source without its complete receipt. - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "UPDATE game_session_canonical_binding_transition" - + " SET status = 'COMMITTED', inventory_revision = inventory_revision + 1" - + " WHERE transition_id = ?", - fixture.transitionId())) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "UPDATE game_session_canonical_binding_transition" + + " SET status = 'COMMITTED', inventory_revision = inventory_revision + 1" + + " WHERE transition_id = ?", + fixture.transitionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) - .satisfies( - failure -> - assertGuardRefusal( - failure, - "23514", - "gs_binding_runtime_fence_terminal_owner_required", - "A lease-bound runtime fence cannot be released without definitive first-NEW Account abort evidence")); + .satisfies(failure -> + assertGuardRefusal( + failure, + "23514", + "gs_binding_runtime_fence_terminal_owner_required", + "A lease-bound runtime fence cannot be released without definitive first-NEW Account abort evidence")); assertThat(sqlImage()).isEqualTo(beforeCommitRows); // Even genuine final readback values cannot authorize changing the original source. - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "UPDATE game_session_canonical_binding_transition SET status = 'COMMITTED'," - + " inventory_revision = inventory_revision + 1," - + " original_new_final_session_sha256 = ?, original_new_admission_at_ms = ?," - + " original_new_continuity_expires_at_ms = ?, original_new_session_duration_ms = ?," - + " candidate_account_index_fence = ? WHERE transition_id = ?", - actual.finalSessionSha256(), - actual.admissionAtMillis(), - actual.continuityExpiresAtMillis(), - actual.canonicalSessionDurationMillis(), - UUID.randomUUID(), - fixture.transitionId())) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "UPDATE game_session_canonical_binding_transition SET status = 'COMMITTED'," + + " inventory_revision = inventory_revision + 1," + + " original_new_final_session_sha256 = ?, original_new_admission_at_ms = ?," + + " original_new_continuity_expires_at_ms = ?, original_new_session_duration_ms = ?," + + " candidate_account_index_fence = ? WHERE transition_id = ?", + actual.finalSessionSha256(), + actual.admissionAtMillis(), + actual.continuityExpiresAtMillis(), + actual.canonicalSessionDurationMillis(), + UUID.randomUUID(), + fixture.transitionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) - .satisfies( - failure -> - assertGuardRefusal( - failure, - "23514", - "gs_original_new_final_transition_source_immutable", - "Original NEW final commit cannot change its original transition source")); + .satisfies(failure -> + assertGuardRefusal( + failure, + "23514", + "gs_original_new_final_transition_source_immutable", + "Original NEW final commit cannot change its original transition source")); assertThat(sqlImage()).isEqualTo(beforeCommitRows); // The pending source fences the actual runtime writer, so a stopped precommit row cannot // be produced through this fixture without bypassing the existing owner guard. @@ -446,13 +435,12 @@ private void assertSameNativeCandidateFinalizesCommitsReadsAndRecoversExactTimes .get(0, String.class); assertThatThrownBy(fixture::stopRuntime) .isInstanceOf(org.jooq.exception.DataAccessException.class) - .satisfies( - failure -> - assertGuardRefusal( - failure, - "23514", - "gs_binding_runtime_row_mutation_fenced", - "Game Instance runtime row is fenced by an unresolved lease-bound binding decision")); + .satisfies(failure -> + assertGuardRefusal( + failure, + "23514", + "gs_binding_runtime_row_mutation_fenced", + "Game Instance runtime row is fenced by an unresolved lease-bound binding decision")); assertThat( fixture .dsl() @@ -491,28 +479,26 @@ private void assertSameNativeCandidateFinalizesCommitsReadsAndRecoversExactTimes assertThat(committedIssuerObligation.localReleaseOperationId()).isNull(); assertThat(committedIssuerObligation.inventoryRevision()) .isEqualTo(committedInventory.inventoryRevision()); - assertThatThrownBy( - () -> - new CanonicalGameplayBindingIssuerIndexObligation( - committedIssuerObligation.transitionId(), - committedIssuerObligation.bindingRef(), - committedIssuerObligation.bindingGeneration(), - committedIssuerObligation.reservationId(), - CanonicalGameplayBindingIssuerIndexObligation.Status.ACKNOWLEDGED, - committedIssuerObligation.inventoryRevision(), - UUID.randomUUID())) + assertThatThrownBy(() -> + new CanonicalGameplayBindingIssuerIndexObligation( + committedIssuerObligation.transitionId(), + committedIssuerObligation.bindingRef(), + committedIssuerObligation.bindingGeneration(), + committedIssuerObligation.reservationId(), + CanonicalGameplayBindingIssuerIndexObligation.Status.ACKNOWLEDGED, + committedIssuerObligation.inventoryRevision(), + UUID.randomUUID())) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage("Issuer release linkage must match its obligation status"); - assertThatThrownBy( - () -> - new CanonicalGameplayBindingIssuerIndexObligation( - committedIssuerObligation.transitionId(), - committedIssuerObligation.bindingRef(), - committedIssuerObligation.bindingGeneration(), - committedIssuerObligation.reservationId(), - CanonicalGameplayBindingIssuerIndexObligation.Status.RELEASED, - committedIssuerObligation.inventoryRevision(), - null)) + assertThatThrownBy(() -> + new CanonicalGameplayBindingIssuerIndexObligation( + committedIssuerObligation.transitionId(), + committedIssuerObligation.bindingRef(), + committedIssuerObligation.bindingGeneration(), + committedIssuerObligation.reservationId(), + CanonicalGameplayBindingIssuerIndexObligation.Status.RELEASED, + committedIssuerObligation.inventoryRevision(), + null)) .isExactlyInstanceOf(IllegalArgumentException.class) .hasMessage("Issuer release linkage must match its obligation status"); var committedSource = inventory.readOriginalNewFinalAdmissionSource(decision); @@ -575,13 +561,12 @@ private void assertSameNativeCandidateFinalizesCommitsReadsAndRecoversExactTimes CanonicalGameplayIssuerCohortSql.cohortBindings( decision.candidate().issuerId(), revision)) .stream() - .filter( - row -> - "TRANSITION".equals(row.get("source_kind", String.class)) - && fixture - .transitionId() - .toString() - .equals(row.get("source_key", String.class))) + .filter(row -> + "TRANSITION".equals(row.get("source_kind", String.class)) + && fixture + .transitionId() + .toString() + .equals(row.get("source_key", String.class))) .findFirst() .orElseThrow(); var capturedTransition = @@ -618,97 +603,82 @@ private void assertSameNativeCandidateFinalizesCommitsReadsAndRecoversExactTimes fixture.transitionId()) .get(0, String.class)) .isEqualTo("ACKNOWLEDGED"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "UPDATE game_session_canonical_binding_issuer_index_obligation SET status = 'REQUIRED'" - + " WHERE transition_id = ?", - fixture.transitionId())) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "UPDATE game_session_canonical_binding_issuer_index_obligation SET status = 'REQUIRED'" + + " WHERE transition_id = ?", + fixture.transitionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) - .satisfies( - failure -> - assertGuardRefusal( - failure, - "23514", - "gs_original_new_issuer_obligation_retained", - "Final original NEW issuer acknowledgement is retained and immutable")); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "UPDATE game_session_canonical_issuer_binding_local_acknowledgement" - + " SET acknowledgement_generation = acknowledgement_generation + 1" - + " WHERE transition_id = ?", - fixture.transitionId())) + .satisfies(failure -> + assertGuardRefusal( + failure, + "23514", + "gs_original_new_issuer_obligation_retained", + "Final original NEW issuer acknowledgement is retained and immutable")); + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "UPDATE game_session_canonical_issuer_binding_local_acknowledgement" + + " SET acknowledgement_generation = acknowledgement_generation + 1" + + " WHERE transition_id = ?", + fixture.transitionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) - .satisfies( - failure -> - assertGuardRefusal( - failure, - "23514", - null, - "issuer binding-local acknowledgements are immutable")); + .satisfies(failure -> + assertGuardRefusal( + failure, "23514", null, "issuer binding-local acknowledgements are immutable")); assertThat(sqlImage()).isEqualTo(rows); // Once committed, the actual receipt and every original transition field remain immutable. - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "UPDATE game_session_canonical_binding_transition SET candidate_account_index_fence = ?" - + " WHERE transition_id = ?", - UUID.randomUUID(), - fixture.transitionId())) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "UPDATE game_session_canonical_binding_transition SET candidate_account_index_fence = ?" + + " WHERE transition_id = ?", + UUID.randomUUID(), + fixture.transitionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) - .satisfies( - failure -> - assertGuardRefusal( - failure, - "23514", - "gs_original_new_final_terminal_source_immutable", - "Committed original NEW final source is immutable")); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "UPDATE game_session_canonical_binding_transition SET original_new_final_session_sha256 = NULL," - + " original_new_admission_at_ms = NULL, original_new_continuity_expires_at_ms = NULL," - + " original_new_session_duration_ms = NULL WHERE transition_id = ?", - fixture.transitionId())) + .satisfies(failure -> + assertGuardRefusal( + failure, + "23514", + "gs_original_new_final_terminal_source_immutable", + "Committed original NEW final source is immutable")); + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "UPDATE game_session_canonical_binding_transition SET original_new_final_session_sha256 = NULL," + + " original_new_admission_at_ms = NULL, original_new_continuity_expires_at_ms = NULL," + + " original_new_session_duration_ms = NULL WHERE transition_id = ?", + fixture.transitionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) - .satisfies( - failure -> - assertGuardRefusal( - failure, - "23514", - "gs_original_new_final_terminal_source_immutable", - "Committed original NEW final source is immutable")); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "UPDATE game_session_canonical_binding_transition SET inventory_revision = inventory_revision - 1" - + " WHERE transition_id = ?", - fixture.transitionId())) + .satisfies(failure -> + assertGuardRefusal( + failure, + "23514", + "gs_original_new_final_terminal_source_immutable", + "Committed original NEW final source is immutable")); + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "UPDATE game_session_canonical_binding_transition SET inventory_revision = inventory_revision - 1" + + " WHERE transition_id = ?", + fixture.transitionId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) - .satisfies( - failure -> - assertGuardRefusal( - failure, - "23514", - "gs_original_new_final_terminal_source_immutable", - "Committed original NEW final source is immutable")); + .satisfies(failure -> + assertGuardRefusal( + failure, + "23514", + "gs_original_new_final_terminal_source_immutable", + "Committed original NEW final source is immutable")); assertThat(sqlImage()).isEqualTo(rows); Map physical = physicalImage(); - assertThatThrownBy( - () -> - reader() - .readActualOriginalFinalAdmission(credential.wrongTokenSelector(), "test")) + assertThatThrownBy(() -> + reader().readActualOriginalFinalAdmission(credential.wrongTokenSelector(), "test")) .isExactlyInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessage( "Finalized session authentication values differ from Account's original anchors"); @@ -783,11 +753,10 @@ void missingOrChangedIndexesAndBarriersNeverRecreateCommittedPostimagesOrExtendT issuerKey(issuerOpen))) { byte[] retained = admin.dump(ascii(key)); admin.del(ascii(key)); - assertThatThrownBy( - () -> - finalOwner() - .finalizeOriginalNewOnce( - committed, template, accountOpen, issuerOpen, deadline())) + assertThatThrownBy(() -> + finalOwner() + .finalizeOriginalNewOnce( + committed, template, accountOpen, issuerOpen, deadline())) .isExactlyInstanceOf(IllegalStateException.class) .hasMessage("Original NEW final admission Redis readback is unavailable"); assertThat(admin.exists(ascii(key))).isZero(); @@ -796,11 +765,10 @@ committed, template, accountOpen, issuerOpen, deadline())) admin.restore(ascii(key), 0L, retained); } admin.hset(ascii(accountOpen.key()), ascii("state"), ascii("CLOSED")); - assertThatThrownBy( - () -> - finalOwner() - .finalizeOriginalNewOnce( - committed, template, accountOpen, issuerOpen, deadline())) + assertThatThrownBy(() -> + finalOwner() + .finalizeOriginalNewOnce( + committed, template, accountOpen, issuerOpen, deadline())) .isExactlyInstanceOf(IllegalStateException.class) .hasMessage("Original NEW final admission Redis readback is unavailable"); assertThat(admin.hget(ascii(accountOpen.key()), ascii("state"))) @@ -808,11 +776,10 @@ committed, template, accountOpen, issuerOpen, deadline())) assertThat(admin.get(ascii(installation.sessionKey()))).containsExactly(finalBytes); assertThat(sqlImage()).isEqualTo(rows); admin.flushdb(); - assertThatThrownBy( - () -> - finalOwner() - .finalizeOriginalNewOnce( - committed, template, accountOpen, issuerOpen, deadline())) + assertThatThrownBy(() -> + finalOwner() + .finalizeOriginalNewOnce( + committed, template, accountOpen, issuerOpen, deadline())) .isExactlyInstanceOf(IllegalStateException.class) .hasMessage("Original NEW final admission Redis readback is unavailable"); assertThatThrownBy( @@ -846,11 +813,9 @@ void provisionalFinalCasRefusesMissingIndexesAndChangedBarriersWithoutAdmission( issuerKey(issuerOpen))) { byte[] retained = admin.dump(ascii(key)); admin.del(ascii(key)); - assertThatThrownBy( - () -> - finalOwner() - .finalizeOriginalNewOnce( - source, template, accountOpen, issuerOpen, deadline())) + assertThatThrownBy(() -> + finalOwner() + .finalizeOriginalNewOnce(source, template, accountOpen, issuerOpen, deadline())) .isExactlyInstanceOf(IllegalStateException.class) .hasMessage("Original NEW final admission Redis readback is unavailable"); assertThat(admin.exists(ascii(key))).isZero(); @@ -859,11 +824,9 @@ source, template, accountOpen, issuerOpen, deadline())) admin.restore(ascii(key), 0L, retained); } admin.hset(ascii(issuerKey(issuerOpen)), ascii("state"), ascii("CLOSED")); - assertThatThrownBy( - () -> - finalOwner() - .finalizeOriginalNewOnce( - source, template, accountOpen, issuerOpen, deadline())) + assertThatThrownBy(() -> + finalOwner() + .finalizeOriginalNewOnce(source, template, accountOpen, issuerOpen, deadline())) .isExactlyInstanceOf(IllegalStateException.class) .hasMessage("Original NEW final admission Redis readback is unavailable"); assertThat(admin.hget(ascii(issuerKey(issuerOpen)), ascii("state"))) @@ -902,36 +865,34 @@ void retainedRevisionAdvanceAcrossPhysicalReadIsUnavailableAndRetryCanRead() thr // Advance retained accounting only, through the installed PostgreSQL guards. The immutable // original candidate, receipt and persisted tag assignment retain their exact values. when(racingTags.assignmentForTransition(fixture.transitionId())) - .thenAnswer( - ignored -> { - fixture - .dsl() - .transaction( - configuration -> { - var tx = org.jooq.impl.DSL.using(configuration); - var revision = - tx.fetchSingle( - "UPDATE game_session_canonical_binding_inventory_clock" - + " SET inventory_revision = inventory_revision + 1" - + " WHERE singleton_id = 1 RETURNING inventory_revision") - .get(0, java.math.BigDecimal.class); - for (String table : - List.of( - "game_session_canonical_binding_transition", - "game_session_canonical_gameplay_binding_inventory", - "game_session_canonical_issuer_partition_reservation")) { - assertThat( - tx.execute( - "UPDATE " - + table - + " SET inventory_revision = ? WHERE transition_id = ?", - revision, - fixture.transitionId())) - .isEqualTo(1); - } - }); - return assignment; - }); + .thenAnswer(ignored -> { + fixture + .dsl() + .transaction(configuration -> { + var tx = org.jooq.impl.DSL.using(configuration); + var revision = + tx.fetchSingle( + "UPDATE game_session_canonical_binding_inventory_clock" + + " SET inventory_revision = inventory_revision + 1" + + " WHERE singleton_id = 1 RETURNING inventory_revision") + .get(0, java.math.BigDecimal.class); + for (String table : + List.of( + "game_session_canonical_binding_transition", + "game_session_canonical_gameplay_binding_inventory", + "game_session_canonical_issuer_partition_reservation")) { + assertThat( + tx.execute( + "UPDATE " + + table + + " SET inventory_revision = ? WHERE transition_id = ?", + revision, + fixture.transitionId())) + .isEqualTo(1); + } + }); + return assignment; + }); var racingReader = new CanonicalGameplayOriginalNewFinalAdmissionReadRepository( fixture.dsl(), ownerClient, racingTags, "test", CLOCK); @@ -980,11 +941,10 @@ void changedPersistedSessionCannotRecoverAgainstTheActualCommittedReceipt() thro net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( json.writeValueAsString(changed)); admin.set(ascii(installation.sessionKey()), changedBytes); - assertThatThrownBy( - () -> - finalOwner() - .finalizeOriginalNewOnce( - committed, template, accountOpen, issuerOpen, deadline())) + assertThatThrownBy(() -> + finalOwner() + .finalizeOriginalNewOnce( + committed, template, accountOpen, issuerOpen, deadline())) .isExactlyInstanceOf(IllegalStateException.class) .hasMessage("Original NEW final admission Redis readback is unavailable"); assertThatThrownBy( @@ -1004,16 +964,14 @@ committed, template, accountOpen, issuerOpen, deadline())) Map stoppedPhysical = physicalImage(); // Reuse the genuine final readback after COMMITTED: this retry has no physical SQL update // for the V1050 trigger to reject, so the Java runtime guard must refuse it explicitly. - assertThatThrownBy( - () -> - new CanonicalGameplayBindingInventoryRepository(fixture.dsl()) - .commitOriginalNewFinalAdmission(actual)) + assertThatThrownBy(() -> + new CanonicalGameplayBindingInventoryRepository(fixture.dsl()) + .commitOriginalNewFinalAdmission(actual)) .isExactlyInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessage("Original NEW final admission commit requires its current RUNNING runtime"); - assertThatThrownBy( - () -> - new CanonicalGameplayBindingInventoryRepository(fixture.dsl()) - .readOriginalNewFinalAdmissionSource(decision)) + assertThatThrownBy(() -> + new CanonicalGameplayBindingInventoryRepository(fixture.dsl()) + .readOriginalNewFinalAdmissionSource(decision)) .isExactlyInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessage("Original NEW final admission source requires its current RUNNING runtime"); assertThat(sqlImage()).isEqualTo(stoppedRows); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionTestFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionTestFixture.java index d699db6cf2..bd71f6d15a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionTestFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewFinalAdmissionTestFixture.java @@ -271,19 +271,18 @@ static final class ControlledRegionSources implements AutoCloseable { var worldSelector = publishedRelease.worldStartLocationEvidence(); var participants = publishedRelease.participantDigests().stream() - .map( - participant -> - new net.firedevops.firemud.common.gamedesign - .AuthoredWorldReleaseAttestationEvidence.Participant( - participant.participantKey(), - participant.scopeValue(), - false, - null, - participant.appliedCommitId(), - participant.contentDigest(), - participant.digestSchemaVersion(), - participant.abilitySchemaDigest() != null, - participant.abilitySchemaDigest())) + .map(participant -> + new net.firedevops.firemud.common.gamedesign + .AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + false, + null, + participant.appliedCommitId(), + participant.contentDigest(), + participant.digestSchemaVersion(), + participant.abilitySchemaDigest() != null, + participant.abilitySchemaDigest())) .toList(); var release = net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence.create( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java index 57c04df334..531351d2e7 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java @@ -298,10 +298,9 @@ void abandonedNeverDispatchedOriginalPreventsFreshInitialForLaterLogin() throws login.evidence().tokenJti(), login.evidence().tokenSha256(), later.requestId()); - assertThatThrownBy( - () -> - fixture.initialRepository.beginOrRead( - later, login, fixture.tenantId, fixture.namespaceId)) + assertThatThrownBy(() -> + fixture.initialRepository.beginOrRead( + later, login, fixture.tenantId, fixture.namespaceId)) .hasStackTraceContaining("uq_gs_initial_account_barrier_never_retarget"); } assertThat( @@ -552,10 +551,8 @@ void initialOpenReadbackExpiredDuringSqlLockWaitCannotCompleteOriginal(String he try (var executor = Executors.newSingleThreadExecutor()) { try { var acceptance = - executor.submit( - () -> - acceptanceRepository.acceptOpenReadback( - fixture.original.requestId(), readback)); + executor.submit(() -> + acceptanceRepository.acceptOpenReadback(fixture.original.requestId(), readback)); awaitInitialBackendBlockedBy(fixture.dsl, acceptancePid, holderPid); trustedMillis.set( Math.max( @@ -729,37 +726,31 @@ void verifiesOnlySignedExactCurrentTargetAndRejectsReplayAndMismatches() throws Mutation.WRONG_KEY_ID, Mutation.BAD_SIGNATURE)) { ControlledSigner invalid = new ControlledSigner(fixture.keyPair(), mutation, null); - assertThatThrownBy( - () -> - fixture - .receiver(invalid) - .observeForFenceTarget(fixture.intent().operationId(), 0L)) + assertThatThrownBy(() -> + fixture.receiver(invalid).observeForFenceTarget(fixture.intent().operationId(), 0L)) .isInstanceOf( CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); } - assertThatThrownBy( - () -> - fixture.receiver(null).observeForFenceTarget(fixture.intent().operationId(), 0L)) + assertThatThrownBy(() -> + fixture.receiver(null).observeForFenceTarget(fixture.intent().operationId(), 0L)) .isInstanceOf( CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); var missingPinnedKeys = fixture.configuration(Map.of(), fixture.expectedEvidence()); - assertThatThrownBy( - () -> - fixture - .receiver(channel, missingPinnedKeys) - .observeForFenceTarget(fixture.intent().operationId(), 0L)) + assertThatThrownBy(() -> + fixture + .receiver(channel, missingPinnedKeys) + .observeForFenceTarget(fixture.intent().operationId(), 0L)) .isInstanceOf( CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); - assertThatThrownBy( - () -> - fixture.configuration( - Map.of( - KEY_ID, - (java.security.interfaces.RSAPublicKey) fixture.keyPair().getPublic()), - null)) + assertThatThrownBy(() -> + fixture.configuration( + Map.of( + KEY_ID, + (java.security.interfaces.RSAPublicKey) fixture.keyPair().getPublic()), + null)) .isInstanceOf( CanonicalGameplayProtectedIncarnationReceiver.ObservationUnavailableException.class); } @@ -813,11 +804,8 @@ void changedCurrentSqlContextAfterSourceCallCannotProduceVerifiedEvidence() thro try (Fixture fixture = Fixture.open()) { ControlledSigner channel = new ControlledSigner(fixture.keyPair(), Mutation.NONE, fixture.dsl()); - assertThatThrownBy( - () -> - fixture - .receiver(channel) - .observeForFenceTarget(fixture.intent().operationId(), 0L)) + assertThatThrownBy(() -> + fixture.receiver(channel).observeForFenceTarget(fixture.intent().operationId(), 0L)) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); assertThat(channel.lastSigned()).isNotNull(); } @@ -852,11 +840,10 @@ void initialArmVerifiesExactOriginalAndNonzeroNoActiveEpochWithSameTrustedVerifi for (Mutation mutation : List.of(Mutation.WRONG_INITIAL_SOURCE_EPOCH, Mutation.WRONG_INITIAL_ATTEMPT)) { - assertThatThrownBy( - () -> - fixture - .receiver(new ControlledSigner(fixture.keyPair(), mutation, null)) - .observeForInitialAccountBarrier(fixture.original().requestId())) + assertThatThrownBy(() -> + fixture + .receiver(new ControlledSigner(fixture.keyPair(), mutation, null)) + .observeForInitialAccountBarrier(fixture.original().requestId())) .isInstanceOf( CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); } @@ -869,11 +856,10 @@ void changedNoActiveEpochAfterInitialObservationCannotProduceVerifiedEvidence() ControlledSigner channel = new ControlledSigner(fixture.keyPair(), Mutation.NONE, fixture.dsl()); - assertThatThrownBy( - () -> - fixture - .receiver(channel) - .observeForInitialAccountBarrier(fixture.original().requestId())) + assertThatThrownBy(() -> + fixture + .receiver(channel) + .observeForInitialAccountBarrier(fixture.original().requestId())) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); assertThat(channel.lastSigned()).isNotNull(); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java index bc22192ba2..b0b219a42e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionBindingBridgeRedisOwnerIntegrationTest.java @@ -154,23 +154,21 @@ void sameGrantAppliesAndReadsBackExactTypedEntityBindingThenPreservesForeignStat ascii(key), java.util.Map.of( ascii("session_id"), foreignSession, ascii("binding_generation"), ascii("2"))); - assertThatThrownBy( - () -> - owner.probeSessionBinding( - grant, - status, - actor.runtimeEntityId(), - SESSION_ID.toString(), - java.math.BigInteger.ONE)) + assertThatThrownBy(() -> + owner.probeSessionBinding( + grant, + status, + actor.runtimeEntityId(), + SESSION_ID.toString(), + java.math.BigInteger.ONE)) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - owner.applySessionBinding( - grant, - status, - actor.runtimeEntityId(), - SESSION_ID.toString(), - java.math.BigInteger.ONE)) + assertThatThrownBy(() -> + owner.applySessionBinding( + grant, + status, + actor.runtimeEntityId(), + SESSION_ID.toString(), + java.math.BigInteger.ONE)) .isInstanceOf(IllegalStateException.class); assertThat(redis.admin().hget(ascii(key), ascii("session_id"))) .containsExactly(foreignSession); @@ -197,27 +195,25 @@ void wrongOrMissingMetaAndExpiredLeaseFailWithoutCreatingBinding() throws Except byte[] leaseValue = redis.admin().get(leaseKey); redis.admin().del(ascii(meta)); - assertThatThrownBy( - () -> - owner.probeSessionBinding( - grant, - status, - actor.runtimeEntityId(), - SESSION_ID.toString(), - java.math.BigInteger.ONE)) + assertThatThrownBy(() -> + owner.probeSessionBinding( + grant, + status, + actor.runtimeEntityId(), + SESSION_ID.toString(), + java.math.BigInteger.ONE)) .isInstanceOf(IllegalStateException.class); assertThat(redis.admin().type(ascii(key))).isEqualTo("none"); seedMeta(redis.admin(), source, "1"); assertThat(redis.admin().hdel(ascii(meta), ascii("current_tick_id"))).isEqualTo(1L); - assertThatThrownBy( - () -> - owner.probeSessionBinding( - grant, - status, - actor.runtimeEntityId(), - SESSION_ID.toString(), - java.math.BigInteger.ONE)) + assertThatThrownBy(() -> + owner.probeSessionBinding( + grant, + status, + actor.runtimeEntityId(), + SESSION_ID.toString(), + java.math.BigInteger.ONE)) .isInstanceOf(IllegalStateException.class) .hasMessage("Canonical Game Session region lease is unavailable") .satisfies(failure -> assertThat(failure.getCause()).isNull()); @@ -229,27 +225,25 @@ void wrongOrMissingMetaAndExpiredLeaseFailWithoutCreatingBinding() throws Except seedMeta(redis.admin(), source, "1"); redis.admin().hset(ascii(meta), ascii("region_epoch"), ascii("2")); - assertThatThrownBy( - () -> - owner.probeSessionBinding( - grant, - status, - actor.runtimeEntityId(), - SESSION_ID.toString(), - java.math.BigInteger.ONE)) + assertThatThrownBy(() -> + owner.probeSessionBinding( + grant, + status, + actor.runtimeEntityId(), + SESSION_ID.toString(), + java.math.BigInteger.ONE)) .isInstanceOf(IllegalStateException.class); assertThat(redis.admin().type(ascii(key))).isEqualTo("none"); seedMeta(redis.admin(), source, "1"); redis.admin().pexpire(ascii(grant.key()), 0L); - assertThatThrownBy( - () -> - owner.probeSessionBinding( - grant, - status, - actor.runtimeEntityId(), - SESSION_ID.toString(), - java.math.BigInteger.ONE)) + assertThatThrownBy(() -> + owner.probeSessionBinding( + grant, + status, + actor.runtimeEntityId(), + SESSION_ID.toString(), + java.math.BigInteger.ONE)) .isInstanceOf(IllegalStateException.class); assertThat(redis.admin().type(ascii(key))).isEqualTo("none"); } @@ -290,14 +284,13 @@ void bridgesTickZeroButRejectsExpiringMetaBeforeReadback() throws Exception { .containsExactly(ascii(SESSION_ID.toString())); assertThat(redis.admin().pexpire(ascii(meta), 60_000L)).isTrue(); - assertThatThrownBy( - () -> - owner.readBackSessionBinding( - grant, - status, - actor.runtimeEntityId(), - SESSION_ID.toString(), - java.math.BigInteger.ONE)) + assertThatThrownBy(() -> + owner.readBackSessionBinding( + grant, + status, + actor.runtimeEntityId(), + SESSION_ID.toString(), + java.math.BigInteger.ONE)) .isInstanceOf(IllegalStateException.class); } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java index 9da9907574..602ce87a68 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseOwnerIntegrationTest.java @@ -240,9 +240,8 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws world, "unavailable-incarnation", CanonicalGameplayRegionIncarnationSource.unavailable()); - assertThatThrownBy( - () -> - unavailableIncarnationOwner.installForTransition(TRANSITION_ID, world.request())) + assertThatThrownBy(() -> + unavailableIncarnationOwner.installForTransition(TRANSITION_ID, world.request())) .isInstanceOf(IllegalStateException.class); assertThat(redis.admin().type(redisKey)).isEqualTo("none"); assertThat(statusRepository.find(qualifiedSource)).isEmpty(); @@ -305,10 +304,8 @@ void composesLeaseInstallRevalidationHandoffAndFailClosedSourceChanges() throws var preparation = statusRepository.findTimelinePreparation(qualifiedSource).orElseThrow(); byte[] initialLeaseValue = redis.admin().get(redisKey); assertThat(redis.admin().hdel(ascii(initialMetaKey), ascii("current_tick_id"))).isEqualTo(1L); - assertThatThrownBy( - () -> - initializeTimelineWithoutCreationPermission( - redisOwner, preparation, "instance-a")) + assertThatThrownBy(() -> + initializeTimelineWithoutCreationPermission(redisOwner, preparation, "instance-a")) .isInstanceOf(IllegalStateException.class) .hasMessage("Canonical Game Session region lease is unavailable") .satisfies(failure -> assertThat(failure.getCause()).isNull()); @@ -647,10 +644,8 @@ void timelinePreflightFailuresLeavePreparedPermissionAndAllowLaterFirstClaim() t world, "preclaim-dependency-drift", incarnationSource); - assertThatThrownBy( - () -> - preClaimDependencyFailureOwner.installForTransition( - TRANSITION_ID, world.request())) + assertThatThrownBy(() -> + preClaimDependencyFailureOwner.installForTransition(TRANSITION_ID, world.request())) .isInstanceOf(IllegalStateException.class); assertPreparedTimelineUnchanged( testSchema.dsl(), statusRepository, redis, source, preparation); @@ -1258,28 +1253,26 @@ void createdOriginNativeBridgeRetainsOriginalPurposeAndRejectsSourceSubstitution .setPlayerCreatedOrigin( origin.toBuilder().setMutationDigest("4".repeat(64))) .build(); - assertThatThrownBy( - () -> - binding - .owner() - .installForTransition( - binding.installation(), - binding.acknowledgement().obligation().transitionId(), - changed)) + assertThatThrownBy(() -> + binding + .owner() + .installForTransition( + binding.installation(), + binding.acknowledgement().obligation().transitionId(), + changed)) .isInstanceOfAny(IllegalArgumentException.class, IllegalStateException.class); var substituted = request.toBuilder() .setAssignmentUuid(origin.getCreationOperationUuid()) .setAssignmentIntentDigest(origin.getMutationDigest()) .build(); - assertThatThrownBy( - () -> - binding - .owner() - .installForTransition( - binding.installation(), - binding.acknowledgement().obligation().transitionId(), - substituted)) + assertThatThrownBy(() -> + binding + .owner() + .installForTransition( + binding.installation(), + binding.acknowledgement().obligation().transitionId(), + substituted)) .isInstanceOfAny(IllegalArgumentException.class, IllegalStateException.class); var unknownOrigin = origin.toBuilder() @@ -1293,14 +1286,13 @@ void createdOriginNativeBridgeRetainsOriginalPurposeAndRejectsSourceSubstitution .build()) .build(); var extended = request.toBuilder().setPlayerCreatedOrigin(unknownOrigin).build(); - assertThatThrownBy( - () -> - binding - .owner() - .installForTransition( - binding.installation(), - binding.acknowledgement().obligation().transitionId(), - extended)) + assertThatThrownBy(() -> + binding + .owner() + .installForTransition( + binding.installation(), + binding.acknowledgement().obligation().transitionId(), + extended)) .isInstanceOfAny(IllegalArgumentException.class, IllegalStateException.class); // Still structurally valid authenticated response, but no longer the original // projection. @@ -1939,15 +1931,14 @@ private WorldFixture( this.initialClient = mock(CanonicalInitialPlayerLocationClient.class); this.lifecycleClient = mock(WorldCanonicalInstanceLifecycleClient.class); when(initialClient.readInitialPlayerLocationRegion(request)) - .thenAnswer( - invocation -> { - int read = reads.incrementAndGet(); - if (read == replaceOnRead) current.set(replacement); - CanonicalInitialPlayerLocationRegionResponse response = - regionResponse(request, current.get()); - if (read == callbackOnRead) afterRead.run(); - return response; - }); + .thenAnswer(invocation -> { + int read = reads.incrementAndGet(); + if (read == replaceOnRead) current.set(replacement); + CanonicalInitialPlayerLocationRegionResponse response = + regionResponse(request, current.get()); + if (read == callbackOnRead) afterRead.run(); + return response; + }); when(lifecycleClient.read(original.request())).thenAnswer(invocation -> current.get()); this.resolver = new CanonicalInitialPlayerLocationRegionResolver( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java index e00b83e6dc..8a07423ff3 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionLeaseRedisOwnerIntegrationTest.java @@ -143,10 +143,8 @@ void missingCurrentTickIdMakesLeaseAcquireReadAndRenewStaleWithoutChangingLeaseO assertThat(redis.admin().hdel(metaKey, ascii("current_tick_id"))).isEqualTo(1L); long ttlBeforeRejectedRenewal = redis.admin().pttl(leaseKey); - assertThatThrownBy( - () -> - owner.acquire( - source, 7L, Duration.ofMinutes(2), identity("after-missing-tick-id"))) + assertThatThrownBy(() -> + owner.acquire(source, 7L, Duration.ofMinutes(2), identity("after-missing-tick-id"))) .isInstanceOf(IllegalStateException.class) .hasMessage("Canonical Game Session region lease is unavailable") .satisfies(failure -> assertThat(failure.getCause()).isNull()); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java index d3be153112..e477edbf05 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionOwnerCompositionFixture.java @@ -338,53 +338,52 @@ static UUID installHistoricalMaterializedRequiredBridge( metaDigest, java.sql.Timestamp.from(now), initializationId)); - dsl.transaction( - configuration -> { - var transaction = DSL.using(configuration); - BigInteger revision = - CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); - BigInteger next = revision.add(BigInteger.ONE); - BigInteger prior = evidence.transition().inventoryRevision(); - historicalWriteRegionRevisionRows(transaction, evidence, prior, next); - historicalRequireOne( - transaction.execute( - """ - UPDATE game_session_canonical_binding_region_bridge_obligation - SET bridge_operation_id = ?, bridge_preimage_state = 'ABSENT', runtime_entity_id = ?, - entity_projection_generation = ?, entity_projection_fence = ?, entity_workload_namespace = ?, - assignment_uuid = ?, assignment_intent_digest = ?, entity_reference_digest = ?, - world_source_digest = ?, canonical_region_id = ?, world_lifecycle_epoch = ?, - world_lifecycle_row_version = ?, world_capture_id = ?, world_graph_sha256 = ?, - world_preparation_input_digest = ?, executor_fence = ?, lease_token_correlation = ?, inventory_revision = ? - WHERE transition_id = ? AND bridge_operation_id IS NULL AND inventory_revision = ? - """, - UUID.randomUUID(), - reference.runtimeEntityId().value(), - reference.projectionGeneration(), - reference.projectionFence(), - reference.workloadNamespace(), - UUID.fromString(worldRequest.getAssignmentUuid()), - worldRequest.getAssignmentIntentDigest(), - parentEntityReferenceDigest, - worldDigest, - source.canonicalRegionId(), - source.lifecycleEpoch(), - source.lifecycleRowVersion(), - source.captureId(), - source.graphSha256(), - source.preparationInputDigest(), - new BigDecimal(status.executorFence()), - grantCorrelation, - new BigDecimal(next), - transitionId, - new BigDecimal(prior))); - historicalRequireOne( - transaction.execute( - "UPDATE game_session_canonical_binding_inventory_clock SET inventory_revision = ?" - + " WHERE singleton_id = 1 AND inventory_revision = ?", - new BigDecimal(next), - new BigDecimal(revision))); - }); + dsl.transaction(configuration -> { + var transaction = DSL.using(configuration); + BigInteger revision = + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + BigInteger next = revision.add(BigInteger.ONE); + BigInteger prior = evidence.transition().inventoryRevision(); + historicalWriteRegionRevisionRows(transaction, evidence, prior, next); + historicalRequireOne( + transaction.execute( + """ + UPDATE game_session_canonical_binding_region_bridge_obligation + SET bridge_operation_id = ?, bridge_preimage_state = 'ABSENT', runtime_entity_id = ?, + entity_projection_generation = ?, entity_projection_fence = ?, entity_workload_namespace = ?, + assignment_uuid = ?, assignment_intent_digest = ?, entity_reference_digest = ?, + world_source_digest = ?, canonical_region_id = ?, world_lifecycle_epoch = ?, + world_lifecycle_row_version = ?, world_capture_id = ?, world_graph_sha256 = ?, + world_preparation_input_digest = ?, executor_fence = ?, lease_token_correlation = ?, inventory_revision = ? + WHERE transition_id = ? AND bridge_operation_id IS NULL AND inventory_revision = ? + """, + UUID.randomUUID(), + reference.runtimeEntityId().value(), + reference.projectionGeneration(), + reference.projectionFence(), + reference.workloadNamespace(), + UUID.fromString(worldRequest.getAssignmentUuid()), + worldRequest.getAssignmentIntentDigest(), + parentEntityReferenceDigest, + worldDigest, + source.canonicalRegionId(), + source.lifecycleEpoch(), + source.lifecycleRowVersion(), + source.captureId(), + source.graphSha256(), + source.preparationInputDigest(), + new BigDecimal(status.executorFence()), + grantCorrelation, + new BigDecimal(next), + transitionId, + new BigDecimal(prior))); + historicalRequireOne( + transaction.execute( + "UPDATE game_session_canonical_binding_inventory_clock SET inventory_revision = ?" + + " WHERE singleton_id = 1 AND inventory_revision = ?", + new BigDecimal(next), + new BigDecimal(revision))); + }); return transitionId; } @@ -1283,10 +1282,9 @@ private static TwoBindingProof installAndBridgeInternal( Arrays.stream(firstTimelineBefore.fields()) .map(field -> field.getName()) .filter(column -> !refreshedPreparationColumns.contains(column)) - .filter( - column -> - !Objects.deepEquals( - firstTimelineBefore.get(column), firstTimelineAfter.get(column))) + .filter(column -> + !Objects.deepEquals( + firstTimelineBefore.get(column), firstTimelineAfter.get(column))) .toList(); boolean preparationGrantMatchesCurrent = Objects.equals( @@ -1605,10 +1603,9 @@ private static void requireMaterializedBridgeCaptured(DSLContext dsl, UUID trans CanonicalGameplayIssuerCohortSql.cohortBindings( GameSessionAccountDelegationProfile.ISSUER, revision)) .stream() - .filter( - row -> - "REGION_OBLIGATION".equals(row.get("source_kind", String.class)) - && transitionId.toString().equals(row.get("source_key", String.class))) + .filter(row -> + "REGION_OBLIGATION".equals(row.get("source_kind", String.class)) + && transitionId.toString().equals(row.get("source_key", String.class))) .toList(); if (captured.size() != 1 || !Objects.equals(exactRow, captured.getFirst().get("source_row_json", String.class))) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java index f066e1a453..edf692a556 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRuntimeStatusRepositoryIntegrationTest.java @@ -85,16 +85,15 @@ void clearOwnerRows() { @Test void initializesOnlyAnAbsentRegionAtItsFirstEpochAndFirstTick() { - assertThatThrownBy( - () -> - repository.installOwner( - source, - 2L, - null, - FIRST_LEASE_CORRELATION, - "game-session-service", - "instance-a", - Instant.parse("2026-10-26T00:00:00Z"))) + assertThatThrownBy(() -> + repository.installOwner( + source, + 2L, + null, + FIRST_LEASE_CORRELATION, + "game-session-service", + "instance-a", + Instant.parse("2026-10-26T00:00:00Z"))) .isInstanceOf(IllegalStateException.class); assertThat(repository.find(source)).isEmpty(); @@ -179,16 +178,15 @@ void exactOwnerRetryReplacesFenceWithoutResettingRegionTimeline() { assertThat(retry.ownerInstanceId()).isEqualTo("instance-b"); assertThat(retry.lastCommittedTickId()).isEqualTo(7L); assertThat(retry.lastCommittedTickBatchId()).isEqualTo("batch-7"); - assertThatThrownBy( - () -> - repository.installOwner( - source, - 1L, - initial, - FIRST_LEASE_CORRELATION, - "game-session-service", - "instance-a", - Instant.parse("2026-10-26T00:00:03Z"))) + assertThatThrownBy(() -> + repository.installOwner( + source, + 1L, + initial, + FIRST_LEASE_CORRELATION, + "game-session-service", + "instance-a", + Instant.parse("2026-10-26T00:00:03Z"))) .isInstanceOf(IllegalStateException.class); assertThat(repository.find(source)).contains(retry); } @@ -204,10 +202,9 @@ void sameNaturalScopeRejectsChangedWorldCaptureEvidence() { "instance-a", Instant.parse("2026-10-26T00:00:01Z")); - assertThatThrownBy( - () -> - repository.find( - source(GAME_INSTANCE_ID, new UUID(0x6666666666666666L, 0x8666666666666666L)))) + assertThatThrownBy(() -> + repository.find( + source(GAME_INSTANCE_ID, new UUID(0x6666666666666666L, 0x8666666666666666L)))) .isInstanceOf(IllegalStateException.class); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java index 08e7c5296e..e03d032b7c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRosterReferencePostgresIntegrationTest.java @@ -147,46 +147,44 @@ void recoverySchedulingMigrationPreservesRetainedRowsAndRetriesPendingMarkers() var createdPendingFixture = createdFixture(true); var createdTerminal = createdTerminalFixture.original(); var createdPending = createdPendingFixture.original(); - upgradeTransaction.executeWithoutResult( - ignored -> { - upgradeRepository.begin(ordinaryTerminal); - upgradeRepository.completeUnissuedDenied(ordinaryTerminal); - for (var original : List.of(recoveredTerminal, pendingRecovery)) { - upgradeRepository.begin(original); - upgradeRepository.reserveSelectionInput(original, selectionInput()); - upgradeRepository.markRosterReadStarted(original); - } - for (var fixture : List.of(createdTerminalFixture, createdPendingFixture)) { - var original = fixture.original(); - upgradeRepository.begin(original); - upgradeRepository.reserveSelectionInput(original, selectionInput()); - upgradeRepository.markRosterReadStarted(original); - upgradeRepository.recordPlayerCreated(original, fixture.roster()); - upgradeRepository.selectOriginal( - original, UUID.fromString(fixture.selected().getSelectedCharacterUuid())); - upgradeRepository.recordSelectedPlayerCreatedCharacter(original, fixture.selected()); - } - }); + upgradeTransaction.executeWithoutResult(ignored -> { + upgradeRepository.begin(ordinaryTerminal); + upgradeRepository.completeUnissuedDenied(ordinaryTerminal); + for (var original : List.of(recoveredTerminal, pendingRecovery)) { + upgradeRepository.begin(original); + upgradeRepository.reserveSelectionInput(original, selectionInput()); + upgradeRepository.markRosterReadStarted(original); + } + for (var fixture : List.of(createdTerminalFixture, createdPendingFixture)) { + var original = fixture.original(); + upgradeRepository.begin(original); + upgradeRepository.reserveSelectionInput(original, selectionInput()); + upgradeRepository.markRosterReadStarted(original); + upgradeRepository.recordPlayerCreated(original, fixture.roster()); + upgradeRepository.selectOriginal( + original, UUID.fromString(fixture.selected().getSelectedCharacterUuid())); + upgradeRepository.recordSelectedPlayerCreatedCharacter(original, fixture.selected()); + } + }); Thread.sleep(10L); var terminalRecoveryUuid = UUID.randomUUID(); var pendingRecoveryUuid = UUID.randomUUID(); var createdTerminalRecoveryUuid = UUID.randomUUID(); var createdPendingRecoveryUuid = UUID.randomUUID(); - upgradeTransaction.executeWithoutResult( - ignored -> { - for (var entry : - List.of( - Map.entry(recoveredTerminal, terminalRecoveryUuid), - Map.entry(pendingRecovery, pendingRecoveryUuid), - Map.entry(createdTerminal, createdTerminalRecoveryUuid), - Map.entry(createdPending, createdPendingRecoveryUuid))) { - upgradeDsl.execute( - "UPDATE game_session_canonical_roster_selection SET recovery_uuid = ?, recovery_started_at = clock_timestamp() WHERE operation_uuid = ?", - entry.getValue(), - UUID.fromString(entry.getKey().getOperationUuid())); - } - }); + upgradeTransaction.executeWithoutResult(ignored -> { + for (var entry : + List.of( + Map.entry(recoveredTerminal, terminalRecoveryUuid), + Map.entry(pendingRecovery, pendingRecoveryUuid), + Map.entry(createdTerminal, createdTerminalRecoveryUuid), + Map.entry(createdPending, createdPendingRecoveryUuid))) { + upgradeDsl.execute( + "UPDATE game_session_canonical_roster_selection SET recovery_uuid = ?, recovery_started_at = clock_timestamp() WHERE operation_uuid = ?", + entry.getValue(), + UUID.fromString(entry.getKey().getOperationUuid())); + } + }); var recoveryRequest = CanonicalGameplayRosterRecoveryEvidence.requireRequest( CanonicalGameplayRosterRecoveryRequest.newBuilder() @@ -202,10 +200,9 @@ void recoverySchedulingMigrationPreservesRetainedRowsAndRetriesPendingMarkers() originalRecord.getOwnerFence(), UUID.fromString(originalRecord.getTargetFenceUuid()), null); - upgradeTransaction.executeWithoutResult( - ignored -> - upgradeRepository.finishRecovery( - verifiedRecovery(recoveryRequest, terminalRecoveryResponse))); + upgradeTransaction.executeWithoutResult(ignored -> + upgradeRepository.finishRecovery( + verifiedRecovery(recoveryRequest, terminalRecoveryResponse))); var createdRecoveryRequest = CanonicalGameplayRosterRecoveryEvidence.requireRequest( @@ -222,10 +219,9 @@ void recoverySchedulingMigrationPreservesRetainedRowsAndRetriesPendingMarkers() createdTerminalRecord.getOwnerFence(), UUID.fromString(createdTerminalRecord.getTargetFenceUuid()), createdTerminalFixture.roster()); - upgradeTransaction.executeWithoutResult( - ignored -> - upgradeRepository.finishRecovery( - verifiedRecovery(createdRecoveryRequest, createdRecoveryResponse))); + upgradeTransaction.executeWithoutResult(ignored -> + upgradeRepository.finishRecovery( + verifiedRecovery(createdRecoveryRequest, createdRecoveryResponse))); var retainedOrdinaryTerminal = upgradeRow(upgradeDsl, ordinaryTerminal); var retainedRecoveredTerminal = upgradeRow(upgradeDsl, recoveredTerminal); @@ -335,17 +331,15 @@ void recoverySchedulingMigrationPreservesRetainedRowsAndRetriesPendingMarkers() // A retained future scheduling value must advance strictly when its pending retry is // selected. - upgradeTransaction.executeWithoutResult( - ignored -> - upgradeDsl.execute( - "UPDATE game_session_canonical_roster_selection SET recovery_last_attempt_at = clock_timestamp() + interval '1 day' WHERE operation_uuid = ?", - UUID.fromString(pendingRecovery.getOperationUuid()))); + upgradeTransaction.executeWithoutResult(ignored -> + upgradeDsl.execute( + "UPDATE game_session_canonical_roster_selection SET recovery_last_attempt_at = clock_timestamp() + interval '1 day' WHERE operation_uuid = ?", + UUID.fromString(pendingRecovery.getOperationUuid()))); String futureAttempt = upgradeRowValue(upgradeDsl, pendingRecovery, "recovery_last_attempt_at", String.class); var retryPage = - upgradeTransaction.execute( - ignored -> - upgradeRepository.beginRecoveries(pendingRecovery, current(pendingRecovery))); + upgradeTransaction.execute(ignored -> + upgradeRepository.beginRecoveries(pendingRecovery, current(pendingRecovery))); assertThat(retryPage).hasSize(1); assertThat(retryPage.get(0).getRecoveryUuid()).isEqualTo(pendingRecoveryUuid.toString()); assertThat(upgradeRowValue(upgradeDsl, pendingRecovery, "recovery_uuid", String.class)) @@ -364,9 +358,8 @@ void recoverySchedulingMigrationPreservesRetainedRowsAndRetriesPendingMarkers() String createdPendingBeforeAttempt = upgradePredecessorColumns(upgradeDsl, createdPending); var createdRetryPage = - upgradeTransaction.execute( - ignored -> - upgradeRepository.beginRecoveries(createdPending, current(createdPending))); + upgradeTransaction.execute(ignored -> + upgradeRepository.beginRecoveries(createdPending, current(createdPending))); assertThat(createdRetryPage).hasSize(1); assertThat(createdRetryPage.getFirst().getRecoveryUuid()) .isEqualTo(createdPendingRecoveryUuid.toString()); @@ -381,13 +374,12 @@ void recoverySchedulingMigrationPreservesRetainedRowsAndRetriesPendingMarkers() "recovery_last_attempt_at = NULL", "recovery_last_attempt_at = recovery_last_attempt_at - interval '1 millisecond'", "recovery_last_attempt_at = recovery_last_attempt_at + interval '1 millisecond', original_request = decode('01', 'hex')")) { - assertThatThrownBy( - () -> - upgradeDsl.execute( - "UPDATE game_session_canonical_roster_selection SET " - + change - + " WHERE operation_uuid = ?", - UUID.fromString(createdPending.getOperationUuid()))) + assertThatThrownBy(() -> + upgradeDsl.execute( + "UPDATE game_session_canonical_roster_selection SET " + + change + + " WHERE operation_uuid = ?", + UUID.fromString(createdPending.getOperationUuid()))) .isInstanceOf(DataAccessException.class); } assertThat(upgradePredecessorRow(upgradeDsl, createdPending)) @@ -401,12 +393,11 @@ void recoverySchedulingMigrationPreservesRetainedRowsAndRetriesPendingMarkers() createdPendingFixture.selected().getTerminal().toBuilder() .setTerminalId(UUID.randomUUID().toString())) .build(); - assertThatThrownBy( - () -> - upgradeDsl.execute( - "UPDATE game_session_canonical_roster_selection SET canonical_selected_player_created_character_receipt = ? WHERE operation_uuid = ?", - alteredSelectedReceipt.toByteArray(), - UUID.fromString(createdPending.getOperationUuid()))) + assertThatThrownBy(() -> + upgradeDsl.execute( + "UPDATE game_session_canonical_roster_selection SET canonical_selected_player_created_character_receipt = ? WHERE operation_uuid = ?", + alteredSelectedReceipt.toByteArray(), + UUID.fromString(createdPending.getOperationUuid()))) .isInstanceOf(DataAccessException.class); assertThat(upgradePredecessorRow(upgradeDsl, createdPending)) .isEqualTo(createdPendingAfterAttempt); @@ -450,25 +441,17 @@ void originalIntentAndReceiptReplayWithoutMutationAndRemainProtected() { execute(ignored -> repository.record(request, receipt))) .isEqualTo(recorded); assertThat(retainedRow(request)).isEqualTo(retained); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> - repository.begin( - request.toBuilder() - .setSessionUuid(UUID.randomUUID().toString()) - .build()))) + assertThatThrownBy(() -> + transaction.execute(ignored -> + repository.begin( + request.toBuilder().setSessionUuid(UUID.randomUUID().toString()).build()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("CONFLICT"); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> - repository.record( - request, - receipt.toBuilder() - .setSnapshotUuid(UUID.randomUUID().toString()) - .build()))) + assertThatThrownBy(() -> + transaction.execute(ignored -> + repository.record( + request, + receipt.toBuilder().setSnapshotUuid(UUID.randomUUID().toString()).build()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("CONFLICT"); assertThatThrownBy(() -> dsl.execute("DELETE FROM game_session_canonical_roster_selection")) @@ -520,10 +503,8 @@ void terminalOriginalCannotBeMarkedAsRosterReadStarted() { assertThat(retainedLifecycle.get("roster_read_started", Boolean.class)).isFalse(); assertThat(retainedLifecycle.get("terminal_outcome", String.class)).isEqualTo("DENIED"); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> repository.markRosterReadStarted(request))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> repository.markRosterReadStarted(request))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_ORIGINAL_DEREFERENCE_CLOSED"); @@ -552,10 +533,8 @@ void rosterReadCannotStartBeforeSelectionInputIsDurablyReserved() { assertThat(retainedDispatchState.get("has_selection_input", Boolean.class)).isFalse(); assertThat(retainedDispatchState.get("roster_read_started", Boolean.class)).isFalse(); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> repository.markRosterReadStarted(request))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> repository.markRosterReadStarted(request))) .isInstanceOf(IllegalStateException.class) .hasMessage("CANONICAL_ROSTER_SELECTION_INPUT_UNAVAILABLE"); @@ -569,11 +548,10 @@ void rosterReadCannotStartBeforeSelectionInputIsDurablyReserved() { .formatJSON()) .isEqualTo(retainedDispatchState.formatJSON()); - transaction.executeWithoutResult( - ignored -> { - repository.reserveSelectionInput(request, selectionInput()); - repository.markRosterReadStarted(request); - }); + transaction.executeWithoutResult(ignored -> { + repository.reserveSelectionInput(request, selectionInput()); + repository.markRosterReadStarted(request); + }); var dispatchedState = dsl.fetchSingle( "SELECT selection_input IS NOT NULL AS has_selection_input, roster_read_started " @@ -588,18 +566,16 @@ void existingTargetFenceKeepsItsConfiguredHorizonsAfterPolicyChanges() throws Ex var originalPolicy = policy(50L, 20L, 25L); repository = repository(originalPolicy); var request = request(); - transaction.executeWithoutResult( - ignored -> { - repository.begin(request); - repository.reserveSelectionInput( - request, - net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput - .newBuilder() - .setSchemaVersion(1) - .build()); - repository.completeSelection( - request, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.DENIED); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(request); + repository.reserveSelectionInput( + request, + net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput.newBuilder() + .setSchemaVersion(1) + .build()); + repository.completeSelection( + request, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.DENIED); + }); Thread.sleep(80L); var changedPolicy = policy(2_000L, 1_000L, 1_500L); @@ -635,11 +611,10 @@ void selectionInputChosenActorAndAssignmentResultCannotChangeWithinOriginalOpera .setMenuSnapshotUuid(menu.toString()) .setMenuSnapshotDigest("d".repeat(64)) .build(); - transaction.executeWithoutResult( - ignored -> { - repository.begin(request); - repository.reserveSelectionInput(request, input); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(request); + repository.reserveSelectionInput(request, input); + }); var roster = receipt(request).toBuilder() .setSnapshotUuid(menu.toString()) @@ -659,19 +634,15 @@ void selectionInputChosenActorAndAssignmentResultCannotChangeWithinOriginalOpera .CANONICAL_ROSTER_ACTOR_KIND_PLAYER)) .build(); transaction.executeWithoutResult(ignored -> repository.record(request, roster)); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.reserveSelectionInput( - request, input.toBuilder().setSelector("2").build()))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + repository.reserveSelectionInput( + request, input.toBuilder().setSelector("2").build()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("CONFLICT"); transaction.executeWithoutResult(ignored -> repository.selectOriginal(request, first)); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> repository.selectOriginal(request, second))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> repository.selectOriginal(request, second))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("CONFLICT"); var assignment = @@ -692,26 +663,23 @@ void selectionInputChosenActorAndAssignmentResultCannotChangeWithinOriginalOpera transaction.executeWithoutResult( ignored -> repository.recordSelectedAssignment(request, assignment)); var retained = retainedRow(request); - transaction.executeWithoutResult( - ignored -> { - repository.reserveSelectionInput(request, input); - repository.selectOriginal(request, first); - repository.recordSelectedAssignment(request, assignment); - }); + transaction.executeWithoutResult(ignored -> { + repository.reserveSelectionInput(request, input); + repository.selectOriginal(request, first); + repository.recordSelectedAssignment(request, assignment); + }); assertThat(retainedRow(request)).isEqualTo(retained); assertThat( CanonicalGameplayRosterReferenceEvidence.selectedAssignmentReceipt( repository.read(request))) .isEqualTo(assignment); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.recordSelectedAssignment( - request, - assignment.toBuilder() - .setAssignmentUuid(UUID.randomUUID().toString()) - .build()))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + repository.recordSelectedAssignment( + request, + assignment.toBuilder() + .setAssignmentUuid(UUID.randomUUID().toString()) + .build()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("CONFLICT"); } @@ -772,13 +740,12 @@ void actualOutcomeAndIndependentCurrentOwnerSupersessionSealEveryOriginalAtOneTa net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput.newBuilder() .setSchemaVersion(1) .build(); - transaction.executeWithoutResult( - ignored -> { - repository.begin(request); - repository.reserveSelectionInput(request, input); - repository.markRosterReadStarted(request); - repository.record(request, receipt(request)); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(request); + repository.reserveSelectionInput(request, input); + repository.markRosterReadStarted(request); + repository.record(request, receipt(request)); + }); var routeReader = org.mockito.Mockito.mock( net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService.class); @@ -787,14 +754,13 @@ void actualOutcomeAndIndependentCurrentOwnerSupersessionSealEveryOriginalAtOneTa routeReader.readCurrentTarget( UUID.fromString( CanonicalGameplayRosterReferenceEvidence.target(request).getTenantUuid()))) - .thenAnswer( - call -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - return current; - }); + .thenAnswer(call -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + return current; + }); // Controlled admission source here; the existing admission-owner integration fixture separately // exercises the real committed reader and actual pointer/attempt/catalog row locks. var admissions = org.mockito.Mockito.mock(CanonicalInitialAdmissionRepository.class); @@ -802,23 +768,21 @@ void actualOutcomeAndIndependentCurrentOwnerSupersessionSealEveryOriginalAtOneTa org.mockito.Mockito.when( admissions.readCurrentOpenSnapshotForRealm( request.getTargetNamespace(), current.canonicalTenantId(), current.realmId())) - .thenAnswer( - call -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - return snapshot; - }); + .thenAnswer(call -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + return snapshot; + }); org.mockito.Mockito.when(admissions.lockExactCurrentOpenSnapshot(snapshot)) - .thenAnswer( - call -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isTrue(); - return snapshot; - }); + .thenAnswer(call -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isTrue(); + return snapshot; + }); var owner = new net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferenceOwner( repository, @@ -850,10 +814,9 @@ void actualOutcomeAndIndependentCurrentOwnerSupersessionSealEveryOriginalAtOneTa admissions.readCurrentOpenSnapshotForRealm( request.getTargetNamespace(), current.canonicalTenantId(), current.realmId())) .thenReturn(snapshot); - transaction.executeWithoutResult( - ignored -> - repository.completeSelection( - request, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.DENIED)); + transaction.executeWithoutResult(ignored -> + repository.completeSelection( + request, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.DENIED)); Thread.sleep(5L); org.mockito.Mockito.doThrow( new CanonicalInitialAdmissionRepository @@ -883,10 +846,8 @@ void actualOutcomeAndIndependentCurrentOwnerSupersessionSealEveryOriginalAtOneTa var newOriginal = request.toBuilder().setOperationUuid(UUID.randomUUID().toString()).build(); assertThatThrownBy(() -> transaction.execute(ignored -> repository.begin(newOriginal))) .hasMessageContaining("RETIRED"); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> repository.markRosterReadStarted(request))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> repository.markRosterReadStarted(request))) .hasMessageContaining("RETIRED"); } @@ -897,14 +858,13 @@ void newAndRecoveredReferencesSerializeAgainstRetirementOnTheSameTargetFence() t net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput.newBuilder() .setSchemaVersion(1) .build(); - transaction.executeWithoutResult( - ignored -> { - repository.begin(request); - repository.reserveSelectionInput(request, input); - repository.record(request, receipt(request)); - repository.completeSelection( - request, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.DENIED); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(request); + repository.reserveSelectionInput(request, input); + repository.record(request, receipt(request)); + repository.completeSelection( + request, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.DENIED); + }); Thread.sleep(5L); CountDownLatch sealed = new CountDownLatch(1); CountDownLatch commit = new CountDownLatch(1); @@ -913,40 +873,34 @@ void newAndRecoveredReferencesSerializeAgainstRetirementOnTheSameTargetFence() t AtomicInteger recoveryPid = new AtomicInteger(); try (var executor = Executors.newFixedThreadPool(2)) { var retirement = - executor.submit( - () -> - transaction.execute( - ignored -> { - retirementPid.set( - java.util.Objects.requireNonNull( - dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class))); - boolean result = repository.sealTargetRetirement(request, current(request)); - sealed.countDown(); - try { - if (!commit.await(15L, TimeUnit.SECONDS)) { - throw new IllegalStateException("fixture timeout"); - } - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(interrupted); - } - return result; - })); + executor.submit(() -> + transaction.execute(ignored -> { + retirementPid.set( + java.util.Objects.requireNonNull( + dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class))); + boolean result = repository.sealTargetRetirement(request, current(request)); + sealed.countDown(); + try { + if (!commit.await(15L, TimeUnit.SECONDS)) { + throw new IllegalStateException("fixture timeout"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return result; + })); assertThat(sealed.await(5L, TimeUnit.SECONDS)).isTrue(); var recovery = - executor.submit( - () -> - transaction.execute( - ignored -> { - recoveryPid.set( - java.util.Objects.requireNonNull( - dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class))); - recoveryStarted.countDown(); - return repository.begin( - request.toBuilder() - .setOperationUuid(UUID.randomUUID().toString()) - .build()); - })); + executor.submit(() -> + transaction.execute(ignored -> { + recoveryPid.set( + java.util.Objects.requireNonNull( + dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class))); + recoveryStarted.countDown(); + return repository.begin( + request.toBuilder().setOperationUuid(UUID.randomUUID().toString()).build()); + })); assertThat(recoveryStarted.await(5L, TimeUnit.SECONDS)).isTrue(); awaitBackendBlockedBy(dsl, recoveryPid.get(), retirementPid.get()); commit.countDown(); @@ -1096,13 +1050,11 @@ void missingOriginalAndRolledBackReservationNeverSupplyPositiveEvidence() { assertThatThrownBy(() -> repository.begin(request)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("TRANSACTION_REQUIRED"); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> { - repository.begin(request); - throw new IllegalStateException("controlled rollback"); - })) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> { + repository.begin(request); + throw new IllegalStateException("controlled rollback"); + })) .hasMessage("controlled rollback"); assertThatThrownBy(() -> repository.read(request)).isInstanceOf(IllegalStateException.class); } @@ -1117,37 +1069,33 @@ void concurrentSameOriginalReservesOneFenceAndCannotReplaceItsIntent() throws Ex AtomicInteger replayPid = new AtomicInteger(); try (var executor = Executors.newFixedThreadPool(2)) { var first = - executor.submit( - () -> - transaction.execute( - ignored -> { - firstPid.set( - java.util.Objects.requireNonNull( - dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class))); - var value = repository.begin(request); - reserved.countDown(); - try { - if (!finish.await(15L, TimeUnit.SECONDS)) { - throw new IllegalStateException("fixture timeout"); - } - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(interrupted); - } - return value; - })); + executor.submit(() -> + transaction.execute(ignored -> { + firstPid.set( + java.util.Objects.requireNonNull( + dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class))); + var value = repository.begin(request); + reserved.countDown(); + try { + if (!finish.await(15L, TimeUnit.SECONDS)) { + throw new IllegalStateException("fixture timeout"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return value; + })); assertThat(reserved.await(5L, TimeUnit.SECONDS)).isTrue(); var replay = - executor.submit( - () -> - transaction.execute( - ignored -> { - replayPid.set( - java.util.Objects.requireNonNull( - dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class))); - replayStarted.countDown(); - return repository.begin(request); - })); + executor.submit(() -> + transaction.execute(ignored -> { + replayPid.set( + java.util.Objects.requireNonNull( + dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class))); + replayStarted.countDown(); + return repository.begin(request); + })); assertThat(replayStarted.await(5L, TimeUnit.SECONDS)).isTrue(); awaitBackendBlockedBy(dsl, replayPid.get(), firstPid.get()); finish.countDown(); @@ -1165,12 +1113,11 @@ void concurrentSameOriginalReservesOneFenceAndCannotReplaceItsIntent() throws Ex void interruptedRosterReadRecoversExactReceiptAndFencesLateWritersBeforeFiniteRetirement() throws Exception { var request = request(); - transaction.executeWithoutResult( - ignored -> { - repository.begin(request); - repository.reserveSelectionInput(request, selectionInput()); - repository.markRosterReadStarted(request); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(request); + repository.reserveSelectionInput(request, selectionInput()); + repository.markRosterReadStarted(request); + }); Thread.sleep(5L); var recovery = transaction @@ -1191,61 +1138,48 @@ void interruptedRosterReadRecoversExactReceiptAndFencesLateWritersBeforeFiniteRe assertThatThrownBy( () -> transaction.execute(ignored -> repository.record(request, originalReceipt))) .hasMessageContaining("RECOVERY_FENCED"); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> repository.reserveSelectionInput(request, selectionInput()))) + assertThatThrownBy(() -> + transaction.executeWithoutResult( + ignored -> repository.reserveSelectionInput(request, selectionInput()))) .hasMessageContaining("RECOVERY_FENCED"); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> repository.markRosterReadStarted(request))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> repository.markRosterReadStarted(request))) .hasMessageContaining("RECOVERY_FENCED"); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.completeSelection( - request, - CanonicalGameplayRosterReferenceRepository.SelectionOutcome.DENIED))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + repository.completeSelection( + request, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.DENIED))) .hasMessageContaining("RECOVERY_FENCED"); transaction.executeWithoutResult(ignored -> repository.completeUnissuedDenied(request)); assertThat(repository.read(request).getTerminalOutcome()).isEmpty(); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_session_canonical_roster_selection SET selection_input = ? WHERE operation_uuid = ?", - selectionInput().toBuilder().setSelector("1").build().toByteArray(), - UUID.fromString(request.getOperationUuid()))) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_session_canonical_roster_selection SET selection_input = ? WHERE operation_uuid = ?", + selectionInput().toBuilder().setSelector("1").build().toByteArray(), + UUID.fromString(request.getOperationUuid()))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_session_canonical_roster_selection SET recovery_uuid = ? WHERE operation_uuid = ?", - UUID.randomUUID(), - UUID.fromString(request.getOperationUuid()))) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_session_canonical_roster_selection SET recovery_uuid = ? WHERE operation_uuid = ?", + UUID.randomUUID(), + UUID.fromString(request.getOperationUuid()))) .isInstanceOf(DataAccessException.class); var response = recoveryResponse(recovery, originalReceipt); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.finishRecovery( - verifiedRecovery( - recovery, - response.toBuilder() - .setTargetFenceUuid(UUID.randomUUID().toString()) - .build())))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + repository.finishRecovery( + verifiedRecovery( + recovery, + response.toBuilder() + .setTargetFenceUuid(UUID.randomUUID().toString()) + .build())))) .hasMessageContaining("FENCE_CONFLICT"); var wrongMarker = recovery.toBuilder().setRecoveryUuid(UUID.randomUUID().toString()).build(); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.finishRecovery( - verifiedRecovery( - wrongMarker, - response.toBuilder().setRequest(wrongMarker).build())))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + repository.finishRecovery( + verifiedRecovery( + wrongMarker, response.toBuilder().setRequest(wrongMarker).build())))) .hasMessageContaining("recovery fence differs"); transaction.executeWithoutResult( ignored -> repository.finishRecovery(verifiedRecovery(recovery, response))); @@ -1256,16 +1190,14 @@ void interruptedRosterReadRecoversExactReceiptAndFencesLateWritersBeforeFiniteRe transaction.executeWithoutResult( ignored -> repository.finishRecovery(verifiedRecovery(recovery, response))); assertThat(retainedRow(request)).isEqualTo(retained); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.finishRecovery( - verifiedRecovery( - recovery, - response.toBuilder() - .setAdmissionUuid(UUID.randomUUID().toString()) - .build())))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + repository.finishRecovery( + verifiedRecovery( + recovery, + response.toBuilder() + .setAdmissionUuid(UUID.randomUUID().toString()) + .build())))) .hasMessageContaining("RECEIPT_CONFLICT"); Thread.sleep(5L); assertThat( @@ -1309,14 +1241,12 @@ void targetCandidateCursorAdvancesAcrossMalformedAndWronglyBoundRetainedOriginal .setCanonicalTarget(wrongBindingTarget.toByteString()) .build() .toByteArray(); - transaction.executeWithoutResult( - ignored -> { - insertRestoreShapedOriginal(malformedOperation, originalFences.get(0), malformedBytes); - insertRestoreShapedOriginal( - invalidOperation, originalFences.get(1), semanticallyInvalidBytes); - insertRestoreShapedOriginal( - wrongBindingOperation, originalFences.get(2), wrongBindingBytes); - }); + transaction.executeWithoutResult(ignored -> { + insertRestoreShapedOriginal(malformedOperation, originalFences.get(0), malformedBytes); + insertRestoreShapedOriginal( + invalidOperation, originalFences.get(1), semanticallyInvalidBytes); + insertRestoreShapedOriginal(wrongBindingOperation, originalFences.get(2), wrongBindingBytes); + }); var first = targetCandidatePage(null); var second = targetCandidatePage(first.operationUuid()); @@ -1377,17 +1307,16 @@ void malformedRecoveryOriginalKeepsItsBytesAndCannotStarveLaterBoundedPages() th repository = repository(policy(5000L, 1L, 1L)); var request = request().toBuilder().setOperationUuid(new UUID(0L, 100L).toString()).build(); var originals = new ArrayList(); - transaction.executeWithoutResult( - ignored -> { - for (int i = 0; i < 9; i++) { - var original = - request.toBuilder().setOperationUuid(new UUID(0L, 100L + i).toString()).build(); - originals.add(original); - repository.begin(original); - repository.reserveSelectionInput(original, selectionInput()); - repository.markRosterReadStarted(original); - } - }); + transaction.executeWithoutResult(ignored -> { + for (int i = 0; i < 9; i++) { + var original = + request.toBuilder().setOperationUuid(new UUID(0L, 100L + i).toString()).build(); + originals.add(original); + repository.begin(original); + repository.reserveSelectionInput(original, selectionInput()); + repository.markRosterReadStarted(original); + } + }); UUID fenceUuid = UUID.fromString(repository.read(request).getTargetFenceUuid()); UUID malformedOperation = new UUID(0L, 1L); byte[] malformedBytes = new byte[] {0x0a, (byte) 0x80}; @@ -1412,12 +1341,11 @@ void malformedRecoveryOriginalKeepsItsBytesAndCannotStarveLaterBoundedPages() th var client = org.mockito.Mockito.mock(CanonicalGameplayRosterRecoveryClient.class); var dispatched = new ArrayList(); org.mockito.Mockito.when(client.read(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - call -> { - CanonicalGameplayRosterRecoveryRequest recovery = call.getArgument(0); - dispatched.add(recovery); - throw io.grpc.Status.UNAVAILABLE.asRuntimeException(); - }); + .thenAnswer(call -> { + CanonicalGameplayRosterRecoveryRequest recovery = call.getArgument(0); + dispatched.add(recovery); + throw io.grpc.Status.UNAVAILABLE.asRuntimeException(); + }); var owner = new net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferenceOwner( repository, @@ -1533,45 +1461,35 @@ void frozenActorWithoutAssignmentReceiptClosesOnlyWithExactRecoveredRoster() thr net.firedevops.firemud.entitymanagement.v1.CanonicalGameplayRosterActorKind .CANONICAL_ROSTER_ACTOR_KIND_PLAYER)) .build(); - transaction.executeWithoutResult( - ignored -> { - repository.begin(request); - repository.reserveSelectionInput(request, selectionInput()); - repository.markRosterReadStarted(request); - repository.record(request, roster); - repository.selectOriginal(request, actor); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(request); + repository.reserveSelectionInput(request, selectionInput()); + repository.markRosterReadStarted(request); + repository.record(request, roster); + repository.selectOriginal(request, actor); + }); Thread.sleep(5L); var recovery = transaction .execute(ignored -> repository.beginRecoveries(request, current(request))) .getFirst(); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> repository.selectOriginal(request, actor))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> repository.selectOriginal(request, actor))) .hasMessageContaining("RECOVERY_FENCED"); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.recordSelectedAssignment( - request, - net.firedevops.firemud.entitymanagement.v1 - .CanonicalGameplayRosterSelectedAssignmentResponse - .getDefaultInstance()))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + repository.recordSelectedAssignment( + request, + net.firedevops.firemud.entitymanagement.v1 + .CanonicalGameplayRosterSelectedAssignmentResponse.getDefaultInstance()))) .hasMessageContaining("RECOVERY_FENCED"); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.finishRecovery( - verifiedRecovery(recovery, recoveryResponse(recovery, null))))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + repository.finishRecovery( + verifiedRecovery(recovery, recoveryResponse(recovery, null))))) .hasMessageContaining("ROSTER_CONFLICT"); - transaction.executeWithoutResult( - ignored -> - repository.finishRecovery( - verifiedRecovery(recovery, recoveryResponse(recovery, roster)))); + transaction.executeWithoutResult(ignored -> + repository.finishRecovery(verifiedRecovery(recovery, recoveryResponse(recovery, roster)))); var closed = repository.read(request); assertThat(closed.getSelectedCharacterUuid()).isEqualTo(actor.toString()); assertThat(closed.getCanonicalSelectedAssignmentReceipt()).isEmpty(); @@ -1586,21 +1504,18 @@ void frozenActorWithoutAssignmentReceiptClosesOnlyWithExactRecoveredRoster() thr @Test void positiveNoCaptureRecoveryAllowsClosureWithoutInventingRosterOrSelection() throws Exception { var request = request(); - transaction.executeWithoutResult( - ignored -> { - repository.begin(request); - repository.reserveSelectionInput(request, selectionInput()); - repository.markRosterReadStarted(request); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(request); + repository.reserveSelectionInput(request, selectionInput()); + repository.markRosterReadStarted(request); + }); Thread.sleep(5L); var recovery = transaction .execute(ignored -> repository.beginRecoveries(request, current(request))) .getFirst(); - transaction.executeWithoutResult( - ignored -> - repository.finishRecovery( - verifiedRecovery(recovery, recoveryResponse(recovery, null)))); + transaction.executeWithoutResult(ignored -> + repository.finishRecovery(verifiedRecovery(recovery, recoveryResponse(recovery, null)))); var result = repository.read(request); assertThat(result.getCanonicalRosterReceipt()).isEmpty(); assertThat(result.getSelectedCharacterUuid()).isEmpty(); @@ -1678,12 +1593,11 @@ void ownerRetriesUnknownEntityOutsideSqlAndRetainsPositiveClosureThroughLocalMin throws Exception { repository = repository(policy(5000L, 1L, 1L)); var request = request(); - transaction.executeWithoutResult( - ignored -> { - repository.begin(request); - repository.reserveSelectionInput(request, selectionInput()); - repository.markRosterReadStarted(request); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(request); + repository.reserveSelectionInput(request, selectionInput()); + repository.markRosterReadStarted(request); + }); Thread.sleep(5L); var routes = org.mockito.Mockito.mock( @@ -1692,49 +1606,45 @@ void ownerRetriesUnknownEntityOutsideSqlAndRetainsPositiveClosureThroughLocalMin var current = current(request); var snapshot = currentSnapshot(request); org.mockito.Mockito.when(routes.readCurrentTarget(current.canonicalTenantId())) - .thenAnswer( - call -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - return current; - }); + .thenAnswer(call -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + return current; + }); org.mockito.Mockito.when( admissions.readCurrentOpenSnapshotForRealm( request.getTargetNamespace(), current.canonicalTenantId(), current.realmId())) - .thenAnswer( - call -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - return snapshot; - }); + .thenAnswer(call -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + return snapshot; + }); org.mockito.Mockito.when(admissions.lockExactCurrentOpenSnapshot(snapshot)) - .thenAnswer( - call -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isTrue(); - return snapshot; - }); + .thenAnswer(call -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isTrue(); + return snapshot; + }); var client = org.mockito.Mockito.mock(CanonicalGameplayRosterRecoveryClient.class); var metrics = new SimpleMeterRegistry(); org.mockito.Mockito.when(client.read(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - call -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isSynchronizationActive()) - .isFalse(); - throw io.grpc.Status.UNAVAILABLE.asRuntimeException(); - }); + .thenAnswer(call -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + .isFalse(); + throw io.grpc.Status.UNAVAILABLE.asRuntimeException(); + }); var owner = new net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferenceOwner( repository, @@ -1800,19 +1710,18 @@ void recoveryPageAdvancesPastFailedBatchWithoutReplacingRecoveryIdentity() throw repository = repository(policy(5000L, 1L, 1L)); var request = request(); var originals = new ArrayList(); - transaction.executeWithoutResult( - ignored -> { - for (int i = 0; i < 9; i++) { - var original = - i == 0 - ? request - : request.toBuilder().setOperationUuid(UUID.randomUUID().toString()).build(); - originals.add(original); - repository.begin(original); - repository.reserveSelectionInput(original, selectionInput()); - repository.markRosterReadStarted(original); - } - }); + transaction.executeWithoutResult(ignored -> { + for (int i = 0; i < 9; i++) { + var original = + i == 0 + ? request + : request.toBuilder().setOperationUuid(UUID.randomUUID().toString()).build(); + originals.add(original); + repository.begin(original); + repository.reserveSelectionInput(original, selectionInput()); + repository.markRosterReadStarted(original); + } + }); Thread.sleep(5L); var routes = org.mockito.Mockito.mock( @@ -1833,16 +1742,15 @@ void recoveryPageAdvancesPastFailedBatchWithoutReplacingRecoveryIdentity() throw var retryCalls = new ArrayList(); var failuresRemaining = new AtomicInteger(8); org.mockito.Mockito.when(client.read(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - call -> { - CanonicalGameplayRosterRecoveryRequest recovery = call.getArgument(0); - if (failuresRemaining.getAndDecrement() > 0) { - failedBatchCalls.add(recovery); - throw io.grpc.Status.UNAVAILABLE.asRuntimeException(); - } - retryCalls.add(recovery); - return verifiedRecovery(recovery, recoveryResponse(recovery, null)); - }); + .thenAnswer(call -> { + CanonicalGameplayRosterRecoveryRequest recovery = call.getArgument(0); + if (failuresRemaining.getAndDecrement() > 0) { + failedBatchCalls.add(recovery); + throw io.grpc.Status.UNAVAILABLE.asRuntimeException(); + } + retryCalls.add(recovery); + return verifiedRecovery(recovery, recoveryResponse(recovery, null)); + }); var metrics = new SimpleMeterRegistry(); var owner = new net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferenceOwner( @@ -1950,35 +1858,29 @@ void recoveryPageAdvancesPastFailedBatchWithoutReplacingRecoveryIdentity() throw AtomicInteger waiterPid = new AtomicInteger(); try (var executor = Executors.newFixedThreadPool(2)) { var holder = - executor.submit( - () -> - transaction.execute( - ignored -> { - holderPid.set( - dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); - var page = repository.beginRecoveries(request, current(request)); - pageHeld.countDown(); - try { - if (!releasePage.await(15L, TimeUnit.SECONDS)) { - throw new IllegalStateException("fixture timeout"); - } - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(interrupted); - } - return page; - })); + executor.submit(() -> + transaction.execute(ignored -> { + holderPid.set(dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + var page = repository.beginRecoveries(request, current(request)); + pageHeld.countDown(); + try { + if (!releasePage.await(15L, TimeUnit.SECONDS)) { + throw new IllegalStateException("fixture timeout"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return page; + })); assertThat(pageHeld.await(5L, TimeUnit.SECONDS)).isTrue(); var waiter = - executor.submit( - () -> - transaction.execute( - ignored -> { - waiterPid.set( - dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); - waiterStarted.countDown(); - return repository.beginRecoveries(request, current(request)); - })); + executor.submit(() -> + transaction.execute(ignored -> { + waiterPid.set(dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + waiterStarted.countDown(); + return repository.beginRecoveries(request, current(request)); + })); assertThat(waiterStarted.await(5L, TimeUnit.SECONDS)).isTrue(); awaitBackendBlockedBy(dsl, waiterPid.get(), holderPid.get()); releasePage.countDown(); @@ -2048,23 +1950,21 @@ void purgedOriginalCannotReturnReservedWhenFreshSourceOrLockedCurrentProofFails( .class)); org.mockito.Mockito.when( admissions.lockExactCurrentOpenSnapshot(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - call -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isTrue(); - CanonicalInitialAdmissionRepository.CurrentOpenSnapshot qualified = - call.getArgument(0); - assertThat(qualified.admissionPointerSnapshotDigest()) - .isEqualTo(published.route().admissionPointerSnapshotDigest()); - assertThat(qualified.ownerProof().proofDigest()) - .isEqualTo(published.route().ownerProofDigest()); - assertThat(qualified.ownerProof().holdId()).isEqualTo(published.route().holdId()); - throw new CanonicalInitialAdmissionRepository - .CanonicalInitialAdmissionReconciliationRequiredException( - "current changed before reservation commit"); - }); + .thenAnswer(call -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isTrue(); + CanonicalInitialAdmissionRepository.CurrentOpenSnapshot qualified = call.getArgument(0); + assertThat(qualified.admissionPointerSnapshotDigest()) + .isEqualTo(published.route().admissionPointerSnapshotDigest()); + assertThat(qualified.ownerProof().proofDigest()) + .isEqualTo(published.route().ownerProofDigest()); + assertThat(qualified.ownerProof().holdId()).isEqualTo(published.route().holdId()); + throw new CanonicalInitialAdmissionRepository + .CanonicalInitialAdmissionReconciliationRequiredException( + "current changed before reservation commit"); + }); assertThatThrownBy(() -> owner.begin(request)).hasMessageContaining("current changed"); assertNoOriginalOrFence(); } @@ -2088,43 +1988,39 @@ void freshReservationQualifiesOutsideSqlAndLocksThatExactSourceBeforeCommit() { org.mockito.ArgumentMatchers.any( net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence .Request.class))) - .thenAnswer( - call -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - assertNoOriginalOrFence(); - var source = sourceEvidence(call.getArgument(0), published); - observed.set(source); - return source; - }); + .thenAnswer(call -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + assertNoOriginalOrFence(); + var source = sourceEvidence(call.getArgument(0), published); + observed.set(source); + return source; + }); org.mockito.Mockito.when( admissions.lockExactCurrentOpenSnapshot(org.mockito.ArgumentMatchers.any())) - .thenAnswer( - call -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isTrue(); - CanonicalInitialAdmissionRepository.CurrentOpenSnapshot qualified = - call.getArgument(0); - assertThat(repository.find(request)).isPresent(); - assertThat(qualified.ownerProof().holdBindingDigest()) - .isEqualTo( - observed.get().gameSessionOwnerProof().holdIdentity().holdBindingDigest()); - assertThat(qualified.ownerProof().initialAdmissionRequestId()) - .isEqualTo( - observed - .get() - .gameSessionOwnerProof() - .holdIdentity() - .request() - .initialAdmissionRequestId()); - assertThat(qualified.admissionPointerSnapshotDigest()) - .isEqualTo(observed.get().admissionPointerSnapshotDigest()); - return qualified; - }); + .thenAnswer(call -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isTrue(); + CanonicalInitialAdmissionRepository.CurrentOpenSnapshot qualified = call.getArgument(0); + assertThat(repository.find(request)).isPresent(); + assertThat(qualified.ownerProof().holdBindingDigest()) + .isEqualTo(observed.get().gameSessionOwnerProof().holdIdentity().holdBindingDigest()); + assertThat(qualified.ownerProof().initialAdmissionRequestId()) + .isEqualTo( + observed + .get() + .gameSessionOwnerProof() + .holdIdentity() + .request() + .initialAdmissionRequestId()); + assertThat(qualified.admissionPointerSnapshotDigest()) + .isEqualTo(observed.get().admissionPointerSnapshotDigest()); + return qualified; + }); var owner = referenceOwner(sources, admissions); assertThat(owner.begin(request).getCanonicalRosterReceipt()).isEmpty(); assertThat(repository.find(request)).isPresent(); @@ -2209,16 +2105,15 @@ void deniedDispatchedReadsKeepTheirOriginalDenialAndActualRepositoryRecoveryProt net.firedevops.firemud.entitymanagement.v1 .CanonicalGameplayRosterActorKind.CANONICAL_ROSTER_ACTOR_KIND_PLAYER)) .build(); - transaction.executeWithoutResult( - ignored -> { - repository.begin(request); - repository.reserveSelectionInput(request, selectionInput()); - repository.markRosterReadStarted(request); - if (selectedRead) { - repository.record(request, roster); - repository.selectOriginal(request, actor); - } - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(request); + repository.reserveSelectionInput(request, selectionInput()); + repository.markRosterReadStarted(request); + if (selectedRead) { + repository.record(request, roster); + repository.selectOriginal(request, actor); + } + }); var routes = org.mockito.Mockito.mock( net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService.class); @@ -2317,15 +2212,14 @@ void allRequiredObservationsAndStoredHorizonProtectOriginalsAndLostReplyReplaysA .build(); var roster = receipt(first); for (var original : List.of(first, second)) { - transaction.executeWithoutResult( - ignored -> { - repository.begin(original); - repository.reserveSelectionInput(original, selectionInput()); - repository.markRosterReadStarted(original); - repository.record(original, roster); - repository.completeSelection( - original, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.MENU); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(original); + repository.reserveSelectionInput(original, selectionInput()); + repository.markRosterReadStarted(original); + repository.record(original, roster); + repository.completeSelection( + original, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.MENU); + }); } var originalFenceUuid = dsl.fetchSingle( @@ -2359,11 +2253,10 @@ void allRequiredObservationsAndStoredHorizonProtectOriginalsAndLostReplyReplaysA .get("target_fence_uuid", UUID.class)) .isEqualTo(originalFenceUuid); } - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_session_canonical_roster_selection SET owner_fence = 2 WHERE operation_uuid = ?", - UUID.fromString(first.getOperationUuid()))) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_session_canonical_roster_selection SET owner_fence = 2 WHERE operation_uuid = ?", + UUID.fromString(first.getOperationUuid()))) .isInstanceOf(DataAccessException.class); for (var original : List.of(first, second)) { assertThat( @@ -2408,12 +2301,10 @@ void allRequiredObservationsAndStoredHorizonProtectOriginalsAndLostReplyReplaysA firstRequest, CanonicalGameplayRosterRetirementEvidence.response( firstRequest, UUID.randomUUID(), 250L)); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> - repository.confirmRetirementAcknowledgement( - unrecordedConfirmation, entityPrincipal()))) + assertThatThrownBy(() -> + transaction.execute(ignored -> + repository.confirmRetirementAcknowledgement( + unrecordedConfirmation, entityPrincipal()))) .hasMessageContaining("ACKNOWLEDGEMENT_CONFLICT"); var firstAck = transaction.execute( @@ -2426,23 +2317,16 @@ unrecordedConfirmation, entityPrincipal()))) ignored -> repository.acknowledgeRetirement(firstRequest, entityPrincipal()))) .isEqualTo(firstAck); assertThat(transferRow(first)).isEqualTo(beforeReplay); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> - repository.acknowledgeRetirement( - firstRequest.toBuilder() - .setAdmissionUuid(UUID.randomUUID().toString()) - .build(), - entityPrincipal()))) + assertThatThrownBy(() -> + transaction.execute(ignored -> + repository.acknowledgeRetirement( + firstRequest.toBuilder().setAdmissionUuid(UUID.randomUUID().toString()).build(), + entityPrincipal()))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> - repository.acknowledgeRetirement( - firstRequest, - "spiffe://firemud/ns/other/sa/entity-management-service"))) + assertThatThrownBy(() -> + transaction.execute(ignored -> + repository.acknowledgeRetirement( + firstRequest, "spiffe://firemud/ns/other/sa/entity-management-service"))) .isInstanceOf(IllegalArgumentException.class); var secondAck = transaction.execute( @@ -2466,25 +2350,22 @@ unrecordedConfirmation, entityPrincipal()))) var confirmation = CanonicalGameplayRosterRetirementEvidence.confirmation(firstRequest, firstAck); assertThat( - transaction.execute( - ignored -> - repository.confirmRetirementAcknowledgement(confirmation, entityPrincipal()))) + transaction.execute(ignored -> + repository.confirmRetirementAcknowledgement(confirmation, entityPrincipal()))) .isEqualTo(CanonicalGameplayRosterRetirementEvidence.confirmationResponse(confirmation)); assertThat( transaction.execute( ignored -> repository.purgeConfirmedRetirementAcknowledgements(8))) .isZero(); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> - repository.confirmRetirementAcknowledgement( - confirmation.toBuilder() - .setAcknowledgement( - firstAck.toBuilder() - .setAcknowledgementUuid(UUID.randomUUID().toString())) - .build(), - entityPrincipal()))) + assertThatThrownBy(() -> + transaction.execute(ignored -> + repository.confirmRetirementAcknowledgement( + confirmation.toBuilder() + .setAcknowledgement( + firstAck.toBuilder() + .setAcknowledgementUuid(UUID.randomUUID().toString())) + .build(), + entityPrincipal()))) .isInstanceOf(IllegalArgumentException.class); Thread.sleep(275L); assertThat( @@ -2492,14 +2373,12 @@ unrecordedConfirmation, entityPrincipal()))) ignored -> repository.purgeConfirmedRetirementAcknowledgements(1))) .isEqualTo(1); assertThat( - transaction.execute( - ignored -> - repository.confirmRetirementAcknowledgement(confirmation, entityPrincipal()))) + transaction.execute(ignored -> + repository.confirmRetirementAcknowledgement(confirmation, entityPrincipal()))) .isEqualTo(CanonicalGameplayRosterRetirementEvidence.confirmationResponse(confirmation)); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> repository.acknowledgeRetirement(firstRequest, entityPrincipal()))) + assertThatThrownBy(() -> + transaction.execute( + ignored -> repository.acknowledgeRetirement(firstRequest, entityPrincipal()))) .isInstanceOf( CanonicalGameplayRosterReferenceRepository.OriginalUnavailableException.class); assertThat( @@ -2507,11 +2386,10 @@ unrecordedConfirmation, entityPrincipal()))) "SELECT count(*) FROM game_session_canonical_roster_retirement_transfers") .get(0, Long.class)) .isEqualTo(1L); - transaction.executeWithoutResult( - ignored -> - repository.confirmRetirementAcknowledgement( - CanonicalGameplayRosterRetirementEvidence.confirmation(secondRequest, secondAck), - entityPrincipal())); + transaction.executeWithoutResult(ignored -> + repository.confirmRetirementAcknowledgement( + CanonicalGameplayRosterRetirementEvidence.confirmation(secondRequest, secondAck), + entityPrincipal())); } @Test @@ -2532,10 +2410,9 @@ void confirmationWithoutInventoryIsOnlyANoopAndCannotCreateFirstAckOrReleaseTarg .isZero(); assertThat(repository.read(original).getTargetFenceUuid()) .isEqualTo(candidate.fenceUuid().toString()); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> repository.acknowledgeRetirement(request, entityPrincipal()))) + assertThatThrownBy(() -> + transaction.execute( + ignored -> repository.acknowledgeRetirement(request, entityPrincipal()))) .isInstanceOf( CanonicalGameplayRosterReferenceRepository.OriginalUnavailableException.class); } @@ -2545,29 +2422,27 @@ void storedMinimumStillGatesPurgeAndConfirmationBeforePurgeCannotShortenReceiptH throws Exception { repository = repository(policy(5_000L, 1L, 1L)); var original = request(); - transaction.executeWithoutResult( - ignored -> { - repository.begin(original); - repository.reserveSelectionInput(original, selectionInput()); - repository.record(original, receipt(original)); - repository.completeSelection( - original, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.MENU); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(original); + repository.reserveSelectionInput(original, selectionInput()); + repository.record(original, receipt(original)); + repository.completeSelection( + original, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.MENU); + }); Awaitility.await() .alias("database clock reaches the stored roster minimum before retirement") .pollInterval(50L, TimeUnit.MILLISECONDS) .atMost(15L, TimeUnit.SECONDS) - .untilAsserted( - () -> - assertThat( - dsl.fetchSingle( - "SELECT s.terminal_at + f.minimum_retention_millis * interval '1 millisecond' <= clock_timestamp() " - + "FROM game_session_canonical_roster_selection s " - + "JOIN game_session_canonical_roster_target_fences f USING (target_fence_uuid) " - + "WHERE s.operation_uuid = ?", - UUID.fromString(original.getOperationUuid())) - .get(0, Boolean.class)) - .isTrue()); + .untilAsserted(() -> + assertThat( + dsl.fetchSingle( + "SELECT s.terminal_at + f.minimum_retention_millis * interval '1 millisecond' <= clock_timestamp() " + + "FROM game_session_canonical_roster_selection s " + + "JOIN game_session_canonical_roster_target_fences f USING (target_fence_uuid) " + + "WHERE s.operation_uuid = ?", + UUID.fromString(original.getOperationUuid())) + .get(0, Boolean.class)) + .isTrue()); assertThat( transaction.execute( ignored -> repository.sealTargetRetirement(original, current(original)))) @@ -2598,24 +2473,22 @@ void storedMinimumStillGatesPurgeAndConfirmationBeforePurgeCannotShortenReceiptH .isFalse(); assertThatThrownBy(() -> dsl.execute("DELETE FROM game_session_canonical_roster_selection")) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_session_canonical_roster_retirement_transfers SET target_purged_at = clock_timestamp()")) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_session_canonical_roster_retirement_transfers SET target_purged_at = clock_timestamp()")) .isInstanceOf(DataAccessException.class); Awaitility.await() .alias("database clock reaches the stored target retirement horizon") .pollInterval(50L, TimeUnit.MILLISECONDS) .atMost(15L, TimeUnit.SECONDS) - .untilAsserted( - () -> - assertThat( - dsl.fetchSingle( - "SELECT retired_at + minimum_retention_millis * interval '1 millisecond' <= clock_timestamp() " - + "FROM game_session_canonical_roster_target_fences WHERE target_fence_uuid = ?", - candidate.fenceUuid()) - .get(0, Boolean.class)) - .isTrue()); + .untilAsserted(() -> + assertThat( + dsl.fetchSingle( + "SELECT retired_at + minimum_retention_millis * interval '1 millisecond' <= clock_timestamp() " + + "FROM game_session_canonical_roster_target_fences WHERE target_fence_uuid = ?", + candidate.fenceUuid()) + .get(0, Boolean.class)) + .isTrue()); assertThat(transaction.execute(ignored -> repository.purgeRetiredTarget(candidate))) .isTrue(); assertThat( @@ -2629,16 +2502,15 @@ void storedMinimumStillGatesPurgeAndConfirmationBeforePurgeCannotShortenReceiptH .alias("database clock reaches the stored confirmed receipt cleanup horizon") .pollInterval(50L, TimeUnit.MILLISECONDS) .atMost(15L, TimeUnit.SECONDS) - .untilAsserted( - () -> - assertThat( - dsl.fetchSingle( - "SELECT GREATEST(confirmed_at, target_purged_at) + effective_minimum_millis * interval '1 millisecond' <= clock_timestamp() " - + "FROM game_session_canonical_roster_retirement_transfers " - + "WHERE target_fence_uuid = ? AND confirmed_at IS NOT NULL AND target_purged_at IS NOT NULL", - candidate.fenceUuid()) - .get(0, Boolean.class)) - .isTrue()); + .untilAsserted(() -> + assertThat( + dsl.fetchSingle( + "SELECT GREATEST(confirmed_at, target_purged_at) + effective_minimum_millis * interval '1 millisecond' <= clock_timestamp() " + + "FROM game_session_canonical_roster_retirement_transfers " + + "WHERE target_fence_uuid = ? AND confirmed_at IS NOT NULL AND target_purged_at IS NOT NULL", + candidate.fenceUuid()) + .get(0, Boolean.class)) + .isTrue()); assertThat( transaction.execute( ignored -> repository.purgeConfirmedRetirementAcknowledgements(8))) @@ -2648,12 +2520,11 @@ void storedMinimumStillGatesPurgeAndConfirmationBeforePurgeCannotShortenReceiptH @Test void recoveryObservationChecksKnownNonceAndExactRetirementBeforeFirstAck() throws Exception { var original = request(); - transaction.executeWithoutResult( - ignored -> { - repository.begin(original); - repository.reserveSelectionInput(original, selectionInput()); - repository.markRosterReadStarted(original); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(original); + repository.reserveSelectionInput(original, selectionInput()); + repository.markRosterReadStarted(original); + }); Thread.sleep(5L); var recovery = transaction @@ -2669,58 +2540,51 @@ void recoveryObservationChecksKnownNonceAndExactRetirementBeforeFirstAck() throw .isTrue(); var proof = repository.read(original); var wrongNonce = acknowledgement(original, proof, UUID.randomUUID(), 1L); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> repository.acknowledgeRetirement(wrongNonce, entityPrincipal()))) + assertThatThrownBy(() -> + transaction.execute( + ignored -> repository.acknowledgeRetirement(wrongNonce, entityPrincipal()))) .hasMessageContaining("ADMISSION_CONFLICT"); var exact = wrongNonce.toBuilder().setAdmissionUuid(closed.getAdmissionUuid()).build(); var wrongFenceProof = CanonicalGameplayRosterReferenceEvidence.sealRetirement( proof.toBuilder().setTargetFenceUuid(UUID.randomUUID().toString()).build()); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> - repository.acknowledgeRetirement( - exact.toBuilder().setObservedRetirement(wrongFenceProof).build(), - entityPrincipal()))) + assertThatThrownBy(() -> + transaction.execute(ignored -> + repository.acknowledgeRetirement( + exact.toBuilder().setObservedRetirement(wrongFenceProof).build(), + entityPrincipal()))) .hasMessageContaining("OBSERVATION_CONFLICT"); var absent = original.toBuilder().setOperationUuid(UUID.randomUUID().toString()).build(); var absentProof = CanonicalGameplayRosterReferenceEvidence.sealRetirement( proof.toBuilder().setRequest(absent).build()); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> - repository.acknowledgeRetirement( - acknowledgement(absent, absentProof, UUID.randomUUID(), 1L), - entityPrincipal()))) + assertThatThrownBy(() -> + transaction.execute(ignored -> + repository.acknowledgeRetirement( + acknowledgement(absent, absentProof, UUID.randomUUID(), 1L), + entityPrincipal()))) .isInstanceOf( CanonicalGameplayRosterReferenceRepository.OriginalUnavailableException.class); var ack = transaction.execute(ignored -> repository.acknowledgeRetirement(exact, entityPrincipal())); assertThat(ack.getMinimumRetentionMillis()).isEqualTo(1L); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_session_canonical_roster_retirement_transfers SET admission_uuid = ?", - UUID.randomUUID())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_session_canonical_roster_retirement_transfers SET admission_uuid = ?", + UUID.randomUUID())) .isInstanceOf(DataAccessException.class); } @Test void firstAckSerializesWithPurgeOnTheRetiredFence() throws Exception { var original = request(); - transaction.executeWithoutResult( - ignored -> { - repository.begin(original); - repository.reserveSelectionInput(original, selectionInput()); - repository.record(original, receipt(original)); - repository.completeSelection( - original, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.MENU); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(original); + repository.reserveSelectionInput(original, selectionInput()); + repository.record(original, receipt(original)); + repository.completeSelection( + original, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.MENU); + }); Thread.sleep(5L); assertThat( transaction.execute( @@ -2741,37 +2605,32 @@ void firstAckSerializesWithPurgeOnTheRetiredFence() throws Exception { var purgePid = new AtomicInteger(); try (var executor = Executors.newFixedThreadPool(2)) { var firstAck = - executor.submit( - () -> - transaction.execute( - ignored -> { - acknowledgementPid.set( - java.util.Objects.requireNonNull( - dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class))); - var ack = repository.acknowledgeRetirement(request, entityPrincipal()); - locked.countDown(); - try { - assertThat(release.await(15L, TimeUnit.SECONDS)).isTrue(); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(interrupted); - } - return ack; - })); + executor.submit(() -> + transaction.execute(ignored -> { + acknowledgementPid.set( + java.util.Objects.requireNonNull( + dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class))); + var ack = repository.acknowledgeRetirement(request, entityPrincipal()); + locked.countDown(); + try { + assertThat(release.await(15L, TimeUnit.SECONDS)).isTrue(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return ack; + })); try { assertThat(locked.await(5L, TimeUnit.SECONDS)).isTrue(); var purged = - executor.submit( - () -> - transaction.execute( - ignored -> { - purgePid.set( - java.util.Objects.requireNonNull( - dsl.fetchSingle("SELECT pg_backend_pid()") - .get(0, Integer.class))); - purgeStarted.countDown(); - return repository.purgeRetiredTarget(candidate); - })); + executor.submit(() -> + transaction.execute(ignored -> { + purgePid.set( + java.util.Objects.requireNonNull( + dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class))); + purgeStarted.countDown(); + return repository.purgeRetiredTarget(candidate); + })); assertThat(purgeStarted.await(5L, TimeUnit.SECONDS)).isTrue(); awaitBackendBlockedBy(dsl, purgePid.get(), acknowledgementPid.get()); release.countDown(); @@ -2869,17 +2728,16 @@ void createdOriginalSurvivesSqlAndProductionMtlsOwnerReadAcknowledgementAndConfi .setMenuSnapshotDigest(roster.getRoster().getSnapshotDigest()) .build(); - transaction.executeWithoutResult( - ignored -> { - repository.begin(original); - repository.reserveSelectionInput(original, input); - repository.markRosterReadStarted(original); - repository.recordPlayerCreated(original, roster); - repository.selectOriginal(original, UUID.fromString(selected.getSelectedCharacterUuid())); - repository.recordSelectedPlayerCreatedCharacter(original, selected); - repository.completeSelection( - original, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.SELECTED); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(original); + repository.reserveSelectionInput(original, input); + repository.markRosterReadStarted(original); + repository.recordPlayerCreated(original, roster); + repository.selectOriginal(original, UUID.fromString(selected.getSelectedCharacterUuid())); + repository.recordSelectedPlayerCreatedCharacter(original, selected); + repository.completeSelection( + original, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.SELECTED); + }); assertThat( dsl.fetchSingle( "SELECT canonical_player_created_roster_receipt FROM game_session_canonical_roster_selection WHERE operation_uuid = ?", @@ -2895,14 +2753,13 @@ void createdOriginalSurvivesSqlAndProductionMtlsOwnerReadAcknowledgementAndConfi Awaitility.await() .atMost(java.time.Duration.ofSeconds(5)) - .untilAsserted( - () -> - assertThat( - dsl.fetchSingle( - "SELECT s.terminal_at + f.minimum_retention_millis * interval '1 millisecond' <= clock_timestamp() FROM game_session_canonical_roster_selection s JOIN game_session_canonical_roster_target_fences f USING (target_fence_uuid) WHERE s.operation_uuid = ?", - UUID.fromString(original.getOperationUuid())) - .get(0, Boolean.class)) - .isTrue()); + .untilAsserted(() -> + assertThat( + dsl.fetchSingle( + "SELECT s.terminal_at + f.minimum_retention_millis * interval '1 millisecond' <= clock_timestamp() FROM game_session_canonical_roster_selection s JOIN game_session_canonical_roster_target_fences f USING (target_fence_uuid) WHERE s.operation_uuid = ?", + UUID.fromString(original.getOperationUuid())) + .get(0, Boolean.class)) + .isTrue()); var routes = org.mockito.Mockito.mock( @@ -3109,15 +2966,14 @@ void createdEmptyMenuReplaysExactTypedReceiptWithoutInventingASelection() throws repository = repository(policy(60000L, 60000L, 60000L)); var fixture = createdFixture(false); var original = fixture.original(); - transaction.executeWithoutResult( - ignored -> { - repository.begin(original); - repository.reserveSelectionInput(original, selectionInput()); - repository.markRosterReadStarted(original); - repository.recordPlayerCreated(original, fixture.roster()); - repository.completeSelection( - original, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.MENU); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(original); + repository.reserveSelectionInput(original, selectionInput()); + repository.markRosterReadStarted(original); + repository.recordPlayerCreated(original, fixture.roster()); + repository.completeSelection( + original, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.MENU); + }); var recorded = repository.read(original); var retained = createdRow(original); assertThat( @@ -3136,10 +2992,8 @@ void createdEmptyMenuReplaysExactTypedReceiptWithoutInventingASelection() throws ignored -> repository.recordPlayerCreated(original, fixture.roster()))) .isEqualTo(recorded); assertThat(createdRow(original)).isEqualTo(retained); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> repository.selectOriginal(original, UUID.randomUUID()))) + assertThatThrownBy(() -> + transaction.execute(ignored -> repository.selectOriginal(original, UUID.randomUUID()))) .isInstanceOf(IllegalStateException.class); } @@ -3149,18 +3003,17 @@ void createdOneActorAndCompleteSelectedTerminalReplayWithExactBytesAndPolicyIsol repository = repository(policy(60000L, 60000L, 60000L)); var fixture = createdFixture(true); var original = fixture.original(); - transaction.executeWithoutResult( - ignored -> { - repository.begin(original); - repository.reserveSelectionInput(original, selectionInput()); - repository.markRosterReadStarted(original); - repository.recordPlayerCreated(original, fixture.roster()); - repository.selectOriginal( - original, UUID.fromString(fixture.selected().getSelectedCharacterUuid())); - repository.recordSelectedPlayerCreatedCharacter(original, fixture.selected()); - repository.completeSelection( - original, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.SELECTED); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(original); + repository.reserveSelectionInput(original, selectionInput()); + repository.markRosterReadStarted(original); + repository.recordPlayerCreated(original, fixture.roster()); + repository.selectOriginal( + original, UUID.fromString(fixture.selected().getSelectedCharacterUuid())); + repository.recordSelectedPlayerCreatedCharacter(original, fixture.selected()); + repository.completeSelection( + original, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.SELECTED); + }); var selected = repository.read(original); assertThat( CanonicalGameplayRosterReferenceEvidence.selectedPlayerCreatedCharacterReceipt( @@ -3177,20 +3030,16 @@ void createdOneActorAndCompleteSelectedTerminalReplayWithExactBytesAndPolicyIsol ignored -> repository.replay(original))) .isEqualTo(selected); assertThat(createdRow(original)).isEqualTo(retained); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> repository.record(original, fixture.roster().getRoster()))) + assertThatThrownBy(() -> + transaction.execute( + ignored -> repository.record(original, fixture.roster().getRoster()))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.recordSelectedAssignment( - original, - net.firedevops.firemud.entitymanagement.v1 - .CanonicalGameplayRosterSelectedAssignmentResponse - .getDefaultInstance()))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + repository.recordSelectedAssignment( + original, + net.firedevops.firemud.entitymanagement.v1 + .CanonicalGameplayRosterSelectedAssignmentResponse.getDefaultInstance()))) .isInstanceOf(IllegalArgumentException.class); var changed = fixture.selected().toBuilder() @@ -3198,10 +3047,9 @@ void createdOneActorAndCompleteSelectedTerminalReplayWithExactBytesAndPolicyIsol fixture.selected().getTerminal().toBuilder() .setTerminalId(UUID.randomUUID().toString())) .build(); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> repository.recordSelectedPlayerCreatedCharacter(original, changed))) + assertThatThrownBy(() -> + transaction.executeWithoutResult( + ignored -> repository.recordSelectedPlayerCreatedCharacter(original, changed))) .hasMessageContaining("CREATED_RECEIPT_CONFLICT"); assertThat(createdRow(original)).isEqualTo(retained); } @@ -3212,12 +3060,11 @@ void createdSourceIdentityOwnsItsFenceAndSqlRefusesMixedMutableAndIncompleteRece repository = repository(policy(60000L, 60000L, 60000L)); var fixture = createdFixture(true); var original = fixture.original(); - transaction.executeWithoutResult( - ignored -> { - repository.begin(original); - repository.reserveSelectionInput(original, selectionInput()); - repository.recordPlayerCreated(original, fixture.roster()); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(original); + repository.reserveSelectionInput(original, selectionInput()); + repository.recordPlayerCreated(original, fixture.roster()); + }); var initial = repository.read(original); var alteredRoster = fixture.roster().toBuilder() @@ -3225,10 +3072,8 @@ void createdSourceIdentityOwnsItsFenceAndSqlRefusesMixedMutableAndIncompleteRece fixture.roster().getRoster().toBuilder() .setSnapshotUuid(UUID.randomUUID().toString())) .build(); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> repository.recordPlayerCreated(original, alteredRoster))) + assertThatThrownBy(() -> + transaction.execute(ignored -> repository.recordPlayerCreated(original, alteredRoster))) .hasMessageContaining("RECEIPT_CONFLICT"); var source = CanonicalGameplayRosterReferenceEvidence.playerCreatedSourceIdentity(original); var changedSource = @@ -3249,43 +3094,36 @@ void createdSourceIdentityOwnsItsFenceAndSqlRefusesMixedMutableAndIncompleteRece changedSource.toBuilder().setOperationUuid(UUID.randomUUID().toString()).build(); var other = transaction.execute(ignored -> repository.begin(otherOperation)); assertThat(other.getTargetFenceUuid()).isNotEqualTo(initial.getTargetFenceUuid()); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_session_canonical_roster_selection SET entry_policy='PRESEEDED_ONLY' WHERE operation_uuid=?", - UUID.fromString(original.getOperationUuid()))) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_session_canonical_roster_selection SET entry_policy='PRESEEDED_ONLY' WHERE operation_uuid=?", + UUID.fromString(original.getOperationUuid()))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_session_canonical_roster_selection SET canonical_roster_receipt=? WHERE operation_uuid=?", - new byte[] {1}, - UUID.fromString(original.getOperationUuid()))) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_session_canonical_roster_selection SET canonical_roster_receipt=? WHERE operation_uuid=?", + new byte[] {1}, + UUID.fromString(original.getOperationUuid()))) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_session_canonical_roster_selection SET canonical_player_created_roster_receipt=? WHERE operation_uuid=?", - alteredRoster.toByteArray(), - UUID.fromString(original.getOperationUuid()))) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_session_canonical_roster_selection SET canonical_player_created_roster_receipt=? WHERE operation_uuid=?", + alteredRoster.toByteArray(), + UUID.fromString(original.getOperationUuid()))) .isInstanceOf(DataAccessException.class); - transaction.execute( - ignored -> - repository.selectOriginal( - original, UUID.fromString(fixture.selected().getSelectedCharacterUuid()))); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.completeSelection( - original, - CanonicalGameplayRosterReferenceRepository.SelectionOutcome.SELECTED))) + transaction.execute(ignored -> + repository.selectOriginal( + original, UUID.fromString(fixture.selected().getSelectedCharacterUuid()))); + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + repository.completeSelection( + original, + CanonicalGameplayRosterReferenceRepository.SelectionOutcome.SELECTED))) .hasMessageContaining("RECOVERY_REQUIRED"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE game_session_canonical_roster_selection SET terminal_outcome='SELECTED', terminal_at=clock_timestamp() WHERE operation_uuid=?", - UUID.fromString(original.getOperationUuid()))) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE game_session_canonical_roster_selection SET terminal_outcome='SELECTED', terminal_at=clock_timestamp() WHERE operation_uuid=?", + UUID.fromString(original.getOperationUuid()))) .isInstanceOf(DataAccessException.class); assertThatThrownBy( () -> dsl.execute("TRUNCATE game_session_canonical_roster_selection CASCADE")) @@ -3307,15 +3145,14 @@ void createdRecoveryClosesMissingSelectedReceiptAndRequiresEveryExactEntityAck() throws Exception { var fixture = createdFixture(true); var original = fixture.original(); - transaction.executeWithoutResult( - ignored -> { - repository.begin(original); - repository.reserveSelectionInput(original, selectionInput()); - repository.markRosterReadStarted(original); - repository.recordPlayerCreated(original, fixture.roster()); - repository.selectOriginal( - original, UUID.fromString(fixture.selected().getSelectedCharacterUuid())); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(original); + repository.reserveSelectionInput(original, selectionInput()); + repository.markRosterReadStarted(original); + repository.recordPlayerCreated(original, fixture.roster()); + repository.selectOriginal( + original, UUID.fromString(fixture.selected().getSelectedCharacterUuid())); + }); Thread.sleep(5L); var recovery = transaction @@ -3329,12 +3166,9 @@ void createdRecoveryClosesMissingSelectedReceiptAndRequiresEveryExactEntityAck() owner.getOwnerFence(), UUID.fromString(owner.getTargetFenceUuid()), fixture.roster()); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - ignored -> - repository.recordSelectedPlayerCreatedCharacter( - original, fixture.selected()))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(ignored -> + repository.recordSelectedPlayerCreatedCharacter(original, fixture.selected()))) .hasMessageContaining("RECOVERY_FENCED"); transaction.executeWithoutResult( ignored -> repository.finishRecovery(verifiedRecovery(recovery, response))); @@ -3361,26 +3195,22 @@ void createdRecoveryClosesMissingSelectedReceiptAndRequiresEveryExactEntityAck() assertThat(transaction.execute(ignored -> repository.purgeRetiredTarget(candidate))) .isFalse(); var acknowledgement = createdAcknowledgement(original, proof, response.getAdmissionUuid()); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> - repository.acknowledgeRetirement( - acknowledgement.toBuilder() - .setAdmissionUuid(UUID.randomUUID().toString()) - .build(), - createdPrincipal(original)))) + assertThatThrownBy(() -> + transaction.execute(ignored -> + repository.acknowledgeRetirement( + acknowledgement.toBuilder() + .setAdmissionUuid(UUID.randomUUID().toString()) + .build(), + createdPrincipal(original)))) .hasMessageContaining("ADMISSION_CONFLICT"); var ack = - transaction.execute( - ignored -> - repository.acknowledgeRetirement(acknowledgement, createdPrincipal(original))); + transaction.execute(ignored -> + repository.acknowledgeRetirement(acknowledgement, createdPrincipal(original))); assertThat(transaction.execute(ignored -> repository.purgeRetiredTarget(candidate))) .isTrue(); assertThat( - transaction.execute( - ignored -> - repository.acknowledgeRetirement(acknowledgement, createdPrincipal(original)))) + transaction.execute(ignored -> + repository.acknowledgeRetirement(acknowledgement, createdPrincipal(original)))) .isEqualTo(ack); } @@ -3390,12 +3220,11 @@ void createdNoCaptureRecoveryRetainsPositiveClosureWithoutInventingEitherRosterR repository = repository(policy(500L, 500L, 500L)); var fixture = createdFixture(false); var original = fixture.original(); - transaction.executeWithoutResult( - ignored -> { - repository.begin(original); - repository.reserveSelectionInput(original, selectionInput()); - repository.markRosterReadStarted(original); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(original); + repository.reserveSelectionInput(original, selectionInput()); + repository.markRosterReadStarted(original); + }); Thread.sleep(550L); var recovery = transaction @@ -3416,10 +3245,9 @@ void createdNoCaptureRecoveryRetainsPositiveClosureWithoutInventingEitherRosterR assertThat(closed.getRecoveryUuid()).isEqualTo(recovery.getRecoveryUuid()); assertThat(closed.getCanonicalRosterReceipt()).isEmpty(); assertThat(closed.getCanonicalPlayerCreatedRosterReceipt()).isEmpty(); - assertThatThrownBy( - () -> - transaction.execute( - ignored -> repository.recordPlayerCreated(original, fixture.roster()))) + assertThatThrownBy(() -> + transaction.execute( + ignored -> repository.recordPlayerCreated(original, fixture.roster()))) .hasMessageContaining("RECOVERY_FENCED"); Thread.sleep(550L); assertThat( @@ -3446,17 +3274,16 @@ void createdNoCaptureRecoveryRetainsPositiveClosureWithoutInventingEitherRosterR void completeCreatedSelectedRetirementFreezesInventoryEvenWithoutDispatchFlag() throws Exception { var fixture = createdFixture(true); var original = fixture.original(); - transaction.executeWithoutResult( - ignored -> { - repository.begin(original); - repository.reserveSelectionInput(original, selectionInput()); - repository.recordPlayerCreated(original, fixture.roster()); - repository.selectOriginal( - original, UUID.fromString(fixture.selected().getSelectedCharacterUuid())); - repository.recordSelectedPlayerCreatedCharacter(original, fixture.selected()); - repository.completeSelection( - original, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.SELECTED); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(original); + repository.reserveSelectionInput(original, selectionInput()); + repository.recordPlayerCreated(original, fixture.roster()); + repository.selectOriginal( + original, UUID.fromString(fixture.selected().getSelectedCharacterUuid())); + repository.recordSelectedPlayerCreatedCharacter(original, fixture.selected()); + repository.completeSelection( + original, CanonicalGameplayRosterReferenceRepository.SelectionOutcome.SELECTED); + }); Thread.sleep(5L); assertThat( transaction.execute( @@ -3536,10 +3363,9 @@ void actual1017To1020UpgradePreservesPriorHistoryOriginalBytesAndXmin() throws E var upgraded = migrate(previousSource, previousSchema, "1020"); assertThat(upgraded.getConfiguration().isOutOfOrder()).isFalse(); assertThat(upgraded.info().applied()) - .allSatisfy( - info -> - assertThat(info.getState()) - .isNotEqualTo(org.flywaydb.core.api.MigrationState.OUT_OF_ORDER)); + .allSatisfy(info -> + assertThat(info.getState()) + .isNotEqualTo(org.flywaydb.core.api.MigrationState.OUT_OF_ORDER)); var after = previous.fetch("SELECT * FROM flyway_schema_history ORDER BY installed_rank").intoMaps(); assertThat(after.subList(0, before.size())).containsExactlyElementsOf(before); @@ -3767,11 +3593,10 @@ private static CreatedFixture createdFixture(boolean oneActor) throws Exception private CanonicalGameplayRosterReferenceRepository.TargetCandidate retireOriginal( GetCanonicalGameplayRosterReferenceRequest request) throws Exception { - transaction.executeWithoutResult( - ignored -> { - repository.begin(request); - repository.completeUnissuedDenied(request); - }); + transaction.executeWithoutResult(ignored -> { + repository.begin(request); + repository.completeUnissuedDenied(request); + }); Thread.sleep(5L); assertThat( transaction.execute( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepositoryPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepositoryPostgresIntegrationTest.java index f016f12c78..19f88de646 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepositoryPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepositoryPostgresIntegrationTest.java @@ -66,19 +66,17 @@ void serializesFirstAllocationPreservesRestartMappingAndRejectsGlobalCrossVersio CanonicalGameplayTenantGameplayTagRepository.Assignment second; try { Future firstFuture = - executor.submit( - () -> { - ready.countDown(); - await(start); - return versionOne.assignmentForTransition(candidateA.transitionId()); - }); + executor.submit(() -> { + ready.countDown(); + await(start); + return versionOne.assignmentForTransition(candidateA.transitionId()); + }); Future secondFuture = - executor.submit( - () -> { - ready.countDown(); - await(start); - return versionOne.assignmentForTransition(candidateA.transitionId()); - }); + executor.submit(() -> { + ready.countDown(); + await(start); + return versionOne.assignmentForTransition(candidateA.transitionId()); + }); assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); start.countDown(); first = firstFuture.get(30, TimeUnit.SECONDS); @@ -132,21 +130,17 @@ void serializesFirstAllocationPreservesRestartMappingAndRejectsGlobalCrossVersio assertThatThrownBy(() -> CanonicalGameplaySessionRedisKeys.session(first, foreignBindingRef)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("persisted tenant assignment"); - assertThatThrownBy( - () -> - new CanonicalGameplayTenantGameplayTagRepository( - dsl, targetB.targetNamespace(), 2) - .assignmentForTransition(candidateA.transitionId())) + assertThatThrownBy(() -> + new CanonicalGameplayTenantGameplayTagRepository(dsl, targetB.targetNamespace(), 2) + .assignmentForTransition(candidateA.transitionId())) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("configured Game Session workload"); // Simulate a future-version candidate colliding with the immutable version-one owner. - assertThatThrownBy( - () -> - new CanonicalGameplayTenantGameplayTagRepository( - dsl, targetB.targetNamespace(), 2) - .assignmentForTransitionWithCandidate( - candidateB.transitionId(), 2, first.tenantGameplayTag())) + assertThatThrownBy(() -> + new CanonicalGameplayTenantGameplayTagRepository(dsl, targetB.targetNamespace(), 2) + .assignmentForTransitionWithCandidate( + candidateB.transitionId(), 2, first.tenantGameplayTag())) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("already owned by a different tenant"); assertThat( @@ -236,53 +230,48 @@ void barrierTargetAssignmentLocksControlBeforeIntentAndTarget() throws Exception ExecutorService executor = Executors.newFixedThreadPool(2); try { Future controlOwner = - executor.submit( - () -> - holderDsl.transactionResult( - configuration -> { - DSLContext transaction = DSL.using(configuration); - if (transaction.fetchOne( - "SELECT account_id FROM" - + " game_session_canonical_account_coverage_control" - + " WHERE account_id = ? FOR UPDATE", - candidate.accountId()) - == null) { - throw new IllegalStateException( - "Current account control row is missing"); - } - controlRowLocked.countDown(); - await(allowIntentAndTargetLocks); - if (transaction.fetchOne( - "SELECT operation_id FROM" - + " game_session_canonical_account_admission_fence_intent" - + " WHERE operation_id = ? AND intent_state =" - + " 'ACQUISITION_INTENT' FOR UPDATE NOWAIT", - operationId) - == null) { - throw new IllegalStateException( - "Current acquisition intent is missing"); - } - if (transaction.fetchOne( - "SELECT operation_id FROM" - + " game_session_canonical_account_admission_fence_intent_barrier_target" - + " WHERE operation_id = ? AND target_ordinal = 0" - + " AND target_state = 'REQUIRED' FOR UPDATE NOWAIT", - operationId) - == null) { - throw new IllegalStateException("Current barrier target is missing"); - } - intentAndTargetLocked.countDown(); - await(releaseControl); - return Boolean.TRUE; - })); + executor.submit(() -> + holderDsl.transactionResult(configuration -> { + DSLContext transaction = DSL.using(configuration); + if (transaction.fetchOne( + "SELECT account_id FROM" + + " game_session_canonical_account_coverage_control" + + " WHERE account_id = ? FOR UPDATE", + candidate.accountId()) + == null) { + throw new IllegalStateException("Current account control row is missing"); + } + controlRowLocked.countDown(); + await(allowIntentAndTargetLocks); + if (transaction.fetchOne( + "SELECT operation_id FROM" + + " game_session_canonical_account_admission_fence_intent" + + " WHERE operation_id = ? AND intent_state =" + + " 'ACQUISITION_INTENT' FOR UPDATE NOWAIT", + operationId) + == null) { + throw new IllegalStateException("Current acquisition intent is missing"); + } + if (transaction.fetchOne( + "SELECT operation_id FROM" + + " game_session_canonical_account_admission_fence_intent_barrier_target" + + " WHERE operation_id = ? AND target_ordinal = 0" + + " AND target_state = 'REQUIRED' FOR UPDATE NOWAIT", + operationId) + == null) { + throw new IllegalStateException("Current barrier target is missing"); + } + intentAndTargetLocked.countDown(); + await(releaseControl); + return Boolean.TRUE; + })); try { assertThat(controlRowLocked.await(10, TimeUnit.SECONDS)).isTrue(); Future assignment = - executor.submit( - () -> - new CanonicalGameplayTenantGameplayTagRepository( - assignmentDsl, runtime.targetNamespace(), 1) - .assignmentForBarrierTarget(operationId, 0L)); + executor.submit(() -> + new CanonicalGameplayTenantGameplayTagRepository( + assignmentDsl, runtime.targetNamespace(), 1) + .assignmentForBarrierTarget(operationId, 0L)); awaitControlLockWait(dsl, assignmentApplicationName); // The reader is queued only on control: the control owner can still lock both later rows diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanPublicationOwnerTestFixtures.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanPublicationOwnerTestFixtures.java index d93f6ed68f..bb049fc568 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanPublicationOwnerTestFixtures.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanPublicationOwnerTestFixtures.java @@ -157,21 +157,20 @@ public static RealmPolicyPublishedEvidence.PublishedSet publishedSet( original.inputDigest()); var appliedEpochs = draft.affectedUnits().stream() - .map( - unit -> - Map.of( - "aggregateType", - unit.aggregateType(), - "aggregateId", - unit.aggregateId(), - "scopeType", - unit.scopeType(), - "scopeId", - unit.scopeId(), - "expectedEpoch", - unit.expectedEpoch(), - "resultingEpoch", - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .map(unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) .toList(); String vector = new String( @@ -223,30 +222,28 @@ public static RealmPolicyPublishedEvidence.PublishedSet publishedSet( new AccountPublicationAuthorizationBinding.PreallocationInput( original.actorAccountId(), selected), java.util.Arrays.stream(SourceKind.values()) - .flatMap( - kind -> { - if (kind == SourceKind.RECENT_REAUTH_POLICY) { - return java.util.stream.Stream.of( - recentReauthenticationPolicyEvidence("PLATFORM", 300L, 30L), - recentReauthenticationPolicyEvidence("DEPLOYMENT", 240L, 30L)); - } - return java.util.stream.Stream.of( - new SourceEvidence( - kind, - switch (kind) { - case ACCOUNT, GLOBAL_ROLES -> - original.actorAccountId().toString(); - case TENANT -> source.canonicalTenantId().toString(); - case MEMBERSHIP -> - original.actorAccountId() + "/" + source.canonicalTenantId(); - default -> "TEST_ONLY-" + kind; - }, - "1", - "1", - null, - null, - ("TEST_ONLY-" + kind).getBytes(StandardCharsets.UTF_8))); - }) + .flatMap(kind -> { + if (kind == SourceKind.RECENT_REAUTH_POLICY) { + return java.util.stream.Stream.of( + recentReauthenticationPolicyEvidence("PLATFORM", 300L, 30L), + recentReauthenticationPolicyEvidence("DEPLOYMENT", 240L, 30L)); + } + return java.util.stream.Stream.of( + new SourceEvidence( + kind, + switch (kind) { + case ACCOUNT, GLOBAL_ROLES -> original.actorAccountId().toString(); + case TENANT -> source.canonicalTenantId().toString(); + case MEMBERSHIP -> + original.actorAccountId() + "/" + source.canonicalTenantId(); + default -> "TEST_ONLY-" + kind; + }, + "1", + "1", + null, + null, + ("TEST_ONLY-" + kind).getBytes(StandardCharsets.UTF_8))); + }) .toList()); String workflow = PublicationDigestRequestBinding.full( @@ -319,22 +316,20 @@ public static RealmPolicyPublishedEvidence.PublishedSet publishedSet( var capture = new RealmPolicySnapshot(draft, "1", policySources); var participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new GameDesignPublicationTerminalEvidence.Participant( - owner, - Long.toString(versionRowId), - null, - draft.commitId().toString(), - "WORLD_MANAGEMENT".equals(owner) - ? world.request().contentDigest() - : "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, - AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, - null, - null)) + .map(owner -> + new GameDesignPublicationTerminalEvidence.Participant( + owner, + Long.toString(versionRowId), + null, + draft.commitId().toString(), + "WORLD_MANAGEMENT".equals(owner) + ? world.request().contentDigest() + : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, + null, + null)) .toList(); var release = new GameDesignPublicationTerminalEvidence.ReleaseContent( @@ -360,27 +355,25 @@ public static RealmPolicyPublishedEvidence.PublishedSet publishedSet( publicationVersionStateEpoch); var policies = policySources.stream() - .map( - policySource -> { - String policyIdentitySuffix = - policySource.policy().realmSlug().equals(request.realmSlug()) - ? "" - : ":" + policySource.policy().realmSlug(); - UUID policyId = - id("policy-identity:" + request.requestId() + policyIdentitySuffix); - return new RealmPolicyPublishedEvidence.Policy( + .map(policySource -> { + String policyIdentitySuffix = + policySource.policy().realmSlug().equals(request.realmSlug()) + ? "" + : ":" + policySource.policy().realmSlug(); + UUID policyId = id("policy-identity:" + request.requestId() + policyIdentitySuffix); + return new RealmPolicyPublishedEvidence.Policy( + policyId, + policySource, + RealmPolicyPublishedEvidence.policyDigest( policyId, - policySource, - RealmPolicyPublishedEvidence.policyDigest( - policyId, - target, - 1, - bundleRef, - release.contentDigest(), - workflow, - release.manifestHash(), - policySource)); - }) + target, + 1, + bundleRef, + release.contentDigest(), + workflow, + release.manifestHash(), + policySource)); + }) .toList(); var frame = new ByteArrayOutputStream(); DraftAuthorizationFenceBinding.frame(frame, "game-design-realm-policy-source-capture/v1"); @@ -460,19 +453,18 @@ private static SourceEvidence recentReauthenticationPolicyEvidence( var release = terminal.releaseContent(); var participants = release.participantDigests().stream() - .map( - participant -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - participant.participantKey(), - Long.toString(descriptor.versionId()), - false, - null, - publishedSet.sourceCommitId().toString(), - participant.contentDigest(), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - participant.participantKey()), - participant.abilitySchemaDigest() != null, - participant.abilitySchemaDigest())) + .map(participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + Long.toString(descriptor.versionId()), + false, + null, + publishedSet.sourceCommitId().toString(), + participant.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participant.participantKey()), + participant.abilitySchemaDigest() != null, + participant.abilitySchemaDigest())) .toList(); var evidence = AuthoredWorldReleaseAttestationEvidence.create( @@ -686,19 +678,18 @@ private static SourceEvidence recentReauthenticationPolicyEvidence( .setCanonicalVersionId(publishedSet.target().canonicalVersionId().toString()); release .participantDigests() - .forEach( - participant -> { - var item = - net.firedevops.firemud.gamedesign.v1.ParticipantDigest.newBuilder() - .setParticipantKey(participant.participantKey()) - .setScopeValue(participant.scopeValue()) - .setAppliedCommitId(participant.appliedCommitId()) - .setContentDigest(participant.contentDigest()) - .setDigestSchemaVersion(participant.digestSchemaVersion()); - if (participant.abilitySchemaDigest() != null) - item.setAbilitySchemaDigest(participant.abilitySchemaDigest()); - proto.addParticipantDigests(item); - }); + .forEach(participant -> { + var item = + net.firedevops.firemud.gamedesign.v1.ParticipantDigest.newBuilder() + .setParticipantKey(participant.participantKey()) + .setScopeValue(participant.scopeValue()) + .setAppliedCommitId(participant.appliedCommitId()) + .setContentDigest(participant.contentDigest()) + .setDigestSchemaVersion(participant.digestSchemaVersion()); + if (participant.abilitySchemaDigest() != null) + item.setAbilitySchemaDigest(participant.abilitySchemaDigest()); + proto.addParticipantDigests(item); + }); var initialRequest = new net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence .Request( @@ -778,15 +769,14 @@ private WorldPublishedStartLocationEvidence build(DraftCommitBinding draft) thro .thenComparing(AffectedUnit::scopeType) .thenComparing(AffectedUnit::scopeId) .thenComparing(AffectedUnit::expectedEpoch)) - .map( - u -> - new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( - u.owner().name(), - u.aggregateType(), - u.aggregateId(), - u.scopeType(), - u.scopeId(), - u.expectedEpoch())) + .map(u -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + u.owner().name(), + u.aggregateType(), + u.aggregateId(), + u.scopeType(), + u.scopeId(), + u.expectedEpoch())) .toList(); var request = new WorldPublishedStartLocationEvidence.Request( @@ -891,23 +881,22 @@ private DraftAuthorizationFenceBinding.OwnerReadback committedReadback( result.put( "appliedEpochs", draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - Map.of( - "aggregateType", - unit.aggregateType(), - "aggregateId", - unit.aggregateId(), - "scopeType", - unit.scopeType(), - "scopeId", - unit.scopeId(), - "expectedEpoch", - unit.expectedEpoch(), - "resultingEpoch", - new java.math.BigInteger(unit.expectedEpoch()) - .add(java.math.BigInteger.ONE) - .toString())) + .map(unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new java.math.BigInteger(unit.expectedEpoch()) + .add(java.math.BigInteger.ONE) + .toString())) .toList()); return new DraftAuthorizationFenceBinding.OwnerReadback( Owner.WORLD, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanRuntimeCompletionRepositoryPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanRuntimeCompletionRepositoryPostgresIntegrationTest.java index 31f3f0dd83..c71d053277 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanRuntimeCompletionRepositoryPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalHumanRuntimeCompletionRepositoryPostgresIntegrationTest.java @@ -208,35 +208,24 @@ void independentAutocommitConnectionCannotBorrowAnAmbientSpringTransaction() thr new CanonicalHumanRuntimeCompletionRepository(independentDsl, "canonical-intent-it"); harness .transactions() - .executeWithoutResult( - status -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()) - .isTrue(); - assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) - .isFalse(); - assertThat( - harness - .dsl() - .fetchSingle("SHOW transaction_isolation") - .get(0, String.class)) - .isEqualTo("read committed"); - assertThat( - independentDsl - .fetchSingle("SELECT pg_backend_pid()") - .get(0, Integer.class)) - .isNotEqualTo( - harness - .dsl() - .fetchSingle("SELECT pg_backend_pid()") - .get(0, Integer.class)); - assertThatThrownBy( - () -> - completion.completeProtected( - prepared.request(), prepared.protection(), prepared.worldProof())) - .isInstanceOf(IllegalStateException.class) - .hasMessage( - "Human runtime completion requires a writable READ COMMITTED transaction"); - }); + .executeWithoutResult(status -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + assertThat( + harness.dsl().fetchSingle("SHOW transaction_isolation").get(0, String.class)) + .isEqualTo("read committed"); + assertThat( + independentDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)) + .isNotEqualTo( + harness.dsl().fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + assertThatThrownBy(() -> + completion.completeProtected( + prepared.request(), prepared.protection(), prepared.worldProof())) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Human runtime completion requires a writable READ COMMITTED transaction"); + }); } assertThat( harness @@ -267,20 +256,17 @@ void manualCompletionRequiresActiveWritableReadCommittedTransaction() throws Exc var completion = new CanonicalHumanRuntimeCompletionRepository(harness.dsl(), "canonical-intent-it"); Record before = runtime(harness, prepared); - assertThatThrownBy( - () -> - completion.completeProtected( - prepared.request(), prepared.protection(), prepared.worldProof())) + assertThatThrownBy(() -> + completion.completeProtected( + prepared.request(), prepared.protection(), prepared.worldProof())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("writable READ COMMITTED transaction"); var readOnly = new TransactionTemplate(harness.transactionManager()); readOnly.setReadOnly(true); - assertThatThrownBy( - () -> - readOnly.executeWithoutResult( - status -> - completion.completeProtected( - prepared.request(), prepared.protection(), prepared.worldProof()))) + assertThatThrownBy(() -> + readOnly.executeWithoutResult(status -> + completion.completeProtected( + prepared.request(), prepared.protection(), prepared.worldProof()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("writable READ COMMITTED transaction"); for (int isolation : @@ -289,12 +275,10 @@ void manualCompletionRequiresActiveWritableReadCommittedTransaction() throws Exc TransactionDefinition.ISOLATION_SERIALIZABLE)) { var transaction = new TransactionTemplate(harness.transactionManager()); transaction.setIsolationLevel(isolation); - assertThatThrownBy( - () -> - transaction.executeWithoutResult( - status -> - completion.completeProtected( - prepared.request(), prepared.protection(), prepared.worldProof()))) + assertThatThrownBy(() -> + transaction.executeWithoutResult(status -> + completion.completeProtected( + prepared.request(), prepared.protection(), prepared.worldProof()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("writable READ COMMITTED transaction"); } @@ -480,10 +464,8 @@ void worldFailureLeavesProtectedAttemptPendingUntilExactExplicitAbort() throws E .isEqualTo(aborted); assertThat(acquisitionCalls).hasValue(1); assertThat(retryAcquisitionCalls).hasValue(0); - assertThatThrownBy( - () -> - abortCoordinator.abort( - prepared.request(), accountRequest, "different abort reason")) + assertThatThrownBy(() -> + abortCoordinator.abort(prepared.request(), accountRequest, "different abort reason")) .isInstanceOf( CanonicalInitialAdmissionRepository.CanonicalInitialAdmissionConflictException.class); assertThat(acquisitionCalls).hasValue(1); @@ -685,16 +667,12 @@ void completionRechecksTheLiveOriginalOwnerAfterProtectedReservation() throws Ex Thread.sleep(10L); } - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> - completion.completeProtected( - prepared.request(), - prepared.protection(), - prepared.worldProof()))) + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult(status -> + completion.completeProtected( + prepared.request(), prepared.protection(), prepared.worldProof()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Account protection original owner lease is no longer live"); assertThat(runtime(harness, prepared).formatJSON()).isEqualTo(before.formatJSON()); @@ -732,14 +710,12 @@ void completesStartingThenCommitsAdmissionWithoutCouplingTheTransactions() throw prepared.protection().accountProtectionId(), 2L, prepared.original()); - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> - completion.completeProtected( - prepared.request(), changedFence, prepared.worldProof()))) + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult(status -> + completion.completeProtected( + prepared.request(), changedFence, prepared.worldProof()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("different Account protection"); var changedEpochProof = @@ -762,14 +738,12 @@ void completesStartingThenCommitsAdmissionWithoutCouplingTheTransactions() throw prepared.request().holdId(), prepared.request().holdFence(), prepared.request().holdBindingDigest()); - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> - completion.completeProtected( - prepared.request(), prepared.protection(), changedEpochProof))) + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult(status -> + completion.completeProtected( + prepared.request(), prepared.protection(), changedEpochProof))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("does not match"); assertThat(runtime(harness, prepared).formatJSON()).isEqualTo(before.formatJSON()); @@ -778,10 +752,9 @@ void completesStartingThenCommitsAdmissionWithoutCouplingTheTransactions() throw Objects.requireNonNull( harness .transactions() - .execute( - status -> - completion.completeProtected( - prepared.request(), prepared.protection(), prepared.worldProof()))); + .execute(status -> + completion.completeProtected( + prepared.request(), prepared.protection(), prepared.worldProof()))); Record running = runtime(harness, prepared); assertThat(running.get("status", String.class)).isEqualTo("RUNNING"); @@ -798,19 +771,17 @@ void completesStartingThenCommitsAdmissionWithoutCouplingTheTransactions() throw Objects.requireNonNull( harness .transactions() - .execute( - status -> - completion.completeProtected( - prepared.request(), prepared.protection(), prepared.worldProof()))); + .execute(status -> + completion.completeProtected( + prepared.request(), prepared.protection(), prepared.worldProof()))); assertThat(replay).isEqualTo(result); assertNoAdmissionEffects(harness, prepared.request()); harness .transactions() - .executeWithoutResult( - status -> - admission.commitProtected( - prepared.request(), prepared.protection(), prepared.worldProof())); + .executeWithoutResult(status -> + admission.commitProtected( + prepared.request(), prepared.protection(), prepared.worldProof())); assertThat(attemptStatus(harness, prepared.request())).isEqualTo("COMMITTED"); assertThat(ownerCount(harness, "gameplay_admission_pointer", prepared.request())).isOne(); assertThat(ownerCount(harness, "gameplay_admission_pointer_event", prepared.request())) @@ -837,40 +808,32 @@ void completionAndDefinitiveAbortUseOnePhysicalRealmFence() throws Exception { var abortPid = new AtomicInteger(); var completing = - executor.submit( - () -> - captureFailure( - () -> - harness - .transactions() - .executeWithoutResult( - status -> { - completionPid.set(postgresPid(harness)); - lockTarget(harness, prepared.request()); - completionLocked.countDown(); - await(releaseCompletion); - completion.completeProtected( - prepared.request(), - prepared.protection(), - prepared.worldProof()); - }))); + executor.submit(() -> + captureFailure(() -> + harness + .transactions() + .executeWithoutResult(status -> { + completionPid.set(postgresPid(harness)); + lockTarget(harness, prepared.request()); + completionLocked.countDown(); + await(releaseCompletion); + completion.completeProtected( + prepared.request(), prepared.protection(), prepared.worldProof()); + }))); assertThat(completionLocked.await(10, TimeUnit.SECONDS)).isTrue(); var aborting = - executor.submit( - () -> - captureFailure( - () -> - harness - .transactions() - .executeWithoutResult( - status -> { - abortPid.set(postgresPid(harness)); - abortEntered.countDown(); - admission.abortProtected( - prepared.request(), - prepared.protection(), - "serialized after runtime completion"); - }))); + executor.submit(() -> + captureFailure(() -> + harness + .transactions() + .executeWithoutResult(status -> { + abortPid.set(postgresPid(harness)); + abortEntered.countDown(); + admission.abortProtected( + prepared.request(), + prepared.protection(), + "serialized after runtime completion"); + }))); assertThat(abortEntered.await(10, TimeUnit.SECONDS)).isTrue(); awaitBlocked(harness, abortPid.get(), completionPid.get()); releaseCompletion.countDown(); @@ -899,23 +862,16 @@ void abortBeforeCompletionFencesRunningAndWritesNoPointerOrAudit() throws Except reserveProtection(harness, admission, prepared); harness .transactions() - .executeWithoutResult( - status -> - admission.abortProtected( - prepared.request(), - prepared.protection(), - "controlled pre-completion abort")); + .executeWithoutResult(status -> + admission.abortProtected( + prepared.request(), prepared.protection(), "controlled pre-completion abort")); - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> - completion.completeProtected( - prepared.request(), - prepared.protection(), - prepared.worldProof()))) + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult(status -> + completion.completeProtected( + prepared.request(), prepared.protection(), prepared.worldProof()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("nonterminal protected reservation"); assertThat(runtime(harness, prepared).get("status", String.class)).isEqualTo("STARTING"); @@ -943,10 +899,9 @@ void upgradedStartingHistoryCompletesWithoutBackfillOrPointerEffects() throws Ex new CanonicalHumanRuntimeCompletionRepository(harness.dsl(), "canonical-intent-it"); harness .transactions() - .executeWithoutResult( - status -> - completion.completeProtected( - prepared.request(), prepared.protection(), prepared.worldProof())); + .executeWithoutResult(status -> + completion.completeProtected( + prepared.request(), prepared.protection(), prepared.worldProof())); assertThat(runtime(harness, prepared).get("status", String.class)).isEqualTo("RUNNING"); assertThat(attemptStatus(harness, prepared.request())).isEqualTo("PENDING"); assertNoAdmissionEffects(harness, prepared.request()); @@ -978,10 +933,9 @@ void healthyHumanRunningRepositorySaveRetainsCompletionForLaterLeaseBoundDecisio harness.dsl(), target); // V1044 required equality with the immutable completion and refused this real owner save. - assertThatThrownBy( - () -> - CanonicalGameplayBindingRuntimeTestFixtures.markProvisional( - harness.dsl(), target, candidate)) + assertThatThrownBy(() -> + CanonicalGameplayBindingRuntimeTestFixtures.markProvisional( + harness.dsl(), target, candidate)) .hasMessageContaining("exact current RUNNING launch row and candidate identity"); harness.migrateLatest(); @@ -997,13 +951,12 @@ void healthyHumanRunningRepositorySaveRetainsCompletionForLaterLeaseBoundDecisio .get("status", String.class)) .isEqualTo("PROVISIONAL"); assertThat(completionImage(harness)).isEqualTo(originalCompletion); - assertThatThrownBy( - () -> - harness - .dsl() - .execute( - "UPDATE game_session_canonical_human_runtime_completion" - + " SET completed_running_row_version = completed_running_row_version + 1")) + assertThatThrownBy(() -> + harness + .dsl() + .execute( + "UPDATE game_session_canonical_human_runtime_completion" + + " SET completed_running_row_version = completed_running_row_version + 1")) .hasMessageContaining("Canonical Human runtime completion evidence is immutable"); assertThat(completionImage(harness)).isEqualTo(originalCompletion); } finally { @@ -1041,10 +994,9 @@ void humanCompletionStillRefusesStoppedMismatchedAndEarlierRuntimeDecisions() th CanonicalGameplayBindingRuntimeTestFixtures.seedCandidateAndPreparedTransition( harness.dsl(), target); - assertThatThrownBy( - () -> - CanonicalGameplayBindingRuntimeTestFixtures.markProvisional( - harness.dsl(), target, candidate)) + assertThatThrownBy(() -> + CanonicalGameplayBindingRuntimeTestFixtures.markProvisional( + harness.dsl(), target, candidate)) .as("Human runtime source mismatch %s", mismatch) .hasMessageContaining("exact current RUNNING launch row and candidate identity"); @@ -1159,11 +1111,10 @@ private static Prepared prepareStarting( holdRequest, uuid(idBase), uuid(idBase + 1)); harness .transactions() - .executeWithoutResult( - status -> - target - .intents() - .reserveHumanStarting(holdRequest, target.lifecycleRequest(uuid(idBase + 2)))); + .executeWithoutResult(status -> + target + .intents() + .reserveHumanStarting(holdRequest, target.lifecycleRequest(uuid(idBase + 2)))); harness .transactions() .executeWithoutResult(status -> target.intents().attachHumanStarting(holdRequest, hold)); @@ -1179,10 +1130,9 @@ private static void reserveProtection( Prepared prepared) { harness .transactions() - .executeWithoutResult( - status -> - admission.reserveProtectedStartingForRuntimeCompletion( - prepared.request(), prepared.protection())); + .executeWithoutResult(status -> + admission.reserveProtectedStartingForRuntimeCompletion( + prepared.request(), prepared.protection())); } private static Original original( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java index 5bb239fc5d..d90873c732 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java @@ -108,10 +108,9 @@ void humanStartingIntentRefusesAnExpiredOriginalOwnerWithoutEffects() throws Exc Thread.sleep(10L); } - assertThatThrownBy( - () -> - harness.transactions.execute( - status -> target.intents().reserveHumanStarting(request, lifecycle))) + assertThatThrownBy(() -> + harness.transactions.execute( + status -> target.intents().reserveHumanStarting(request, lifecycle))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Exact canonical pins are required before STARTING"); assertThat( @@ -135,10 +134,8 @@ void reservesExactIntentAndAttachesOnlyTheMatchingWorldIdentity() throws java.sq new net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity( request, uuid(411), uuid(412)); - assertThatThrownBy( - () -> - harness.transactions.execute( - status -> target.intents().attach(request, identity))) + assertThatThrownBy(() -> + harness.transactions.execute(status -> target.intents().attach(request, identity))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("must commit before World hold identity attachment"); assertNoAdmissionMutation(harness.dsl); @@ -155,15 +152,14 @@ void reservesExactIntentAndAttachesOnlyTheMatchingWorldIdentity() throws java.sq target.intents().read(target.targetNamespace(), request.initialAdmissionRequestId())) .contains(reserved); - harness.transactions.execute( - status -> { - harness.dsl.execute( - "UPDATE game_instances SET row_version = row_version + 1 " - + "WHERE tenant_id = ? AND id = ?", - target.gameSessionTenantId(), - target.gameInstanceId()); - return null; - }); + harness.transactions.execute(status -> { + harness.dsl.execute( + "UPDATE game_instances SET row_version = row_version + 1 " + + "WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()); + return null; + }); CanonicalInitialAdmissionIntentSnapshot retry = harness.transactions.execute(status -> target.intents().reserve(request, lifecycle)); assertThat(retry).isEqualTo(reserved); @@ -192,34 +188,30 @@ void reservesExactIntentAndAttachesOnlyTheMatchingWorldIdentity() throws java.sq .isEqualTo(target.catalog().sourceIntakeReceipt().intakeRequestId()); assertPendingIntentVisibleFromSeparateConnection(harness, request, lifecycle); var changedLifecycle = target.lifecycleRequest(uuid(413)); - assertThatThrownBy( - () -> - harness.transactions.execute( - status -> target.intents().reserve(request, changedLifecycle))) + assertThatThrownBy(() -> + harness.transactions.execute( + status -> target.intents().reserve(request, changedLifecycle))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("retained request or locked owner source binding"); var changedDigest = withDigest(request, "b".repeat(64)); - assertThatThrownBy( - () -> - harness.transactions.execute( - status -> target.intents().reserve(changedDigest, lifecycle))) + assertThatThrownBy(() -> + harness.transactions.execute( + status -> target.intents().reserve(changedDigest, lifecycle))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("does not bind the complete initial-admission input"); var changedSource = withInstance(request, uuid(414)); - assertThatThrownBy( - () -> - harness.transactions.execute( - status -> target.intents().reserve(changedSource, lifecycle))) + assertThatThrownBy(() -> + harness.transactions.execute( + status -> target.intents().reserve(changedSource, lifecycle))) .isInstanceOf(IllegalStateException.class); var competingRequest = holdRequest(target, "intent-other-request"); var competingLifecycle = target.lifecycleRequest(uuid(415)); - assertThatThrownBy( - () -> - harness.transactions.execute( - status -> target.intents().reserve(competingRequest, competingLifecycle))) + assertThatThrownBy(() -> + harness.transactions.execute( + status -> target.intents().reserve(competingRequest, competingLifecycle))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("already owns this realm"); @@ -240,10 +232,9 @@ void reservesExactIntentAndAttachesOnlyTheMatchingWorldIdentity() throws java.sq var changedIdentity = new net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity( request, uuid(416), uuid(417)); - assertThatThrownBy( - () -> - harness.transactions.execute( - status -> target.intents().attach(request, changedIdentity))) + assertThatThrownBy(() -> + harness.transactions.execute( + status -> target.intents().attach(request, changedIdentity))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("cannot accept a changed hold identity"); assertThat( @@ -331,68 +322,59 @@ void rollbackLeavesNoIntentAndRowVersionRegressionBlocksRetry() { var request = holdRequest(target, "intent-runtime-version"); var lifecycle = target.lifecycleRequest(uuid(420)); - assertThatThrownBy( - () -> - harness.transactions.execute( - status -> { - target.intents().reserve(request, lifecycle); - throw new IllegalStateException("force owner rollback"); - })) + assertThatThrownBy(() -> + harness.transactions.execute(status -> { + target.intents().reserve(request, lifecycle); + throw new IllegalStateException("force owner rollback"); + })) .hasMessageContaining("force owner rollback"); assertThat( target.intents().read(target.targetNamespace(), request.initialAdmissionRequestId())) .isEmpty(); assertNoAdmissionMutation(harness.dsl); - harness.transactions.execute( - status -> { - harness.dsl.execute( - "UPDATE game_instances SET row_version = row_version + 1 " - + "WHERE tenant_id = ? AND id = ?", - target.gameSessionTenantId(), - target.gameInstanceId()); - return null; - }); + harness.transactions.execute(status -> { + harness.dsl.execute( + "UPDATE game_instances SET row_version = row_version + 1 " + + "WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()); + return null; + }); CanonicalInitialAdmissionIntentSnapshot reserved = harness.transactions.execute(status -> target.intents().reserve(request, lifecycle)); - harness.transactions.execute( - status -> { - harness.dsl.execute( - "UPDATE game_instances SET row_version = row_version + 1 " - + "WHERE tenant_id = ? AND id = ?", - target.gameSessionTenantId(), - target.gameInstanceId()); - return null; - }); + harness.transactions.execute(status -> { + harness.dsl.execute( + "UPDATE game_instances SET row_version = row_version + 1 " + + "WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()); + return null; + }); CanonicalInitialAdmissionIntentSnapshot monotonicRetry = harness.transactions.execute(status -> target.intents().reserve(request, lifecycle)); assertThat(monotonicRetry).isEqualTo(reserved); assertThat(monotonicRetry.sourceBinding().currentRowVersion()) .isEqualTo(reserved.sourceBinding().currentRowVersion()); - harness.transactions.execute( - status -> { - harness.dsl.execute( - "UPDATE game_instances SET row_version = ? WHERE tenant_id = ? AND id = ?", - reserved.sourceBinding().currentRowVersion() - 1, - target.gameSessionTenantId(), - target.gameInstanceId()); - return null; - }); + harness.transactions.execute(status -> { + harness.dsl.execute( + "UPDATE game_instances SET row_version = ? WHERE tenant_id = ? AND id = ?", + reserved.sourceBinding().currentRowVersion() - 1, + target.gameSessionTenantId(), + target.gameInstanceId()); + return null; + }); var identity = new net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity( request, uuid(421), uuid(422)); - assertThatThrownBy( - () -> - harness.transactions.execute( - status -> target.intents().reserve(request, lifecycle))) + assertThatThrownBy(() -> + harness.transactions.execute(status -> target.intents().reserve(request, lifecycle))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("retained request or locked owner source binding"); - assertThatThrownBy( - () -> - harness.transactions.execute( - status -> target.intents().attach(request, identity))) + assertThatThrownBy(() -> + harness.transactions.execute(status -> target.intents().attach(request, identity))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("retained request or locked owner source binding"); assertThat( @@ -424,10 +406,9 @@ void retryRejectsRuntimeVersionDescriptorAndCatalogChanges() { holdRequest( target, request.initialAdmissionRequestId(), target.catalog().catalogRevision() + 1); - assertThatThrownBy( - () -> - harness.transactions.execute( - status -> target.intents().reserve(changedCatalogRequest, lifecycle))) + assertThatThrownBy(() -> + harness.transactions.execute( + status -> target.intents().reserve(changedCatalogRequest, lifecycle))) .isInstanceOf( GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException.class) .hasMessageContaining("missing or stale"); @@ -456,15 +437,13 @@ private static void assertRuntimeSourceMutationRejected(String updateSql) { target.gameSessionTenantId(), target.gameInstanceId())); - assertThatThrownBy( - () -> - harness.transactions.execute( - status -> { - harness.dsl.execute( - updateSql, target.gameSessionTenantId(), target.gameInstanceId()); - target.intents().reserve(request, lifecycle); - return null; - })) + assertThatThrownBy(() -> + harness.transactions.execute(status -> { + harness.dsl.execute( + updateSql, target.gameSessionTenantId(), target.gameInstanceId()); + target.intents().reserve(request, lifecycle); + return null; + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("complete launch binding"); Record runtimeSourceAfterRollback = @@ -862,15 +841,13 @@ private OwnerTarget seed(boolean completeRunning, Duration ownerLease) { Objects.requireNonNull( transactions.execute( status -> sourceRepository.register(INTAKE_REQUEST, freshSource()))); - transactions.execute( - status -> - new GameSessionFreshTenantAssociationRepository(dsl) - .associateFresh( - ASSOCIATION_OPERATION, - NAMESPACE, - source, - CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( - source.source()))); + transactions.execute(status -> + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + ASSOCIATION_OPERATION, + NAMESPACE, + source, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(source.source()))); var preparedCatalog = catalogRepository.prepareInitialPublicProduction( catalogRequest(source), publishedPolicy(source)); @@ -932,33 +909,32 @@ private UUID createTestOnlyFreshMappingAndLaunch( CanonicalHumanPublicationOwnerTestFixtures.pinLaunch( dsl, transactions, tuple, source.source(), publishedPolicy(source), binding, ownerLease); return Objects.requireNonNull( - transactions.execute( - status -> { - var association = - new GameSessionFreshTenantAssociationRepository(dsl) - .associateFresh( - ASSOCIATION_OPERATION, - NAMESPACE, - source, - CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( - source.source())); - var starting = - new GameSessionCanonicalStartingInstanceRepository(dsl, NAMESPACE) - .createStarting( - association, - binding, - ACTOR, - tuple.controlPlaneRequestId(), - tuple.mutationDigest(), - tuple); - if (completeRunning) { - dsl.execute( - "UPDATE game_instances SET status = 'RUNNING' WHERE tenant_id = ? AND id = ?", - association.legacyGameSessionTenantId(), - starting.gameInstanceId()); - } - return starting.gameInstanceUuid(); - }), + transactions.execute(status -> { + var association = + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + ASSOCIATION_OPERATION, + NAMESPACE, + source, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( + source.source())); + var starting = + new GameSessionCanonicalStartingInstanceRepository(dsl, NAMESPACE) + .createStarting( + association, + binding, + ACTOR, + tuple.controlPlaneRequestId(), + tuple.mutationDigest(), + tuple); + if (completeRunning) { + dsl.execute( + "UPDATE game_instances SET status = 'RUNNING' WHERE tenant_id = ? AND id = ?", + association.legacyGameSessionTenantId(), + starting.gameInstanceId()); + } + return starting.gameInstanceUuid(); + }), "Actual owner-allocated canonical instance UUID"); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionProtectedWriterPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionProtectedWriterPostgresIntegrationTest.java index af2ee3e76a..1d4e56da94 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionProtectedWriterPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionProtectedWriterPostgresIntegrationTest.java @@ -107,32 +107,25 @@ void closedCreationCompletesWhileProtectedNoPriorReservationWaitsForItsCatalog() prepared.request().initialAdmissionRequestId()) .formatJSON(); Future closedResult = - executor.submit( - () -> - captureFailure( - () -> - harness - .transactions() - .executeWithoutResult( - status -> { - closedPid.set(postgresBackendPid(harness)); - pointers.createInitialClosed(closed); - }))); + executor.submit(() -> + captureFailure(() -> + harness + .transactions() + .executeWithoutResult(status -> { + closedPid.set(postgresBackendPid(harness)); + pointers.createInitialClosed(closed); + }))); assertThat(closedCatalogLocked.await(10, TimeUnit.SECONDS)).isTrue(); Future protectedResult = - executor.submit( - () -> - captureFailure( - () -> - harness - .transactions() - .executeWithoutResult( - status -> { - protectedPid.set(postgresBackendPid(harness)); - protectedEntered.countDown(); - repository.reserveProtected( - prepared.request(), prepared.protection()); - }))); + executor.submit(() -> + captureFailure(() -> + harness + .transactions() + .executeWithoutResult(status -> { + protectedPid.set(postgresBackendPid(harness)); + protectedEntered.countDown(); + repository.reserveProtected(prepared.request(), prepared.protection()); + }))); assertThat(protectedEntered.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(protectedPid.get()).isNotEqualTo(closedPid.get()); awaitBlockingEdge(harness, protectedPid.get(), closedPid.get()); @@ -262,25 +255,20 @@ public ExpectedClosedEvidence lockExpectedClosedForRealm( .formatJSON(); // Current-origin refusal is controlled; this does not produce an independently OPEN route. rejectCurrentOrigin.set(true); - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> - repository.commitProtected( - prepared.request(), - prepared.protection(), - prepared.worldProof()))) + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult(status -> + repository.commitProtected( + prepared.request(), prepared.protection(), prepared.worldProof()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("controlled current-origin refusal"); assertThat(currentOriginReads).hasValue(2); harness .transactions() - .executeWithoutResult( - status -> - repository.abortProtected( - prepared.request(), prepared.protection(), "controlled upstream denial")); + .executeWithoutResult(status -> + repository.abortProtected( + prepared.request(), prepared.protection(), "controlled upstream denial")); Record aborted = terminal(harness, prepared.request()); assertThat(aborted.get("status", String.class)).isEqualTo("ABORTED"); assertThat(aborted.get("prior_pointer_request_id", UUID.class)).isEqualTo(origin.requestId()); @@ -298,10 +286,9 @@ public ExpectedClosedEvidence lockExpectedClosedForRealm( .orElseThrow(); harness .transactions() - .executeWithoutResult( - status -> - repository.abortProtected( - prepared.request(), prepared.protection(), "controlled upstream denial")); + .executeWithoutResult(status -> + repository.abortProtected( + prepared.request(), prepared.protection(), "controlled upstream denial")); assertThat(terminal(harness, prepared.request()).formatJSON()) .isEqualTo(aborted.formatJSON()); assertThat( @@ -399,20 +386,19 @@ void protectedClosedAbortRetainsImmutableOriginAfterSyntheticCurrentPointerRemov try { harness .transactions() - .executeWithoutResult( - status -> - assertThat( - harness - .dsl() - .execute( - "DELETE FROM gameplay_admission_pointer WHERE id = ? " - + "AND representation_version = 2 AND target_namespace = ? " - + "AND canonical_tenant_id = ? AND realm_id = ?", - pointerId, - catalog.targetNamespace(), - catalog.tenantId(), - catalog.realmId())) - .isEqualTo(1)); + .executeWithoutResult(status -> + assertThat( + harness + .dsl() + .execute( + "DELETE FROM gameplay_admission_pointer WHERE id = ? " + + "AND representation_version = 2 AND target_namespace = ? " + + "AND canonical_tenant_id = ? AND realm_id = ?", + pointerId, + catalog.targetNamespace(), + catalog.tenantId(), + catalog.realmId())) + .isEqualTo(1)); } finally { harness .dsl() @@ -450,12 +436,9 @@ void protectedClosedAbortRetainsImmutableOriginAfterSyntheticCurrentPointerRemov harness .transactions() - .executeWithoutResult( - status -> - repository.abortProtected( - prepared.request(), - prepared.protection(), - "synthetic current pointer missing")); + .executeWithoutResult(status -> + repository.abortProtected( + prepared.request(), prepared.protection(), "synthetic current pointer missing")); Record aborted = terminal(harness, prepared.request()); assertThat(aborted.get("status", String.class)).isEqualTo("ABORTED"); assertThat(aborted.get("prior_pointer_request_id", UUID.class)).isEqualTo(origin.requestId()); @@ -478,12 +461,9 @@ void protectedClosedAbortRetainsImmutableOriginAfterSyntheticCurrentPointerRemov .orElseThrow(); harness .transactions() - .executeWithoutResult( - status -> - repository.abortProtected( - prepared.request(), - prepared.protection(), - "synthetic current pointer missing")); + .executeWithoutResult(status -> + repository.abortProtected( + prepared.request(), prepared.protection(), "synthetic current pointer missing")); assertThat(terminal(harness, prepared.request()).formatJSON()) .isEqualTo(aborted.formatJSON()); assertThat( @@ -543,12 +523,11 @@ void commitsOneProtectionBoundPointerAuditAttemptAndIntentWithExactReplay() thro .isEqualTo(prepared.protection().accountProtectionId()); assertThat(pending.get("account_protection_evidence_bytes", byte[].class)) .containsExactly(prepared.protection().canonicalBytes()); - assertThatThrownBy( - () -> - new AccountInitialAdmissionProtectionBindingRepository(harness.dsl()) - .read( - prepared.request().targetNamespace(), - prepared.request().initialAdmissionRequestId())) + assertThatThrownBy(() -> + new AccountInitialAdmissionProtectionBindingRepository(harness.dsl()) + .read( + prepared.request().targetNamespace(), + prepared.request().initialAdmissionRequestId())) .isInstanceOf(IllegalStateException.class) .hasMessage("Protected admission has no immutable terminal result"); @@ -569,54 +548,49 @@ void commitsOneProtectionBoundPointerAuditAttemptAndIntentWithExactReplay() thro prepared.original(), "changed-controlled-account-source"); for (var changed : List.of(changedId, changedFence, changedBytes)) { - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> repository.reserveProtected(prepared.request(), changed))) + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult( + status -> repository.reserveProtected(prepared.request(), changed))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("different Account protection"); assertThat(terminal(harness, prepared.request()).formatJSON()) .isEqualTo(pending.formatJSON()); } - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> - harness - .dsl() - .execute( - "INSERT INTO game_session_canonical_initial_admission_attempt " - + "SELECT (jsonb_populate_record(NULL::game_session_canonical_initial_admission_attempt, " - + "to_jsonb(a) || jsonb_build_object(" - + "'initial_admission_request_id', ?, 'account_protection_id', NULL))).* " - + "FROM game_session_canonical_initial_admission_attempt a " - + "WHERE target_namespace = ? AND initial_admission_request_id = ?", - prepared.request().initialAdmissionRequestId() + "-partial", - prepared.request().targetNamespace(), - prepared.request().initialAdmissionRequestId()))) + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult(status -> + harness + .dsl() + .execute( + "INSERT INTO game_session_canonical_initial_admission_attempt " + + "SELECT (jsonb_populate_record(NULL::game_session_canonical_initial_admission_attempt, " + + "to_jsonb(a) || jsonb_build_object(" + + "'initial_admission_request_id', ?, 'account_protection_id', NULL))).* " + + "FROM game_session_canonical_initial_admission_attempt a " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + prepared.request().initialAdmissionRequestId() + "-partial", + prepared.request().targetNamespace(), + prepared.request().initialAdmissionRequestId()))) .rootCause() .hasMessageContaining("requires complete retained Account protection evidence"); assertThat(terminal(harness, prepared.request()).formatJSON()) .isEqualTo(pending.formatJSON()); - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> - harness - .dsl() - .execute( - "UPDATE game_session_canonical_initial_admission_attempt " - + "SET account_protection_id = ? WHERE target_namespace = ? " - + "AND initial_admission_request_id = ?", - uuid(599), - prepared.request().targetNamespace(), - prepared.request().initialAdmissionRequestId()))) + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult(status -> + harness + .dsl() + .execute( + "UPDATE game_session_canonical_initial_admission_attempt " + + "SET account_protection_id = ? WHERE target_namespace = ? " + + "AND initial_admission_request_id = ?", + uuid(599), + prepared.request().targetNamespace(), + prepared.request().initialAdmissionRequestId()))) .rootCause() .hasMessageContaining("immutable"); assertThat(terminal(harness, prepared.request()).formatJSON()) @@ -625,10 +599,9 @@ void commitsOneProtectionBoundPointerAuditAttemptAndIntentWithExactReplay() thro OffsetDateTime terminalBefore = databaseTimestamp(harness); harness .transactions() - .executeWithoutResult( - status -> - repository.commitProtected( - prepared.request(), prepared.protection(), prepared.worldProof())); + .executeWithoutResult(status -> + repository.commitProtected( + prepared.request(), prepared.protection(), prepared.worldProof())); OffsetDateTime terminalAfter = databaseTimestamp(harness); var proof = @@ -693,21 +666,18 @@ void commitsOneProtectionBoundPointerAuditAttemptAndIntentWithExactReplay() thro status -> repository.reserveProtected(prepared.request(), prepared.protection())); harness .transactions() - .executeWithoutResult( - status -> - repository.commitProtected( - prepared.request(), prepared.protection(), prepared.worldProof())); + .executeWithoutResult(status -> + repository.commitProtected( + prepared.request(), prepared.protection(), prepared.worldProof())); assertThat(terminal(harness, prepared.request()).formatJSON()) .isEqualTo(terminal.formatJSON()); - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> - repository.commitProtected( - prepared.request(), changedId, prepared.worldProof()))) + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult(status -> + repository.commitProtected( + prepared.request(), changedId, prepared.worldProof()))) .isInstanceOf( CanonicalInitialAdmissionRepository.CanonicalInitialAdmissionConflictException.class) .hasMessageContaining("changed Account protection"); @@ -736,14 +706,11 @@ void upgradeRetainsLegacyAllNullPendingWithoutAdoptingIt() throws Exception { Record after = terminal(harness, prepared.request()); assertThat(after.formatJSON()).isEqualTo(before.formatJSON()); CanonicalInitialAdmissionRepository repository = repository(harness); - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> - repository.reserveProtected( - prepared.request(), prepared.protection()))) + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult(status -> + repository.reserveProtected(prepared.request(), prepared.protection()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("PENDING admission reservation retains different"); assertThat(terminal(harness, prepared.request()).formatJSON()).isEqualTo(before.formatJSON()); @@ -768,10 +735,9 @@ void definitiveProtectedAbortWritesNoCommitOriginAndRejectsLaterCommit() throws OffsetDateTime terminalBefore = databaseTimestamp(harness); harness .transactions() - .executeWithoutResult( - status -> - repository.abortProtected( - prepared.request(), prepared.protection(), "controlled upstream denial")); + .executeWithoutResult(status -> + repository.abortProtected( + prepared.request(), prepared.protection(), "controlled upstream denial")); OffsetDateTime terminalAfter = databaseTimestamp(harness); Record terminal = terminal(harness, prepared.request()); @@ -806,20 +772,15 @@ void definitiveProtectedAbortWritesNoCommitOriginAndRejectsLaterCommit() throws harness .transactions() - .executeWithoutResult( - status -> - repository.abortProtected( - prepared.request(), prepared.protection(), "controlled upstream denial")); - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> - repository.commitProtected( - prepared.request(), - prepared.protection(), - prepared.worldProof()))) + .executeWithoutResult(status -> + repository.abortProtected( + prepared.request(), prepared.protection(), "controlled upstream denial")); + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult(status -> + repository.commitProtected( + prepared.request(), prepared.protection(), prepared.worldProof()))) .isInstanceOf( CanonicalInitialAdmissionRepository.CanonicalInitialAdmissionConflictException.class) .hasMessageContaining("ABORTED"); @@ -863,16 +824,12 @@ void pendingNoPriorAbortSurvivesAnIndependentlyCreatedClosedPointer() throws Exc pointers .readOriginalClosedOrigin(closeRequest.targetNamespace(), closeRequest.requestId()) .orElseThrow(); - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> - repository.commitProtected( - prepared.request(), - prepared.protection(), - prepared.worldProof()))) + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult(status -> + repository.commitProtected( + prepared.request(), prepared.protection(), prepared.worldProof()))) .isInstanceOf(RuntimeException.class) .hasMessageContaining("representation"); assertThat(terminal(harness, prepared.request()).get("status", String.class)) @@ -882,60 +839,53 @@ void pendingNoPriorAbortSurvivesAnIndependentlyCreatedClosedPointer() throws Exc "visible = false", "public_production = false", "catalog_revision = catalog_revision + 1")) { - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> - harness - .dsl() - .execute( - "UPDATE game_session_canonical_realm_catalog SET " - + mutation - + " WHERE target_namespace=? AND realm_id=?", - catalog.targetNamespace(), - catalog.realmId()))) + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult(status -> + harness + .dsl() + .execute( + "UPDATE game_session_canonical_realm_catalog SET " + + mutation + + " WHERE target_namespace=? AND realm_id=?", + catalog.targetNamespace(), + catalog.realmId()))) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("immutable"); } - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> - harness - .dsl() - .execute( - "UPDATE game_session_canonical_instance_launch SET public_production=false" - + " WHERE target_namespace=? AND game_instance_uuid=?", - catalog.targetNamespace(), - prepared.request().canonicalGameInstanceId()))) + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult(status -> + harness + .dsl() + .execute( + "UPDATE game_session_canonical_instance_launch SET public_production=false" + + " WHERE target_namespace=? AND game_instance_uuid=?", + catalog.targetNamespace(), + prepared.request().canonicalGameInstanceId()))) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("immutable"); - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> - harness - .dsl() - .execute( - "UPDATE gameplay_admission_pointer SET pointer_version=pointer_version+1" - + " WHERE target_namespace=? AND realm_id=?", - catalog.targetNamespace(), - catalog.realmId()))) + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult(status -> + harness + .dsl() + .execute( + "UPDATE gameplay_admission_pointer SET pointer_version=pointer_version+1" + + " WHERE target_namespace=? AND realm_id=?", + catalog.targetNamespace(), + catalog.realmId()))) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining( "Canonical CLOSED pointer may only enter the fenced first-OPEN operation"); harness .transactions() - .executeWithoutResult( - status -> - repository.abortProtected( - prepared.request(), prepared.protection(), "controlled upstream denial")); + .executeWithoutResult(status -> + repository.abortProtected( + prepared.request(), prepared.protection(), "controlled upstream denial")); Record terminal = terminal(harness, prepared.request()); assertThat(terminal.get("status", String.class)).isEqualTo("ABORTED"); assertThat(terminal.get("intent_state", String.class)).isEqualTo("TERMINAL"); @@ -943,10 +893,9 @@ void pendingNoPriorAbortSurvivesAnIndependentlyCreatedClosedPointer() throws Exc assertThat(terminal.get("audit_event_id")).isNull(); harness .transactions() - .executeWithoutResult( - status -> - repository.abortProtected( - prepared.request(), prepared.protection(), "controlled upstream denial")); + .executeWithoutResult(status -> + repository.abortProtected( + prepared.request(), prepared.protection(), "controlled upstream denial")); assertThat(terminal(harness, prepared.request()).formatJSON()) .isEqualTo(terminal.formatJSON()); assertThat( @@ -1077,16 +1026,12 @@ void expiredOriginalLeaseAllowsOnlyTheExactProtectedAbortAcrossForwardMigration( .isEqualTo(launchBefore.formatJSON()); awaitOriginalOwnerLeaseExpiration(harness, prepared); - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> - repository.commitProtected( - prepared.request(), - prepared.protection(), - prepared.worldProof()))) + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult(status -> + repository.commitProtected( + prepared.request(), prepared.protection(), prepared.worldProof()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("original owner lease is no longer live"); assertThat(terminal(harness, prepared.request()).formatJSON()) @@ -1094,12 +1039,11 @@ void expiredOriginalLeaseAllowsOnlyTheExactProtectedAbortAcrossForwardMigration( harness .transactions() - .executeWithoutResult( - status -> - repository.abortProtected( - prepared.request(), - prepared.protection(), - "controlled denial after original lease expiry")); + .executeWithoutResult(status -> + repository.abortProtected( + prepared.request(), + prepared.protection(), + "controlled denial after original lease expiry")); Record aborted = terminal(harness, prepared.request()); assertThat(aborted.get("status", String.class)).isEqualTo("ABORTED"); @@ -1178,40 +1122,33 @@ void expiredOriginalLeaseAllowsOnlyTheExactProtectedAbortAcrossForwardMigration( .isTrue(); harness .transactions() - .executeWithoutResult( - status -> - repository.abortProtected( - prepared.request(), - prepared.protection(), - "controlled denial after original lease expiry")); + .executeWithoutResult(status -> + repository.abortProtected( + prepared.request(), + prepared.protection(), + "controlled denial after original lease expiry")); assertThat(terminal(harness, prepared.request()).formatJSON()) .isEqualTo(aborted.formatJSON()); var changedProtection = protection(target, prepared.hold(), uuid(1005), 1L, prepared.original()); - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> - repository.abortProtected( - prepared.request(), - changedProtection, - "controlled denial after original lease expiry"))) + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult(status -> + repository.abortProtected( + prepared.request(), + changedProtection, + "controlled denial after original lease expiry"))) .isInstanceOf( CanonicalInitialAdmissionRepository.CanonicalInitialAdmissionConflictException.class) .hasMessageContaining("changed Account protection"); - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> - repository.commitProtected( - prepared.request(), - prepared.protection(), - prepared.worldProof()))) + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult(status -> + repository.commitProtected( + prepared.request(), prepared.protection(), prepared.worldProof()))) .isInstanceOf( CanonicalInitialAdmissionRepository.CanonicalInitialAdmissionConflictException.class) .hasMessageContaining("ABORTED"); @@ -1248,55 +1185,45 @@ private static void proveConcurrentTerminalRace(boolean commitWins, int idBase) var winnerPid = new AtomicInteger(); var loserPid = new AtomicInteger(); Future winner = - executor.submit( - () -> - captureFailure( - () -> - harness - .transactions() - .executeWithoutResult( - status -> { - winnerPid.set(postgresBackendPid(harness)); - lockAdmissionTarget(harness, prepared.request()); - winnerLocked.countDown(); - await(releaseWinner, "release terminal winner"); - if (commitWins) { - repository.commitProtected( - prepared.request(), - prepared.protection(), - prepared.worldProof()); - } else { - repository.abortProtected( - prepared.request(), - prepared.protection(), - "concurrent controlled denial"); - } - }))); + executor.submit(() -> + captureFailure(() -> + harness + .transactions() + .executeWithoutResult(status -> { + winnerPid.set(postgresBackendPid(harness)); + lockAdmissionTarget(harness, prepared.request()); + winnerLocked.countDown(); + await(releaseWinner, "release terminal winner"); + if (commitWins) { + repository.commitProtected( + prepared.request(), prepared.protection(), prepared.worldProof()); + } else { + repository.abortProtected( + prepared.request(), + prepared.protection(), + "concurrent controlled denial"); + } + }))); assertThat(winnerLocked.await(10, TimeUnit.SECONDS)).isTrue(); Future loser = - executor.submit( - () -> - captureFailure( - () -> - harness - .transactions() - .executeWithoutResult( - status -> { - loserPid.set(postgresBackendPid(harness)); - loserEntered.countDown(); - if (commitWins) { - repository.abortProtected( - prepared.request(), - prepared.protection(), - "concurrent controlled denial"); - } else { - repository.commitProtected( - prepared.request(), - prepared.protection(), - prepared.worldProof()); - } - }))); + executor.submit(() -> + captureFailure(() -> + harness + .transactions() + .executeWithoutResult(status -> { + loserPid.set(postgresBackendPid(harness)); + loserEntered.countDown(); + if (commitWins) { + repository.abortProtected( + prepared.request(), + prepared.protection(), + "concurrent controlled denial"); + } else { + repository.commitProtected( + prepared.request(), prepared.protection(), prepared.worldProof()); + } + }))); assertThat(loserEntered.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(loserPid.get()).isNotEqualTo(winnerPid.get()); awaitBlockingEdge(harness, loserPid.get(), winnerPid.get()); @@ -1338,20 +1265,17 @@ private static void proveConcurrentTerminalRace(boolean commitWins, int idBase) assertThat(terminal.get("abort_proof_digest")).isNull(); harness .transactions() - .executeWithoutResult( - status -> - repository.commitProtected( - prepared.request(), prepared.protection(), prepared.worldProof())); - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> - repository.abortProtected( - prepared.request(), - prepared.protection(), - "concurrent controlled denial"))) + .executeWithoutResult(status -> + repository.commitProtected( + prepared.request(), prepared.protection(), prepared.worldProof())); + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult(status -> + repository.abortProtected( + prepared.request(), + prepared.protection(), + "concurrent controlled denial"))) .isInstanceOf( CanonicalInitialAdmissionRepository.CanonicalInitialAdmissionConflictException .class) @@ -1364,20 +1288,15 @@ private static void proveConcurrentTerminalRace(boolean commitWins, int idBase) assertThat(terminal.get("abort_proof_digest", String.class)).startsWith("sha256:"); harness .transactions() - .executeWithoutResult( - status -> - repository.abortProtected( - prepared.request(), prepared.protection(), "concurrent controlled denial")); - assertThatThrownBy( - () -> - harness - .transactions() - .executeWithoutResult( - status -> - repository.commitProtected( - prepared.request(), - prepared.protection(), - prepared.worldProof()))) + .executeWithoutResult(status -> + repository.abortProtected( + prepared.request(), prepared.protection(), "concurrent controlled denial")); + assertThatThrownBy(() -> + harness + .transactions() + .executeWithoutResult(status -> + repository.commitProtected( + prepared.request(), prepared.protection(), prepared.worldProof()))) .isInstanceOf( CanonicalInitialAdmissionRepository.CanonicalInitialAdmissionConflictException .class) @@ -1558,11 +1477,10 @@ private static Prepared prepare( target .harness() .transactions() - .executeWithoutResult( - status -> - target - .intents() - .reserve(retainedHoldRequest, target.lifecycleRequest(uuid(idBase + 2)))); + .executeWithoutResult(status -> + target + .intents() + .reserve(retainedHoldRequest, target.lifecycleRequest(uuid(idBase + 2)))); target .harness() .transactions() @@ -1680,40 +1598,39 @@ private static void insertLegacyPending( CanonicalInitialAdmissionRequest request) { harness .transactions() - .executeWithoutResult( - status -> - harness - .dsl() - .execute( - "INSERT INTO game_session_canonical_initial_admission_attempt " - + "(target_namespace, initial_admission_request_id, request_digest, " - + "canonical_tenant_id, world_slug, realm_id, playable_state_namespace_id, " - + "playable_state_scope, canonical_game_instance_id, game_session_tenant_id, " - + "game_instance_id, canonical_version_id, runtime_version_id, " - + "expected_catalog_revision, origin_kind, expected_prior_pointer_version, " - + "active_lifecycle_epoch, hold_id, hold_fence, hold_binding_digest, status, " - + "created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " - + "?, ?, ?, ?, ?, ?, 'PENDING', clock_timestamp(), clock_timestamp())", - request.targetNamespace(), - request.initialAdmissionRequestId(), - request.requestDigest(), - request.canonicalTenantId(), - request.worldSlug(), - request.realmId(), - request.playableStateNamespaceId(), - request.playableStateScope(), - request.canonicalGameInstanceId(), - target.launch().association().gameSessionTenantId(), - target.launch().gameInstanceId(), - request.canonicalVersionId(), - target.launch().runtimeVersionId(), - request.expectedCatalogRevision(), - request.originKind().name(), - request.expectedPriorPointerVersion(), - request.activeLifecycleEpoch(), - request.holdId(), - request.holdFence(), - request.holdBindingDigest())); + .executeWithoutResult(status -> + harness + .dsl() + .execute( + "INSERT INTO game_session_canonical_initial_admission_attempt " + + "(target_namespace, initial_admission_request_id, request_digest, " + + "canonical_tenant_id, world_slug, realm_id, playable_state_namespace_id, " + + "playable_state_scope, canonical_game_instance_id, game_session_tenant_id, " + + "game_instance_id, canonical_version_id, runtime_version_id, " + + "expected_catalog_revision, origin_kind, expected_prior_pointer_version, " + + "active_lifecycle_epoch, hold_id, hold_fence, hold_binding_digest, status, " + + "created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "?, ?, ?, ?, ?, ?, 'PENDING', clock_timestamp(), clock_timestamp())", + request.targetNamespace(), + request.initialAdmissionRequestId(), + request.requestDigest(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + target.launch().association().gameSessionTenantId(), + target.launch().gameInstanceId(), + request.canonicalVersionId(), + target.launch().runtimeVersionId(), + request.expectedCatalogRevision(), + request.originKind().name(), + request.expectedPriorPointerVersion(), + request.activeLifecycleEpoch(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest())); } private static CanonicalInitialAdmissionRepository repository( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java index 3f733165f8..90633d4285 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java @@ -128,20 +128,19 @@ void historicalRealmOriginLookupRetainsExactClosedEvidenceAfterRetainedOpen() th long.class); lookup.setAccessible(true); var historical = - fixture.transactions.execute( - status -> { - try { - return lookup.invoke( - fixture.pointerRepository, - origin.targetNamespace(), - origin.canonicalTenantId(), - origin.realmId(), - origin.pointerVersion(), - origin.catalogRevision()); - } catch (ReflectiveOperationException exception) { - throw new IllegalStateException("Historical owner lookup failed", exception); - } - }); + fixture.transactions.execute(status -> { + try { + return lookup.invoke( + fixture.pointerRepository, + origin.targetNamespace(), + origin.canonicalTenantId(), + origin.realmId(), + origin.pointerVersion(), + origin.catalogRevision()); + } catch (ReflectiveOperationException exception) { + throw new IllegalStateException("Historical owner lookup failed", exception); + } + }); assertThat(historical).usingRecursiveComparison().isEqualTo(origin); assertThat(pointerAndAuditProjection(fixture)).isEqualTo(before); } @@ -217,11 +216,10 @@ void rosterRetirementUsesRealCommittedAdmissionReaderAndLocksCurrentPointerUnder java.time.Duration.ofMillis(1), java.time.Duration.ofSeconds(1), 8)); - fixture.transactions.executeWithoutResult( - status -> { - references.begin(request); - references.completeUnissuedDenied(request); - }); + fixture.transactions.executeWithoutResult(status -> { + references.begin(request); + references.completeUnissuedDenied(request); + }); byte[] retainedResponseBytes = references.find(request).orElseThrow().toByteArray(); String retained = fixture @@ -266,54 +264,49 @@ void rosterRetirementUsesRealCommittedAdmissionReaderAndLocksCurrentPointerUnder .class), new SimpleMeterRegistry()); // This is the actual guard hidden by the old whole-route mock. - assertThatThrownBy( - () -> - fixture.transactions.execute( - status -> - fixture.initialAdmissionRepository.readCurrentOpenSnapshotForRealm( - NAMESPACE, TENANT, current.realmId()))) + assertThatThrownBy(() -> + fixture.transactions.execute(status -> + fixture.initialAdmissionRepository.readCurrentOpenSnapshotForRealm( + NAMESPACE, TENANT, current.realmId()))) .isInstanceOf(IllegalStateException.class); try (var executor = java.util.concurrent.Executors.newFixedThreadPool(2)) { var retirement = new java.util.concurrent.atomic.AtomicReference>(); var recovery = new java.util.concurrent.atomic.AtomicReference>(); - fixture.transactions.executeWithoutResult( - status -> { - fixture.dsl.fetchSingle( - "SELECT id FROM gameplay_admission_pointer WHERE target_namespace = ? " - + "AND canonical_tenant_id = ? AND realm_id = ? FOR UPDATE", - NAMESPACE, - TENANT, - current.realmId()); - int pointerHolderPid = - Objects.requireNonNull( - fixture.dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); - retirement.set(executor.submit(() -> owner.retireTarget(request))); - try { - assertThat(lockAttempted.await(5L, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); - awaitBackendBlockedBy(fixture.dsl, retirementPid.get(), pointerHolderPid); - recovery.set( - executor.submit( - () -> - fixture.transactions.execute( - ignored -> { - recoveryPid.set( - Objects.requireNonNull( - fixture - .dsl - .fetchSingle("SELECT pg_backend_pid()") - .get(0, Integer.class))); - recoveryStarted.countDown(); - return references.begin(request); - }))); - assertThat(recoveryStarted.await(5L, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); - awaitBackendBlockedBy(fixture.dsl, recoveryPid.get(), retirementPid.get()); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(interrupted); - } - }); + fixture.transactions.executeWithoutResult(status -> { + fixture.dsl.fetchSingle( + "SELECT id FROM gameplay_admission_pointer WHERE target_namespace = ? " + + "AND canonical_tenant_id = ? AND realm_id = ? FOR UPDATE", + NAMESPACE, + TENANT, + current.realmId()); + int pointerHolderPid = + Objects.requireNonNull( + fixture.dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + retirement.set(executor.submit(() -> owner.retireTarget(request))); + try { + assertThat(lockAttempted.await(5L, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + awaitBackendBlockedBy(fixture.dsl, retirementPid.get(), pointerHolderPid); + recovery.set( + executor.submit(() -> + fixture.transactions.execute(ignored -> { + recoveryPid.set( + Objects.requireNonNull( + fixture + .dsl + .fetchSingle("SELECT pg_backend_pid()") + .get(0, Integer.class))); + recoveryStarted.countDown(); + return references.begin(request); + }))); + assertThat(recoveryStarted.await(5L, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + awaitBackendBlockedBy(fixture.dsl, recoveryPid.get(), retirementPid.get()); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + }); // Actual pointer supersession reaches the lock path; the stored minimum still protects it. assertThat(retirement.get().get(5L, java.util.concurrent.TimeUnit.SECONDS)).isFalse(); assertThatThrownBy(() -> recovery.get().get(5L, java.util.concurrent.TimeUnit.SECONDS)) @@ -375,40 +368,32 @@ void recoveryUsesRealCommittedV2PointerWithSyntheticRetainedV1Originals() throws .hasMessageContaining("active owner transaction"); var readOnly = new TransactionTemplate(fixture.transactionManager); readOnly.setReadOnly(true); - assertThatThrownBy( - () -> - readOnly.execute( - status -> - fixture.pointerRepository.lockOriginalClosedOrigin( - NAMESPACE, origin.requestId()))) + assertThatThrownBy(() -> + readOnly.execute(status -> + fixture.pointerRepository.lockOriginalClosedOrigin(NAMESPACE, origin.requestId()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("read-write transaction"); - assertThatThrownBy( - () -> - fixture.transactions.execute( - status -> - fixture.pointerRepository.readOriginalClosedOrigin( - NAMESPACE, origin.requestId()))) + assertThatThrownBy(() -> + fixture.transactions.execute(status -> + fixture.pointerRepository.readOriginalClosedOrigin(NAMESPACE, origin.requestId()))) .isInstanceOf(IllegalStateException.class); - fixture.transactions.executeWithoutResult( - status -> { - var lockedOrigin = - fixture - .pointerRepository - .lockOriginalClosedOrigin(NAMESPACE, origin.requestId()) - .orElseThrow(); - assertThat(lockedOrigin.requestId()).isEqualTo(origin.requestId()); - assertThat(lockedOrigin.requestDigest()).isEqualTo(origin.requestDigest()); - assertThat(lockedOrigin.receiptDigest()).isEqualTo(origin.receiptDigest()); - assertThat(lockedOrigin.auditEventId()).isEqualTo(origin.auditEventId()); - assertThat( - fixture.pointerRepository.lockOriginalClosedOrigin(NAMESPACE, UUID.randomUUID())) - .isEmpty(); - assertThat( - fixture.pointerRepository.lockOriginalClosedOrigin( - "substituted-namespace", origin.requestId())) - .isEmpty(); - }); + fixture.transactions.executeWithoutResult(status -> { + var lockedOrigin = + fixture + .pointerRepository + .lockOriginalClosedOrigin(NAMESPACE, origin.requestId()) + .orElseThrow(); + assertThat(lockedOrigin.requestId()).isEqualTo(origin.requestId()); + assertThat(lockedOrigin.requestDigest()).isEqualTo(origin.requestDigest()); + assertThat(lockedOrigin.receiptDigest()).isEqualTo(origin.receiptDigest()); + assertThat(lockedOrigin.auditEventId()).isEqualTo(origin.auditEventId()); + assertThat(fixture.pointerRepository.lockOriginalClosedOrigin(NAMESPACE, UUID.randomUUID())) + .isEmpty(); + assertThat( + fixture.pointerRepository.lockOriginalClosedOrigin( + "substituted-namespace", origin.requestId())) + .isEmpty(); + }); String originalOwnerRows = pointerAndAuditProjection(fixture); var references = new CanonicalGameplayRosterReferenceRepository( @@ -466,27 +451,25 @@ void recoveryUsesRealCommittedV2PointerWithSyntheticRetainedV1Originals() throws net.firedevops.firemud.gamesession.v1.CanonicalGameplayRosterSelectionInput.newBuilder() .setSchemaVersion(1) .build(); - fixture.transactions.executeWithoutResult( - status -> { - references.begin(missingRoster); - references.reserveSelectionInput(missingRoster, input); - references.markRosterReadStarted(missingRoster); - references.begin(missingAssignment); - references.reserveSelectionInput(missingAssignment, input); - references.markRosterReadStarted(missingAssignment); - references.record(missingAssignment, roster); - references.selectOriginal(missingAssignment, actor); - }); + fixture.transactions.executeWithoutResult(status -> { + references.begin(missingRoster); + references.reserveSelectionInput(missingRoster, input); + references.markRosterReadStarted(missingRoster); + references.begin(missingAssignment); + references.reserveSelectionInput(missingAssignment, input); + references.markRosterReadStarted(missingAssignment); + references.record(missingAssignment, roster); + references.selectOriginal(missingAssignment, actor); + }); Thread.sleep(5L); var recoveryClient = mock(net.firedevops.firemud.gamesession.client.CanonicalGameplayRosterRecoveryClient.class); org.mockito.Mockito.when(recoveryClient.read(any())) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - throw io.grpc.Status.UNAVAILABLE.asRuntimeException(); - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + throw io.grpc.Status.UNAVAILABLE.asRuntimeException(); + }); var admissions = org.mockito.Mockito.spy(fixture.initialAdmissionRepository); org.mockito.Mockito.doAnswer( call -> { @@ -604,11 +587,10 @@ void recoveryUsesRealCommittedV2PointerWithSyntheticRetainedV1Originals() throws .setSnapshotDigest(roster.getSnapshotDigest()) .setMinimumRetentionMillis(1L) .build(); - fixture.transactions.execute( - ignored -> - references.acknowledgeRetirement( - acknowledgement, - "spiffe://firemud/ns/" + NAMESPACE + "/sa/entity-management-service")); + fixture.transactions.execute(ignored -> + references.acknowledgeRetirement( + acknowledgement, + "spiffe://firemud/ns/" + NAMESPACE + "/sa/entity-management-service")); } assertThat( fixture.transactions.execute( @@ -662,10 +644,9 @@ void exactCurrentOpenLockRejectsUnjoinedDslConnectionInsideSpringTransaction() t new CanonicalInitialAdmissionRepository( unjoinedDsl, fixture.catalogRepository, fixture.pointerRepository); - assertThatThrownBy( - () -> - fixture.transactions.execute( - ignored -> admissions.lockExactCurrentOpenSnapshot(qualified))) + assertThatThrownBy(() -> + fixture.transactions.execute( + ignored -> admissions.lockExactCurrentOpenSnapshot(qualified))) .isInstanceOf(IllegalStateException.class) .hasMessage( "Exact current OPEN lock requires the DSL connection to join the owner transaction"); @@ -686,53 +667,49 @@ void exactCurrentOpenLockWaitsForCatalogBeforeAcquiringPointerLock() throws Exce java.util.concurrent.Future>(); try (var executor = java.util.concurrent.Executors.newSingleThreadExecutor()) { - fixture.transactions.executeWithoutResult( - ignored -> { - fixture.dsl.fetchSingle( - "SELECT realm_id FROM game_session_canonical_realm_catalog " - + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? " - + "FOR UPDATE", - NAMESPACE, - TENANT, - qualified.ownerProof().realmId()); - holderPid.set( - Objects.requireNonNull( - fixture.dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class))); - reader.set( - executor.submit( - () -> - fixture.transactions.execute( - transaction -> { - readerPid.set( - Objects.requireNonNull( - fixture - .dsl - .fetchSingle("SELECT pg_backend_pid()") - .get(0, Integer.class))); - readerStarted.countDown(); - return fixture.initialAdmissionRepository - .lockExactCurrentOpenSnapshot(qualified); - }))); - try { - assertThat(readerStarted.await(5L, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); - awaitBackendBlockedBy(fixture.dsl, readerPid.get(), holderPid.get()); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(interrupted); - } - assertThat( - fixture - .dsl - .fetchSingle( - "SELECT count(*) FROM pg_locks " - + "WHERE pid = ? " - + "AND relation = to_regclass('gameplay_admission_pointer') " - + "AND mode = 'RowShareLock' AND granted", - readerPid.get()) - .get(0, Long.class)) - .as("reader holds no OPEN pointer row-lock relation while catalog is contested") - .isZero(); - }); + fixture.transactions.executeWithoutResult(ignored -> { + fixture.dsl.fetchSingle( + "SELECT realm_id FROM game_session_canonical_realm_catalog " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? " + + "FOR UPDATE", + NAMESPACE, + TENANT, + qualified.ownerProof().realmId()); + holderPid.set( + Objects.requireNonNull( + fixture.dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class))); + reader.set( + executor.submit(() -> + fixture.transactions.execute(transaction -> { + readerPid.set( + Objects.requireNonNull( + fixture + .dsl + .fetchSingle("SELECT pg_backend_pid()") + .get(0, Integer.class))); + readerStarted.countDown(); + return fixture.initialAdmissionRepository.lockExactCurrentOpenSnapshot(qualified); + }))); + try { + assertThat(readerStarted.await(5L, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + awaitBackendBlockedBy(fixture.dsl, readerPid.get(), holderPid.get()); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + assertThat( + fixture + .dsl + .fetchSingle( + "SELECT count(*) FROM pg_locks " + + "WHERE pid = ? " + + "AND relation = to_regclass('gameplay_admission_pointer') " + + "AND mode = 'RowShareLock' AND granted", + readerPid.get()) + .get(0, Long.class)) + .as("reader holds no OPEN pointer row-lock relation while catalog is contested") + .isZero(); + }); assertThat(reader.get().get(5L, java.util.concurrent.TimeUnit.SECONDS)).isEqualTo(qualified); } } @@ -781,55 +758,54 @@ void freshHumanReservationDeniesBeforeEffectsAndRetainedPendingCannotCommit() th .isZero(); UUID mismatchedGameInstance = uuid(998); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "INSERT INTO gameplay_admission_pointer_event (" - + "world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " - + "game_instance_id, pointer_version, visible, requires_character_selection, " - + "state_scope, character_creation_policy, actor_principal, reason, " - + "control_plane_request_id, occurred_at, prepared_version_upgrade_id, " - + "public_production_realm, catalog_revision, realm_id, " - + "playable_state_namespace_id, representation_version, target_namespace, " - + "canonical_tenant_id, admission_state, canonical_game_instance_id, " - + "canonical_version_id, runtime_version_id, initial_admission_request_id, " - + "initial_admission_request_digest, initial_admission_origin_kind, " - + "initial_admission_prior_pointer_version, initial_admission_active_epoch, " - + "initial_admission_hold_id, initial_admission_hold_fence, " - + "initial_admission_hold_binding_digest) " - + "SELECT attempt.world_slug, catalog.realm_slug, catalog.source_world_display_name, " - + "catalog.realm_display_name, attempt.game_session_tenant_id, attempt.game_instance_id, " - + "CASE WHEN attempt.origin_kind = 'NO_PRIOR_POINTER' THEN 1 " - + "ELSE attempt.expected_prior_pointer_version + 1 END, catalog.visible, NULL, " - + "attempt.playable_state_scope, catalog.character_creation_policy, " - + "'game-session-canonical-initial-admission', 'World-held initial admission', " - + "attempt.initial_admission_request_id, CURRENT_TIMESTAMP, NULL, " - + "catalog.public_production, attempt.expected_catalog_revision, attempt.realm_id, " - + "attempt.playable_state_namespace_id, 3, attempt.target_namespace, " - + "attempt.canonical_tenant_id, 'OPEN', ?, attempt.canonical_version_id, " - + "attempt.runtime_version_id, attempt.initial_admission_request_id, " - + "attempt.request_digest, attempt.origin_kind, attempt.expected_prior_pointer_version, " - + "attempt.active_lifecycle_epoch, attempt.hold_id, attempt.hold_fence, " - + "attempt.hold_binding_digest " - + "FROM game_session_canonical_initial_admission_attempt attempt " - + "JOIN game_session_canonical_realm_catalog catalog " - + "ON catalog.target_namespace = attempt.target_namespace " - + "AND catalog.canonical_tenant_id = attempt.canonical_tenant_id " - + "AND catalog.realm_id = attempt.realm_id " - + "AND catalog.catalog_revision = attempt.expected_catalog_revision " - + "JOIN game_session_canonical_instance_launch launch " - + "ON launch.target_namespace = attempt.target_namespace " - + "AND launch.canonical_tenant_id = attempt.canonical_tenant_id " - + "AND launch.canonical_realm_id = attempt.realm_id " - + "AND launch.game_session_tenant_id = attempt.game_session_tenant_id " - + "AND launch.game_instance_id = attempt.game_instance_id " - + "AND launch.game_instance_uuid = attempt.canonical_game_instance_id " - + "AND launch.version_id = attempt.runtime_version_id " - + "WHERE attempt.target_namespace = ? " - + "AND attempt.initial_admission_request_id = ? AND attempt.status = 'PENDING'", - mismatchedGameInstance, - NAMESPACE, - request.initialAdmissionRequestId())) + assertThatThrownBy(() -> + fixture.dsl.execute( + "INSERT INTO gameplay_admission_pointer_event (" + + "world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, actor_principal, reason, " + + "control_plane_request_id, occurred_at, prepared_version_upgrade_id, " + + "public_production_realm, catalog_revision, realm_id, " + + "playable_state_namespace_id, representation_version, target_namespace, " + + "canonical_tenant_id, admission_state, canonical_game_instance_id, " + + "canonical_version_id, runtime_version_id, initial_admission_request_id, " + + "initial_admission_request_digest, initial_admission_origin_kind, " + + "initial_admission_prior_pointer_version, initial_admission_active_epoch, " + + "initial_admission_hold_id, initial_admission_hold_fence, " + + "initial_admission_hold_binding_digest) " + + "SELECT attempt.world_slug, catalog.realm_slug, catalog.source_world_display_name, " + + "catalog.realm_display_name, attempt.game_session_tenant_id, attempt.game_instance_id, " + + "CASE WHEN attempt.origin_kind = 'NO_PRIOR_POINTER' THEN 1 " + + "ELSE attempt.expected_prior_pointer_version + 1 END, catalog.visible, NULL, " + + "attempt.playable_state_scope, catalog.character_creation_policy, " + + "'game-session-canonical-initial-admission', 'World-held initial admission', " + + "attempt.initial_admission_request_id, CURRENT_TIMESTAMP, NULL, " + + "catalog.public_production, attempt.expected_catalog_revision, attempt.realm_id, " + + "attempt.playable_state_namespace_id, 3, attempt.target_namespace, " + + "attempt.canonical_tenant_id, 'OPEN', ?, attempt.canonical_version_id, " + + "attempt.runtime_version_id, attempt.initial_admission_request_id, " + + "attempt.request_digest, attempt.origin_kind, attempt.expected_prior_pointer_version, " + + "attempt.active_lifecycle_epoch, attempt.hold_id, attempt.hold_fence, " + + "attempt.hold_binding_digest " + + "FROM game_session_canonical_initial_admission_attempt attempt " + + "JOIN game_session_canonical_realm_catalog catalog " + + "ON catalog.target_namespace = attempt.target_namespace " + + "AND catalog.canonical_tenant_id = attempt.canonical_tenant_id " + + "AND catalog.realm_id = attempt.realm_id " + + "AND catalog.catalog_revision = attempt.expected_catalog_revision " + + "JOIN game_session_canonical_instance_launch launch " + + "ON launch.target_namespace = attempt.target_namespace " + + "AND launch.canonical_tenant_id = attempt.canonical_tenant_id " + + "AND launch.canonical_realm_id = attempt.realm_id " + + "AND launch.game_session_tenant_id = attempt.game_session_tenant_id " + + "AND launch.game_instance_id = attempt.game_instance_id " + + "AND launch.game_instance_uuid = attempt.canonical_game_instance_id " + + "AND launch.version_id = attempt.runtime_version_id " + + "WHERE attempt.target_namespace = ? " + + "AND attempt.initial_admission_request_id = ? AND attempt.status = 'PENDING'", + mismatchedGameInstance, + NAMESPACE, + request.initialAdmissionRequestId())) .hasMessageContaining("Numeric-only tenant scope cannot use a fresh source-bound key"); assertThat( fixture.initialAdmissionRepository.read(NAMESPACE, request.initialAdmissionRequestId())) @@ -842,16 +818,12 @@ void freshHumanReservationDeniesBeforeEffectsAndRetainedPendingCannotCommit() th .isZero(); for (int retry = 0; retry < 2; retry++) { - assertHumanProtectionUnavailable( - () -> - fixture.transactions.executeWithoutResult( - status -> - fixture.initialAdmissionRepository.commit(request, testWorldProof(request)))); - assertHumanProtectionUnavailable( - () -> - fixture.transactions.executeWithoutResult( - status -> - fixture.initialAdmissionRepository.abort(request, "Missing protection"))); + assertHumanProtectionUnavailable(() -> + fixture.transactions.executeWithoutResult(status -> + fixture.initialAdmissionRepository.commit(request, testWorldProof(request)))); + assertHumanProtectionUnavailable(() -> + fixture.transactions.executeWithoutResult( + status -> fixture.initialAdmissionRepository.abort(request, "Missing protection"))); assertThat(attemptProjection(fixture, request)).isEqualTo(before); assertThat( fixture.initialAdmissionRepository.read( @@ -939,11 +911,10 @@ void freshExpectedClosedHumanIntentDeniesBeforeEffects() { "canonical-initial-admission-test", "Create exact CLOSED origin"); var preparedClosed = fixture.pointerRepository.prepareInitialClosed(closeRequest); - fixture.transactions.execute( - status -> { - fixture.pointerRepository.createInitialClosed(preparedClosed); - return null; - }); + fixture.transactions.execute(status -> { + fixture.pointerRepository.createInitialClosed(preparedClosed); + return null; + }); CanonicalInitialAdmissionRequest unsupportedPriorVersion = initialAdmissionRequest( @@ -974,10 +945,9 @@ void freshExpectedClosedHumanIntentDeniesBeforeEffects() { assertHumanProtectionUnavailable( () -> fixture.initialAdmissionRepository.reserve(firstOpenRequest)); assertNoAttemptAndNoPending(fixture, firstOpenRequest); - assertHumanProtectionUnavailable( - () -> - fixture.initialAdmissionRepository.commit( - firstOpenRequest, testWorldProof(firstOpenRequest))); + assertHumanProtectionUnavailable(() -> + fixture.initialAdmissionRepository.commit( + firstOpenRequest, testWorldProof(firstOpenRequest))); assertHumanProtectionUnavailable( () -> fixture.initialAdmissionRepository.abort(firstOpenRequest, "Missing protection")); assertThat(pointerAndAuditProjection(fixture)).isEqualTo(closedBefore); @@ -1084,17 +1054,14 @@ void retainedPendingRowsPreserveUnprotectedTerminalWriteGuards() throws Exceptio terminalColumns.put("abort_proof_digest", "sha256:" + "f".repeat(64)); terminalColumns.put("terminal_at", terminalColumns.get("updated_at")); - assertThatThrownBy( - () -> - fixture.transactions.executeWithoutResult( - status -> - fixture - .dsl - .insertInto( - DSL.table( - DSL.name("game_session_canonical_initial_admission_attempt"))) - .set(terminalColumns) - .execute())) + assertThatThrownBy(() -> + fixture.transactions.executeWithoutResult(status -> + fixture + .dsl + .insertInto( + DSL.table(DSL.name("game_session_canonical_initial_admission_attempt"))) + .set(terminalColumns) + .execute())) .isInstanceOfSatisfying( DataAccessException.class, exception -> { @@ -1103,20 +1070,18 @@ void retainedPendingRowsPreserveUnprotectedTerminalWriteGuards() throws Exceptio .hasStackTraceContaining( "New canonical initial-admission attempts must begin PENDING"); }); - assertThatThrownBy( - () -> - fixture.transactions.executeWithoutResult( - status -> - fixture.dsl.execute( - "UPDATE game_session_canonical_initial_admission_attempt SET " - + "status = 'ABORTED', abort_reason = ?, abort_proof_digest = ?, " - + "updated_at = updated_at + INTERVAL '1 second', " - + "terminal_at = updated_at + INTERVAL '1 second' " - + "WHERE target_namespace = ? AND initial_admission_request_id = ?", - terminalColumns.get("abort_reason"), - terminalColumns.get("abort_proof_digest"), - NAMESPACE, - request.initialAdmissionRequestId()))) + assertThatThrownBy(() -> + fixture.transactions.executeWithoutResult(status -> + fixture.dsl.execute( + "UPDATE game_session_canonical_initial_admission_attempt SET " + + "status = 'ABORTED', abort_reason = ?, abort_proof_digest = ?, " + + "updated_at = updated_at + INTERVAL '1 second', " + + "terminal_at = updated_at + INTERVAL '1 second' " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + terminalColumns.get("abort_reason"), + terminalColumns.get("abort_proof_digest"), + NAMESPACE, + request.initialAdmissionRequestId()))) .isInstanceOfSatisfying( DataAccessException.class, exception -> @@ -1133,17 +1098,14 @@ void retainedPendingRowsPreserveUnprotectedTerminalWriteGuards() throws Exceptio "original_owner_fence")) { var partial = new HashMap<>(terminalColumns); putControlledPartialProtection(fixture, partial, missing); - assertThatThrownBy( - () -> - fixture.transactions.executeWithoutResult( - status -> - fixture - .dsl - .insertInto( - DSL.table( - DSL.name("game_session_canonical_initial_admission_attempt"))) - .set(partial) - .execute())) + assertThatThrownBy(() -> + fixture.transactions.executeWithoutResult(status -> + fixture + .dsl + .insertInto( + DSL.table(DSL.name("game_session_canonical_initial_admission_attempt"))) + .set(partial) + .execute())) .isInstanceOfSatisfying( DataAccessException.class, exception -> { @@ -1152,28 +1114,26 @@ void retainedPendingRowsPreserveUnprotectedTerminalWriteGuards() throws Exceptio .hasStackTraceContaining( "New canonical initial-admission attempts must begin PENDING"); }); - assertThatThrownBy( - () -> - fixture.transactions.executeWithoutResult( - status -> - fixture.dsl.execute( - "UPDATE game_session_canonical_initial_admission_attempt SET status = 'ABORTED', " - + "abort_reason = ?, abort_proof_digest = ?, updated_at = updated_at + INTERVAL '1 second', " - + "terminal_at = updated_at + INTERVAL '1 second', account_protection_evidence_version = ?, " - + "account_protection_id = ?, account_protection_fence = ?, original_owner_attempt_id = ?, " - + "original_owner_mutation_id = ?, original_owner_fence = ?, account_protection_evidence_bytes = ? " - + "WHERE target_namespace = ? AND initial_admission_request_id = ?", - partial.get("abort_reason"), - partial.get("abort_proof_digest"), - partial.get("account_protection_evidence_version"), - partial.get("account_protection_id"), - partial.get("account_protection_fence"), - partial.get("original_owner_attempt_id"), - partial.get("original_owner_mutation_id"), - partial.get("original_owner_fence"), - partial.get("account_protection_evidence_bytes"), - NAMESPACE, - request.initialAdmissionRequestId()))) + assertThatThrownBy(() -> + fixture.transactions.executeWithoutResult(status -> + fixture.dsl.execute( + "UPDATE game_session_canonical_initial_admission_attempt SET status = 'ABORTED', " + + "abort_reason = ?, abort_proof_digest = ?, updated_at = updated_at + INTERVAL '1 second', " + + "terminal_at = updated_at + INTERVAL '1 second', account_protection_evidence_version = ?, " + + "account_protection_id = ?, account_protection_fence = ?, original_owner_attempt_id = ?, " + + "original_owner_mutation_id = ?, original_owner_fence = ?, account_protection_evidence_bytes = ? " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + partial.get("abort_reason"), + partial.get("abort_proof_digest"), + partial.get("account_protection_evidence_version"), + partial.get("account_protection_id"), + partial.get("account_protection_fence"), + partial.get("original_owner_attempt_id"), + partial.get("original_owner_mutation_id"), + partial.get("original_owner_fence"), + partial.get("account_protection_evidence_bytes"), + NAMESPACE, + request.initialAdmissionRequestId()))) .isInstanceOfSatisfying( DataAccessException.class, exception -> @@ -1363,19 +1323,16 @@ void pre1006CommittedAndAbortedRowsSurviveForwardProtectionMigration() throws Ex .containsOnlyNulls(); assertHumanProtectionUnavailable( () -> predecessor.initialAdmissionRepository.commit(request, testWorldProof(request))); - assertHumanProtectionUnavailable( - () -> - predecessor.initialAdmissionRepository.abort( - request, "Current Human retry remains unprotected")); - assertThatThrownBy( - () -> - predecessor.transactions.executeWithoutResult( - status -> - predecessor.dsl.execute( - "UPDATE game_session_canonical_initial_admission_attempt SET updated_at = updated_at + INTERVAL '1 second' " - + "WHERE target_namespace = ? AND initial_admission_request_id = ?", - NAMESPACE, - request.initialAdmissionRequestId()))) + assertHumanProtectionUnavailable(() -> + predecessor.initialAdmissionRepository.abort( + request, "Current Human retry remains unprotected")); + assertThatThrownBy(() -> + predecessor.transactions.executeWithoutResult(status -> + predecessor.dsl.execute( + "UPDATE game_session_canonical_initial_admission_attempt SET updated_at = updated_at + INTERVAL '1 second' " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + NAMESPACE, + request.initialAdmissionRequestId()))) .isInstanceOf(DataAccessException.class); assertThat(predecessorAttemptProjection(predecessor, request)).isEqualTo(originalAttempt); assertThat(pointerAndAuditProjection(predecessor)).isEqualTo(originalPointerAndAudit); @@ -1422,14 +1379,12 @@ void malformedProtectedOriginalHistoryFailsCorrectionWithoutChangingRowsGuardsOr "ALTER TABLE game_session_canonical_initial_admission_attempt DISABLE TRIGGER " + "game_session_canonical_initial_admission_v44_terminal_evidence"); try { - fixture.transactions.executeWithoutResult( - status -> - fixture - .dsl - .insertInto( - DSL.table(DSL.name("game_session_canonical_initial_admission_attempt"))) - .set(partial) - .execute()); + fixture.transactions.executeWithoutResult(status -> + fixture + .dsl + .insertInto(DSL.table(DSL.name("game_session_canonical_initial_admission_attempt"))) + .set(partial) + .execute()); } finally { fixture.dsl.execute( "ALTER TABLE game_session_canonical_initial_admission_attempt ENABLE TRIGGER " @@ -1510,15 +1465,14 @@ private static PredecessorAdmission preparePre1006Admission(Fixture fixture) thr IntakeReceipt source = fixture.registerSource(); var association = Objects.requireNonNull( - fixture.transactions.execute( - status -> - new GameSessionFreshTenantAssociationRepository(fixture.dsl) - .associateFresh( - ASSOCIATION_OPERATION, - NAMESPACE, - source, - CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( - source.source())))); + fixture.transactions.execute(status -> + new GameSessionFreshTenantAssociationRepository(fixture.dsl) + .associateFresh( + ASSOCIATION_OPERATION, + NAMESPACE, + source, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( + source.source())))); var request = catalogRequest(source); var policy = publishedPolicy(source); // This preparation is compatible with1005 and validates the complete closed policy/source @@ -1600,70 +1554,69 @@ private static PredecessorAdmission preparePre1006Admission(Fixture fixture) thr catalogDigest, receiptDigest, source); - fixture.transactions.executeWithoutResult( - status -> { - fixture.dsl.execute( - "INSERT INTO gameplay_tenant_shared_playable_state_namespace (tenant_id, " - + "playable_state_namespace_id, canonical_tenant_id, target_namespace, " - + "source_intake_operation_id, source_intake_schema_version, source_intake_request_id, " - + "source_intake_request_digest, source_intake_receipt_digest, source_schema_version, " - + "source_registration_request_id, source_operation_id, source_request_digest, " - + "source_game_row_id, source_game_tenant_key, source_provenance_kind, source_evidence_digest) " - + "VALUES (NULL, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - namespace, - TENANT, - NAMESPACE, - source.operationId(), - source.intakeRequestId(), - source.requestDigest(), - source.receiptDigest(), - authored.schemaVersion(), - authored.registrationRequestId(), - authored.operationId(), - authored.requestDigest(), - authored.sourceGameRowId(), - authored.sourceGameTenantKey(), - authored.provenanceKind(), - authored.evidenceDigest()); - fixture.dsl.execute( - "INSERT INTO game_session_canonical_realm_catalog (target_namespace, canonical_tenant_id, " - + "tenant_slug, world_slug, realm_id, realm_slug, realm_display_name, visible, " - + "public_production, state_scope, playable_state_namespace_id, character_creation_policy, " - + "catalog_revision, creation_request_id, request_digest, receipt_digest, " - + "source_intake_operation_id, source_intake_schema_version, source_intake_request_id, " - + "source_intake_request_digest, source_intake_receipt_digest, source_schema_version, " - + "source_registration_request_id, source_operation_id, source_request_digest, " - + "source_world_display_name, source_game_row_id, source_game_tenant_key, " - + "source_provenance_kind, source_evidence_digest, complete_policy_set_evidence) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, TRUE, TRUE, 'SHARED', ?, ?, 1, ?, ?, ?, ?, 1, " - + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - NAMESPACE, - TENANT, - authored.tenantSlug(), - authored.worldSlug(), - realm, - request.realmSlug(), - request.realmDisplayName(), - namespace, - request.characterCreationPolicy(), - request.requestId(), - catalogDigest, - receiptDigest, - source.operationId(), - source.intakeRequestId(), - source.requestDigest(), - source.receiptDigest(), - authored.schemaVersion(), - authored.registrationRequestId(), - authored.operationId(), - authored.requestDigest(), - authored.worldDisplayName(), - authored.sourceGameRowId(), - authored.sourceGameTenantKey(), - authored.provenanceKind(), - authored.evidenceDigest(), - policyBytes); - }); + fixture.transactions.executeWithoutResult(status -> { + fixture.dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace (tenant_id, " + + "playable_state_namespace_id, canonical_tenant_id, target_namespace, " + + "source_intake_operation_id, source_intake_schema_version, source_intake_request_id, " + + "source_intake_request_digest, source_intake_receipt_digest, source_schema_version, " + + "source_registration_request_id, source_operation_id, source_request_digest, " + + "source_game_row_id, source_game_tenant_key, source_provenance_kind, source_evidence_digest) " + + "VALUES (NULL, ?, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + namespace, + TENANT, + NAMESPACE, + source.operationId(), + source.intakeRequestId(), + source.requestDigest(), + source.receiptDigest(), + authored.schemaVersion(), + authored.registrationRequestId(), + authored.operationId(), + authored.requestDigest(), + authored.sourceGameRowId(), + authored.sourceGameTenantKey(), + authored.provenanceKind(), + authored.evidenceDigest()); + fixture.dsl.execute( + "INSERT INTO game_session_canonical_realm_catalog (target_namespace, canonical_tenant_id, " + + "tenant_slug, world_slug, realm_id, realm_slug, realm_display_name, visible, " + + "public_production, state_scope, playable_state_namespace_id, character_creation_policy, " + + "catalog_revision, creation_request_id, request_digest, receipt_digest, " + + "source_intake_operation_id, source_intake_schema_version, source_intake_request_id, " + + "source_intake_request_digest, source_intake_receipt_digest, source_schema_version, " + + "source_registration_request_id, source_operation_id, source_request_digest, " + + "source_world_display_name, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, source_evidence_digest, complete_policy_set_evidence) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, TRUE, TRUE, 'SHARED', ?, ?, 1, ?, ?, ?, ?, 1, " + + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + NAMESPACE, + TENANT, + authored.tenantSlug(), + authored.worldSlug(), + realm, + request.realmSlug(), + request.realmDisplayName(), + namespace, + request.characterCreationPolicy(), + request.requestId(), + catalogDigest, + receiptDigest, + source.operationId(), + source.intakeRequestId(), + source.requestDigest(), + source.receiptDigest(), + authored.schemaVersion(), + authored.registrationRequestId(), + authored.operationId(), + authored.requestDigest(), + authored.worldDisplayName(), + authored.sourceGameRowId(), + authored.sourceGameTenantKey(), + authored.provenanceKind(), + authored.evidenceDigest(), + policyBytes); + }); var preparationRequest = preparationRequest(source, catalog); var descriptor = AuthoredWorldLaunchDescriptorEvidence.create( @@ -1695,81 +1648,80 @@ private static PredecessorAdmission preparePre1006Admission(Fixture fixture) thr long tenantId = association.legacyGameSessionTenantId(); var sourceIdentity = association.sourceEvidence(); Long instanceId = - fixture.transactions.execute( - status -> { - long allocated = - fixture - .dsl - .fetchSingle( - "INSERT INTO game_instances (tenant_id, runtime_version, owner_account_uuid, status, " - + "row_version, game_template_id, launch_descriptor_id, version_id, release_bundle_id, " - + "version_state_epoch, generation_config_revision, run_owned_start_request_id, " - + "run_owned_start_request_digest, run_owned_start_published_release_bundle_ref, " - + "game_instance_uuid) VALUES (?, ?, ?, 'STARTING', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " - + "RETURNING id", - tenantId, - Long.toString(descriptor.versionId()), - ACTOR, - descriptor.gameTemplateId(), - descriptor.launchDescriptorId(), - descriptor.versionId(), - descriptor.releaseBundleId(), - descriptor.versionStateEpoch(), - descriptor.generationConfigRevision(), - tuple.controlPlaneRequestId(), - tuple.mutationDigest(), - descriptor.publishedReleaseBundleRef(), - instanceUuid) - .get("id", Long.class); - fixture.dsl.execute( - "INSERT INTO game_session_canonical_instance_launch (target_namespace, control_plane_request_id, " - + "game_session_tenant_id, canonical_tenant_id, tenant_association_operation_id, " - + "tenant_association_request_id, tenant_source_schema_version, tenant_source_target_namespace, " - + "tenant_source_request_id, tenant_source_canonical_tenant_id, tenant_source_game_row_id, " - + "tenant_source_game_tenant_key, tenant_source_provenance_kind, tenant_association_kind, " - + "game_instance_id, game_instance_uuid, canonical_realm_id, world_slug, " - + "playable_state_namespace_id, playable_state_scope, public_production, " - + "captured_starting_row_version, game_template_id, launch_descriptor_id, version_id, " - + "release_bundle_id, generation_config_revision, version_state_epoch, complete_launch_binding_evidence, " - + "original_start_session_tuple, catalog_creation_request_id, catalog_revision, " - + "catalog_source_intake_operation_id, catalog_source_intake_request_id) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'FRESH_SOURCE_BOUND', ?, ?, ?, ?, ?, " - + "'SHARED', TRUE, 0, ?, ?, ?, ?, ?, ?, CAST(? AS JSONB), ?, ?, 1, ?, ?)", - NAMESPACE, - tuple.controlPlaneRequestId(), - tenantId, - TENANT, - ASSOCIATION_OPERATION, - sourceIdentity.requestId(), - sourceIdentity.schemaVersion(), - NAMESPACE, - sourceIdentity.requestId(), - TENANT, - sourceIdentity.sourceGameRowId(), - sourceIdentity.sourceGameTenantKey(), - sourceIdentity.provenanceKind(), - allocated, - instanceUuid, - realm, - authored.worldSlug(), - namespace, - descriptor.gameTemplateId(), - descriptor.launchDescriptorId(), - descriptor.versionId(), - descriptor.releaseBundleId(), - descriptor.generationConfigRevision(), - descriptor.versionStateEpoch(), - bindingJson, - tuple.canonicalBytes(), - CATALOG_REQUEST, - source.operationId(), - source.intakeRequestId()); - fixture.dsl.execute( - "UPDATE game_instances SET status = 'RUNNING' WHERE tenant_id = ? AND id = ?", - tenantId, - allocated); - return allocated; - }); + fixture.transactions.execute(status -> { + long allocated = + fixture + .dsl + .fetchSingle( + "INSERT INTO game_instances (tenant_id, runtime_version, owner_account_uuid, status, " + + "row_version, game_template_id, launch_descriptor_id, version_id, release_bundle_id, " + + "version_state_epoch, generation_config_revision, run_owned_start_request_id, " + + "run_owned_start_request_digest, run_owned_start_published_release_bundle_ref, " + + "game_instance_uuid) VALUES (?, ?, ?, 'STARTING', 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + + "RETURNING id", + tenantId, + Long.toString(descriptor.versionId()), + ACTOR, + descriptor.gameTemplateId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + descriptor.releaseBundleId(), + descriptor.versionStateEpoch(), + descriptor.generationConfigRevision(), + tuple.controlPlaneRequestId(), + tuple.mutationDigest(), + descriptor.publishedReleaseBundleRef(), + instanceUuid) + .get("id", Long.class); + fixture.dsl.execute( + "INSERT INTO game_session_canonical_instance_launch (target_namespace, control_plane_request_id, " + + "game_session_tenant_id, canonical_tenant_id, tenant_association_operation_id, " + + "tenant_association_request_id, tenant_source_schema_version, tenant_source_target_namespace, " + + "tenant_source_request_id, tenant_source_canonical_tenant_id, tenant_source_game_row_id, " + + "tenant_source_game_tenant_key, tenant_source_provenance_kind, tenant_association_kind, " + + "game_instance_id, game_instance_uuid, canonical_realm_id, world_slug, " + + "playable_state_namespace_id, playable_state_scope, public_production, " + + "captured_starting_row_version, game_template_id, launch_descriptor_id, version_id, " + + "release_bundle_id, generation_config_revision, version_state_epoch, complete_launch_binding_evidence, " + + "original_start_session_tuple, catalog_creation_request_id, catalog_revision, " + + "catalog_source_intake_operation_id, catalog_source_intake_request_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'FRESH_SOURCE_BOUND', ?, ?, ?, ?, ?, " + + "'SHARED', TRUE, 0, ?, ?, ?, ?, ?, ?, CAST(? AS JSONB), ?, ?, 1, ?, ?)", + NAMESPACE, + tuple.controlPlaneRequestId(), + tenantId, + TENANT, + ASSOCIATION_OPERATION, + sourceIdentity.requestId(), + sourceIdentity.schemaVersion(), + NAMESPACE, + sourceIdentity.requestId(), + TENANT, + sourceIdentity.sourceGameRowId(), + sourceIdentity.sourceGameTenantKey(), + sourceIdentity.provenanceKind(), + allocated, + instanceUuid, + realm, + authored.worldSlug(), + namespace, + descriptor.gameTemplateId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + descriptor.releaseBundleId(), + descriptor.generationConfigRevision(), + descriptor.versionStateEpoch(), + bindingJson, + tuple.canonicalBytes(), + CATALOG_REQUEST, + source.operationId(), + source.intakeRequestId()); + fixture.dsl.execute( + "UPDATE game_instances SET status = 'RUNNING' WHERE tenant_id = ? AND id = ?", + tenantId, + allocated); + return allocated; + }); var captured = new CanonicalGameInstanceLaunchAssociation( NAMESPACE, @@ -1797,37 +1749,36 @@ private static void reservePre1006Attempt( Fixture fixture, CanonicalInitialAdmissionLaunchTarget launch, CanonicalInitialAdmissionRequest request) { - fixture.transactions.executeWithoutResult( - status -> - fixture.dsl.execute( - "INSERT INTO game_session_canonical_initial_admission_attempt (target_namespace, " - + "initial_admission_request_id, request_digest, canonical_tenant_id, world_slug, realm_id, " - + "playable_state_namespace_id, playable_state_scope, canonical_game_instance_id, " - + "game_session_tenant_id, game_instance_id, canonical_version_id, runtime_version_id, " - + "expected_catalog_revision, origin_kind, expected_prior_pointer_version, active_lifecycle_epoch, " - + "hold_id, hold_fence, hold_binding_digest, status, created_at, updated_at) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING', " - + "clock_timestamp(), clock_timestamp())", - NAMESPACE, - request.initialAdmissionRequestId(), - request.requestDigest(), - TENANT, - request.worldSlug(), - request.realmId(), - request.playableStateNamespaceId(), - request.playableStateScope(), - request.canonicalGameInstanceId(), - launch.association().gameSessionTenantId(), - launch.gameInstanceId(), - request.canonicalVersionId(), - launch.runtimeVersionId(), - request.expectedCatalogRevision(), - request.originKind().name(), - request.expectedPriorPointerVersion(), - request.activeLifecycleEpoch(), - request.holdId(), - request.holdFence(), - request.holdBindingDigest())); + fixture.transactions.executeWithoutResult(status -> + fixture.dsl.execute( + "INSERT INTO game_session_canonical_initial_admission_attempt (target_namespace, " + + "initial_admission_request_id, request_digest, canonical_tenant_id, world_slug, realm_id, " + + "playable_state_namespace_id, playable_state_scope, canonical_game_instance_id, " + + "game_session_tenant_id, game_instance_id, canonical_version_id, runtime_version_id, " + + "expected_catalog_revision, origin_kind, expected_prior_pointer_version, active_lifecycle_epoch, " + + "hold_id, hold_fence, hold_binding_digest, status, created_at, updated_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING', " + + "clock_timestamp(), clock_timestamp())", + NAMESPACE, + request.initialAdmissionRequestId(), + request.requestDigest(), + TENANT, + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + launch.association().gameSessionTenantId(), + launch.gameInstanceId(), + request.canonicalVersionId(), + launch.runtimeVersionId(), + request.expectedCatalogRevision(), + request.originKind().name(), + request.expectedPriorPointerVersion(), + request.activeLifecycleEpoch(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest())); } /** Independent SQL encoding of the predecessor catalog's decimal-length UTF-8 framing. */ @@ -1901,79 +1852,78 @@ private static void seedPre1006ExpectedClosedTerminal( CanonicalInitialAdmissionRequest request, net.firedevops.firemud.gamesession.dto.CanonicalClosedAdmissionPointerSnapshot origin) { Instant terminalAt = Instant.now().truncatedTo(ChronoUnit.MICROS); - fixture.transactions.executeWithoutResult( - status -> { - long audit = - new GameplayAdmissionPointerEventRepository(fixture.dsl) - .appendCanonicalInitialAdmissionOpen( - request, - prepared.catalog(), - launch, - 2L, - prepared.catalog().catalogRevision(), - terminalAt); - long pointer = - fixture - .dsl - .fetchSingle( - "UPDATE gameplay_admission_pointer SET (world_slug, realm_slug, world_display_name, realm_display_name, " - + "tenant_id, game_instance_id, pointer_version, visible, requires_character_selection, state_scope, " - + "character_creation_policy, last_updated_by, last_update_reason, updated_at, public_production_realm, " - + "catalog_revision, realm_id, playable_state_namespace_id, representation_version, target_namespace, " - + "canonical_tenant_id, admission_state, canonical_game_instance_id, canonical_version_id, runtime_version_id, " - + "initial_admission_request_id, initial_admission_request_digest, initial_admission_origin_kind, " - + "initial_admission_prior_pointer_version, initial_admission_active_epoch, initial_admission_hold_id, " - + "initial_admission_hold_fence, initial_admission_hold_binding_digest) = " - + "(SELECT world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, game_instance_id, " - + "pointer_version, visible, requires_character_selection, state_scope, character_creation_policy, " - + "actor_principal, reason, occurred_at, public_production_realm, catalog_revision, realm_id, " - + "playable_state_namespace_id, representation_version, target_namespace, canonical_tenant_id, admission_state, " - + "canonical_game_instance_id, canonical_version_id, runtime_version_id, initial_admission_request_id, " - + "initial_admission_request_digest, initial_admission_origin_kind, initial_admission_prior_pointer_version, " - + "initial_admission_active_epoch, initial_admission_hold_id, initial_admission_hold_fence, initial_admission_hold_binding_digest " - + "FROM gameplay_admission_pointer_event WHERE id = ?) WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? RETURNING id", - audit, - NAMESPACE, - TENANT, - request.realmId()) - .get("id", Long.class); - String proof = - fixture - .dsl - .fetchSingle( - "SELECT 'sha256:' || encode(sha256(string_agg(int4send(octet_length(convert_to(field, 'UTF8'))) " - + "|| convert_to(field, 'UTF8'), ''::BYTEA ORDER BY ordinal)), 'hex') AS proof " - + "FROM game_session_canonical_initial_admission_attempt attempt CROSS JOIN LATERAL unnest(ARRAY[" - + "'gs-canonical-initial-admission-commit-proof/v1', request_digest, initial_admission_request_id, " - + "target_namespace, canonical_tenant_id::TEXT, world_slug, realm_id::TEXT, playable_state_namespace_id::TEXT, " - + "playable_state_scope, canonical_game_instance_id::TEXT, canonical_version_id::TEXT, runtime_version_id::TEXT, " - + "active_lifecycle_epoch::TEXT, expected_catalog_revision::TEXT, origin_kind, expected_prior_pointer_version::TEXT, " - + "hold_id::TEXT, hold_fence::TEXT, hold_binding_digest, '2', ?::TEXT, ?::TEXT, ?::TEXT, ?::TEXT, ?::TEXT]) " - + "WITH ORDINALITY fields(field, ordinal) WHERE target_namespace = ? AND initial_admission_request_id = ?", - Long.toString(audit), - origin.requestId().toString(), - origin.requestDigest(), - Long.toString(origin.auditEventId()), - terminalAt.toString(), - NAMESPACE, - request.initialAdmissionRequestId()) - .get("proof", String.class); - fixture.dsl.execute( - "UPDATE game_session_canonical_initial_admission_attempt SET status = 'COMMITTED', pointer_id = ?, " - + "pointer_version = 2, audit_event_id = ?, prior_pointer_request_id = ?, prior_pointer_request_digest = ?, " - + "prior_pointer_audit_event_id = ?, commit_proof_digest = ?, updated_at = CAST(? AS TIMESTAMPTZ), " - + "terminal_at = CAST(? AS TIMESTAMPTZ) WHERE target_namespace = ? AND initial_admission_request_id = ?", - pointer, - audit, - origin.requestId(), - origin.requestDigest(), - origin.auditEventId(), - proof, - terminalAt.atOffset(ZoneOffset.UTC), - terminalAt.atOffset(ZoneOffset.UTC), - NAMESPACE, - request.initialAdmissionRequestId()); - }); + fixture.transactions.executeWithoutResult(status -> { + long audit = + new GameplayAdmissionPointerEventRepository(fixture.dsl) + .appendCanonicalInitialAdmissionOpen( + request, + prepared.catalog(), + launch, + 2L, + prepared.catalog().catalogRevision(), + terminalAt); + long pointer = + fixture + .dsl + .fetchSingle( + "UPDATE gameplay_admission_pointer SET (world_slug, realm_slug, world_display_name, realm_display_name, " + + "tenant_id, game_instance_id, pointer_version, visible, requires_character_selection, state_scope, " + + "character_creation_policy, last_updated_by, last_update_reason, updated_at, public_production_realm, " + + "catalog_revision, realm_id, playable_state_namespace_id, representation_version, target_namespace, " + + "canonical_tenant_id, admission_state, canonical_game_instance_id, canonical_version_id, runtime_version_id, " + + "initial_admission_request_id, initial_admission_request_digest, initial_admission_origin_kind, " + + "initial_admission_prior_pointer_version, initial_admission_active_epoch, initial_admission_hold_id, " + + "initial_admission_hold_fence, initial_admission_hold_binding_digest) = " + + "(SELECT world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, game_instance_id, " + + "pointer_version, visible, requires_character_selection, state_scope, character_creation_policy, " + + "actor_principal, reason, occurred_at, public_production_realm, catalog_revision, realm_id, " + + "playable_state_namespace_id, representation_version, target_namespace, canonical_tenant_id, admission_state, " + + "canonical_game_instance_id, canonical_version_id, runtime_version_id, initial_admission_request_id, " + + "initial_admission_request_digest, initial_admission_origin_kind, initial_admission_prior_pointer_version, " + + "initial_admission_active_epoch, initial_admission_hold_id, initial_admission_hold_fence, initial_admission_hold_binding_digest " + + "FROM gameplay_admission_pointer_event WHERE id = ?) WHERE target_namespace = ? AND canonical_tenant_id = ? AND realm_id = ? RETURNING id", + audit, + NAMESPACE, + TENANT, + request.realmId()) + .get("id", Long.class); + String proof = + fixture + .dsl + .fetchSingle( + "SELECT 'sha256:' || encode(sha256(string_agg(int4send(octet_length(convert_to(field, 'UTF8'))) " + + "|| convert_to(field, 'UTF8'), ''::BYTEA ORDER BY ordinal)), 'hex') AS proof " + + "FROM game_session_canonical_initial_admission_attempt attempt CROSS JOIN LATERAL unnest(ARRAY[" + + "'gs-canonical-initial-admission-commit-proof/v1', request_digest, initial_admission_request_id, " + + "target_namespace, canonical_tenant_id::TEXT, world_slug, realm_id::TEXT, playable_state_namespace_id::TEXT, " + + "playable_state_scope, canonical_game_instance_id::TEXT, canonical_version_id::TEXT, runtime_version_id::TEXT, " + + "active_lifecycle_epoch::TEXT, expected_catalog_revision::TEXT, origin_kind, expected_prior_pointer_version::TEXT, " + + "hold_id::TEXT, hold_fence::TEXT, hold_binding_digest, '2', ?::TEXT, ?::TEXT, ?::TEXT, ?::TEXT, ?::TEXT]) " + + "WITH ORDINALITY fields(field, ordinal) WHERE target_namespace = ? AND initial_admission_request_id = ?", + Long.toString(audit), + origin.requestId().toString(), + origin.requestDigest(), + Long.toString(origin.auditEventId()), + terminalAt.toString(), + NAMESPACE, + request.initialAdmissionRequestId()) + .get("proof", String.class); + fixture.dsl.execute( + "UPDATE game_session_canonical_initial_admission_attempt SET status = 'COMMITTED', pointer_id = ?, " + + "pointer_version = 2, audit_event_id = ?, prior_pointer_request_id = ?, prior_pointer_request_digest = ?, " + + "prior_pointer_audit_event_id = ?, commit_proof_digest = ?, updated_at = CAST(? AS TIMESTAMPTZ), " + + "terminal_at = CAST(? AS TIMESTAMPTZ) WHERE target_namespace = ? AND initial_admission_request_id = ?", + pointer, + audit, + origin.requestId(), + origin.requestDigest(), + origin.auditEventId(), + proof, + terminalAt.atOffset(ZoneOffset.UTC), + terminalAt.atOffset(ZoneOffset.UTC), + NAMESPACE, + request.initialAdmissionRequestId()); + }); } private static void seedPre1006Terminal( @@ -1992,82 +1942,80 @@ private static void seedPre1006Terminal( .get(0, Long.class)) .isZero(); Instant terminalAt = Instant.now().truncatedTo(ChronoUnit.MICROS); - fixture.transactions.executeWithoutResult( - status -> { - Long pointerId = null; - Long auditId = null; - String reason = "Explicit pre1006 owner abort fixture"; - if (committed) { - auditId = - new GameplayAdmissionPointerEventRepository(fixture.dsl) - .appendCanonicalInitialAdmissionOpen( - request, - prepared.catalog(), - launch, - 1L, - prepared.catalog().catalogRevision(), - terminalAt); - pointerId = - fixture - .dsl - .fetchSingle( - "INSERT INTO gameplay_admission_pointer (world_slug, realm_slug, world_display_name, " - + "realm_display_name, tenant_id, game_instance_id, pointer_version, visible, " - + "requires_character_selection, state_scope, character_creation_policy, " - + "last_updated_by, last_update_reason, created_at, updated_at, " - + "public_production_realm, catalog_revision, realm_id, playable_state_namespace_id, " - + "representation_version, target_namespace, canonical_tenant_id, admission_state, " - + "canonical_game_instance_id, canonical_version_id, runtime_version_id, " - + "initial_admission_request_id, initial_admission_request_digest, " - + "initial_admission_origin_kind, initial_admission_prior_pointer_version, " - + "initial_admission_active_epoch, initial_admission_hold_id, " - + "initial_admission_hold_fence, initial_admission_hold_binding_digest) " - + "SELECT world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " - + "game_instance_id, pointer_version, visible, requires_character_selection, " - + "state_scope, character_creation_policy, actor_principal, reason, occurred_at, " - + "occurred_at, public_production_realm, catalog_revision, realm_id, " - + "playable_state_namespace_id, representation_version, target_namespace, " - + "canonical_tenant_id, admission_state, canonical_game_instance_id, " - + "canonical_version_id, runtime_version_id, initial_admission_request_id, " - + "initial_admission_request_digest, initial_admission_origin_kind, " - + "initial_admission_prior_pointer_version, initial_admission_active_epoch, " - + "initial_admission_hold_id, initial_admission_hold_fence, " - + "initial_admission_hold_binding_digest FROM gameplay_admission_pointer_event " - + "WHERE id = ? RETURNING id", - auditId) - .get("id", Long.class); - } - String proof = - predecessorTerminalProofDigest( - fixture, request, committed, auditId, reason, terminalAt); - if (committed) { - fixture.dsl.execute( - "UPDATE game_session_canonical_initial_admission_attempt SET " - + "status = 'COMMITTED', pointer_id = ?, pointer_version = 1, audit_event_id = ?, " - + "commit_proof_digest = ?, updated_at = CAST(? AS TIMESTAMPTZ), " - + "terminal_at = CAST(? AS TIMESTAMPTZ) " - + "WHERE target_namespace = ? AND initial_admission_request_id = ?", - pointerId, - auditId, - proof, - terminalAt.atOffset(ZoneOffset.UTC), - terminalAt.atOffset(ZoneOffset.UTC), - NAMESPACE, - request.initialAdmissionRequestId()); - } else { - fixture.dsl.execute( - "UPDATE game_session_canonical_initial_admission_attempt SET " - + "status = 'ABORTED', abort_reason = ?, abort_proof_digest = ?, " - + "updated_at = CAST(? AS TIMESTAMPTZ), terminal_at = CAST(? AS TIMESTAMPTZ) " - + "WHERE target_namespace = ? AND initial_admission_request_id = ?", - reason, - proof, - terminalAt.atOffset(ZoneOffset.UTC), - terminalAt.atOffset(ZoneOffset.UTC), - NAMESPACE, - request.initialAdmissionRequestId()); - } - }); + fixture.transactions.executeWithoutResult(status -> { + Long pointerId = null; + Long auditId = null; + String reason = "Explicit pre1006 owner abort fixture"; + if (committed) { + auditId = + new GameplayAdmissionPointerEventRepository(fixture.dsl) + .appendCanonicalInitialAdmissionOpen( + request, + prepared.catalog(), + launch, + 1L, + prepared.catalog().catalogRevision(), + terminalAt); + pointerId = + fixture + .dsl + .fetchSingle( + "INSERT INTO gameplay_admission_pointer (world_slug, realm_slug, world_display_name, " + + "realm_display_name, tenant_id, game_instance_id, pointer_version, visible, " + + "requires_character_selection, state_scope, character_creation_policy, " + + "last_updated_by, last_update_reason, created_at, updated_at, " + + "public_production_realm, catalog_revision, realm_id, playable_state_namespace_id, " + + "representation_version, target_namespace, canonical_tenant_id, admission_state, " + + "canonical_game_instance_id, canonical_version_id, runtime_version_id, " + + "initial_admission_request_id, initial_admission_request_digest, " + + "initial_admission_origin_kind, initial_admission_prior_pointer_version, " + + "initial_admission_active_epoch, initial_admission_hold_id, " + + "initial_admission_hold_fence, initial_admission_hold_binding_digest) " + + "SELECT world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, actor_principal, reason, occurred_at, " + + "occurred_at, public_production_realm, catalog_revision, realm_id, " + + "playable_state_namespace_id, representation_version, target_namespace, " + + "canonical_tenant_id, admission_state, canonical_game_instance_id, " + + "canonical_version_id, runtime_version_id, initial_admission_request_id, " + + "initial_admission_request_digest, initial_admission_origin_kind, " + + "initial_admission_prior_pointer_version, initial_admission_active_epoch, " + + "initial_admission_hold_id, initial_admission_hold_fence, " + + "initial_admission_hold_binding_digest FROM gameplay_admission_pointer_event " + + "WHERE id = ? RETURNING id", + auditId) + .get("id", Long.class); + } + String proof = + predecessorTerminalProofDigest(fixture, request, committed, auditId, reason, terminalAt); + if (committed) { + fixture.dsl.execute( + "UPDATE game_session_canonical_initial_admission_attempt SET " + + "status = 'COMMITTED', pointer_id = ?, pointer_version = 1, audit_event_id = ?, " + + "commit_proof_digest = ?, updated_at = CAST(? AS TIMESTAMPTZ), " + + "terminal_at = CAST(? AS TIMESTAMPTZ) " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + pointerId, + auditId, + proof, + terminalAt.atOffset(ZoneOffset.UTC), + terminalAt.atOffset(ZoneOffset.UTC), + NAMESPACE, + request.initialAdmissionRequestId()); + } else { + fixture.dsl.execute( + "UPDATE game_session_canonical_initial_admission_attempt SET " + + "status = 'ABORTED', abort_reason = ?, abort_proof_digest = ?, " + + "updated_at = CAST(? AS TIMESTAMPTZ), terminal_at = CAST(? AS TIMESTAMPTZ) " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + reason, + proof, + terminalAt.atOffset(ZoneOffset.UTC), + terminalAt.atOffset(ZoneOffset.UTC), + NAMESPACE, + request.initialAdmissionRequestId()); + } + }); } /** Independent PostgreSQL encoding of the retained v1 length-prefixed terminal frame. */ @@ -2251,42 +2199,37 @@ private static void assertDistinctAccountSourceReadersShareAndExcludeWriters( for (int index = 0; index < requests.size(); index++) { int slot = index; readers.add( - executor.submit( - () -> - fixture.transactions.execute( - status -> { - readerPids - .get(slot) - .set( - Objects.requireNonNull( - fixture - .dsl - .fetchSingle("SELECT pg_backend_pid()") - .get(0, Integer.class))); - var original = references.begin(requests.get(slot)); - assertThat( - fixture.initialAdmissionRepository.lockExactCurrentOpenSnapshot( - qualified)) - .isEqualTo(qualified); - assertThat(references.find(requests.get(slot))).contains(original); - acquired.get(slot).countDown(); - try { - if (!release - .get(slot) - .await(30L, java.util.concurrent.TimeUnit.SECONDS)) { - throw new IllegalStateException( - "Current-source reader was not released"); - } - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(interrupted); - } finally { - // Retained owner histories and existing selection assertions remain - // unchanged. - status.setRollbackOnly(); - } - return original.getTargetFenceUuid(); - }))); + executor.submit(() -> + fixture.transactions.execute(status -> { + readerPids + .get(slot) + .set( + Objects.requireNonNull( + fixture + .dsl + .fetchSingle("SELECT pg_backend_pid()") + .get(0, Integer.class))); + var original = references.begin(requests.get(slot)); + assertThat( + fixture.initialAdmissionRepository.lockExactCurrentOpenSnapshot( + qualified)) + .isEqualTo(qualified); + assertThat(references.find(requests.get(slot))).contains(original); + acquired.get(slot).countDown(); + try { + if (!release.get(slot).await(30L, java.util.concurrent.TimeUnit.SECONDS)) { + throw new IllegalStateException("Current-source reader was not released"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } finally { + // Retained owner histories and existing selection assertions remain + // unchanged. + status.setRollbackOnly(); + } + return original.getTargetFenceUuid(); + }))); // Both complete revalidations must acquire their shared locks while the first stays open. assertThat(acquired.get(slot).await(5L, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); } @@ -2296,25 +2239,23 @@ private static void assertDistinctAccountSourceReadersShareAndExcludeWriters( int slot = index; var started = new java.util.concurrent.CountDownLatch(1); writers.add( - executor.submit( - () -> - fixture.transactions.execute( - status -> { - writerPids - .get(slot) - .set( - Objects.requireNonNull( - fixture - .dsl - .fetchSingle("SELECT pg_backend_pid()") - .get(0, Integer.class))); - started.countDown(); - var locked = - fixture.dsl.fetchSingle( - writerSql.get(slot), NAMESPACE, TENANT, current.realmId()); - status.setRollbackOnly(); - return locked.get(0); - }))); + executor.submit(() -> + fixture.transactions.execute(status -> { + writerPids + .get(slot) + .set( + Objects.requireNonNull( + fixture + .dsl + .fetchSingle("SELECT pg_backend_pid()") + .get(0, Integer.class))); + started.countDown(); + var locked = + fixture.dsl.fetchSingle( + writerSql.get(slot), NAMESPACE, TENANT, current.realmId()); + status.setRollbackOnly(); + return locked.get(0); + }))); assertThat(started.await(5L, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); int holder = awaitBackendBlockedByCurrentSourceReader( @@ -2518,11 +2459,10 @@ private static void assertV1013RetentionLaunchForeignKey(Fixture fixture) { .extracting(row -> row.get("tgtype", Integer.class)) .containsExactly(9, 17); assertThat(launchTriggers) - .allSatisfy( - trigger -> { - assertThat(trigger.get("tgenabled", String.class)).isEqualTo("O"); - assertThat(trigger.get("tgisinternal", Boolean.class)).isTrue(); - }); + .allSatisfy(trigger -> { + assertThat(trigger.get("tgenabled", String.class)).isEqualTo("O"); + assertThat(trigger.get("tgisinternal", Boolean.class)).isTrue(); + }); } private static void assertV1040CompletionForeignKeyTriggers(Fixture fixture) { @@ -2542,11 +2482,10 @@ private static void assertV1040CompletionForeignKeyTriggers(Fixture fixture) { + "AND child_namespace.nspname = current_schema()"); assertThat(triggers).hasSize(6); assertThat(triggers) - .allSatisfy( - trigger -> { - assertThat(trigger.get("tgenabled", String.class)).isEqualTo("O"); - assertThat(trigger.get("tgisinternal", Boolean.class)).isTrue(); - }); + .allSatisfy(trigger -> { + assertThat(trigger.get("tgenabled", String.class)).isEqualTo("O"); + assertThat(trigger.get("tgisinternal", Boolean.class)).isTrue(); + }); } private static String otherGuardProjection(Fixture fixture) { @@ -2959,15 +2898,13 @@ IntakeReceipt registerSource() { } CanonicalRealmCatalogSnapshot createCatalog(IntakeReceipt source) { - transactions.execute( - status -> - new GameSessionFreshTenantAssociationRepository(dsl) - .associateFresh( - ASSOCIATION_OPERATION, - NAMESPACE, - source, - CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( - source.source()))); + transactions.execute(status -> + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + ASSOCIATION_OPERATION, + NAMESPACE, + source, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(source.source()))); var prepared = catalogRepository.prepareInitialPublicProduction( catalogRequest(source), publishedPolicy(source)); @@ -2988,31 +2925,30 @@ FreshGameSessionTenantAssociation createTestOnlyFreshMappingAndRunningLaunch( CanonicalHumanPublicationOwnerTestFixtures.pinLaunch( dsl, transactions, tuple, source.source(), publishedPolicy(source), binding); return Objects.requireNonNull( - transactions.execute( - status -> { - var association = - new GameSessionFreshTenantAssociationRepository(dsl) - .associateFresh( - ASSOCIATION_OPERATION, - NAMESPACE, - source, - CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( - source.source())); - var starting = - new GameSessionCanonicalStartingInstanceRepository(dsl, NAMESPACE) - .createStarting( - association, - binding, - ACTOR, - tuple.controlPlaneRequestId(), - tuple.mutationDigest(), - tuple); - dsl.execute( - "UPDATE game_instances SET status = 'RUNNING' WHERE tenant_id = ? AND id = ?", - association.legacyGameSessionTenantId(), - starting.gameInstanceId()); - return association; - }), + transactions.execute(status -> { + var association = + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + ASSOCIATION_OPERATION, + NAMESPACE, + source, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( + source.source())); + var starting = + new GameSessionCanonicalStartingInstanceRepository(dsl, NAMESPACE) + .createStarting( + association, + binding, + ACTOR, + tuple.controlPlaneRequestId(), + tuple.mutationDigest(), + tuple); + dsl.execute( + "UPDATE game_instances SET status = 'RUNNING' WHERE tenant_id = ? AND id = ?", + association.legacyGameSessionTenantId(), + starting.gameInstanceId()); + return association; + }), "Controlled actual GS tenant association"); } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalRosterCorrectionMigrationOrderingPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalRosterCorrectionMigrationOrderingPostgresIntegrationTest.java index 604f833f04..7fd7a9fddd 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalRosterCorrectionMigrationOrderingPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalRosterCorrectionMigrationOrderingPostgresIntegrationTest.java @@ -256,11 +256,10 @@ private void proveEntityPublishedV1017UpgradeAndNoOp() { requestBinding) .get(0, Long.class)) .isEqualTo(1L); - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM entity_canonical_roster_admissions WHERE operation_uuid = ?", - operation)) + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM entity_canonical_roster_admissions WHERE operation_uuid = ?", + operation)) .isInstanceOf(org.jooq.exception.DataAccessException.class); migrate(dataSource, schema, ENTITY.locations(), null); @@ -294,13 +293,12 @@ private void proveEntityPublishedV1019TypedRecognitionUpgradeAndNoOp() { List targetRowsAt1019 = retainedEntitySnapshotTargets(dataSource); List historyAt1019 = history(dataSource); assertThat(historyAt1019) - .anySatisfy( - row -> - assertThat(row) - .contains( - "1019", - "V1019__canonical_roster_snapshot_retirement_seals.sql", - "\"success\": true")); + .anySatisfy(row -> + assertThat(row) + .contains( + "1019", + "V1019__canonical_roster_snapshot_retirement_seals.sql", + "\"success\": true")); migrate(dataSource, schema, ENTITY.locations(), null); List historyAt1020 = history(dataSource); @@ -385,17 +383,16 @@ private EntitySnapshotSeed seedCreatedSnapshot( private void classifyRetainedDependencies(DriverManagerDataSource dataSource, int limit) { new TransactionTemplate(new DataSourceTransactionManager(dataSource)) - .execute( - status -> { - new net.firedevops.firemud.entitymanagement.repository - .CanonicalGameplayRosterRetentionRepository( - DSL.using( - new org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy( - dataSource), - SQLDialect.POSTGRES)) - .classifyRetainedDependencies(limit); - return null; - }); + .execute(status -> { + new net.firedevops.firemud.entitymanagement.repository + .CanonicalGameplayRosterRetentionRepository( + DSL.using( + new org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy( + dataSource), + SQLDialect.POSTGRES)) + .classifyRetainedDependencies(limit); + return null; + }); } private void assertTypedCreatedTarget( @@ -561,11 +558,10 @@ private void assertEntitySnapshotClassification( .get(0, Boolean.class)) .isTrue(); assertThat(retainedEntitySnapshotTargets(dataSource)).isEmpty(); - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM entity_canonical_roster_retired_targets WHERE snapshot_uuid = ?", - sealSnapshot)) + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM entity_canonical_roster_retired_targets WHERE snapshot_uuid = ?", + sealSnapshot)) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(entitySealPurgeable(dsl, sealDigest)).isFalse(); @@ -616,11 +612,10 @@ private void assertEntitySnapshotClassification( .get(0, Long.class)) .isEqualTo(2L); assertThat(entitySealPurgeable(dsl, sealDigest)).isFalse(); - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM entity_canonical_roster_retired_targets WHERE snapshot_uuid = ?", - sealSnapshot)) + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM entity_canonical_roster_retired_targets WHERE snapshot_uuid = ?", + sealSnapshot)) .isInstanceOf(org.jooq.exception.DataAccessException.class); } @@ -789,13 +784,12 @@ private void assertHistoryPrefix(List current, List original, St private void assertMigrationPresent(List history, String version, String script) { assertThat(history) - .anySatisfy( - row -> - assertThat(row) - .contains( - "\"version\": \"" + version + "\"", - "\"script\": \"" + script + "\"", - "\"success\": true")); + .anySatisfy(row -> + assertThat(row) + .contains( + "\"version\": \"" + version + "\"", + "\"script\": \"" + script + "\"", + "\"success\": true")); } private DriverManagerDataSource dataSource(String schema) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceScriptPinMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceScriptPinMigrationIntegrationTest.java index 9f6383ce5f..0636763e1a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceScriptPinMigrationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameInstanceScriptPinMigrationIntegrationTest.java @@ -45,68 +45,61 @@ void baselineEnforcesCoherentScriptPinTuplesAndUnpinnedMetadata() { .extracting(record -> record.get("id", Long.class)) .containsExactlyInAnyOrder(101L, 102L); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO game_instances (id, tenant_id, runtime_version, " - + "script_patch_version, owner_account_id, status) VALUES " - + "(103, 42, '1.0.0', 'patch-only', 103, 'STOPPED')")) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, " + + "script_patch_version, owner_account_id, status) VALUES " + + "(103, 42, '1.0.0', 'patch-only', 103, 'STOPPED')")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("game_instances_script_pin_tuple_coherent"); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO game_instances (id, tenant_id, runtime_version, script_pin_epoch, " - + "owner_account_id, status) VALUES " - + "(104, 42, '1.0.0', 4, 104, 'STOPPED')")) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, script_pin_epoch, " + + "owner_account_id, status) VALUES " + + "(104, 42, '1.0.0', 4, 104, 'STOPPED')")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("game_instances_script_pin_tuple_coherent"); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO game_instances (id, tenant_id, runtime_version, " - + "script_patch_pinned_control_plane_request_id, owner_account_id, status) " - + "VALUES (105, 42, '1.0.0', 'request-only', 105, 'STOPPED')")) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, " + + "script_patch_pinned_control_plane_request_id, owner_account_id, status) " + + "VALUES (105, 42, '1.0.0', 'request-only', 105, 'STOPPED')")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("game_instances_script_pin_tuple_coherent"); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO game_instances (id, tenant_id, runtime_version, " - + "script_patch_version, script_pin_epoch, " - + "script_patch_pinned_control_plane_request_id, owner_account_id, status) " - + "VALUES (109, 42, '1.0.0', 'patch-zero-epoch', 0, " - + "'request-zero-epoch', 109, 'STOPPED')")) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, " + + "script_patch_version, script_pin_epoch, " + + "script_patch_pinned_control_plane_request_id, owner_account_id, status) " + + "VALUES (109, 42, '1.0.0', 'patch-zero-epoch', 0, " + + "'request-zero-epoch', 109, 'STOPPED')")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("game_instances_script_pin_tuple_coherent"); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO game_instances (id, tenant_id, runtime_version, " - + "script_patch_version, script_pin_epoch, " - + "script_patch_pinned_control_plane_request_id, owner_account_id, status) " - + "VALUES (107, 42, '1.0.0', ' ', 1, 'request-whitespace-patch', " - + "107, 'STOPPED')")) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, " + + "script_patch_version, script_pin_epoch, " + + "script_patch_pinned_control_plane_request_id, owner_account_id, status) " + + "VALUES (107, 42, '1.0.0', ' ', 1, 'request-whitespace-patch', " + + "107, 'STOPPED')")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("game_instances_script_pin_tuple_coherent"); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO game_instances (id, tenant_id, runtime_version, " - + "script_patch_version, script_pin_epoch, " - + "script_patch_pinned_control_plane_request_id, owner_account_id, status) " - + "VALUES (108, 42, '1.0.0', 'patch-whitespace-request', 1, ' ', " - + "108, 'STOPPED')")) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, " + + "script_patch_version, script_pin_epoch, " + + "script_patch_pinned_control_plane_request_id, owner_account_id, status) " + + "VALUES (108, 42, '1.0.0', 'patch-whitespace-request', 1, ' ', " + + "108, 'STOPPED')")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("game_instances_script_pin_tuple_coherent"); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO game_instances (id, tenant_id, runtime_version, " - + "script_patch_pinned_at, script_patch_pinned_by, script_patch_pinned_reason, " - + "owner_account_id, status) VALUES " - + "(106, 42, '1.0.0', TIMESTAMP '2026-01-02 03:04:05', " - + "'stale-owner', 'stale-reason', 106, 'STOPPED')")) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, " + + "script_patch_pinned_at, script_patch_pinned_by, script_patch_pinned_reason, " + + "owner_account_id, status) VALUES " + + "(106, 42, '1.0.0', TIMESTAMP '2026-01-02 03:04:05', " + + "'stale-owner', 'stale-reason', 106, 'STOPPED')")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("game_instances_unpinned_script_pin_metadata_coherent"); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java index f1d5c6d6db..fa49d85616 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionPostgresIntegrationTest.java @@ -201,13 +201,11 @@ void retainsExactEmptyOwnerResultAndRejectsConflictOrMutation() throws Exception byte[] conflictingBytes = canonicalEmptyResult(requestBytes, "different exact result"); Candidate conflict = candidate(launch, attempt, requestBytes, conflictingBytes); - assertThatThrownBy( - () -> - fixture - .transactions() - .execute( - status -> - fixture.retentionRepository().retainInOwnerTransaction(conflict))) + assertThatThrownBy(() -> + fixture + .transactions() + .execute( + status -> fixture.retentionRepository().retainInOwnerTransaction(conflict))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("conflicts with its first exact result"); assertThat( @@ -225,32 +223,29 @@ void retainsExactEmptyOwnerResultAndRejectsConflictOrMutation() throws Exception + "' AND control_plane_request_id = '" + launch.tuple().controlPlaneRequestId() + "'"; - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "UPDATE gs_original_start_session_authored_actor_core_retention" - + " SET source_result_digest = 'sha256:' || repeat('0', 64)" - + where)) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "UPDATE gs_original_start_session_authored_actor_core_retention" + + " SET source_result_digest = 'sha256:' || repeat('0', 64)" + + where)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining( "Game Session authored-core source retention is immutable and append-only"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "DELETE FROM gs_original_start_session_authored_actor_core_retention" - + where)) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "DELETE FROM gs_original_start_session_authored_actor_core_retention" + + where)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining( "Game Session authored-core source retention is immutable and append-only"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute("TRUNCATE gs_original_start_session_authored_actor_core_retention")) + assertThatThrownBy(() -> + fixture + .dsl() + .execute("TRUNCATE gs_original_start_session_authored_actor_core_retention")) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("Game Session authored-core source retention cannot be truncated"); } @@ -315,38 +310,35 @@ void originalAssociationReadRequiresExactLiveOwnerAndActualPinsAreAppendOnly() t var attemptRepository = new GameSessionStartSessionOperatorAttemptRepository( fixture.dsl(), Duration.ofMinutes(5)); - assertThatThrownBy( - () -> - attemptRepository.readHistoricalOwnerAttempt( - tuple, UUID.randomUUID(), owner.ownerFence())) + assertThatThrownBy(() -> + attemptRepository.readHistoricalOwnerAttempt( + tuple, UUID.randomUUID(), owner.ownerFence())) .isInstanceOf( GameSessionStartSessionOperatorAttemptRepository .StaleStartSessionOperatorAttemptClaimException.class) .hasMessage("Historical owner read does not match the original owner attempt and fence"); - assertThatThrownBy( - () -> - attemptRepository.readHistoricalOwnerAttempt( - tuple, owner.ownerAttemptId(), owner.ownerFence() + 1)) + assertThatThrownBy(() -> + attemptRepository.readHistoricalOwnerAttempt( + tuple, owner.ownerAttemptId(), owner.ownerFence() + 1)) .isInstanceOf( GameSessionStartSessionOperatorAttemptRepository .StaleStartSessionOperatorAttemptClaimException.class) .hasMessage("Historical owner read does not match the original owner attempt and fence"); UUID wrongTenantId = UUID.randomUUID(); - assertThatThrownBy( - () -> - new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( - UUID.randomUUID(), - exactSelector.targetNamespace(), - wrongTenantId, - exactSelector.worldSlug(), - exactSelector.gameInstanceUuid(), - exactSelector.controlPlaneRequestId(), - exactSelector.launchDescriptorId(), - exactSelector.expectedDescriptorRequestDigest(), - exactSelector.expectedDescriptorResultDigest(), - exactSelector.expectedReleaseAttestationEvidenceDigest(), - exactSelector.originalOperation())) + assertThatThrownBy(() -> + new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( + UUID.randomUUID(), + exactSelector.targetNamespace(), + wrongTenantId, + exactSelector.worldSlug(), + exactSelector.gameInstanceUuid(), + exactSelector.controlPlaneRequestId(), + exactSelector.launchDescriptorId(), + exactSelector.expectedDescriptorRequestDigest(), + exactSelector.expectedDescriptorResultDigest(), + exactSelector.expectedReleaseAttestationEvidenceDigest(), + exactSelector.originalOperation())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Original operation differs from the exact independent launch selector"); @@ -439,9 +431,8 @@ void originalAssociationReadRequiresExactLiveOwnerAndActualPinsAreAppendOnly() t exactSelector.expectedDescriptorResultDigest(), exactSelector.expectedReleaseAttestationEvidenceDigest(), exactSelector.originalOperation()); - assertThatThrownBy( - () -> - associationReadRepository.readOriginalStartSessionAssociation(wrongWorldSelector)) + assertThatThrownBy(() -> + associationReadRepository.readOriginalStartSessionAssociation(wrongWorldSelector)) .isInstanceOf( CanonicalGameInstanceLaunchAssociationRepository .LaunchAssociationOwnerReadMismatchException.class) @@ -454,65 +445,51 @@ void originalAssociationReadRequiresExactLiveOwnerAndActualPinsAreAppendOnly() t + "' AND control_plane_request_id = '" + operationId + "'"; - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "UPDATE game_session_start_session_template_association_pin" - + " SET association_response_digest = 'sha256:' || repeat('0', 64)" - + where)) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "UPDATE game_session_start_session_template_association_pin" + + " SET association_response_digest = 'sha256:' || repeat('0', 64)" + + where)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining("StartSession template association pins are immutable"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "UPDATE game_session_start_session_launch_descriptor_pin" - + " SET descriptor_response_digest = 'sha256:' || repeat('0', 64)" - + where)) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "UPDATE game_session_start_session_launch_descriptor_pin" + + " SET descriptor_response_digest = 'sha256:' || repeat('0', 64)" + + where)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining("StartSession launch descriptor pins are immutable"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "DELETE FROM game_session_start_session_launch_descriptor_pin" + where)) + assertThatThrownBy(() -> + fixture + .dsl() + .execute("DELETE FROM game_session_start_session_launch_descriptor_pin" + where)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining("StartSession launch descriptor pins are immutable"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "DELETE FROM game_session_start_session_template_association_pin" - + where)) + assertThatThrownBy(() -> + fixture + .dsl() + .execute( + "DELETE FROM game_session_start_session_template_association_pin" + where)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining("StartSession template association pins are immutable"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute("TRUNCATE game_session_start_session_launch_descriptor_pin")) + assertThatThrownBy(() -> + fixture.dsl().execute("TRUNCATE game_session_start_session_launch_descriptor_pin")) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining("StartSession launch descriptor pins are immutable"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute("TRUNCATE game_session_start_session_template_association_pin")) + assertThatThrownBy(() -> + fixture.dsl().execute("TRUNCATE game_session_start_session_template_association_pin")) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining("cannot truncate a table referenced in a foreign key constraint") .hasStackTraceContaining("game_session_start_session_launch_descriptor_pin") .hasStackTraceContaining("game_session_start_session_template_association_pin"); - assertThatThrownBy( - () -> - fixture - .dsl() - .execute( - "TRUNCATE game_session_start_session_template_association_pin CASCADE")) + assertThatThrownBy(() -> + fixture + .dsl() + .execute("TRUNCATE game_session_start_session_template_association_pin CASCADE")) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining("pins are immutable"); @@ -1062,15 +1039,14 @@ LaunchInputs createLaunch(Duration leaseDuration) { StartingInstance starting = Objects.requireNonNull( transactions() - .execute( - status -> - startingRepository.createStarting( - fresh.tenantAssociation(), - binding, - tuple.preAuthorizationTuple().action().target().ownerAccountId(), - tuple.controlPlaneRequestId(), - tuple.mutationDigest(), - tuple)), + .execute(status -> + startingRepository.createStarting( + fresh.tenantAssociation(), + binding, + tuple.preAuthorizationTuple().action().target().ownerAccountId(), + tuple.controlPlaneRequestId(), + tuple.mutationDigest(), + tuple)), "created original Human StartSession instance"); var attempts = new GameSessionStartSessionOperatorAttemptRepository(dsl, leaseDuration); AttemptSnapshot attempt = @@ -1083,10 +1059,9 @@ LaunchInputs createLaunch(Duration leaseDuration) { associationReadRepository .readOriginalStartSessionAssociation( originalSelector(starting.launchAssociation(), tuple, claim)) - .orElseThrow( - () -> - new IllegalStateException( - "Canonical Human launch association must read back with its original owner")); + .orElseThrow(() -> + new IllegalStateException( + "Canonical Human launch association must read back with its original owner")); assertThat(original.association()).isEqualTo(starting.launchAssociation()); assertThat(original.postAuthorizationExecutionTuple().canonicalBytes()) .containsExactly(tuple.canonicalBytes()); @@ -1116,13 +1091,12 @@ private FreshAssociationInputs createFreshAssociation(AuthoredWorldSourceEvidenc FreshGameSessionTenantAssociation tenantAssociation = Objects.requireNonNull( transactions() - .execute( - status -> - tenantRepository.associateFresh( - UUID.randomUUID(), - NAMESPACE, - sourceReceipt, - CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(source))), + .execute(status -> + tenantRepository.associateFresh( + UUID.randomUUID(), + NAMESPACE, + sourceReceipt, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(source))), "created canonical fresh tenant association"); return new FreshAssociationInputs(sourceReceipt, tenantAssociation); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionServiceTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionServiceTest.java index 4e98f89a0c..51ddaac1b2 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionServiceTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionServiceTest.java @@ -530,11 +530,10 @@ private static void stubAuthenticatedSourceResult( when(source.canonicalBytes()).thenReturn(bytes); when(source.digest()).thenReturn(sha256(bytes)); when(inputs.gameDesign().read(any(AuthoredInitialActorCoreReadEvidence.ReadRequest.class))) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return source; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return source; + }); } private static AttemptSnapshot snapshot(TestInputs inputs, UUID mutationId) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java index a22292e506..7e115e1ec7 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryIntegrationTest.java @@ -115,13 +115,12 @@ void persistsExactFreshSelectorsAndSharedNamespaceWithoutChangingRetainedNumeric + "FROM gameplay_tenant_shared_playable_state_namespace " + "WHERE canonical_tenant_id = ?", tenant(1))) - .satisfies( - row -> { - assertThat(row.get("tenant_id", Long.class)).isNull(); - assertThat(row.get("canonical_tenant_id", UUID.class)).isEqualTo(tenant(1)); - assertThat(row.get("playable_state_namespace_id", UUID.class)) - .isEqualTo(created.playableStateNamespaceId()); - }); + .satisfies(row -> { + assertThat(row.get("tenant_id", Long.class)).isNull(); + assertThat(row.get("canonical_tenant_id", UUID.class)).isEqualTo(tenant(1)); + assertThat(row.get("playable_state_namespace_id", UUID.class)) + .isEqualTo(created.playableStateNamespaceId()); + }); assertThat( requiredRecord( fixture.dsl, @@ -199,34 +198,31 @@ void persistsExactFreshSelectorsAndSharedNamespaceWithoutChangingRetainedNumeric .get("xmin", String.class)) .isEqualTo(retainedNamespaceXmin); - assertThatThrownBy( - () -> - fixture.create( - request( - source, - uuid(21), - "another-realm", - "Another Realm", - "PRESEEDED_ONLY", - "SHARED"))) + assertThatThrownBy(() -> + fixture.create( + request( + source, + uuid(21), + "another-realm", + "Another Realm", + "PRESEEDED_ONLY", + "SHARED"))) .isInstanceOf(CatalogConflictException.class) .hasMessageContaining("already has a public-production"); assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) .isEqualTo(1); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "UPDATE game_session_canonical_realm_catalog SET realm_slug = ? " - + "WHERE creation_request_id = ?", - "rewritten-realm", - request.requestId())) + assertThatThrownBy(() -> + fixture.dsl.execute( + "UPDATE game_session_canonical_realm_catalog SET realm_slug = ? " + + "WHERE creation_request_id = ?", + "rewritten-realm", + request.requestId())) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("evidence is immutable"); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "DELETE FROM game_session_canonical_realm_catalog WHERE creation_request_id = ?", - request.requestId())) + assertThatThrownBy(() -> + fixture.dsl.execute( + "DELETE FROM game_session_canonical_realm_catalog WHERE creation_request_id = ?", + request.requestId())) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("evidence is immutable"); assertThatThrownBy(() -> fixture.dsl.execute("TRUNCATE game_session_canonical_realm_catalog")) @@ -238,21 +234,19 @@ void persistsExactFreshSelectorsAndSharedNamespaceWithoutChangingRetainedNumeric () -> fixture.dsl.execute("TRUNCATE game_session_canonical_realm_catalog CASCADE")) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("evidence is immutable"); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "UPDATE gameplay_tenant_shared_playable_state_namespace " - + "SET playable_state_namespace_id = ? WHERE canonical_tenant_id = ?", - uuid(805), - tenant(1))) + assertThatThrownBy(() -> + fixture.dsl.execute( + "UPDATE gameplay_tenant_shared_playable_state_namespace " + + "SET playable_state_namespace_id = ? WHERE canonical_tenant_id = ?", + uuid(805), + tenant(1))) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("fresh shared namespace identity is immutable"); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "DELETE FROM gameplay_tenant_shared_playable_state_namespace " - + "WHERE canonical_tenant_id = ?", - tenant(1))) + assertThatThrownBy(() -> + fixture.dsl.execute( + "DELETE FROM gameplay_tenant_shared_playable_state_namespace " + + "WHERE canonical_tenant_id = ?", + tenant(1))) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("fresh shared namespace identity is immutable"); assertThatThrownBy( @@ -315,9 +309,8 @@ void historicalCatalogAndAssociationRemainUnchangedWithoutPoisoningFreshDiscover () -> fixture.catalogRepository.readByRequest(NAMESPACE, historicalRequest.requestId())) .isInstanceOf(InvalidCatalogEvidenceException.class) .hasMessageContaining("Exactly one complete catalog policy provenance required"); - assertThatThrownBy( - () -> - fixture.catalogRepository.readUniqueVisiblePublicProduction(NAMESPACE, tenant(40))) + assertThatThrownBy(() -> + fixture.catalogRepository.readUniqueVisiblePublicProduction(NAMESPACE, tenant(40))) .isInstanceOf(InvalidCatalogEvidenceException.class); IntakeReceipt freshSource = @@ -352,23 +345,22 @@ void discoveryStillRejectsMalformedEvidenceAndDatabaseRejectsPartialOrBothProven () -> insertCatalogRow(fixture, source, request, java.util.Map.of(column, value))) .isInstanceOf(DataAccessException.class); } - assertThatThrownBy( - () -> - insertCatalogRow( - fixture, - source, - request, - java.util.Map.of( - "complete_policy_set_evidence", - new byte[] {1}, - "fixture_policy_request_bytes", - new byte[] {1}, - "fixture_policy_seal_operation_id", - uuid(1043), - "fixture_policy_seal_request_digest", - "sha256:" + "a".repeat(64), - "fixture_policy_seal_evidence_digest", - "sha256:" + "b".repeat(64)))) + assertThatThrownBy(() -> + insertCatalogRow( + fixture, + source, + request, + java.util.Map.of( + "complete_policy_set_evidence", + new byte[] {1}, + "fixture_policy_request_bytes", + new byte[] {1}, + "fixture_policy_seal_operation_id", + uuid(1043), + "fixture_policy_seal_request_digest", + "sha256:" + "a".repeat(64), + "fixture_policy_seal_evidence_digest", + "sha256:" + "b".repeat(64)))) .isInstanceOf(DataAccessException.class); assertThatThrownBy(() -> insertCatalogRow(fixture, source, request, java.util.Map.of())) .isInstanceOf(DataAccessException.class); @@ -394,10 +386,9 @@ void requiresOwnerWriteTransactionRejectsChangedRequestAndDeniesRetainedProvenan .hasMessageContaining("active owner transaction"); TransactionTemplate readOnly = new TransactionTemplate(fixture.transactionManager); readOnly.setReadOnly(true); - assertThatThrownBy( - () -> - readOnly.execute( - status -> fixture.catalogRepository.createInitialPublicProduction(prepared))) + assertThatThrownBy(() -> + readOnly.execute( + status -> fixture.catalogRepository.createInitialPublicProduction(prepared))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("read-write"); @@ -481,11 +472,9 @@ void requiresOwnerWriteTransactionRejectsChangedRequestAndDeniesRetainedProvenan + "WHERE operation_id = ?", retained.operationId()) .get("xmin", String.class); - assertThatThrownBy( - () -> - fixture.create( - request( - retained, uuid(31), "retained-realm", "Realm", "PRESEEDED_ONLY", "SHARED"))) + assertThatThrownBy(() -> + fixture.create( + request(retained, uuid(31), "retained-realm", "Realm", "PRESEEDED_ONLY", "SHARED"))) .isInstanceOf(InvalidCatalogEvidenceException.class) .hasMessageContaining("fresh Game Design"); assertThat( @@ -494,23 +483,21 @@ retained, uuid(31), "retained-realm", "Realm", "PRESEEDED_ONLY", "SHARED"))) "SELECT xmin::text AS xmin, provenance_kind FROM " + "game_session_authored_world_tenant_source_binding WHERE canonical_tenant_id = ?", retained.source().canonicalTenantId())) - .satisfies( - row -> { - assertThat(row.get("xmin", String.class)).isEqualTo(retainedBindingXmin); - assertThat(row.get("provenance_kind", String.class)).isEqualTo("RETAINED_GAME_V29"); - }); + .satisfies(row -> { + assertThat(row.get("xmin", String.class)).isEqualTo(retainedBindingXmin); + assertThat(row.get("provenance_kind", String.class)).isEqualTo("RETAINED_GAME_V29"); + }); assertThat( requiredRecord( fixture.dsl, "SELECT xmin::text AS xmin, source_provenance_kind FROM " + "game_session_authored_world_source_intake WHERE operation_id = ?", retained.operationId())) - .satisfies( - row -> { - assertThat(row.get("xmin", String.class)).isEqualTo(retainedIntakeXmin); - assertThat(row.get("source_provenance_kind", String.class)) - .isEqualTo("RETAINED_GAME_V29"); - }); + .satisfies(row -> { + assertThat(row.get("xmin", String.class)).isEqualTo(retainedIntakeXmin); + assertThat(row.get("source_provenance_kind", String.class)) + .isEqualTo("RETAINED_GAME_V29"); + }); assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_session_canonical_realm_catalog")))) .isEqualTo(1); } @@ -521,47 +508,45 @@ void rawSqlRejectsV30AndUnknownProvenanceForNewSourceRows() { for (String provenance : new String[] {"RETAINED_GAME_V30", "UNKNOWN_KIND"}) { int suffix = provenance.equals("RETAINED_GAME_V30") ? 1 : 2; - assertThatThrownBy( - () -> - fixture.dsl.execute( - "INSERT INTO game_session_authored_world_tenant_source_binding " - + "(target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id, " - + "source_game_tenant_key, provenance_kind) VALUES (?, ?, ?, ?, ?, ?)", - NAMESPACE, - uuid(900 + suffix), - "raw-binding-" + suffix, - 990L + suffix, - "legacy-key-" + suffix, - provenance)) + assertThatThrownBy(() -> + fixture.dsl.execute( + "INSERT INTO game_session_authored_world_tenant_source_binding " + + "(target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id, " + + "source_game_tenant_key, provenance_kind) VALUES (?, ?, ?, ?, ?, ?)", + NAMESPACE, + uuid(900 + suffix), + "raw-binding-" + suffix, + 990L + suffix, + "legacy-key-" + suffix, + provenance)) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("chk_gs_authored_world_tenant_source_provenance_v29"); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "INSERT INTO game_session_authored_world_source_intake (" - + "operation_id, schema_version, target_namespace, intake_request_id, " - + "request_digest, source_schema_version, source_registration_request_id, " - + "source_operation_id, source_request_digest, canonical_tenant_id, " - + "tenant_slug, world_slug, world_display_name, source_game_row_id, " - + "source_game_tenant_key, source_provenance_kind, source_evidence_digest, " - + "receipt_digest) VALUES (?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - uuid(910 + suffix), - NAMESPACE, - uuid(920 + suffix), - "sha256:" + "a".repeat(64), - uuid(930 + suffix), - uuid(940 + suffix), - "sha256:" + "b".repeat(64), - uuid(900 + suffix), - "raw-binding-" + suffix, - "raw-world-" + suffix, - "Raw World", - 990L + suffix, - "legacy-key-" + suffix, - provenance, - "sha256:" + "c".repeat(64), - "sha256:" + "d".repeat(64))) + assertThatThrownBy(() -> + fixture.dsl.execute( + "INSERT INTO game_session_authored_world_source_intake (" + + "operation_id, schema_version, target_namespace, intake_request_id, " + + "request_digest, source_schema_version, source_registration_request_id, " + + "source_operation_id, source_request_digest, canonical_tenant_id, " + + "tenant_slug, world_slug, world_display_name, source_game_row_id, " + + "source_game_tenant_key, source_provenance_kind, source_evidence_digest, " + + "receipt_digest) VALUES (?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + uuid(910 + suffix), + NAMESPACE, + uuid(920 + suffix), + "sha256:" + "a".repeat(64), + uuid(930 + suffix), + uuid(940 + suffix), + "sha256:" + "b".repeat(64), + uuid(900 + suffix), + "raw-binding-" + suffix, + "raw-world-" + suffix, + "Raw World", + 990L + suffix, + "legacy-key-" + suffix, + provenance, + "sha256:" + "c".repeat(64), + "sha256:" + "d".repeat(64))) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("chk_gs_authored_world_source_intake_provenance_v29"); } @@ -581,42 +566,41 @@ void v40PreservesExistingV30SourceRowsAndRejectsNewV30Rows() { String sourceEvidenceDigest = "sha256:" + "3".repeat(64); String receiptDigest = "sha256:" + "4".repeat(64); - fixture.transactions.execute( - status -> { - fixture.dsl.execute( - "INSERT INTO game_session_authored_world_tenant_source_binding " - + "(target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id, " - + "source_game_tenant_key, provenance_kind) VALUES (?, ?, ?, ?, ?, 'RETAINED_GAME_V30')", - NAMESPACE, - canonicalTenantId, - tenantSlug, - sourceGameRowId, - sourceGameTenantKey); - fixture.dsl.execute( - "INSERT INTO game_session_authored_world_source_intake (" - + "operation_id, schema_version, target_namespace, intake_request_id, " - + "request_digest, source_schema_version, source_registration_request_id, " - + "source_operation_id, source_request_digest, canonical_tenant_id, tenant_slug, " - + "world_slug, world_display_name, source_game_row_id, source_game_tenant_key, " - + "source_provenance_kind, source_evidence_digest, receipt_digest) " - + "VALUES (?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'RETAINED_GAME_V30', ?, ?)", - intakeOperationId, - NAMESPACE, - uuid(952), - requestDigest, - uuid(953), - uuid(954), - sourceRequestDigest, - canonicalTenantId, - tenantSlug, - worldSlug, - "Retained V30 World", - sourceGameRowId, - sourceGameTenantKey, - sourceEvidenceDigest, - receiptDigest); - return null; - }); + fixture.transactions.execute(status -> { + fixture.dsl.execute( + "INSERT INTO game_session_authored_world_tenant_source_binding " + + "(target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id, " + + "source_game_tenant_key, provenance_kind) VALUES (?, ?, ?, ?, ?, 'RETAINED_GAME_V30')", + NAMESPACE, + canonicalTenantId, + tenantSlug, + sourceGameRowId, + sourceGameTenantKey); + fixture.dsl.execute( + "INSERT INTO game_session_authored_world_source_intake (" + + "operation_id, schema_version, target_namespace, intake_request_id, " + + "request_digest, source_schema_version, source_registration_request_id, " + + "source_operation_id, source_request_digest, canonical_tenant_id, tenant_slug, " + + "world_slug, world_display_name, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, source_evidence_digest, receipt_digest) " + + "VALUES (?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'RETAINED_GAME_V30', ?, ?)", + intakeOperationId, + NAMESPACE, + uuid(952), + requestDigest, + uuid(953), + uuid(954), + sourceRequestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + "Retained V30 World", + sourceGameRowId, + sourceGameTenantKey, + sourceEvidenceDigest, + receiptDigest); + return null; + }); Record retainedBindingBefore = requiredRecord( @@ -656,46 +640,44 @@ void v40PreservesExistingV30SourceRowsAndRejectsNewV30Rows() { .isEqualTo(sourceEvidenceDigest); assertThat(retainedIntakeAfter.get("receipt_digest", String.class)).isEqualTo(receiptDigest); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "INSERT INTO game_session_authored_world_tenant_source_binding " - + "(target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id, " - + "source_game_tenant_key, provenance_kind) " - + "VALUES (?, ?, ?, ?, ?, 'RETAINED_GAME_V30')", - NAMESPACE, - uuid(960), - "new-v30-tenant", - 9760L, - "gds-new-v30")) + assertThatThrownBy(() -> + fixture.dsl.execute( + "INSERT INTO game_session_authored_world_tenant_source_binding " + + "(target_namespace, canonical_tenant_id, tenant_slug, source_game_row_id, " + + "source_game_tenant_key, provenance_kind) " + + "VALUES (?, ?, ?, ?, ?, 'RETAINED_GAME_V30')", + NAMESPACE, + uuid(960), + "new-v30-tenant", + 9760L, + "gds-new-v30")) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("chk_gs_authored_world_tenant_source_provenance_v29"); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "INSERT INTO game_session_authored_world_source_intake (" - + "operation_id, schema_version, target_namespace, intake_request_id, " - + "request_digest, source_schema_version, source_registration_request_id, " - + "source_operation_id, source_request_digest, canonical_tenant_id, tenant_slug, " - + "world_slug, world_display_name, source_game_row_id, source_game_tenant_key, " - + "source_provenance_kind, source_evidence_digest, receipt_digest) " - + "VALUES (?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, " - + "'RETAINED_GAME_V30', ?, ?)", - uuid(961), - NAMESPACE, - uuid(962), - requestDigest, - uuid(963), - uuid(964), - sourceRequestDigest, - uuid(965), - "new-v30-tenant", - "new-v30-world", - "New V30 World", - 9761L, - "gds-new-v30-intake", - sourceEvidenceDigest, - receiptDigest)) + assertThatThrownBy(() -> + fixture.dsl.execute( + "INSERT INTO game_session_authored_world_source_intake (" + + "operation_id, schema_version, target_namespace, intake_request_id, " + + "request_digest, source_schema_version, source_registration_request_id, " + + "source_operation_id, source_request_digest, canonical_tenant_id, tenant_slug, " + + "world_slug, world_display_name, source_game_row_id, source_game_tenant_key, " + + "source_provenance_kind, source_evidence_digest, receipt_digest) " + + "VALUES (?, 1, ?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "'RETAINED_GAME_V30', ?, ?)", + uuid(961), + NAMESPACE, + uuid(962), + requestDigest, + uuid(963), + uuid(964), + sourceRequestDigest, + uuid(965), + "new-v30-tenant", + "new-v30-world", + "New V30 World", + 9761L, + "gds-new-v30-intake", + sourceEvidenceDigest, + receiptDigest)) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("chk_gs_authored_world_source_intake_provenance_v29"); } @@ -727,13 +709,12 @@ void isolatedCreationAllocatesDistinctRealmLocalNamespacesOutsideSharedRegistry( .isEmpty(); assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, uuid(40))).contains(first); assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, uuid(50))).contains(second); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "UPDATE gameplay_tenant_shared_playable_state_namespace " - + "SET playable_state_namespace_id = ? WHERE tenant_id = ?", - first.playableStateNamespaceId(), - RETAINED_TENANT_ID)) + assertThatThrownBy(() -> + fixture.dsl.execute( + "UPDATE gameplay_tenant_shared_playable_state_namespace " + + "SET playable_state_namespace_id = ? WHERE tenant_id = ?", + first.playableStateNamespaceId(), + RETAINED_TENANT_ID)) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining( "Legacy tenant SHARED namespace conflicts with a canonical ISOLATED realm namespace"); @@ -1024,40 +1005,39 @@ private static void insertHistoricalFreshAssociation(Fixture fixture, IntakeRece AuthoredWorldSourceEvidence source = receipt.source(); UUID operationId = uuid(1044); long privateTenantId = 1044L; - fixture.transactions.execute( - status -> { - fixture.dsl.execute( - "INSERT INTO game_session_tenant_scope_reservation " - + "(game_session_tenant_id, reservation_kind) VALUES (?, 'FRESH_SOURCE_BOUND')", - privateTenantId); - fixture.dsl.execute( - "INSERT INTO game_session_tenant_canonical_claim " - + "(target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, association_kind, " - + "reservation_kind, association_operation_id, association_request_id) " - + "VALUES (?, ?, ?, 'FRESH_SOURCE_BOUND', 'FRESH_SOURCE_BOUND', ?, ?)", - NAMESPACE, - source.canonicalTenantId(), - privateTenantId, - operationId, - source.registrationRequestId()); - fixture.dsl.execute( - "INSERT INTO game_session_fresh_tenant_association " - + "(association_operation_id, target_namespace, association_request_id, source_schema_version, " - + "source_target_namespace, source_request_id, source_canonical_tenant_id, canonical_tenant_id, " - + "legacy_game_session_tenant_id, source_game_row_id, source_game_tenant_key, provenance_kind) " - + "VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW')", - operationId, - NAMESPACE, - source.registrationRequestId(), - NAMESPACE, - source.registrationRequestId(), - source.canonicalTenantId(), - source.canonicalTenantId(), - privateTenantId, - source.sourceGameRowId(), - source.sourceGameTenantKey()); - return null; - }); + fixture.transactions.execute(status -> { + fixture.dsl.execute( + "INSERT INTO game_session_tenant_scope_reservation " + + "(game_session_tenant_id, reservation_kind) VALUES (?, 'FRESH_SOURCE_BOUND')", + privateTenantId); + fixture.dsl.execute( + "INSERT INTO game_session_tenant_canonical_claim " + + "(target_namespace, canonical_tenant_id, legacy_game_session_tenant_id, association_kind, " + + "reservation_kind, association_operation_id, association_request_id) " + + "VALUES (?, ?, ?, 'FRESH_SOURCE_BOUND', 'FRESH_SOURCE_BOUND', ?, ?)", + NAMESPACE, + source.canonicalTenantId(), + privateTenantId, + operationId, + source.registrationRequestId()); + fixture.dsl.execute( + "INSERT INTO game_session_fresh_tenant_association " + + "(association_operation_id, target_namespace, association_request_id, source_schema_version, " + + "source_target_namespace, source_request_id, source_canonical_tenant_id, canonical_tenant_id, " + + "legacy_game_session_tenant_id, source_game_row_id, source_game_tenant_key, provenance_kind) " + + "VALUES (?, ?, ?, 1, ?, ?, ?, ?, ?, ?, ?, 'NEW_GAME_ROW')", + operationId, + NAMESPACE, + source.registrationRequestId(), + NAMESPACE, + source.registrationRequestId(), + source.canonicalTenantId(), + source.canonicalTenantId(), + privateTenantId, + source.sourceGameRowId(), + source.sourceGameTenantKey()); + return null; + }); } private static void insertCatalogRow( @@ -1265,17 +1245,15 @@ PreparedInitialPublicProduction prepare(CreateCanonicalRealmCatalogRequest reque if (retained || !"NEW_GAME_ROW".equals(source.source().provenanceKind())) { return catalogRepository.prepareInitialPublicProduction(request, null); } - transactions.execute( - status -> - new GameSessionFreshTenantAssociationRepository(dsl) - .associateFresh( - UUID.nameUUIDFromBytes( - ("gs-association/" + source.source().canonicalTenantId()) - .getBytes(java.nio.charset.StandardCharsets.UTF_8)), - source.source().targetNamespace(), - source, - CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( - source.source()))); + transactions.execute(status -> + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + UUID.nameUUIDFromBytes( + ("gs-association/" + source.source().canonicalTenantId()) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)), + source.source().targetNamespace(), + source, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(source.source()))); UUID versionId = UUID.nameUUIDFromBytes( ("controlled-version/" + source.source().canonicalTenantId()) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java index 5b8db5d07b..db1fc7a01e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalStartingInstanceRepositoryIntegrationTest.java @@ -212,10 +212,9 @@ void changedOwnerDigestOrBindingConflictsWithoutCreatingAnotherRuntimeRow() { () -> fixture.start(uuid(209), CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, binding)) .isInstanceOf(InvalidCanonicalStartingInstanceEvidenceException.class) .hasMessageContaining("owner"); - assertThatThrownBy( - () -> - fixture.start( - OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, OTHER_REQUEST_DIGEST, binding)) + assertThatThrownBy(() -> + fixture.start( + OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, OTHER_REQUEST_DIGEST, binding)) .isInstanceOf(InvalidCanonicalStartingInstanceEvidenceException.class) .hasMessageContaining("launch request"); @@ -226,10 +225,9 @@ void changedOwnerDigestOrBindingConflictsWithoutCreatingAnotherRuntimeRow() { CONTROL_PLANE_REQUEST_ID, CHANGED_LAUNCH_DESCRIPTOR_ID, fixture.source().source().operationId()); - assertThatThrownBy( - () -> - fixture.start( - OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, changedBinding)) + assertThatThrownBy(() -> + fixture.start( + OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, changedBinding)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Canonical descriptor pin differs from complete launch binding"); @@ -258,10 +256,9 @@ void invalidPersistedSourceAndMissingRealmLeaveNoPartialStartingRowOrAssociation CONTROL_PLANE_REQUEST_ID, "descriptor-for-starting", uuid(299)); - assertThatThrownBy( - () -> - fixture.start( - OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, mismatchedSource)) + assertThatThrownBy(() -> + fixture.start( + OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, mismatchedSource)) .isInstanceOf(InvalidCanonicalStartingInstanceEvidenceException.class) .hasMessageContaining("persisted authored-world source receipt"); assertNoStartingRows(fixture); @@ -270,10 +267,9 @@ void invalidPersistedSourceAndMissingRealmLeaveNoPartialStartingRowOrAssociation CompleteLaunchBindingEvidence validBinding = launchBinding( missingRealm.source().source(), missingRealm.publishedSet(), CONTROL_PLANE_REQUEST_ID); - assertThatThrownBy( - () -> - missingRealm.start( - OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, validBinding)) + assertThatThrownBy(() -> + missingRealm.start( + OWNER_ACCOUNT_UUID, CONTROL_PLANE_REQUEST_ID, REQUEST_DIGEST, validBinding)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("visible public SHARED realm"); assertNoStartingRows(missingRealm); @@ -305,17 +301,12 @@ void captureWaitsForRequestLockBeforeRejectingUnavailableOriginalPins() throws E } Future capture = - executor.submit( - () -> - fixture - .transactions() - .executeWithoutResult( - status -> - associationRepository.capture( - fixture.tenantAssociation(), - 1L, - unpinnedBinding, - unpinnedTuple))); + executor.submit(() -> + fixture + .transactions() + .executeWithoutResult(status -> + associationRepository.capture( + fixture.tenantAssociation(), 1L, unpinnedBinding, unpinnedTuple))); awaitAdvisoryWaiter(fixture, lockKey, capture); assertThat(capture.isDone()).isFalse(); assertNoStartingRows(fixture); @@ -520,15 +511,14 @@ StartingInstance start( String requestDigest, CompleteLaunchBindingEvidence binding) { return Objects.requireNonNull( - transactions.execute( - status -> - startingRepository.createStarting( - tenantAssociation, - binding, - ownerAccountUuid, - controlPlaneRequestId, - requestDigest, - originalTuple)), + transactions.execute(status -> + startingRepository.createStarting( + tenantAssociation, + binding, + ownerAccountUuid, + controlPlaneRequestId, + requestDigest, + originalTuple)), "canonical STARTING owner result"); } } @@ -563,14 +553,12 @@ private static Fixture fixture(boolean createRealm) { "registered authored-world source receipt"); FreshGameSessionTenantAssociation tenantAssociation = Objects.requireNonNull( - transactions.execute( - status -> - tenantAssociationRepository.associateFresh( - TENANT_ASSOCIATION_OPERATION_ID, - NAMESPACE, - source, - CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( - source.source()))), + transactions.execute(status -> + tenantAssociationRepository.associateFresh( + TENANT_ASSOCIATION_OPERATION_ID, + NAMESPACE, + source, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(source.source()))), "fresh complete source-bound Game Session tenant association"); var request = new CreateCanonicalRealmCatalogRequest( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCurrentPrivatePlaytestPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCurrentPrivatePlaytestPostgresIntegrationTest.java index 25aae26495..256477fa71 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCurrentPrivatePlaytestPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionCurrentPrivatePlaytestPostgresIntegrationTest.java @@ -209,49 +209,42 @@ void absentPreparationWrongScopeAndAbsentPrivatePolicyCannotBecomeCurrent() { Optional initiallyAbsent = context .transaction() - .execute( - status -> - context - .repository() - .readCurrent( - NAMESPACE, - context.scope().tenantId(), - "source-world", - "private-playtest")); + .execute(status -> + context + .repository() + .readCurrent( + NAMESPACE, context.scope().tenantId(), "source-world", "private-playtest")); assertThat(initiallyAbsent).isEmpty(); - assertThatThrownBy( - () -> - context.select( - new Request( - UUID.randomUUID(), - context.scope(), - UUID.randomUUID(), - UUID.randomUUID(), - null, - null))) + assertThatThrownBy(() -> + context.select( + new Request( + UUID.randomUUID(), + context.scope(), + UUID.randomUUID(), + UUID.randomUUID(), + null, + null))) .isInstanceOf(SourceUnavailableException.class); Preparation first = context.prepare(context.now().plusSeconds(3600)); - assertThatThrownBy( - () -> - context.select( - new Request( - UUID.randomUUID(), - new Scope(NAMESPACE, UUID.randomUUID(), "source-world", "private-playtest"), - first.request().requestId(), - first.playtestLifecycleId(), - null, - null))) + assertThatThrownBy(() -> + context.select( + new Request( + UUID.randomUUID(), + new Scope(NAMESPACE, UUID.randomUUID(), "source-world", "private-playtest"), + first.request().requestId(), + first.playtestLifecycleId(), + null, + null))) .isInstanceOf(SourceUnavailableException.class); - assertThatThrownBy( - () -> - context.select( - new Request( - UUID.randomUUID(), - context.scope(), - UUID.randomUUID(), - first.playtestLifecycleId(), - null, - null))) + assertThatThrownBy(() -> + context.select( + new Request( + UUID.randomUUID(), + context.scope(), + UUID.randomUUID(), + first.playtestLifecycleId(), + null, + null))) .isInstanceOf(SourceUnavailableException.class); assertThat(context.count(HISTORY)).isZero(); assertThat(context.count(HEAD)).isZero(); @@ -259,16 +252,15 @@ void absentPreparationWrongScopeAndAbsentPrivatePolicyCannotBecomeCurrent() { assertThatThrownBy(() -> publicOnly.prepare(publicOnly.now().plusSeconds(3600))) .isInstanceOf( GameSessionInitialPlaytestLifecycleRepository.SourceUnavailableException.class); - assertThatThrownBy( - () -> - publicOnly.select( - new Request( - UUID.randomUUID(), - publicOnly.scope(), - UUID.randomUUID(), - UUID.randomUUID(), - null, - null))) + assertThatThrownBy(() -> + publicOnly.select( + new Request( + UUID.randomUUID(), + publicOnly.scope(), + UUID.randomUUID(), + UUID.randomUUID(), + null, + null))) .isInstanceOf(SourceUnavailableException.class); assertThat(publicOnly.count(HEAD)).isZero(); assertThat(publicOnly.count(HISTORY)).isZero(); @@ -284,10 +276,9 @@ void expiredCurrentRemainsNonAdmissibleAndHistoricalReplayDoesNotReplaceIt() { assertThat(context.current().selectedPrepSnapshot().state()).isEqualTo(ReadState.EXPIRED); assertThat(context.current().admissionAllowed()).isFalse(); assertThat(context.select(initial)).isEqualTo(new SelectionResult(selected.receipt(), true)); - assertThatThrownBy( - () -> - context.select( - context.request(UUID.randomUUID(), first, 1L, first.playtestLifecycleId()))) + assertThatThrownBy(() -> + context.select( + context.request(UUID.randomUUID(), first, 1L, first.playtestLifecycleId()))) .isInstanceOf(SourceUnavailableException.class) .hasMessageContaining("expired"); Preparation next = context.prepare(context.now().plusSeconds(3600)); @@ -303,32 +294,27 @@ void rollbackAndFinalCommitExpiryLeaveNeitherHeadNorReceiptAndCannotReserveReque Context context = context(true); Preparation first = context.prepare(context.now().plusSeconds(3600)); Request original = context.request(UUID.randomUUID(), first, null, null); - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult( - status -> { - context.repository().select(original); - throw new IllegalStateException("Controlled protected workflow refusal"); - })) + assertThatThrownBy(() -> + context + .transaction() + .executeWithoutResult(status -> { + context.repository().select(original); + throw new IllegalStateException("Controlled protected workflow refusal"); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("Controlled protected workflow refusal"); assertThat(context.count(HISTORY)).isZero(); assertThat(context.count(HEAD)).isZero(); Preparation shortPreparation = context.prepare(context.now().plusSeconds(5)); - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult( - status -> { - context - .repository() - .select( - context.request(UUID.randomUUID(), shortPreparation, null, null)); - awaitExpiry(context, shortPreparation.request().forkExpiresAt()); - })) + assertThatThrownBy(() -> + context + .transaction() + .executeWithoutResult(status -> { + context + .repository() + .select(context.request(UUID.randomUUID(), shortPreparation, null, null)); + awaitExpiry(context, shortPreparation.request().forkExpiresAt()); + })) .isInstanceOf(RuntimeException.class) .hasStackTraceContaining("expired before final commit"); assertThat(context.count(HISTORY)).isZero(); @@ -352,20 +338,18 @@ void immutableHistoryScopeAndExactHeadReferenceGuardsRejectDirectViolations() { "UPDATE " + HEAD + " SET head_revision = 3", "UPDATE " + HEAD + " SET head_revision = 2", "UPDATE " + HEAD + " SET playtest_lifecycle_id = gen_random_uuid()")) { - assertThatThrownBy( - () -> - context.transaction().executeWithoutResult(status -> context.dsl().execute(sql))) + assertThatThrownBy(() -> + context.transaction().executeWithoutResult(status -> context.dsl().execute(sql))) .as(sql) .isInstanceOf(RuntimeException.class); } assertThat(context.current().selection()).isEqualTo(selected.receipt()); assertThat(context.count(HISTORY)).isEqualTo(1); - assertThatThrownBy( - () -> - context - .repository() - .readCurrent( - NAMESPACE, context.scope().tenantId(), "source-world", "private-playtest")) + assertThatThrownBy(() -> + context + .repository() + .readCurrent( + NAMESPACE, context.scope().tenantId(), "source-world", "private-playtest")) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("owner transaction"); } @@ -456,18 +440,16 @@ private Context context(boolean privatePolicy) { evidenceDigest); var intake = Objects.requireNonNull( - transaction.execute( - status -> - new GameSessionAuthoredWorldSourceRepository(dsl) - .register(UUID.randomUUID(), evidence))); - transaction.executeWithoutResult( - status -> - new GameSessionFreshTenantAssociationRepository(dsl) - .associateFresh( - UUID.randomUUID(), - NAMESPACE, - intake, - CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(evidence))); + transaction.execute(status -> + new GameSessionAuthoredWorldSourceRepository(dsl) + .register(UUID.randomUUID(), evidence))); + transaction.executeWithoutResult(status -> + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + UUID.randomUUID(), + NAMESPACE, + intake, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(evidence))); var catalogRequest = new CreateCanonicalRealmCatalogRequest( UUID.randomUUID(), @@ -575,12 +557,10 @@ SelectionResult select(Request request) { Current current() { return Objects.requireNonNull( - transaction.execute( - status -> - repository - .readCurrent( - NAMESPACE, scope.tenantId(), scope.worldSlug(), scope.realmSlug()) - .orElseThrow())); + transaction.execute(status -> + repository + .readCurrent(NAMESPACE, scope.tenantId(), scope.worldSlug(), scope.realmSlug()) + .orElseThrow())); } int count(String table) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java index ea98d13bfd..98e27a7349 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantAssociationRepositoryIntegrationTest.java @@ -245,18 +245,16 @@ void exactHumanRetryReadsCommittedAssociationAfterAdvisoryWaitOnRepeatableReadDe AtomicReference> retry = new AtomicReference<>(); try { FreshGameSessionTenantAssociation first = - fixture.transactions.execute( - status -> { - fixture.dsl.fetch( - "SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", canonicalLockKey); - retry.set( - executor.submit( - () -> - fixture.associationRepository.associateFreshTenant( - creation.creationRequestId(), creation.requestDigest()))); - awaitAdvisoryWait(fixture, canonicalLockKey); - return fixture.associateFresh(uuid(640), NAMESPACE, source); - }); + fixture.transactions.execute(status -> { + fixture.dsl.fetch( + "SELECT pg_advisory_xact_lock(hashtextextended(?, 0))", canonicalLockKey); + retry.set( + executor.submit(() -> + fixture.associationRepository.associateFreshTenant( + creation.creationRequestId(), creation.requestDigest()))); + awaitAdvisoryWait(fixture, canonicalLockKey); + return fixture.associateFresh(uuid(640), NAMESPACE, source); + }); FreshTenantAssociation actualRetry = retry.get().get(15, TimeUnit.SECONDS); assertThat(actualRetry.targetNamespace()).isEqualTo(creation.targetNamespace()); @@ -379,10 +377,9 @@ void differentCreationRequestForBoundCanonicalTenantConflictsWithoutOwnerMutatio original.legacyGameSessionTenantId()), "expected original source-bound tenant reservation"); - assertThatThrownBy( - () -> - fixture.associationRepository.associateFreshTenant( - competingEvidence.creationRequestId(), competingEvidence.requestDigest())) + assertThatThrownBy(() -> + fixture.associationRepository.associateFreshTenant( + competingEvidence.creationRequestId(), competingEvidence.requestDigest())) .isExactlyInstanceOf(FreshTenantAssociationConflictException.class) .hasMessageContaining("canonical tenant"); verify(humanFixture.gameDesignClient()) @@ -486,13 +483,12 @@ void retainedSourceProvenanceCannotCreateAFreshTenantMapping() { // A complete NEW_GAME_ROW candidate is deliberately paired with the committed retained // receipt so the real GS intake reader exercises its provenance refusal before allocation. - assertThatThrownBy( - () -> - fixture.associate( - uuid(622), - NAMESPACE, - retainedSource, - creationEvidence(retainedSource.source(), "NEW_GAME_ROW"))) + assertThatThrownBy(() -> + fixture.associate( + uuid(622), + NAMESPACE, + retainedSource, + creationEvidence(retainedSource.source(), "NEW_GAME_ROW"))) .isInstanceOf(InvalidFreshTenantSourceException.class) .hasMessageContaining("NEW_GAME_ROW"); @@ -504,11 +500,10 @@ void retainedSourceProvenanceCannotCreateAFreshTenantMapping() { + "WHERE canonical_tenant_id = ?", retainedSource.source().canonicalTenantId()), "expected retained tenant source binding after denial")) - .satisfies( - row -> { - assertThat(row.get("xmin", String.class)).isEqualTo(bindingXmin); - assertThat(row.get("provenance_kind", String.class)).isEqualTo("RETAINED_GAME_V29"); - }); + .satisfies(row -> { + assertThat(row.get("xmin", String.class)).isEqualTo(bindingXmin); + assertThat(row.get("provenance_kind", String.class)).isEqualTo("RETAINED_GAME_V29"); + }); assertThat( Objects.requireNonNull( fixture.dsl.fetchOne( @@ -516,12 +511,11 @@ void retainedSourceProvenanceCannotCreateAFreshTenantMapping() { + "FROM game_session_authored_world_source_intake WHERE operation_id = ?", retainedSource.operationId()), "expected retained source intake after denial")) - .satisfies( - row -> { - assertThat(row.get("xmin", String.class)).isEqualTo(intakeXmin); - assertThat(row.get("source_provenance_kind", String.class)) - .isEqualTo("RETAINED_GAME_V29"); - }); + .satisfies(row -> { + assertThat(row.get("xmin", String.class)).isEqualTo(intakeXmin); + assertThat(row.get("source_provenance_kind", String.class)) + .isEqualTo("RETAINED_GAME_V29"); + }); assertNoFreshAssociation(fixture); } @@ -807,10 +801,9 @@ IntakeReceipt registerSource( FreshGameSessionTenantAssociation associateFresh( UUID associationOperationId, String namespace, IntakeReceipt source) { - return transactions.execute( - status -> - associationRepository.associateFresh( - associationOperationId, namespace, source, creationEvidence(source.source()))); + return transactions.execute(status -> + associationRepository.associateFresh( + associationOperationId, namespace, source, creationEvidence(source.source()))); } FreshGameSessionTenantAssociation associate( @@ -825,10 +818,9 @@ FreshGameSessionTenantAssociation associate( IntakeReceipt source, FreshTenantCreationEvidence creationEvidence) { return Objects.requireNonNull( - transactions.execute( - status -> - associationRepository.associateFresh( - associationOperationId, namespace, source, creationEvidence)), + transactions.execute(status -> + associationRepository.associateFresh( + associationOperationId, namespace, source, creationEvidence)), "fresh tenant association result"); } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantHistoryPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantHistoryPostgresIntegrationTest.java index 647e436514..497327079a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantHistoryPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionFreshTenantHistoryPostgresIntegrationTest.java @@ -140,12 +140,11 @@ void originalV25AssociationRetainsItsPhysicalRowsAndCannotGainMissingCreationAut .class) .hasMessageContaining("complete_source_evidence"); verifyNoInteractions(client); - assertThatThrownBy( - () -> - sql.execute( - "UPDATE game_session_fresh_tenant_association SET complete_source_evidence = '{}'::jsonb " - + "WHERE canonical_tenant_id = ?", - tenantId)) + assertThatThrownBy(() -> + sql.execute( + "UPDATE game_session_fresh_tenant_association SET complete_source_evidence = '{}'::jsonb " + + "WHERE canonical_tenant_id = ?", + tenantId)) .isInstanceOf(DataAccessException.class); assertThat(snapshot(sql, originalColumns)).isEqualTo(before); assertThat(history(sql, lastOriginalRank)).isEqualTo(originalHistory); @@ -172,22 +171,21 @@ private static void migrate(DriverManagerDataSource source, String schema, Strin private static Map>> snapshot( DSLContext sql, Map> columns) { Map>> rows = new LinkedHashMap<>(); - columns.forEach( - (table, names) -> { - String projection = - names.stream() - .map(GameSessionFreshTenantHistoryPostgresIntegrationTest::quote) - .collect(Collectors.joining(", ")); - rows.put( - table, - sql.fetch( - "SELECT jsonb_build_array(" - + projection - + ")::text AS original_bytes, xmin::text AS physical_version FROM " - + quote(table) - + " ORDER BY original_bytes") - .intoMaps()); - }); + columns.forEach((table, names) -> { + String projection = + names.stream() + .map(GameSessionFreshTenantHistoryPostgresIntegrationTest::quote) + .collect(Collectors.joining(", ")); + rows.put( + table, + sql.fetch( + "SELECT jsonb_build_array(" + + projection + + ")::text AS original_bytes, xmin::text AS physical_version FROM " + + quote(table) + + " ORDER BY original_bytes") + .intoMaps()); + }); return rows; } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionInitialPlaytestLifecyclePostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionInitialPlaytestLifecyclePostgresIntegrationTest.java index 364d6d82f2..ae8cacd557 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionInitialPlaytestLifecyclePostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionInitialPlaytestLifecyclePostgresIntegrationTest.java @@ -132,10 +132,9 @@ void privateRuntimeIdentityAllocationRetainsExactCurrentSourcesAndHasNoGameplayE var currentRead = context .transaction() - .execute( - status -> - owner.readForWorldPreparation( - result.preparationRequestId(), result.playtestLifecycleId())); + .execute(status -> + owner.readForWorldPreparation( + result.preparationRequestId(), result.playtestLifecycleId())); assertThat(currentRead).contains(result); assertThat( retainedRowWithXmin( @@ -204,11 +203,10 @@ void privateRuntimeReadsNeverAllocateAndChangedRetryIntentConflictsWithoutWrites var absentRead = context .transaction() - .execute( - status -> - owner.readForWorldPreparation( - fixture.target().preparationRequestId(), - fixture.target().playtestLifecycleId())); + .execute(status -> + owner.readForWorldPreparation( + fixture.target().preparationRequestId(), + fixture.target().playtestLifecycleId())); assertThat(absentRead).isEmpty(); assertThat(context.dsl().fetchCount(DSL.table(RUNTIME_ALLOCATIONS))).isZero(); var first = allocateRuntime(context, fixture.request()); @@ -301,11 +299,9 @@ void privateRuntimeReadsNeverAllocateAndChangedRetryIntentConflictsWithoutWrites GameSessionPrivateFreshRuntimeAllocationRepository.IdempotencyConflictException .class); } - assertThatThrownBy( - () -> - allocateRuntime( - context, - runtimeRequest(UUID.randomUUID(), fixture.target(), fixture.selection()))) + assertThatThrownBy(() -> + allocateRuntime( + context, runtimeRequest(UUID.randomUUID(), fixture.target(), fixture.selection()))) .isInstanceOf( GameSessionPrivateFreshRuntimeAllocationRepository.IdempotencyConflictException.class); assertThat(owner.readByRequest(r.requestId())).contains(first.snapshot()); @@ -367,14 +363,12 @@ void privateRuntimeHistoricalReplaySurvivesSupersessionButCannotQualifyCurrentSo retainedRowWithXmin(context, RUNTIME_ALLOCATIONS, "request_id", firstRequest.requestId()); var later = context.advancePrivateRevision(revision.advanceRequest()).snapshot(); // Catalog advancement and workflow selection are distinct authorities; a mismatch refuses. - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> - owner.readForWorldPreparation( - initial.preparationRequestId(), initial.playtestLifecycleId()))) + assertThatThrownBy(() -> + context + .transaction() + .execute(status -> + owner.readForWorldPreparation( + initial.preparationRequestId(), initial.playtestLifecycleId()))) .isInstanceOf(IllegalStateException.class); var wrongSelectionRequest = runtimeRequest(UUID.randomUUID(), later, firstSelection); assertThatThrownBy(() -> allocateRuntime(context, wrongSelectionRequest)) @@ -393,10 +387,8 @@ void privateRuntimeHistoricalReplaySurvivesSupersessionButCannotQualifyCurrentSo .isEqualTo( new GameSessionPrivateFreshRuntimeAllocationRepository.Allocation( first.snapshot(), true)); - assertThatThrownBy( - () -> - allocateRuntime( - context, runtimeRequest(UUID.randomUUID(), initial, firstSelection))) + assertThatThrownBy(() -> + allocateRuntime(context, runtimeRequest(UUID.randomUUID(), initial, firstSelection))) .isInstanceOf(IllegalStateException.class); assertThat( retainedRowWithXmin( @@ -421,21 +413,17 @@ void privateRuntimeExpiryRefusesNewEffectsAndKeepsHistoricalAllocationAndRetry() .isEqualTo( new GameSessionPrivateFreshRuntimeAllocationRepository.Allocation( first.snapshot(), true)); - assertThatThrownBy( - () -> - context - .transaction() - .execute( - status -> - owner.readForWorldPreparation( - first.snapshot().preparationRequestId(), - first.snapshot().playtestLifecycleId()))) + assertThatThrownBy(() -> + context + .transaction() + .execute(status -> + owner.readForWorldPreparation( + first.snapshot().preparationRequestId(), + first.snapshot().playtestLifecycleId()))) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - allocateRuntime( - context, - runtimeRequest(UUID.randomUUID(), fixture.target(), fixture.selection()))) + assertThatThrownBy(() -> + allocateRuntime( + context, runtimeRequest(UUID.randomUUID(), fixture.target(), fixture.selection()))) .isInstanceOf(IllegalStateException.class); assertThat( retainedRowWithXmin( @@ -452,38 +440,30 @@ void privateRuntimeExpiryRefusesNewEffectsAndKeepsHistoricalAllocationAndRetry() void privateRuntimeFinalCommitRejectsExpiryOrSourceChangeAndRollsBackAllocation() { var expiring = runtimeFixture(5); Throwable expired = - catchThrowable( - () -> - expiring - .context() - .serializableTransaction() - .executeWithoutResult( - status -> { - new GameSessionPrivateFreshRuntimeAllocationRepository( - expiring.context().dsl()) - .allocate(expiring.request()); - awaitExpiry( - expiring.context(), expiring.preparation().request().forkExpiresAt()); - })); + catchThrowable(() -> + expiring + .context() + .serializableTransaction() + .executeWithoutResult(status -> { + new GameSessionPrivateFreshRuntimeAllocationRepository(expiring.context().dsl()) + .allocate(expiring.request()); + awaitExpiry(expiring.context(), expiring.preparation().request().forkExpiresAt()); + })); assertThat(sqlStateInCauseChain(expired)).isEqualTo("23514"); assertThat(expiring.context().dsl().fetchCount(DSL.table(RUNTIME_ALLOCATIONS))).isZero(); var changed = runtimeFixture(3600); Throwable superseded = - catchThrowable( - () -> - changed - .context() - .serializableTransaction() - .executeWithoutResult( - status -> { - new GameSessionPrivateFreshRuntimeAllocationRepository( - changed.context().dsl()) - .allocate(changed.request()); - // Even a self-consistent re-selection of the same lifecycle changes the - // captured exact head. - selectRuntimeSource( - changed.context(), changed.target(), changed.selection()); - })); + catchThrowable(() -> + changed + .context() + .serializableTransaction() + .executeWithoutResult(status -> { + new GameSessionPrivateFreshRuntimeAllocationRepository(changed.context().dsl()) + .allocate(changed.request()); + // Even a self-consistent re-selection of the same lifecycle changes the + // captured exact head. + selectRuntimeSource(changed.context(), changed.target(), changed.selection()); + })); assertThat(sqlStateInCauseChain(superseded)).isEqualTo("23514"); assertThat(changed.context().dsl().fetchCount(DSL.table(RUNTIME_ALLOCATIONS))).isZero(); } @@ -511,14 +491,12 @@ void privateRuntimeStorageRefusesSelfConsistentForgedSourceAndRetainsImmutableRo "{\"selection_head_revision\":2}", "{\"selection_request_digest\":\"sha256:" + "e".repeat(64) + "\"}")) { Throwable rejected = - catchThrowable( - () -> - context - .serializableTransaction() - .executeWithoutResult( - status -> - insertForgedRuntimeAllocation( - context, fixture.request().requestId(), patch))); + catchThrowable(() -> + context + .serializableTransaction() + .executeWithoutResult(status -> + insertForgedRuntimeAllocation( + context, fixture.request().requestId(), patch))); assertThat(sqlStateInCauseChain(rejected)).as(patch).isIn("23514", "P0002"); } for (String sql : @@ -551,40 +529,32 @@ void privateRuntimeConcurrentStaleSnapshotRequiresWholeTransactionRetryAndRetain var workers = Executors.newFixedThreadPool(2); try { var first = - workers.submit( - () -> - context - .serializableTransaction() - .execute( - status -> { - var result = owner.allocate(fixture.request()); - held.countDown(); - await(release); - return result; - })); + workers.submit(() -> + context + .serializableTransaction() + .execute(status -> { + var result = owner.allocate(fixture.request()); + held.countDown(); + await(release); + return result; + })); await(held); var second = - workers.submit( - () -> { - try { - context - .serializableTransaction() - .executeWithoutResult( - status -> { - assertThat(context.dsl().fetchCount(DSL.table(RUNTIME_ALLOCATIONS))) - .isZero(); - secondPid.set( - context - .dsl() - .fetchSingle("SELECT pg_backend_pid()") - .get(0, Integer.class)); - snapshotEstablished.countDown(); - owner.allocate(fixture.request()); - }); - } catch (Throwable failed) { - secondFailure.set(failed); - } - }); + workers.submit(() -> { + try { + context + .serializableTransaction() + .executeWithoutResult(status -> { + assertThat(context.dsl().fetchCount(DSL.table(RUNTIME_ALLOCATIONS))).isZero(); + secondPid.set( + context.dsl().fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + snapshotEstablished.countDown(); + owner.allocate(fixture.request()); + }); + } catch (Throwable failed) { + secondFailure.set(failed); + } + }); await(snapshotEstablished); awaitAdvisoryLockWait(context, secondPid.get()); release.countDown(); @@ -741,10 +711,9 @@ void allocatesFreshNonAdmissibleIdentityFromExactRetainedCanonicalSourceAndRepla assertThat(selectedPolicy) .isEqualTo( context.published().policies().stream() - .filter( - candidate -> - candidate.source().policy().worldSlug().equals(request.worldSlug()) - && candidate.source().policy().realmSlug().equals(request.realmSlug())) + .filter(candidate -> + candidate.source().policy().worldSlug().equals(request.worldSlug()) + && candidate.source().policy().realmSlug().equals(request.realmSlug())) .findFirst() .orElseThrow()); assertThat(context.prepare(request)).isEqualTo(new Allocation(preparation, true)); @@ -943,12 +912,11 @@ void laterPreparationAndSelectionRemainAvailableAfterPriorPrivateCatalogAllocati Objects.requireNonNull( context .transaction() - .execute( - status -> - selectionRepository - .readCurrent( - NAMESPACE, scope.tenantId(), scope.worldSlug(), scope.realmSlug()) - .orElseThrow())); + .execute(status -> + selectionRepository + .readCurrent( + NAMESPACE, scope.tenantId(), scope.worldSlug(), scope.realmSlug()) + .orElseThrow())); assertThat(current.selection()).isEqualTo(replacementSelection.receipt()); assertThat(current.selectedPrepSnapshot().preparation()).isEqualTo(laterPreparation); assertThat(current.selectedPrepSnapshot().state()).isEqualTo(ReadState.INCOMPLETE); @@ -1052,12 +1020,11 @@ void laterPreparationAndSelectionRemainAvailableAfterPriorPrivateCatalogAllocati Objects.requireNonNull( context .transaction() - .execute( - status -> - selectionRepository - .readCurrent( - NAMESPACE, scope.tenantId(), scope.worldSlug(), scope.realmSlug()) - .orElseThrow())); + .execute(status -> + selectionRepository + .readCurrent( + NAMESPACE, scope.tenantId(), scope.worldSlug(), scope.realmSlug()) + .orElseThrow())); assertThat(currentAfterReplay.selection()).isEqualTo(replacementSelection.receipt()); assertThat(currentAfterReplay.admissionAllowed()).isFalse(); } @@ -1319,12 +1286,11 @@ void advancesPrivateCatalogLifecycleWithoutChangingStableRealmOrOriginalEvidence Objects.requireNonNull( context .transaction() - .execute( - status -> - selections - .readCurrent( - NAMESPACE, scope.tenantId(), scope.worldSlug(), scope.realmSlug()) - .orElseThrow())); + .execute(status -> + selections + .readCurrent( + NAMESPACE, scope.tenantId(), scope.worldSlug(), scope.realmSlug()) + .orElseThrow())); assertThat(currentSelection.selection()).isEqualTo(laterSelection.receipt()); assertThat(currentSelection.selectedPrepSnapshot().preparation()) .isEqualTo(fixture.laterPreparation()); @@ -1339,10 +1305,9 @@ void advancesPrivateCatalogLifecycleWithoutChangingStableRealmOrOriginalEvidence Objects.requireNonNull( context .serializableTransaction() - .execute( - status -> - revisions.readForWorldPreparation( - fixture.laterRequest().requestId(), target.playtestLifecycleId()))); + .execute(status -> + revisions.readForWorldPreparation( + fixture.laterRequest().requestId(), target.playtestLifecycleId()))); assertThat(currentWorldTarget).contains(target); assertThat(context.prepare(fixture.initialRequest())) .isEqualTo(new Allocation(fixture.initialPreparation(), true)); @@ -1518,50 +1483,46 @@ INSERT INTO game_session_private_catalog_revision_history ( second.playtestLifecycleId().toString(), next.requestDigest()); Throwable wrongFrame = - catchThrowable( - () -> - context - .serializableTransaction() - .executeWithoutResult( - status -> - context - .dsl() - .execute( - sql, - second.realmId(), - intended.requestId(), - wrongPreimage, - sha256(wrongPreimage), - "sha256:" + "0".repeat(64), - nextRequest.requestId(), - next.playtestLifecycleId(), - next.playableStateNamespaceId(), - second.playtestLifecycleId()))); + catchThrowable(() -> + context + .serializableTransaction() + .executeWithoutResult(status -> + context + .dsl() + .execute( + sql, + second.realmId(), + intended.requestId(), + wrongPreimage, + sha256(wrongPreimage), + "sha256:" + "0".repeat(64), + nextRequest.requestId(), + next.playtestLifecycleId(), + next.playableStateNamespaceId(), + second.playtestLifecycleId()))); assertThat(sqlStateInCauseChain(wrongFrame)).isEqualTo("23514"); assertThat(databaseFailureSummary(wrongFrame).toLowerCase(java.util.Locale.ROOT)) .contains("request"); assertThat(privateRevisionRows(context)).isEqualTo(before); Throwable wrongReceipt = - catchThrowable( - () -> - context - .serializableTransaction() - .executeWithoutResult( - status -> - context - .dsl() - .execute( - sql, - second.realmId(), - intended.requestId(), - validPreimage, - intended.requestDigest(next.requestDigest()), - "sha256:" + "0".repeat(64), - nextRequest.requestId(), - next.playtestLifecycleId(), - next.playableStateNamespaceId(), - second.playtestLifecycleId()))); + catchThrowable(() -> + context + .serializableTransaction() + .executeWithoutResult(status -> + context + .dsl() + .execute( + sql, + second.realmId(), + intended.requestId(), + validPreimage, + intended.requestDigest(next.requestDigest()), + "sha256:" + "0".repeat(64), + nextRequest.requestId(), + next.playtestLifecycleId(), + next.playableStateNamespaceId(), + second.playtestLifecycleId()))); assertThat(sqlStateInCauseChain(wrongReceipt)).isEqualTo("23514"); assertThat(databaseFailureSummary(wrongReceipt).toLowerCase(java.util.Locale.ROOT)) .contains("receipt"); @@ -1578,26 +1539,24 @@ INSERT INTO game_session_private_catalog_revision_history ( byte[] reusedPreimage = reusedPreparation.canonicalPreimage(fixture.initialPreparation().requestDigest()); Throwable wrongPreparation = - catchThrowable( - () -> - context - .serializableTransaction() - .executeWithoutResult( - status -> - context - .dsl() - .execute( - sql, - second.realmId(), - reusedPreparation.requestId(), - reusedPreimage, - reusedPreparation.requestDigest( - fixture.initialPreparation().requestDigest()), - "sha256:" + "0".repeat(64), - fixture.initialRequest().requestId(), - fixture.initialPreparation().playtestLifecycleId(), - fixture.initialPreparation().playableStateNamespaceId(), - second.playtestLifecycleId()))); + catchThrowable(() -> + context + .serializableTransaction() + .executeWithoutResult(status -> + context + .dsl() + .execute( + sql, + second.realmId(), + reusedPreparation.requestId(), + reusedPreimage, + reusedPreparation.requestDigest( + fixture.initialPreparation().requestDigest()), + "sha256:" + "0".repeat(64), + fixture.initialRequest().requestId(), + fixture.initialPreparation().playtestLifecycleId(), + fixture.initialPreparation().playableStateNamespaceId(), + second.playtestLifecycleId()))); assertThat(sqlStateInCauseChain(wrongPreparation)).isEqualTo("23514"); assertThat(databaseFailureSummary(wrongPreparation).toLowerCase(java.util.Locale.ROOT)) .contains("reuses original"); @@ -1614,11 +1573,10 @@ INSERT INTO game_session_private_catalog_revision_history ( "UPDATE game_session_canonical_realm_catalog SET receipt_digest = receipt_digest", "DELETE FROM game_session_canonical_realm_catalog")) { Throwable refused = - catchThrowable( - () -> - context - .serializableTransaction() - .executeWithoutResult(status -> context.dsl().execute(mutation))); + catchThrowable(() -> + context + .serializableTransaction() + .executeWithoutResult(status -> context.dsl().execute(mutation))); assertThat(refused).as("retained-history mutation: %s", mutation).isNotNull(); assertThat(sqlStateInCauseChain(refused)) .as("retained-history mutation: %s", mutation) @@ -1676,16 +1634,14 @@ void privateRevisionCommitExpiryRollsBackHistoryAndHeadTogether() { var revisions = new GameSessionPrivateFreshCatalogRevisionRepository(context.dsl()); var before = privateRevisionRows(context); Throwable failure = - catchThrowable( - () -> - context - .serializableTransaction() - .executeWithoutResult( - status -> { - var allocated = revisions.advance(fixture.advanceRequest()); - assertThat(allocated.snapshot().catalogRevision()).isEqualTo(2); - awaitExpiry(context, fixture.laterRequest().forkExpiresAt()); - })); + catchThrowable(() -> + context + .serializableTransaction() + .executeWithoutResult(status -> { + var allocated = revisions.advance(fixture.advanceRequest()); + assertThat(allocated.snapshot().catalogRevision()).isEqualTo(2); + awaitExpiry(context, fixture.laterRequest().forkExpiresAt()); + })); assertThat(failure).isNotNull(); assertThat(sqlStateInCauseChain(failure)).isEqualTo("23514"); assertThat(privateRevisionRows(context)).isEqualTo(before); @@ -1708,31 +1664,27 @@ void privateCatalogRequestRejectsChangedPreparationLifecycleAndSecondRequestForO requestId, preparation.request().requestId(), preparation.playtestLifecycleId()); var allocation = context.allocatePrivateTarget(original); - assertThatThrownBy( - () -> - context.allocatePrivateTarget( - new GameSessionPrivateFreshTargetRepository.Request( - requestId, UUID.randomUUID(), preparation.playtestLifecycleId()))) + assertThatThrownBy(() -> + context.allocatePrivateTarget( + new GameSessionPrivateFreshTargetRepository.Request( + requestId, UUID.randomUUID(), preparation.playtestLifecycleId()))) .isInstanceOf(GameSessionPrivateFreshTargetRepository.IdempotencyConflictException.class); - assertThatThrownBy( - () -> - context.allocatePrivateTarget( - new GameSessionPrivateFreshTargetRepository.Request( - requestId, preparation.request().requestId(), UUID.randomUUID()))) + assertThatThrownBy(() -> + context.allocatePrivateTarget( + new GameSessionPrivateFreshTargetRepository.Request( + requestId, preparation.request().requestId(), UUID.randomUUID()))) .isInstanceOf(GameSessionPrivateFreshTargetRepository.IdempotencyConflictException.class); - assertThatThrownBy( - () -> - context.allocatePrivateTarget( - new GameSessionPrivateFreshTargetRepository.Request( - UUID.randomUUID(), - preparation.request().requestId(), - preparation.playtestLifecycleId()))) + assertThatThrownBy(() -> + context.allocatePrivateTarget( + new GameSessionPrivateFreshTargetRepository.Request( + UUID.randomUUID(), + preparation.request().requestId(), + preparation.playtestLifecycleId()))) .isInstanceOf(GameSessionPrivateFreshTargetRepository.IdempotencyConflictException.class); - assertThatThrownBy( - () -> - context.allocatePrivateTarget( - new GameSessionPrivateFreshTargetRepository.Request( - UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()))) + assertThatThrownBy(() -> + context.allocatePrivateTarget( + new GameSessionPrivateFreshTargetRepository.Request( + UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()))) .isInstanceOf( GameSessionPrivateFreshTargetRepository.PreparationUnavailableException.class); assertThat(context.allocatePrivateTarget(original).snapshot()).isEqualTo(allocation.snapshot()); @@ -1776,22 +1728,20 @@ void committedPrivateCatalogOutcomeReplaysAfterExpiryWithoutAllocatingOrRenewing targetRequest.requestId()) .get(0, String.class)) .isEqualTo(retainedRow); - assertThatThrownBy( - () -> - context.allocatePrivateTarget( - new GameSessionPrivateFreshTargetRepository.Request( - UUID.randomUUID(), - preparation.request().requestId(), - preparation.playtestLifecycleId()))) + assertThatThrownBy(() -> + context.allocatePrivateTarget( + new GameSessionPrivateFreshTargetRepository.Request( + UUID.randomUUID(), + preparation.request().requestId(), + preparation.playtestLifecycleId()))) .isInstanceOf( GameSessionPrivateFreshTargetRepository.PreparationUnavailableException.class); - assertThatThrownBy( - () -> - context.allocatePrivateTarget( - new GameSessionPrivateFreshTargetRepository.Request( - targetRequest.requestId(), - preparation.request().requestId(), - UUID.randomUUID()))) + assertThatThrownBy(() -> + context.allocatePrivateTarget( + new GameSessionPrivateFreshTargetRepository.Request( + targetRequest.requestId(), + preparation.request().requestId(), + UUID.randomUUID()))) .isInstanceOf(GameSessionPrivateFreshTargetRepository.IdempotencyConflictException.class); assertThat(context.dsl().fetchCount(DSL.table("game_session_canonical_realm_catalog"))) .isEqualTo(2); @@ -1807,13 +1757,12 @@ void expiredPreparationCannotAllocatePrivateCatalogIdentity() { var preparation = context.prepare(preparationRequest).preparation(); awaitExpiry(context, preparationRequest.forkExpiresAt()); - assertThatThrownBy( - () -> - context.allocatePrivateTarget( - new GameSessionPrivateFreshTargetRepository.Request( - UUID.randomUUID(), - preparation.request().requestId(), - preparation.playtestLifecycleId()))) + assertThatThrownBy(() -> + context.allocatePrivateTarget( + new GameSessionPrivateFreshTargetRepository.Request( + UUID.randomUUID(), + preparation.request().requestId(), + preparation.playtestLifecycleId()))) .isInstanceOf(GameSessionPrivateFreshTargetRepository.PreparationUnavailableException.class) .hasMessageContaining("expired"); assertThat(context.dsl().fetchCount(DSL.table("game_session_canonical_realm_catalog"))) @@ -1883,22 +1832,20 @@ INSERT INTO game_session_canonical_realm_catalog ( WHERE p.request_id = ? AND p.playtest_lifecycle_id = ? """; - assertThatThrownBy( - () -> - context - .serializableTransaction() - .executeWithoutResult( - status -> - context - .dsl() - .execute( - sql, - wrongNamespace, - requestId, - requestDigest, - requestPreimage, - preparation.request().requestId(), - preparation.playtestLifecycleId()))) + assertThatThrownBy(() -> + context + .serializableTransaction() + .executeWithoutResult(status -> + context + .dsl() + .execute( + sql, + wrongNamespace, + requestId, + requestDigest, + requestPreimage, + preparation.request().requestId(), + preparation.playtestLifecycleId()))) .isInstanceOf(RuntimeException.class) .hasStackTraceContaining( "Private FRESH catalog row differs from its exact retained preparation"); @@ -1909,22 +1856,20 @@ INSERT INTO game_session_canonical_realm_catalog ( "p.canonical_version_id, p.published_release_bundle_ref,", "p.canonical_version_id, NULL,"); assertThat(nullBuildSql).isNotEqualTo(sql); - assertThatThrownBy( - () -> - context - .serializableTransaction() - .executeWithoutResult( - status -> - context - .dsl() - .execute( - nullBuildSql, - preparation.playableStateNamespaceId(), - requestId, - requestDigest, - requestPreimage, - preparation.request().requestId(), - preparation.playtestLifecycleId()))) + assertThatThrownBy(() -> + context + .serializableTransaction() + .executeWithoutResult(status -> + context + .dsl() + .execute( + nullBuildSql, + preparation.playableStateNamespaceId(), + requestId, + requestDigest, + requestPreimage, + preparation.request().requestId(), + preparation.playtestLifecycleId()))) .isInstanceOf(RuntimeException.class) .hasStackTraceContaining("chk_gs_private_fresh_catalog_binding"); assertThat(context.dsl().fetchCount(DSL.table("game_session_canonical_realm_catalog"))) @@ -1949,23 +1894,22 @@ void canonicalIntakeGuardRejectsPrivateForgedTenantSlugWithRecomputedReceipt() { Objects.requireNonNull( context .serializableTransaction() - .execute( - status -> { - context.privateTargets().allocate(targetRequest); - var genuine = - Objects.requireNonNull( - context - .dsl() - .fetchOne( - "SELECT * FROM game_session_canonical_realm_catalog WHERE creation_request_id = ?", - creationRequestId)); - DetachedCatalogRow detachedValues = - new DetachedCatalogRow( - new LinkedHashMap<>(genuine.intoMap()), - List.copyOf(java.util.Arrays.asList(genuine.fields()))); - status.setRollbackOnly(); - return detachedValues; - })); + .execute(status -> { + context.privateTargets().allocate(targetRequest); + var genuine = + Objects.requireNonNull( + context + .dsl() + .fetchOne( + "SELECT * FROM game_session_canonical_realm_catalog WHERE creation_request_id = ?", + creationRequestId)); + DetachedCatalogRow detachedValues = + new DetachedCatalogRow( + new LinkedHashMap<>(genuine.intoMap()), + List.copyOf(java.util.Arrays.asList(genuine.fields()))); + status.setRollbackOnly(); + return detachedValues; + })); assertThat( context .privateTargets() @@ -2003,19 +1947,17 @@ void canonicalIntakeGuardRejectsPrivateForgedTenantSlugWithRecomputedReceipt() { values[index] = forged.get(originalField.getName()); } Throwable insertFailure = - catchThrowable( - () -> - context - .serializableTransaction() - .executeWithoutResult( - status -> - context - .dsl() - .insertInto( - DSL.table(DSL.name("game_session_canonical_realm_catalog")), - insertFields) - .values(values) - .execute())); + catchThrowable(() -> + context + .serializableTransaction() + .executeWithoutResult(status -> + context + .dsl() + .insertInto( + DSL.table(DSL.name("game_session_canonical_realm_catalog")), + insertFields) + .values(values) + .execute())); String failureSummary = databaseFailureSummary(insertFailure); assertThat(insertFailure) .as("Forged INSERT failure should expose its database cause: %s", failureSummary) @@ -2052,15 +1994,13 @@ void privateCatalogCommitGuardRechecksPreparationExpiry() { preparation.request().requestId(), preparation.playtestLifecycleId()); - assertThatThrownBy( - () -> - context - .serializableTransaction() - .executeWithoutResult( - status -> { - context.privateTargets().allocate(targetRequest); - awaitExpiry(context, preparationRequest.forkExpiresAt()); - })) + assertThatThrownBy(() -> + context + .serializableTransaction() + .executeWithoutResult(status -> { + context.privateTargets().allocate(targetRequest); + awaitExpiry(context, preparationRequest.forkExpiresAt()); + })) .isInstanceOf(RuntimeException.class) .hasStackTraceContaining( "Private FRESH catalog preparation expired before final catalog commit"); @@ -2141,11 +2081,10 @@ void changedIntentUnderOneRequestConflictsBeforeSourceLookupOrAllocation() { @Test void missingOrMismatchedRetainedSourceAndBuildNeverAllocate() { Context missing = context(false); - assertThatThrownBy( - () -> - missing.prepare( - missing.request( - UUID.randomUUID(), "private-playtest", missing.now().plusSeconds(300)))) + assertThatThrownBy(() -> + missing.prepare( + missing.request( + UUID.randomUUID(), "private-playtest", missing.now().plusSeconds(300)))) .isInstanceOf(SourceUnavailableException.class); assertThat(missing.count()).isZero(); Context context = context(true); @@ -2266,26 +2205,24 @@ void sqlGuardRejectsTargetPolicyBytesNotSelectedFromRetainedPublishedSet() { .replace("\"realmSlug\":\"private-playtest\"", "\"realmSlug\":\"other-target\""); assertThat(changedPolicy) .isNotEqualTo(new String(storedPolicy, java.nio.charset.StandardCharsets.UTF_8)); - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult( - status -> - context - .dsl() - .execute( - "INSERT INTO " - + TABLE - + " (request_id, request_preimage, request_digest, target_namespace, canonical_tenant_id, world_slug, realm_slug, initialization_mode, preparation_state, playtest_state_generation, fork_expiry_second, fork_expiry_nano, fork_expiry_text, source_catalog_realm_id, source_catalog_request_id, source_catalog_revision, source_catalog_receipt_digest, source_intake_operation_id, source_intake_receipt_digest, source_operation_id, source_evidence_digest, canonical_version_id, published_release_bundle_ref, published_release_bundle_digest, source_policy_set_digest, source_policy_carrier_digest, target_policy_id, target_policy_source_commit_id, target_policy_source_revision_id, target_policy_logical_revision_id, target_policy_digest, target_policy_canonical_json, target_policy_schema_version, target_policy_world_slug, target_policy_realm_slug, target_policy_visible, target_policy_world_display_name, target_policy_public_production, target_policy_state_scope, target_policy_realm_display_name, target_policy_entry_policy) " - + "SELECT ?, ?, ?, target_namespace, canonical_tenant_id, world_slug, realm_slug, initialization_mode, preparation_state, playtest_state_generation, fork_expiry_second, fork_expiry_nano, fork_expiry_text, source_catalog_realm_id, source_catalog_request_id, source_catalog_revision, source_catalog_receipt_digest, source_intake_operation_id, source_intake_receipt_digest, source_operation_id, source_evidence_digest, canonical_version_id, published_release_bundle_ref, published_release_bundle_digest, source_policy_set_digest, source_policy_carrier_digest, target_policy_id, target_policy_source_commit_id, target_policy_source_revision_id, target_policy_logical_revision_id, target_policy_digest, ?, target_policy_schema_version, target_policy_world_slug, target_policy_realm_slug, target_policy_visible, target_policy_world_display_name, target_policy_public_production, target_policy_state_scope, target_policy_realm_display_name, target_policy_entry_policy FROM " - + TABLE - + " WHERE request_id = ?", - tampered.requestId(), - tampered.canonicalPreimage(), - tampered.requestDigest(), - changedPolicy.getBytes(java.nio.charset.StandardCharsets.UTF_8), - original.requestId()))) + assertThatThrownBy(() -> + context + .transaction() + .executeWithoutResult(status -> + context + .dsl() + .execute( + "INSERT INTO " + + TABLE + + " (request_id, request_preimage, request_digest, target_namespace, canonical_tenant_id, world_slug, realm_slug, initialization_mode, preparation_state, playtest_state_generation, fork_expiry_second, fork_expiry_nano, fork_expiry_text, source_catalog_realm_id, source_catalog_request_id, source_catalog_revision, source_catalog_receipt_digest, source_intake_operation_id, source_intake_receipt_digest, source_operation_id, source_evidence_digest, canonical_version_id, published_release_bundle_ref, published_release_bundle_digest, source_policy_set_digest, source_policy_carrier_digest, target_policy_id, target_policy_source_commit_id, target_policy_source_revision_id, target_policy_logical_revision_id, target_policy_digest, target_policy_canonical_json, target_policy_schema_version, target_policy_world_slug, target_policy_realm_slug, target_policy_visible, target_policy_world_display_name, target_policy_public_production, target_policy_state_scope, target_policy_realm_display_name, target_policy_entry_policy) " + + "SELECT ?, ?, ?, target_namespace, canonical_tenant_id, world_slug, realm_slug, initialization_mode, preparation_state, playtest_state_generation, fork_expiry_second, fork_expiry_nano, fork_expiry_text, source_catalog_realm_id, source_catalog_request_id, source_catalog_revision, source_catalog_receipt_digest, source_intake_operation_id, source_intake_receipt_digest, source_operation_id, source_evidence_digest, canonical_version_id, published_release_bundle_ref, published_release_bundle_digest, source_policy_set_digest, source_policy_carrier_digest, target_policy_id, target_policy_source_commit_id, target_policy_source_revision_id, target_policy_logical_revision_id, target_policy_digest, ?, target_policy_schema_version, target_policy_world_slug, target_policy_realm_slug, target_policy_visible, target_policy_world_display_name, target_policy_public_production, target_policy_state_scope, target_policy_realm_display_name, target_policy_entry_policy FROM " + + TABLE + + " WHERE request_id = ?", + tampered.requestId(), + tampered.canonicalPreimage(), + tampered.requestDigest(), + changedPolicy.getBytes(java.nio.charset.StandardCharsets.UTF_8), + original.requestId()))) .isInstanceOf(RuntimeException.class) .hasStackTraceContaining("Selected private target policy differs"); assertThat(context.count()).isEqualTo(1); @@ -2302,19 +2239,17 @@ void concurrentExactRequestAllocatesOnceAndNewRequestsForSameRealmGetDistinctIde var executor = Executors.newFixedThreadPool(2); try { var first = - executor.submit( - () -> { - ready.countDown(); - await(begin); - return context.prepare(request); - }); + executor.submit(() -> { + ready.countDown(); + await(begin); + return context.prepare(request); + }); var second = - executor.submit( - () -> { - ready.countDown(); - await(begin); - return context.prepare(request); - }); + executor.submit(() -> { + ready.countDown(); + await(begin); + return context.prepare(request); + }); assertThat(ready.await(30, TimeUnit.SECONDS)).isTrue(); begin.countDown(); Allocation left = first.get(60, TimeUnit.SECONDS); @@ -2371,49 +2306,42 @@ void staleSerializableSnapshotMustRetryPrivateAllocationInANewOwnerTransaction() var firstAllocation = new AtomicReference(); var first = - executor.submit( - () -> - Objects.requireNonNull( - context - .serializableTransaction() - .execute( - status -> { - var allocated = context.privateTargets().allocate(targetRequest); - firstAllocation.set(allocated); - firstAllocationHeld.countDown(); - await(releaseFirstAllocation); - return allocated; - }))); + executor.submit(() -> + Objects.requireNonNull( + context + .serializableTransaction() + .execute(status -> { + var allocated = context.privateTargets().allocate(targetRequest); + firstAllocation.set(allocated); + firstAllocationHeld.countDown(); + await(releaseFirstAllocation); + return allocated; + }))); await(firstAllocationHeld); var second = - executor.submit( - () -> { - try { - context - .serializableTransaction() - .executeWithoutResult( - status -> { - var visibleBeforeCommit = - context - .dsl() - .fetchSingle( - "SELECT count(*) FROM game_session_canonical_realm_catalog WHERE private_preparation_request_id = ?", - preparation.request().requestId()) - .get(0, Long.class); - assertThat(visibleBeforeCommit).isZero(); - secondBackendPid.set( - context - .dsl() - .fetchSingle("SELECT pg_backend_pid()") - .get(0, Integer.class)); - secondSnapshotEstablished.countDown(); - context.privateTargets().allocate(targetRequest); - }); - } catch (Throwable failure) { - staleFailure.set(failure); - } - }); + executor.submit(() -> { + try { + context + .serializableTransaction() + .executeWithoutResult(status -> { + var visibleBeforeCommit = + context + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_session_canonical_realm_catalog WHERE private_preparation_request_id = ?", + preparation.request().requestId()) + .get(0, Long.class); + assertThat(visibleBeforeCommit).isZero(); + secondBackendPid.set( + context.dsl().fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + secondSnapshotEstablished.countDown(); + context.privateTargets().allocate(targetRequest); + }); + } catch (Throwable failure) { + staleFailure.set(failure); + } + }); await(secondSnapshotEstablished); awaitAdvisoryLockWait(context, secondBackendPid.get()); releaseFirstAllocation.countDown(); @@ -2470,55 +2398,51 @@ void exactReadRejectsWrongLifecycleAndReportsRealExpiryWithoutChangingOriginal() Optional wrongLifecycle = context .transaction() - .execute( - status -> - context - .repository() - .readExact( - NAMESPACE, - request.tenantId(), - request.worldSlug(), - request.realmSlug(), - UUID.randomUUID())); + .execute(status -> + context + .repository() + .readExact( + NAMESPACE, + request.tenantId(), + request.worldSlug(), + request.realmSlug(), + UUID.randomUUID())); Optional wrongRealm = context .transaction() - .execute( - status -> - context - .repository() - .readExact( - NAMESPACE, - request.tenantId(), - request.worldSlug(), - "wrong-realm", - original.playtestLifecycleId())); + .execute(status -> + context + .repository() + .readExact( + NAMESPACE, + request.tenantId(), + request.worldSlug(), + "wrong-realm", + original.playtestLifecycleId())); Optional wrongTenant = context .transaction() - .execute( - status -> - context - .repository() - .readExact( - NAMESPACE, - UUID.randomUUID(), - request.worldSlug(), - request.realmSlug(), - original.playtestLifecycleId())); + .execute(status -> + context + .repository() + .readExact( + NAMESPACE, + UUID.randomUUID(), + request.worldSlug(), + request.realmSlug(), + original.playtestLifecycleId())); Optional wrongWorld = context .transaction() - .execute( - status -> - context - .repository() - .readExact( - NAMESPACE, - request.tenantId(), - "wrong-world", - request.realmSlug(), - original.playtestLifecycleId())); + .execute(status -> + context + .repository() + .readExact( + NAMESPACE, + request.tenantId(), + "wrong-world", + request.realmSlug(), + original.playtestLifecycleId())); assertThat(wrongLifecycle).isEmpty(); assertThat(wrongRealm).isEmpty(); assertThat(wrongTenant).isEmpty(); @@ -2545,32 +2469,26 @@ void rollbackExpiredFinalCommitAndImmutableHistoryViolationNeverPublishAuthority Context context = context(true); Request request = context.request(UUID.randomUUID(), "private-playtest", context.now().plusSeconds(3600)); - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult( - status -> { - context.repository().prepare(request); - throw new IllegalStateException("Controlled coordinator refusal"); - })) + assertThatThrownBy(() -> + context + .transaction() + .executeWithoutResult(status -> { + context.repository().prepare(request); + throw new IllegalStateException("Controlled coordinator refusal"); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("Controlled coordinator refusal"); assertThat(context.count()).isZero(); - assertThatThrownBy( - () -> - context - .transaction() - .executeWithoutResult( - status -> { - Request shortRequest = - context.request( - UUID.randomUUID(), - "private-playtest", - context.now().plusSeconds(5)); - context.repository().prepare(shortRequest); - awaitExpiry(context, shortRequest.forkExpiresAt()); - })) + assertThatThrownBy(() -> + context + .transaction() + .executeWithoutResult(status -> { + Request shortRequest = + context.request( + UUID.randomUUID(), "private-playtest", context.now().plusSeconds(5)); + context.repository().prepare(shortRequest); + awaitExpiry(context, shortRequest.forkExpiresAt()); + })) .isInstanceOf(RuntimeException.class) .hasStackTraceContaining("expired before final preparation commit"); assertThat(context.count()).isZero(); @@ -2582,9 +2500,8 @@ void rollbackExpiredFinalCommitAndImmutableHistoryViolationNeverPublishAuthority "UPDATE " + TABLE + " SET fork_expiry_second = fork_expiry_second + 1", "DELETE FROM " + TABLE, "TRUNCATE " + TABLE)) { - assertThatThrownBy( - () -> - context.transaction().executeWithoutResult(status -> context.dsl().execute(sql))) + assertThatThrownBy(() -> + context.transaction().executeWithoutResult(status -> context.dsl().execute(sql))) .as(sql) .isInstanceOf(RuntimeException.class); } @@ -2600,23 +2517,22 @@ void unsupportedInitializationAndMissingOwnerTransactionFailBeforeAllocation() { context.request(UUID.randomUUID(), "private-playtest", context.now().plusSeconds(3600)); for (InitializationMode mode : List.of(InitializationMode.SEEDED, InitializationMode.SNAPSHOT)) { - assertThatThrownBy( - () -> - new Request( - request.requestId(), - NAMESPACE, - request.tenantId(), - request.worldSlug(), - request.realmSlug(), - request.sourceCatalogRealmId(), - request.sourceCatalogRequestId(), - request.sourceCatalogRevision(), - request.sourceIntakeOperationId(), - request.canonicalVersionId(), - request.publishedReleaseBundleRef(), - request.publishedReleaseBundleDigest(), - mode, - request.forkExpiresAt())) + assertThatThrownBy(() -> + new Request( + request.requestId(), + NAMESPACE, + request.tenantId(), + request.worldSlug(), + request.realmSlug(), + request.sourceCatalogRealmId(), + request.sourceCatalogRequestId(), + request.sourceCatalogRevision(), + request.sourceIntakeOperationId(), + request.canonicalVersionId(), + request.publishedReleaseBundleRef(), + request.publishedReleaseBundleDigest(), + mode, + request.forkExpiresAt())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Only initial FRESH"); } @@ -2652,18 +2568,17 @@ private static void awaitAdvisoryLockWait(Context context, int backendPid) { Awaitility.await() .atMost(30, TimeUnit.SECONDS) .pollInterval(10, TimeUnit.MILLISECONDS) - .untilAsserted( - () -> { - var activity = - context - .dsl() - .fetchOne( - "SELECT wait_event_type, wait_event FROM pg_stat_activity WHERE pid = ?", - backendPid); - assertThat(activity).isNotNull(); - assertThat(activity.get("wait_event_type", String.class)).isEqualTo("Lock"); - assertThat(activity.get("wait_event", String.class)).isEqualTo("advisory"); - }); + .untilAsserted(() -> { + var activity = + context + .dsl() + .fetchOne( + "SELECT wait_event_type, wait_event FROM pg_stat_activity WHERE pid = ?", + backendPid); + assertThat(activity).isNotNull(); + assertThat(activity.get("wait_event_type", String.class)).isEqualTo("Lock"); + assertThat(activity.get("wait_event", String.class)).isEqualTo("advisory"); + }); } private static String privateCatalogRow(Context context, UUID requestId) { @@ -2848,24 +2763,19 @@ void pendingPrivateSourceProtectionBlocksBothSupersessionWritersAndCannotBeDelet later.playtestLifecycleId(), f.selection().headRevision(), f.selection().playtestLifecycleId()); - assertThatThrownBy( - () -> - f.context() - .transaction() - .execute( - status -> - new GameSessionCurrentPrivatePlaytestRepository(f.context().dsl()) - .select(select))) + assertThatThrownBy(() -> + f.context() + .transaction() + .execute(status -> + new GameSessionCurrentPrivatePlaytestRepository(f.context().dsl()) + .select(select))) .isInstanceOf(RuntimeException.class) .hasStackTraceContaining("unresolved World preparation"); var unsupported = new TransactionTemplate(f.context().transaction().getTransactionManager()); unsupported.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); - assertThatThrownBy( - () -> - unsupported.execute( - status -> - new GameSessionCurrentPrivatePlaytestRepository(f.context().dsl()) - .select(select))) + assertThatThrownBy(() -> + unsupported.execute(status -> + new GameSessionCurrentPrivatePlaytestRepository(f.context().dsl()).select(select))) .isInstanceOf(RuntimeException.class) .hasStackTraceContaining("READ COMMITTED or SERIALIZABLE"); var advance = @@ -2921,11 +2831,8 @@ void expiredPrivateProtectionRemainsPendingButCannotQualifyCurrentSource() { retainedRowWithXmin( f.context(), "game_session_private_preparation_protection", "request_id", request)) .isEqualTo(retained); - assertThatThrownBy( - () -> - f.context() - .dsl() - .execute("DELETE FROM game_session_private_preparation_protection")) + assertThatThrownBy(() -> + f.context().dsl().execute("DELETE FROM game_session_private_preparation_protection")) .isInstanceOf(RuntimeException.class); } @@ -2942,17 +2849,16 @@ void competingExactPrivateProtectionAcquisitionsReturnOneCommittedHold() throws .dsl() .configuration() .derive( - org.jooq.ExecuteListener.onRecordEnd( - execution -> { - String sql = execution.sql(); - var record = execution.record(); - if (sql != null - && sql.contains("pg_try_advisory_xact_lock") - && record != null - && Boolean.FALSE.equals(record.get("acquired", Boolean.class)) - && attemptedThreads.add(Thread.currentThread().threadId())) - attempts.countDown(); - }))); + org.jooq.ExecuteListener.onRecordEnd(execution -> { + String sql = execution.sql(); + var record = execution.record(); + if (sql != null + && sql.contains("pg_try_advisory_xact_lock") + && record != null + && Boolean.FALSE.equals(record.get("acquired", Boolean.class)) + && attemptedThreads.add(Thread.currentThread().threadId())) + attempts.countDown(); + }))); var owner = new GameSessionPrivatePreparationProtectionRepository( observedDsl, Objects.requireNonNull(f.context().transaction().getTransactionManager())); @@ -2960,36 +2866,33 @@ var record = execution.record(); try (var executor = Executors.newFixedThreadPool(2)) { var gate = new CountDownLatch(1); var first = - executor.submit( - () -> { - gate.await(); - return owner.acquire(request, source); - }); + executor.submit(() -> { + gate.await(); + return owner.acquire(request, source); + }); var second = - executor.submit( - () -> { - gate.await(); - return owner.acquire(request, source); - }); + executor.submit(() -> { + gate.await(); + return owner.acquire(request, source); + }); // Both callers must encounter a busy request. They must release those SERIALIZABLE // transactions before retrying, rather than retain pre-wait snapshots under a blocking lock. f.context() .transaction() - .executeWithoutResult( - status -> { - f.context() - .dsl() - .fetch( - "SELECT pg_advisory_xact_lock(hashtextextended(?,0))", - "private-source-protection/" + request); - gate.countDown(); - try { - assertThat(attempts.await(3, TimeUnit.SECONDS)).isTrue(); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(interrupted); - } - }); + .executeWithoutResult(status -> { + f.context() + .dsl() + .fetch( + "SELECT pg_advisory_xact_lock(hashtextextended(?,0))", + "private-source-protection/" + request); + gate.countDown(); + try { + assertThat(attempts.await(3, TimeUnit.SECONDS)).isTrue(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + }); assertThat(first.get(10, TimeUnit.SECONDS)).isEqualTo(second.get(10, TimeUnit.SECONDS)); } assertThat( @@ -3013,43 +2916,36 @@ void staleSerializableSelectionWriterCannotMissCommittedPrivateProtection() thro var protectionCommitted = new CountDownLatch(1); try (var executor = Executors.newSingleThreadExecutor()) { var writer = - executor.submit( - () -> - catchThrowable( - () -> - f.context() - .serializableTransaction() - .executeWithoutResult( - status -> { - f.context() - .dsl() - .fetch( - "SELECT * FROM game_session_current_private_playtests"); - snapshotTaken.countDown(); - try { - if (!protectionCommitted.await(10, TimeUnit.SECONDS)) - throw new IllegalStateException( - "Protection did not commit"); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(interrupted); - } - new GameSessionCurrentPrivatePlaytestRepository( - f.context().dsl()) - .select( - new GameSessionCurrentPrivatePlaytestRepository.Request( - UUID.randomUUID(), - new GameSessionCurrentPrivatePlaytestRepository - .Scope( - NAMESPACE, - f.target().tenantId(), - f.target().worldSlug(), - f.target().realmSlug()), - later.request().requestId(), - later.playtestLifecycleId(), - f.selection().headRevision(), - f.selection().playtestLifecycleId())); - }))); + executor.submit(() -> + catchThrowable(() -> + f.context() + .serializableTransaction() + .executeWithoutResult(status -> { + f.context() + .dsl() + .fetch("SELECT * FROM game_session_current_private_playtests"); + snapshotTaken.countDown(); + try { + if (!protectionCommitted.await(10, TimeUnit.SECONDS)) + throw new IllegalStateException("Protection did not commit"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + new GameSessionCurrentPrivatePlaytestRepository(f.context().dsl()) + .select( + new GameSessionCurrentPrivatePlaytestRepository.Request( + UUID.randomUUID(), + new GameSessionCurrentPrivatePlaytestRepository.Scope( + NAMESPACE, + f.target().tenantId(), + f.target().worldSlug(), + f.target().realmSlug()), + later.request().requestId(), + later.playtestLifecycleId(), + f.selection().headRevision(), + f.selection().playtestLifecycleId())); + }))); assertThat(snapshotTaken.await(10, TimeUnit.SECONDS)).isTrue(); var owner = privateProtectionOwner(f.context()); var held = owner.acquire(UUID.randomUUID(), expected); @@ -3072,21 +2968,20 @@ private static PrivateWorldPreparationReadEvidence.Snapshot privateProtectionSou var c = f.context(); return Objects.requireNonNull( c.transaction() - .execute( - status -> - new GameSessionPrivateWorldPreparationSourceReader( - new GameSessionCurrentPrivatePlaytestRepository(c.dsl()), - c.privateTargets(), - new GameSessionPrivateFreshRuntimeAllocationRepository(c.dsl())) - .read( - new PrivateWorldPreparationReadGrpcCodec.Request( - UUID.randomUUID(), - new CurrentPrivatePlaytestLifecycleReadEvidence.Scope( - NAMESPACE, - f.target().tenantId(), - f.target().worldSlug(), - f.target().realmSlug()), - f.preparation().request().requestId())))); + .execute(status -> + new GameSessionPrivateWorldPreparationSourceReader( + new GameSessionCurrentPrivatePlaytestRepository(c.dsl()), + c.privateTargets(), + new GameSessionPrivateFreshRuntimeAllocationRepository(c.dsl())) + .read( + new PrivateWorldPreparationReadGrpcCodec.Request( + UUID.randomUUID(), + new CurrentPrivatePlaytestLifecycleReadEvidence.Scope( + NAMESPACE, + f.target().tenantId(), + f.target().worldSlug(), + f.target().realmSlug()), + f.preparation().request().requestId())))); } private static final String RUNTIME_ALLOCATIONS = @@ -3131,10 +3026,8 @@ private static GameSessionCurrentPrivatePlaytestRepository.SelectionReceipt sele return Objects.requireNonNull( context .transaction() - .execute( - status -> - new GameSessionCurrentPrivatePlaytestRepository(context.dsl()) - .select(request))) + .execute(status -> + new GameSessionCurrentPrivatePlaytestRepository(context.dsl()).select(request))) .receipt(); } @@ -3159,10 +3052,9 @@ private static GameSessionPrivateFreshRuntimeAllocationRepository.Allocation all return Objects.requireNonNull( context .serializableTransaction() - .execute( - status -> - new GameSessionPrivateFreshRuntimeAllocationRepository(context.dsl()) - .allocate(request))); + .execute(status -> + new GameSessionPrivateFreshRuntimeAllocationRepository(context.dsl()) + .allocate(request))); } private static List> runtimeSourceRows(Context context) { @@ -3360,14 +3252,13 @@ private Context context( var intake = Objects.requireNonNull( transaction.execute(status -> sourceOwner.register(UUID.randomUUID(), evidence))); - transaction.executeWithoutResult( - status -> - new GameSessionFreshTenantAssociationRepository(dsl) - .associateFresh( - UUID.randomUUID(), - NAMESPACE, - intake, - CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(evidence))); + transaction.executeWithoutResult(status -> + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + UUID.randomUUID(), + NAMESPACE, + intake, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(evidence))); var catalogRequest = new CreateCanonicalRealmCatalogRequest( UUID.randomUUID(), @@ -3545,16 +3436,15 @@ GameSessionPrivateFreshTargetRepository.Allocation advancePrivateRevision( GameSessionInitialPlaytestLifecycleRepository.Snapshot read(Request request, UUID lifecycle) { return Objects.requireNonNull( - transaction.execute( - status -> - repository - .readExact( - NAMESPACE, - request.tenantId(), - request.worldSlug(), - request.realmSlug(), - lifecycle) - .orElseThrow())); + transaction.execute(status -> + repository + .readExact( + NAMESPACE, + request.tenantId(), + request.worldSlug(), + request.realmSlug(), + lifecycle) + .orElseThrow())); } int count() { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java index 25137b4d5a..1b444843e2 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionOriginalStartSessionAssociationReadIntegrationTest.java @@ -682,13 +682,12 @@ private static Fixture fixture( "registered fresh source receipt"); FreshGameSessionTenantAssociation tenantAssociation = Objects.requireNonNull( - transactions.execute( - status -> - tenantRepository.associateFresh( - UUID.randomUUID(), - namespace, - sourceReceipt, - CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(source))), + transactions.execute(status -> + tenantRepository.associateFresh( + UUID.randomUUID(), + namespace, + sourceReceipt, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(source))), "fresh tenant association"); var createCatalog = new CreateCanonicalRealmCatalogRequest( @@ -757,15 +756,14 @@ OwnerBackedStarting startWithOwnerPins(StartSessionPostAuthorizationExecutionTup dsl, transactions, tuple, source, publishedSet, binding, ownerClaimLease); StartingInstance startingInstance = Objects.requireNonNull( - transactions.execute( - status -> - starting.createStarting( - tenantAssociation, - binding, - tuple.preAuthorizationTuple().action().target().ownerAccountId(), - tuple.controlPlaneRequestId(), - tuple.mutationDigest(), - tuple))); + transactions.execute(status -> + starting.createStarting( + tenantAssociation, + binding, + tuple.preAuthorizationTuple().action().target().ownerAccountId(), + tuple.controlPlaneRequestId(), + tuple.mutationDigest(), + tuple))); return new OwnerBackedStarting(startingInstance, claim); } @@ -774,34 +772,16 @@ OwnerBackedStarting startWithOwnerAttemptWithoutPins( ReservationResult reservation = Objects.requireNonNull(transactions.execute(status -> attempts.reserve(tuple))); AttemptClaim claim = reservation.claim().orElseThrow(); - transactions.executeWithoutResult( - status -> - attempts.attachAccountRedemptionProjection( - claim, - GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.projection( - tuple))); + transactions.executeWithoutResult(status -> + attempts.attachAccountRedemptionProjection( + claim, + GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.projection( + tuple))); var descriptor = unpinnedDescriptor(tuple, source); var binding = completeBinding(descriptor, CANONICAL_VERSION, publishedSet); StartingInstance startingInstance = Objects.requireNonNull( - transactions.execute( - status -> - starting.createStarting( - tenantAssociation, - binding, - tuple.preAuthorizationTuple().action().target().ownerAccountId(), - tuple.controlPlaneRequestId(), - tuple.mutationDigest(), - tuple))); - return new OwnerBackedStarting(startingInstance, claim); - } - - StartingInstance startWithoutOwnerPins(StartSessionPostAuthorizationExecutionTuple tuple) { - var descriptor = unpinnedDescriptor(tuple, source); - var binding = completeBinding(descriptor, CANONICAL_VERSION, publishedSet); - return Objects.requireNonNull( - transactions.execute( - status -> + transactions.execute(status -> starting.createStarting( tenantAssociation, binding, @@ -809,6 +789,21 @@ StartingInstance startWithoutOwnerPins(StartSessionPostAuthorizationExecutionTup tuple.controlPlaneRequestId(), tuple.mutationDigest(), tuple))); + return new OwnerBackedStarting(startingInstance, claim); + } + + StartingInstance startWithoutOwnerPins(StartSessionPostAuthorizationExecutionTuple tuple) { + var descriptor = unpinnedDescriptor(tuple, source); + var binding = completeBinding(descriptor, CANONICAL_VERSION, publishedSet); + return Objects.requireNonNull( + transactions.execute(status -> + starting.createStarting( + tenantAssociation, + binding, + tuple.preAuthorizationTuple().action().target().ownerAccountId(), + tuple.controlPlaneRequestId(), + tuple.mutationDigest(), + tuple))); } java.util.Optional read( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java index 9a74c5c01f..9445bcc76a 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java @@ -90,13 +90,12 @@ void allocatesOneStartingLaunchWithExactPolicyAndIndependentOwnerReadback() thro FreshGameSessionTenantAssociation freshAssociation = Objects.requireNonNull( - fixture.transactions.execute( - status -> - fixture.tenantAssociationRepository.associateFresh( - associationOperationId(source), - NAMESPACE, - sourceReceipt, - evidence.creationEvidence())), + fixture.transactions.execute(status -> + fixture.tenantAssociationRepository.associateFresh( + associationOperationId(source), + NAMESPACE, + sourceReceipt, + evidence.creationEvidence())), "actual Game Session fresh private-tenant allocation"); assertThat(freshAssociation.legacyGameSessionTenantId()).isPositive(); assertThat(freshAssociation.sourceEvidence().sourceGameRowId()) @@ -272,18 +271,16 @@ void allocatesOneStartingLaunchWithExactPolicyAndIndependentOwnerReadback() thro AuthoredWorldSourceEvidence changedSource = source(SOURCE_GAME_ROW_ID + 1L); RunOwnedInitialAdmissionLaunchEvidence changedSourceEvidence = launchEvidence(changedSource, OWNER_ACCOUNT_ID); - assertThatThrownBy( - () -> - fixture.launchRepository.createVerifiedFixtureStartingLaunch(changedSourceEvidence)) + assertThatThrownBy(() -> + fixture.launchRepository.createVerifiedFixtureStartingLaunch(changedSourceEvidence)) .isInstanceOf(InvalidFreshTenantAssociationException.class) .hasMessageContaining("complete original Game Design receipt"); assertThat(ownerRows(fixture, evidence, first.gameInstanceId())).isEqualTo(originalRows); RunOwnedInitialAdmissionLaunchEvidence changedPolicyEvidence = launchEvidence(source, OWNER_ACCOUNT_ID + 1L); - assertThatThrownBy( - () -> - fixture.launchRepository.createVerifiedFixtureStartingLaunch(changedPolicyEvidence)) + assertThatThrownBy(() -> + fixture.launchRepository.createVerifiedFixtureStartingLaunch(changedPolicyEvidence)) .isInstanceOf(GameSessionCanonicalRealmCatalogRepository.CatalogConflictException.class) .hasMessageContaining("reused with changed input or source evidence"); assertThat(ownerRows(fixture, evidence, first.gameInstanceId())).isEqualTo(originalRows); @@ -471,11 +468,10 @@ void originalV1003CatalogRetainsPhysicalOwnerRowsWithoutAcquiringMissingPublishe GameSessionCanonicalRealmCatalogRepository.InvalidCatalogEvidenceException.class) .hasMessageContaining("Exactly one complete catalog policy provenance required"); assertThat(catalogs.readVisiblePublicProductionSnapshots(NAMESPACE)).isEmpty(); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "UPDATE game_session_canonical_realm_catalog " - + "SET complete_policy_set_evidence = decode('0102', 'hex')")) + assertThatThrownBy(() -> + fixture.dsl.execute( + "UPDATE game_session_canonical_realm_catalog " + + "SET complete_policy_set_evidence = decode('0102', 'hex')")) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(originalOwnerRows(fixture, columns)).isEqualTo(before); assertThat(originalHistoryRows(fixture, rank)).isEqualTo(historyBefore); @@ -572,10 +568,9 @@ void originalV1004LaunchRetainsPhysicalRowsWithoutAcquiringTupleOrCatalogCapture .isTrue(); assertThat(fixture.catalogRepository.readByRequest(NAMESPACE, request.requestId())).isPresent(); - assertThatThrownBy( - () -> - insertPreV1005HumanLaunch( - fixture, receipt, realmId, "new-missing-history-capture", policy)) + assertThatThrownBy(() -> + insertPreV1005HumanLaunch( + fixture, receipt, realmId, "new-missing-history-capture", policy)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining( "New canonical launch requires exactly one complete Human or verified fixture provenance and exact catalog identity"); @@ -586,17 +581,16 @@ void originalV1004LaunchRetainsPhysicalRowsWithoutAcquiringTupleOrCatalogCapture uuid(Math.toIntExact(OWNER_ACCOUNT_ID)), GAME_TEMPLATE_ID, "original-human-history"); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "UPDATE game_session_canonical_instance_launch SET original_start_session_tuple = ?, " - + "catalog_creation_request_id = ?, catalog_revision = ?, " - + "catalog_source_intake_operation_id = ?, catalog_source_intake_request_id = ?", - tuple.canonicalBytes(), - request.requestId(), - 1L, - receipt.operationId(), - receipt.intakeRequestId())) + assertThatThrownBy(() -> + fixture.dsl.execute( + "UPDATE game_session_canonical_instance_launch SET original_start_session_tuple = ?, " + + "catalog_creation_request_id = ?, catalog_revision = ?, " + + "catalog_source_intake_operation_id = ?, catalog_source_intake_request_id = ?", + tuple.canonicalBytes(), + request.requestId(), + 1L, + receipt.operationId(), + receipt.intakeRequestId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasStackTraceContaining("Game Session canonical instance launch evidence is immutable"); assertThat(originalOwnerRows(fixture, columns)).isEqualTo(before); @@ -722,24 +716,23 @@ private static java.util.Map> historicalOwnerColu private static java.util.Map>> originalOwnerRows(Fixture fixture, java.util.Map> columns) { var rows = new java.util.LinkedHashMap>>(); - columns.forEach( - (table, names) -> { - String projection = - names.stream() - .map(name -> "\"" + name.replace("\"", "\"\"") + "\"") - .collect(java.util.stream.Collectors.joining(", ")); - rows.put( - table, - fixture - .dsl - .fetch( - "SELECT jsonb_build_array(" - + projection - + ")::text AS original_bytes, xmin::text AS physical_version FROM \"" - + table - + "\" ORDER BY original_bytes") - .intoMaps()); - }); + columns.forEach((table, names) -> { + String projection = + names.stream() + .map(name -> "\"" + name.replace("\"", "\"\"") + "\"") + .collect(java.util.stream.Collectors.joining(", ")); + rows.put( + table, + fixture + .dsl + .fetch( + "SELECT jsonb_build_array(" + + projection + + ")::text AS original_bytes, xmin::text AS physical_version FROM \"" + + table + + "\" ORDER BY original_bytes") + .intoMaps()); + }); return rows; } @@ -761,14 +754,12 @@ private static IntakeReceipt registerAndAssociate( RunOwnedInitialAdmissionLaunchEvidence evidence) { var receipt = Objects.requireNonNull( - fixture.transactions.execute( - status -> - fixture.sourceRepository.register( - UUID.fromString(evidence.fixtureCapability().operationId()), source))); - fixture.transactions.executeWithoutResult( - status -> - fixture.tenantAssociationRepository.associateFresh( - associationOperationId(source), NAMESPACE, receipt, evidence.creationEvidence())); + fixture.transactions.execute(status -> + fixture.sourceRepository.register( + UUID.fromString(evidence.fixtureCapability().operationId()), source))); + fixture.transactions.executeWithoutResult(status -> + fixture.tenantAssociationRepository.associateFresh( + associationOperationId(source), NAMESPACE, receipt, evidence.creationEvidence())); return receipt; } @@ -915,11 +906,10 @@ private static void insertHistoricalCatalog( namespace.put(field, entry.getValue()); } } - fixture.transactions.executeWithoutResult( - status -> { - insertOwnerRow(fixture, "gameplay_tenant_shared_playable_state_namespace", namespace); - insertOwnerRow(fixture, "game_session_canonical_realm_catalog", columns); - }); + fixture.transactions.executeWithoutResult(status -> { + insertOwnerRow(fixture, "gameplay_tenant_shared_playable_state_namespace", namespace); + insertOwnerRow(fixture, "game_session_canonical_realm_catalog", columns); + }); } private static void insertPreV1005HumanLaunch( @@ -980,66 +970,65 @@ private static void insertPreV1005HumanLaunch( // Closed complete pair, but upstream publication and Account identity remain controlled inputs. var binding = CanonicalHumanPublicationOwnerTestFixtures.completeBinding(descriptor, policy); String bindingJson = new tools.jackson.databind.ObjectMapper().writeValueAsString(binding); - fixture.transactions.executeWithoutResult( - status -> { - long instanceId = - fixture - .dsl - .fetchSingle( - "INSERT INTO game_instances (tenant_id, runtime_version, owner_account_id, owner_account_uuid, status, row_version, " - + "game_instance_uuid, game_template_id, launch_descriptor_id, version_id, release_bundle_id, " - + "generation_config_revision, version_state_epoch, run_owned_start_request_id, " - + "run_owned_start_request_digest, run_owned_start_published_release_bundle_ref) " - + "VALUES (?, '72', NULL, ?, 'STARTING', 0, ?, ?, 'human-launch-descriptor', 72, 73, 'generation-1', " - + "3, ?, ?, 'human-release-bundle') RETURNING id", - fresh.get("legacy_game_session_tenant_id"), - tuple.preAuthorizationTuple().action().target().ownerAccountId(), - instanceUuid, - GAME_TEMPLATE_ID, - requestId, - tuple.mutationDigest()) - .get("id", Long.class); - var columns = new java.util.LinkedHashMap(); - columns.put("target_namespace", NAMESPACE); - columns.put("control_plane_request_id", requestId); - columns.put("game_session_tenant_id", fresh.get("legacy_game_session_tenant_id")); - columns.put("canonical_tenant_id", receipt.source().canonicalTenantId()); - for (String field : - java.util.List.of( - "association_operation_id", - "association_request_id", - "source_schema_version", - "source_target_namespace", - "source_request_id", - "source_canonical_tenant_id", - "source_game_row_id", - "source_game_tenant_key", - "source_provenance_kind", - "association_kind")) { - String target = "tenant_" + field; - if (field.equals("source_provenance_kind")) { - columns.put(target, fresh.get("provenance_kind")); - } else { - columns.put(target, fresh.get(field)); - } - } - columns.put("game_instance_id", instanceId); - columns.put("game_instance_uuid", instanceUuid); - columns.put("canonical_realm_id", realmId); - columns.put("world_slug", catalog.get("world_slug")); - columns.put("playable_state_namespace_id", catalog.get("playable_state_namespace_id")); - columns.put("playable_state_scope", catalog.get("state_scope")); - columns.put("public_production", true); - columns.put("captured_starting_row_version", 0L); - columns.put("game_template_id", GAME_TEMPLATE_ID); - columns.put("launch_descriptor_id", "human-launch-descriptor"); - columns.put("version_id", 72L); - columns.put("release_bundle_id", 73L); - columns.put("generation_config_revision", "generation-1"); - columns.put("version_state_epoch", 3L); - columns.put("complete_launch_binding_evidence", org.jooq.JSONB.valueOf(bindingJson)); - insertOwnerRow(fixture, "game_session_canonical_instance_launch", columns); - }); + fixture.transactions.executeWithoutResult(status -> { + long instanceId = + fixture + .dsl + .fetchSingle( + "INSERT INTO game_instances (tenant_id, runtime_version, owner_account_id, owner_account_uuid, status, row_version, " + + "game_instance_uuid, game_template_id, launch_descriptor_id, version_id, release_bundle_id, " + + "generation_config_revision, version_state_epoch, run_owned_start_request_id, " + + "run_owned_start_request_digest, run_owned_start_published_release_bundle_ref) " + + "VALUES (?, '72', NULL, ?, 'STARTING', 0, ?, ?, 'human-launch-descriptor', 72, 73, 'generation-1', " + + "3, ?, ?, 'human-release-bundle') RETURNING id", + fresh.get("legacy_game_session_tenant_id"), + tuple.preAuthorizationTuple().action().target().ownerAccountId(), + instanceUuid, + GAME_TEMPLATE_ID, + requestId, + tuple.mutationDigest()) + .get("id", Long.class); + var columns = new java.util.LinkedHashMap(); + columns.put("target_namespace", NAMESPACE); + columns.put("control_plane_request_id", requestId); + columns.put("game_session_tenant_id", fresh.get("legacy_game_session_tenant_id")); + columns.put("canonical_tenant_id", receipt.source().canonicalTenantId()); + for (String field : + java.util.List.of( + "association_operation_id", + "association_request_id", + "source_schema_version", + "source_target_namespace", + "source_request_id", + "source_canonical_tenant_id", + "source_game_row_id", + "source_game_tenant_key", + "source_provenance_kind", + "association_kind")) { + String target = "tenant_" + field; + if (field.equals("source_provenance_kind")) { + columns.put(target, fresh.get("provenance_kind")); + } else { + columns.put(target, fresh.get(field)); + } + } + columns.put("game_instance_id", instanceId); + columns.put("game_instance_uuid", instanceUuid); + columns.put("canonical_realm_id", realmId); + columns.put("world_slug", catalog.get("world_slug")); + columns.put("playable_state_namespace_id", catalog.get("playable_state_namespace_id")); + columns.put("playable_state_scope", catalog.get("state_scope")); + columns.put("public_production", true); + columns.put("captured_starting_row_version", 0L); + columns.put("game_template_id", GAME_TEMPLATE_ID); + columns.put("launch_descriptor_id", "human-launch-descriptor"); + columns.put("version_id", 72L); + columns.put("release_bundle_id", 73L); + columns.put("generation_config_revision", "generation-1"); + columns.put("version_state_epoch", 3L); + columns.put("complete_launch_binding_evidence", org.jooq.JSONB.valueOf(bindingJson)); + insertOwnerRow(fixture, "game_session_canonical_instance_launch", columns); + }); } private static void insertHumanLaunch( @@ -1062,85 +1051,84 @@ private static void insertHumanLaunch( uuid(Math.toIntExact(OWNER_ACCOUNT_ID)), GAME_TEMPLATE_ID, requestId); - fixture.transactions.executeWithoutResult( - status -> { - long instanceId = - fixture - .dsl - .fetchSingle( - "INSERT INTO game_instances (tenant_id, runtime_version, owner_account_id, status, row_version, " - + "game_instance_uuid, game_template_id, launch_descriptor_id, version_id, release_bundle_id, " - + "generation_config_revision, version_state_epoch, run_owned_start_request_id, " - + "run_owned_start_request_digest, run_owned_start_published_release_bundle_ref) " - + "VALUES (?, '72', ?, 'STARTING', 0, ?, ?, 'human-launch-descriptor', 72, 73, 'generation-1', " - + "3, ?, ?, 'human-release-bundle') RETURNING id", - fresh.get("legacy_game_session_tenant_id"), - OWNER_ACCOUNT_ID, - instanceUuid, - GAME_TEMPLATE_ID, - requestId, - tuple.mutationDigest()) - .get("id", Long.class); - var columns = new java.util.LinkedHashMap(); - columns.put("target_namespace", NAMESPACE); - columns.put("control_plane_request_id", requestId); - columns.put("game_session_tenant_id", fresh.get("legacy_game_session_tenant_id")); - columns.put("canonical_tenant_id", receipt.source().canonicalTenantId()); - for (String field : - java.util.List.of( - "association_operation_id", - "association_request_id", - "source_schema_version", - "source_target_namespace", - "source_request_id", - "source_canonical_tenant_id", - "source_game_row_id", - "source_game_tenant_key", - "source_provenance_kind", - "association_kind")) { - String target = "tenant_" + field; - if (field.equals("source_provenance_kind")) { - columns.put(target, fresh.get("provenance_kind")); - } else { - columns.put(target, fresh.get(field)); - } - } - columns.put("game_instance_id", instanceId); - columns.put("game_instance_uuid", instanceUuid); - columns.put("canonical_realm_id", realmId); - columns.put("world_slug", catalog.get("world_slug")); - columns.put("playable_state_namespace_id", catalog.get("playable_state_namespace_id")); - columns.put("playable_state_scope", catalog.get("state_scope")); - columns.put("public_production", true); - columns.put("captured_starting_row_version", 0L); - columns.put("game_template_id", GAME_TEMPLATE_ID); - columns.put("launch_descriptor_id", "human-launch-descriptor"); - columns.put("version_id", 72L); - columns.put("release_bundle_id", 73L); - columns.put("generation_config_revision", "generation-1"); - columns.put("version_state_epoch", 3L); - // Guard-level SQL input; the full Human launch binding remains separately - // owner-validated. - String bindingJson = - String.format( - "{\"descriptor\":{\"targetNamespace\":\"%s\",\"controlPlaneRequestId\":\"%s\"," - + "\"canonicalTenantId\":\"%s\",\"worldSlug\":\"%s\",\"gameTemplateId\":%d," - + "\"launchDescriptorId\":\"human-launch-descriptor\",\"versionId\":72,\"releaseBundleId\":73," - + "\"generationConfigRevision\":\"generation-1\",\"versionStateEpoch\":3," - + "\"publishedReleaseBundleRef\":\"human-release-bundle\"},\"releaseAttestation\":{}}", - NAMESPACE, + fixture.transactions.executeWithoutResult(status -> { + long instanceId = + fixture + .dsl + .fetchSingle( + "INSERT INTO game_instances (tenant_id, runtime_version, owner_account_id, status, row_version, " + + "game_instance_uuid, game_template_id, launch_descriptor_id, version_id, release_bundle_id, " + + "generation_config_revision, version_state_epoch, run_owned_start_request_id, " + + "run_owned_start_request_digest, run_owned_start_published_release_bundle_ref) " + + "VALUES (?, '72', ?, 'STARTING', 0, ?, ?, 'human-launch-descriptor', 72, 73, 'generation-1', " + + "3, ?, ?, 'human-release-bundle') RETURNING id", + fresh.get("legacy_game_session_tenant_id"), + OWNER_ACCOUNT_ID, + instanceUuid, + GAME_TEMPLATE_ID, requestId, - receipt.source().canonicalTenantId(), - catalog.get("world_slug"), - GAME_TEMPLATE_ID); - columns.put("complete_launch_binding_evidence", org.jooq.JSONB.valueOf(bindingJson)); - columns.put("original_start_session_tuple", tuple.canonicalBytes()); - columns.put("catalog_creation_request_id", catalog.get("creation_request_id")); - columns.put("catalog_revision", catalog.get("catalog_revision")); - columns.put("catalog_source_intake_operation_id", receipt.operationId()); - columns.put("catalog_source_intake_request_id", receipt.intakeRequestId()); - insertOwnerRow(fixture, "game_session_canonical_instance_launch", columns); - }); + tuple.mutationDigest()) + .get("id", Long.class); + var columns = new java.util.LinkedHashMap(); + columns.put("target_namespace", NAMESPACE); + columns.put("control_plane_request_id", requestId); + columns.put("game_session_tenant_id", fresh.get("legacy_game_session_tenant_id")); + columns.put("canonical_tenant_id", receipt.source().canonicalTenantId()); + for (String field : + java.util.List.of( + "association_operation_id", + "association_request_id", + "source_schema_version", + "source_target_namespace", + "source_request_id", + "source_canonical_tenant_id", + "source_game_row_id", + "source_game_tenant_key", + "source_provenance_kind", + "association_kind")) { + String target = "tenant_" + field; + if (field.equals("source_provenance_kind")) { + columns.put(target, fresh.get("provenance_kind")); + } else { + columns.put(target, fresh.get(field)); + } + } + columns.put("game_instance_id", instanceId); + columns.put("game_instance_uuid", instanceUuid); + columns.put("canonical_realm_id", realmId); + columns.put("world_slug", catalog.get("world_slug")); + columns.put("playable_state_namespace_id", catalog.get("playable_state_namespace_id")); + columns.put("playable_state_scope", catalog.get("state_scope")); + columns.put("public_production", true); + columns.put("captured_starting_row_version", 0L); + columns.put("game_template_id", GAME_TEMPLATE_ID); + columns.put("launch_descriptor_id", "human-launch-descriptor"); + columns.put("version_id", 72L); + columns.put("release_bundle_id", 73L); + columns.put("generation_config_revision", "generation-1"); + columns.put("version_state_epoch", 3L); + // Guard-level SQL input; the full Human launch binding remains separately + // owner-validated. + String bindingJson = + String.format( + "{\"descriptor\":{\"targetNamespace\":\"%s\",\"controlPlaneRequestId\":\"%s\"," + + "\"canonicalTenantId\":\"%s\",\"worldSlug\":\"%s\",\"gameTemplateId\":%d," + + "\"launchDescriptorId\":\"human-launch-descriptor\",\"versionId\":72,\"releaseBundleId\":73," + + "\"generationConfigRevision\":\"generation-1\",\"versionStateEpoch\":3," + + "\"publishedReleaseBundleRef\":\"human-release-bundle\"},\"releaseAttestation\":{}}", + NAMESPACE, + requestId, + receipt.source().canonicalTenantId(), + catalog.get("world_slug"), + GAME_TEMPLATE_ID); + columns.put("complete_launch_binding_evidence", org.jooq.JSONB.valueOf(bindingJson)); + columns.put("original_start_session_tuple", tuple.canonicalBytes()); + columns.put("catalog_creation_request_id", catalog.get("creation_request_id")); + columns.put("catalog_revision", catalog.get("catalog_revision")); + columns.put("catalog_source_intake_operation_id", receipt.operationId()); + columns.put("catalog_source_intake_request_id", receipt.intakeRequestId()); + insertOwnerRow(fixture, "game_session_canonical_instance_launch", columns); + }); } private static void insertOwnerRow( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index 61f0f11f42..a54c30a5eb 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -99,24 +99,22 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB .isEqualTo(f.tables().size()); for (String name : List.of("gameplay_command", "remote_followup")) { assertThat(catalog.families()) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo(name); - assertThat(family.stateClass()).isEqualTo(StateClass.UNKNOWN); - assertThat(family.freshDisposition()) - .isEqualTo(FreshDisposition.STATE_CLASS_UNKNOWN_BLOCKING); - }); + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo(name); + assertThat(family.stateClass()).isEqualTo(StateClass.UNKNOWN); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.STATE_CLASS_UNKNOWN_BLOCKING); + }); } assertThat(catalog.families()) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo("game_manifest"); - assertThat(family.stateClass()).isEqualTo(StateClass.UNRESOLVED); - assertThat(family.freshDisposition()) - .isEqualTo(FreshDisposition.UNSUPPORTED_SOURCE_BLOCKING); - assertThat(family.ownerConsequence()) - .contains("legacy", "tenant", "Not build or FRESH authority"); - }); + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo("game_manifest"); + assertThat(family.stateClass()).isEqualTo(StateClass.UNRESOLVED); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.UNSUPPORTED_SOURCE_BLOCKING); + assertThat(family.ownerConsequence()) + .contains("legacy", "tenant", "Not build or FRESH authority"); + }); for (String name : List.of( "tick_batch", @@ -126,19 +124,17 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "game_session_region_runtime_status", "game_session_region_timeline_preparation")) { assertThat(catalog.families()) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo(name); - assertThat(family.freshDisposition()) - .isEqualTo(FreshDisposition.RUNTIME_EVIDENCE_BLOCKING); - }); + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo(name); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.RUNTIME_EVIDENCE_BLOCKING); + }); } assertThat(catalog.families()) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo("player_command_history"); - assertThat(family.role()).isEqualTo(Role.AUDIT); - }); + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo("player_command_history"); + assertThat(family.role()).isEqualTo(Role.AUDIT); + }); for (String name : List.of( "saga_instance", @@ -159,11 +155,10 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB assertPrivateRevisionClassifications(catalog); assertPrivateRuntimeClassification(catalog); assertThat(catalog.families()) - .noneMatch( - family -> - family.familyId().equals("redis_session") - || family.familyId().equals("tick_queue") - || family.familyId().equals("issuer_redis_index")); + .noneMatch(family -> + family.familyId().equals("redis_session") + || family.familyId().equals("tick_queue") + || family.familyId().equals("issuer_redis_index")); assertThat(catalog.families()) .allSatisfy(family -> assertThat(family.ownerConsequence()).isNotBlank()); assertThat(catalog.nonSqlGaps()) @@ -186,14 +181,13 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1060", "catalog-installation:1061", "catalog-installation:1062") - .noneMatch( - identity -> - identity.contains(":1057:") - || identity.contains(":1058:") - || identity.contains(":1059:") - || identity.contains(":1060:") - || identity.contains(":1061:") - || identity.contains(":1062:")); + .noneMatch(identity -> + identity.contains(":1057:") + || identity.contains(":1058:") + || identity.contains(":1059:") + || identity.contains(":1060:") + || identity.contains(":1061:") + || identity.contains(":1062:")); assertThat( f.dsl .fetchSingle( @@ -227,11 +221,10 @@ void actualConfiguredHistoryIsBoundWithoutHardcodedHistoryAlias() { try (Fixture f = fixture(null, history)) { var evidence = f.owner().capture(request()); assertThat(evidence.catalog().families()) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo(history); - assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.CONTROL_ONLY); - }); + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo(history); + assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.CONTROL_ONLY); + }); assertThat(f.owner().readExact(evidence.request())).isEqualTo(evidence); assertThat( f.dsl @@ -279,17 +272,15 @@ void concurrentExactRetriesConvergeOnOneCommittedSnapshot() throws Exception { Request read = request(); var start = new CountDownLatch(1); var first = - workers.submit( - () -> { - start.await(); - return f.owner().capture(read); - }); + workers.submit(() -> { + start.await(); + return f.owner().capture(read); + }); var second = - workers.submit( - () -> { - start.await(); - return f.owner().capture(read); - }); + workers.submit(() -> { + start.await(); + return f.owner().capture(read); + }); start.countDown(); var evidence = first.get(30, TimeUnit.SECONDS); assertThat(second.get(30, TimeUnit.SECONDS)).isEqualTo(evidence); @@ -447,23 +438,20 @@ void populatedV1056UpgradePreservesAllOriginalRowsHistorySequencesAndGuards() { assertThat(f.rows(before.keySet())).isEqualTo(before); assertThat(f.sequencePositions()).containsAll(sequences); // Original authority/replay/hold guards remain effective, not merely present by name. - assertThatThrownBy( - () -> - f.dsl.execute( - "UPDATE game_session_start_session_operator_attempt SET owner_fence=owner_fence+1")) + assertThatThrownBy(() -> + f.dsl.execute( + "UPDATE game_session_start_session_operator_attempt SET owner_fence=owner_fence+1")) .hasMessageContaining("immutable"); - assertThatThrownBy( - () -> - f.dsl.execute( - "UPDATE game_session_start_session_operator_attempt SET lease_expires_at=lease_expires_at+interval '1 hour'")) + assertThatThrownBy(() -> + f.dsl.execute( + "UPDATE game_session_start_session_operator_attempt SET lease_expires_at=lease_expires_at+interval '1 hour'")) .hasMessageContaining("immutable"); assertThatThrownBy( () -> f.dsl.execute("DELETE FROM game_session_start_session_operator_attempt")) .hasMessageContaining("immutable"); - assertThatThrownBy( - () -> - f.dsl.execute( - "UPDATE game_session_initial_gameplay_login_journal SET expected_attempt_fence=2")) + assertThatThrownBy(() -> + f.dsl.execute( + "UPDATE game_session_initial_gameplay_login_journal SET expected_attempt_fence=2")) .hasMessageContaining("cannot be replaced or reopened"); assertThatThrownBy( () -> f.dsl.execute("DELETE FROM game_session_initial_gameplay_login_journal")) @@ -738,13 +726,11 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow var original = f.owner().capture(request()); assertThat(original.catalog().catalogEpoch()).isEqualTo(6); assertThat(original.catalog().schemaFacts()) - .anyMatch( - fact -> - fact.kind() == FactKind.VIEW && fact.identity().equals("catalog_probe_view")) - .anyMatch( - fact -> - fact.kind() == FactKind.VIEW - && fact.identity().equals("catalog_probe_materialized")); + .anyMatch(fact -> + fact.kind() == FactKind.VIEW && fact.identity().equals("catalog_probe_view")) + .anyMatch(fact -> + fact.kind() == FactKind.VIEW + && fact.identity().equals("catalog_probe_materialized")); Map before = f.rows(f.tables()); var definitions = f.dsl.fetch( @@ -954,53 +940,49 @@ void metadataEpochAndSnapshotGuardsRefuseMutationStaleBytesAndChangedExactSqlFra .hasMessageContaining("immutable"); } for (String consequence : List.of(" ", "\t")) { - assertThatThrownBy( - () -> - f.dsl.execute( - "INSERT INTO " - + CLASSIFICATIONS - + " VALUES('game_manifest.description','game_manifest','description','SOURCE','UNRESOLVED'," - + "'UNSUPPORTED_SOURCE_BLOCKING','UNRESOLVED_RETAINED',?)", - consequence)) + assertThatThrownBy(() -> + f.dsl.execute( + "INSERT INTO " + + CLASSIFICATIONS + + " VALUES('game_manifest.description','game_manifest','description','SOURCE','UNRESOLVED'," + + "'UNSUPPORTED_SOURCE_BLOCKING','UNRESOLVED_RETAINED',?)", + consequence)) .hasMessageContaining("ck_gs_runtime_family_consequence"); } - assertThatThrownBy( - () -> - f.dsl.execute( - "INSERT INTO " - + EPOCHS - + "(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 7,catalog_bytes,catalog_digest FROM " - + EPOCHS - + " WHERE catalog_epoch=6")) + assertThatThrownBy(() -> + f.dsl.execute( + "INSERT INTO " + + EPOCHS + + "(catalog_epoch,catalog_bytes,catalog_digest)" + + " SELECT 7,catalog_bytes,catalog_digest FROM " + + EPOCHS + + " WHERE catalog_epoch=6")) .hasMessageContaining("exact classified installed schema"); - assertThatThrownBy( - () -> - f.dsl.execute( - "INSERT INTO " - + SNAPSHOTS - + "(read_request_id,target_namespace,request_bytes,request_digest,snapshot_id,catalog_epoch,catalog_digest,evidence_bytes,evidence_digest)" - + " SELECT ?,target_namespace,request_bytes,request_digest,?,catalog_epoch,catalog_digest,evidence_bytes,evidence_digest" - + " FROM " - + SNAPSHOTS - + " WHERE read_request_id=?", - UUID.randomUUID(), - UUID.randomUUID(), - original.request().readRequestId())) + assertThatThrownBy(() -> + f.dsl.execute( + "INSERT INTO " + + SNAPSHOTS + + "(read_request_id,target_namespace,request_bytes,request_digest,snapshot_id,catalog_epoch,catalog_digest,evidence_bytes,evidence_digest)" + + " SELECT ?,target_namespace,request_bytes,request_digest,?,catalog_epoch,catalog_digest,evidence_bytes,evidence_digest" + + " FROM " + + SNAPSHOTS + + " WHERE read_request_id=?", + UUID.randomUUID(), + UUID.randomUUID(), + original.request().readRequestId())) .hasMessageContaining("complete exact request and evidence"); - assertThatThrownBy( - () -> - f.dsl.execute( - "INSERT INTO " - + SNAPSHOTS - + "(read_request_id,target_namespace,request_bytes,request_digest,snapshot_id,catalog_epoch,catalog_digest,evidence_bytes,evidence_digest)" - + " SELECT ?,target_namespace,request_bytes,request_digest,?,catalog_epoch,'sha256:'||repeat('0',64),evidence_bytes,evidence_digest" - + " FROM " - + SNAPSHOTS - + " WHERE read_request_id=?", - UUID.randomUUID(), - UUID.randomUUID(), - original.request().readRequestId())) + assertThatThrownBy(() -> + f.dsl.execute( + "INSERT INTO " + + SNAPSHOTS + + "(read_request_id,target_namespace,request_bytes,request_digest,snapshot_id,catalog_epoch,catalog_digest,evidence_bytes,evidence_digest)" + + " SELECT ?,target_namespace,request_bytes,request_digest,?,catalog_epoch,'sha256:'||repeat('0',64),evidence_bytes,evidence_digest" + + " FROM " + + SNAPSHOTS + + " WHERE read_request_id=?", + UUID.randomUUID(), + UUID.randomUUID(), + original.request().readRequestId())) .hasMessageContaining("new owner epoch required"); assertThat(f.count(SNAPSHOTS)).isEqualTo(1); } @@ -1266,17 +1248,15 @@ private static Request request() { private static void assertPrivateRuntimeClassification(GameSessionRuntimeFamilyCatalog catalog) { assertThat(catalog.families()) - .anySatisfy( - family -> { - assertThat(family.familyId()) - .isEqualTo("game_session_private_fresh_runtime_allocations"); - assertThat(family.role()).isEqualTo(Role.CONTROL); - assertThat(family.stateClass()).isEqualTo(StateClass.NOT_PAYLOAD); - assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.CONTROL_ONLY); - assertThat(family.retentionDisposition()) - .isEqualTo(RetentionDisposition.IMMUTABLE_RETAINED); - assertThat(family.ownerConsequence()).contains("provenance", "no running instance"); - }); + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo("game_session_private_fresh_runtime_allocations"); + assertThat(family.role()).isEqualTo(Role.CONTROL); + assertThat(family.stateClass()).isEqualTo(StateClass.NOT_PAYLOAD); + assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.CONTROL_ONLY); + assertThat(family.retentionDisposition()) + .isEqualTo(RetentionDisposition.IMMUTABLE_RETAINED); + assertThat(family.ownerConsequence()).contains("provenance", "no running instance"); + }); } private static void assertPrivateRevisionClassifications( @@ -1290,15 +1270,14 @@ private static void assertPrivateRevisionClassifications( "game_session_current_private_catalog_revisions", RetentionDisposition.OWNER_POLICY_RETAINED))) { assertThat(catalog.families()) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo(expected.getKey()); - assertThat(family.role()).isEqualTo(Role.CONTROL); - assertThat(family.stateClass()).isEqualTo(StateClass.NOT_PAYLOAD); - assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.CONTROL_ONLY); - assertThat(family.retentionDisposition()).isEqualTo(expected.getValue()); - assertThat(family.ownerConsequence()).isNotBlank(); - }); + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo(expected.getKey()); + assertThat(family.role()).isEqualTo(Role.CONTROL); + assertThat(family.stateClass()).isEqualTo(StateClass.NOT_PAYLOAD); + assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.CONTROL_ONLY); + assertThat(family.retentionDisposition()).isEqualTo(expected.getValue()); + assertThat(family.ownerConsequence()).isNotBlank(); + }); } } @@ -1548,14 +1527,13 @@ void populatePrivateCatalogAllocation() { var intake = Objects.requireNonNull( transaction.execute(status -> sourceOwner.register(UUID.randomUUID(), evidence))); - transaction.executeWithoutResult( - status -> - new GameSessionFreshTenantAssociationRepository(dsl) - .associateFresh( - UUID.randomUUID(), - "test", - intake, - CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(evidence))); + transaction.executeWithoutResult(status -> + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + UUID.randomUUID(), + "test", + intake, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(evidence))); var catalogRequest = new CreateCanonicalRealmCatalogRequest( UUID.randomUUID(), @@ -1617,23 +1595,21 @@ void populatePrivateCatalogAllocation() { .plusSeconds(3600)); var preparation = Objects.requireNonNull( - transaction.execute( - status -> - new GameSessionInitialPlaytestLifecycleRepository(dsl) - .prepare(preparationRequest))) + transaction.execute(status -> + new GameSessionInitialPlaytestLifecycleRepository(dsl) + .prepare(preparationRequest))) .preparation(); var privateTargets = new GameSessionPrivateFreshTargetRepository(dsl); var serializable = new TransactionTemplate(manager); serializable.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); var allocation = Objects.requireNonNull( - serializable.execute( - status -> - privateTargets.allocate( - new GameSessionPrivateFreshTargetRepository.Request( - UUID.randomUUID(), - preparationRequest.requestId(), - preparation.playtestLifecycleId())))); + serializable.execute(status -> + privateTargets.allocate( + new GameSessionPrivateFreshTargetRepository.Request( + UUID.randomUUID(), + preparationRequest.requestId(), + preparation.playtestLifecycleId())))); assertThat(allocation.replayed()).isFalse(); assertThat( privateTargets.readByPreparation( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java index 616027f924..8a224012d4 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryIntegrationTest.java @@ -114,15 +114,14 @@ void pinsCanonicalDescriptorAndExactRepeatReturnsOriginalWireEvidence() { GameSessionStartSessionLaunchDescriptorRepository .StartSessionLaunchDescriptorConflictException.class) .hasMessageContaining("original immutable StartSession pin"); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "UPDATE game_session_start_session_launch_descriptor_pin " - + "SET descriptor_response_digest = ? WHERE target_namespace = ? " - + "AND control_plane_request_id = ?", - "sha256:" + "c".repeat(64), - retained.claim().targetNamespace(), - retained.claim().controlPlaneRequestId())) + assertThatThrownBy(() -> + fixture.dsl.execute( + "UPDATE game_session_start_session_launch_descriptor_pin " + + "SET descriptor_response_digest = ? WHERE target_namespace = ? " + + "AND control_plane_request_id = ?", + "sha256:" + "c".repeat(64), + retained.claim().targetNamespace(), + retained.claim().controlPlaneRequestId())) .isInstanceOf(RuntimeException.class); assertThat(fixture.pinCount()).isEqualTo(1); } @@ -246,12 +245,11 @@ void continuationCannotPinAReselectedAssociationDigest() { originalAssociation.worldPublishedStartLocationEvidence(), originalAssociation.phaseEpoch()); - assertThatThrownBy( - () -> - fixture.pin( - continuation, - new StartSessionLaunchDescriptorGrpcCodec.Resolved( - substitutedAssociation, original.outcome()))) + assertThatThrownBy(() -> + fixture.pin( + continuation, + new StartSessionLaunchDescriptorGrpcCodec.Resolved( + substitutedAssociation, original.outcome()))) .isInstanceOf( GameSessionStartSessionLaunchDescriptorRepository .StartSessionLaunchDescriptorConflictException.class) @@ -289,46 +287,40 @@ void continuationReplayRejectsAClaimThatExpiresWhileTheDescriptorReadWaits() thr java.util.concurrent.CompletableFuture blockerPid = new java.util.concurrent.CompletableFuture<>(); Future blocker = - executor.submit( - () -> - fixture.transactions.executeWithoutResult( - status -> { - int backendPid = - Objects.requireNonNull( - Objects.requireNonNull( - fixture.dsl.fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class)); - fixture.dsl.fetchOne( - "SELECT 1 FROM game_session_start_session_launch_descriptor_pin " - + "WHERE target_namespace = ? AND control_plane_request_id = ? " - + "FOR UPDATE", - retained.claim().targetNamespace(), - retained.claim().controlPlaneRequestId()); - blockerPid.complete(backendPid); - blockerReady.countDown(); - awaitLatch(releaseBlocker, "descriptor read lock release"); - })); + executor.submit(() -> + fixture.transactions.executeWithoutResult(status -> { + int backendPid = + Objects.requireNonNull( + Objects.requireNonNull(fixture.dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + fixture.dsl.fetchOne( + "SELECT 1 FROM game_session_start_session_launch_descriptor_pin " + + "WHERE target_namespace = ? AND control_plane_request_id = ? " + + "FOR UPDATE", + retained.claim().targetNamespace(), + retained.claim().controlPlaneRequestId()); + blockerPid.complete(backendPid); + blockerReady.countDown(); + awaitLatch(releaseBlocker, "descriptor read lock release"); + })); assertThat(blockerReady.await(15, TimeUnit.SECONDS)).isTrue(); java.util.concurrent.CompletableFuture waiterPid = new java.util.concurrent.CompletableFuture<>(); Future waiter = - executor.submit( - () -> - fixture.transactions.execute( - status -> { - waiterPid.complete( - Objects.requireNonNull( - Objects.requireNonNull( - fixture.dsl.fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class))); - try { - fixture.descriptors.findPinned(continuation); - return null; - } catch (RuntimeException failure) { - return failure; - } - })); + executor.submit(() -> + fixture.transactions.execute(status -> { + waiterPid.complete( + Objects.requireNonNull( + Objects.requireNonNull(fixture.dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class))); + try { + fixture.descriptors.findPinned(continuation); + return null; + } catch (RuntimeException failure) { + return failure; + } + })); int readBackendPid = waiterPid.get(15, TimeUnit.SECONDS); int blockerBackendPid = blockerPid.get(15, TimeUnit.SECONDS); awaitPostgresLockWait(fixture.dsl, readBackendPid, blockerBackendPid); @@ -369,10 +361,8 @@ void liveOwnerClaimCannotCreateDescriptorPinAfterOriginalAuthorizationExpires() assertThat(fixture.originalAuthorizationReferenceLive(originalAuthorizationExpiresAt)).isTrue(); awaitOriginalAuthorizationExpiry(fixture, originalAuthorizationExpiresAt); assertThat(fixture.ownerClaimLeaseLive(retained.claim().controlPlaneRequestId())).isTrue(); - assertThatThrownBy( - () -> - fixture.pin( - retained.claim(), descriptor(retained, "expired-original-auth-descriptor"))) + assertThatThrownBy(() -> + fixture.pin(retained.claim(), descriptor(retained, "expired-original-auth-descriptor"))) .isInstanceOf( GameSessionStartSessionOperatorAttemptRepository .StaleStartSessionOperatorAttemptClaimException.class) @@ -406,46 +396,40 @@ void continuationReplayRejectsOriginalReferenceThatExpiresWhileDescriptorReadWai java.util.concurrent.CompletableFuture blockerPid = new java.util.concurrent.CompletableFuture<>(); Future blocker = - executor.submit( - () -> - fixture.transactions.executeWithoutResult( - status -> { - int backendPid = - Objects.requireNonNull( - Objects.requireNonNull( - fixture.dsl.fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class)); - fixture.dsl.fetchOne( - "SELECT 1 FROM game_session_start_session_launch_descriptor_pin " - + "WHERE target_namespace = ? AND control_plane_request_id = ? " - + "FOR UPDATE", - retained.claim().targetNamespace(), - retained.claim().controlPlaneRequestId()); - blockerPid.complete(backendPid); - blockerReady.countDown(); - awaitLatch(releaseBlocker, "descriptor read lock release"); - })); + executor.submit(() -> + fixture.transactions.executeWithoutResult(status -> { + int backendPid = + Objects.requireNonNull( + Objects.requireNonNull(fixture.dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + fixture.dsl.fetchOne( + "SELECT 1 FROM game_session_start_session_launch_descriptor_pin " + + "WHERE target_namespace = ? AND control_plane_request_id = ? " + + "FOR UPDATE", + retained.claim().targetNamespace(), + retained.claim().controlPlaneRequestId()); + blockerPid.complete(backendPid); + blockerReady.countDown(); + awaitLatch(releaseBlocker, "descriptor read lock release"); + })); assertThat(blockerReady.await(15, TimeUnit.SECONDS)).isTrue(); java.util.concurrent.CompletableFuture waiterPid = new java.util.concurrent.CompletableFuture<>(); Future waiter = - executor.submit( - () -> - fixture.transactions.execute( - status -> { - waiterPid.complete( - Objects.requireNonNull( - Objects.requireNonNull( - fixture.dsl.fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class))); - try { - fixture.descriptors.findPinned(continuation); - return null; - } catch (RuntimeException failure) { - return failure; - } - })); + executor.submit(() -> + fixture.transactions.execute(status -> { + waiterPid.complete( + Objects.requireNonNull( + Objects.requireNonNull(fixture.dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class))); + try { + fixture.descriptors.findPinned(continuation); + return null; + } catch (RuntimeException failure) { + return failure; + } + })); int readBackendPid = waiterPid.get(15, TimeUnit.SECONDS); int blockerBackendPid = blockerPid.get(15, TimeUnit.SECONDS); awaitPostgresLockWait(fixture.dsl, readBackendPid, blockerBackendPid); @@ -545,12 +529,11 @@ void continuationServiceCallsGameDesignOutsideSqlAndPinsItsExactReplayOutcome() StartSessionLaunchDescriptorReadClient client = mock(StartSessionLaunchDescriptorReadClient.class); when(client.resolve(any(Request.class))) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - return candidate; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return candidate; + }); var service = fixture.continuationService(accountClient, client); PinnedLaunchDescriptorSnapshot pinned = service.continueOriginalEvidence(retained.tuple()); @@ -575,12 +558,11 @@ private static StartSessionRedeemedOperationProjectionClient projectionClient( ReadRedeemedOperationProjectionResponse response = redeemedProjection(retained.tuple(), request.ownerAttemptId(), request.ownerFence()); when(client.read(retained.tuple(), request.ownerAttemptId(), request.ownerFence())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - return response; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return response; + }); return client; } @@ -674,30 +656,29 @@ private static void assertDescriptorPinRejectedForOwnerTuple( UUID canonicalTenantId, UUID ownerAttemptId, long ownerFence) { - assertThatThrownBy( - () -> - fixture.dsl.execute( - "INSERT INTO game_session_start_session_launch_descriptor_pin " - + "(target_namespace, control_plane_request_id, canonical_tenant_id, " - + "owner_attempt_id, owner_fence, association_request_digest, " - + "association_response_digest, descriptor_request_wire, " - + "descriptor_response_wire, descriptor_request_digest, " - + "descriptor_response_digest) " - + "SELECT association.target_namespace, association.control_plane_request_id, " - + "?, ?, ?, association.association_request_digest, " - + "association.association_response_digest, ?, ?, ?, ? " - + "FROM game_session_start_session_template_association_pin association " - + "WHERE association.target_namespace = ? " - + "AND association.control_plane_request_id = ?", - canonicalTenantId, - ownerAttemptId, - ownerFence, - new byte[] {1}, - new byte[] {1}, - "sha256:" + "a".repeat(64), - "sha256:" + "b".repeat(64), - retained.claim().targetNamespace(), - retained.claim().controlPlaneRequestId())) + assertThatThrownBy(() -> + fixture.dsl.execute( + "INSERT INTO game_session_start_session_launch_descriptor_pin " + + "(target_namespace, control_plane_request_id, canonical_tenant_id, " + + "owner_attempt_id, owner_fence, association_request_digest, " + + "association_response_digest, descriptor_request_wire, " + + "descriptor_response_wire, descriptor_request_digest, " + + "descriptor_response_digest) " + + "SELECT association.target_namespace, association.control_plane_request_id, " + + "?, ?, ?, association.association_request_digest, " + + "association.association_response_digest, ?, ?, ?, ? " + + "FROM game_session_start_session_template_association_pin association " + + "WHERE association.target_namespace = ? " + + "AND association.control_plane_request_id = ?", + canonicalTenantId, + ownerAttemptId, + ownerFence, + new byte[] {1}, + new byte[] {1}, + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + retained.claim().targetNamespace(), + retained.claim().controlPlaneRequestId())) .isInstanceOf(RuntimeException.class) .hasMessageContaining("fk_gs_start_session_launch_descriptor_association"); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java index 50f925e789..bc0477b006 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java @@ -307,10 +307,9 @@ private static PriorRuntime seedV34_3PriorRuntime( IntakeReceipt sourceReceipt = Objects.requireNonNull( new TransactionTemplate(new DataSourceTransactionManager(dataSource)) - .execute( - status -> - new GameSessionAuthoredWorldSourceRepository(dsl) - .register(sourceIntakeRequestId, sourceEvidence)), + .execute(status -> + new GameSessionAuthoredWorldSourceRepository(dsl) + .register(sourceIntakeRequestId, sourceEvidence)), "registered V34.3 authored-world source through its owner"); PriorRuntime target = new PriorRuntime( @@ -341,17 +340,16 @@ private static PriorRuntime seedV34_3PriorRuntime( "launch-" + token, "published-release-" + shortToken); // The V22 source uses its owner above; remaining rows use only deployed V23/V26 columns. - dsl.transaction( - configuration -> { - DSLContext tx = DSL.using(configuration); - seedV34_3SourceAndCatalog(tx, target, sourceEvidence, sourceReceipt); - seedV34_3TenantAssociation(tx, target); - seedV34_3StartingRuntimeAndLaunch(tx, target); - tx.execute( - "UPDATE game_instances SET status = 'RUNNING' WHERE tenant_id = ? AND id = ?", - target.gameSessionTenantId(), - target.gameInstanceId()); - }); + dsl.transaction(configuration -> { + DSLContext tx = DSL.using(configuration); + seedV34_3SourceAndCatalog(tx, target, sourceEvidence, sourceReceipt); + seedV34_3TenantAssociation(tx, target); + seedV34_3StartingRuntimeAndLaunch(tx, target); + tx.execute( + "UPDATE game_instances SET status = 'RUNNING' WHERE tenant_id = ? AND id = ?", + target.gameSessionTenantId(), + target.gameInstanceId()); + }); return target; } @@ -842,11 +840,10 @@ void exactAccountProjectionAttachesOnceWhileFingerprintAndSourceSubstitutionsCon AccountRedemptionProjection exact = projection(FINGERPRINT, exactBundle, ISSUANCE_ID, 23L, tuple); - fixture.transactions.executeWithoutResult( - status -> { - fixture.repository.attachAccountRedemptionProjection(claim, exact); - status.setRollbackOnly(); - }); + fixture.transactions.executeWithoutResult(status -> { + fixture.repository.attachAccountRedemptionProjection(claim, exact); + status.setRollbackOnly(); + }); assertThat(fixture.reserve(tuple).snapshot().accountRedemptionProjection()).isNull(); AttemptSnapshot attached = fixture.attach(claim, exact); @@ -993,10 +990,9 @@ void currentOriginalAttemptReadRejectsExpiredAndUnattachedOrMismatchedEvidenceWi AttemptClaim unattachedClaim = unattached.reserve(unattachedTuple).claim().orElseThrow(); String unattachedBefore = unattached.ownerAttemptRowJson(unattachedTuple.controlPlaneRequestId()); - assertThatThrownBy( - () -> - unattached.currentOriginalAttempt( - currentAttemptRequest(unattachedTuple, unattachedClaim))) + assertThatThrownBy(() -> + unattached.currentOriginalAttempt( + currentAttemptRequest(unattachedTuple, unattachedClaim))) .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class) .hasMessageContaining("no attached Account projection"); assertThat(unattached.ownerAttemptRowJson(unattachedTuple.controlPlaneRequestId())) @@ -1015,32 +1011,29 @@ void currentOriginalAttemptReadRejectsExpiredAndUnattachedOrMismatchedEvidenceWi 23L, tuple)); String before = mismatched.ownerAttemptRowJson(tuple.controlPlaneRequestId()); - assertThatThrownBy( - () -> - mismatched.currentOriginalAttempt( - currentAttemptRequest( - tuple, - UUID.fromString("1819a1ce-04d2-4e3f-bb64-4a672d4eb711"), - claim.ownerMutationId(), - claim.ownerFence()))) + assertThatThrownBy(() -> + mismatched.currentOriginalAttempt( + currentAttemptRequest( + tuple, + UUID.fromString("1819a1ce-04d2-4e3f-bb64-4a672d4eb711"), + claim.ownerMutationId(), + claim.ownerFence()))) .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class); - assertThatThrownBy( - () -> - mismatched.currentOriginalAttempt( - currentAttemptRequest( - tuple, - claim.ownerAttemptId(), - UUID.fromString("2819a1ce-04d2-4e3f-bb64-4a672d4eb711"), - claim.ownerFence()))) + assertThatThrownBy(() -> + mismatched.currentOriginalAttempt( + currentAttemptRequest( + tuple, + claim.ownerAttemptId(), + UUID.fromString("2819a1ce-04d2-4e3f-bb64-4a672d4eb711"), + claim.ownerFence()))) .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class); - assertThatThrownBy( - () -> - mismatched.currentOriginalAttempt( - currentAttemptRequest( - tuple, - claim.ownerAttemptId(), - claim.ownerMutationId(), - claim.ownerFence() + 1L))) + assertThatThrownBy(() -> + mismatched.currentOriginalAttempt( + currentAttemptRequest( + tuple, + claim.ownerAttemptId(), + claim.ownerMutationId(), + claim.ownerFence() + 1L))) .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class); StartSessionPostAuthorizationExecutionTuple changedTuple = tuple(tuple.controlPlaneRequestId(), "different complete action"); @@ -1197,41 +1190,34 @@ void historicalOwnerReadRejectsWrongTupleTenantAttemptAndFence() { 23L, tuple)); - assertThatThrownBy( - () -> - fixture.historical( - tuple(tuple.controlPlaneRequestId(), "different complete action"), - claim.ownerAttemptId(), - claim.ownerFence())) + assertThatThrownBy(() -> + fixture.historical( + tuple(tuple.controlPlaneRequestId(), "different complete action"), + claim.ownerAttemptId(), + claim.ownerFence())) .isInstanceOf( GameSessionStartSessionOperatorAttemptRepository .StartSessionOperatorAttemptConflictException.class); - assertThatThrownBy( - () -> - fixture.historical( - tupleWithTenant( - tuple.controlPlaneRequestId(), - UUID.fromString("4d2cde3b-0834-4e65-84aa-436d88e5f6c5")), - claim.ownerAttemptId(), - claim.ownerFence())) + assertThatThrownBy(() -> + fixture.historical( + tupleWithTenant( + tuple.controlPlaneRequestId(), + UUID.fromString("4d2cde3b-0834-4e65-84aa-436d88e5f6c5")), + claim.ownerAttemptId(), + claim.ownerFence())) .isInstanceOf( GameSessionStartSessionOperatorAttemptRepository .StartSessionOperatorAttemptConflictException.class); - assertThatThrownBy( - () -> - fixture.historical( - tuple, - UUID.fromString("1819a1ce-04d2-4e3f-bb64-4a672d4eb711"), - claim.ownerFence())) + assertThatThrownBy(() -> + fixture.historical( + tuple, UUID.fromString("1819a1ce-04d2-4e3f-bb64-4a672d4eb711"), claim.ownerFence())) .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class); assertThatThrownBy( () -> fixture.historical(tuple, claim.ownerAttemptId(), claim.ownerFence() + 1L)) .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class); - assertThatThrownBy( - () -> - fixture.transactions.execute( - status -> - fixture.historical(tuple, claim.ownerAttemptId(), claim.ownerFence()))) + assertThatThrownBy(() -> + fixture.transactions.execute( + status -> fixture.historical(tuple, claim.ownerAttemptId(), claim.ownerFence()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("outside the owner transaction"); assertThat(fixture.attemptCount()).isEqualTo(1); @@ -1243,10 +1229,9 @@ void historicalOwnerReadRejectsMissingAndCorruptedAttachedProjection() { StartSessionPostAuthorizationExecutionTuple missingTuple = tuple("operator-attempt-historical-no-projection"); AttemptClaim missingClaim = missing.reserve(missingTuple).claim().orElseThrow(); - assertThatThrownBy( - () -> - missing.historical( - missingTuple, missingClaim.ownerAttemptId(), missingClaim.ownerFence())) + assertThatThrownBy(() -> + missing.historical( + missingTuple, missingClaim.ownerAttemptId(), missingClaim.ownerFence())) .isInstanceOf(StaleStartSessionOperatorAttemptClaimException.class) .hasMessageContaining("no attached Account projection"); @@ -1277,10 +1262,9 @@ void historicalOwnerReadRejectsMissingAndCorruptedAttachedProjection() { "ALTER TABLE game_session_start_session_operator_attempt " + "ENABLE TRIGGER game_session_start_session_operator_attempt_immutable"); } - assertThatThrownBy( - () -> - corrupted.historical( - corruptedTuple, corruptedClaim.ownerAttemptId(), corruptedClaim.ownerFence())) + assertThatThrownBy(() -> + corrupted.historical( + corruptedTuple, corruptedClaim.ownerAttemptId(), corruptedClaim.ownerFence())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("projection differs"); assertThat(corrupted.attemptCount()).isEqualTo(1); @@ -1313,10 +1297,9 @@ void evidenceContinuationRequiresTheExactAttachedProjectionAndUnexpiredOriginalA ReservationResult exactReplay = fixture.reserve(tuple); assertThat(exactReplay.claim()).isEmpty(); assertThat(exactReplay.disposition()).isEqualTo(ReservationDisposition.EXACT_REPLAY); - assertThatThrownBy( - () -> - fixture.continueEvidence( - tuple(tuple.controlPlaneRequestId(), "changed complete action"))) + assertThatThrownBy(() -> + fixture.continueEvidence( + tuple(tuple.controlPlaneRequestId(), "changed complete action"))) .isInstanceOf( GameSessionStartSessionOperatorAttemptRepository .StartSessionOperatorAttemptConflictException.class) @@ -1411,24 +1394,23 @@ void descriptorInsertRechecksOriginalReferenceExpiryAfterContinuationPrechecks() ExecutorService executor = Executors.newSingleThreadExecutor(); AtomicReference> pinAttempt = new AtomicReference<>(); try { - fixture.transactions.executeWithoutResult( - status -> { - fixture.dsl.execute( - "LOCK TABLE game_session_start_session_launch_descriptor_pin IN SHARE MODE"); - pinAttempt.set(executor.submit(() -> fixture.pin(continuation, descriptor))); - awaitDescriptorPinInsertWait(fixture); - long remainingMillis = - Duration.between(Instant.now(), authorityExpiresAt.plusMillis(500)).toMillis(); - if (remainingMillis > 0L) { - try { - Thread.sleep(remainingMillis); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException( - "Interrupted while holding descriptor pin lock", interrupted); - } - } - }); + fixture.transactions.executeWithoutResult(status -> { + fixture.dsl.execute( + "LOCK TABLE game_session_start_session_launch_descriptor_pin IN SHARE MODE"); + pinAttempt.set(executor.submit(() -> fixture.pin(continuation, descriptor))); + awaitDescriptorPinInsertWait(fixture); + long remainingMillis = + Duration.between(Instant.now(), authorityExpiresAt.plusMillis(500)).toMillis(); + if (remainingMillis > 0L) { + try { + Thread.sleep(remainingMillis); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while holding descriptor pin lock", interrupted); + } + } + }); try { pinAttempt.get().get(10, TimeUnit.SECONDS); @@ -1518,11 +1500,10 @@ void rollbackLeavesNoAttemptRecord() { Fixture fixture = fixture(Duration.ofSeconds(30)); StartSessionPostAuthorizationExecutionTuple tuple = tuple("operator-attempt-rollback"); - fixture.transactions.executeWithoutResult( - status -> { - fixture.repository.reserve(tuple); - status.setRollbackOnly(); - }); + fixture.transactions.executeWithoutResult(status -> { + fixture.repository.reserve(tuple); + status.setRollbackOnly(); + }); assertThat(fixture.attemptCount()).isZero(); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java index 438c20808c..50c7e0b264 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryIntegrationTest.java @@ -186,15 +186,14 @@ void pinsOneInitialSelectionAndExactReplayReturnsTheOriginalWireSelection() { assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("game_instances")))).isZero(); assertThat(fixture.dsl.fetchCount(DSL.table(DSL.name("gameplay_admission_pointer")))).isZero(); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "UPDATE game_session_start_session_template_association_pin " - + "SET selected_commit_id = ? WHERE target_namespace = ? " - + "AND control_plane_request_id = ?", - UUID.fromString("66666666-6666-4666-8666-666666666666"), - claim.targetNamespace(), - claim.controlPlaneRequestId())) + assertThatThrownBy(() -> + fixture.dsl.execute( + "UPDATE game_session_start_session_template_association_pin " + + "SET selected_commit_id = ? WHERE target_namespace = ? " + + "AND control_plane_request_id = ?", + UUID.fromString("66666666-6666-4666-8666-666666666666"), + claim.targetNamespace(), + claim.controlPlaneRequestId())) .isInstanceOf(RuntimeException.class); assertThat(fixture.pinCount()).isEqualTo(1); } @@ -255,11 +254,9 @@ void historicalPinReadReturnsExpiredOwnerSelectionWithoutChangingOwnerState() th GameSessionStartSessionOperatorAttemptRepository .StaleStartSessionOperatorAttemptClaimException.class) .hasMessageContaining("expired"); - assertThatThrownBy( - () -> - fixture.transactions.execute( - status -> - fixture.historical(tuple, claim.ownerAttemptId(), claim.ownerFence()))) + assertThatThrownBy(() -> + fixture.transactions.execute( + status -> fixture.historical(tuple, claim.ownerAttemptId(), claim.ownerFence()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("outside the owner transaction"); assertThat(fixture.attemptCount()).isEqualTo(attemptsBefore); @@ -300,10 +297,8 @@ void physicalAssociationPinRejectsSourceFenceAndLinearizationSubstitutions() { tupleWithReference(tuple, referenceChange[0], referenceChange[1]); replaceOwnerProjection(fixture, tuple, substituted.canonicalBytes()); - assertThatThrownBy( - () -> - fixture.pin( - claim, result(tuple, claim, new InitialConfigured(), UUID.randomUUID()))) + assertThatThrownBy(() -> + fixture.pin(claim, result(tuple, claim, new InitialConfigured(), UUID.randomUUID()))) .isInstanceOf( GameSessionStartSessionOperatorAttemptRepository .StaleStartSessionOperatorAttemptClaimException.class) @@ -393,10 +388,8 @@ void initialAssociationInsertRejectsExpiredOriginalAuthorizationWhileOwnerClaimR assertThat(fixture.leaseExpired(claim.controlPlaneRequestId())).isFalse(); assertThat(fixture.originalAuthorizationReferenceLive(expiresAt.toString())).isFalse(); - assertThatThrownBy( - () -> - fixture.pin( - claim, result(tuple, claim, new InitialConfigured(), UUID.randomUUID()))) + assertThatThrownBy(() -> + fixture.pin(claim, result(tuple, claim, new InitialConfigured(), UUID.randomUUID()))) .isInstanceOf( GameSessionStartSessionOperatorAttemptRepository .StaleStartSessionOperatorAttemptClaimException.class) @@ -427,43 +420,37 @@ void initialAssociationInsertRejectsOriginalAuthorizationThatExpiresWhileWriteIs java.util.concurrent.CompletableFuture blockerPid = new java.util.concurrent.CompletableFuture<>(); Future blocker = - executor.submit( - () -> - fixture.transactions.executeWithoutResult( - status -> { - int backendPid = - Objects.requireNonNull( - Objects.requireNonNull( - fixture.dsl.fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class)); - fixture.dsl.execute( - "LOCK TABLE game_session_start_session_template_association_pin " - + "IN SHARE ROW EXCLUSIVE MODE"); - blockerPid.complete(backendPid); - blockerReady.countDown(); - awaitLatch(releaseBlocker, "association insert lock release"); - })); + executor.submit(() -> + fixture.transactions.executeWithoutResult(status -> { + int backendPid = + Objects.requireNonNull( + Objects.requireNonNull(fixture.dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + fixture.dsl.execute( + "LOCK TABLE game_session_start_session_template_association_pin " + + "IN SHARE ROW EXCLUSIVE MODE"); + blockerPid.complete(backendPid); + blockerReady.countDown(); + awaitLatch(releaseBlocker, "association insert lock release"); + })); assertThat(blockerReady.await(15, TimeUnit.SECONDS)).isTrue(); java.util.concurrent.CompletableFuture waiterPid = new java.util.concurrent.CompletableFuture<>(); Future waiter = - executor.submit( - () -> - fixture.transactions.execute( - status -> { - waiterPid.complete( - Objects.requireNonNull( - Objects.requireNonNull( - fixture.dsl.fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class))); - try { - fixture.pins.pinInitialOrValidateExactReplay(claim, initial); - return null; - } catch (RuntimeException failure) { - return failure; - } - })); + executor.submit(() -> + fixture.transactions.execute(status -> { + waiterPid.complete( + Objects.requireNonNull( + Objects.requireNonNull(fixture.dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class))); + try { + fixture.pins.pinInitialOrValidateExactReplay(claim, initial); + return null; + } catch (RuntimeException failure) { + return failure; + } + })); int pinBackendPid = waiterPid.get(15, TimeUnit.SECONDS); int blockerBackendPid = blockerPid.get(15, TimeUnit.SECONDS); awaitPostgresLockWait(fixture.dsl, pinBackendPid, blockerBackendPid); @@ -500,43 +487,37 @@ void initialAssociationInsertRejectsAClaimThatExpiresWhileTheInsertIsBlocked() t java.util.concurrent.CompletableFuture blockerPid = new java.util.concurrent.CompletableFuture<>(); Future blocker = - executor.submit( - () -> - fixture.transactions.executeWithoutResult( - status -> { - int backendPid = - Objects.requireNonNull( - Objects.requireNonNull( - fixture.dsl.fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class)); - fixture.dsl.execute( - "LOCK TABLE game_session_start_session_template_association_pin " - + "IN SHARE ROW EXCLUSIVE MODE"); - blockerPid.complete(backendPid); - blockerReady.countDown(); - awaitLatch(releaseBlocker, "association insert lock release"); - })); + executor.submit(() -> + fixture.transactions.executeWithoutResult(status -> { + int backendPid = + Objects.requireNonNull( + Objects.requireNonNull(fixture.dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class)); + fixture.dsl.execute( + "LOCK TABLE game_session_start_session_template_association_pin " + + "IN SHARE ROW EXCLUSIVE MODE"); + blockerPid.complete(backendPid); + blockerReady.countDown(); + awaitLatch(releaseBlocker, "association insert lock release"); + })); assertThat(blockerReady.await(15, TimeUnit.SECONDS)).isTrue(); java.util.concurrent.CompletableFuture waiterPid = new java.util.concurrent.CompletableFuture<>(); Future waiter = - executor.submit( - () -> - fixture.transactions.execute( - status -> { - waiterPid.complete( - Objects.requireNonNull( - Objects.requireNonNull( - fixture.dsl.fetchOne("SELECT pg_backend_pid()")) - .get(0, Integer.class))); - try { - fixture.pins.pinInitialOrValidateExactReplay(claim, initial); - return null; - } catch (RuntimeException failure) { - return failure; - } - })); + executor.submit(() -> + fixture.transactions.execute(status -> { + waiterPid.complete( + Objects.requireNonNull( + Objects.requireNonNull(fixture.dsl.fetchOne("SELECT pg_backend_pid()")) + .get(0, Integer.class))); + try { + fixture.pins.pinInitialOrValidateExactReplay(claim, initial); + return null; + } catch (RuntimeException failure) { + return failure; + } + })); int pinBackendPid = waiterPid.get(15, TimeUnit.SECONDS); int blockerBackendPid = blockerPid.get(15, TimeUnit.SECONDS); awaitPostgresLockWait(fixture.dsl, pinBackendPid, blockerBackendPid); @@ -845,26 +826,22 @@ private static PublishedReleaseBundle release(WorldPublishedStartLocationEvidenc .setCanonicalVersionId(VERSION.toString()) .setManifestSchemaVersion(1); AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder() - .forEach( - owner -> { - ParticipantDigest.Builder participant = - ParticipantDigest.newBuilder() - .setParticipantKey(owner) - .setScopeValue("19") - .setAppliedCommitId(request.appliedCommitId()) - .setContentDigest( - "WORLD_MANAGEMENT".equals(owner) - ? request.contentDigest() - : "d".repeat(64)) - .setDigestSchemaVersion( - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, - AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION)); - if ("GAME_LOGIC".equals(owner)) { - participant.setAbilitySchemaDigest("sha256:" + "e".repeat(64)); - } - builder.addParticipantDigests(participant); - }); + .forEach(owner -> { + ParticipantDigest.Builder participant = + ParticipantDigest.newBuilder() + .setParticipantKey(owner) + .setScopeValue("19") + .setAppliedCommitId(request.appliedCommitId()) + .setContentDigest( + "WORLD_MANAGEMENT".equals(owner) ? request.contentDigest() : "d".repeat(64)) + .setDigestSchemaVersion( + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION)); + if ("GAME_LOGIC".equals(owner)) { + participant.setAbilitySchemaDigest("sha256:" + "e".repeat(64)); + } + builder.addParticipantDigests(participant); + }); return builder.build(); } @@ -889,15 +866,14 @@ private static WorldPublishedStartLocationEvidence worldEvidence() { graphDigest); var tuples = draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) + .map(unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) .toList(); var selectorRequest = new WorldPublishedStartLocationEvidence.Request( @@ -1032,15 +1008,14 @@ private static byte[] appliedReadback( applied.put( "appliedEpochs", draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - Map.of( - "aggregateType", unit.aggregateType(), - "aggregateId", unit.aggregateId(), - "scopeType", unit.scopeType(), - "scopeId", unit.scopeId(), - "expectedEpoch", unit.expectedEpoch(), - "resultingEpoch", "1")) + .map(unit -> + Map.of( + "aggregateType", unit.aggregateType(), + "aggregateId", unit.aggregateId(), + "scopeType", unit.scopeType(), + "scopeId", unit.scopeId(), + "expectedEpoch", unit.expectedEpoch(), + "resultingEpoch", "1")) .toList()); return Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(applied)); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java index 651ba6a033..c246fe4010 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerCardinalityIntegrationTest.java @@ -91,17 +91,16 @@ void forwardIndexPreservesRetainedRowsAndEnforcesVisiblePublicCardinality() { + "AND public_production_realm = true")) .isEqualTo(2L); - assertUniqueIndexViolation( - () -> - dsl.execute( - "INSERT INTO gameplay_admission_pointer (world_slug, world_display_name, " - + "realm_slug, realm_display_name, tenant_id, game_instance_id, " - + "pointer_version, visible, requires_character_selection, state_scope, " - + "character_creation_policy, last_updated_by, last_update_reason, " - + "public_production_realm) VALUES ('write-attempt', 'Write Attempt', " - + "'production', 'Production', ?, 9510201, 1, true, false, 'SHARED', " - + "'ALLOW_NEW', 'test/cardinality', 'second public insert', true)", - SINGLE_PUBLIC_TENANT_ID)); + assertUniqueIndexViolation(() -> + dsl.execute( + "INSERT INTO gameplay_admission_pointer (world_slug, world_display_name, " + + "realm_slug, realm_display_name, tenant_id, game_instance_id, " + + "pointer_version, visible, requires_character_selection, state_scope, " + + "character_creation_policy, last_updated_by, last_update_reason, " + + "public_production_realm) VALUES ('write-attempt', 'Write Attempt', " + + "'production', 'Production', ?, 9510201, 1, true, false, 'SHARED', " + + "'ALLOW_NEW', 'test/cardinality', 'second public insert', true)", + SINGLE_PUBLIC_TENANT_ID)); assertThat( scalarLong( dsl, @@ -111,12 +110,11 @@ void forwardIndexPreservesRetainedRowsAndEnforcesVisiblePublicCardinality() { .isZero(); String nonpublicBefore = rowAndXmin(dsl, VISIBLE_NONPUBLIC_ID); - assertUniqueIndexViolation( - () -> - dsl.execute( - "UPDATE gameplay_admission_pointer SET public_production_realm = true " - + "WHERE id = ?", - VISIBLE_NONPUBLIC_ID)); + assertUniqueIndexViolation(() -> + dsl.execute( + "UPDATE gameplay_admission_pointer SET public_production_realm = true " + + "WHERE id = ?", + VISIBLE_NONPUBLIC_ID)); assertThat(rowAndXmin(dsl, VISIBLE_NONPUBLIC_ID)).isEqualTo(nonpublicBefore); assertThat(visiblePublicCount(dsl, SINGLE_PUBLIC_TENANT_ID)).isEqualTo(1L); @@ -178,28 +176,24 @@ void actualUniqueIndexViolationsAreTypedAndRollBackPointerAndAuditWrites() { retainedRowsAndXmins(dsl, "gameplay_admission_pointer"); List eventsBeforeCreateConflict = retainedRowsAndXmins(dsl, "gameplay_admission_pointer_event"); - assertThatThrownBy( - () -> - dsl.transaction( - configuration -> - authorityService(DSL.using(configuration)) - .upsertPointer( - pointerMutation( - "another-world", - "production", - SINGLE_PUBLIC_TENANT_ID, - 9510202L, - true, - 0L, - 0L, - "duplicate-public-create")))) + assertThatThrownBy(() -> + dsl.transaction(configuration -> + authorityService(DSL.using(configuration)) + .upsertPointer( + pointerMutation( + "another-world", + "production", + SINGLE_PUBLIC_TENANT_ID, + 9510202L, + true, + 0L, + 0L, + "duplicate-public-create")))) .isInstanceOf(AdmissionPointerConflictException.class) - .satisfies( - failure -> { - assertThat(failure.getCause()) - .isInstanceOf(IntegrityConstraintViolationException.class); - assertThat(sqlState(failure)).isEqualTo("23505"); - }); + .satisfies(failure -> { + assertThat(failure.getCause()).isInstanceOf(IntegrityConstraintViolationException.class); + assertThat(sqlState(failure)).isEqualTo("23505"); + }); assertThat(retainedRowsAndXmins(dsl, "gameplay_admission_pointer")) .isEqualTo(pointersBeforeCreateConflict); assertThat(retainedRowsAndXmins(dsl, "gameplay_admission_pointer_event")) @@ -219,28 +213,24 @@ void actualUniqueIndexViolationsAreTypedAndRollBackPointerAndAuditWrites() { retainedRowsAndXmins(dsl, "gameplay_admission_pointer"); List eventsBeforeUpdateConflict = retainedRowsAndXmins(dsl, "gameplay_admission_pointer_event"); - assertThatThrownBy( - () -> - dsl.transaction( - configuration -> - authorityService(DSL.using(configuration)) - .upsertPointer( - pointerMutation( - "preview-world", - "preview", - SINGLE_PUBLIC_TENANT_ID, - 9510203L, - true, - 1L, - 1L, - "duplicate-public-update")))) + assertThatThrownBy(() -> + dsl.transaction(configuration -> + authorityService(DSL.using(configuration)) + .upsertPointer( + pointerMutation( + "preview-world", + "preview", + SINGLE_PUBLIC_TENANT_ID, + 9510203L, + true, + 1L, + 1L, + "duplicate-public-update")))) .isInstanceOf(AdmissionPointerConflictException.class) - .satisfies( - failure -> { - assertThat(failure.getCause()) - .isInstanceOf(IntegrityConstraintViolationException.class); - assertThat(sqlState(failure)).isEqualTo("23505"); - }); + .satisfies(failure -> { + assertThat(failure.getCause()).isInstanceOf(IntegrityConstraintViolationException.class); + assertThat(sqlState(failure)).isEqualTo("23505"); + }); assertThat(retainedRowsAndXmins(dsl, "gameplay_admission_pointer")) .isEqualTo(pointersBeforeUpdateConflict); assertThat(retainedRowsAndXmins(dsl, "gameplay_admission_pointer_event")) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java index 61d1fe3926..bb28da6fd7 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java @@ -569,24 +569,19 @@ void migrationsV1ThroughV7BackfillPointerIdentityAndKeepHistoricalAuditUnknown() () -> insertPointer(dsl, 6L, 10L, "demo", "alternate", 111L, true, false, "SHARED")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("uq_gameplay_admission_pointer_runtime_target"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE gameplay_admission_pointer SET realm_id = ? WHERE id = 3", - sharedRealmId)) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE gameplay_admission_pointer SET realm_id = ? WHERE id = 3", sharedRealmId)) .isInstanceOf(DataAccessException.class) .hasMessageContaining("uq_gameplay_admission_pointer_realm_id"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE gameplay_admission_pointer SET playable_state_namespace_id = NULL " - + "WHERE id = 1")) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE gameplay_admission_pointer SET playable_state_namespace_id = NULL " + + "WHERE id = 1")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("gameplay_admission_pointer_identity_pair_complete"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE gameplay_admission_pointer SET catalog_revision = 0 WHERE id = 1")) + assertThatThrownBy(() -> + dsl.execute("UPDATE gameplay_admission_pointer SET catalog_revision = 0 WHERE id = 1")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("gameplay_admission_pointer_catalog_revision_positive"); @@ -632,18 +627,16 @@ void migrationsV1ThroughV7BackfillPointerIdentityAndKeepHistoricalAuditUnknown() assertThat(boundEvent.get("realm_id", UUID.class)).isEqualTo(eventRealmId); assertThat(boundEvent.get("playable_state_namespace_id", UUID.class)) .isEqualTo(eventNamespaceId); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE gameplay_admission_pointer_event SET catalog_revision = 0 " - + "WHERE id = 9002")) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE gameplay_admission_pointer_event SET catalog_revision = 0 " + + "WHERE id = 9002")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("gameplay_admission_pointer_event_catalog_revision_positive"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE gameplay_admission_pointer_event SET playable_state_namespace_id = NULL " - + "WHERE id = 9002")) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE gameplay_admission_pointer_event SET playable_state_namespace_id = NULL " + + "WHERE id = 9002")) .isInstanceOf(DataAccessException.class) .hasMessageContaining("gameplay_admission_pointer_event_identity_pair_complete"); } @@ -770,10 +763,9 @@ private static List worldViewsFromDatabase( row.get("playable_state_namespace_id", UUID.class))); } return realmsByWorld.entrySet().stream() - .map( - entry -> - new GameplayWorldCatalog.WorldView( - entry.getKey(), displayNamesByWorld.get(entry.getKey()), entry.getValue())) + .map(entry -> + new GameplayWorldCatalog.WorldView( + entry.getKey(), displayNamesByWorld.get(entry.getKey()), entry.getValue())) .toList(); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java index ca1ca93f47..505db2efb0 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java @@ -92,21 +92,20 @@ void cleanTable() { String originalGuardState = humanRuntimeCompletionTruncateGuardState(); assertThat(originalGuardState).isIn("O", "A"); - transactionTemplate.executeWithoutResult( - status -> { - dsl.execute( - "ALTER TABLE " - + HUMAN_RUNTIME_COMPLETION_TABLE - + " DISABLE TRIGGER " - + HUMAN_RUNTIME_COMPLETION_TRUNCATE_GUARD); - assertThat(humanRuntimeCompletionTruncateGuardState()).isEqualTo("D"); - dsl.execute( - "TRUNCATE TABLE gameplay_command, gameplay_admission_pointer, tick_batch, tick_effect, " - + HUMAN_RUNTIME_COMPLETION_TABLE - + " RESTART IDENTITY CASCADE"); - restoreHumanRuntimeCompletionTruncateGuard(originalGuardState); - assertThat(humanRuntimeCompletionTruncateGuardState()).isEqualTo(originalGuardState); - }); + transactionTemplate.executeWithoutResult(status -> { + dsl.execute( + "ALTER TABLE " + + HUMAN_RUNTIME_COMPLETION_TABLE + + " DISABLE TRIGGER " + + HUMAN_RUNTIME_COMPLETION_TRUNCATE_GUARD); + assertThat(humanRuntimeCompletionTruncateGuardState()).isEqualTo("D"); + dsl.execute( + "TRUNCATE TABLE gameplay_command, gameplay_admission_pointer, tick_batch, tick_effect, " + + HUMAN_RUNTIME_COMPLETION_TABLE + + " RESTART IDENTITY CASCADE"); + restoreHumanRuntimeCompletionTruncateGuard(originalGuardState); + assertThat(humanRuntimeCompletionTruncateGuardState()).isEqualTo(originalGuardState); + }); assertThat(humanRuntimeCompletionTruncateGuardState()).isEqualTo(originalGuardState); } @@ -665,13 +664,11 @@ void accountUuidEvidenceInsertRollsBackWithItsContainingTransaction() { command.setAccountId(345L); command.setAccountUuid(accountUuid); - assertThatThrownBy( - () -> - transactionTemplate.executeWithoutResult( - status -> { - repository.save(command); - throw new IllegalStateException("force transaction rollback"); - })) + assertThatThrownBy(() -> + transactionTemplate.executeWithoutResult(status -> { + repository.save(command); + throw new IllegalStateException("force transaction rollback"); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("force transaction rollback"); @@ -794,32 +791,27 @@ void stagingEligibilityLockIsTenantAndGameInstanceQualified() { boolean matchingScope = Boolean.TRUE.equals( - transactionTemplate.execute( - status -> - repository.lockAcceptedCommandForStaging( - 1L, 7L, "cmd-staging-scope", "say hello", false))); + transactionTemplate.execute(status -> + repository.lockAcceptedCommandForStaging( + 1L, 7L, "cmd-staging-scope", "say hello", false))); boolean foreignTenant = Boolean.TRUE.equals( - transactionTemplate.execute( - status -> - repository.lockAcceptedCommandForStaging( - 2L, 7L, "cmd-staging-scope", "say hello", false))); + transactionTemplate.execute(status -> + repository.lockAcceptedCommandForStaging( + 2L, 7L, "cmd-staging-scope", "say hello", false))); boolean foreignInstance = Boolean.TRUE.equals( - transactionTemplate.execute( - status -> - repository.lockAcceptedCommandForStaging( - 1L, 8L, "cmd-staging-scope", "say hello", false))); + transactionTemplate.execute(status -> + repository.lockAcceptedCommandForStaging( + 1L, 8L, "cmd-staging-scope", "say hello", false))); assertThat(matchingScope).isTrue(); assertThat(foreignTenant).isFalse(); assertThat(foreignInstance).isFalse(); - assertThatThrownBy( - () -> - transactionTemplate.execute( - status -> - repository.lockAcceptedCommandForStaging( - 1L, 7L, "cmd-staging-scope", "say goodbye", false))) + assertThatThrownBy(() -> + transactionTemplate.execute(status -> + repository.lockAcceptedCommandForStaging( + 1L, 7L, "cmd-staging-scope", "say goodbye", false))) .isInstanceOf(IllegalArgumentException.class) .hasMessage( "Gameplay command identity was reused with conflicting target or queue payload: " @@ -835,17 +827,15 @@ void concurrentAutomationAdmissionsUseOneDurableIdentityRow() throws Exception { try { Future firstResult = - executor.submit( - () -> { - start.await(); - return repository.insertIfAbsentByIdempotencyIdentity(first); - }); + executor.submit(() -> { + start.await(); + return repository.insertIfAbsentByIdempotencyIdentity(first); + }); Future secondResult = - executor.submit( - () -> { - start.await(); - return repository.insertIfAbsentByIdempotencyIdentity(second); - }); + executor.submit(() -> { + start.await(); + return repository.insertIfAbsentByIdempotencyIdentity(second); + }); start.countDown(); GameplayCommandRepository.IdempotentInsertResult firstInsert = firstResult.get(); @@ -902,25 +892,23 @@ private void assertRoutedAdmissionLocksPointerMutation(GameplayCommand command) assertThat(pointerLockInterlock.pointerLockAcquired.await(10, TimeUnit.SECONDS)).isTrue(); Future pointerMutation = - executor.submit( - () -> { - try { - transactionTemplate.execute( - status -> { - dsl.execute("SET LOCAL lock_timeout = '100ms'"); - assertThat(dsl.fetchValue("SHOW lock_timeout")).isEqualTo("100ms"); - return updateAdmissionPointer(); - }); - pointerLockInterlock.pointerMutationBlocked.countDown(); - throw new AssertionError("The pointer mutation interleaved with admission"); - } catch (RuntimeException failure) { - pointerLockInterlock.pointerMutationBlocked.countDown(); - if (!"55P03".equals(sqlState(failure))) { - throw failure; - } - } - return transactionTemplate.execute(status -> updateAdmissionPointer()); + executor.submit(() -> { + try { + transactionTemplate.execute(status -> { + dsl.execute("SET LOCAL lock_timeout = '100ms'"); + assertThat(dsl.fetchValue("SHOW lock_timeout")).isEqualTo("100ms"); + return updateAdmissionPointer(); }); + pointerLockInterlock.pointerMutationBlocked.countDown(); + throw new AssertionError("The pointer mutation interleaved with admission"); + } catch (RuntimeException failure) { + pointerLockInterlock.pointerMutationBlocked.countDown(); + if (!"55P03".equals(sqlState(failure))) { + throw failure; + } + } + return transactionTemplate.execute(status -> updateAdmissionPointer()); + }); assertThat(pointerLockInterlock.mutationStatementStarted.await(10, TimeUnit.SECONDS)) .isTrue(); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java index c2e725e1f0..4f5ad0f372 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java @@ -136,12 +136,11 @@ void disposeOnlyOwnedSchema() throws Exception { @Test void committedReservationIsExactReplayableAndSurvivesOwnerReplacementWithoutCredentials() { var original = coordinates(); - transactions.executeWithoutResult( - status -> { - assertThat(journal.reserve(original).coordinates()).isEqualTo(original); - assertThatThrownBy(() -> journal.readCommitted(original)) - .isInstanceOf(JournalUnavailableException.class); - }); + transactions.executeWithoutResult(status -> { + assertThat(journal.reserve(original).coordinates()).isEqualTo(original); + assertThatThrownBy(() -> journal.readCommitted(original)) + .isInstanceOf(JournalUnavailableException.class); + }); var committed = journal.readCommitted(original).orElseThrow(); assertThat(committed.abandoned()).isFalse(); assertThat(committed.verifiedWitness()).isEmpty(); @@ -188,11 +187,10 @@ void committedReservationIsExactReplayableAndSurvivesOwnerReplacementWithoutCred @Test void rolledBackReservationIsNotCommittedDispatchEvidence() { var original = coordinates(); - transactions.executeWithoutResult( - status -> { - journal.reserve(original); - status.setRollbackOnly(); - }); + transactions.executeWithoutResult(status -> { + journal.reserve(original); + status.setRollbackOnly(); + }); assertThat(journal.readCommitted(original)).isEmpty(); assertThat(journal.readRetainedPage(Optional.empty(), 128)).isEmpty(); assertThatThrownBy(() -> transactions.executeWithoutResult(status -> journal.abandon(original))) @@ -227,10 +225,8 @@ void requestIdentityAndContextFenceCannotBeRebound() { void frozenWitnessAbsenceSurvivesLateValidatedResultAndReceiptReplay() throws Exception { var original = coordinates(); reserve(original); - assertThatThrownBy( - () -> - transactions.executeWithoutResult( - status -> journal.freezeRetirementRequest(original))) + assertThatThrownBy(() -> + transactions.executeWithoutResult(status -> journal.freezeRetirementRequest(original))) .isInstanceOf(JournalConflictException.class); transactions.executeWithoutResult(status -> journal.abandon(original)); transactions.executeWithoutResult(status -> journal.freezeRetirementRequest(original)); @@ -246,16 +242,14 @@ void frozenWitnessAbsenceSurvivesLateValidatedResultAndReceiptReplay() throws Ex assertThat(frozenBytes(original)).containsExactly(frozen); transactions.executeWithoutResult(status -> journal.recordVerifiedResult(original, result)); var changedResult = validatedResult(original, UUID.randomUUID()); - assertThatThrownBy( - () -> - transactions.executeWithoutResult( - status -> journal.recordVerifiedResult(original, changedResult))) + assertThatThrownBy(() -> + transactions.executeWithoutResult( + status -> journal.recordVerifiedResult(original, changedResult))) .isInstanceOf(JournalConflictException.class); var otherOriginalResult = validatedResult(coordinates(), UUID.randomUUID()); - assertThatThrownBy( - () -> - transactions.executeWithoutResult( - status -> journal.recordVerifiedResult(original, otherOriginalResult))) + assertThatThrownBy(() -> + transactions.executeWithoutResult( + status -> journal.recordVerifiedResult(original, otherOriginalResult))) .isInstanceOf(JournalConflictException.class); UUID operation = UUID.randomUUID(); var pending = receipt(original, operation, Disposition.PENDING); @@ -269,10 +263,9 @@ void frozenWitnessAbsenceSurvivesLateValidatedResultAndReceiptReplay() throws Ex pending, receipt(original, operation, Disposition.NO_TOKEN), receipt(original, UUID.randomUUID(), Disposition.RETIRED))) { - assertThatThrownBy( - () -> - transactions.executeWithoutResult( - status -> journal.recordDisposalReceipt(original, conflict))) + assertThatThrownBy(() -> + transactions.executeWithoutResult( + status -> journal.recordDisposalReceipt(original, conflict))) .isInstanceOf(JournalConflictException.class); } assertThat(journal.readCommitted(original).orElseThrow().retainedReceipt()).contains(terminal); @@ -313,32 +306,27 @@ void independentTransactionsSerializeFreezeAgainstLateWitness() throws Exception var executor = Executors.newFixedThreadPool(2); try { var freezer = - executor.submit( - () -> - transactions.execute( - status -> { - journal.abandon(original); - var request = - journal - .freezeRetirementRequest(original) - .frozenRetirementRequest() - .orElseThrow(); - frozenInsideTransaction.countDown(); - await(releaseCommit); - return request; - })); + executor.submit(() -> + transactions.execute(status -> { + journal.abandon(original); + var request = + journal + .freezeRetirementRequest(original) + .frozenRetirementRequest() + .orElseThrow(); + frozenInsideTransaction.countDown(); + await(releaseCommit); + return request; + })); assertThat(frozenInsideTransaction.await(5, TimeUnit.SECONDS)).isTrue(); var late = - executor.submit( - () -> - transactions.execute( - status -> { - lateBackend.set( - dsl.fetchSingle("SELECT pg_backend_pid() AS pid") - .get("pid", Integer.class)); - lateStarted.countDown(); - return journal.recordVerifiedResult(original, result); - })); + executor.submit(() -> + transactions.execute(status -> { + lateBackend.set( + dsl.fetchSingle("SELECT pg_backend_pid() AS pid").get("pid", Integer.class)); + lateStarted.countDown(); + return journal.recordVerifiedResult(original, result); + })); assertThat(lateStarted.await(5, TimeUnit.SECONDS)).isTrue(); long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); boolean waiting = false; @@ -487,22 +475,19 @@ void transactionAndDurabilityMisuseCannotSupplyCommittedRemoteDispatchEvidence() assertThatThrownBy( () -> transactions.executeWithoutResult(status -> unjoined.reserve(original))) .isInstanceOf(JournalUnavailableException.class); - assertThatThrownBy( - () -> - transactions.executeWithoutResult( - status -> { - dsl.execute("SET LOCAL synchronous_commit = 'off'"); - journal.reserve(original); - })) + assertThatThrownBy(() -> + transactions.executeWithoutResult(status -> { + dsl.execute("SET LOCAL synchronous_commit = 'off'"); + journal.reserve(original); + })) .isInstanceOf(JournalUnavailableException.class); reserve(original); - transactions.executeWithoutResult( - status -> { - assertThatThrownBy(() -> journal.readCommitted(original)) - .isInstanceOf(JournalUnavailableException.class); - assertThatThrownBy(() -> journal.readRetainedPage(Optional.empty(), 1)) - .isInstanceOf(JournalUnavailableException.class); - }); + transactions.executeWithoutResult(status -> { + assertThatThrownBy(() -> journal.readCommitted(original)) + .isInstanceOf(JournalUnavailableException.class); + assertThatThrownBy(() -> journal.readRetainedPage(Optional.empty(), 1)) + .isInstanceOf(JournalUnavailableException.class); + }); try (Connection connection = dataSource.getConnection()) { var reader = new InitialGameplayLoginCoordinationJournalRepository( @@ -527,13 +512,12 @@ void retainedInventoryIsBoundedKeysetOrderedAndIncludesReservedAndTerminalDuty() List.of(coordinates(), coordinates(), coordinates(), coordinates(), coordinates()); originals.forEach(this::reserve); var terminalOriginal = originals.get(0); - transactions.executeWithoutResult( - status -> { - journal.abandon(terminalOriginal); - journal.freezeRetirementRequest(terminalOriginal); - journal.recordDisposalReceipt( - terminalOriginal, receipt(terminalOriginal, UUID.randomUUID(), Disposition.NO_TOKEN)); - }); + transactions.executeWithoutResult(status -> { + journal.abandon(terminalOriginal); + journal.freezeRetirementRequest(terminalOriginal); + journal.recordDisposalReceipt( + terminalOriginal, receipt(terminalOriginal, UUID.randomUUID(), Disposition.NO_TOKEN)); + }); var expected = dsl.fetch("SELECT request_id FROM " + TABLE + " ORDER BY request_id") .getValues("request_id", UUID.class); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java index d59c1941fe..e52005d6a1 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/PlayerCommandHistoryRepositoryIntegrationTest.java @@ -149,11 +149,10 @@ void concurrentAppendsKeepTheDurableScopeWithinItsConfiguredMaximum() throws Exc @Test void appendCommitsIndependentlyWhenTheCallerTransactionRollsBack() { - transactionTemplate.executeWithoutResult( - status -> { - storageService.append(22L, 7L, 13L, "LOOK", 5); - status.setRollbackOnly(); - }); + transactionTemplate.executeWithoutResult(status -> { + storageService.append(22L, 7L, 13L, "LOOK", 5); + status.setRollbackOnly(); + }); assertThat(repository.findByScope(22L, 7L, 13L)) .extracting(PlayerCommandHistoryEntry::getCommandText) @@ -180,21 +179,18 @@ void persistsTheRetentionSweepCursorAcrossRepositoryInstances() { } private void appendAfterBarrier(String command, CountDownLatch ready, CountDownLatch start) { - transactionTemplate.executeWithoutResult( - status -> { - ready.countDown(); - try { - if (!start.await(5, TimeUnit.SECONDS)) { - throw new IllegalStateException( - "Timed out waiting to start concurrent history append"); - } - } catch (InterruptedException ex) { - Thread.currentThread().interrupt(); - throw new IllegalStateException( - "Interrupted while starting concurrent history append", ex); - } - storageService.append(22L, 7L, 13L, command, 1); - }); + transactionTemplate.executeWithoutResult(status -> { + ready.countDown(); + try { + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting to start concurrent history append"); + } + } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while starting concurrent history append", ex); + } + storageService.append(22L, 7L, 13L, command, 1); + }); } private PlayerCommandHistoryStorageService transactionalStorageService( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/RuntimeRegionStatusRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/RuntimeRegionStatusRepositoryIntegrationTest.java index 385a0ad345..d1b0f8c632 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/RuntimeRegionStatusRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/RuntimeRegionStatusRepositoryIntegrationTest.java @@ -76,14 +76,11 @@ void concurrentNaturalKeyCreationReturnsTheSingleCommittedOwnershipRow() throws try (ExecutorService executor = Executors.newFixedThreadPool(2)) { Future first = - executor.submit( - () -> - saveAfterBarrier(runtimeStatus("region-first", "instance-first"), ready, start)); + executor.submit(() -> + saveAfterBarrier(runtimeStatus("region-first", "instance-first"), ready, start)); Future second = - executor.submit( - () -> - saveAfterBarrier( - runtimeStatus("region-second", "instance-second"), ready, start)); + executor.submit(() -> + saveAfterBarrier(runtimeStatus("region-second", "instance-second"), ready, start)); assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); start.countDown(); @@ -128,12 +125,11 @@ void advanceOwnershipEpochAtomicallyUpdatesPauseAndFence() { assertThat(updated.getExecutorFence()).isEqualTo("fence-pause"); assertThat(repository.findByTenantIdAndGameInstanceId(1L, 2L)) .get() - .satisfies( - committed -> { - assertThat(committed.getRegionEpoch()).isEqualTo(2L); - assertThat(committed.isPaused()).isTrue(); - assertThat(committed.getExecutorFence()).isEqualTo("fence-pause"); - }); + .satisfies(committed -> { + assertThat(committed.getRegionEpoch()).isEqualTo(2L); + assertThat(committed.isPaused()).isTrue(); + assertThat(committed.getExecutorFence()).isEqualTo("fence-pause"); + }); } @Test @@ -163,31 +159,28 @@ void staleBaselineRefreshCannotOverwriteConcurrentPause() throws Exception { try (ExecutorService executor = Executors.newFixedThreadPool(2)) { Future> baseline = - executor.submit( - () -> { - RuntimeRegionStatus baselineStatus = - repository.ensureBaseline( - runtimeStatus("region-baseline", "instance-baseline")); - baselineRead.countDown(); - assertThat(pauseCommitted.await(5, TimeUnit.SECONDS)).isTrue(); - return repository.claimObservedOwnership( - baselineStatus, - "game-session-service", - "instance-baseline", - baselineStatus.getExecutorFence(), - Instant.parse("2026-07-23T00:00:01Z")); - }); + executor.submit(() -> { + RuntimeRegionStatus baselineStatus = + repository.ensureBaseline(runtimeStatus("region-baseline", "instance-baseline")); + baselineRead.countDown(); + assertThat(pauseCommitted.await(5, TimeUnit.SECONDS)).isTrue(); + return repository.claimObservedOwnership( + baselineStatus, + "game-session-service", + "instance-baseline", + baselineStatus.getExecutorFence(), + Instant.parse("2026-07-23T00:00:01Z")); + }); Future pause = - executor.submit( - () -> { - assertThat(baselineRead.await(5, TimeUnit.SECONDS)).isTrue(); - RuntimeRegionStatus pauseStatus = runtimeStatus("region-pause", "instance-pause"); - pauseStatus.setPaused(true); - pauseStatus.setExecutorFence("fence-pause"); - RuntimeRegionStatus paused = repository.advanceOwnershipEpoch(pauseStatus); - pauseCommitted.countDown(); - return paused; - }); + executor.submit(() -> { + assertThat(baselineRead.await(5, TimeUnit.SECONDS)).isTrue(); + RuntimeRegionStatus pauseStatus = runtimeStatus("region-pause", "instance-pause"); + pauseStatus.setPaused(true); + pauseStatus.setExecutorFence("fence-pause"); + RuntimeRegionStatus paused = repository.advanceOwnershipEpoch(pauseStatus); + pauseCommitted.countDown(); + return paused; + }); RuntimeRegionStatus pauseResult = pause.get(10, TimeUnit.SECONDS); assertThat(baseline.get(10, TimeUnit.SECONDS)).isEmpty(); @@ -232,13 +225,12 @@ void staleOwnerClaimCannotOverwriteFencedOwnerHandoff() { assertThat(repository.commitDrainedBatch(stale, "stale-batch")).isEmpty(); assertThat(repository.findByTenantIdAndGameInstanceId(1L, 2L)) .get() - .satisfies( - committed -> { - assertThat(committed.getRegionEpoch()).isEqualTo(handedOff.getRegionEpoch()); - assertThat(committed.getExecutorFence()).isEqualTo(handedOff.getExecutorFence()); - assertThat(committed.getOwnerService()).isEqualTo(handedOff.getOwnerService()); - assertThat(committed.getOwnerInstanceId()).isEqualTo(handedOff.getOwnerInstanceId()); - }); + .satisfies(committed -> { + assertThat(committed.getRegionEpoch()).isEqualTo(handedOff.getRegionEpoch()); + assertThat(committed.getExecutorFence()).isEqualTo(handedOff.getExecutorFence()); + assertThat(committed.getOwnerService()).isEqualTo(handedOff.getOwnerService()); + assertThat(committed.getOwnerInstanceId()).isEqualTo(handedOff.getOwnerInstanceId()); + }); } @Test @@ -254,12 +246,11 @@ void staleTickProgressCannotOverwriteAConcurrentPause() { assertThat(repository.advanceLastCommittedTickId(staleWriter)).isEmpty(); assertThat(repository.findByTenantIdAndGameInstanceId(1L, 2L)) .get() - .satisfies( - committed -> { - assertThat(committed.isPaused()).isTrue(); - assertThat(committed.getRegionEpoch()).isEqualTo(paused.getRegionEpoch()); - assertThat(committed.getLastCommittedTickId()).isEqualTo(0L); - }); + .satisfies(committed -> { + assertThat(committed.isPaused()).isTrue(); + assertThat(committed.getRegionEpoch()).isEqualTo(paused.getRegionEpoch()); + assertThat(committed.getLastCommittedTickId()).isEqualTo(0L); + }); } @Test @@ -275,12 +266,11 @@ void staleBatchDrainCannotOverwriteAConcurrentPause() { assertThat(repository.commitDrainedBatch(staleWriter, "batch-stale")).isEmpty(); assertThat(repository.findByTenantIdAndGameInstanceId(1L, 2L)) .get() - .satisfies( - committed -> { - assertThat(committed.isPaused()).isTrue(); - assertThat(committed.getRegionEpoch()).isEqualTo(paused.getRegionEpoch()); - assertThat(committed.getLastCommittedTickBatchId()).isNull(); - }); + .satisfies(committed -> { + assertThat(committed.isPaused()).isTrue(); + assertThat(committed.getRegionEpoch()).isEqualTo(paused.getRegionEpoch()); + assertThat(committed.getLastCommittedTickBatchId()).isNull(); + }); } private RuntimeRegionStatus saveAfterBarrier( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ScriptPinOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ScriptPinOperationRepositoryIntegrationTest.java index d9d0a96a44..b8745eeead 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ScriptPinOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/ScriptPinOperationRepositoryIntegrationTest.java @@ -148,14 +148,13 @@ void baselineEnforcesScriptPinOperationChecksAndAllowsValidOutcomeShapes() { .from(SCRIPT_PIN_OPERATION) .where(SCRIPT_PIN_OPERATION.CONTROL_PLANE_REQUEST_ID.eq("direct-valid-committed")) .fetchOne()) - .satisfies( - record -> { - assertThat(record.get(SCRIPT_PIN_OPERATION.OUTCOME)).isEqualTo("COMMITTED"); - assertThat(record.get(SCRIPT_PIN_OPERATION.ERROR_CODE)).isNull(); - assertThat(record.get(SCRIPT_PIN_OPERATION.RESULTING_SCRIPT_PATCH_VERSION)) - .isEqualTo("patch-committed"); - assertThat(record.get(SCRIPT_PIN_OPERATION.RESULTING_SCRIPT_PIN_EPOCH)).isEqualTo(2L); - }); + .satisfies(record -> { + assertThat(record.get(SCRIPT_PIN_OPERATION.OUTCOME)).isEqualTo("COMMITTED"); + assertThat(record.get(SCRIPT_PIN_OPERATION.ERROR_CODE)).isNull(); + assertThat(record.get(SCRIPT_PIN_OPERATION.RESULTING_SCRIPT_PATCH_VERSION)) + .isEqualTo("patch-committed"); + assertThat(record.get(SCRIPT_PIN_OPERATION.RESULTING_SCRIPT_PIN_EPOCH)).isEqualTo(2L); + }); assertThat( dsl.select( SCRIPT_PIN_OPERATION.OUTCOME, @@ -167,14 +166,13 @@ record -> { SCRIPT_PIN_OPERATION.CONTROL_PLANE_REQUEST_ID.eq( "direct-valid-failed-unpinned")) .fetchOne()) - .satisfies( - record -> { - assertThat(record.get(SCRIPT_PIN_OPERATION.OUTCOME)).isEqualTo("FAILED"); - assertThat(record.get(SCRIPT_PIN_OPERATION.ERROR_CODE)) - .isEqualTo("SCRIPT_PATCH_AUTHORITY_UNAVAILABLE"); - assertThat(record.get(SCRIPT_PIN_OPERATION.RESULTING_SCRIPT_PATCH_VERSION)).isNull(); - assertThat(record.get(SCRIPT_PIN_OPERATION.RESULTING_SCRIPT_PIN_EPOCH)).isNull(); - }); + .satisfies(record -> { + assertThat(record.get(SCRIPT_PIN_OPERATION.OUTCOME)).isEqualTo("FAILED"); + assertThat(record.get(SCRIPT_PIN_OPERATION.ERROR_CODE)) + .isEqualTo("SCRIPT_PATCH_AUTHORITY_UNAVAILABLE"); + assertThat(record.get(SCRIPT_PIN_OPERATION.RESULTING_SCRIPT_PATCH_VERSION)).isNull(); + assertThat(record.get(SCRIPT_PIN_OPERATION.RESULTING_SCRIPT_PIN_EPOCH)).isNull(); + }); assertThat( dsl.select( SCRIPT_PIN_OPERATION.OUTCOME, @@ -185,15 +183,14 @@ record -> { .where( SCRIPT_PIN_OPERATION.CONTROL_PLANE_REQUEST_ID.eq("direct-valid-failed-pinned")) .fetchOne()) - .satisfies( - record -> { - assertThat(record.get(SCRIPT_PIN_OPERATION.OUTCOME)).isEqualTo("FAILED"); - assertThat(record.get(SCRIPT_PIN_OPERATION.ERROR_CODE)) - .isEqualTo("SCRIPT_PATCH_AUTHORITY_UNAVAILABLE"); - assertThat(record.get(SCRIPT_PIN_OPERATION.RESULTING_SCRIPT_PATCH_VERSION)) - .isEqualTo("patch-1"); - assertThat(record.get(SCRIPT_PIN_OPERATION.RESULTING_SCRIPT_PIN_EPOCH)).isEqualTo(1L); - }); + .satisfies(record -> { + assertThat(record.get(SCRIPT_PIN_OPERATION.OUTCOME)).isEqualTo("FAILED"); + assertThat(record.get(SCRIPT_PIN_OPERATION.ERROR_CODE)) + .isEqualTo("SCRIPT_PATCH_AUTHORITY_UNAVAILABLE"); + assertThat(record.get(SCRIPT_PIN_OPERATION.RESULTING_SCRIPT_PATCH_VERSION)) + .isEqualTo("patch-1"); + assertThat(record.get(SCRIPT_PIN_OPERATION.RESULTING_SCRIPT_PIN_EPOCH)).isEqualTo(1L); + }); assertConstraintRejected( "ck_script_pin_operation_kind", @@ -329,12 +326,11 @@ void concurrentExpectedEpochWritersAllowOneAndRejectTheStaleWriter() throws Exce .from(GAME_INSTANCES) .where(GAME_INSTANCES.ID.eq(7L)) .fetchOne()) - .satisfies( - record -> { - assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)) - .isEqualTo(winner.resultingScriptPatchVersion()); - assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(2L); - }); + .satisfies(record -> { + assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)) + .isEqualTo(winner.resultingScriptPatchVersion()); + assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(2L); + }); ScriptPinMutationResult retry = repository.applyScriptPin( 1L, @@ -430,15 +426,13 @@ void sameVersionSuccessIsRepinAndReplayAndConflictUseItsDigest() { .from(SCRIPT_PIN_OPERATION) .where(SCRIPT_PIN_OPERATION.CONTROL_PLANE_REQUEST_ID.eq("request-repin")) .fetchOne()) - .satisfies( - operation -> { - assertThat(operation.get(SCRIPT_PIN_OPERATION.VALIDATED_BASE_VERSION_ID)) - .isEqualTo(100L); - assertThat(operation.get(SCRIPT_PIN_OPERATION.PREVIOUS_SCRIPT_PATCH_BASE_VERSION_ID)) - .isNull(); - assertThat(operation.get(SCRIPT_PIN_OPERATION.RESULTING_SCRIPT_PATCH_BASE_VERSION_ID)) - .isEqualTo(100L); - }); + .satisfies(operation -> { + assertThat(operation.get(SCRIPT_PIN_OPERATION.VALIDATED_BASE_VERSION_ID)).isEqualTo(100L); + assertThat(operation.get(SCRIPT_PIN_OPERATION.PREVIOUS_SCRIPT_PATCH_BASE_VERSION_ID)) + .isNull(); + assertThat(operation.get(SCRIPT_PIN_OPERATION.RESULTING_SCRIPT_PATCH_BASE_VERSION_ID)) + .isEqualTo(100L); + }); } @Test @@ -550,11 +544,10 @@ void pinAdmissionBaseMustStillMatchTheRowLockedRuntimeAndIsBoundToTheReceipt() { .from(GAME_INSTANCES) .where(GAME_INSTANCES.ID.eq(7L)) .fetchOne()) - .satisfies( - instance -> { - assertThat(instance.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-1"); - assertThat(instance.get(GAME_INSTANCES.SCRIPT_PATCH_BASE_VERSION_ID)).isNull(); - }); + .satisfies(instance -> { + assertThat(instance.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-1"); + assertThat(instance.get(GAME_INSTANCES.SCRIPT_PATCH_BASE_VERSION_ID)).isNull(); + }); assertThat( dsl.select(SCRIPT_PIN_OPERATION.VALIDATED_BASE_VERSION_ID) .from(SCRIPT_PIN_OPERATION) @@ -604,29 +597,27 @@ void pinAdmissionBaseMustStillMatchTheRowLockedRuntimeAndIsBoundToTheReceipt() { .from(GAME_INSTANCES) .where(GAME_INSTANCES.ID.eq(7L)) .fetchOne()) - .satisfies( - instance -> { - assertThat(instance.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-1"); - assertThat(instance.get(GAME_INSTANCES.SCRIPT_PATCH_BASE_VERSION_ID)).isNull(); - assertThat(instance.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(1L); - }); + .satisfies(instance -> { + assertThat(instance.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-1"); + assertThat(instance.get(GAME_INSTANCES.SCRIPT_PATCH_BASE_VERSION_ID)).isNull(); + assertThat(instance.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(1L); + }); } @Test void callerSuppliedRepinMustTargetTheRowLockedCurrentPatch() { - assertThatThrownBy( - () -> - repository.applyScriptPin( - 1L, - 7L, - "REPIN", - "patch-2", - "request-invalid-repin", - "operator", - "repin", - "EXPECT_EPOCH", - 1L, - 100L)) + assertThatThrownBy(() -> + repository.applyScriptPin( + 1L, + 7L, + "REPIN", + "patch-2", + "request-invalid-repin", + "operator", + "repin", + "EXPECT_EPOCH", + 1L, + 100L)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("REPIN requires target_script_patch_version to equal the current script patch"); assertThat(dsl.fetchCount(SCRIPT_PIN_OPERATION)).isZero(); @@ -635,11 +626,10 @@ void callerSuppliedRepinMustTargetTheRowLockedCurrentPatch() { .from(GAME_INSTANCES) .where(GAME_INSTANCES.ID.eq(7L)) .fetchOne()) - .satisfies( - record -> { - assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-1"); - assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(1L); - }); + .satisfies(record -> { + assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-1"); + assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(1L); + }); } @Test @@ -794,23 +784,21 @@ void unconditionalPinOverridesMismatchedCurrentEpochAndPersistsOperationKind() { .from(GAME_INSTANCES) .where(GAME_INSTANCES.ID.eq(7L)) .fetchOne()) - .satisfies( - record -> { - assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)) - .isEqualTo("patch-unconditional"); - assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(2L); - }); + .satisfies(record -> { + assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)) + .isEqualTo("patch-unconditional"); + assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(2L); + }); assertThat( dsl.select(SCRIPT_PIN_OPERATION.OPERATION_KIND, SCRIPT_PIN_OPERATION.EXPECTED_PIN_KIND) .from(SCRIPT_PIN_OPERATION) .where(SCRIPT_PIN_OPERATION.CONTROL_PLANE_REQUEST_ID.eq("request-unconditional")) .fetchOne()) - .satisfies( - operation -> { - assertThat(operation.get(SCRIPT_PIN_OPERATION.OPERATION_KIND)).isEqualTo("SET"); - assertThat(operation.get(SCRIPT_PIN_OPERATION.EXPECTED_PIN_KIND)) - .isEqualTo("UNCONDITIONAL"); - }); + .satisfies(operation -> { + assertThat(operation.get(SCRIPT_PIN_OPERATION.OPERATION_KIND)).isEqualTo("SET"); + assertThat(operation.get(SCRIPT_PIN_OPERATION.EXPECTED_PIN_KIND)) + .isEqualTo("UNCONDITIONAL"); + }); } @Test @@ -874,41 +862,38 @@ void expectedUnpinnedRejectsACurrentlyPinnedInstanceWithoutMutation() { .from(GAME_INSTANCES) .where(GAME_INSTANCES.ID.eq(7L)) .fetchOne()) - .satisfies( - record -> { - assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-1"); - assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(1L); - }); + .satisfies(record -> { + assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-1"); + assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(1L); + }); assertThat(dsl.fetchCount(SCRIPT_PIN_OPERATION)).isEqualTo(1); } @Test void nullExpectedPinKindFailsClosedWithoutMutatingTheInstance() { org.assertj.core.api.Assertions.assertThatIllegalArgumentException() - .isThrownBy( - () -> - repository.applyScriptPin( - 1L, - 7L, - "SET", - "patch-new", - "request-null-kind", - "operator", - "test", - null, - null, - 100L)) + .isThrownBy(() -> + repository.applyScriptPin( + 1L, + 7L, + "SET", + "patch-new", + "request-null-kind", + "operator", + "test", + null, + null, + 100L)) .withMessage("expected_pin_kind is required"); assertThat( dsl.select(GAME_INSTANCES.SCRIPT_PATCH_VERSION, GAME_INSTANCES.SCRIPT_PIN_EPOCH) .from(GAME_INSTANCES) .where(GAME_INSTANCES.ID.eq(7L)) .fetchOne()) - .satisfies( - record -> { - assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-1"); - assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(1L); - }); + .satisfies(record -> { + assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-1"); + assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(1L); + }); assertThat(dsl.fetchCount(SCRIPT_PIN_OPERATION)).isZero(); } @@ -916,19 +901,18 @@ record -> { void nullOrBlankTargetScriptPatchVersionFailsBeforePersistence() { for (String targetScriptPatchVersion : java.util.Arrays.asList(null, " ")) { org.assertj.core.api.Assertions.assertThatIllegalArgumentException() - .isThrownBy( - () -> - repository.applyScriptPin( - 1L, - 7L, - "SET", - targetScriptPatchVersion, - "request-invalid-target", - "operator", - "pin", - "EXPECT_EPOCH", - 1L, - 100L)) + .isThrownBy(() -> + repository.applyScriptPin( + 1L, + 7L, + "SET", + targetScriptPatchVersion, + "request-invalid-target", + "operator", + "pin", + "EXPECT_EPOCH", + 1L, + 100L)) .withMessage("target_script_patch_version is required"); } assertThat(dsl.fetchCount(SCRIPT_PIN_OPERATION)).isZero(); @@ -937,30 +921,28 @@ void nullOrBlankTargetScriptPatchVersionFailsBeforePersistence() { .from(GAME_INSTANCES) .where(GAME_INSTANCES.ID.eq(7L)) .fetchOne()) - .satisfies( - record -> { - assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-1"); - assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(1L); - }); + .satisfies(record -> { + assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-1"); + assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(1L); + }); } @Test void recordScriptPinFailureRejectsNullOrBlankTargetBeforePersistence() { for (String targetScriptPatchVersion : java.util.Arrays.asList(null, " ")) { org.assertj.core.api.Assertions.assertThatIllegalArgumentException() - .isThrownBy( - () -> - repository.recordScriptPinFailure( - 1L, - 7L, - "SET", - targetScriptPatchVersion, - "request-invalid-failure-target", - "operator", - "authority unavailable", - "EXPECT_EPOCH", - 1L, - "SCRIPT_PATCH_AUTHORITY_UNAVAILABLE")) + .isThrownBy(() -> + repository.recordScriptPinFailure( + 1L, + 7L, + "SET", + targetScriptPatchVersion, + "request-invalid-failure-target", + "operator", + "authority unavailable", + "EXPECT_EPOCH", + 1L, + "SCRIPT_PATCH_AUTHORITY_UNAVAILABLE")) .withMessage("target_script_patch_version is required"); } assertThat(dsl.fetchCount(SCRIPT_PIN_OPERATION)).isZero(); @@ -969,49 +951,46 @@ void recordScriptPinFailureRejectsNullOrBlankTargetBeforePersistence() { @Test void expectedPinEpochShapeFailsBeforePersistence() { org.assertj.core.api.Assertions.assertThatIllegalArgumentException() - .isThrownBy( - () -> - repository.applyScriptPin( - 1L, - 7L, - "SET", - "patch-new", - "request-invalid-unpinned-epoch", - "operator", - "pin", - "EXPECT_UNPINNED", - 1L, - 100L)) + .isThrownBy(() -> + repository.applyScriptPin( + 1L, + 7L, + "SET", + "patch-new", + "request-invalid-unpinned-epoch", + "operator", + "pin", + "EXPECT_UNPINNED", + 1L, + 100L)) .withMessage("expected_script_pin_epoch must be null for EXPECT_UNPINNED"); org.assertj.core.api.Assertions.assertThatIllegalArgumentException() - .isThrownBy( - () -> - repository.applyScriptPin( - 1L, - 7L, - "SET", - "patch-new", - "request-invalid-epoch", - "operator", - "pin", - "EXPECT_EPOCH", - 0L, - 100L)) + .isThrownBy(() -> + repository.applyScriptPin( + 1L, + 7L, + "SET", + "patch-new", + "request-invalid-epoch", + "operator", + "pin", + "EXPECT_EPOCH", + 0L, + 100L)) .withMessage("expected_script_pin_epoch must be positive for EXPECT_EPOCH"); org.assertj.core.api.Assertions.assertThatIllegalArgumentException() - .isThrownBy( - () -> - repository.applyScriptPin( - 1L, - 7L, - "SET", - "patch-new", - "request-invalid-unconditional-epoch", - "operator", - "pin", - "UNCONDITIONAL", - 1L, - 100L)) + .isThrownBy(() -> + repository.applyScriptPin( + 1L, + 7L, + "SET", + "patch-new", + "request-invalid-unconditional-epoch", + "operator", + "pin", + "UNCONDITIONAL", + 1L, + 100L)) .withMessage("expected_script_pin_epoch must be null for UNCONDITIONAL"); assertThat(dsl.fetchCount(SCRIPT_PIN_OPERATION)).isZero(); } @@ -1020,34 +999,32 @@ void expectedPinEpochShapeFailsBeforePersistence() { void controlPlaneRequestIdMustBeNonBlankBeforePersistence() { for (String controlPlaneRequestId : java.util.Arrays.asList(null, " ")) { org.assertj.core.api.Assertions.assertThatIllegalArgumentException() - .isThrownBy( - () -> - repository.applyScriptPin( - 1L, - 7L, - "SET", - "patch-new", - controlPlaneRequestId, - "operator", - "pin", - "EXPECT_EPOCH", - 1L, - 100L)) + .isThrownBy(() -> + repository.applyScriptPin( + 1L, + 7L, + "SET", + "patch-new", + controlPlaneRequestId, + "operator", + "pin", + "EXPECT_EPOCH", + 1L, + 100L)) .withMessage("control_plane_request_id is required"); org.assertj.core.api.Assertions.assertThatIllegalArgumentException() - .isThrownBy( - () -> - repository.recordScriptPinFailure( - 1L, - 7L, - "SET", - "patch-new", - controlPlaneRequestId, - "operator", - "authority unavailable", - "EXPECT_EPOCH", - 1L, - "SCRIPT_PATCH_AUTHORITY_UNAVAILABLE")) + .isThrownBy(() -> + repository.recordScriptPinFailure( + 1L, + 7L, + "SET", + "patch-new", + controlPlaneRequestId, + "operator", + "authority unavailable", + "EXPECT_EPOCH", + 1L, + "SCRIPT_PATCH_AUTHORITY_UNAVAILABLE")) .withMessage("control_plane_request_id is required"); } assertThat(dsl.fetchCount(SCRIPT_PIN_OPERATION)).isZero(); @@ -1056,19 +1033,18 @@ void controlPlaneRequestIdMustBeNonBlankBeforePersistence() { @Test void unsupportedExpectedPinKindFailsBeforePersistence() { org.assertj.core.api.Assertions.assertThatIllegalArgumentException() - .isThrownBy( - () -> - repository.applyScriptPin( - 1L, - 7L, - "SET", - "patch-new", - "request-unsupported-kind", - "operator", - "pin", - "UNKNOWN", - null, - 100L)) + .isThrownBy(() -> + repository.applyScriptPin( + 1L, + 7L, + "SET", + "patch-new", + "request-unsupported-kind", + "operator", + "pin", + "UNKNOWN", + null, + 100L)) .withMessage("expected_pin_kind is not supported"); assertThat(dsl.fetchCount(SCRIPT_PIN_OPERATION)).isZero(); } @@ -1133,29 +1109,27 @@ void recordScriptPinFailurePersistsAndReplaysByExactDigest() { .from(SCRIPT_PIN_OPERATION) .where(SCRIPT_PIN_OPERATION.CONTROL_PLANE_REQUEST_ID.eq("request-failure")) .fetchOne()) - .satisfies( - record -> { - assertThat(record.get(SCRIPT_PIN_OPERATION.OUTCOME)).isEqualTo("FAILED"); - assertThat(record.get(SCRIPT_PIN_OPERATION.ERROR_CODE)) - .isEqualTo("SCRIPT_PATCH_AUTHORITY_UNAVAILABLE"); - assertThat(record.get(SCRIPT_PIN_OPERATION.MUTATION_DIGEST)).isNotBlank(); - assertThat(record.get(SCRIPT_PIN_OPERATION.PREVIOUS_SCRIPT_PATCH_VERSION)) - .isEqualTo("patch-1"); - assertThat(record.get(SCRIPT_PIN_OPERATION.PREVIOUS_SCRIPT_PIN_EPOCH)).isEqualTo(1L); - assertThat(record.get(SCRIPT_PIN_OPERATION.RESULTING_SCRIPT_PATCH_VERSION)) - .isEqualTo("patch-1"); - assertThat(record.get(SCRIPT_PIN_OPERATION.RESULTING_SCRIPT_PIN_EPOCH)).isEqualTo(1L); - }); + .satisfies(record -> { + assertThat(record.get(SCRIPT_PIN_OPERATION.OUTCOME)).isEqualTo("FAILED"); + assertThat(record.get(SCRIPT_PIN_OPERATION.ERROR_CODE)) + .isEqualTo("SCRIPT_PATCH_AUTHORITY_UNAVAILABLE"); + assertThat(record.get(SCRIPT_PIN_OPERATION.MUTATION_DIGEST)).isNotBlank(); + assertThat(record.get(SCRIPT_PIN_OPERATION.PREVIOUS_SCRIPT_PATCH_VERSION)) + .isEqualTo("patch-1"); + assertThat(record.get(SCRIPT_PIN_OPERATION.PREVIOUS_SCRIPT_PIN_EPOCH)).isEqualTo(1L); + assertThat(record.get(SCRIPT_PIN_OPERATION.RESULTING_SCRIPT_PATCH_VERSION)) + .isEqualTo("patch-1"); + assertThat(record.get(SCRIPT_PIN_OPERATION.RESULTING_SCRIPT_PIN_EPOCH)).isEqualTo(1L); + }); assertThat( dsl.select(GAME_INSTANCES.SCRIPT_PATCH_VERSION, GAME_INSTANCES.SCRIPT_PIN_EPOCH) .from(GAME_INSTANCES) .where(GAME_INSTANCES.ID.eq(7L)) .fetchOne()) - .satisfies( - record -> { - assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-1"); - assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(1L); - }); + .satisfies(record -> { + assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-1"); + assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(1L); + }); } @Test @@ -1180,11 +1154,10 @@ void concurrentExactRetriesReplayOneCommittedResult() throws Exception { .from(GAME_INSTANCES) .where(GAME_INSTANCES.ID.eq(7L)) .fetchOne()) - .satisfies( - record -> { - assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-same"); - assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(2L); - }); + .satisfies(record -> { + assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-same"); + assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(2L); + }); } } @@ -1204,11 +1177,10 @@ void requestIdReuseWithDifferentDigestDoesNotMutate() { .from(GAME_INSTANCES) .where(GAME_INSTANCES.ID.eq(7L)) .fetchOne()) - .satisfies( - record -> { - assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-a"); - assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(2L); - }); + .satisfies(record -> { + assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-a"); + assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(2L); + }); } @Test @@ -1306,13 +1278,12 @@ void newMutationAtEpochExhaustionRecordsFailureAndReplaysWithoutStateChange() { .from(GAME_INSTANCES) .where(GAME_INSTANCES.ID.eq(7L)) .fetchOne()) - .satisfies( - record -> { - assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-1"); - assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(Long.MAX_VALUE); - assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_PINNED_CONTROL_PLANE_REQUEST_ID)) - .isEqualTo("initial"); - }); + .satisfies(record -> { + assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-1"); + assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(Long.MAX_VALUE); + assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_PINNED_CONTROL_PLANE_REQUEST_ID)) + .isEqualTo("initial"); + }); } @Test @@ -1343,11 +1314,10 @@ void epochExhaustionDoesNotMaskExpectationMismatch() { .from(GAME_INSTANCES) .where(GAME_INSTANCES.ID.eq(7L)) .fetchOne()) - .satisfies( - record -> { - assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-1"); - assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(Long.MAX_VALUE); - }); + .satisfies(record -> { + assertThat(record.get(GAME_INSTANCES.SCRIPT_PATCH_VERSION)).isEqualTo("patch-1"); + assertThat(record.get(GAME_INSTANCES.SCRIPT_PIN_EPOCH)).isEqualTo(Long.MAX_VALUE); + }); } private void assertConstraintRejected(String constraintName, Object... values) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java index 3ee0e23f3b..f5fc3b347e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java @@ -151,16 +151,15 @@ static void awaitPostgresJdbcReady() { + "canonical_tenant_id, playable_state_namespace_id FROM gameplay_admission_pointer " + "WHERE tenant_id = ?", RETAINED_TENANT_ID)) - .satisfies( - row -> { - assertThat(row.get("representation_version", Integer.class)).isEqualTo(1); - assertThat(row.get("tenant_id", Long.class)).isEqualTo(RETAINED_TENANT_ID); - assertThat(row.get("game_instance_id", Long.class)).isEqualTo(501L); - assertThat(row.get("realm_id", UUID.class)).isEqualTo(RETAINED_REALM_ID); - assertThat(row.get("canonical_tenant_id", UUID.class)).isNull(); - assertThat(row.get("playable_state_namespace_id", UUID.class)) - .isEqualTo(RETAINED_PLAYABLE_NAMESPACE_ID); - }); + .satisfies(row -> { + assertThat(row.get("representation_version", Integer.class)).isEqualTo(1); + assertThat(row.get("tenant_id", Long.class)).isEqualTo(RETAINED_TENANT_ID); + assertThat(row.get("game_instance_id", Long.class)).isEqualTo(501L); + assertThat(row.get("realm_id", UUID.class)).isEqualTo(RETAINED_REALM_ID); + assertThat(row.get("canonical_tenant_id", UUID.class)).isNull(); + assertThat(row.get("playable_state_namespace_id", UUID.class)) + .isEqualTo(RETAINED_PLAYABLE_NAMESPACE_ID); + }); assertThat( requiredRecord( fixture.dsl, @@ -187,14 +186,11 @@ void ownerRollbackLeavesNoPartialPreparationAndImmutableRowsRejectMutation() { AuthoredWorldLaunchDescriptorEvidence descriptor = syntheticDescriptor(request, catalog, source); - assertThatThrownBy( - () -> - fixture.transactions.execute( - status -> { - fixture.preparationRepository.persistPrepared( - request, catalog, source, descriptor); - throw new IllegalStateException("forced owner rollback"); - })) + assertThatThrownBy(() -> + fixture.transactions.execute(status -> { + fixture.preparationRepository.persistPrepared(request, catalog, source, descriptor); + throw new IllegalStateException("forced owner rollback"); + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("forced owner rollback"); assertThat( @@ -208,21 +204,19 @@ void ownerRollbackLeavesNoPartialPreparationAndImmutableRowsRejectMutation() { fixture.preparationRepository.readByControlPlaneRequestId( NAMESPACE, request.controlPlaneRequestId())) .contains(committed); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "UPDATE game_session_canonical_launch_preparation " - + "SET receipt_digest = ? WHERE target_namespace = ?", - digest("f"), - NAMESPACE)) + assertThatThrownBy(() -> + fixture.dsl.execute( + "UPDATE game_session_canonical_launch_preparation " + + "SET receipt_digest = ? WHERE target_namespace = ?", + digest("f"), + NAMESPACE)) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("Canonical launch preparation evidence is immutable"); - assertThatThrownBy( - () -> - fixture.dsl.execute( - "DELETE FROM game_session_canonical_launch_preparation " - + "WHERE target_namespace = ?", - NAMESPACE)) + assertThatThrownBy(() -> + fixture.dsl.execute( + "DELETE FROM game_session_canonical_launch_preparation " + + "WHERE target_namespace = ?", + NAMESPACE)) .isInstanceOf(DataAccessException.class) .hasStackTraceContaining("Canonical launch preparation evidence is immutable"); assertThatThrownBy( @@ -236,28 +230,26 @@ void ownerRollbackLeavesNoPartialPreparationAndImmutableRowsRejectMutation() { // Simulate privileged storage corruption in this isolated test schema; normal update/delete // paths remain blocked by the immutable trigger above. - fixture.transactions.execute( - status -> { - fixture.dsl.execute( - "ALTER TABLE game_session_canonical_launch_preparation DISABLE TRIGGER " - + "game_session_canonical_launch_preparation_immutable"); - fixture.dsl.execute( - "UPDATE game_session_canonical_launch_preparation " - + "SET catalog_evidence_json = jsonb_set(catalog_evidence_json, " - + "'{realmDisplayName}', to_jsonb(CAST(? AS text))) " - + "WHERE target_namespace = ? AND control_plane_request_id = ?", - "Tampered Realm Display Name", - NAMESPACE, - request.controlPlaneRequestId()); - fixture.dsl.execute( - "ALTER TABLE game_session_canonical_launch_preparation ENABLE TRIGGER " - + "game_session_canonical_launch_preparation_immutable"); - return null; - }); - assertThatThrownBy( - () -> - fixture.preparationRepository.readByControlPlaneRequestId( - NAMESPACE, request.controlPlaneRequestId())) + fixture.transactions.execute(status -> { + fixture.dsl.execute( + "ALTER TABLE game_session_canonical_launch_preparation DISABLE TRIGGER " + + "game_session_canonical_launch_preparation_immutable"); + fixture.dsl.execute( + "UPDATE game_session_canonical_launch_preparation " + + "SET catalog_evidence_json = jsonb_set(catalog_evidence_json, " + + "'{realmDisplayName}', to_jsonb(CAST(? AS text))) " + + "WHERE target_namespace = ? AND control_plane_request_id = ?", + "Tampered Realm Display Name", + NAMESPACE, + request.controlPlaneRequestId()); + fixture.dsl.execute( + "ALTER TABLE game_session_canonical_launch_preparation ENABLE TRIGGER " + + "game_session_canonical_launch_preparation_immutable"); + return null; + }); + assertThatThrownBy(() -> + fixture.preparationRepository.readByControlPlaneRequestId( + NAMESPACE, request.controlPlaneRequestId())) .isInstanceOf( GameSessionCanonicalLaunchPreparationRepository .InvalidLaunchPreparationEvidenceException.class) @@ -313,12 +305,11 @@ void authorizedLaunchPreparationBindsTheRetainedAccountOwnerTupleAndRejectsSubst authorized.fixture(), authorized.ownerTuple(), substituted); AuthoredWorldLaunchDescriptorClient descriptorClient = syntheticGameDesignClient(); - assertThatThrownBy( - () -> - authorized - .fixture() - .service(descriptorClient) - .prepareAuthorized(authorized.claim(), authorized.request())) + assertThatThrownBy(() -> + authorized + .fixture() + .service(descriptorClient) + .prepareAuthorized(authorized.claim(), authorized.request())) .isInstanceOf( GameSessionCanonicalLaunchPreparationRepository .InvalidLaunchPreparationEvidenceException.class) @@ -362,20 +353,18 @@ void authorizedLaunchPreparationBindsTheRetainedAccountOwnerTupleAndRejectsSubst private static AuthoredWorldLaunchDescriptorClient syntheticGameDesignClient() { AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); when(client.resolve(any(AuthoredWorldLaunchDescriptorEvidence.Request.class))) - .thenAnswer( - invocation -> { - AuthoredWorldLaunchDescriptorEvidence.Request request = invocation.getArgument(0); - return syntheticDescriptor(request); - }); + .thenAnswer(invocation -> { + AuthoredWorldLaunchDescriptorEvidence.Request request = invocation.getArgument(0); + return syntheticDescriptor(request); + }); when(client.get(any(GetRequest.class))) - .thenAnswer( - invocation -> { - GetRequest request = invocation.getArgument(0); - AuthoredWorldLaunchDescriptorEvidence descriptor = - syntheticDescriptor(request.expectedRequest()); - assertThat(request.expectedResultDigest()).isEqualTo(descriptor.resultDigest()); - return descriptor; - }); + .thenAnswer(invocation -> { + GetRequest request = invocation.getArgument(0); + AuthoredWorldLaunchDescriptorEvidence descriptor = + syntheticDescriptor(request.expectedRequest()); + assertThat(request.expectedResultDigest()).isEqualTo(descriptor.resultDigest()); + return descriptor; + }); return client; } @@ -383,30 +372,27 @@ private static AuthoredWorldLaunchDescriptorClient concurrentSyntheticGameDesign CountDownLatch bothResolved) { AuthoredWorldLaunchDescriptorClient client = mock(AuthoredWorldLaunchDescriptorClient.class); when(client.resolve(any(AuthoredWorldLaunchDescriptorEvidence.Request.class))) - .thenAnswer( - invocation -> { - AuthoredWorldLaunchDescriptorEvidence.Request request = invocation.getArgument(0); - bothResolved.countDown(); - try { - if (!bothResolved.await(15, TimeUnit.SECONDS)) { - throw new IllegalStateException("Concurrent exact attempts did not both resolve"); - } - } catch (InterruptedException exception) { - Thread.currentThread().interrupt(); - throw new IllegalStateException( - "Concurrent exact attempt was interrupted", exception); - } - return syntheticDescriptor(request); - }); + .thenAnswer(invocation -> { + AuthoredWorldLaunchDescriptorEvidence.Request request = invocation.getArgument(0); + bothResolved.countDown(); + try { + if (!bothResolved.await(15, TimeUnit.SECONDS)) { + throw new IllegalStateException("Concurrent exact attempts did not both resolve"); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Concurrent exact attempt was interrupted", exception); + } + return syntheticDescriptor(request); + }); when(client.get(any(GetRequest.class))) - .thenAnswer( - invocation -> { - GetRequest request = invocation.getArgument(0); - AuthoredWorldLaunchDescriptorEvidence descriptor = - syntheticDescriptor(request.expectedRequest()); - assertThat(request.expectedResultDigest()).isEqualTo(descriptor.resultDigest()); - return descriptor; - }); + .thenAnswer(invocation -> { + GetRequest request = invocation.getArgument(0); + AuthoredWorldLaunchDescriptorEvidence descriptor = + syntheticDescriptor(request.expectedRequest()); + assertThat(request.expectedResultDigest()).isEqualTo(descriptor.resultDigest()); + return descriptor; + }); return client; } @@ -864,33 +850,31 @@ private static CanonicalRealmCatalogSnapshot seedHistoricalCatalog( columns.put("source_game_tenant_key", source.sourceGameTenantKey()); columns.put("source_provenance_kind", source.provenanceKind()); columns.put("source_evidence_digest", source.evidenceDigest()); - transactions.executeWithoutResult( - status -> { - java.util.Map namespaceColumns = new java.util.LinkedHashMap<>(); - namespaceColumns.put("target_namespace", NAMESPACE); - namespaceColumns.put("canonical_tenant_id", source.canonicalTenantId()); - namespaceColumns.put("playable_state_namespace_id", namespace); - columns.forEach( - (name, value) -> { - if (name.startsWith("source_") && !name.equals("source_world_display_name")) { - namespaceColumns.put(name, value); - } - }); - dsl.execute( - "INSERT INTO gameplay_tenant_shared_playable_state_namespace (" - + String.join(",", namespaceColumns.keySet()) - + ") VALUES (" - + String.join(",", java.util.Collections.nCopies(namespaceColumns.size(), "?")) - + ")", - namespaceColumns.values().toArray()); - dsl.execute( - "INSERT INTO game_session_canonical_realm_catalog (" - + String.join(",", columns.keySet()) - + ") VALUES (" - + String.join(",", java.util.Collections.nCopies(columns.size(), "?")) - + ")", - columns.values().toArray()); - }); + transactions.executeWithoutResult(status -> { + java.util.Map namespaceColumns = new java.util.LinkedHashMap<>(); + namespaceColumns.put("target_namespace", NAMESPACE); + namespaceColumns.put("canonical_tenant_id", source.canonicalTenantId()); + namespaceColumns.put("playable_state_namespace_id", namespace); + columns.forEach((name, value) -> { + if (name.startsWith("source_") && !name.equals("source_world_display_name")) { + namespaceColumns.put(name, value); + } + }); + dsl.execute( + "INSERT INTO gameplay_tenant_shared_playable_state_namespace (" + + String.join(",", namespaceColumns.keySet()) + + ") VALUES (" + + String.join(",", java.util.Collections.nCopies(namespaceColumns.size(), "?")) + + ")", + namespaceColumns.values().toArray()); + dsl.execute( + "INSERT INTO game_session_canonical_realm_catalog (" + + String.join(",", columns.keySet()) + + ") VALUES (" + + String.join(",", java.util.Collections.nCopies(columns.size(), "?")) + + ")", + columns.values().toArray()); + }); return new CanonicalRealmCatalogSnapshot( NAMESPACE, source.canonicalTenantId(), @@ -1045,15 +1029,13 @@ CanonicalRealmCatalogSnapshot createCatalog(IntakeReceipt source) { "PRESEEDED_ONLY", null, null); - transactions.execute( - status -> - new GameSessionFreshTenantAssociationRepository(dsl) - .associateFresh( - uuid(980), - NAMESPACE, - source, - CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( - source.source()))); + transactions.execute(status -> + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + uuid(980), + NAMESPACE, + source, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(source.source()))); var policy = CanonicalHumanPublicationOwnerTestFixtures.publishedSet( request, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java index d00fab47e8..5e35efa07d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorIntegrationTest.java @@ -88,19 +88,17 @@ void postgresClaimIsCommittedBeforeAccountAndExactRetryDoesNotRedeemAgain() thro StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); AtomicInteger accountCalls = new AtomicInteger(); when(redemptionClient.redeem(any(), eq(OPAQUE_REFERENCE), any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(fixture.attemptCount()) - .as("the claim must be visible from an independent PostgreSQL connection") - .isEqualTo(1); - accountCalls.incrementAndGet(); - StartSessionPostAuthorizationExecutionTuple deliveredTuple = - invocation.getArgument(0); - AttemptClaim claim = invocation.getArgument(2); - return new StartSessionOperatorRedemptionClient.RedemptionResult( - claim, projection(deliveredTuple), false); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(fixture.attemptCount()) + .as("the claim must be visible from an independent PostgreSQL connection") + .isEqualTo(1); + accountCalls.incrementAndGet(); + StartSessionPostAuthorizationExecutionTuple deliveredTuple = invocation.getArgument(0); + AttemptClaim claim = invocation.getArgument(2); + return new StartSessionOperatorRedemptionClient.RedemptionResult( + claim, projection(deliveredTuple), false); + }); GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = coordinator(fixture, redemptionClient); @@ -134,13 +132,12 @@ void ambiguousAccountTransportStaysPendingAndExactRetryDoesNotCallAccountAgain() StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); AtomicInteger accountCalls = new AtomicInteger(); when(redemptionClient.redeem(any(), eq(OPAQUE_REFERENCE), any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(fixture.attemptCount()).isEqualTo(1); - accountCalls.incrementAndGet(); - throw new StatusRuntimeException(Status.DEADLINE_EXCEEDED); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(fixture.attemptCount()).isEqualTo(1); + accountCalls.incrementAndGet(); + throw new StatusRuntimeException(Status.DEADLINE_EXCEEDED); + }); GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = coordinator(fixture, redemptionClient); @@ -173,18 +170,16 @@ void expiredRealPostgresClaimCannotPersistTheReturnedAccountProjection() throws StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); AtomicInteger accountCalls = new AtomicInteger(); when(redemptionClient.redeem(any(), eq(OPAQUE_REFERENCE), any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(fixture.attemptCount()).isEqualTo(1); - accountCalls.incrementAndGet(); - StartSessionPostAuthorizationExecutionTuple deliveredTuple = - invocation.getArgument(0); - AttemptClaim claim = invocation.getArgument(2); - fixture.awaitClaimLeaseExpired(claim); - return new StartSessionOperatorRedemptionClient.RedemptionResult( - claim, projection(deliveredTuple), false); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(fixture.attemptCount()).isEqualTo(1); + accountCalls.incrementAndGet(); + StartSessionPostAuthorizationExecutionTuple deliveredTuple = invocation.getArgument(0); + AttemptClaim claim = invocation.getArgument(2); + fixture.awaitClaimLeaseExpired(claim); + return new StartSessionOperatorRedemptionClient.RedemptionResult( + claim, projection(deliveredTuple), false); + }); GameSessionStartSessionOperatorAuthorizationCoordinator coordinator = coordinator(fixture, redemptionClient); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java index 7fb1eca394..6824437a96 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java @@ -70,17 +70,12 @@ void competingWritersWithSamePositiveVersionPairCommitOnePointerAndAudit() throw GameplayAdmissionPointerSnapshot initial = fixture .transactionTemplate() - .execute( - status -> - fixture - .service() - .upsertPointer( - mutation( - "Initial World", - INITIAL_GAME_INSTANCE_ID, - 0L, - 0L, - "initial-pointer"))); + .execute(status -> + fixture + .service() + .upsertPointer( + mutation( + "Initial World", INITIAL_GAME_INSTANCE_ID, 0L, 0L, "initial-pointer"))); assertThat(initial).isNotNull(); assertThat(initial.pointerVersion()).isEqualTo(1L); assertThat(initial.catalogRevision()).isEqualTo(1L); @@ -100,81 +95,76 @@ void competingWritersWithSamePositiveVersionPairCommitOnePointerAndAudit() throw return thread; }); Future first = - executor.submit( - () -> { - try { - GameplayAdmissionPointerSnapshot snapshot = - fixture - .transactionTemplate() - .execute( - status -> { - fixture.dsl().execute("SET LOCAL statement_timeout = '30000ms'"); - var backendPidRecord = - Objects.requireNonNull( - fixture.dsl().fetchOne("select pg_backend_pid()"), - "Winning backend PID query returned no row"); - winningBackendPid.set( - Objects.requireNonNull( - backendPidRecord.get(0, Integer.class), - "Winning backend PID query returned no value")); - GameplayAdmissionPointerSnapshot updated = - fixture - .service() - .upsertPointer( - mutation( - "Concurrent World A", - INITIAL_GAME_INSTANCE_ID, - 1L, - 1L, - "writer-a")); - winningTransactionReady.countDown(); - awaitLatch( - releaseWinningTransaction, - "release of winning pointer transaction"); - return updated; - }); - return new MutationAttempt(snapshot, null); - } catch (Throwable failure) { - return new MutationAttempt(null, failure); - } - }); + executor.submit(() -> { + try { + GameplayAdmissionPointerSnapshot snapshot = + fixture + .transactionTemplate() + .execute(status -> { + fixture.dsl().execute("SET LOCAL statement_timeout = '30000ms'"); + var backendPidRecord = + Objects.requireNonNull( + fixture.dsl().fetchOne("select pg_backend_pid()"), + "Winning backend PID query returned no row"); + winningBackendPid.set( + Objects.requireNonNull( + backendPidRecord.get(0, Integer.class), + "Winning backend PID query returned no value")); + GameplayAdmissionPointerSnapshot updated = + fixture + .service() + .upsertPointer( + mutation( + "Concurrent World A", + INITIAL_GAME_INSTANCE_ID, + 1L, + 1L, + "writer-a")); + winningTransactionReady.countDown(); + awaitLatch( + releaseWinningTransaction, "release of winning pointer transaction"); + return updated; + }); + return new MutationAttempt(snapshot, null); + } catch (Throwable failure) { + return new MutationAttempt(null, failure); + } + }); Future second = - executor.submit( - () -> { - try { - GameplayAdmissionPointerSnapshot snapshot = - fixture - .transactionTemplate() - .execute( - status -> { - fixture.dsl().execute("SET LOCAL statement_timeout = '30000ms'"); - var backendPidRecord = - Objects.requireNonNull( - fixture.dsl().fetchOne("select pg_backend_pid()"), - "Competing backend PID query returned no row"); - competingBackendPid.set( - Objects.requireNonNull( - backendPidRecord.get(0, Integer.class), - "Competing backend PID query returned no value")); - competingTransactionReady.countDown(); - awaitLatch( - winningTransactionReady, - "winning pointer transaction to acquire and hold its row lock"); - return fixture - .service() - .upsertPointer( - mutation( - "Concurrent World B", - INITIAL_GAME_INSTANCE_ID, - 1L, - 1L, - "writer-b")); - }); - return new MutationAttempt(snapshot, null); - } catch (Throwable failure) { - return new MutationAttempt(null, failure); - } - }); + executor.submit(() -> { + try { + GameplayAdmissionPointerSnapshot snapshot = + fixture + .transactionTemplate() + .execute(status -> { + fixture.dsl().execute("SET LOCAL statement_timeout = '30000ms'"); + var backendPidRecord = + Objects.requireNonNull( + fixture.dsl().fetchOne("select pg_backend_pid()"), + "Competing backend PID query returned no row"); + competingBackendPid.set( + Objects.requireNonNull( + backendPidRecord.get(0, Integer.class), + "Competing backend PID query returned no value")); + competingTransactionReady.countDown(); + awaitLatch( + winningTransactionReady, + "winning pointer transaction to acquire and hold its row lock"); + return fixture + .service() + .upsertPointer( + mutation( + "Concurrent World B", + INITIAL_GAME_INSTANCE_ID, + 1L, + 1L, + "writer-b")); + }); + return new MutationAttempt(snapshot, null); + } catch (Throwable failure) { + return new MutationAttempt(null, failure); + } + }); try { assertThat(winningTransactionReady.await(10, TimeUnit.SECONDS)).isTrue(); @@ -220,17 +210,12 @@ void auditInsertFailureRollsBackPointerRevisionAndRuntimeTarget() { GameplayAdmissionPointerSnapshot initial = fixture .transactionTemplate() - .execute( - status -> - fixture - .service() - .upsertPointer( - mutation( - "Initial World", - INITIAL_GAME_INSTANCE_ID, - 0L, - 0L, - "initial-pointer"))); + .execute(status -> + fixture + .service() + .upsertPointer( + mutation( + "Initial World", INITIAL_GAME_INSTANCE_ID, 0L, 0L, "initial-pointer"))); assertThat(initial).isNotNull(); List initialAudit = fixture.service().listPointerAudit(TENANT_ID, WORLD_SLUG, REALM_SLUG); @@ -249,21 +234,19 @@ void auditInsertFailureRollsBackPointerRevisionAndRuntimeTarget() { + "gameplay_admission_pointer_event FOR EACH ROW EXECUTE FUNCTION " + "reject_gameplay_admission_audit()"); - assertThatThrownBy( - () -> - fixture - .transactionTemplate() - .execute( - status -> - fixture - .service() - .upsertPointer( - mutation( - "Initial World", - INITIAL_GAME_INSTANCE_ID + 1L, - initial.pointerVersion(), - initial.catalogRevision(), - "failed-audit")))) + assertThatThrownBy(() -> + fixture + .transactionTemplate() + .execute(status -> + fixture + .service() + .upsertPointer( + mutation( + "Initial World", + INITIAL_GAME_INSTANCE_ID + 1L, + initial.pointerVersion(), + initial.catalogRevision(), + "failed-audit")))) .isInstanceOf(RuntimeException.class) .hasMessageContaining("forced admission audit insert failure"); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java index c2c545109b..683f4ab1c2 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java @@ -61,12 +61,11 @@ void initialAdmissionLedgerCommitsPointerAuditAndAttemptTogetherAndReadbackFails gameInstanceRepository); InitialAdmissionBindCatalogSnapshot catalog = - transactionTemplate.execute( - status -> - toSnapshot( - service.registerPublicSharedFixtureCatalog( - new InitialAdmissionBindCatalogDescriptor( - 41L, 810L, "smoke", "Smoke World", "production", "Live Realm", true)))); + transactionTemplate.execute(status -> + toSnapshot( + service.registerPublicSharedFixtureCatalog( + new InitialAdmissionBindCatalogDescriptor( + 41L, 810L, "smoke", "Smoke World", "production", "Live Realm", true)))); var request = new InitialAdmissionBindRequest( 41L, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java index 3db0c1bf41..02d85d4726 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java @@ -609,26 +609,24 @@ void actualJournalCleanupRetiresOnlyInsideExactCurrentExclusionAndOldReceiptCann Disposition.RETIRED, ProofKind.PHYSICAL_TOKEN_DENIAL); when(account.retireInitialGameplayLogin(any())) - .thenAnswer( - invocation -> { - assertThat(authority.active).isTrue(); - assertThat(authority.current).isTrue(); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(admin.get(key(original))) - .containsExactly(InitialGameplayLoginContextState.closed(original).encode()); - assertThat(provider.traces).hasSize(2); - assertThat(provider.traces.get(0)).contains("WAITAOF"); - assertThat(provider.traces.get(1)).contains("get"); - assertThat( - invocation - .getArgument( - 0, - net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest - .class) - .getCallerContextId()) - .isEqualTo(original.callerContextId().toString()); - return receipt; - }); + .thenAnswer(invocation -> { + assertThat(authority.active).isTrue(); + assertThat(authority.current).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(admin.get(key(original))) + .containsExactly(InitialGameplayLoginContextState.closed(original).encode()); + assertThat(provider.traces).hasSize(2); + assertThat(provider.traces.get(0)).contains("WAITAOF"); + assertThat(provider.traces.get(1)).contains("get"); + assertThat( + invocation + .getArgument( + 0, + net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest.class) + .getCallerContextId()) + .isEqualTo(original.callerContextId().toString()); + return receipt; + }); // This positive closure proof allows replica fsync under shared-runner load. // Insufficient-acknowledgement cases retain their separate short failure deadline. var owner = @@ -679,30 +677,29 @@ void ownerComposesDurableOriginalWithPhysicalPendingAndExactNonAdmittingInstall( } }; when(account.authenticate(any(AuthenticateRequest.class), any())) - .thenAnswer( - invocation -> { - var request = invocation.getArgument(0, AuthenticateRequest.class); - var original = coordinates(request); - requestRef.set(request); - assertThat(original).isEqualTo(reservationRef.get()); - assertThat(original.expectedAttemptFence()).isEqualTo(1L); - assertThat(original.requestId().version()).isEqualTo(4); - assertThat(original.callerContextId().version()).isEqualTo(4); - assertThat(original.requestId()).isNotEqualTo(original.callerContextId()); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(provider.traces).hasSize(2); - assertThat(provider.traces.get(0)).containsSubsequence("evalsha", "WAITAOF", "close"); - assertThat(provider.traces.get(1)).containsSubsequence("get", "close"); - assertThat(admin.get(key(original))) - .containsExactly(InitialGameplayLoginContextState.pending(original).encode()); - var committed = journal.readCommitted(original).orElseThrow(); - assertThat(committed.abandoned()).isFalse(); - assertThat(committed.verifiedWitness()).isEmpty(); - assertThat(committed.frozenRetirementRequest()).isEmpty(); - var result = validatedResult(request, UUID.randomUUID()); - resultRef.set(result); - return result; - }); + .thenAnswer(invocation -> { + var request = invocation.getArgument(0, AuthenticateRequest.class); + var original = coordinates(request); + requestRef.set(request); + assertThat(original).isEqualTo(reservationRef.get()); + assertThat(original.expectedAttemptFence()).isEqualTo(1L); + assertThat(original.requestId().version()).isEqualTo(4); + assertThat(original.callerContextId().version()).isEqualTo(4); + assertThat(original.requestId()).isNotEqualTo(original.callerContextId()); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(provider.traces).hasSize(2); + assertThat(provider.traces.get(0)).containsSubsequence("evalsha", "WAITAOF", "close"); + assertThat(provider.traces.get(1)).containsSubsequence("get", "close"); + assertThat(admin.get(key(original))) + .containsExactly(InitialGameplayLoginContextState.pending(original).encode()); + var committed = journal.readCommitted(original).orElseThrow(); + assertThat(committed.abandoned()).isFalse(); + assertThat(committed.verifiedWitness()).isEmpty(); + assertThat(committed.frozenRetirementRequest()).isEmpty(); + var result = validatedResult(request, UUID.randomUUID()); + resultRef.set(result); + return result; + }); var outcome = owner.receive(credentials); var original = outcome.coordinates(); @@ -762,52 +759,50 @@ void ownerClosesExactOriginalAndWipesResultWhenCredentialCustodyEndsAfterAccount var retirementRef = new AtomicReference(); when(account.authenticate(any(AuthenticateRequest.class), any())) - .thenAnswer( - invocation -> { - var request = invocation.getArgument(0, AuthenticateRequest.class); - var original = coordinates(request); - assertThat(provider.traces).hasSize(2); - assertThat(admin.get(key(original))) - .containsExactly(InitialGameplayLoginContextState.pending(original).encode()); - assertThat(journal.readCommitted(original).orElseThrow().verifiedWitness()).isEmpty(); - var result = validatedResult(request, UUID.randomUUID()); - resultRef.set(result); - credentials.close(); - return result; - }); + .thenAnswer(invocation -> { + var request = invocation.getArgument(0, AuthenticateRequest.class); + var original = coordinates(request); + assertThat(provider.traces).hasSize(2); + assertThat(admin.get(key(original))) + .containsExactly(InitialGameplayLoginContextState.pending(original).encode()); + assertThat(journal.readCommitted(original).orElseThrow().verifiedWitness()).isEmpty(); + var result = validatedResult(request, UUID.randomUUID()); + resultRef.set(result); + credentials.close(); + return result; + }); when(account.retireInitialGameplayLogin(any())) - .thenAnswer( - invocation -> { - var request = - invocation.getArgument( - 0, net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest.class); - var original = coordinates(request); - retirementRef.set(request); - assertThat(authority.active).isTrue(); - assertThat(authority.current).isTrue(); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(resultRef.get()) - .as( - "late-custody scenario requires successful CREATE_PENDING and a returned " - + "Authenticate response; provider command trace: %s", - provider.traces) - .isNotNull(); - assertThat(request.hasTokenWitness()).isTrue(); - assertThat(provider.traces).hasSize(4); - assertThat(provider.traces.get(2)).containsSubsequence("evalsha", "WAITAOF", "close"); - assertThat(provider.traces.get(3)).containsSubsequence("get", "close"); - assertThat(admin.get(key(original))) - .containsExactly(InitialGameplayLoginContextState.closed(original).encode()); - var beforeAccount = journal.readCommitted(original).orElseThrow(); - assertThat(beforeAccount.abandoned()).isTrue(); - assertThat(beforeAccount.frozenRetirementRequest()).contains(request); - return new InitialGameplayLoginDisposalResult( - UUID.fromString(request.getRequestId()), - UUID.fromString(request.getCallerContextId()), - UUID.randomUUID(), - Disposition.PENDING, - ProofKind.NONE); - }); + .thenAnswer(invocation -> { + var request = + invocation.getArgument( + 0, net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest.class); + var original = coordinates(request); + retirementRef.set(request); + assertThat(authority.active).isTrue(); + assertThat(authority.current).isTrue(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(resultRef.get()) + .as( + "late-custody scenario requires successful CREATE_PENDING and a returned " + + "Authenticate response; provider command trace: %s", + provider.traces) + .isNotNull(); + assertThat(request.hasTokenWitness()).isTrue(); + assertThat(provider.traces).hasSize(4); + assertThat(provider.traces.get(2)).containsSubsequence("evalsha", "WAITAOF", "close"); + assertThat(provider.traces.get(3)).containsSubsequence("get", "close"); + assertThat(admin.get(key(original))) + .containsExactly(InitialGameplayLoginContextState.closed(original).encode()); + var beforeAccount = journal.readCommitted(original).orElseThrow(); + assertThat(beforeAccount.abandoned()).isTrue(); + assertThat(beforeAccount.frozenRetirementRequest()).contains(request); + return new InitialGameplayLoginDisposalResult( + UUID.fromString(request.getRequestId()), + UUID.fromString(request.getCallerContextId()), + UUID.randomUUID(), + Disposition.PENDING, + ProofKind.NONE); + }); var outcome = owner.receive(credentials); var original = outcome.coordinates(); @@ -831,11 +826,10 @@ void ownerClosesExactOriginalAndWipesResultWhenCredentialCustodyEndsAfterAccount assertThat(committed.frozenRetirementRequest()).contains(exactRetirement); assertThat(retirementRef.get()).isEqualTo(exactRetirement); assertThat(committed.retainedReceipt()) - .hasValueSatisfying( - receipt -> { - assertThat(receipt.disposition()).isEqualTo(Disposition.PENDING); - assertThat(receipt.proofKind()).isEqualTo(ProofKind.NONE); - }); + .hasValueSatisfying(receipt -> { + assertThat(receipt.disposition()).isEqualTo(Disposition.PENDING); + assertThat(receipt.proofKind()).isEqualTo(ProofKind.NONE); + }); assertThat(provider.traces).hasSize(4); assertThat(outcome.takePrivateResult()).isEmpty(); verify(account).authenticate(any(AuthenticateRequest.class), any()); @@ -918,21 +912,19 @@ void actualInstalledBorrowExcludesCleanupUntilLobbyReadbackAndRefusesLaterBorrow var release = new CountDownLatch(1); var closing = new CountDownLatch(1); var fixture = - installedLobbyFixture( - () -> { - entered.countDown(); - awaitLobby(release); - }); + installedLobbyFixture(() -> { + entered.countDown(); + awaitLobby(release); + }); try (var executor = Executors.newFixedThreadPool(2)) { var borrowing = executor.submit(fixture::realms); try { assertThat(entered.await(10, TimeUnit.SECONDS)).isTrue(); var closed = - executor.submit( - () -> { - closing.countDown(); - fixture.installed().close(); - }); + executor.submit(() -> { + closing.countDown(); + fixture.installed().close(); + }); assertThat(closing.await(10, TimeUnit.SECONDS)).isTrue(); assertThatThrownBy(() -> closed.get(100, TimeUnit.MILLISECONDS)) .isInstanceOf(TimeoutException.class); @@ -982,62 +974,56 @@ void sqlRowThenResultReadProgressesWhileBorrowWaitsForRowAndCloseDrains() throws org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); try (var executor = Executors.newFixedThreadPool(3)) { var rowOwner = - executor.submit( - () -> - transaction.execute( - status -> { - fixture - .repository() - .verifyOriginal(fixture.installed().coordinates(), fixture.result()); - rowLocked.countDown(); - awaitLobby(readResult); - // This is the actual repository ordering: original SQL row, then live - // result bytes. - scope.requireCurrent( - fixture.installed().coordinates(), - fixture.result(), - fixture.transport(), - CLOCK); - // Neither drain waiting nor cleanup may hold the Outcome monitor across SQL - // work. - assertThat(fixture.installed().custodyLossCleanup()).isEmpty(); - return true; - })); + executor.submit(() -> + transaction.execute(status -> { + fixture + .repository() + .verifyOriginal(fixture.installed().coordinates(), fixture.result()); + rowLocked.countDown(); + awaitLobby(readResult); + // This is the actual repository ordering: original SQL row, then live + // result bytes. + scope.requireCurrent( + fixture.installed().coordinates(), + fixture.result(), + fixture.transport(), + CLOCK); + // Neither drain waiting nor cleanup may hold the Outcome monitor across SQL + // work. + assertThat(fixture.installed().custodyLossCleanup()).isEmpty(); + return true; + })); try { boolean locked = rowLocked.await(10, TimeUnit.SECONDS); if (!locked) rowOwner.get(1, TimeUnit.SECONDS); // Surface an early owner failure. assertThat(locked).isTrue(); var borrowing = - executor.submit( - () -> - fixture - .installed() - .withOwnedPrivateResult( - result -> { - assertThat(result).isSameAs(fixture.result()); - borrowEntered.countDown(); - return transaction.execute( - status -> { - DSL.using( - new TransactionAwareDataSourceProxy(journalDataSource), - SQLDialect.POSTGRES) - .execute("SET LOCAL lock_timeout = '5s'"); - return fixture - .repository() - .current( - fixture.installed().coordinates(), - result, - fixture.transport(), - CLOCK); - }); - })); + executor.submit(() -> + fixture + .installed() + .withOwnedPrivateResult(result -> { + assertThat(result).isSameAs(fixture.result()); + borrowEntered.countDown(); + return transaction.execute(status -> { + DSL.using( + new TransactionAwareDataSourceProxy(journalDataSource), + SQLDialect.POSTGRES) + .execute("SET LOCAL lock_timeout = '5s'"); + return fixture + .repository() + .current( + fixture.installed().coordinates(), + result, + fixture.transport(), + CLOCK); + }); + })); assertThat(borrowEntered.await(10, TimeUnit.SECONDS)).isTrue(); var closed = - executor.submit( - () -> { - closing.countDown(); - fixture.installed().close(); - }); + executor.submit(() -> { + closing.countDown(); + fixture.installed().close(); + }); assertThat(closing.await(10, TimeUnit.SECONDS)).isTrue(); assertThatThrownBy(() -> closed.get(100, TimeUnit.MILLISECONDS)) .isInstanceOf(TimeoutException.class); @@ -1069,27 +1055,24 @@ private LobbyFixture installedLobbyFixture(Runnable duringScopeCall) throws Exce var cleanup = cleanup(contexts, account); var result = new AtomicReference(); when(account.retireInitialGameplayLogin(any())) - .thenAnswer( - call -> { - var request = - call.getArgument( - 0, net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest.class); - return new InitialGameplayLoginDisposalResult( - UUID.fromString(request.getRequestId()), - UUID.fromString(request.getCallerContextId()), - UUID.randomUUID(), - Disposition.PENDING, - ProofKind.NONE); - }); + .thenAnswer(call -> { + var request = + call.getArgument( + 0, net.firedevops.firemud.account.v1.RetireInitialGameplayLoginRequest.class); + return new InitialGameplayLoginDisposalResult( + UUID.fromString(request.getRequestId()), + UUID.fromString(request.getCallerContextId()), + UUID.randomUUID(), + Disposition.PENDING, + ProofKind.NONE); + }); when(account.authenticate(any(AuthenticateRequest.class), any())) - .thenAnswer( - call -> { - var value = - validatedResult( - call.getArgument(0, AuthenticateRequest.class), UUID.randomUUID()); - result.set(value); - return value; - }); + .thenAnswer(call -> { + var value = + validatedResult(call.getArgument(0, AuthenticateRequest.class), UUID.randomUUID()); + result.set(value); + return value; + }); var installed = new InitialGameplayLoginOwner(contexts, cleanup, account) .receive( @@ -1132,16 +1115,15 @@ private LobbyFixture installedLobbyFixture(Runnable duringScopeCall) throws Exce DSL.using(new TransactionAwareDataSourceProxy(journalDataSource), SQLDialect.POSTGRES)); var lobbyAccount = mock(AccountClient.class); when(lobbyAccount.issueDirectTextConnectScope(any(), any())) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - duringScopeCall.run(); - return IssueDirectTextConnectScopeResponse.newBuilder() - .setConnectScopeId("controlled-scope") - .setEvaluatedAt(CLOCK.instant().minusSeconds(1).toString()) - .setConnectScopeExpiresAt(CLOCK.instant().plusSeconds(60).toString()) - .build(); - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + duringScopeCall.run(); + return IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("controlled-scope") + .setEvaluatedAt(CLOCK.instant().minusSeconds(1).toString()) + .setConnectScopeExpiresAt(CLOCK.instant().plusSeconds(60).toString()) + .build(); + }); return new LobbyFixture( installed, result.get(), @@ -1169,24 +1151,23 @@ private record LobbyFixture( DirectTextWorldSelectionService selection, AccountClient lobbyAccount) { DirectTextAuthenticatedLobbyScope realms() { - return installed.withOwnedPrivateResult( - borrowed -> { - assertThat(borrowed).isSameAs(result); - var custody = - new DirectTextAuthenticatedLobbyCustody() { - @Override - public T withCurrent( - InitialGameplayLoginAttemptCoordinates original, - CanonicalGameplayLoginResult candidate, - Function action) { - assertThat(original).isEqualTo(installed.coordinates()); - assertThat(candidate).isSameAs(borrowed); - return action.apply(transport); - } - }; - return lobby.realms( - installed.coordinates(), borrowed, custody, selection.browse().orElseThrow(), "1"); - }); + return installed.withOwnedPrivateResult(borrowed -> { + assertThat(borrowed).isSameAs(result); + var custody = + new DirectTextAuthenticatedLobbyCustody() { + @Override + public T withCurrent( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult candidate, + Function action) { + assertThat(original).isEqualTo(installed.coordinates()); + assertThat(candidate).isSameAs(borrowed); + return action.apply(transport); + } + }; + return lobby.realms( + installed.coordinates(), borrowed, custody, selection.browse().orElseThrow(), "1"); + }); } } @@ -1369,19 +1350,18 @@ private AckResponseDropper(int upstreamPort, AcknowledgementPolicy policy) throw this.upstreamPort = upstreamPort; this.policy = policy; listener = new ServerSocket(0, 8, InetAddress.getByName("127.0.0.1")); - workers.submit( - () -> { - while (!stopping.get()) { - try { - var downstream = listener.accept(); - sockets.add(downstream); - workers.submit(() -> relay(downstream)); - } catch (IOException disconnected) { - if (!stopping.get()) - throw new IllegalStateException("Controlled loopback relay unavailable"); - } - } - }); + workers.submit(() -> { + while (!stopping.get()) { + try { + var downstream = listener.accept(); + sockets.add(downstream); + workers.submit(() -> relay(downstream)); + } catch (IOException disconnected) { + if (!stopping.get()) + throw new IllegalStateException("Controlled loopback relay unavailable"); + } + } + }); } private int port() { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java index 307f7aae49..25e94f9d21 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java @@ -86,13 +86,11 @@ void concurrentExactIdentityAllocationConvergesAndOrdinaryRowsRemainNullable() t assertThatThrownBy(() -> insertDuplicateIdentity(dsl, firstId + 1L)) .isInstanceOf(DataAccessException.class) - .satisfies( - failure -> { - assertThat(sqlState(failure)).isEqualTo("23505"); - assertThat( - hasCauseMessage(failure, "game_instances_run_owned_start_request_unique")) - .isTrue(); - }); + .satisfies(failure -> { + assertThat(sqlState(failure)).isEqualTo("23505"); + assertThat(hasCauseMessage(failure, "game_instances_run_owned_start_request_unique")) + .isTrue(); + }); GameInstance savedOrdinaryOne = repository.save(ordinaryInstance(1001L)); GameInstance savedOrdinaryTwo = repository.save(ordinaryInstance(1002L)); @@ -121,20 +119,17 @@ private static long allocateOrReadSameRunOwnedInstance( throw new IllegalStateException("concurrent allocation start gate timed out"); } Long id = - transactions.execute( - status -> { - repository.lockRunOwnedStartIdentity(TENANT_ID, REQUEST_ID); - var existing = - repository.findByTenantIdAndRunOwnedStartRequestIdForUpdate( - TENANT_ID, REQUEST_ID); - if (existing.isPresent()) { - assertThat(existing.get().getRunOwnedStartRequestDigest()) - .isEqualTo(REQUEST_DIGEST); - return existing.get().getId(); - } - GameInstance instance = runOwnedInstance(); - return repository.save(instance).getId(); - }); + transactions.execute(status -> { + repository.lockRunOwnedStartIdentity(TENANT_ID, REQUEST_ID); + var existing = + repository.findByTenantIdAndRunOwnedStartRequestIdForUpdate(TENANT_ID, REQUEST_ID); + if (existing.isPresent()) { + assertThat(existing.get().getRunOwnedStartRequestDigest()).isEqualTo(REQUEST_DIGEST); + return existing.get().getId(); + } + GameInstance instance = runOwnedInstance(); + return repository.save(instance).getId(); + }); if (id == null) { throw new IllegalStateException("run-owned instance allocation returned no id"); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java index 812f909908..42f7f995ec 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyIntegrationTest.java @@ -160,11 +160,10 @@ void migratePopulatedOriginalThenComposeInactiveOwner() throws Exception { journal = new InitialGameplayLoginCoordinationJournalRepository(dsl); original = new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 7); verified = verified(original, ACCOUNT, UUID.randomUUID(), "5"); - tx.executeWithoutResult( - status -> { - journal.reserve(original); - journal.recordVerifiedResult(original, verified); - }); + tx.executeWithoutResult(status -> { + journal.reserve(original); + journal.recordVerifiedResult(original, verified); + }); parentBeforeMigration = parentJson(); migrate(null); repository = new DirectTextAuthenticatedLobbyRepository(dsl); @@ -199,13 +198,12 @@ void migratePopulatedOriginalThenComposeInactiveOwner() throws Exception { new ControlledCustody( original, verified, new ObservedDirectTextTransport("00042", UUID.randomUUID())); when(account.issueDirectTextConnectScope(any(), any())) - .thenAnswer( - call -> - IssueDirectTextConnectScopeResponse.newBuilder() - .setConnectScopeId("opaque-" + UUID.randomUUID()) - .setEvaluatedAt(NOW.minusSeconds(1).toString()) - .setConnectScopeExpiresAt(NOW.plusSeconds(60).toString()) - .build()); + .thenAnswer(call -> + IssueDirectTextConnectScopeResponse.newBuilder() + .setConnectScopeId("opaque-" + UUID.randomUUID()) + .setEvaluatedAt(NOW.minusSeconds(1).toString()) + .setConnectScopeExpiresAt(NOW.plusSeconds(60).toString()) + .build()); owner = owner(repository, manager); } @@ -251,30 +249,29 @@ void forwardMigrationPreservesPopulatedMinimalParentAndFullExactNonsecretScope() void actualOwnerReadsCommittedExactRequestBeforeAccountAndRetainsPositiveReply() { var scope = realms(); when(account.joinPublicProductionMembership(any(), any(), any(), any())) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - var row = - dsl.fetchSingle( - "SELECT * FROM " + JOIN + " WHERE scope_record_id = ?", scope.recordId()); - assertThat(row.get("state", String.class)).isEqualTo("DISPATCH_POSSIBLE"); - var request = - DirectTextAuthenticatedLobbyJoin.decodeRequest( - row.get("request_bytes", byte[].class)); - assertThat(request.getPlayerContext()) - .isEqualTo( - call.getArgument( - 0, net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); - assertThat(request.getPlayerContext().getAccountId()).isEqualTo(ACCOUNT.toString()); - assertThat(request.getPlayerContext().getSessionId()) - .isEqualTo(custody.transport.transportSessionId()); - assertThat(request.getConnectScopeId()).isEqualTo(scope.issued().connectScopeId()); - assertThat(request.getConnectScopeId()).isEqualTo(call.getArgument(1, String.class)); - assertThat(request.getRequestId()).isEqualTo(call.getArgument(2, String.class)); - assertThat(call.getArgument(3, Instant.class)) - .isEqualTo(scope.issued().connectScopeExpiresAtInstant()); - return positive(); - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + var row = + dsl.fetchSingle( + "SELECT * FROM " + JOIN + " WHERE scope_record_id = ?", scope.recordId()); + assertThat(row.get("state", String.class)).isEqualTo("DISPATCH_POSSIBLE"); + var request = + DirectTextAuthenticatedLobbyJoin.decodeRequest( + row.get("request_bytes", byte[].class)); + assertThat(request.getPlayerContext()) + .isEqualTo( + call.getArgument( + 0, net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)); + assertThat(request.getPlayerContext().getAccountId()).isEqualTo(ACCOUNT.toString()); + assertThat(request.getPlayerContext().getSessionId()) + .isEqualTo(custody.transport.transportSessionId()); + assertThat(request.getConnectScopeId()).isEqualTo(scope.issued().connectScopeId()); + assertThat(request.getConnectScopeId()).isEqualTo(call.getArgument(1, String.class)); + assertThat(request.getRequestId()).isEqualTo(call.getArgument(2, String.class)); + assertThat(call.getArgument(3, Instant.class)) + .isEqualTo(scope.issued().connectScopeExpiresAtInstant()); + return positive(); + }); var completed = owner.join(original, verified, custody); assertThat(completed.status()) .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.COMPLETED_CURRENT_NON_ADMITTING); @@ -320,17 +317,15 @@ void independentConnectionsAllocateOneFrozenWinnerAndOnlyOneDispatchClaim() thro var executor = Executors.newFixedThreadPool(2); try { var one = - executor.submit( - () -> { - await(gate); - return freeze(); - }); + executor.submit(() -> { + await(gate); + return freeze(); + }); var two = - executor.submit( - () -> { - await(gate); - return freeze(); - }); + executor.submit(() -> { + await(gate); + return freeze(); + }); gate.countDown(); var first = one.get(10, TimeUnit.SECONDS); var second = two.get(10, TimeUnit.SECONDS); @@ -368,42 +363,34 @@ void actualParentAbandonmentAndDispatchClaimSerializeInBothOrders(boolean abando var executor = Executors.newFixedThreadPool(2); try { var winner = - executor.submit( - () -> - tx.execute( - status -> { - repository.verifyOriginal(original, verified); - if (abandonmentFirst) journal.abandon(original); - else - assertThat( - repository.claimDispatch( - frozen, verified, custody.transport, clock)) - .isTrue(); - locked.countDown(); - await(release); - return true; - })); + executor.submit(() -> + tx.execute(status -> { + repository.verifyOriginal(original, verified); + if (abandonmentFirst) journal.abandon(original); + else + assertThat(repository.claimDispatch(frozen, verified, custody.transport, clock)) + .isTrue(); + locked.countDown(); + await(release); + return true; + })); assertThat(locked.await(5, TimeUnit.SECONDS)).isTrue(); var follower = - executor.submit( - () -> { - try { - return tx.execute( - status -> { - followerPid.set( - dsl.fetchSingle("SELECT pg_backend_pid() AS pid") - .get("pid", Integer.class)); - followerStarted.countDown(); - if (abandonmentFirst) - return repository.claimDispatch( - frozen, verified, custody.transport, clock); - journal.abandon(original); - return true; - }); - } catch (IllegalStateException denied) { - return false; - } + executor.submit(() -> { + try { + return tx.execute(status -> { + followerPid.set( + dsl.fetchSingle("SELECT pg_backend_pid() AS pid").get("pid", Integer.class)); + followerStarted.countDown(); + if (abandonmentFirst) + return repository.claimDispatch(frozen, verified, custody.transport, clock); + journal.abandon(original); + return true; }); + } catch (IllegalStateException denied) { + return false; + } + }); assertThat(followerStarted.await(5, TimeUnit.SECONDS)).isTrue(); awaitActualLockWait(followerPid.get()); assertThat(follower.isDone()).isFalse(); @@ -598,12 +585,11 @@ public void rollback(TransactionStatus status) { void positiveInflightResultAfterAbandonmentAndTransportResetIsHistoricalOnly() { var scope = realms(); when(account.joinPublicProductionMembership(any(), any(), any(), any())) - .thenAnswer( - call -> { - tx.executeWithoutResult(status -> journal.abandon(original)); - custody.resetAfterCurrentCallback(); - return positive(); - }); + .thenAnswer(call -> { + tx.executeWithoutResult(status -> journal.abandon(original)); + custody.resetAfterCurrentCallback(); + return positive(); + }); var observed = owner.join(original, verified, custody); assertThat(observed.status()) .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.HISTORICAL_ONLY); @@ -619,12 +605,11 @@ void positiveInflightResultAfterAbandonmentAndTransportResetIsHistoricalOnly() { void delayedPositiveResultDoesNotMoveANewerCurrentScope() { var old = realms(); when(account.joinPublicProductionMembership(any(), any(), any(), any())) - .thenAnswer( - call -> { - var newer = realms(); - assertThat(newer.recordId()).isNotEqualTo(old.recordId()); - return positive(); - }); + .thenAnswer(call -> { + var newer = realms(); + assertThat(newer.recordId()).isNotEqualTo(old.recordId()); + return positive(); + }); var observed = owner.join(original, verified, custody); assertThat(observed.status()) .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.HISTORICAL_ONLY); @@ -647,25 +632,20 @@ void currentVerifiedIdentityAndCompleteWitnessAreRequiredNotMerelyMatchingSqlOrF try (var differentAccount = verified(original, UUID.randomUUID(), verified.evidence().tokenJti(), "5"); var differentWitness = verified(original, ACCOUNT, UUID.randomUUID(), "6")) { - assertThatThrownBy( - () -> - tx.execute( - status -> - repository.current(original, differentAccount, custody.transport, clock))) + assertThatThrownBy(() -> + tx.execute(status -> + repository.current(original, differentAccount, custody.transport, clock))) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - tx.execute( - status -> - repository.current(original, differentWitness, custody.transport, clock))) + assertThatThrownBy(() -> + tx.execute(status -> + repository.current(original, differentWitness, custody.transport, clock))) .isInstanceOf(IllegalStateException.class); } var wrongFence = new InitialGameplayLoginAttemptCoordinates( original.requestId(), original.callerContextId(), 8); - assertThatThrownBy( - () -> - tx.executeWithoutResult(status -> repository.verifyOriginal(wrongFence, verified))) + assertThatThrownBy(() -> + tx.executeWithoutResult(status -> repository.verifyOriginal(wrongFence, verified))) .isInstanceOf(IllegalStateException.class); var missing = new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 1); @@ -728,20 +708,17 @@ void nonDurableUnjoinedOrAmbientTransactionsCannotSupplyReadbackOrDispatchEviden var frozen = freeze(); assertThatThrownBy(() -> tx.execute(status -> repository.readCommittedJoin(frozen))) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - tx.execute( - status -> { - dsl.execute("SET LOCAL synchronous_commit = 'off'"); - return repository.claimDispatch(frozen, verified, custody.transport, clock); - })) + assertThatThrownBy(() -> + tx.execute(status -> { + dsl.execute("SET LOCAL synchronous_commit = 'off'"); + return repository.claimDispatch(frozen, verified, custody.transport, clock); + })) .isInstanceOf(IllegalStateException.class); var unjoined = new DirectTextAuthenticatedLobbyRepository(DSL.using(source, SQLDialect.POSTGRES)); - assertThatThrownBy( - () -> - tx.execute( - status -> unjoined.claimDispatch(frozen, verified, custody.transport, clock))) + assertThatThrownBy(() -> + tx.execute( + status -> unjoined.claimDispatch(frozen, verified, custody.transport, clock))) .isInstanceOf(IllegalStateException.class); assertThat(repository.readCommittedJoin(frozen).state()).isEqualTo(State.NEVER_DISPATCHED); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/CurrentPrivatePlaytestLifecycleReadGrpcServiceIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/CurrentPrivatePlaytestLifecycleReadGrpcServiceIntegrationTest.java index 23bbc20c36..bc8cefc20e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/CurrentPrivatePlaytestLifecycleReadGrpcServiceIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/CurrentPrivatePlaytestLifecycleReadGrpcServiceIntegrationTest.java @@ -179,10 +179,9 @@ void accountSelectorMustNameThisGameSessionNamespace() { Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .run( - () -> - service.readCurrentPrivatePlaytestLifecycle( - CurrentPrivatePlaytestLifecycleReadGrpcCodec.toRequest(selector), observer)); + .run(() -> + service.readCurrentPrivatePlaytestLifecycle( + CurrentPrivatePlaytestLifecycleReadGrpcCodec.toRequest(selector), observer)); ArgumentCaptor failure = ArgumentCaptor.forClass(Throwable.class); org.mockito.Mockito.verify(observer).onError(failure.capture()); @@ -205,10 +204,9 @@ void ambientTransactionIsRejectedBeforeOwnerRead() { try { Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, accountPeer(NAMESPACE)) - .run( - () -> - service.readCurrentPrivatePlaytestLifecycle( - CurrentPrivatePlaytestLifecycleReadGrpcCodec.toRequest(selector), observer)); + .run(() -> + service.readCurrentPrivatePlaytestLifecycle( + CurrentPrivatePlaytestLifecycleReadGrpcCodec.toRequest(selector), observer)); } finally { TransactionSynchronizationManager.setActualTransactionActive(false); } @@ -247,10 +245,9 @@ service, peerIdentityInterceptor(NAMESPACE), guard)) CurrentPrivatePlaytestLifecycleReadServiceGrpc.newBlockingStub(channel) .withDeadlineAfter(5, TimeUnit.SECONDS); Request selector = new Request(UUID.randomUUID(), scope); - assertThatThrownBy( - () -> - stub.readCurrentPrivatePlaytestLifecycle( - CurrentPrivatePlaytestLifecycleReadGrpcCodec.toRequest(selector))) + assertThatThrownBy(() -> + stub.readCurrentPrivatePlaytestLifecycle( + CurrentPrivatePlaytestLifecycleReadGrpcCodec.toRequest(selector))) .isInstanceOfSatisfying( StatusRuntimeException.class, failure -> { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java index 9812ffd5a5..518ff184ac 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceLifecycleIntegrationTest.java @@ -118,27 +118,26 @@ void setUp() throws Exception { repository.deleteAll(); doNothing().when(sagaRunner).run(any()); when(gameInstanceMapper.toDto(any(GameInstance.class))) - .thenAnswer( - invocation -> { - GameInstance entity = invocation.getArgument(0); - return new GameInstanceDto( - entity.getId(), - entity.getTenantId(), - entity.getRuntimeVersion(), - entity.getScriptPatchVersion(), - entity.getScriptPatchBaseVersionId(), - entity.getScriptPinEpoch(), - entity.getScriptPatchPinnedControlPlaneRequestId(), - entity.getGameTemplateId(), - entity.getLaunchDescriptorId(), - entity.getVersionId(), - entity.getReleaseBundleId(), - entity.getVersionStateEpoch(), - entity.getGenerationConfigRevision(), - entity.getRemapSetId(), - entity.getOwnerAccountId(), - entity.getStatus()); - }); + .thenAnswer(invocation -> { + GameInstance entity = invocation.getArgument(0); + return new GameInstanceDto( + entity.getId(), + entity.getTenantId(), + entity.getRuntimeVersion(), + entity.getScriptPatchVersion(), + entity.getScriptPatchBaseVersionId(), + entity.getScriptPinEpoch(), + entity.getScriptPatchPinnedControlPlaneRequestId(), + entity.getGameTemplateId(), + entity.getLaunchDescriptorId(), + entity.getVersionId(), + entity.getReleaseBundleId(), + entity.getVersionStateEpoch(), + entity.getGenerationConfigRevision(), + entity.getRemapSetId(), + entity.getOwnerAccountId(), + entity.getStatus()); + }); when(gameDesignClient.resolveLaunchDescriptor(42L, 7L, "cp-1")) .thenReturn( net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse.newBuilder() @@ -275,99 +274,85 @@ void setUp() throws Exception { anyString(), anyLong(), any())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse.newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setGameTemplateId(Long.toString(invocation.getArgument(2, Long.class))) - .setControlPlaneRequestId(invocation.getArgument(3, String.class)) - .setLaunchDescriptorId(invocation.getArgument(4, String.class)) - .setVersionId(Long.toString(invocation.getArgument(5, Long.class))) - .setReleaseBundleId( - Long.toString(invocation.getArgument(9, Long.class))) - .setGenerationConfigRevision(invocation.getArgument(8, String.class)) - .setPublishedReleaseBundleRef(invocation.getArgument(10, String.class)) - .setVersionStateEpoch(invocation.getArgument(11, Long.class)) - .setLifecycleEpoch(1L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) - .build()) - .build()); + .thenAnswer(invocation -> + net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse.newBuilder() + .setWorldInstance( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot + .newBuilder() + .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) + .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) + .setGameTemplateId(Long.toString(invocation.getArgument(2, Long.class))) + .setControlPlaneRequestId(invocation.getArgument(3, String.class)) + .setLaunchDescriptorId(invocation.getArgument(4, String.class)) + .setVersionId(Long.toString(invocation.getArgument(5, Long.class))) + .setReleaseBundleId(Long.toString(invocation.getArgument(9, Long.class))) + .setGenerationConfigRevision(invocation.getArgument(8, String.class)) + .setPublishedReleaseBundleRef(invocation.getArgument(10, String.class)) + .setVersionStateEpoch(invocation.getArgument(11, Long.class)) + .setLifecycleEpoch(1L) + .setStatus( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus + .WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) + .build()) + .build()); when(worldManagementClient.activatePreparedWorldInstance(anyLong(), anyLong(), anyLong())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse - .newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setLifecycleEpoch(invocation.getArgument(2, Long.class) + 1L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) - .build()) - .build()); + .thenAnswer(invocation -> + net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse + .newBuilder() + .setWorldInstance( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot + .newBuilder() + .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) + .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) + .setLifecycleEpoch(invocation.getArgument(2, Long.class) + 1L) + .setStatus( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus + .WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) + .build()) + .build()); when(worldManagementClient.failPreparedWorldInstance(anyLong(), anyLong(), anyLong(), any())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.FailPreparedWorldInstanceResponse - .newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setLifecycleEpoch(invocation.getArgument(2, Long.class) + 1L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_FAILED_PRE_ACTIVATION) - .build()) - .build()); + .thenAnswer(invocation -> + net.firedevops.firemud.worldmanagement.v1.FailPreparedWorldInstanceResponse.newBuilder() + .setWorldInstance( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot + .newBuilder() + .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) + .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) + .setLifecycleEpoch(invocation.getArgument(2, Long.class) + 1L) + .setStatus( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus + .WORLD_INSTANCE_LIFECYCLE_STATUS_FAILED_PRE_ACTIVATION) + .build()) + .build()); when(worldManagementClient.getWorldInstanceLifecycle(anyLong(), anyLong())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse - .newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0))) - .setGameInstanceId(Long.toString(invocation.getArgument(1))) - .setLifecycleEpoch(2L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) - .build()) - .build()); + .thenAnswer(invocation -> + net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse.newBuilder() + .setWorldInstance( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot + .newBuilder() + .setTenantId(Long.toString(invocation.getArgument(0))) + .setGameInstanceId(Long.toString(invocation.getArgument(1))) + .setLifecycleEpoch(2L) + .setStatus( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus + .WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) + .build()) + .build()); when(worldManagementClient.terminateWorldInstance( anyLong(), anyLong(), anyLong(), anyString(), anyString())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.TerminateWorldInstanceResponse - .newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0))) - .setGameInstanceId(Long.toString(invocation.getArgument(1))) - .setLifecycleEpoch(((Long) invocation.getArgument(2)) + 1L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATED) - .build()) - .build()); + .thenAnswer(invocation -> + net.firedevops.firemud.worldmanagement.v1.TerminateWorldInstanceResponse.newBuilder() + .setWorldInstance( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot + .newBuilder() + .setTenantId(Long.toString(invocation.getArgument(0))) + .setGameInstanceId(Long.toString(invocation.getArgument(1))) + .setLifecycleEpoch(((Long) invocation.getArgument(2)) + 1L) + .setStatus( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus + .WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATED) + .build()) + .build()); } @Test diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverMtlsIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverMtlsIntegrationTest.java index 835b881ad6..eae9adfb0b 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverMtlsIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/GameSessionJwtReadinessReceiverMtlsIntegrationTest.java @@ -315,15 +315,14 @@ void accountMtlsCallUsesProductionOwnerReadAndRealProfileVerificationWithoutAuth assertThat(responseHadNoApplicationAuthContext).isTrue(); assertThat(ownerHandlerAuthContexts) .hasSize(2) - .allSatisfy( - context -> { - assertThat(context.accountId()).isNull(); - assertThat(context.globalRoles()).isEmpty(); - assertThat(context.scopedRoles()).isEmpty(); - assertThat(context.internalService()).isFalse(); - assertThat(context.serviceName()).isNull(); - assertThat(context.serviceInstanceId()).isNull(); - }); + .allSatisfy(context -> { + assertThat(context.accountId()).isNull(); + assertThat(context.globalRoles()).isEmpty(); + assertThat(context.scopedRoles()).isEmpty(); + assertThat(context.internalService()).isFalse(); + assertThat(context.serviceName()).isNull(); + assertThat(context.serviceInstanceId()).isNull(); + }); // JUnit-thread cleanup checks only; server-context proof is captured above. assertThat(SessionContext.getAccountId()).isNull(); assertThat(SessionContext.getGlobalRoles()).isEmpty(); @@ -395,16 +394,13 @@ void warmKnownKeyCannotIssueReceiptNamingADifferentProtectedSourceIdentity() thr private void assertWarmSnapshotBindingDenied() { assertThatThrownBy(() -> receive(pki.account(), validRequest)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION); - assertThat(Status.fromThrowable(failure).getDescription()) - .doesNotContain( - validCompactJwt, - fixturePublicJwksSha256, - jwksSourceIdentity.apiServerOrigin()); - }); + .satisfies(failure -> { + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(Status.fromThrowable(failure).getDescription()) + .doesNotContain( + validCompactJwt, fixturePublicJwksSha256, jwksSourceIdentity.apiServerOrigin()); + }); assertThat(ownerReadCalls).hasValue(1); assertThat(jwksLoads).hasValue(1); assertThat(lastOwnerRequest.get().getProtectedLocalIdentity()) @@ -433,15 +429,14 @@ void currentMetadataBootstrapUsesAccountMtlsAndOnlyProjectedUidAndActualLeafPin( assertThat(metadataSawPeerUri).hasValue(GAME_SESSION_URI); assertThat(metadataHandlerAuthContexts) .hasSize(1) - .allSatisfy( - context -> { - assertThat(context.accountId()).isNull(); - assertThat(context.globalRoles()).isEmpty(); - assertThat(context.scopedRoles()).isEmpty(); - assertThat(context.internalService()).isFalse(); - assertThat(context.serviceName()).isNull(); - assertThat(context.serviceInstanceId()).isNull(); - }); + .allSatisfy(context -> { + assertThat(context.accountId()).isNull(); + assertThat(context.globalRoles()).isEmpty(); + assertThat(context.scopedRoles()).isEmpty(); + assertThat(context.internalService()).isFalse(); + assertThat(context.serviceName()).isNull(); + assertThat(context.serviceInstanceId()).isNull(); + }); // JUnit-thread cleanup checks only; the Account handler values are captured above. assertThat(SessionContext.getAccountId()).isNull(); assertThat(SessionContext.getGlobalRoles()).isEmpty(); @@ -455,14 +450,13 @@ void unavailableAccountOwnerDeniesTheReceiverAndMetadataRead() throws Exception accountOwnerServer = null; assertUnavailable(validRequest); - assertThatThrownBy( - () -> - ownerClient.readCurrent( - GetCurrentReadinessReceiverMetadataRequest.newBuilder() - .setSchemaVersion(1) - .setProjectedPodUid(POD_UID) - .setServerLeafSpkiSha256(spkiSha256(pki.gameSession().certificate())) - .build())) + assertThatThrownBy(() -> + ownerClient.readCurrent( + GetCurrentReadinessReceiverMetadataRequest.newBuilder() + .setSchemaVersion(1) + .setProjectedPodUid(POD_UID) + .setServerLeafSpkiSha256(spkiSha256(pki.gameSession().certificate())) + .build())) .isInstanceOf(GameSessionJwtReadinessProbeOwnerClient.OwnerReadUnavailableException.class); assertThat(ownerReadCalls).hasValue(0); assertThat(metadataReadCalls).hasValue(0); @@ -478,18 +472,16 @@ void accountReadsRejectATrustedServerWithAnotherWorkloadSan() throws Exception { new GameSessionJwtReadinessProbeOwnerClient( endpoints, clientProperties(gameSessionFiles), new GrpcChannelFactory(), NAMESPACE); - assertThatThrownBy( - () -> - wrongPeerClient.readCurrent( - GetCurrentReadinessProbeOwnerRequest.newBuilder() - .setExpectedCoordinates(validRequest.getCoordinates()) - .build())) + assertThatThrownBy(() -> + wrongPeerClient.readCurrent( + GetCurrentReadinessProbeOwnerRequest.newBuilder() + .setExpectedCoordinates(validRequest.getCoordinates()) + .build())) .isInstanceOf( GameSessionJwtReadinessProbeOwnerClient.OwnerReadUnavailableException.class); - assertThatThrownBy( - () -> - wrongPeerClient.readCurrent( - GetCurrentReadinessReceiverMetadataRequest.newBuilder().build())) + assertThatThrownBy(() -> + wrongPeerClient.readCurrent( + GetCurrentReadinessReceiverMetadataRequest.newBuilder().build())) .isInstanceOf( GameSessionJwtReadinessProbeOwnerClient.OwnerReadUnavailableException.class); } finally { @@ -503,16 +495,13 @@ void ambientSqlTransactionDeniesBothAccountReadsBeforeDispatch() { TransactionSynchronizationManager.isActualTransactionActive(); TransactionSynchronizationManager.setActualTransactionActive(true); try { - assertThatThrownBy( - () -> - ownerClient.readCurrent( - GetCurrentReadinessProbeOwnerRequest.newBuilder().build())) + assertThatThrownBy(() -> + ownerClient.readCurrent(GetCurrentReadinessProbeOwnerRequest.newBuilder().build())) .isInstanceOf( GameSessionJwtReadinessProbeOwnerClient.OwnerReadUnavailableException.class); - assertThatThrownBy( - () -> - ownerClient.readCurrent( - GetCurrentReadinessReceiverMetadataRequest.newBuilder().build())) + assertThatThrownBy(() -> + ownerClient.readCurrent( + GetCurrentReadinessReceiverMetadataRequest.newBuilder().build())) .isInstanceOf( GameSessionJwtReadinessProbeOwnerClient.OwnerReadUnavailableException.class); assertThat(ownerReadCalls).hasValue(0); @@ -527,10 +516,9 @@ void wrongWorkloadAndMissingWorkloadIdentityAreDeniedBeforeOwnerRead() throws Ex for (TestCertificate caller : List.of(pki.wrongWorkload(), pki.missingWorkloadUri())) { assertThatThrownBy(() -> receive(caller, validRequest)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); assertThat(ownerReadCalls).hasValue(0); } } @@ -611,10 +599,9 @@ void wrongKeyAndTamperedSignatureAreRejectedByProductionVerifier() throws Except ReceiveReadinessProbeRequest wrongKeyRequest = request(validCompactJwt, wrongKeyCoordinates); assertThatThrownBy(() -> receive(pki.account(), wrongKeyRequest)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); assertThat(ownerReadCalls).hasValue(1); ownerReadCalls.set(0); @@ -623,20 +610,17 @@ void wrongKeyAndTamperedSignatureAreRejectedByProductionVerifier() throws Except request(tamperedJwt, validRequest.getCoordinates()); assertThatThrownBy(() -> receive(pki.account(), tamperedRequest)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); assertThat(ownerReadCalls).hasValue(1); } private void assertUnavailable(ReceiveReadinessProbeRequest request) throws Exception { assertThatThrownBy(() -> receive(pki.account(), request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAVAILABLE)); } private ReceiveReadinessProbeResponse receive( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java index 7d7864ce0a..55090f032c 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/SessionContextSecretAndPresenceRedisIntegrationTest.java @@ -276,11 +276,10 @@ private Map snapshot(List keys) { } private void assertRetainedUnchanged(Map retained) { - retained.forEach( - (key, value) -> { - assertThat(rawValue(key)).containsExactly(value.bytes()); - assertThat(remainingTtl(key)).isPositive().isLessThanOrEqualTo(value.ttlMillis()); - }); + retained.forEach((key, value) -> { + assertThat(rawValue(key)).containsExactly(value.bytes()); + assertThat(remainingTtl(key)).isPositive().isLessThanOrEqualTo(value.ttlMillis()); + }); } private long remainingTtl(String key) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceRedisIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceRedisIntegrationTest.java index 6f2fc3fb2b..a689c4cda2 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceRedisIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceRedisIntegrationTest.java @@ -174,9 +174,8 @@ void conflictingSameCommandIdAcrossProjectionsFailsClosedWithoutMutation() { redisTemplate.opsForList().rightPush(QUEUE_KEY, existingPayload); redisTemplate.opsForList().rightPush(PENDING_KEY, conflictingPayload); - assertThatThrownBy( - () -> - service.enqueueCommand(TENANT_ID, GAME_INSTANCE_ID, "cmd-conflict", "look", false)) + assertThatThrownBy(() -> + service.enqueueCommand(TENANT_ID, GAME_INSTANCE_ID, "cmd-conflict", "look", false)) .isInstanceOf(IllegalArgumentException.class); assertThat(values(QUEUE_KEY)).containsExactly(existingPayload); @@ -196,9 +195,8 @@ void duplicateIdentityAcrossQueueAndPendingFailsClosedDuringIndexRebuild() { redisTemplate.opsForList().rightPush(QUEUE_KEY, payload); redisTemplate.opsForList().rightPush(PENDING_KEY, payload); - assertThatThrownBy( - () -> - service.enqueueCommand(TENANT_ID, GAME_INSTANCE_ID, "cmd-duplicate", "look", false)) + assertThatThrownBy(() -> + service.enqueueCommand(TENANT_ID, GAME_INSTANCE_ID, "cmd-duplicate", "look", false)) .isInstanceOf(IllegalArgumentException.class); assertThat(values(QUEUE_KEY)).containsExactly(payload); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index c6499a3147..b4d42bace2 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -238,12 +238,10 @@ void setUp() { .when(redisSetOperations) .remove(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any()); when(redisSetOperations.members(org.mockito.ArgumentMatchers.anyString())) - .thenAnswer( - invocation -> { - java.util.LinkedHashSet members = - redisSetStore.get(invocation.getArgument(0)); - return members == null ? java.util.Set.of() : new java.util.LinkedHashSet<>(members); - }); + .thenAnswer(invocation -> { + java.util.LinkedHashSet members = redisSetStore.get(invocation.getArgument(0)); + return members == null ? java.util.Set.of() : new java.util.LinkedHashSet<>(members); + }); when(moderationPolicyClient.evaluateGameplayAdmission( org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString())) .thenReturn( @@ -280,16 +278,15 @@ void setUp() { org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.nullable(String.class)); - org.mockito.Mockito.doAnswer( - invocation -> - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(true) - .setAllowPublicJoin(true) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt(java.time.Instant.now().toString()) - .build()) + org.mockito.Mockito.doAnswer(invocation -> + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(true) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt(java.time.Instant.now().toString()) + .build()) .when(accountClient) .getTenantEntitlementsForRuntime( org.mockito.ArgumentMatchers.anyString(), @@ -331,21 +328,19 @@ void setUp() { when(commandService.enqueue(eq("41"), eq("QUICKLOOK"), eq(false))) .thenReturn(CommandEnqueueResult.success()); when(commandService.enqueue(eq("41"), eq("AFK"), eq(false))) - .thenAnswer( - invocation -> { - gameplayPresenceService.setExplicitAfk(41L, true); - return CommandEnqueueResult.success(); - }); + .thenAnswer(invocation -> { + gameplayPresenceService.setExplicitAfk(41L, true); + return CommandEnqueueResult.success(); + }); when(commandService.enqueue(eq("42"), eq("LOOK"), eq(false))) .thenReturn(CommandEnqueueResult.success()); when(commandService.enqueue(eq("1"), eq("PLAY demo Emberline"), eq(false))) .thenReturn(CommandEnqueueResult.success()); when(commandService.enqueue(eq("1"), eq("AFK"), eq(false))) - .thenAnswer( - invocation -> { - gameplayPresenceService.setExplicitAfk(1L, true); - return CommandEnqueueResult.success(); - }); + .thenAnswer(invocation -> { + gameplayPresenceService.setExplicitAfk(1L, true); + return CommandEnqueueResult.success(); + }); when(commandService.enqueue(eq("1"), eq("LOOK"), eq(false))) .thenReturn(CommandEnqueueResult.success()); when(gameLogicClient.resolveLook( @@ -428,44 +423,41 @@ void setUp() { org.mockito.Mockito.doReturn(Optional.of(instance)).when(gameInstanceRepository).findById(2L); when(worldManagementClient.getWorldInstanceLifecycle( org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong())) - .thenAnswer( - invocation -> { - long tenantId = invocation.getArgument(0); - long gameInstanceId = invocation.getArgument(1); - return GetWorldInstanceLifecycleResponse.newBuilder() - .setWorldInstance( - WorldInstanceLifecycleSnapshot.newBuilder() - .setTenantId(Long.toString(tenantId)) - .setGameInstanceId(Long.toString(gameInstanceId)) - .setLifecycleEpoch(2L) - .setStatus( - WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) - .build()) - .build(); - }); + .thenAnswer(invocation -> { + long tenantId = invocation.getArgument(0); + long gameInstanceId = invocation.getArgument(1); + return GetWorldInstanceLifecycleResponse.newBuilder() + .setWorldInstance( + WorldInstanceLifecycleSnapshot.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setGameInstanceId(Long.toString(gameInstanceId)) + .setLifecycleEpoch(2L) + .setStatus( + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) + .build()) + .build(); + }); when(worldManagementClient.terminateWorldInstance( org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyLong(), org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyString())) - .thenAnswer( - invocation -> { - long tenantId = invocation.getArgument(0); - long gameInstanceId = invocation.getArgument(1); - long expectedLifecycleEpoch = invocation.getArgument(2); - return TerminateWorldInstanceResponse.newBuilder() - .setWorldInstance( - WorldInstanceLifecycleSnapshot.newBuilder() - .setTenantId(Long.toString(tenantId)) - .setGameInstanceId(Long.toString(gameInstanceId)) - .setLifecycleEpoch(expectedLifecycleEpoch + 1L) - .setStatus( - WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATED) - .build()) - .build(); - }); + .thenAnswer(invocation -> { + long tenantId = invocation.getArgument(0); + long gameInstanceId = invocation.getArgument(1); + long expectedLifecycleEpoch = invocation.getArgument(2); + return TerminateWorldInstanceResponse.newBuilder() + .setWorldInstance( + WorldInstanceLifecycleSnapshot.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setGameInstanceId(Long.toString(gameInstanceId)) + .setLifecycleEpoch(expectedLifecycleEpoch + 1L) + .setStatus( + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATED) + .build()) + .build(); + }); } @Test @@ -482,19 +474,17 @@ void websocketLoginThenLookUsesAuthenticatedPath() throws Exception { assertThat(payloads) .anyMatch(payload -> payload.startsWith("OK PLAY") && payload.endsWith("> ")); assertThat(payloads) - .anyMatch( - payload -> - payload.startsWith("OK LOOK") - && payload.contains("Room: Login Hall") - && payload.contains("Long: A narrow testing hall used for login verification.") - && payload.endsWith("> ")); + .anyMatch(payload -> + payload.startsWith("OK LOOK") + && payload.contains("Room: Login Hall") + && payload.contains("Long: A narrow testing hall used for login verification.") + && payload.endsWith("> ")); assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)) - .hasValueSatisfying( - context -> { - assertThat(context.gameInstanceId()).isEqualTo(1L); - assertThat(context.characterId()).isEqualTo(123L); - assertThat(context.roomInstanceId()).isNotBlank(); - }); + .hasValueSatisfying(context -> { + assertThat(context.gameInstanceId()).isEqualTo(1L); + assertThat(context.characterId()).isEqualTo(123L); + assertThat(context.roomInstanceId()).isNotBlank(); + }); verify(commandService, never()).enqueue("41", "LOGIN demo@example.com swordfish", false); verify(commandService).enqueue("41", "LOOK", false); @@ -582,12 +572,11 @@ void websocketQuickLookUsesDistinctCommandLabelAndPrompt() throws Exception { assertThat(payloads).hasSizeGreaterThanOrEqualTo(3); assertThat(payloads) - .anyMatch( - payload -> - payload.startsWith("OK QUICKLOOK") - && payload.endsWith("> ") - && payload.contains("Room: Login Hall") - && !payload.contains("Long:")); + .anyMatch(payload -> + payload.startsWith("OK QUICKLOOK") + && payload.endsWith("> ") + && payload.contains("Room: Login Hall") + && !payload.contains("Long:")); verify(lookCacheService) .cache( eq(22L), @@ -694,13 +683,12 @@ void websocketAfkCommandUpdatesLiveGameplayPresence() throws Exception { java.time.Duration.ofSeconds(5), () -> { return Mockito.mockingDetails(commandService).getInvocations().stream() - .anyMatch( - invocation -> - invocation.getMethod().getName().equals("enqueue") - && invocation.getArguments().length == 3 - && "41".equals(invocation.getArguments()[0]) - && "AFK".equals(invocation.getArguments()[1]) - && Boolean.FALSE.equals(invocation.getArguments()[2])); + .anyMatch(invocation -> + invocation.getMethod().getName().equals("enqueue") + && invocation.getArguments().length == 3 + && "41".equals(invocation.getArguments()[0]) + && "AFK".equals(invocation.getArguments()[1]) + && Boolean.FALSE.equals(invocation.getArguments()[2])); }); GameplayAsyncAssertions.assertEventually( "AFK presence state", @@ -769,10 +757,9 @@ void websocketLocaleHeaderAppliesToBuiltInLookRendering() throws Exception { assertThat(payloads).hasSizeGreaterThanOrEqualTo(3); assertThat(payloads) - .anyMatch( - payload -> - payload.contains("Salle : Galerie") - && payload.contains("Court : Un couloir etroit file vers le sud.")); + .anyMatch(payload -> + payload.contains("Salle : Galerie") + && payload.contains("Court : Un couloir etroit file vers le sud.")); assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)) .hasValueSatisfying(context -> assertThat(context.localeTag()).isEqualTo("fr")); } @@ -789,11 +776,10 @@ void websocketMoveEnqueuesDurableCommandAfterPlay() throws Exception { java.time.Duration.ofSeconds(5), () -> { return org.mockito.Mockito.mockingDetails(commandService).getInvocations().stream() - .anyMatch( - invocation -> - "enqueue".equals(invocation.getMethod().getName()) - && java.util.List.of(invocation.getArguments()) - .equals(java.util.List.of("42", "north", false))); + .anyMatch(invocation -> + "enqueue".equals(invocation.getMethod().getName()) + && java.util.List.of(invocation.getArguments()) + .equals(java.util.List.of("42", "north", false))); }); payloads = client.responses(); } @@ -819,21 +805,18 @@ void websocketLoginCanBrowseRealmsButCharsStaysUnavailableBeforePlay() throws Ex assertThat(payloads).anyMatch(payload -> payload.startsWith("OK LOGIN")); assertThat(payloads) - .anyMatch( - payload -> - payload.startsWith("OK REALMS") - && payload.contains("Live Realm (production) [shared, allow_new]")); + .anyMatch(payload -> + payload.startsWith("OK REALMS") + && payload.contains("Live Realm (production) [shared, allow_new]")); assertThat(payloads) - .anyMatch( - payload -> - payload.startsWith("ERROR CHARACTER_LIST_UNAVAILABLE") - && payload.contains("known character name")); + .anyMatch(payload -> + payload.startsWith("ERROR CHARACTER_LIST_UNAVAILABLE") + && payload.contains("known character name")); assertThat(payloads) - .noneMatch( - payload -> - payload.startsWith("OK CHARS") - || payload.contains("Emberline [lvl") - || payload.contains("Sora [lvl")); + .noneMatch(payload -> + payload.startsWith("OK CHARS") + || payload.contains("Emberline [lvl") + || payload.contains("Sora [lvl")); verify(commandService, never()).enqueue("41", "LOGIN demo@example.com swordfish", false); verify(commandService, never()).enqueue("41", "REALMS demo", false); verify(commandService, never()).enqueue("41", "CHARS demo", false); @@ -1005,25 +988,22 @@ void websocketGenericRouteChangeOnReusedTransportClearsOldStateAndRefreshesBoots assertThat(payloads).anyMatch(payload -> payload.startsWith("ERROR LOGIN_REQUIRED")); assertThat(payloads).anyMatch(payload -> payload.startsWith("OK LOGIN")); assertThat(payloads) - .anyMatch( - payload -> - payload.startsWith("OK WORLDS") && !payload.contains("Builder Sandbox (sandbox)")); + .anyMatch(payload -> + payload.startsWith("OK WORLDS") && !payload.contains("Builder Sandbox (sandbox)")); assertThat(payloads) - .anyMatch( - payload -> - payload.startsWith("ERROR INVALID_ARGUMENT") - && payload.contains("REALMS requires a valid world selector")); + .anyMatch(payload -> + payload.startsWith("ERROR INVALID_ARGUMENT") + && payload.contains("REALMS requires a valid world selector")); assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)) - .hasValueSatisfying( - context -> { - assertThat(context.accountId()).isEqualTo(ACCOUNT_UUID); - assertThat(context.gameInstanceId()).isZero(); - assertThat(context.characterId()).isZero(); - assertThat(context.bootstrapGameInstanceId()).isEqualTo(2L); - assertThat(context.worldSlug()).isEqualTo("sandbox"); - assertThat(context.realmSlug()).isEqualTo("production"); - assertThat(context.pointerVersion()).isEqualTo(1L); - }); + .hasValueSatisfying(context -> { + assertThat(context.accountId()).isEqualTo(ACCOUNT_UUID); + assertThat(context.gameInstanceId()).isZero(); + assertThat(context.characterId()).isZero(); + assertThat(context.bootstrapGameInstanceId()).isEqualTo(2L); + assertThat(context.worldSlug()).isEqualTo("sandbox"); + assertThat(context.realmSlug()).isEqualTo("production"); + assertThat(context.pointerVersion()).isEqualTo(1L); + }); assertThat(gameplayPresenceService.findConnectedBySessionId(41L)).isEmpty(); } @@ -1079,11 +1059,10 @@ private void bumpProductionAdmissionPointer( long newGameInstanceId, boolean requiresCharacterSelection) { GameplayAdmissionPointerSnapshot currentPointer = gameplayAdmissionPointerAuthorityService.listPointers().stream() - .filter( - pointer -> - pointer.tenantId() == 22L - && "demo".equals(pointer.worldSlug()) - && "production".equals(pointer.realmSlug())) + .filter(pointer -> + pointer.tenantId() == 22L + && "demo".equals(pointer.worldSlug()) + && "production".equals(pointer.realmSlug())) .findFirst() .orElseThrow(); gameplayAdmissionPointerAuthorityService.upsertPointer( @@ -1149,9 +1128,8 @@ private void resetAdmissionPointers() { 0L, null)); assertThat(gameplayAdmissionPointerAuthorityService.listPointers()) - .filteredOn( - pointer -> - pointer.tenantId() == 22L && pointer.visible() && pointer.publicProductionRealm()) + .filteredOn(pointer -> + pointer.tenantId() == 22L && pointer.visible() && pointer.publicProductionRealm()) .extracting(GameplayAdmissionPointerSnapshot::worldSlug) .containsExactly("demo"); } @@ -1159,11 +1137,10 @@ private void resetAdmissionPointers() { @SuppressWarnings("unchecked") private static void stubTransactionExecution(RedisTemplate redisTemplate) { when(redisTemplate.execute(Mockito.any(SessionCallback.class))) - .thenAnswer( - invocation -> { - SessionCallback callback = invocation.getArgument(0); - return callback.execute((RedisOperations) redisTemplate); - }); + .thenAnswer(invocation -> { + SessionCallback callback = invocation.getArgument(0); + return callback.execute((RedisOperations) redisTemplate); + }); when(redisTemplate.exec()).thenReturn(List.of("OK")); } diff --git a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/cache/RedisScreenBufferServiceTest.java b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/cache/RedisScreenBufferServiceTest.java index 1d097e9d70..f183fcfc3f 100644 --- a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/cache/RedisScreenBufferServiceTest.java +++ b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/cache/RedisScreenBufferServiceTest.java @@ -47,11 +47,10 @@ class RedisScreenBufferServiceTest { void setUp() { when(redisTemplate.opsForValue()).thenReturn((ValueOperations) valueOperations); when(redisTemplate.execute(any(SessionCallback.class))) - .thenAnswer( - invocation -> { - SessionCallback callback = invocation.getArgument(0); - return callback.execute(redisOperations); - }); + .thenAnswer(invocation -> { + SessionCallback callback = invocation.getArgument(0); + return callback.execute(redisOperations); + }); when(redisOperations.opsForValue()).thenReturn((ValueOperations) valueOperations); doAnswer( invocation -> { @@ -178,12 +177,10 @@ void retainsSingleEntryWhoseCanonicalEnvelopeExceedsHardLimit() { cacheService.append(22L, 1L, 123L, List.of(oversized)); assertThat(cacheService.get(22L, 1L, 123L)) - .hasValueSatisfying( - screen -> { - assertThat(screen.messageCount()).isEqualTo(1); - assertThat(screen.entries().getFirst().payloadJson()) - .isEqualTo(oversized.payloadJson()); - }); + .hasValueSatisfying(screen -> { + assertThat(screen.messageCount()).isEqualTo(1); + assertThat(screen.entries().getFirst().payloadJson()).isEqualTo(oversized.payloadJson()); + }); } @Test @@ -202,13 +199,12 @@ void laterAppendEvictsOlderOversizedEntryToKeepTheWindowSingleEntry() { 22L, 1L, 123L, List.of(ScreenBufferService.BufferedEntry.fromText("CURRENT\n"))); assertThat(cacheService.get(22L, 1L, 123L)) - .hasValueSatisfying( - screen -> { - assertThat(screen.messageCount()).isEqualTo(1); - assertThat(screen.protocolText()).isEqualTo("CURRENT\n"); - assertThat(screen.entries().getFirst().payloadJson()) - .isNotEqualTo(oversized.payloadJson()); - }); + .hasValueSatisfying(screen -> { + assertThat(screen.messageCount()).isEqualTo(1); + assertThat(screen.protocolText()).isEqualTo("CURRENT\n"); + assertThat(screen.entries().getFirst().payloadJson()) + .isNotEqualTo(oversized.payloadJson()); + }); } @Test @@ -229,11 +225,10 @@ void trimsOldestEntryWhenConfiguredEntryLimitIsExceeded() { assertThat(limitedCache.get(22L, 1L, 123L)) .map(ScreenBufferService.BufferedScreen::protocolText) - .hasValueSatisfying( - transcript -> { - assertThat(transcript).contains("SECOND\n"); - assertThat(transcript).doesNotContain("FIRST\n"); - }); + .hasValueSatisfying(transcript -> { + assertThat(transcript).contains("SECOND\n"); + assertThat(transcript).doesNotContain("FIRST\n"); + }); } @Test @@ -291,13 +286,9 @@ void replaceLeavesTheExistingCacheVisibleWhenTheReplacementWriteFails() { .when(valueOperations) .set(eq(REDIS_KEY), anyString(), any(Duration.class)); - assertThatThrownBy( - () -> - cacheService.replace( - 22L, - 1L, - 123L, - List.of(ScreenBufferService.BufferedEntry.fromText("CURRENT\\n")))) + assertThatThrownBy(() -> + cacheService.replace( + 22L, 1L, 123L, List.of(ScreenBufferService.BufferedEntry.fromText("CURRENT\\n")))) .isInstanceOf(IllegalStateException.class) .hasMessage("Redis unavailable"); diff --git a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeysTest.java b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeysTest.java index 90231c1bf7..9c4418c245 100644 --- a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeysTest.java +++ b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionRedisKeysTest.java @@ -37,10 +37,9 @@ void projectionIsStableAndIncludesTheFullOwnerScope() { @Test void projectionRejectsNilScopeIdentifiers() { - assertThatThrownBy( - () -> - CanonicalGameplayRegionRedisKeys.tenantRegionTag( - TENANT_ID, new UUID(0L, 0L), REGION_ID)) + assertThatThrownBy(() -> + CanonicalGameplayRegionRedisKeys.tenantRegionTag( + TENANT_ID, new UUID(0L, 0L), REGION_ID)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("gameInstanceId"); } diff --git a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java index 7af02dc9a4..7e1a33a32e 100644 --- a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java +++ b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java @@ -84,9 +84,8 @@ public void removeBySessionId(long sessionId) { public List listConnectedByGameInstance(long tenantId, long gameInstanceId) { List matches = presences.values().stream() - .filter( - presence -> - presence.tenantId() == tenantId && presence.gameInstanceId() == gameInstanceId) + .filter(presence -> + presence.tenantId() == tenantId && presence.gameInstanceId() == gameInstanceId) .sorted(ordering()) .toList(); return List.copyOf(matches); @@ -105,10 +104,9 @@ public Map> listConnectedByAccountIds( } List matches = presences.values().stream() - .filter( - presence -> - presence.tenantId() == tenantId - && Objects.equals(presence.accountId(), accountId)) + .filter(presence -> + presence.tenantId() == tenantId + && Objects.equals(presence.accountId(), accountId)) .sorted(ordering()) .toList(); if (!matches.isEmpty()) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAccountMemberRepairOperationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAccountMemberRepairOperationTest.java index bc7311e218..81b7b135ff 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAccountMemberRepairOperationTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/binding/CanonicalGameplayAccountMemberRepairOperationTest.java @@ -61,41 +61,39 @@ void rejectsCrossTenantBindingReferenceAndMemberThatDoesNotMatchFrozenTuple() { new CanonicalGameplayAccountIndexMember(reference, BigInteger.TEN, ACCOUNT_INDEX_FENCE) .value(); - assertThatThrownBy( - () -> - new CanonicalGameplayAccountMemberRepairOperation( - TRANSITION_ID, - OPERATION_ID, - BigInteger.ONE, - COVERAGE_FENCE, - BigInteger.valueOf(11), - reference, - ACCOUNT_ID, - UUID.fromString("77777777-7777-4777-8777-777777777777"), - BigInteger.TEN, - ACCOUNT_INDEX_FENCE, - obligation, - exactMember, - BigInteger.ZERO)) + assertThatThrownBy(() -> + new CanonicalGameplayAccountMemberRepairOperation( + TRANSITION_ID, + OPERATION_ID, + BigInteger.ONE, + COVERAGE_FENCE, + BigInteger.valueOf(11), + reference, + ACCOUNT_ID, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + BigInteger.TEN, + ACCOUNT_INDEX_FENCE, + obligation, + exactMember, + BigInteger.ZERO)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("bindingRef tenant segment"); - assertThatThrownBy( - () -> - new CanonicalGameplayAccountMemberRepairOperation( - TRANSITION_ID, - OPERATION_ID, - BigInteger.ONE, - COVERAGE_FENCE, - BigInteger.valueOf(11), - reference, - ACCOUNT_ID, - TENANT_ID, - BigInteger.TEN, - ACCOUNT_INDEX_FENCE, - obligation, - exactMember + "-foreign", - BigInteger.ZERO)) + assertThatThrownBy(() -> + new CanonicalGameplayAccountMemberRepairOperation( + TRANSITION_ID, + OPERATION_ID, + BigInteger.ONE, + COVERAGE_FENCE, + BigInteger.valueOf(11), + reference, + ACCOUNT_ID, + TENANT_ID, + BigInteger.TEN, + ACCOUNT_INDEX_FENCE, + obligation, + exactMember + "-foreign", + BigInteger.ZERO)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("member differs"); } @@ -103,32 +101,30 @@ void rejectsCrossTenantBindingReferenceAndMemberThatDoesNotMatchFrozenTuple() { @Test void requiresLaterEvidenceGenerationAndOriginalNewObligation() { CanonicalGameplayAccountMemberRepairOperation operation = operation(TENANT_ID); - assertThatThrownBy( - () -> - new CanonicalGameplayAccountMemberAcknowledgement( - operation, operation.inventorySnapshotRevision(), operation.member())) + assertThatThrownBy(() -> + new CanonicalGameplayAccountMemberAcknowledgement( + operation, operation.inventorySnapshotRevision(), operation.member())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("newer than"); CanonicalGameplayBindingRef reference = reference(TENANT_ID); - assertThatThrownBy( - () -> - new CanonicalGameplayAccountMemberRepairOperation( - TRANSITION_ID, - OPERATION_ID, - BigInteger.ONE, - COVERAGE_FENCE, - BigInteger.valueOf(11), - reference, - ACCOUNT_ID, - TENANT_ID, - BigInteger.TEN, - ACCOUNT_INDEX_FENCE, - obligation(reference, TENANT_ID, BigInteger.ONE), - new CanonicalGameplayAccountIndexMember( - reference, BigInteger.TEN, ACCOUNT_INDEX_FENCE) - .value(), - BigInteger.ZERO)) + assertThatThrownBy(() -> + new CanonicalGameplayAccountMemberRepairOperation( + TRANSITION_ID, + OPERATION_ID, + BigInteger.ONE, + COVERAGE_FENCE, + BigInteger.valueOf(11), + reference, + ACCOUNT_ID, + TENANT_ID, + BigInteger.TEN, + ACCOUNT_INDEX_FENCE, + obligation(reference, TENANT_ID, BigInteger.ONE), + new CanonicalGameplayAccountIndexMember( + reference, BigInteger.TEN, ACCOUNT_INDEX_FENCE) + .value(), + BigInteger.ZERO)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact outstanding NEW"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceServiceTest.java index c20073ee5d..1d7cad56bb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/charactercreate/GameSessionCharacterCreatePublicSourceServiceTest.java @@ -138,10 +138,9 @@ void resolvedCreatedSourceBindsActualSelectedTargetDescriptorAndAuthoredIdentity assertThat( GameSessionCharacterCreatePublicSourceService.ResolvedPlayerCreatedRosterSource.class .getDeclaredConstructors()) - .allSatisfy( - constructor -> - assertThat(java.lang.reflect.Modifier.isPrivate(constructor.getModifiers())) - .isTrue()); + .allSatisfy(constructor -> + assertThat(java.lang.reflect.Modifier.isPrivate(constructor.getModifiers())) + .isTrue()); } } @@ -156,14 +155,13 @@ void resolvedCreatedSourceRejectsMalformedDescriptorBindingAndChangedAuthoredRea invalidate.accept(fixture); assertThatThrownBy(() -> fixture.service.resolvePlayerCreatedRosterSource(rosterRequest())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION); - assertThat(Status.fromThrowable(failure).getDescription()) - .isEqualTo( - "Exact original public CHARACTER_CREATE source is unavailable or changed"); - }); + .satisfies(failure -> { + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(Status.fromThrowable(failure).getDescription()) + .isEqualTo( + "Exact original public CHARACTER_CREATE source is unavailable or changed"); + }); } } @@ -179,14 +177,13 @@ void resolvedCreatedSourceRejectsMalformedDescriptorBindingAndChangedAuthoredRea invalidate.accept(fixture); assertThatThrownBy(() -> fixture.service.resolvePlayerCreatedRosterSource(rosterRequest())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION); - assertThat(Status.fromThrowable(failure).getDescription()) - .isEqualTo( - "Exact original public CHARACTER_CREATE source is unavailable or changed"); - }); + .satisfies(failure -> { + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(Status.fromThrowable(failure).getDescription()) + .isEqualTo( + "Exact original public CHARACTER_CREATE source is unavailable or changed"); + }); } } } @@ -474,10 +471,9 @@ void entityRosterRejectsIndependentlyChangedWorldSelectorsAndImmutableReleaseFie invalidate.accept(fixture); assertThatThrownBy(() -> fixture.service.readPlayerCreatedRosterSource(rosterRequest())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); } } } @@ -488,11 +484,10 @@ void finalTargetRereadOccursAfterTheAdditionalPublishedPolicyOwnerCall() { var changed = mock(CanonicalPlayableTarget.class); when(changed.targetNamespace()).thenReturn("other"); when(fixture.publishedPolicies.listPublishedRealmEntryPolicies(TENANT, VERSION)) - .thenAnswer( - invocation -> { - when(fixture.routes.readCurrentTarget(TENANT)).thenReturn(changed); - return fixture.policySet; - }); + .thenAnswer(invocation -> { + when(fixture.routes.readCurrentTarget(TENANT)).thenReturn(changed); + return fixture.policySet; + }); assertThatThrownBy(() -> fixture.service.resolvePlayerCreatedRosterSource(rosterRequest())) .isInstanceOf(StatusRuntimeException.class); verify(fixture.gameDesign).read(any()); @@ -864,10 +859,9 @@ void accountSourceRejectsOverlengthSlugsBeforeReadingAnyOwner() { try (var fixture = new Fixture()) { assertThatThrownBy(() -> fixture.service.read(invalid)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.INVALID_ARGUMENT)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT)); verifyNoInteractions( fixture.routes, fixture.catalogs, @@ -1326,19 +1320,16 @@ private static final class Fixture implements AutoCloseable { .thenReturn("sha256:" + "1".repeat(64)); when(publicationTerminal.releaseContent().canonicalBytes()).thenReturn(new byte[] {8}); when(publishedPolicies.listPublishedRealmEntryPolicies(TENANT, VERSION)) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()) - .isFalse(); - return policySet; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return policySet; + }); when(gameDesign.read(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - return authored; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return authored; + }); sourceCodec .when(() -> AuthoredInitialActorCoreReadGrpcCodec.toResponse(authored)) .thenReturn( @@ -1347,12 +1338,11 @@ private static final class Fixture implements AutoCloseable { .setCanonicalResultBytes(ByteString.copyFrom(sourceBytes)) .build()); when(world.read(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - when(lifecycle.request()).thenReturn(invocation.getArgument(0)); - return lifecycle; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + when(lifecycle.request()).thenReturn(invocation.getArgument(0)); + return lifecycle; + }); when(lifecycle.lifecycleStatus()).thenReturn("ACTIVE"); when(lifecycle.lifecycleEpoch()).thenReturn(7L); when(lifecycle.launchBinding()).thenReturn(launchBinding); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java index ff8aed9ff4..7d1a5bd1ea 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountClientTest.java @@ -306,38 +306,35 @@ void directTextTargetRejectsMalformedRoutingEvidenceWithoutNormalizing() { } }; for (var fields : malformed) { - assertThatThrownBy( - () -> - new DirectTextConnectScopeTarget( - fields[0], fields[1], fields[2], fields[3], fields[4], fields[5], fields[6], - 7L, 4L)) + assertThatThrownBy(() -> + new DirectTextConnectScopeTarget( + fields[0], fields[1], fields[2], fields[3], fields[4], fields[5], fields[6], 7L, + 4L)) .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - new DirectTextConnectScopeTarget( - "22222222-2222-4222-8222-222222222222", - "world", - "realm", - target.realmId(), - target.playableStateNamespaceId(), - "SHARED", - "44444444-4444-4444-8444-444444444444", - 0L, - 4L)) + assertThatThrownBy(() -> + new DirectTextConnectScopeTarget( + "22222222-2222-4222-8222-222222222222", + "world", + "realm", + target.realmId(), + target.playableStateNamespaceId(), + "SHARED", + "44444444-4444-4444-8444-444444444444", + 0L, + 4L)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new DirectTextConnectScopeTarget( - "22222222-2222-4222-8222-222222222222", - "world", - "realm", - target.realmId(), - target.playableStateNamespaceId(), - "SHARED", - "44444444-4444-4444-8444-444444444444", - 7L, - -1L)) + assertThatThrownBy(() -> + new DirectTextConnectScopeTarget( + "22222222-2222-4222-8222-222222222222", + "world", + "realm", + target.realmId(), + target.playableStateNamespaceId(), + "SHARED", + "44444444-4444-4444-8444-444444444444", + 7L, + -1L)) .isInstanceOf(IllegalArgumentException.class); } @@ -725,11 +722,10 @@ void joinRechecksExpiryAfterInitialStubPreparationBeforeFirstDispatch() throws E var clock = new TestClock(JOIN_TEST_NOW); var fixture = newRetryFixture(clock); when(fixture.initialStub().withDeadlineAfter(5L, TimeUnit.SECONDS)) - .thenAnswer( - invocation -> { - clock.set(JOIN_TEST_NOW.plusSeconds(60)); - return fixture.initialStub(); - }); + .thenAnswer(invocation -> { + clock.set(JOIN_TEST_NOW.plusSeconds(60)); + return fixture.initialStub(); + }); assertThat(join(fixture.client(), directTextContext()).getError().getCode()) .isEqualTo("CONNECT_SCOPE_INVALID"); @@ -744,11 +740,10 @@ void joinExpiryAfterAmbiguityIsUnavailableNotNoCommitEvidence(String status) thr var clock = new TestClock(JOIN_TEST_NOW); var fixture = newRetryFixture(clock); when(fixture.initialStub().joinPublicProductionMembership(any())) - .thenAnswer( - invocation -> { - clock.set(JOIN_TEST_NOW.plusSeconds(60)); - throw Status.fromCode(Status.Code.valueOf(status)).asRuntimeException(); - }); + .thenAnswer(invocation -> { + clock.set(JOIN_TEST_NOW.plusSeconds(60)); + throw Status.fromCode(Status.Code.valueOf(status)).asRuntimeException(); + }); assertThat(join(fixture.client(), directTextContext()).getError().getCode()) .isEqualTo("AUTH_UNAVAILABLE"); @@ -765,11 +760,10 @@ void joinRechecksExpiryDuringChannelReloadBeforeRetry() throws Exception { when(fixture.initialStub().joinPublicProductionMembership(any())) .thenThrow(Status.UNAVAILABLE.asRuntimeException()); when(fixture.channelFactory().buildChannel(anyString(), anyInt(), any(), anyBoolean())) - .thenAnswer( - invocation -> { - clock.set(JOIN_TEST_NOW.plusSeconds(60)); - return mock(ManagedChannel.class); - }); + .thenAnswer(invocation -> { + clock.set(JOIN_TEST_NOW.plusSeconds(60)); + return mock(ManagedChannel.class); + }); assertThat(join(fixture.client(), directTextContext()).getError().getCode()) .isEqualTo("AUTH_UNAVAILABLE"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClientTest.java index 13619f2c12..5ca2bb685a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountGameplayAdmissionLeaseClientTest.java @@ -198,33 +198,29 @@ public void abortGameplayAdmissionLease( assertThat(acquireRequests.getFirst().getPresentedInitialGsaCompactJwt(0)).isEqualTo(JWT); assertThat(finalizeRequests) .singleElement() - .satisfies( - request -> { - assertThat(request.getOriginalLeaseEvidenceUtf8(0).toByteArray()) - .containsExactly(originalBytes); - assertThat(request.getBindingDecisionUuid(0)).isEqualTo(DECISION_ID.toString()); - }); + .satisfies(request -> { + assertThat(request.getOriginalLeaseEvidenceUtf8(0).toByteArray()) + .containsExactly(originalBytes); + assertThat(request.getBindingDecisionUuid(0)).isEqualTo(DECISION_ID.toString()); + }); assertThat(readRequests) .singleElement() - .satisfies( - request -> - assertThat(request.getOriginalLeaseEvidenceUtf8(0).toByteArray()) - .containsExactly(originalBytes)); + .satisfies(request -> + assertThat(request.getOriginalLeaseEvidenceUtf8(0).toByteArray()) + .containsExactly(originalBytes)); assertThat(abortRequests) .singleElement() - .satisfies( - request -> { - assertThat(request.getOriginalLeaseEvidenceUtf8(0).toByteArray()) - .containsExactly(originalBytes); - assertThat(request.getBindingDecisionUuidCount()).isZero(); - }); + .satisfies(request -> { + assertThat(request.getOriginalLeaseEvidenceUtf8(0).toByteArray()) + .containsExactly(originalBytes); + assertThat(request.getBindingDecisionUuidCount()).isZero(); + }); assertThat(deadlines) .hasSize(4) - .allSatisfy( - deadline -> { - long remainingMillis = deadline.timeRemaining(TimeUnit.MILLISECONDS); - assertThat(remainingMillis).isPositive().isLessThanOrEqualTo(5_000L); - }); + .allSatisfy(deadline -> { + long remainingMillis = deadline.timeRemaining(TimeUnit.MILLISECONDS); + assertThat(remainingMillis).isPositive().isLessThanOrEqualTo(5_000L); + }); assertThat(acquired.toString()).doesNotContain(JWT); } finally { stop(server); @@ -342,30 +338,27 @@ public void confirmOriginalNewGameplayAdmission( assertThat(observed).containsExactly(GAME_SESSION_PEER, GAME_SESSION_PEER); assertThat(issuedRequests) .singleElement() - .satisfies( - request -> { - assertThat(request.getPresentedInitialGsaCompactJwt(0)).isEqualTo(JWT); - assertThat(request.getOriginalLeaseEvidenceUtf8(0).toByteArray()) - .containsExactly(originalLease); - }); + .satisfies(request -> { + assertThat(request.getPresentedInitialGsaCompactJwt(0)).isEqualTo(JWT); + assertThat(request.getOriginalLeaseEvidenceUtf8(0).toByteArray()) + .containsExactly(originalLease); + }); assertThat(confirmation.lineageId()) .isEqualTo(UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")); assertThat(confirmation.continuityExpiresAtMillis()).isEqualTo(1_320_000L); assertThat(confirmationRequests) .singleElement() - .satisfies( - request -> { - assertThat(request.getPresentedInitialGsaCompactJwt(0)).isEqualTo(JWT); - assertThat(request.getOriginalLeaseEvidenceUtf8(0).toByteArray()) - .containsExactly(originalLease); - }); + .satisfies(request -> { + assertThat(request.getPresentedInitialGsaCompactJwt(0)).isEqualTo(JWT); + assertThat(request.getOriginalLeaseEvidenceUtf8(0).toByteArray()) + .containsExactly(originalLease); + }); assertThat(deadlines) .hasSize(2) - .allSatisfy( - deadline -> { - long remainingMillis = deadline.timeRemaining(TimeUnit.MILLISECONDS); - assertThat(remainingMillis).isPositive().isLessThanOrEqualTo(5_000L); - }); + .allSatisfy(deadline -> { + long remainingMillis = deadline.timeRemaining(TimeUnit.MILLISECONDS); + assertThat(remainingMillis).isPositive().isLessThanOrEqualTo(5_000L); + }); received.close(); java.util.Arrays.fill(originalLease, (byte) 0); } finally { @@ -430,13 +423,12 @@ public void issueOriginalNewGameplayCredential( .isInstanceOf(IllegalStateException.class) .hasMessage("Account returned invalid original-new credential evidence") .hasCauseInstanceOf(IllegalArgumentException.class) - .satisfies( - failure -> { - assertThat(failure.getCause()) - .hasMessage("Account credential result changed its original lease"); - assertThat(throwableText(failure)) - .doesNotContain(JWT, signedJwt, HexFormat.of().formatHex(handle)); - }); + .satisfies(failure -> { + assertThat(failure.getCause()) + .hasMessage("Account credential result changed its original lease"); + assertThat(throwableText(failure)) + .doesNotContain(JWT, signedJwt, HexFormat.of().formatHex(handle)); + }); assertThatThrownBy(parsed::opaqueRebindHandle) .isInstanceOf(IllegalStateException.class) .hasMessage("Credential result is closed"); @@ -661,13 +653,12 @@ public void acquireGameplayAdmissionLease( .isInstanceOf(IllegalStateException.class) .hasMessage("Account returned invalid gameplay admission lease evidence") .hasCauseInstanceOf(IllegalArgumentException.class) - .satisfies( - failure -> { - assertThat(failure.getCause()) - .hasMessage("Unsupported Account admission lease schema") - .hasNoCause(); - assertThat(throwableText(failure)).doesNotContain(JWT); - }); + .satisfies(failure -> { + assertThat(failure.getCause()) + .hasMessage("Unsupported Account admission lease schema") + .hasNoCause(); + assertThat(throwableText(failure)).doesNotContain(JWT); + }); } finally { stop(server); } @@ -678,19 +669,17 @@ void rejectsPlaintextNamespaceAndAmbientSqlOrSynchronizationBeforeRpc() throws E var endpoints = new ServiceEndpointsProperties(); var plaintext = new CommonGrpcClientProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionLeaseClient( - endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) + assertThatThrownBy(() -> + new AccountGameplayAdmissionLeaseClient( + endpoints, plaintext, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("requires workload mTLS"); - assertThatThrownBy( - () -> - new AccountGameplayAdmissionLeaseClient( - endpoints, - pki.clientProperties(directory, pki.identity("client")), - new GrpcChannelFactory(), - "bad namespace")) + assertThatThrownBy(() -> + new AccountGameplayAdmissionLeaseClient( + endpoints, + pki.clientProperties(directory, pki.identity("client")), + new GrpcChannelFactory(), + "bad namespace")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("namespace"); @@ -782,14 +771,12 @@ private static void assertSanitizedStatusFailure( assertThatThrownBy(operation::run) .isInstanceOf(IllegalStateException.class) .hasMessage(expectedMessage) - .satisfies( - failure -> { - assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expectedCode); - assertThat(failure.getCause()).isInstanceOf(StatusRuntimeException.class); - assertThat(Status.fromThrowable(failure.getCause()).getCode()) - .isEqualTo(expectedCode); - assertThat(throwableText(failure)).doesNotContain(JWT); - }); + .satisfies(failure -> { + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expectedCode); + assertThat(failure.getCause()).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(failure.getCause()).getCode()).isEqualTo(expectedCode); + assertThat(throwableText(failure)).doesNotContain(JWT); + }); } private static String throwableText(Throwable failure) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java index c5b7a76e55..c85c0b5e99 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AccountPlayerAdmissionEntitlementClientMtlsTest.java @@ -424,10 +424,9 @@ void directTextInvalidOrStaleInputsDiscloseNoCredential(String change) throws Ex refusal .isExactlyInstanceOf(StatusRuntimeException.class) .hasMessage("CANCELLED: Account player-admission entitlement read did not complete") - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.CANCELLED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.CANCELLED)); case "original-request", "original-context", "attempt-fence", @@ -650,10 +649,9 @@ void directTextRechecksLiveInputsAfterRpc(String change) throws Exception { case "custody" -> refusal .isExactlyInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.CANCELLED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.CANCELLED)); case "scope-expiry", "login-expiry" -> refusal .isExactlyInstanceOf(IllegalArgumentException.class) @@ -865,12 +863,11 @@ private static CanonicalGameplayLoginResult loginCustody(List borrowed) canonical(List.of())); when(login.evidence()).thenReturn(evidence); when(login.compactJwtBytes()) - .thenAnswer( - invocation -> { - byte[] bytes = JWT.getBytes(StandardCharsets.US_ASCII); - borrowed.add(bytes); - return bytes; - }); + .thenAnswer(invocation -> { + byte[] bytes = JWT.getBytes(StandardCharsets.US_ASCII); + borrowed.add(bytes); + return bytes; + }); return login; } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AutomationRuntimeFamilyCatalogClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AutomationRuntimeFamilyCatalogClientMtlsTest.java index eea605570d..61b103bae9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AutomationRuntimeFamilyCatalogClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/AutomationRuntimeFamilyCatalogClientMtlsTest.java @@ -217,13 +217,9 @@ public void readAutomationRuntimeFamilyCatalog( } var plaintext = new CommonGrpcClientProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new AutomationRuntimeFamilyCatalogClient( - new ServiceEndpointsProperties(), - plaintext, - new GrpcChannelFactory(), - NAMESPACE)) + assertThatThrownBy(() -> + new AutomationRuntimeFamilyCatalogClient( + new ServiceEndpointsProperties(), plaintext, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java index e97ac3d5e4..740aba3254 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java @@ -279,14 +279,13 @@ void expiredParentDeadlineAndInvalidSourceDenyBeforeTransportCall() throws Excep try (var expired = io.grpc.Context.current() .withDeadline(Deadline.after(-1, TimeUnit.NANOSECONDS), scheduler)) { - expired.run( - () -> - assertThatThrownBy(() -> client.authenticate(request(), () -> true)) - .isInstanceOfSatisfying( - StatusRuntimeException.class, - error -> - assertThat(error.getStatus().getCode()) - .isEqualTo(Status.Code.DEADLINE_EXCEEDED))); + expired.run(() -> + assertThatThrownBy(() -> client.authenticate(request(), () -> true)) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> + assertThat(error.getStatus().getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED))); } finally { scheduler.shutdownNow(); } @@ -311,17 +310,16 @@ void expiredParentDeadlineAndInvalidSourceDenyBeforeTransportCall() throws Excep void constructorRequiresMutualTlsAndExplicitInitialization() throws Exception { var tls = pki.clientProperties(temporaryDirectory); tls.setPlaintext(true); - assertThatThrownBy( - () -> - new CanonicalGameplayLoginAccountClient( - new ServiceEndpointsProperties(), - tls, - new GrpcChannelFactory(), - BlockingGrpcStubCustomizer.noop(), - "test", - Clock.systemUTC(), - Duration.ofSeconds(5), - mock(AccountAsymmetricJwtVerifier.class))) + assertThatThrownBy(() -> + new CanonicalGameplayLoginAccountClient( + new ServiceEndpointsProperties(), + tls, + new GrpcChannelFactory(), + BlockingGrpcStubCustomizer.noop(), + "test", + Clock.systemUTC(), + Duration.ofSeconds(5), + mock(AccountAsymmetricJwtVerifier.class))) .isInstanceOf(IllegalArgumentException.class); var factory = mock(GrpcChannelFactory.class); try (var uninitialized = @@ -516,36 +514,32 @@ void disposalInvalidRequestAndExpiredOrCancelledParentNeverReachTransport() thro var verifier = mock(AccountAsymmetricJwtVerifier.class); try (var client = client(server, Duration.ofSeconds(5), verifier)) { client.initialize(); - assertThatThrownBy( - () -> - client.retireInitialGameplayLogin( - disposalRequest().toBuilder().clearCallerContextId().build())) + assertThatThrownBy(() -> + client.retireInitialGameplayLogin( + disposalRequest().toBuilder().clearCallerContextId().build())) .isInstanceOf(InitialGameplayLoginDisposalResult.InvalidResultException.class); var scheduler = java.util.concurrent.Executors.newSingleThreadScheduledExecutor(); try (var expired = io.grpc.Context.current() .withDeadline(Deadline.after(-1, TimeUnit.NANOSECONDS), scheduler)) { - expired.run( - () -> - assertThatThrownBy(() -> client.retireInitialGameplayLogin(disposalRequest())) - .isInstanceOfSatisfying( - StatusRuntimeException.class, - error -> - assertThat(error.getStatus().getCode()) - .isEqualTo(Status.Code.DEADLINE_EXCEEDED))); + expired.run(() -> + assertThatThrownBy(() -> client.retireInitialGameplayLogin(disposalRequest())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> + assertThat(error.getStatus().getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED))); } finally { scheduler.shutdownNow(); } try (var cancelled = io.grpc.Context.current().withCancellation()) { cancelled.cancel(null); - cancelled.run( - () -> - assertThatThrownBy(() -> client.retireInitialGameplayLogin(disposalRequest())) - .isInstanceOfSatisfying( - StatusRuntimeException.class, - error -> - assertThat(error.getStatus().getCode()) - .isEqualTo(Status.Code.CANCELLED))); + cancelled.run(() -> + assertThatThrownBy(() -> client.retireInitialGameplayLogin(disposalRequest())) + .isInstanceOfSatisfying( + StatusRuntimeException.class, + error -> + assertThat(error.getStatus().getCode()).isEqualTo(Status.Code.CANCELLED))); } assertThat(starts.get()).isZero(); assertThat(requests).isEmpty(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java index 11f71d4f76..860b17ccec 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayRosterClientTest.java @@ -80,22 +80,21 @@ void sendsExactPublishedTargetWithAccountAndValidatesSourceSnapshot() throws Exc var route = publishedRoute(); var stub = mockStub(); when(stub.listPreseededRoster(any())) - .thenAnswer( - invocation -> { - CanonicalGameplayRosterRequest request = invocation.getArgument(0); - var actor = actor(ACTOR_UUID, "Pilot One"); - return CanonicalGameplayRosterResponse.newBuilder() - .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) - .setTarget(request.getExpectedTarget()) - .setSnapshotUuid(SNAPSHOT_UUID.toString()) - .setSnapshotDigest( - snapshotDigest( - ACCOUNT_UUID, - request.getExpectedTarget(), - List.of(ACTOR_UUID.toString(), "Pilot One"))) - .addActors(actor) - .build(); - }); + .thenAnswer(invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + var actor = actor(ACTOR_UUID, "Pilot One"); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest( + snapshotDigest( + ACCOUNT_UUID, + request.getExpectedTarget(), + List.of(ACTOR_UUID.toString(), "Pilot One"))) + .addActors(actor) + .build(); + }); var client = newClient(stub); var roster = client.listPreseededRoster(route, listContext()); @@ -152,10 +151,9 @@ void closedStoredAssignmentReferencesFailBeforeEntityRpcOrReceiptWrites() throws var stub = mockStub(); var owner = mockReferenceOwner(); when(owner.begin(any())) - .thenAnswer( - call -> - CanonicalGameplayRosterReferenceEvidence.response( - call.getArgument(0), 1L, uuid("12121212-1212-4212-8212-121212121212"), null)); + .thenAnswer(call -> + CanonicalGameplayRosterReferenceEvidence.response( + call.getArgument(0), 1L, uuid("12121212-1212-4212-8212-121212121212"), null)); when(owner.selectOriginal(any(), any())) .thenAnswer(call -> closedOriginal(call.getArgument(0), state, true)); var client = newClient(stub, owner); @@ -176,16 +174,15 @@ void recordedStoredRosterAndAssignmentReceiptsStillReplayWithoutEntityRpc() thro var rosterStub = mockStub(); var rosterOwner = mockReferenceOwner(); when(rosterOwner.begin(any())) - .thenAnswer( - call -> - closedOriginal( - call.getArgument(0), - new ClosedDereferenceState( - CanonicalGameplayRosterReferenceState - .CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RECORDED, - "", - false), - false)); + .thenAnswer(call -> + closedOriginal( + call.getArgument(0), + new ClosedDereferenceState( + CanonicalGameplayRosterReferenceState + .CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RECORDED, + "", + false), + false)); var replayedRoster = newClient(rosterStub, rosterOwner).listPreseededRoster(publishedRoute(), listContext()); assertThat(replayedRoster.snapshotUuid()).isEqualTo(SNAPSHOT_UUID); @@ -196,21 +193,19 @@ void recordedStoredRosterAndAssignmentReceiptsStillReplayWithoutEntityRpc() thro var assignmentStub = mockStub(); var assignmentOwner = mockReferenceOwner(); when(assignmentOwner.begin(any())) - .thenAnswer( - call -> - CanonicalGameplayRosterReferenceEvidence.response( - call.getArgument(0), 1L, uuid("12121212-1212-4212-8212-121212121212"), null)); + .thenAnswer(call -> + CanonicalGameplayRosterReferenceEvidence.response( + call.getArgument(0), 1L, uuid("12121212-1212-4212-8212-121212121212"), null)); when(assignmentOwner.selectOriginal(any(), any())) - .thenAnswer( - call -> - closedOriginal( - call.getArgument(0), - new ClosedDereferenceState( - CanonicalGameplayRosterReferenceState - .CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RECORDED, - "", - false), - true)); + .thenAnswer(call -> + closedOriginal( + call.getArgument(0), + new ClosedDereferenceState( + CanonicalGameplayRosterReferenceState + .CANONICAL_GAMEPLAY_ROSTER_REFERENCE_RECORDED, + "", + false), + true)); var assignmentClient = newClient(assignmentStub, assignmentOwner); var roster = validatedRoster(assignmentClient, assignmentStub); clearInvocations(assignmentStub, assignmentOwner); @@ -227,10 +222,9 @@ void rosterDispatchStopsWhenOriginalClosesBeforeReadStartedMark() throws Excepti var owner = mockReferenceOwner(); var closedBeforeDispatch = new IllegalStateException("original closed before dispatch"); when(owner.begin(any())) - .thenAnswer( - call -> - CanonicalGameplayRosterReferenceEvidence.response( - call.getArgument(0), 1L, uuid("12121212-1212-4212-8212-121212121212"), null)); + .thenAnswer(call -> + CanonicalGameplayRosterReferenceEvidence.response( + call.getArgument(0), 1L, uuid("12121212-1212-4212-8212-121212121212"), null)); doThrow(closedBeforeDispatch).when(owner).markRosterReadStarted(any()); var client = newClient(stub, owner); @@ -279,78 +273,67 @@ void rejectsMissingMalformedAndSubstitutedInitialExecutionContextBeforeRpc() thr assertThatThrownBy(() -> client.listPreseededRoster(publishedRoute(), null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("context is required"); - assertThatThrownBy( - () -> - client.listPreseededRoster( - publishedRoute(), listContext().toBuilder().setAccountId("not-a-uuid").build())) + assertThatThrownBy(() -> + client.listPreseededRoster( + publishedRoute(), listContext().toBuilder().setAccountId("not-a-uuid").build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("account_id"); - assertThatThrownBy( - () -> - client.listPreseededRoster( - publishedRoute(), listContext().toBuilder().setSessionId("").build())) + assertThatThrownBy(() -> + client.listPreseededRoster( + publishedRoute(), listContext().toBuilder().setSessionId("").build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("session_id"); - assertThatThrownBy( - () -> - client.listPreseededRoster( - publishedRoute(), listContext().toBuilder().setRequestId("not-a-uuid").build())) + assertThatThrownBy(() -> + client.listPreseededRoster( + publishedRoute(), listContext().toBuilder().setRequestId("not-a-uuid").build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("request_id"); - assertThatThrownBy( - () -> - client.listPreseededRoster( - publishedRoute(), - listContext().toBuilder() - .setPlayableStateNamespaceId(SNAPSHOT_UUID.toString()) - .build())) + assertThatThrownBy(() -> + client.listPreseededRoster( + publishedRoute(), + listContext().toBuilder() + .setPlayableStateNamespaceId(SNAPSHOT_UUID.toString()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("playable_state_namespace_id"); - assertThatThrownBy( - () -> - client.listPreseededRoster( - publishedRoute(), - listContext().toBuilder().setTenantId(ACCOUNT_UUID.toString()).build())) + assertThatThrownBy(() -> + client.listPreseededRoster( + publishedRoute(), + listContext().toBuilder().setTenantId(ACCOUNT_UUID.toString()).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("tenant_id"); - assertThatThrownBy( - () -> - client.listPreseededRoster( - publishedRoute(), - listContext().toBuilder().setRealmId(ACCOUNT_UUID.toString()).build())) + assertThatThrownBy(() -> + client.listPreseededRoster( + publishedRoute(), + listContext().toBuilder().setRealmId(ACCOUNT_UUID.toString()).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("realm_id"); - assertThatThrownBy( - () -> - client.listPreseededRoster( - publishedRoute(), - listContext().toBuilder().setGameInstanceId(ACCOUNT_UUID.toString()).build())) + assertThatThrownBy(() -> + client.listPreseededRoster( + publishedRoute(), + listContext().toBuilder().setGameInstanceId(ACCOUNT_UUID.toString()).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("game_instance_id"); - assertThatThrownBy( - () -> - client.listPreseededRoster( - publishedRoute(), listContext().toBuilder().setPlayableStateScope("2").build())) + assertThatThrownBy(() -> + client.listPreseededRoster( + publishedRoute(), listContext().toBuilder().setPlayableStateScope("2").build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact SHARED or ISOLATED"); - assertThatThrownBy( - () -> - client.listPreseededRoster( - publishedRoute(), - listContext().toBuilder().setPlayableStateScope("ISOLATED").build())) + assertThatThrownBy(() -> + client.listPreseededRoster( + publishedRoute(), + listContext().toBuilder().setPlayableStateScope("ISOLATED").build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("does not match the expected target"); - assertThatThrownBy( - () -> - client.listPreseededRoster( - publishedRoute(), - listContext().toBuilder().setCharacterId(ACTOR_UUID.toString()).build())) + assertThatThrownBy(() -> + client.listPreseededRoster( + publishedRoute(), + listContext().toBuilder().setCharacterId(ACTOR_UUID.toString()).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("must not select an actor"); - assertThatThrownBy( - () -> - client.listPreseededRoster( - publishedRoute(), listContext().toBuilder().setUnknownFields(unknown).build())) + assertThatThrownBy(() -> + client.listPreseededRoster( + publishedRoute(), listContext().toBuilder().setUnknownFields(unknown).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("unknown fields"); @@ -400,16 +383,15 @@ void matchesEntityOwnedRosterDigestV3GoldenVector() throws Exception { void rejectsChangedAccountAndCompleteTargetEcho() throws Exception { var stub = mockStub(); when(stub.listPreseededRoster(any())) - .thenAnswer( - invocation -> { - CanonicalGameplayRosterRequest request = invocation.getArgument(0); - return CanonicalGameplayRosterResponse.newBuilder() - .setCanonicalAccountUuid(TENANT_UUID.toString()) - .setTarget(request.getExpectedTarget()) - .setSnapshotUuid(SNAPSHOT_UUID.toString()) - .setSnapshotDigest("a".repeat(64)) - .build(); - }); + .thenAnswer(invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(TENANT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest("a".repeat(64)) + .build(); + }); assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) .isInstanceOf(IllegalStateException.class) @@ -436,27 +418,23 @@ void rejectsChangedAccountAndCompleteTargetEcho() throws Exception { void rejectsDuplicateMalformedAndUnsupportedActors() throws Exception { var stub = mockStub(); when(stub.listPreseededRoster(any())) - .thenAnswer( - invocation -> { - CanonicalGameplayRosterRequest request = invocation.getArgument(0); - var duplicate = actor(ACTOR_UUID, "Pilot One"); - return CanonicalGameplayRosterResponse.newBuilder() - .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) - .setTarget(request.getExpectedTarget()) - .setSnapshotUuid(SNAPSHOT_UUID.toString()) - .setSnapshotDigest( - snapshotDigest( - ACCOUNT_UUID, - request.getExpectedTarget(), - List.of( - ACTOR_UUID.toString(), - "Pilot One", - ACTOR_UUID.toString(), - "Pilot One"))) - .addActors(duplicate) - .addActors(duplicate) - .build(); - }); + .thenAnswer(invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + var duplicate = actor(ACTOR_UUID, "Pilot One"); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest( + snapshotDigest( + ACCOUNT_UUID, + request.getExpectedTarget(), + List.of( + ACTOR_UUID.toString(), "Pilot One", ACTOR_UUID.toString(), "Pilot One"))) + .addActors(duplicate) + .addActors(duplicate) + .build(); + }); assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) .isInstanceOf(IllegalStateException.class) @@ -507,17 +485,16 @@ void rejectsDuplicateMalformedAndUnsupportedActors() throws Exception { void rejectsBadSnapshotDigestAndPropagatesEntityTransportFailures() throws Exception { var stub = mockStub(); when(stub.listPreseededRoster(any())) - .thenAnswer( - invocation -> { - CanonicalGameplayRosterRequest request = invocation.getArgument(0); - return CanonicalGameplayRosterResponse.newBuilder() - .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) - .setTarget(request.getExpectedTarget()) - .setSnapshotUuid(SNAPSHOT_UUID.toString()) - .setSnapshotDigest("a".repeat(64)) - .addActors(actor(ACTOR_UUID, "Pilot One")) - .build(); - }); + .thenAnswer(invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest("a".repeat(64)) + .addActors(actor(ACTOR_UUID, "Pilot One")) + .build(); + }); assertThatThrownBy(() -> newClient(stub).listPreseededRoster(publishedRoute(), listContext())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("snapshot_digest does not bind"); @@ -551,11 +528,10 @@ void readsExactSelectedAssignmentAndReturnsBoundNonAdmissionCapability() throws var client = newClient(stub); var roster = validatedRoster(client, stub); when(stub.readSelectedPreseededAssignment(any())) - .thenAnswer( - invocation -> { - CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); - return selectedAssignmentResponse(request); - }); + .thenAnswer(invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + return selectedAssignmentResponse(request); + }); var verified = client.readSelectedPreseededAssignment(roster, selectedContext()); @@ -593,33 +569,28 @@ void rejectsSelectedContextAccountNamespaceAndActorSubstitutionBeforeRpc() throw var client = newClient(stub); var roster = validatedRoster(client, stub); - assertThatThrownBy( - () -> - client.readSelectedPreseededAssignment( - roster, - selectedContext().toBuilder().setAccountId(TENANT_UUID.toString()).build())) + assertThatThrownBy(() -> + client.readSelectedPreseededAssignment( + roster, selectedContext().toBuilder().setAccountId(TENANT_UUID.toString()).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("account does not match"); - assertThatThrownBy( - () -> - client.readSelectedPreseededAssignment( - roster, - selectedContext().toBuilder() - .setPlayableStateNamespaceId(SNAPSHOT_UUID.toString()) - .build())) + assertThatThrownBy(() -> + client.readSelectedPreseededAssignment( + roster, + selectedContext().toBuilder() + .setPlayableStateNamespaceId(SNAPSHOT_UUID.toString()) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("playable_state_namespace_id"); - assertThatThrownBy( - () -> - client.readSelectedPreseededAssignment( - roster, - selectedContext().toBuilder().setCharacterId(SNAPSHOT_UUID.toString()).build())) + assertThatThrownBy(() -> + client.readSelectedPreseededAssignment( + roster, + selectedContext().toBuilder().setCharacterId(SNAPSHOT_UUID.toString()).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exactly once"); - assertThatThrownBy( - () -> - client.readSelectedPreseededAssignment( - roster, selectedContext().toBuilder().setRequestId("not-a-uuid").build())) + assertThatThrownBy(() -> + client.readSelectedPreseededAssignment( + roster, selectedContext().toBuilder().setRequestId("not-a-uuid").build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("request_id"); @@ -633,25 +604,23 @@ void rejectsSelectedReadbackSnapshotUuidOrDigestSubstitution() throws Exception var roster = validatedRoster(client, stub); var responseNumber = new AtomicInteger(); when(stub.readSelectedPreseededAssignment(any())) - .thenAnswer( - invocation -> { - CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); - var response = selectedAssignmentResponse(request).toBuilder(); - return switch (responseNumber.getAndIncrement()) { - case 0 -> - response - .setSnapshot( - request.getExpectedSnapshot().toBuilder() - .setSnapshotUuid(ASSIGNMENT_UUID.toString())) - .build(); - default -> - response - .setSnapshot( - request.getExpectedSnapshot().toBuilder() - .setSnapshotDigest("a".repeat(64))) - .build(); - }; - }); + .thenAnswer(invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + var response = selectedAssignmentResponse(request).toBuilder(); + return switch (responseNumber.getAndIncrement()) { + case 0 -> + response + .setSnapshot( + request.getExpectedSnapshot().toBuilder() + .setSnapshotUuid(ASSIGNMENT_UUID.toString())) + .build(); + default -> + response + .setSnapshot( + request.getExpectedSnapshot().toBuilder().setSnapshotDigest("a".repeat(64))) + .build(); + }; + }); assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) .isInstanceOf(IllegalStateException.class) @@ -668,20 +637,19 @@ void rejectsChangedAssignmentCorrelationAccountActorAndCompleteTarget() throws E var roster = validatedRoster(client, stub); var responseNumber = new AtomicInteger(); when(stub.readSelectedPreseededAssignment(any())) - .thenAnswer( - invocation -> { - CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); - var response = selectedAssignmentResponse(request).toBuilder(); - return switch (responseNumber.getAndIncrement()) { - case 0 -> response.setRequestUuid(UUID.randomUUID().toString()).build(); - case 1 -> response.setCanonicalAccountUuid(TENANT_UUID.toString()).build(); - case 2 -> response.setSelectedCharacterUuid(SNAPSHOT_UUID.toString()).build(); - default -> - response - .setTarget(request.getExpectedTarget().toBuilder().setPointerVersion(99L)) - .build(); - }; - }); + .thenAnswer(invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + var response = selectedAssignmentResponse(request).toBuilder(); + return switch (responseNumber.getAndIncrement()) { + case 0 -> response.setRequestUuid(UUID.randomUUID().toString()).build(); + case 1 -> response.setCanonicalAccountUuid(TENANT_UUID.toString()).build(); + case 2 -> response.setSelectedCharacterUuid(SNAPSHOT_UUID.toString()).build(); + default -> + response + .setTarget(request.getExpectedTarget().toBuilder().setPointerVersion(99L)) + .build(); + }; + }); assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) .isInstanceOf(IllegalStateException.class) @@ -707,13 +675,10 @@ void rejectsUnknownFieldsAndMissingSelectedAssignmentFields() throws Exception { .addField(101, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) .build(); when(stub.readSelectedPreseededAssignment(any())) - .thenAnswer( - invocation -> { - CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); - return selectedAssignmentResponse(request).toBuilder() - .setUnknownFields(unknown) - .build(); - }); + .thenAnswer(invocation -> { + CanonicalGameplayRosterSelectedAssignmentRequest request = invocation.getArgument(0); + return selectedAssignmentResponse(request).toBuilder().setUnknownFields(unknown).build(); + }); assertThatThrownBy(() -> client.readSelectedPreseededAssignment(roster, selectedContext())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("unknown fields"); @@ -881,35 +846,28 @@ void refusesSelectedAssignmentReadInsideTransactionOrSynchronization() throws Ex void rejectsNilAccountBeforeClientUseAndRequiresWorkloadMtls() { var factory = mock(GrpcChannelFactory.class); var uninitialized = newClientWithoutStub(factory); - assertThatThrownBy( - () -> - uninitialized.listPreseededRoster( - publishedRoute(), - listContext().toBuilder().setAccountId(new UUID(0L, 0L).toString()).build())) + assertThatThrownBy(() -> + uninitialized.listPreseededRoster( + publishedRoute(), + listContext().toBuilder().setAccountId(new UUID(0L, 0L).toString()).build())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical non-nil"); verifyNoInteractions(factory); var plaintext = mtlsProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new CanonicalGameplayRosterClient( - new ServiceEndpointsProperties(), - plaintext, - factory, - NAMESPACE, - referenceOwner())) + assertThatThrownBy(() -> + new CanonicalGameplayRosterClient( + new ServiceEndpointsProperties(), plaintext, factory, NAMESPACE, referenceOwner())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mTLS"); - assertThatThrownBy( - () -> - new CanonicalGameplayRosterClient( - new ServiceEndpointsProperties(), - mtlsProperties(), - factory, - "invalid.ns", - referenceOwner())) + assertThatThrownBy(() -> + new CanonicalGameplayRosterClient( + new ServiceEndpointsProperties(), + mtlsProperties(), + factory, + "invalid.ns", + referenceOwner())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("one DNS label"); verifyNoInteractions(factory); @@ -1116,21 +1074,20 @@ private static CanonicalGameplayRosterClient.PreseededRosterSnapshot validatedRo CanonicalGameplayRosterClient client, CanonicalGameplayRosterServiceGrpc.CanonicalGameplayRosterServiceBlockingStub stub) { when(stub.listPreseededRoster(any())) - .thenAnswer( - invocation -> { - CanonicalGameplayRosterRequest request = invocation.getArgument(0); - return CanonicalGameplayRosterResponse.newBuilder() - .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) - .setTarget(request.getExpectedTarget()) - .setSnapshotUuid(SNAPSHOT_UUID.toString()) - .setSnapshotDigest( - snapshotDigest( - ACCOUNT_UUID, - request.getExpectedTarget(), - List.of(ACTOR_UUID.toString(), "Pilot One"))) - .addActors(actor(ACTOR_UUID, "Pilot One")) - .build(); - }); + .thenAnswer(invocation -> { + CanonicalGameplayRosterRequest request = invocation.getArgument(0); + return CanonicalGameplayRosterResponse.newBuilder() + .setCanonicalAccountUuid(ACCOUNT_UUID.toString()) + .setTarget(request.getExpectedTarget()) + .setSnapshotUuid(SNAPSHOT_UUID.toString()) + .setSnapshotDigest( + snapshotDigest( + ACCOUNT_UUID, + request.getExpectedTarget(), + List.of(ACTOR_UUID.toString(), "Pilot One"))) + .addActors(actor(ACTOR_UUID, "Pilot One")) + .build(); + }); return client.listPreseededRoster(publishedRoute(), listContext()); } @@ -1363,52 +1320,48 @@ private static CanonicalGameplayRosterClient newClientWithoutStub(GrpcChannelFac mock( net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferenceOwner.class); when(owner.begin(any())) - .thenAnswer( - call -> - net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence - .response( - call.getArgument(0), - 1L, - java.util.UUID.fromString("12121212-1212-4212-8212-121212121212"), - null)); + .thenAnswer(call -> + net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence.response( + call.getArgument(0), + 1L, + java.util.UUID.fromString("12121212-1212-4212-8212-121212121212"), + null)); when(owner.read(any())) - .thenAnswer( - call -> { - net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest - request = call.getArgument(0); - var receipt = - rosterResponse( - CanonicalGameplayRosterRequest.newBuilder() - .setExpectedTarget( - net.firedevops.firemud.common.world - .CanonicalGameplayRosterReferenceEvidence.target(request)) - .build(), - "Pilot One"); - return net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence - .response( - request, - 1L, - java.util.UUID.fromString("12121212-1212-4212-8212-121212121212"), - receipt); - }); + .thenAnswer(call -> { + net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest request = + call.getArgument(0); + var receipt = + rosterResponse( + CanonicalGameplayRosterRequest.newBuilder() + .setExpectedTarget( + net.firedevops.firemud.common.world + .CanonicalGameplayRosterReferenceEvidence.target(request)) + .build(), + "Pilot One"); + return net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence + .response( + request, + 1L, + java.util.UUID.fromString("12121212-1212-4212-8212-121212121212"), + receipt); + }); when(owner.selectOriginal(any(), any())) - .thenAnswer( - call -> { - net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest - request = call.getArgument(0); - UUID selectedCharacter = call.getArgument(1); - var original = owner.read(request); - return net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence - .requireResponse( - request, - original.toBuilder() - .setSelectionInput( - net.firedevops.firemud.gamesession.v1 - .CanonicalGameplayRosterSelectionInput.newBuilder() - .setSchemaVersion(1)) - .setSelectedCharacterUuid(selectedCharacter.toString()) - .build()); - }); + .thenAnswer(call -> { + net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest request = + call.getArgument(0); + UUID selectedCharacter = call.getArgument(1); + var original = owner.read(request); + return net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence + .requireResponse( + request, + original.toBuilder() + .setSelectionInput( + net.firedevops.firemud.gamesession.v1 + .CanonicalGameplayRosterSelectionInput.newBuilder() + .setSchemaVersion(1)) + .setSelectedCharacterUuid(selectedCharacter.toString()) + .build()); + }); var beans = new StaticListableBeanFactory(); beans.addBean("controlledReferenceOwner", owner); return beans.getBeanProvider( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java index 5394282f0e..2914429478 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalInitialPlayerLocationClientTest.java @@ -558,32 +558,28 @@ void actualStubPinsWorldPeerAndCarriesCompressionDeadlineAndClientIdentity() thr void constructorRejectsPlaintextMissingTlsAndInvalidNamespace() { var plaintext = tls.copy(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new CanonicalInitialPlayerLocationClient( - new ServiceEndpointsProperties(), plaintext, channels, NAMESPACE)) + assertThatThrownBy(() -> + new CanonicalInitialPlayerLocationClient( + new ServiceEndpointsProperties(), plaintext, channels, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); var classpath = tls.copy(); classpath.setCertChain("classpath:client.crt"); - assertThatThrownBy( - () -> - new CanonicalInitialPlayerLocationClient( - new ServiceEndpointsProperties(), classpath, channels, NAMESPACE)) + assertThatThrownBy(() -> + new CanonicalInitialPlayerLocationClient( + new ServiceEndpointsProperties(), classpath, channels, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); var missing = tls.copy(); missing.setCaCert(directory.resolve("missing-ca.crt").toString()); - assertThatThrownBy( - () -> - new CanonicalInitialPlayerLocationClient( - new ServiceEndpointsProperties(), missing, channels, NAMESPACE)) + assertThatThrownBy(() -> + new CanonicalInitialPlayerLocationClient( + new ServiceEndpointsProperties(), missing, channels, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new CanonicalInitialPlayerLocationClient( - new ServiceEndpointsProperties(), tls, channels, "bad/namespace")) + assertThatThrownBy(() -> + new CanonicalInitialPlayerLocationClient( + new ServiceEndpointsProperties(), tls, channels, "bad/namespace")) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java index bb13571b92..2c1fbb74d9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPlayerCreatedRosterClientTest.java @@ -94,52 +94,47 @@ void controlledComposition() throws Exception { when(stub.withDeadlineAfter(20L, TimeUnit.SECONDS)).thenReturn(stub); when(stub.withMaxInboundMessageSize(anyInt())).thenReturn(stub); when(stub.listPlayerCreatedRoster(any())) - .thenAnswer( - call -> { - outside(); - return fixture.roster(); - }); + .thenAnswer(call -> { + outside(); + return fixture.roster(); + }); when(stub.readSelectedPlayerCreatedCharacter(any())) - .thenAnswer( - call -> { - outside(); - return fixture.selected(); - }); + .thenAnswer(call -> { + outside(); + return fixture.selected(); + }); stored = new AtomicReference<>( CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( fixture.original(), 1, UUID.randomUUID(), null)); when(owner.begin(fixture.original())) - .thenAnswer( - call -> { - outside(); - return stored.get(); - }); + .thenAnswer(call -> { + outside(); + return stored.get(); + }); when(owner.recordPlayerCreated(fixture.original(), fixture.roster())) - .thenAnswer( - call -> { - outside(); - stored.set( - CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( - fixture.original(), - 1, - UUID.fromString(stored.get().getTargetFenceUuid()), - fixture.roster())); - return stored.get(); - }); + .thenAnswer(call -> { + outside(); + stored.set( + CanonicalGameplayRosterReferenceEvidence.playerCreatedResponse( + fixture.original(), + 1, + UUID.fromString(stored.get().getTargetFenceUuid()), + fixture.roster())); + return stored.get(); + }); when(owner.selectOriginal( fixture.original(), UUID.fromString(fixture.selected().getSelectedCharacterUuid()))) - .thenAnswer( - call -> { - outside(); - stored.set( - stored.get().toBuilder() - .setSelectionInput( - CanonicalGameplayRosterSelectionInput.newBuilder().setSchemaVersion(1)) - .setSelectedCharacterUuid(fixture.selected().getSelectedCharacterUuid()) - .build()); - return stored.get(); - }); + .thenAnswer(call -> { + outside(); + stored.set( + stored.get().toBuilder() + .setSelectionInput( + CanonicalGameplayRosterSelectionInput.newBuilder().setSchemaVersion(1)) + .setSelectedCharacterUuid(fixture.selected().getSelectedCharacterUuid()) + .build()); + return stored.get(); + }); doAnswer( call -> { outside(); @@ -246,10 +241,8 @@ void reserveAndCompleteUseExactCreatedOriginalAndClosedInput() throws Exception assertThatThrownBy( () -> client.reserveSelectionInput(source, fixture.context(), "1", null, "invalid")) .isInstanceOf(NullPointerException.class); - assertThatThrownBy( - () -> - client.reserveSelectionInput( - source, fixture.context(), "x".repeat(129), null, null)) + assertThatThrownBy(() -> + client.reserveSelectionInput(source, fixture.context(), "x".repeat(129), null, null)) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(stub); } @@ -522,25 +515,15 @@ void wrappersHaveOnlyPrivateConstructorsAndTlsConfigurationIsRequired() { } var plaintext = new CommonGrpcClientProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new CanonicalPlayerCreatedRosterClient( - new ServiceEndpointsProperties(), - plaintext, - channels, - fixture.namespace(), - owner)) + assertThatThrownBy(() -> + new CanonicalPlayerCreatedRosterClient( + new ServiceEndpointsProperties(), plaintext, channels, fixture.namespace(), owner)) .isInstanceOf(IllegalArgumentException.class); var classpath = tls.copy(); classpath.setCertChain("classpath:client.crt"); - assertThatThrownBy( - () -> - new CanonicalPlayerCreatedRosterClient( - new ServiceEndpointsProperties(), - classpath, - channels, - fixture.namespace(), - owner)) + assertThatThrownBy(() -> + new CanonicalPlayerCreatedRosterClient( + new ServiceEndpointsProperties(), classpath, channels, fixture.namespace(), owner)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClientTest.java index 79ca2812ba..09d5b97545 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalPreseededActorAssignmentClientTest.java @@ -268,32 +268,28 @@ void actualStubPinsEntityPeerAndCarriesCompressionDeadlineAndClientIdentity() th void constructorRejectsPlaintextMissingTlsAndInvalidNamespace() { var plaintext = tls.copy(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new CanonicalPreseededActorAssignmentClient( - new ServiceEndpointsProperties(), plaintext, channels, NAMESPACE)) + assertThatThrownBy(() -> + new CanonicalPreseededActorAssignmentClient( + new ServiceEndpointsProperties(), plaintext, channels, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); var classpath = tls.copy(); classpath.setCertChain("classpath:client.crt"); - assertThatThrownBy( - () -> - new CanonicalPreseededActorAssignmentClient( - new ServiceEndpointsProperties(), classpath, channels, NAMESPACE)) + assertThatThrownBy(() -> + new CanonicalPreseededActorAssignmentClient( + new ServiceEndpointsProperties(), classpath, channels, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); var missing = tls.copy(); missing.setCaCert(directory.resolve("missing-ca.crt").toString()); - assertThatThrownBy( - () -> - new CanonicalPreseededActorAssignmentClient( - new ServiceEndpointsProperties(), missing, channels, NAMESPACE)) + assertThatThrownBy(() -> + new CanonicalPreseededActorAssignmentClient( + new ServiceEndpointsProperties(), missing, channels, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new CanonicalPreseededActorAssignmentClient( - new ServiceEndpointsProperties(), tls, channels, "bad/namespace")) + assertThatThrownBy(() -> + new CanonicalPreseededActorAssignmentClient( + new ServiceEndpointsProperties(), tls, channels, "bad/namespace")) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/DirectTextIssuedConnectScopeTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/DirectTextIssuedConnectScopeTest.java index 91158e2764..b4ae17ec63 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/DirectTextIssuedConnectScopeTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/DirectTextIssuedConnectScopeTest.java @@ -42,13 +42,12 @@ void enforcesExpiryAtTheExactAccountExpiryBoundary() { assertThat(scope.isLive(clock(Instant.parse("2026-08-02T00:01:59.999999999Z")))).isTrue(); assertThat(scope.isLive(clock(Instant.parse(EXPIRES_AT)))).isFalse(); - assertThatThrownBy( - () -> - DirectTextIssuedConnectScope.fromAccountResponse( - ACCOUNT_ID, - target(), - response("scope", EVALUATED_AT, EXPIRES_AT), - clock(Instant.parse(EXPIRES_AT)))) + assertThatThrownBy(() -> + DirectTextIssuedConnectScope.fromAccountResponse( + ACCOUNT_ID, + target(), + response("scope", EVALUATED_AT, EXPIRES_AT), + clock(Instant.parse(EXPIRES_AT)))) .isInstanceOf(IllegalArgumentException.class); } @@ -130,10 +129,8 @@ private static void assertRejected( String accountId, DirectTextConnectScopeTarget target, Clock clock) { - assertThatThrownBy( - () -> - DirectTextIssuedConnectScope.fromAccountResponse( - accountId, target, response, clock)) + assertThatThrownBy(() -> + DirectTextIssuedConnectScope.fromAccountResponse(accountId, target, response, clock)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java index dd5dcd8c30..58b9f60fea 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java @@ -134,10 +134,9 @@ public > T customize(T stub) { }) void rosterReadRejectsNonCanonicalAccountBeforeTransport(String accountId) { EntityManagementClient client = newClient(); - assertThatThrownBy( - () -> - client.listCharactersByAccount( - "22", accountId, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) + assertThatThrownBy(() -> + client.listCharactersByAccount( + "22", accountId, "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) .isInstanceOf(IllegalArgumentException.class); } @@ -223,10 +222,9 @@ void findCharacterByNameRejectsLegacyRuntimeRoomIdsInSessionContextBeforeDispatc SESSION_CONTEXT.pointerVersion(), SESSION_CONTEXT.playableStateScope()); - assertThatThrownBy( - () -> - client.findCharacterByName( - legacyRoomContext, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, "Emberline")) + assertThatThrownBy(() -> + client.findCharacterByName( + legacyRoomContext, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, "Emberline")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("roomInstanceId must be a runtime room id like R-1021"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClientMtlsTest.java index 21143a911a..11410192d3 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityRuntimeFamilyCatalogClientMtlsTest.java @@ -209,10 +209,9 @@ public void readEntityRuntimeFamilyCatalog( } var tls = new CommonGrpcClientProperties(); tls.setPlaintext(true); - assertThatThrownBy( - () -> - new EntityRuntimeFamilyCatalogClient( - new ServiceEndpointsProperties(), tls, new GrpcChannelFactory(), NAMESPACE)) + assertThatThrownBy(() -> + new EntityRuntimeFamilyCatalogClient( + new ServiceEndpointsProperties(), tls, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientTest.java index 83c5d76ae1..26c62d0148 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignFreshTenantCreationClientTest.java @@ -81,10 +81,9 @@ void rejectsInvalidWorkloadNamespaceBeforeChannelCreation(@TempDir Path director throws Exception { GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); - assertThatThrownBy( - () -> - new GameDesignFreshTenantCreationClient( - new ServiceEndpointsProperties(), tls(directory), channelFactory, " ")) + assertThatThrownBy(() -> + new GameDesignFreshTenantCreationClient( + new ServiceEndpointsProperties(), tls(directory), channelFactory, " ")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("one DNS label"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientMtlsTest.java index 340bc79c00..ba214da064 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientMtlsTest.java @@ -134,11 +134,9 @@ public ServerCall.Listener interceptCall( .isEqualTo("spiffe://firemud/ns/test/sa/game-session-service"); assertThat(observedRequest.get().getTargetNamespace()).isEqualTo("test"); } else { - assertThatThrownBy( - () -> - client.listPublishedRealmEntryPolicies( - evidence.target().canonicalTenantId(), - evidence.target().canonicalVersionId())) + assertThatThrownBy(() -> + client.listPublishedRealmEntryPolicies( + evidence.target().canonicalTenantId(), evidence.target().canonicalVersionId())) .isInstanceOfSatisfying( StatusRuntimeException.class, failure -> diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java index 9df3bf5565..2053b93f75 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameDesignPublishedRealmPolicyClientTest.java @@ -46,13 +46,12 @@ void returnsCompleteTypedEvidenceAndSendsExactRequestWithDeadline() throws Excep var evidence = evidence(); var stub = mockStub(); when(stub.listPublishedRealmEntryPolicies(any())) - .thenAnswer( - invocation -> { - var request = - PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( - invocation.getArgument(0, ListPublishedRealmEntryPoliciesRequest.class)); - return PublishedRealmEntryPolicyReadGrpcCodec.toResponse(request, evidence); - }); + .thenAnswer(invocation -> { + var request = + PublishedRealmEntryPolicyReadGrpcCodec.fromRequest( + invocation.getArgument(0, ListPublishedRealmEntryPoliciesRequest.class)); + return PublishedRealmEntryPolicyReadGrpcCodec.toResponse(request, evidence); + }); var client = newClient(stub); PublishedRealmEntryPolicySetEvidence result = @@ -112,15 +111,13 @@ void rejectsChangedRequestUnknownFieldsAndMalformedClosedEvidence() throws Excep var expectedEvidence = evidence(); var stub = mockStub(); when(stub.listPublishedRealmEntryPolicies(any())) - .thenAnswer( - invocation -> { - ListPublishedRealmEntryPoliciesRequest request = invocation.getArgument(0); - return ListPublishedRealmEntryPoliciesResponse.newBuilder() - .setRequest( - request.toBuilder().setCanonicalVersionId(TENANT_ID.toString()).build()) - .setPolicySetEvidence(ByteString.copyFrom(expectedEvidence.canonicalBytes())) - .build(); - }); + .thenAnswer(invocation -> { + ListPublishedRealmEntryPoliciesRequest request = invocation.getArgument(0); + return ListPublishedRealmEntryPoliciesResponse.newBuilder() + .setRequest(request.toBuilder().setCanonicalVersionId(TENANT_ID.toString()).build()) + .setPolicySetEvidence(ByteString.copyFrom(expectedEvidence.canonicalBytes())) + .build(); + }); assertThatThrownBy(() -> newClient(stub).listPublishedRealmEntryPolicies(TENANT_ID, VERSION_ID)) .isInstanceOf(GameDesignPublishedRealmPolicyClient.InvalidResponseException.class) .hasMessageContaining("response is invalid"); @@ -207,31 +204,27 @@ void rejectsPlaintextIncompleteClasspathTlsAndInvalidNamespaceBeforeChannelCreat var channelFactory = mock(GrpcChannelFactory.class); var plaintext = mtlsProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new GameDesignPublishedRealmPolicyClient( - new ServiceEndpointsProperties(), plaintext, channelFactory, NAMESPACE)) + assertThatThrownBy(() -> + new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mTLS"); - assertThatThrownBy( - () -> - new GameDesignPublishedRealmPolicyClient( - new ServiceEndpointsProperties(), null, channelFactory, NAMESPACE)) + assertThatThrownBy(() -> + new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), null, channelFactory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("TLS configuration is required"); var classpath = mtlsProperties(); classpath.setPrivateKey("classpath:certs/client.key"); - assertThatThrownBy( - () -> - new GameDesignPublishedRealmPolicyClient( - new ServiceEndpointsProperties(), classpath, channelFactory, NAMESPACE)) + assertThatThrownBy(() -> + new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), classpath, channelFactory, NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("file-backed"); - assertThatThrownBy( - () -> - new GameDesignPublishedRealmPolicyClient( - new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, "bad.ns")) + assertThatThrownBy(() -> + new GameDesignPublishedRealmPolicyClient( + new ServiceEndpointsProperties(), mtlsProperties(), channelFactory, "bad.ns")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("one DNS label"); verifyNoInteractions(channelFactory); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java index a6829bbf01..55429f33f5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java @@ -429,17 +429,16 @@ void sendCommunicationRejectsInvalidAccountUuidBeforeRpc() throws Exception { setStub(client, stub); for (String accountId : INVALID_ACCOUNT_IDS) { - assertThatThrownBy( - () -> - client.sendCommunication( - sessionContextWithAccountId(accountId), - "Sora", - "R-1021", - CommunicationType.SAY, - "hello", - null, - null, - null)) + assertThatThrownBy(() -> + client.sendCommunication( + sessionContextWithAccountId(accountId), + "Sora", + "R-1021", + CommunicationType.SAY, + "hello", + null, + null, + null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical non-nil Account UUID"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GrpcAccountStartSessionAdmissionProtectionClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GrpcAccountStartSessionAdmissionProtectionClientMtlsTest.java index 88cc21dd2f..f757a66e87 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GrpcAccountStartSessionAdmissionProtectionClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GrpcAccountStartSessionAdmissionProtectionClientMtlsTest.java @@ -112,10 +112,9 @@ void rejectsSameCaServerWithWrongWorkloadBeforeSendingRequest() throws Exception assertThat(failure) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - thrown -> - assertThat(((StatusRuntimeException) thrown).getStatus().getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(thrown -> + assertThat(((StatusRuntimeException) thrown).getStatus().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(rpcCalls).hasValue(0); assertThat(receivedRequest.get()).isNull(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GrpcAccountStartSessionAdmissionProtectionClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GrpcAccountStartSessionAdmissionProtectionClientTest.java index 18bc778633..31aeec82fd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GrpcAccountStartSessionAdmissionProtectionClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GrpcAccountStartSessionAdmissionProtectionClientTest.java @@ -19,18 +19,16 @@ void requiresFileBackedMutualTlsAndCanonicalNamespace() throws Exception { var plaintext = new CommonGrpcClientProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new GrpcAccountStartSessionAdmissionProtectionClient( - endpoints, plaintext, new GrpcChannelFactory(), "world-runtime")) + assertThatThrownBy(() -> + new GrpcAccountStartSessionAdmissionProtectionClient( + endpoints, plaintext, new GrpcChannelFactory(), "world-runtime")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("requires workload mTLS"); CommonGrpcClientProperties tls = fileBackedProperties(); - assertThatThrownBy( - () -> - new GrpcAccountStartSessionAdmissionProtectionClient( - endpoints, tls, new GrpcChannelFactory(), "WORLD")) + assertThatThrownBy(() -> + new GrpcAccountStartSessionAdmissionProtectionClient( + endpoints, tls, new GrpcChannelFactory(), "WORLD")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Canonical Game Session workload namespace"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/SocialRuntimeFamilyCatalogClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/SocialRuntimeFamilyCatalogClientMtlsTest.java index 0c3b6dd1f0..60a0c538c4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/SocialRuntimeFamilyCatalogClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/SocialRuntimeFamilyCatalogClientMtlsTest.java @@ -204,10 +204,9 @@ public void readSocialRuntimeFamilyCatalog( } var tls = new CommonGrpcClientProperties(); tls.setPlaintext(true); - assertThatThrownBy( - () -> - new SocialRuntimeFamilyCatalogClient( - new ServiceEndpointsProperties(), tls, new GrpcChannelFactory(), NAMESPACE)) + assertThatThrownBy(() -> + new SocialRuntimeFamilyCatalogClient( + new ServiceEndpointsProperties(), tls, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientMtlsTest.java index 0628386957..8d38d72a08 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientMtlsTest.java @@ -159,10 +159,9 @@ void sameCaWrongWorkloadAndWrongNamespaceAccountServersReceiveNoRedemptionRpc() assertThat(failure) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - thrown -> - assertThat(((StatusRuntimeException) thrown).getStatus().getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)) + .satisfies(thrown -> + assertThat(((StatusRuntimeException) thrown).getStatus().getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)) .hasMessageNotContaining(REFERENCE); assertThat(rpcStarts).hasValue(0); assertThat(applicationCalls).hasValue(0); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java index 5dee2bc327..8bed7ddf87 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java @@ -160,18 +160,17 @@ void rejectsMismatchedClaimAndExpiredAuthorityBeforeCallingAccount() throws Exce StartSessionOperatorRedemptionClient client = newClient(stub, CURRENT_CLOCK); StartSessionPostAuthorizationExecutionTuple tuple = tuple(REQUEST_ID); - assertThatThrownBy( - () -> - client.redeem( - tuple, - OPAQUE_REFERENCE, - new AttemptClaim( - "another-namespace", - REQUEST_ID, - OWNER_ATTEMPT, - OWNER_MUTATION, - CLAIM_OWNER, - 37L))) + assertThatThrownBy(() -> + client.redeem( + tuple, + OPAQUE_REFERENCE, + new AttemptClaim( + "another-namespace", + REQUEST_ID, + OWNER_ATTEMPT, + OWNER_MUTATION, + CLAIM_OWNER, + 37L))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("claim differs"); @@ -258,29 +257,27 @@ void letsRedemptionTimeoutRemainAmbiguousWithoutAutomaticRetryOrTerminalization( void refusesPlaintextOrMissingMutualTlsCredentialsAndDoesNotInitializeByConstruction() { CommonGrpcClientProperties plaintext = tlsProperties(); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new StartSessionOperatorRedemptionClient( - new ServiceEndpointsProperties(), - plaintext, - mock(GrpcChannelFactory.class), - BlockingGrpcStubCustomizer.noop(), - NAMESPACE, - CURRENT_CLOCK)) + assertThatThrownBy(() -> + new StartSessionOperatorRedemptionClient( + new ServiceEndpointsProperties(), + plaintext, + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + NAMESPACE, + CURRENT_CLOCK)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mutual TLS"); CommonGrpcClientProperties missingIdentity = new CommonGrpcClientProperties(); missingIdentity.setCaCert("ca.pem"); - assertThatThrownBy( - () -> - new StartSessionOperatorRedemptionClient( - new ServiceEndpointsProperties(), - missingIdentity, - mock(GrpcChannelFactory.class), - BlockingGrpcStubCustomizer.noop(), - NAMESPACE, - CURRENT_CLOCK)) + assertThatThrownBy(() -> + new StartSessionOperatorRedemptionClient( + new ServiceEndpointsProperties(), + missingIdentity, + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + NAMESPACE, + CURRENT_CLOCK)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mutual TLS"); @@ -290,15 +287,14 @@ void refusesPlaintextOrMissingMutualTlsCredentialsAndDoesNotInitializeByConstruc .isInstanceOf(IllegalStateException.class) .hasMessageContaining("explicitly initialized"); - assertThatThrownBy( - () -> - new StartSessionOperatorRedemptionClient( - new ServiceEndpointsProperties(), - tlsProperties(), - mock(GrpcChannelFactory.class), - BlockingGrpcStubCustomizer.noop(), - "Invalid_Namespace", - CURRENT_CLOCK)) + assertThatThrownBy(() -> + new StartSessionOperatorRedemptionClient( + new ServiceEndpointsProperties(), + tlsProperties(), + mock(GrpcChannelFactory.class), + BlockingGrpcStubCustomizer.noop(), + "Invalid_Namespace", + CURRENT_CLOCK)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical DNS label"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClientTest.java index 64a371a80e..5b362a59fc 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClientTest.java @@ -151,10 +151,9 @@ void rejectsWrongServerWorkloadBeforeRequestAndRejectsEmptyOrUnknownResponses() client.init(); assertThatThrownBy(() -> client.readIdentity(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(serverCallStarts).hasValue(0); assertThat(applicationCalls).hasValue(0); stopTransport(); @@ -217,12 +216,10 @@ void requiresExplicitInitializationConfiguredNamespaceMatchingAndNoAmbientTransa assertThatThrownBy(() -> client.acquire(request, lifecycleRequest("other"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact initial-admission target"); - assertThatThrownBy( - () -> - client.readState( - identity, - lifecycleRequest( - NAMESPACE, true, uuid("99999999-9999-4999-8999-999999999999")))) + assertThatThrownBy(() -> + client.readState( + identity, + lifecycleRequest(NAMESPACE, true, uuid("99999999-9999-4999-8999-999999999999")))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact initial-admission target"); assertThatThrownBy(() -> lifecycleRequest(NAMESPACE, false)) @@ -363,10 +360,9 @@ void stateReadRejectsWrongPeerCorrelationAndUnknownResponseFieldsBeforeAccepting client.init(); assertThatThrownBy(() -> client.readState(identity, lifecycle)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); assertThat(serverCallStarts).hasValue(0); assertThat(applicationCalls).hasValue(0); stopTransport(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldManagementClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldManagementClientTest.java index 36d16b3615..76747b3a8d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldManagementClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldManagementClientTest.java @@ -74,33 +74,31 @@ void initialAdmissionHoldRequestCarriesExactTypedNoPriorPointerTuple() { @Test void initialAdmissionHoldRequestRejectsUnspecifiedScopeAndIncompleteTuple() { - assertThatThrownBy( - () -> - WorldManagementClient.buildAcquireInitialAdmissionBindHoldRequest( - 7L, - 42L, - 11L, - 4L, - "request-id", - "a".repeat(64), - UUID.randomUUID(), - UUID.randomUUID(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED, - 3L)) + assertThatThrownBy(() -> + WorldManagementClient.buildAcquireInitialAdmissionBindHoldRequest( + 7L, + 42L, + 11L, + 4L, + "request-id", + "a".repeat(64), + UUID.randomUUID(), + UUID.randomUUID(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED, + 3L)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldManagementClient.buildAcquireInitialAdmissionBindHoldRequest( - 7L, - 42L, - 11L, - 4L, - "request-id", - "a".repeat(64), - null, - UUID.randomUUID(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - 3L)) + assertThatThrownBy(() -> + WorldManagementClient.buildAcquireInitialAdmissionBindHoldRequest( + 7L, + 42L, + 11L, + 4L, + "request-id", + "a".repeat(64), + null, + UUID.randomUUID(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + 3L)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClientMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClientMtlsTest.java index 4d2c368620..b164064677 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClientMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldRuntimeFamilyCatalogClientMtlsTest.java @@ -208,10 +208,9 @@ public void readWorldRuntimeFamilyCatalog( } var tls = new CommonGrpcClientProperties(); tls.setPlaintext(true); - assertThatThrownBy( - () -> - new WorldRuntimeFamilyCatalogClient( - new ServiceEndpointsProperties(), tls, new GrpcChannelFactory(), NAMESPACE)) + assertThatThrownBy(() -> + new WorldRuntimeFamilyCatalogClient( + new ServiceEndpointsProperties(), tls, new GrpcChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReaderTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReaderTest.java index 7457fb6443..8e95825839 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReaderTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReaderTest.java @@ -280,19 +280,19 @@ private GameInstance admittedInstance() { private String validDefinition() { return """ - {"schemaVersion":1,"commandId":"salute","semanticOwner":"GAME_LOGIC","executionDiscipline":"DURABLE_GAMEPLAY","stageRequirement":"GAMEPLAY","promptPolicy":"WHEN_GAMEPLAY","actionCategory":"SOCIAL","historyRecordable":true,"aliases":["salute"],"actionTags":["COMMUNICATION"],"effects":[]} - """; + {"schemaVersion":1,"commandId":"salute","semanticOwner":"GAME_LOGIC","executionDiscipline":"DURABLE_GAMEPLAY","stageRequirement":"GAMEPLAY","promptPolicy":"WHEN_GAMEPLAY","actionCategory":"SOCIAL","historyRecordable":true,"aliases":["salute"],"actionTags":["COMMUNICATION"],"effects":[]} + """; } private String validActionStateDefinition() { return """ - {"schemaVersion":1,"commandId":"block","semanticOwner":"GAME_LOGIC","executionDiscipline":"DURABLE_GAMEPLAY","stageRequirement":"GAMEPLAY","promptPolicy":"WHEN_GAMEPLAY","actionCategory":"GAMEPLAY","historyRecordable":true,"aliases":["block"],"actionTags":["COMBAT"],"effects":[{"effectKind":"APPLY_ACTION_STATE","schemaVersion":1,"targeting":"SELF","replayPolicy":"EFFECT_IDEMPOTENT","payload":{"conditionKey":"blocking","durationSeconds":5,"effectPayload":{"modifiers":[{"operation":"ADD","target_key":"block_mitigation","value":1,"scope_kind":"ACTION_FAMILY","scope_key":"defense"}]}}}]} - """; + {"schemaVersion":1,"commandId":"block","semanticOwner":"GAME_LOGIC","executionDiscipline":"DURABLE_GAMEPLAY","stageRequirement":"GAMEPLAY","promptPolicy":"WHEN_GAMEPLAY","actionCategory":"GAMEPLAY","historyRecordable":true,"aliases":["block"],"actionTags":["COMBAT"],"effects":[{"effectKind":"APPLY_ACTION_STATE","schemaVersion":1,"targeting":"SELF","replayPolicy":"EFFECT_IDEMPOTENT","payload":{"conditionKey":"blocking","durationSeconds":5,"effectPayload":{"modifiers":[{"operation":"ADD","target_key":"block_mitigation","value":1,"scope_kind":"ACTION_FAMILY","scope_key":"defense"}]}}}]} + """; } private String validActionStateDefinitionWithoutScopes() { return """ - {"schemaVersion":1,"commandId":"block","semanticOwner":"GAME_LOGIC","executionDiscipline":"DURABLE_GAMEPLAY","stageRequirement":"GAMEPLAY","promptPolicy":"WHEN_GAMEPLAY","actionCategory":"GAMEPLAY","historyRecordable":true,"aliases":["block"],"actionTags":["COMBAT"],"effects":[{"effectKind":"APPLY_ACTION_STATE","schemaVersion":1,"targeting":"SELF","replayPolicy":"EFFECT_IDEMPOTENT","payload":{"conditionKey":"blocking","durationSeconds":5,"effectPayload":{"modifiers":[{"operation":"ADD","target_key":"block_mitigation","value":1}]}}}]} - """; + {"schemaVersion":1,"commandId":"block","semanticOwner":"GAME_LOGIC","executionDiscipline":"DURABLE_GAMEPLAY","stageRequirement":"GAMEPLAY","promptPolicy":"WHEN_GAMEPLAY","actionCategory":"GAMEPLAY","historyRecordable":true,"aliases":["block"],"actionTags":["COMBAT"],"effects":[{"effectKind":"APPLY_ACTION_STATE","schemaVersion":1,"targeting":"SELF","replayPolicy":"EFFECT_IDEMPOTENT","payload":{"conditionKey":"blocking","durationSeconds":5,"effectPayload":{"modifiers":[{"operation":"ADD","target_key":"block_mitigation","value":1}]}}}]} + """; } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java index e40a640165..c22ca2f6d0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java @@ -169,19 +169,18 @@ void registryFindsDefinitionsByAliasCaseInsensitively() { void registryFindsDefinitionsByCommandIdCaseInsensitively() { AggregatingTextCommandRegistry commandIdRegistry = new AggregatingTextCommandRegistry( - List.of( - () -> - List.of( - new TextCommandDefinition( - "wave-salute", - TextCommandType.AUTHORED, - List.of(), - TextCommandDispatchGroup.AUTHORED, - TextCommandStageRequirement.GAMEPLAY, - TextCommandPromptPolicy.WHEN_GAMEPLAY, - TextCommandActionCategory.GAMEPLAY, - List.of(), - TextCommandSource.GAME_AUTHORED)))); + List.of(() -> + List.of( + new TextCommandDefinition( + "wave-salute", + TextCommandType.AUTHORED, + List.of(), + TextCommandDispatchGroup.AUTHORED, + TextCommandStageRequirement.GAMEPLAY, + TextCommandPromptPolicy.WHEN_GAMEPLAY, + TextCommandActionCategory.GAMEPLAY, + List.of(), + TextCommandSource.GAME_AUTHORED)))); TextCommandDefinition definition = commandIdRegistry.findDefinition("WAVE-SALUTE").orElseThrow(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java index 173d551717..868e118cfb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java @@ -120,12 +120,11 @@ void saySuccessReturnsCanonicalText() { Mockito.verify(scriptEventPublisher) .publishCommandEvent( Mockito.eq(sessionContext), - Mockito.argThat( - gameplayCommand -> - "SAY".equals(gameplayCommand.getCommandName()) - && "say hello travelers".equals(gameplayCommand.getCommandText()) - && gameplayCommand.getCommandId() != null - && gameplayCommand.getCommandId().startsWith("comm-"))); + Mockito.argThat(gameplayCommand -> + "SAY".equals(gameplayCommand.getCommandName()) + && "say hello travelers".equals(gameplayCommand.getCommandText()) + && gameplayCommand.getCommandId() != null + && gameplayCommand.getCommandId().startsWith("comm-"))); } @Test @@ -317,11 +316,10 @@ void underlyingFailurePropagates() { Mockito.verify(scriptEventPublisher) .publishCommandEvent( Mockito.eq(sessionContext), - Mockito.argThat( - gameplayCommand -> - "SAY".equals(gameplayCommand.getCommandName()) - && gameplayCommand.getCommandId() != null - && gameplayCommand.getCommandId().startsWith("comm-"))); + Mockito.argThat(gameplayCommand -> + "SAY".equals(gameplayCommand.getCommandName()) + && gameplayCommand.getCommandId() != null + && gameplayCommand.getCommandId().startsWith("comm-"))); } @Test @@ -354,10 +352,9 @@ void communicationEffectUsesDeterministicScriptEventId() { Mockito.verify(scriptEventPublisher) .publishCommandEvent( Mockito.eq(sessionContext), - Mockito.argThat( - gameplayCommand -> - "SAY".equals(gameplayCommand.getCommandName()) - && "effect-1:communication:say".equals(gameplayCommand.getCommandId()))); + Mockito.argThat(gameplayCommand -> + "SAY".equals(gameplayCommand.getCommandName()) + && "effect-1:communication:say".equals(gameplayCommand.getCommandId()))); } @Test @@ -380,12 +377,10 @@ void tellFailsClosedWhenSessionContextDropsAdmittedPlayableStateScope() { sessionContext.pointerVersion(), null); - assertThatThrownBy( - () -> - handler.handle( - missingScope, - new TextCommand( - TextCommandType.TELL, List.of("Sora", "hello"), "TELL Sora hello"))) + assertThatThrownBy(() -> + handler.handle( + missingScope, + new TextCommand(TextCommandType.TELL, List.of("Sora", "hello"), "TELL Sora hello"))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Missing admitted playableStateScope"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreTest.java index 15968f9f4f..cd0af8ac9b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldMenuRedisStoreTest.java @@ -62,11 +62,10 @@ class DirectTextWorldMenuRedisStoreTest { private final AtomicInteger catalogReads = new AtomicInteger(); private final DirectTextWorldSelectionService selection = new DirectTextWorldSelectionService( - GameplayWorldCatalog.forWorldSupplier( - () -> { - catalogReads.incrementAndGet(); - return List.of(); - }), + GameplayWorldCatalog.forWorldSupplier(() -> { + catalogReads.incrementAndGet(); + return List.of(); + }), routes, CLOCK); private final StatefulRedisConnection connection = mockConnection(); @@ -96,12 +95,11 @@ void prepare() throws Exception { when(commands.exists(any(byte[].class))) .thenAnswer(invocation -> stored.get() == null ? 0L : 1L); when(commands.scriptLoad(any(byte[].class))) - .thenAnswer( - invocation -> - HexFormat.of() - .formatHex( - MessageDigest.getInstance("SHA-1") - .digest(invocation.getArgument(0, byte[].class)))); + .thenAnswer(invocation -> + HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-1") + .digest(invocation.getArgument(0, byte[].class)))); when(commands.evalsha( anyString(), eq(ScriptOutputType.STATUS), @@ -111,30 +109,25 @@ void prepare() throws Exception { any(byte[].class), any(byte[].class), any(byte[].class))) - .thenAnswer( - invocation -> { - assertThat( + .thenAnswer(invocation -> { + assertThat(new String(invocation.getArgument(7, byte[].class), StandardCharsets.US_ASCII)) + .isEqualTo(Long.toString(CLOCK.millis())); + boolean clear = + "CLEAR" + .equals( new String( - invocation.getArgument(7, byte[].class), StandardCharsets.US_ASCII)) - .isEqualTo(Long.toString(CLOCK.millis())); - boolean clear = - "CLEAR" - .equals( - new String( - invocation.getArgument(3, byte[].class), StandardCharsets.US_ASCII)); - assertThat( - new String( - invocation.getArgument(6, byte[].class), StandardCharsets.US_ASCII)) - .isEqualTo(clear ? "0" : Long.toString(CLOCK.millis() + 300_000L)); - byte[] expected = invocation.getArgument(4, byte[].class); - if (!Arrays.equals(expected, stored.get() == null ? new byte[0] : stored.get())) { - return "PREIMAGE_MISMATCH"; - } - if ("MENU_WRITTEN".equals(outcome.get())) { - stored.set(invocation.getArgument(5, byte[].class)); - } - return outcome.get(); - }); + invocation.getArgument(3, byte[].class), StandardCharsets.US_ASCII)); + assertThat(new String(invocation.getArgument(6, byte[].class), StandardCharsets.US_ASCII)) + .isEqualTo(clear ? "0" : Long.toString(CLOCK.millis() + 300_000L)); + byte[] expected = invocation.getArgument(4, byte[].class); + if (!Arrays.equals(expected, stored.get() == null ? new byte[0] : stored.get())) { + return "PREIMAGE_MISMATCH"; + } + if ("MENU_WRITTEN".equals(outcome.get())) { + stored.set(invocation.getArgument(5, byte[].class)); + } + return outcome.get(); + }); store = new DirectTextWorldMenuRedisStore(selection, CLOCK, () -> connection, installed()); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java index 9177c00339..7a9d16fe2b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/DirectTextWorldSelectionServiceTest.java @@ -63,11 +63,10 @@ void historicalEncodingRemainsClockIndependentWhileRestorationAndResolutionRefus var first = target(""); var reads = new AtomicInteger(); var catalog = - GameplayWorldCatalog.forWorldSupplier( - () -> { - reads.incrementAndGet(); - return List.of(world(first)); - }); + GameplayWorldCatalog.forWorldSupplier(() -> { + reads.incrementAndGet(); + return List.of(world(first)); + }); var source = service(catalog, List.of(first)); var menu = source.browse().orElseThrow(); byte[] original = source.encodeSnapshot(menu).orElseThrow(); @@ -274,31 +273,28 @@ void restorationRechecksOriginalExpiryAfterCanonicalAndCatalogReads() { var first = target(""); AtomicReference readEffect = new AtomicReference<>(() -> {}); var catalog = - GameplayWorldCatalog.forWorldSupplier( - () -> { - readEffect.get().run(); - return List.of(world(first)); - }); + GameplayWorldCatalog.forWorldSupplier(() -> { + readEffect.get().run(); + return List.of(world(first)); + }); var source = service(catalog, List.of(first)); byte[] stored = source.encodeSnapshot(source.browse().orElseThrow()).orElseThrow(); var replacement = service(catalog, List.of(first)); when(reader.readVisiblePublicProductionTargets()) - .thenAnswer( - invocation -> { - clock.now = NOW.plusSeconds(300); - return List.of(first); - }); + .thenAnswer(invocation -> { + clock.now = NOW.plusSeconds(300); + return List.of(first); + }); assertThat(replacement.restoreSnapshot(stored)).isEmpty(); clock.now = NOW; when(reader.readVisiblePublicProductionTargets()).thenReturn(List.of(first)); AtomicInteger reads = new AtomicInteger(); - readEffect.set( - () -> { - if (reads.incrementAndGet() == 2) { - clock.now = NOW.plusSeconds(300); - } - }); + readEffect.set(() -> { + if (reads.incrementAndGet() == 2) { + clock.now = NOW.plusSeconds(300); + } + }); assertThat(replacement.restoreSnapshot(stored)).isEmpty(); } @@ -323,10 +319,9 @@ void restorationKeepsParsingRefusalSeparateFromUnavailableAndInvalidSources() { var catalogUnavailable = new GameplayWorldCatalog.AuthorityPointerUnavailableException("unavailable"); var unreachableCatalog = - GameplayWorldCatalog.forWorldSupplier( - () -> { - throw catalogUnavailable; - }); + GameplayWorldCatalog.forWorldSupplier(() -> { + throw catalogUnavailable; + }); var catalogReplacement = new DirectTextWorldSelectionService(unreachableCatalog, reader, clock); assertThatThrownBy(() -> catalogReplacement.restoreSnapshot(stored)) .isSameAs(catalogUnavailable); @@ -347,11 +342,10 @@ void restorationDoesNotHideCatalogDriftDuringFreshCompositionOrDuplicateCanonica var source = service(catalog, List.of(first)); byte[] stored = source.encodeSnapshot(source.browse().orElseThrow()).orElseThrow(); when(reader.readVisiblePublicProductionTargets()) - .thenAnswer( - invocation -> { - worlds.set(List.of()); - return List.of(first); - }); + .thenAnswer(invocation -> { + worlds.set(List.of()); + return List.of(first); + }); assertThat(source.restoreSnapshot(stored)).isEmpty(); worlds.set(List.of(world(first))); when(reader.readVisiblePublicProductionTargets()).thenReturn(List.of(first, first)); @@ -427,11 +421,10 @@ void invalidSelectorsDoNotReadSources(String selector) { var first = target(""); AtomicInteger catalogReads = new AtomicInteger(); var catalog = - GameplayWorldCatalog.forWorldSupplier( - () -> { - catalogReads.incrementAndGet(); - return List.of(world(first)); - }); + GameplayWorldCatalog.forWorldSupplier(() -> { + catalogReads.incrementAndGet(); + return List.of(world(first)); + }); var service = service(catalog, List.of(first)); var menu = service.browse().orElseThrow(); clearInvocations(reader); @@ -516,11 +509,10 @@ void changedCatalogDuringBrowseIsRefused() { AtomicReference> worlds = new AtomicReference<>(List.of(world(first))); var catalog = GameplayWorldCatalog.forWorldSupplier(worlds::get); when(reader.readVisiblePublicProductionTargets()) - .thenAnswer( - invocation -> { - worlds.set(List.of()); - return List.of(first); - }); + .thenAnswer(invocation -> { + worlds.set(List.of()); + return List.of(first); + }); assertThat(new DirectTextWorldSelectionService(catalog, reader, clock).browse()).isEmpty(); } @@ -550,11 +542,10 @@ void expiryIsExclusiveAtFiveMinutesAndExpiredSelectionsHaveNoSourceEffects() { AtomicInteger catalogReads = new AtomicInteger(); var service = service( - GameplayWorldCatalog.forWorldSupplier( - () -> { - catalogReads.incrementAndGet(); - return List.of(world(first)); - }), + GameplayWorldCatalog.forWorldSupplier(() -> { + catalogReads.incrementAndGet(); + return List.of(world(first)); + }), List.of(first)); var menu = service.browse().orElseThrow(); clock.now = NOW.plusSeconds(300).minusNanos(1); @@ -597,19 +588,17 @@ void expiryIsRecheckedAfterCanonicalAndCatalogReads() { AtomicReference onCatalogRead = new AtomicReference<>(() -> {}); var service = service( - GameplayWorldCatalog.forWorldSupplier( - () -> { - onCatalogRead.get().run(); - return List.of(world(first)); - }), + GameplayWorldCatalog.forWorldSupplier(() -> { + onCatalogRead.get().run(); + return List.of(world(first)); + }), List.of(first)); var menu = service.browse().orElseThrow(); when(reader.readCurrentTarget(first)) - .thenAnswer( - invocation -> { - clock.now = NOW.plusSeconds(300); - return first; - }); + .thenAnswer(invocation -> { + clock.now = NOW.plusSeconds(300); + return first; + }); assertThat(service.resolve(menu, "1")).isEmpty(); when(reader.readCurrentTarget(first)).thenReturn(first); @@ -623,11 +612,10 @@ void browseTimeConsumesTheSameBoundedMenuLifetime() { var first = target(""); var service = service(List.of(world(first)), List.of(first)); when(reader.readVisiblePublicProductionTargets()) - .thenAnswer( - invocation -> { - clock.now = NOW.plusSeconds(300); - return List.of(first); - }); + .thenAnswer(invocation -> { + clock.now = NOW.plusSeconds(300); + return List.of(first); + }); assertThat(service.browse()).isEmpty(); } @@ -760,18 +748,16 @@ void catalogUnavailabilityEscapesDuringBrowseAndResolve() { AtomicReference readEffect = new AtomicReference<>(() -> {}); var service = service( - GameplayWorldCatalog.forWorldSupplier( - () -> { - readEffect.get().run(); - return List.of(world(first)); - }), + GameplayWorldCatalog.forWorldSupplier(() -> { + readEffect.get().run(); + return List.of(world(first)); + }), List.of(first)); var menu = service.browse().orElseThrow(); var unavailable = new GameplayWorldCatalog.AuthorityPointerUnavailableException("unavailable"); - readEffect.set( - () -> { - throw unavailable; - }); + readEffect.set(() -> { + throw unavailable; + }); assertThatThrownBy(service::browse).isSameAs(unavailable); assertThatThrownBy(() -> service.resolve(menu, "1")).isSameAs(unavailable); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java index 018ecb9cc1..63515a3e41 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java @@ -252,15 +252,14 @@ void friendsMapsVisiblePresenceToTypedViewAndText() { assertThat(view.matchCount()).isEqualTo(1); assertThat(view.friends()) .singleElement() - .satisfies( - entry -> { - assertThat(entry.friendLinkId()).isNull(); - assertThat(entry.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); - assertThat(entry.status()).isEqualTo("active"); - assertThat(entry.linkedAtEpochMs()).isNull(); - assertThat(entry.displayName()).isEqualTo("Sora"); - assertThat(entry.activityState()).isEqualTo("AUTO_AFK"); - }); + .satisfies(entry -> { + assertThat(entry.friendLinkId()).isNull(); + assertThat(entry.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); + assertThat(entry.status()).isEqualTo("active"); + assertThat(entry.linkedAtEpochMs()).isNull(); + assertThat(entry.displayName()).isEqualTo("Sora"); + assertThat(entry.activityState()).isEqualTo("AUTO_AFK"); + }); assertThat( new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) @@ -270,12 +269,11 @@ void friendsMapsVisiblePresenceToTypedViewAndText() { Mockito.verify(scriptEventPublisher) .publishCommandEvent( Mockito.any(), - Mockito.argThat( - gameplayCommand -> - "FRIENDS".equals(gameplayCommand.getCommandName()) - && "FRIENDS".equals(gameplayCommand.getCommandText()) - && gameplayCommand.getCommandId() != null - && gameplayCommand.getCommandId().startsWith("friends-"))); + Mockito.argThat(gameplayCommand -> + "FRIENDS".equals(gameplayCommand.getCommandName()) + && "FRIENDS".equals(gameplayCommand.getCommandText()) + && gameplayCommand.getCommandId() != null + && gameplayCommand.getCommandId().startsWith("friends-"))); } @Test @@ -312,15 +310,14 @@ void friendsShowsOnlyLastSeenTimeForRecentOfflinePresence() { assertThat(view.filter()).isEqualTo("ALL"); assertThat(view.friends()) .singleElement() - .satisfies( - entry -> { - assertThat(entry.friendLinkId()).isNull(); - assertThat(entry.status()).isEqualTo("active"); - assertThat(entry.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID); - assertThat(entry.lastSeenAtEpochMs()) - .isEqualTo(Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()); - assertThat(entry.visibilityPolicy()).isNull(); - }); + .satisfies(entry -> { + assertThat(entry.friendLinkId()).isNull(); + assertThat(entry.status()).isEqualTo("active"); + assertThat(entry.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID); + assertThat(entry.lastSeenAtEpochMs()) + .isEqualTo(Instant.parse("2026-04-11T06:15:30Z").toEpochMilli()); + assertThat(entry.visibilityPolicy()).isNull(); + }); String rendered = new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) @@ -351,25 +348,23 @@ void friendsAddLinksAccountScopedFriendAndReturnsNotice() { assertThat(result.commandResult().accepted()).isTrue(); assertThat(result.outputs()) .singleElement() - .satisfies( - output -> { - assertThat(output.text()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + " added."); - assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); - FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); - assertThat(mutation.action()).isEqualTo("ADD"); - assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); - assertThat(mutation.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID); - assertThat(mutation.characterName()).isNull(); - assertThat(mutation.ordinal()).isNull(); - }); + .satisfies(output -> { + assertThat(output.text()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + " added."); + assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); + FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); + assertThat(mutation.action()).isEqualTo("ADD"); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); + assertThat(mutation.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID); + assertThat(mutation.characterName()).isNull(); + assertThat(mutation.ordinal()).isNull(); + }); Mockito.verify(scriptEventPublisher) .publishCommandEvent( Mockito.any(), - Mockito.argThat( - gameplayCommand -> - "FRIENDS".equals(gameplayCommand.getCommandName()) - && ("FRIENDS ADD " + FRIEND_ACCOUNT_ID) - .equals(gameplayCommand.getCommandText()))); + Mockito.argThat(gameplayCommand -> + "FRIENDS".equals(gameplayCommand.getCommandName()) + && ("FRIENDS ADD " + FRIEND_ACCOUNT_ID) + .equals(gameplayCommand.getCommandText()))); } @Test @@ -465,12 +460,11 @@ void friendsPrivateFiltersCanonicalRosterByVisibilityPolicy() { assertThat(view.matchCount()).isEqualTo(1); assertThat(view.friends()) .singleElement() - .satisfies( - entry -> { - assertThat(entry.ordinal()).isEqualTo(2); - assertThat(entry.friendAccountId()).isEqualTo(OTHER_FRIEND_ACCOUNT_ID); - assertThat(entry.visibilityPolicy()).isEqualTo("PRIVATE"); - }); + .satisfies(entry -> { + assertThat(entry.ordinal()).isEqualTo(2); + assertThat(entry.friendAccountId()).isEqualTo(OTHER_FRIEND_ACCOUNT_ID); + assertThat(entry.visibilityPolicy()).isEqualTo("PRIVATE"); + }); assertThat( new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) @@ -521,12 +515,11 @@ void friendsSharedFiltersCanonicalRosterByPlayableStateScope() { assertThat(view.matchCount()).isEqualTo(1); assertThat(view.friends()) .singleElement() - .satisfies( - entry -> { - assertThat(entry.ordinal()).isEqualTo(1); - assertThat(entry.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); - assertThat(entry.playableStateScope()).isEqualTo("SHARED"); - }); + .satisfies(entry -> { + assertThat(entry.ordinal()).isEqualTo(1); + assertThat(entry.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); + assertThat(entry.playableStateScope()).isEqualTo("SHARED"); + }); assertThat( new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) @@ -676,16 +669,15 @@ void friendsAddResolvesCharacterNameToCanonicalAccountId() { assertThat(result.commandResult().accepted()).isTrue(); assertThat(result.outputs()) .singleElement() - .satisfies( - output -> { - assertThat(output.text()).isEqualTo("Sora [acct #" + FRIEND_ACCOUNT_ID + "] added."); - assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); - FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); - assertThat(mutation.action()).isEqualTo("ADD"); - assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); - assertThat(mutation.displayName()).isEqualTo("Sora"); - assertThat(mutation.characterName()).isEqualTo("Sora"); - }); + .satisfies(output -> { + assertThat(output.text()).isEqualTo("Sora [acct #" + FRIEND_ACCOUNT_ID + "] added."); + assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); + FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); + assertThat(mutation.action()).isEqualTo("ADD"); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); + assertThat(mutation.displayName()).isEqualTo("Sora"); + assertThat(mutation.characterName()).isEqualTo("Sora"); + }); Mockito.verify(socialGroupsClient).addFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID); } @@ -710,17 +702,16 @@ void friendsRemoveUnlinksAccountScopedFriendAndReturnsNotice() { assertThat(result.commandResult().accepted()).isTrue(); assertThat(result.outputs()) .singleElement() - .satisfies( - output -> { - assertThat(output.text()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + " removed."); - assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); - FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); - assertThat(mutation.action()).isEqualTo("REMOVE"); - assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); - assertThat(mutation.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID); - assertThat(mutation.characterName()).isNull(); - assertThat(mutation.ordinal()).isNull(); - }); + .satisfies(output -> { + assertThat(output.text()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID + " removed."); + assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); + FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); + assertThat(mutation.action()).isEqualTo("REMOVE"); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); + assertThat(mutation.displayName()).isEqualTo("Friend #" + FRIEND_ACCOUNT_ID); + assertThat(mutation.characterName()).isNull(); + assertThat(mutation.ordinal()).isNull(); + }); } @Test @@ -755,17 +746,15 @@ void friendsRemoveResolvesCharacterNameToCanonicalAccountId() { assertThat(result.commandResult().accepted()).isTrue(); assertThat(result.outputs()) .singleElement() - .satisfies( - output -> { - assertThat(output.text()) - .isEqualTo("Sora [acct #" + FRIEND_ACCOUNT_ID + "] removed."); - assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); - FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); - assertThat(mutation.action()).isEqualTo("REMOVE"); - assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); - assertThat(mutation.displayName()).isEqualTo("Sora"); - assertThat(mutation.characterName()).isEqualTo("Sora"); - }); + .satisfies(output -> { + assertThat(output.text()).isEqualTo("Sora [acct #" + FRIEND_ACCOUNT_ID + "] removed."); + assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); + FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); + assertThat(mutation.action()).isEqualTo("REMOVE"); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); + assertThat(mutation.displayName()).isEqualTo("Sora"); + assertThat(mutation.characterName()).isEqualTo("Sora"); + }); Mockito.verify(socialGroupsClient).removeFriend(1L, CALLER_ACCOUNT_ID, FRIEND_ACCOUNT_ID); } @@ -801,18 +790,16 @@ void friendsRemoveByOrdinalUsesCanonicalRemoveSurface() { assertThat(result.commandResult().accepted()).isTrue(); assertThat(result.outputs()) .singleElement() - .satisfies( - output -> { - assertThat(output.text()) - .isEqualTo("Sora [acct #" + FRIEND_ACCOUNT_ID + "] removed."); - assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); - FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); - assertThat(mutation.action()).isEqualTo("REMOVE"); - assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); - assertThat(mutation.displayName()).isEqualTo("Sora"); - assertThat(mutation.characterName()).isEqualTo("Sora"); - assertThat(mutation.ordinal()).isEqualTo(1); - }); + .satisfies(output -> { + assertThat(output.text()).isEqualTo("Sora [acct #" + FRIEND_ACCOUNT_ID + "] removed."); + assertThat(output.payload()).isInstanceOf(FriendMutationResultOutput.class); + FriendMutationResultOutput mutation = (FriendMutationResultOutput) output.payload(); + assertThat(mutation.action()).isEqualTo("REMOVE"); + assertThat(mutation.friendAccountId()).isEqualTo(FRIEND_ACCOUNT_ID); + assertThat(mutation.displayName()).isEqualTo("Sora"); + assertThat(mutation.characterName()).isEqualTo("Sora"); + assertThat(mutation.ordinal()).isEqualTo(1); + }); Mockito.verify(socialGroupsClient).removeFriendByOrdinal(1L, CALLER_ACCOUNT_ID, 1); } @@ -1225,12 +1212,11 @@ void friendsVisibilityShowsCurrentCanonicalPolicy() { assertThat(view.currentPolicy()).isEqualTo("FRIENDS_ONLY"); assertThat(view.options()).hasSize(3); assertThat(view.options()) - .anySatisfy( - option -> { - assertThat(option.policy()).isEqualTo("FRIENDS_ONLY"); - assertThat(option.current()).isTrue(); - assertThat(option.selectable()).isTrue(); - }); + .anySatisfy(option -> { + assertThat(option.policy()).isEqualTo("FRIENDS_ONLY"); + assertThat(option.current()).isTrue(); + assertThat(option.selectable()).isTrue(); + }); String rendered = new TextPlayerOutputRenderer( new net.firedevops.firemud.gamesession.config.PresentationProperties()) @@ -1311,11 +1297,10 @@ void friendsVisibilityUpdatesCanonicalPolicy() { (FriendPresencePolicyViewOutput) result.outputs().get(1).payload(); assertThat(view.currentPolicy()).isEqualTo("PRIVATE"); assertThat(view.options()) - .anySatisfy( - option -> { - assertThat(option.policy()).isEqualTo("PRIVATE"); - assertThat(option.current()).isTrue(); - }); + .anySatisfy(option -> { + assertThat(option.policy()).isEqualTo("PRIVATE"); + assertThat(option.current()).isTrue(); + }); Mockito.verify(socialGroupsClient) .updateFriendPresencePolicy( 1L, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index 68e4d67386..7bfa779757 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -769,11 +769,10 @@ void publicProductionCardinalityCountsSameTenantCandidatesAcrossWorlds() { void browseViewUsesOneWorldSnapshotForDefaultRealmAndCardinalityChecks() { AtomicInteger supplierCalls = new AtomicInteger(); GameplayWorldCatalog catalog = - GameplayWorldCatalog.forWorldSupplier( - () -> - supplierCalls.getAndIncrement() == 0 - ? List.of(worldWithRealm("demo", "production", 7L, true)) - : List.of(worldWithRealm("demo", "preview", 7L, false))); + GameplayWorldCatalog.forWorldSupplier(() -> + supplierCalls.getAndIncrement() == 0 + ? List.of(worldWithRealm("demo", "production", 7L, true)) + : List.of(worldWithRealm("demo", "preview", 7L, false))); assertThat(catalog.browseView().worlds()) .extracting( @@ -806,11 +805,10 @@ void authoritySnapshotReadsOnceAndRetainsSuppressedPointerComparisonEvidence() { new AtomicReference<>(List.of(visible, hidden)); AtomicInteger reads = new AtomicInteger(); when(authorityService.listPointers()) - .thenAnswer( - invocation -> { - reads.incrementAndGet(); - return source.get(); - }); + .thenAnswer(invocation -> { + reads.incrementAndGet(); + return source.get(); + }); GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); GameplayWorldCatalog.DiscoverySnapshot original = catalog.discoverySnapshot(); @@ -848,11 +846,10 @@ void authoritySnapshotReadsOnceAndRetainsSuppressedPointerComparisonEvidence() { void discoverySnapshotReadsItsSourceOnce() { AtomicInteger supplierCalls = new AtomicInteger(); GameplayWorldCatalog catalog = - GameplayWorldCatalog.forWorldSupplier( - () -> { - supplierCalls.incrementAndGet(); - return List.of(worldWithRealm("demo", "production", 7L, true)); - }); + GameplayWorldCatalog.forWorldSupplier(() -> { + supplierCalls.incrementAndGet(); + return List.of(worldWithRealm("demo", "production", 7L, true)); + }); GameplayWorldCatalog.DiscoverySnapshot snapshot = catalog.discoverySnapshot(); @@ -874,11 +871,10 @@ void callerFreeRealmDiscoveryReadsOnceAndDoesNotExposePrivateOrHiddenRealms() { realmView("preview", "Preview Realm", 7L, 12L, 2L, true, false, "ALLOW_NEW"), realmView("hidden", "Hidden Realm", 7L, 13L, 3L, false, false, "ALLOW_NEW"))); GameplayWorldCatalog catalog = - GameplayWorldCatalog.forWorldSupplier( - () -> { - supplierCalls.incrementAndGet(); - return List.of(selectedWorld); - }); + GameplayWorldCatalog.forWorldSupplier(() -> { + supplierCalls.incrementAndGet(); + return List.of(selectedWorld); + }); GameplayWorldCatalog.DiscoverySnapshot discovery = catalog.discoverySnapshot(); assertThat(supplierCalls).hasValue(1); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java index d2f96625bc..15ed2f1aa1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java @@ -34,12 +34,11 @@ void publishesCommandEventForGameplayScopedHelp() { Mockito.verify(scriptEventPublisher) .publishCommandEvent( Mockito.eq(context), - Mockito.argThat( - gameplayCommand -> - "HELP".equals(gameplayCommand.getCommandName()) - && "HELP who".equals(gameplayCommand.getCommandText()) - && gameplayCommand.getCommandId() != null - && gameplayCommand.getCommandId().startsWith("help-"))); + Mockito.argThat(gameplayCommand -> + "HELP".equals(gameplayCommand.getCommandName()) + && "HELP who".equals(gameplayCommand.getCommandText()) + && gameplayCommand.getCommandId() != null + && gameplayCommand.getCommandId().startsWith("help-"))); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ItemCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ItemCommandHandlerTest.java index def50acbb4..0381ec8085 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ItemCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ItemCommandHandlerTest.java @@ -62,12 +62,11 @@ void publishesScriptEventForSuccessfulDirectInventoryRead() { Mockito.verify(scriptEventPublisher) .publishCommandEvent( Mockito.eq(context), - Mockito.argThat( - gameplayCommand -> - "INVENTORY".equals(gameplayCommand.getCommandName()) - && "INVENTORY".equals(gameplayCommand.getCommandText()) - && gameplayCommand.getCommandId() != null - && gameplayCommand.getCommandId().startsWith("item-"))); + Mockito.argThat(gameplayCommand -> + "INVENTORY".equals(gameplayCommand.getCommandName()) + && "INVENTORY".equals(gameplayCommand.getCommandText()) + && gameplayCommand.getCommandId() != null + && gameplayCommand.getCommandId().startsWith("item-"))); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ObservedDirectTextTransportTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ObservedDirectTextTransportTest.java index 10f4f08f03..614eaccfdb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ObservedDirectTextTransportTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ObservedDirectTextTransportTest.java @@ -32,10 +32,8 @@ void acceptsOnlyCanonicalNonNilUuidV4ObservedInTrustedProxyMode() { @Test void constructorRejectsNonNumericTransportIdAndNonV4ProxyId() { - assertThatThrownBy( - () -> - new ObservedDirectTextTransport( - "transport-hash", UUID.fromString(PROXY_CONNECTION_ID))) + assertThatThrownBy(() -> + new ObservedDirectTextTransport("transport-hash", UUID.fromString(PROXY_CONNECTION_ID))) .isInstanceOf(IllegalArgumentException.class); for (String invalidSession : List.of("0", "-1", "9223372036854775808")) { assertThat( @@ -43,10 +41,9 @@ void constructorRejectsNonNumericTransportIdAndNonV4ProxyId() { "trusted_tcp_proxy", invalidSession, PROXY_CONNECTION_ID)) .isEmpty(); } - assertThatThrownBy( - () -> - new ObservedDirectTextTransport( - "41", UUID.fromString("00000000-0000-0000-0000-000000000000"))) + assertThatThrownBy(() -> + new ObservedDirectTextTransport( + "41", UUID.fromString("00000000-0000-0000-0000-000000000000"))) .isInstanceOf(IllegalArgumentException.class); } @@ -55,14 +52,13 @@ void dispatchRequestRejectsObservationBoundToDifferentSessionId() { ObservedDirectTextTransport observed = new ObservedDirectTextTransport("41", UUID.fromString(PROXY_CONNECTION_ID)); - assertThatThrownBy( - () -> - new TextCommandDispatchRequest( - "42", - new TextCommand(TextCommandType.WORLDS, List.of(), "WORLDS"), - false, - Optional.empty(), - Optional.of(observed))) + assertThatThrownBy(() -> + new TextCommandDispatchRequest( + "42", + new TextCommand(TextCommandType.WORLDS, List.of(), "WORLDS"), + false, + Optional.empty(), + Optional.of(observed))) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index f97868fd5b..6b3a57f73f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -124,30 +124,28 @@ void setUp() { .setEvaluatedAt(Instant.now().toString()) .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenAnswer( - invocation -> - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(true) - .setAllowPublicJoin(true) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt(Instant.now().toString()) - .build()); + .thenAnswer(invocation -> + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(true) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt(Instant.now().toString()) + .build()); when(accountClient.getRealmAccessGrantForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) - .thenAnswer( - invocation -> - realmGrantResponse( - invocation.getArgument(0), - invocation.getArgument(1), - invocation.getArgument(2), - invocation.getArgument(3), - true)); + .thenAnswer(invocation -> + realmGrantResponse( + invocation.getArgument(0), + invocation.getArgument(1), + invocation.getArgument(2), + invocation.getArgument(3), + true)); when(sessionRoutingNormalizationService.normalizeProjectedContext( Mockito.any(SessionContext.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -157,23 +155,22 @@ void setUp() { Mockito.anyString(), Mockito.anyString(), Mockito.any(PlayableStateScope.class))) - .thenAnswer( - invocation -> { - String tenantId = invocation.getArgument(0); - String accountId = invocation.getArgument(1); - String gameInstanceId = invocation.getArgument(2); - PlayableStateScope scope = invocation.getArgument(3); - String characterName = "demo"; - String characterId = "7001"; - if ("2".equals(gameInstanceId)) { - characterName = "Emberline"; - characterId = "9007"; - } else if ("41".equals(gameInstanceId)) { - characterName = "Emberline"; - characterId = "7002"; - } - return characterRoster(characterId, characterName, tenantId, accountId, scope); - }); + .thenAnswer(invocation -> { + String tenantId = invocation.getArgument(0); + String accountId = invocation.getArgument(1); + String gameInstanceId = invocation.getArgument(2); + PlayableStateScope scope = invocation.getArgument(3); + String characterName = "demo"; + String characterId = "7001"; + if ("2".equals(gameInstanceId)) { + characterName = "Emberline"; + characterId = "9007"; + } else if ("41".equals(gameInstanceId)) { + characterName = "Emberline"; + characterId = "7002"; + } + return characterRoster(characterId, characterName, tenantId, accountId, scope); + }); } @Test @@ -189,12 +186,11 @@ void playResolvesAnExactNumericWorldSlugInsteadOfItsListPosition() { .isEqualTo("Entered world: 1 (preview) as Emberline"); Mockito.verify(sessionContextService) .save( - Mockito.argThat( - saved -> - saved.worldSlug().equals("1") - && saved.realmSlug().equals("preview") - && saved.gameInstanceId() == 41L - && saved.characterName().equals("Emberline"))); + Mockito.argThat(saved -> + saved.worldSlug().equals("1") + && saved.realmSlug().equals("preview") + && saved.gameInstanceId() == 41L + && saved.characterName().equals("Emberline"))); } @ParameterizedTest @@ -232,12 +228,11 @@ void playResolvesAnExactNumericRealmSlugInsteadOfItsListPosition() { .isEqualTo("Entered world: sandbox (1) as Emberline"); Mockito.verify(sessionContextService) .save( - Mockito.argThat( - saved -> - saved.worldSlug().equals("sandbox") - && saved.realmSlug().equals("1") - && saved.gameInstanceId() == 41L - && saved.characterName().equals("Emberline"))); + Mockito.argThat(saved -> + saved.worldSlug().equals("sandbox") + && saved.realmSlug().equals("1") + && saved.gameInstanceId() == 41L + && saved.characterName().equals("Emberline"))); } @Test @@ -280,12 +275,11 @@ void numericCharacterSelectorResolvesItsExactNameWithoutRosterIndexing(String co assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo as 1"); Mockito.verify(sessionContextService) .save( - Mockito.argThat( - saved -> - saved.gameInstanceId() == 1L - && saved.realmSlug().equals("production") - && saved.characterId() == 7001L - && saved.characterName().equals("1"))); + Mockito.argThat(saved -> + saved.gameInstanceId() == 1L + && saved.realmSlug().equals("production") + && saved.characterId() == 7001L + && saved.characterName().equals("1"))); Mockito.verify(accountClient, never()) .getRealmAccessGrantForRuntime( Mockito.anyString(), @@ -322,11 +316,10 @@ void twoArgumentNumericSelectorPrefersAnExactKnownRealmSlug() { .isEqualTo("Entered world: demo (1) as Realm Actor"); Mockito.verify(sessionContextService) .save( - Mockito.argThat( - saved -> - saved.gameInstanceId() == 41L - && saved.realmSlug().equals("1") - && saved.characterName().equals("Realm Actor"))); + Mockito.argThat(saved -> + saved.gameInstanceId() == 41L + && saved.realmSlug().equals("1") + && saved.characterName().equals("Realm Actor"))); Mockito.verify(accountClient) .getRealmAccessGrantForRuntime( Mockito.eq(ACCOUNT_ID), @@ -358,12 +351,11 @@ void explicitRealmKeepsNumericCharacterNameUnambiguousWhenSameNumericRealmExists assertThat(joinedOutputText(result.outputs())).isEqualTo("Entered world: demo as 1"); Mockito.verify(sessionContextService) .save( - Mockito.argThat( - saved -> - saved.gameInstanceId() == 1L - && saved.realmSlug().equals("production") - && saved.characterId() == 7001L - && saved.characterName().equals("1"))); + Mockito.argThat(saved -> + saved.gameInstanceId() == 1L + && saved.realmSlug().equals("production") + && saved.characterId() == 7001L + && saved.characterName().equals("1"))); } @ParameterizedTest diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorderTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorderTest.java index 4701725a85..eda839e326 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorderTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorderTest.java @@ -156,14 +156,13 @@ void quarantinesHistoryPersistenceFailure() { .when(storageService) .append(7L, 11L, 17L, "LOOK", 10); - assertDoesNotThrow( - () -> - recorder.record( - new TextCommand(TextCommandType.LOOK, List.of(), "LOOK"), - true, - CommandEnqueueResult.success(), - Optional.of(context), - Optional.of(context))); + assertDoesNotThrow(() -> + recorder.record( + new TextCommand(TextCommandType.LOOK, List.of(), "LOOK"), + true, + CommandEnqueueResult.success(), + Optional.of(context), + Optional.of(context))); } @Test @@ -173,14 +172,13 @@ void quarantinesHistorySettingsResolutionFailure() { .when(settingsResolver) .commandHistory(context); - assertDoesNotThrow( - () -> - recorder.record( - new TextCommand(TextCommandType.LOOK, List.of(), "LOOK"), - true, - CommandEnqueueResult.success(), - Optional.of(context), - Optional.of(context))); + assertDoesNotThrow(() -> + recorder.record( + new TextCommand(TextCommandType.LOOK, List.of(), "LOOK"), + true, + CommandEnqueueResult.success(), + Optional.of(context), + Optional.of(context))); verify(storageService, never()) .append( @@ -219,14 +217,13 @@ void quarantinesCapabilityResolutionFailure() { PlayerCommandCapability.COMMAND_HISTORY, 7L, 11L)) .thenThrow(new IllegalStateException("settings authority unavailable")); - assertDoesNotThrow( - () -> - recorder.record( - new TextCommand(TextCommandType.LOOK, List.of(), "LOOK"), - true, - CommandEnqueueResult.success(), - Optional.of(context), - Optional.of(context))); + assertDoesNotThrow(() -> + recorder.record( + new TextCommand(TextCommandType.LOOK, List.of(), "LOOK"), + true, + CommandEnqueueResult.success(), + Optional.of(context), + Optional.of(context))); verify(storageService, never()) .append( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/RegistryBackedTextCommandMetadataResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/RegistryBackedTextCommandMetadataResolverTest.java index 65029503ea..09ad85295b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/RegistryBackedTextCommandMetadataResolverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/RegistryBackedTextCommandMetadataResolverTest.java @@ -30,36 +30,33 @@ class RegistryBackedTextCommandMetadataResolverTest { void resolvesBuiltInAliasMetadata() { assertThat(resolver.resolve("LoGoFf")) .get() - .satisfies( - metadata -> { - assertThat(metadata.dispatchGroup()).isEqualTo(TextCommandDispatchGroup.SESSION); - assertThat(metadata.promptPolicy()).isEqualTo(TextCommandPromptPolicy.NEVER); - assertThat(metadata.actionCategory()).isEqualTo(TextCommandActionCategory.META); - assertThat(metadata.actionTags()).containsExactly(TextCommandActionTag.SESSION); - assertThat(metadata.capability()).isEqualTo(PlayerCommandCapability.MANDATORY); - }); + .satisfies(metadata -> { + assertThat(metadata.dispatchGroup()).isEqualTo(TextCommandDispatchGroup.SESSION); + assertThat(metadata.promptPolicy()).isEqualTo(TextCommandPromptPolicy.NEVER); + assertThat(metadata.actionCategory()).isEqualTo(TextCommandActionCategory.META); + assertThat(metadata.actionTags()).containsExactly(TextCommandActionTag.SESSION); + assertThat(metadata.capability()).isEqualTo(PlayerCommandCapability.MANDATORY); + }); } @Test void resolvesAuthoredCommandIdMetadata() { assertThat(resolver.resolve("wave")) .get() - .satisfies( - metadata -> { - assertThat(metadata.dispatchGroup()).isEqualTo(TextCommandDispatchGroup.AUTHORED); - assertThat(metadata.promptPolicy()).isEqualTo(TextCommandPromptPolicy.WHEN_GAMEPLAY); - assertThat(metadata.actionCategory()).isEqualTo(TextCommandActionCategory.SOCIAL); - assertThat(metadata.actionTags()).containsExactly(TextCommandActionTag.COMMUNICATION); - assertThat(metadata.capability()).isEqualTo(PlayerCommandCapability.MANDATORY); - }); + .satisfies(metadata -> { + assertThat(metadata.dispatchGroup()).isEqualTo(TextCommandDispatchGroup.AUTHORED); + assertThat(metadata.promptPolicy()).isEqualTo(TextCommandPromptPolicy.WHEN_GAMEPLAY); + assertThat(metadata.actionCategory()).isEqualTo(TextCommandActionCategory.SOCIAL); + assertThat(metadata.actionTags()).containsExactly(TextCommandActionTag.COMMUNICATION); + assertThat(metadata.capability()).isEqualTo(PlayerCommandCapability.MANDATORY); + }); } @Test void resolvesOptionalStandardCommandCapabilityMetadata() { assertThat(resolver.resolve("say")) .get() - .satisfies( - metadata -> - assertThat(metadata.capability()).isEqualTo(PlayerCommandCapability.SOCIAL)); + .satisfies(metadata -> + assertThat(metadata.capability()).isEqualTo(PlayerCommandCapability.SOCIAL)); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index 9b04f0e80c..1a913e76ac 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -151,15 +151,14 @@ void setUp() { when(pointerAuthorityService.listByRuntimeTarget(22L, 2L)) .thenReturn(List.of(pointer("sandbox", "production", 22L, 2L, 1L, false))); when(instanceRepository.findById(Mockito.anyLong())) - .thenAnswer( - invocation -> { - long sessionId = invocation.getArgument(0); - GameInstance perCall = new GameInstance(); - perCall.setId(sessionId); - perCall.setTenantId(22L); - perCall.setOwnerAccountId(77L); - return Optional.of(perCall); - }); + .thenAnswer(invocation -> { + long sessionId = invocation.getArgument(0); + GameInstance perCall = new GameInstance(); + perCall.setId(sessionId); + perCall.setTenantId(22L); + perCall.setOwnerAccountId(77L); + return Optional.of(perCall); + }); when(commandService.enqueue(anyString(), anyString(), anyBoolean())) .thenReturn(CommandEnqueueResult.success()); when(accountClient.authenticate(Mockito.anyString(), Mockito.anyString())) @@ -191,16 +190,15 @@ void setUp() { .setAllowed(true) .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenAnswer( - invocation -> - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(true) - .setAllowPublicJoin(true) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt(java.time.Instant.now().toString()) - .build()); + .thenAnswer(invocation -> + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(true) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt(java.time.Instant.now().toString()) + .build()); when(entityManagementClient.listCharactersByAccount( Mockito.anyString(), Mockito.anyString(), @@ -422,12 +420,11 @@ void logoutClearsSessionSoLaterLoginStartsFreshWithoutResumeOrTakeover() { .recordDisconnect(1L, AccountRecentPresenceDisposition.LOGOUT); verify(scriptEventPublisher) .publishRegionExitEvent( - Mockito.argThat( - context -> - context.sessionId() == 1L - && context.gameInstanceId() == 1L - && context.characterId() == 7001L - && "R-1021".equals(context.roomInstanceId())), + Mockito.argThat(context -> + context.sessionId() == 1L + && context.gameInstanceId() == 1L + && context.characterId() == 7001L + && "R-1021".equals(context.roomInstanceId())), Mockito.eq("logout:1:1:7001"), Mockito.eq("LOGOUT")); @@ -549,15 +546,14 @@ void staleIdentityMappingFallsBackToFreshSession() { "LOGIN demo@example.com swordfish"); when(instanceRepository.findById(Mockito.anyLong())) - .thenAnswer( - invocation -> { - long sessionId = invocation.getArgument(0); - GameInstance perCall = new GameInstance(); - perCall.setId(sessionId); - perCall.setTenantId(22L); - perCall.setOwnerAccountId(77L); - return Optional.of(perCall); - }); + .thenAnswer(invocation -> { + long sessionId = invocation.getArgument(0); + GameInstance perCall = new GameInstance(); + perCall.setId(sessionId); + perCall.setTenantId(22L); + perCall.setOwnerAccountId(77L); + return Optional.of(perCall); + }); interpreter.interpret("1", command, false); interpreter.interpret( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclarationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclarationTest.java index 2d1a477c61..cb6cd2d06f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclarationTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandEffectDeclarationTest.java @@ -9,22 +9,18 @@ class TextCommandEffectDeclarationTest { @Test void applyActionStateRejectsInvalidExecutionInvariants() { - assertThatThrownBy( - () -> - new TextCommandEffectDeclaration.ApplyActionState( - " ", Duration.ofSeconds(1), List.of())) + assertThatThrownBy(() -> + new TextCommandEffectDeclaration.ApplyActionState( + " ", Duration.ofSeconds(1), List.of())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("conditionKey must not be null or blank"); - assertThatThrownBy( - () -> - new TextCommandEffectDeclaration.ApplyActionState( - "stunned", Duration.ZERO, List.of())) + assertThatThrownBy(() -> + new TextCommandEffectDeclaration.ApplyActionState("stunned", Duration.ZERO, List.of())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("duration must be positive"); - assertThatThrownBy( - () -> - new TextCommandEffectDeclaration.ApplyActionState( - "stunned", Duration.ofSeconds(-1), List.of())) + assertThatThrownBy(() -> + new TextCommandEffectDeclaration.ApplyActionState( + "stunned", Duration.ofSeconds(-1), List.of())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("duration must be positive"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 4d10a006c7..601b555d89 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -192,16 +192,15 @@ void setUp() { .setAllowed(true) .build()); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) - .thenAnswer( - invocation -> - GetTenantEntitlementsForRuntimeResponse.newBuilder() - .setTenantId("22") - .setGameplayAvailable(true) - .setAllowPublicJoin(true) - .setEntitlementVersion(1L) - .setTenantBillingSequence(1L) - .setEvaluatedAt(java.time.Instant.now().toString()) - .build()); + .thenAnswer(invocation -> + GetTenantEntitlementsForRuntimeResponse.newBuilder() + .setTenantId("22") + .setGameplayAvailable(true) + .setAllowPublicJoin(true) + .setEntitlementVersion(1L) + .setTenantBillingSequence(1L) + .setEvaluatedAt(java.time.Instant.now().toString()) + .build()); when(gameLogicClient.queryInventory(Mockito.any(SessionContext.class))) .thenReturn( QueryInventoryResponse.newBuilder() @@ -339,15 +338,14 @@ void setUp() { when(pointerAuthorityService.listByRuntimeTarget(22L, 2L)) .thenReturn(List.of(pointer("sandbox", "production", 22L, 2L, 1L, false))); when(gameInstanceRepository.findById(Mockito.anyLong())) - .thenAnswer( - invocation -> { - long sessionId = invocation.getArgument(0); - GameInstance instance = new GameInstance(); - instance.setId(sessionId); - instance.setTenantId(22L); - instance.setOwnerAccountId(123L); - return Optional.of(instance); - }); + .thenAnswer(invocation -> { + long sessionId = invocation.getArgument(0); + GameInstance instance = new GameInstance(); + instance.setId(sessionId); + instance.setTenantId(22L); + instance.setOwnerAccountId(123L); + return Optional.of(instance); + }); sessionAuthenticationService = new SessionAuthenticationService( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java index 119eca5a11..2c01244a8f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandParserTest.java @@ -215,19 +215,18 @@ void parsesAuthoredCommandByCommandIdCaseInsensitivelyWhenNoAliasConfigured() { TextCommandParser parser = new TextCommandParser( new AggregatingTextCommandRegistry( - List.of( - () -> - List.of( - new TextCommandDefinition( - "wave-salute", - TextCommandType.AUTHORED, - List.of(), - TextCommandDispatchGroup.AUTHORED, - TextCommandStageRequirement.GAMEPLAY, - TextCommandPromptPolicy.WHEN_GAMEPLAY, - TextCommandActionCategory.GAMEPLAY, - List.of(), - TextCommandSource.GAME_AUTHORED))))); + List.of(() -> + List.of( + new TextCommandDefinition( + "wave-salute", + TextCommandType.AUTHORED, + List.of(), + TextCommandDispatchGroup.AUTHORED, + TextCommandStageRequirement.GAMEPLAY, + TextCommandPromptPolicy.WHEN_GAMEPLAY, + TextCommandActionCategory.GAMEPLAY, + List.of(), + TextCommandSource.GAME_AUTHORED))))); TextCommand command = parser.parse("WAVE-SALUTE captain"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java index 08445c1fc2..a99fd98259 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java @@ -40,12 +40,11 @@ void whoShowsBoundedEmptyStateWhenNobodyIsConnected() { Mockito.verify(scriptEventPublisher) .publishCommandEvent( Mockito.any(), - Mockito.argThat( - gameplayCommand -> - "WHO".equals(gameplayCommand.getCommandName()) - && "who".equals(gameplayCommand.getCommandText()) - && gameplayCommand.getCommandId() != null - && gameplayCommand.getCommandId().startsWith("who-"))); + Mockito.argThat(gameplayCommand -> + "WHO".equals(gameplayCommand.getCommandName()) + && "who".equals(gameplayCommand.getCommandText()) + && gameplayCommand.getCommandId() != null + && gameplayCommand.getCommandId().startsWith("who-"))); } @Test @@ -155,11 +154,9 @@ void whoAnnotatesExplicitAndAutoAfkPlayers() { assertThat(result.commandResult().accepted()).isTrue(); assertThat(result.outputs()) .singleElement() - .satisfies( - output -> - assertThat(output.payload()) - .isInstanceOf( - net.firedevops.firemud.gamesession.presentation.WhoViewOutput.class)); + .satisfies(output -> + assertThat(output.payload()) + .isInstanceOf(net.firedevops.firemud.gamesession.presentation.WhoViewOutput.class)); assertThat(render(result)).isEqualTo("Gods [0]: \nPlayers [2]: Aster, Ben (AFK)"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index e44aa7d3a2..a5c42c8781 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -138,11 +138,10 @@ void numericWorldAndRealmSelectorsResolveExactSlugsWithoutOrdinalFallback() { TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties).visibleWorlds(); AtomicInteger reads = new AtomicInteger(); var catalog = - GameplayWorldCatalog.forWorldSupplier( - () -> { - reads.incrementAndGet(); - return original; - }); + GameplayWorldCatalog.forWorldSupplier(() -> { + reads.incrementAndGet(); + return original; + }); var localHandler = new WorldsCommandHandler(catalog); var actor = GameplayCommandTestFixtures.worldBrowseDemo(); @@ -183,11 +182,10 @@ void charsAcceptsAnExactNumericRealmSlug() { void numericCharacterBrowseSelectorStillRequiresCanonicalAccountIdentity() { AtomicInteger reads = new AtomicInteger(); var catalog = - GameplayWorldCatalog.forWorldSupplier( - () -> { - reads.incrementAndGet(); - return List.of(new GameplayWorldCatalog.WorldView("123", "Numeric World", List.of())); - }); + GameplayWorldCatalog.forWorldSupplier(() -> { + reads.incrementAndGet(); + return List.of(new GameplayWorldCatalog.WorldView("123", "Numeric World", List.of())); + }); var invalidAccountContext = new net.firedevops.firemud.gamesession.service.SessionContext( 1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index a330b7b62f..cf07133b45 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -42,10 +42,9 @@ void preparedJoinExplicitlyRefusesWithoutDiscoveryOrGameplayEffects() { assertThat(result.commandResult().errorCode()).isEqualTo("FEATURE_UNAVAILABLE"); assertThat(result.outputs()) .singleElement() - .satisfies( - output -> - assertThat(output.text()) - .isEqualTo("ERROR FEATURE_UNAVAILABLE JOIN is not available.")); + .satisfies(output -> + assertThat(output.text()) + .isEqualTo("ERROR FEATURE_UNAVAILABLE JOIN is not available.")); Mockito.verifyNoInteractions(scriptEventPublisher); } @@ -65,11 +64,10 @@ void nonmatchingNumericWorldSelectorReturnsRediscoveryGuidanceWithoutPublishingA assertThat(result.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); assertThat(result.outputs()) .singleElement() - .satisfies( - output -> - assertThat(output.text()) - .isEqualTo( - "ERROR INVALID_ARGUMENT REALMS requires a valid world selector. Use WORLDS first.")); + .satisfies(output -> + assertThat(output.text()) + .isEqualTo( + "ERROR INVALID_ARGUMENT REALMS requires a valid world selector. Use WORLDS first.")); Mockito.verifyNoInteractions(scriptEventPublisher); } @@ -91,18 +89,16 @@ void dispatchAcceptsExactNumericWorldSlugWithoutTreatingItAsAListPosition() { assertThat(result.commandResult().accepted()).isTrue(); assertThat(result.outputs()) .singleElement() - .satisfies( - output -> { - assertThat(output.payload()).isInstanceOf(RealmBrowseViewOutput.class); - assertThat(((RealmBrowseViewOutput) output.payload()).worldSlug()).isEqualTo("1"); - }); + .satisfies(output -> { + assertThat(output.payload()).isInstanceOf(RealmBrowseViewOutput.class); + assertThat(((RealmBrowseViewOutput) output.payload()).worldSlug()).isEqualTo("1"); + }); Mockito.verify(scriptEventPublisher) .publishCommandEvent( Mockito.eq(context), - Mockito.argThat( - gameplayCommand -> - "REALMS".equals(gameplayCommand.getCommandName()) - && "REALMS 1".equals(gameplayCommand.getCommandText()))); + Mockito.argThat(gameplayCommand -> + "REALMS".equals(gameplayCommand.getCommandName()) + && "REALMS 1".equals(gameplayCommand.getCommandText()))); } @Test @@ -126,12 +122,11 @@ void publishesCommandEventForGameplayScopedWorldsBrowse() { Mockito.verify(scriptEventPublisher) .publishCommandEvent( Mockito.eq(context), - Mockito.argThat( - gameplayCommand -> - "WORLDS".equals(gameplayCommand.getCommandName()) - && "WORLDS".equals(gameplayCommand.getCommandText()) - && gameplayCommand.getCommandId() != null - && gameplayCommand.getCommandId().startsWith("worlds-"))); + Mockito.argThat(gameplayCommand -> + "WORLDS".equals(gameplayCommand.getCommandName()) + && "WORLDS".equals(gameplayCommand.getCommandText()) + && gameplayCommand.getCommandId() != null + && gameplayCommand.getCommandId().startsWith("worlds-"))); } @Test @@ -156,10 +151,9 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { Mockito.verify(scriptEventPublisher) .publishCommandEvent( Mockito.eq(context), - Mockito.argThat( - gameplayCommand -> - "REALMS".equals(gameplayCommand.getCommandName()) - && "REALMS demo".equals(gameplayCommand.getCommandText()))); + Mockito.argThat(gameplayCommand -> + "REALMS".equals(gameplayCommand.getCommandName()) + && "REALMS demo".equals(gameplayCommand.getCommandText()))); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/AuthenticatedGameplayRuntimeConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/AuthenticatedGameplayRuntimeConfigurationTest.java index 48587cb804..115880bb2b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/AuthenticatedGameplayRuntimeConfigurationTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/AuthenticatedGameplayRuntimeConfigurationTest.java @@ -49,16 +49,15 @@ void absentOrFalseSelectorLeavesRuntimeUnregisteredEvenWithAllAuthorities() { new String[] {"", "firemud.game-session.authenticated-gameplay.enabled=false"}) { var runner = infrastructure().withUserConfiguration(ScannedComposition.class); if (!property.isEmpty()) runner = runner.withPropertyValues(property); - runner.run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).hasSingleBean(InitialGameplayLoginCoordinationQualification.class); - assertThat(context).hasSingleBean(AccountAsymmetricJwtVerifier.class); - assertThat(context).doesNotHaveBean(CanonicalGameplayLoginAccountClient.class); - assertThat(context).doesNotHaveBean(InitialGameplayLoginOwner.class); - assertThat(context).doesNotHaveBean(DirectTextWorldSelectionService.class); - assertThat(context).doesNotHaveBean(DirectTextAuthenticatedLobbyOwner.class); - }); + runner.run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(InitialGameplayLoginCoordinationQualification.class); + assertThat(context).hasSingleBean(AccountAsymmetricJwtVerifier.class); + assertThat(context).doesNotHaveBean(CanonicalGameplayLoginAccountClient.class); + assertThat(context).doesNotHaveBean(InitialGameplayLoginOwner.class); + assertThat(context).doesNotHaveBean(DirectTextWorldSelectionService.class); + assertThat(context).doesNotHaveBean(DirectTextAuthenticatedLobbyOwner.class); + }); } } @@ -67,25 +66,24 @@ void componentScanComposesRealOwnersFromSeparateAuthorities() { infrastructure() .withUserConfiguration(ScannedComposition.class) .withPropertyValues(ENABLED) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).hasSingleBean(CanonicalGameplayLoginAccountClient.class); - assertThat(context).hasSingleBean(InitialGameplayLoginOwner.class); - assertThat(context).hasSingleBean(DirectTextWorldSelectionService.class); - assertThat(context).hasSingleBean(DirectTextAuthenticatedLobbyOwner.class); - verifyNoInteractions( - context.getBean(InitialGameplayLoginRedisBinding.class), - context.getBean(InitialGameplayLoginCoordinationQualification.class), - context.getBean(AccountAsymmetricJwtVerifier.class), - context.getBean(CanonicalPlayerRouteReadService.class), - context.getBean(DSLContext.class)); - // Spring invokes this ordinary client's @PostConstruct callback, but composition - // must make no Account RPC or other client call. - assertThat(mockingDetails(context.getBean(AccountClient.class)).getInvocations()) - .extracting(invocation -> invocation.getMethod().getName()) - .containsExactly("init"); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(CanonicalGameplayLoginAccountClient.class); + assertThat(context).hasSingleBean(InitialGameplayLoginOwner.class); + assertThat(context).hasSingleBean(DirectTextWorldSelectionService.class); + assertThat(context).hasSingleBean(DirectTextAuthenticatedLobbyOwner.class); + verifyNoInteractions( + context.getBean(InitialGameplayLoginRedisBinding.class), + context.getBean(InitialGameplayLoginCoordinationQualification.class), + context.getBean(AccountAsymmetricJwtVerifier.class), + context.getBean(CanonicalPlayerRouteReadService.class), + context.getBean(DSLContext.class)); + // Spring invokes this ordinary client's @PostConstruct callback, but composition + // must make no Account RPC or other client call. + assertThat(mockingDetails(context.getBean(AccountClient.class)).getInvocations()) + .extracting(invocation -> invocation.getMethod().getName()) + .containsExactly("init"); + }); } @ParameterizedTest @@ -102,14 +100,13 @@ void composesWithRuntimeRegisteredBeforeOrAfterAuthorityConfiguration(boolean ru infrastructure() .withUserConfiguration(configurations) .withPropertyValues(ENABLED) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).hasSingleBean(CanonicalGameplayLoginAccountClient.class); - assertThat(context).hasSingleBean(InitialGameplayLoginOwner.class); - assertThat(context).hasSingleBean(DirectTextWorldSelectionService.class); - assertThat(context).hasSingleBean(DirectTextAuthenticatedLobbyOwner.class); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(CanonicalGameplayLoginAccountClient.class); + assertThat(context).hasSingleBean(InitialGameplayLoginOwner.class); + assertThat(context).hasSingleBean(DirectTextWorldSelectionService.class); + assertThat(context).hasSingleBean(DirectTextAuthenticatedLobbyOwner.class); + }); } @ParameterizedTest @@ -118,12 +115,11 @@ void enabledRuntimeFailsStartupForEveryMissingAuthority(String missing) { infrastructure() .withUserConfiguration(ScannedComposition.class) .withPropertyValues(ENABLED, "fixture.authority." + missing + "=false") - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasRootCauseInstanceOf(NoSuchBeanDefinitionException.class); - }); + .run(context -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasRootCauseInstanceOf(NoSuchBeanDefinitionException.class); + }); } private static ApplicationContextRunner infrastructure() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfigurationTest.java index 7de92397fc..cab59274c4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfigurationTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalGameInstanceLaunchAssociationReadConfigurationTest.java @@ -20,12 +20,11 @@ void associationOwnerRepositoryIsDisabledByDefault() { new ApplicationContextRunner() .withUserConfiguration( CanonicalGameInstanceLaunchAssociationReadConfiguration.class, Dependencies.class) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context) - .doesNotHaveBean(CanonicalGameInstanceLaunchAssociationRepository.class); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .doesNotHaveBean(CanonicalGameInstanceLaunchAssociationRepository.class); + }); } @Test @@ -34,12 +33,10 @@ void explicitOptInRequiresAndUsesTheExactWorkloadNamespace() { .withUserConfiguration( CanonicalGameInstanceLaunchAssociationReadConfiguration.class, Dependencies.class) .withPropertyValues(OWNER_OPT_IN + "=true", "firemud.grpc.workload-namespace=gameplay") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context) - .hasSingleBean(CanonicalGameInstanceLaunchAssociationRepository.class); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(CanonicalGameInstanceLaunchAssociationRepository.class); + }); new ApplicationContextRunner() .withUserConfiguration( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfigurationTest.java index 7aa4812c98..53f700018d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfigurationTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalInitialAdmissionOwnerConfigurationTest.java @@ -27,12 +27,11 @@ class CanonicalInitialAdmissionOwnerConfigurationTest { void disabledOwnerCompositionDoesNotRequireCanonicalLaunchRepositories() { new ApplicationContextRunner() .withUserConfiguration(CanonicalInitialAdmissionOwnerConfiguration.class) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(CanonicalInitialAdmissionRepository.class); - assertThat(context).doesNotHaveBean(CanonicalInitialAdmissionService.class); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(CanonicalInitialAdmissionRepository.class); + assertThat(context).doesNotHaveBean(CanonicalInitialAdmissionService.class); + }); } @Test @@ -51,12 +50,11 @@ void enabledCompositionCreatesOwnerServiceOnlyWithItsExplicitDependencies() { CanonicalInitialAdmissionOwnerConfiguration.class, OwnerDependencies.class) .withPropertyValues(OWNER_OPT_IN + "=true", "firemud.grpc.workload-namespace=gameplay") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).hasSingleBean(CanonicalInitialAdmissionRepository.class); - assertThat(context).hasSingleBean(CanonicalInitialAdmissionService.class); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(CanonicalInitialAdmissionRepository.class); + assertThat(context).hasSingleBean(CanonicalInitialAdmissionService.class); + }); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfigurationTest.java index fb9a999971..7415823bab 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfigurationTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/CanonicalPlayerRouteReadConfigurationTest.java @@ -39,14 +39,13 @@ class CanonicalPlayerRouteReadConfigurationTest { void defaultConfigurationLeavesCanonicalRosterRouteSourceUnregistered() { new ApplicationContextRunner() .withUserConfiguration(CanonicalPlayerRouteReadConfiguration.class) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(GameDesignPublishedRealmPolicyClient.class); - assertThat(context).doesNotHaveBean(CanonicalPlayerRouteReadService.class); - assertThat(context).doesNotHaveBean(CanonicalPublishedPlayerRouteReadService.class); - assertThat(context).doesNotHaveBean(CanonicalGameplayRosterSelectionService.class); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(GameDesignPublishedRealmPolicyClient.class); + assertThat(context).doesNotHaveBean(CanonicalPlayerRouteReadService.class); + assertThat(context).doesNotHaveBean(CanonicalPublishedPlayerRouteReadService.class); + assertThat(context).doesNotHaveBean(CanonicalGameplayRosterSelectionService.class); + }); } @Test @@ -54,14 +53,13 @@ void explicitlyDisabledConfigurationLeavesCanonicalRosterRouteSourceUnregistered new ApplicationContextRunner() .withUserConfiguration(CanonicalPlayerRouteReadConfiguration.class) .withPropertyValues("firemud.canonical-gameplay-roster-owner-read.enabled=false") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(GameDesignPublishedRealmPolicyClient.class); - assertThat(context).doesNotHaveBean(CanonicalPlayerRouteReadService.class); - assertThat(context).doesNotHaveBean(CanonicalPublishedPlayerRouteReadService.class); - assertThat(context).doesNotHaveBean(CanonicalGameplayRosterSelectionService.class); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(GameDesignPublishedRealmPolicyClient.class); + assertThat(context).doesNotHaveBean(CanonicalPlayerRouteReadService.class); + assertThat(context).doesNotHaveBean(CanonicalPublishedPlayerRouteReadService.class); + assertThat(context).doesNotHaveBean(CanonicalGameplayRosterSelectionService.class); + }); } // Composition proof only: repositories and channels are controlled doubles with file-backed @@ -104,65 +102,64 @@ void enabledConfigurationComposesRealRouteSourcesWithFileBackedTlsAndExactTarget .withPropertyValues( "firemud.canonical-gameplay-roster-owner-read.enabled=true", "firemud.grpc.workload-namespace=games") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).hasSingleBean(GameDesignPublishedRealmPolicyClient.class); - assertThat(context).hasSingleBean(CanonicalPlayerRouteReadService.class); - assertThat(context).hasSingleBean(CanonicalPublishedPlayerRouteReadService.class); - assertThat(context).hasSingleBean(CanonicalGameplayRosterSelectionService.class); - assertThat(context).hasSingleBean(CanonicalGameplayRosterClient.class); - assertThat(context) - .doesNotHaveBean( - net.firedevops.firemud.gamesession.service - .CanonicalGameplayRosterReferenceOwner.class); - var rosterClient = context.getBean(CanonicalGameplayRosterClient.class); - assertThat(Mockito.mockingDetails(rosterClient).isMock()).isFalse(); - var published = - support.net.firedevops.firemud.gamesession.PublishedRealmPolicyEvidenceFixture - .canonicalPublishedRoute(); - var route = published.route(); - var player = - net.firedevops.firemud.shared.v1.PlayerExecutionContext.newBuilder() - .setAccountId("66666666-6666-4666-8666-666666666666") - .setSessionId("dddddddd-dddd-4ddd-8ddd-dddddddddddd") - .setRequestId("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee") - .setTenantId(route.canonicalTenantId().toString()) - .setRealmId(route.realmId().toString()) - .setPlayableStateNamespaceId(route.playableStateNamespaceId().toString()) - .setPlayableStateScope(route.playableStateScope()) - .setGameInstanceId(route.canonicalGameInstanceId().toString()) - .build(); - assertThatThrownBy(() -> rosterClient.listPreseededRoster(published, player)) - .isInstanceOfSatisfying( - io.grpc.StatusRuntimeException.class, - failure -> - assertThat(failure.getStatus().getCode()) - .isEqualTo(io.grpc.Status.Code.UNAVAILABLE)); - verify(channel, never()).newCall(any(), any()); - assertThat( - Mockito.mockingDetails( - context.getBean(GameDesignPublishedRealmPolicyClient.class)) - .isMock()) - .isFalse(); - assertThat( - Mockito.mockingDetails(context.getBean(CanonicalPlayerRouteReadService.class)) - .isMock()) - .isFalse(); - assertThat( - Mockito.mockingDetails( - context.getBean(CanonicalPublishedPlayerRouteReadService.class)) - .isMock()) - .isFalse(); - verify(channelFactory) - .buildChannel(eq("game-design.test:7654"), eq(6565), eq(tlsProperties), eq(true)); - verify(channelFactory) - .buildChannel(eq("entity.test:7655"), eq(6565), eq(tlsProperties), eq(true)); - verifyNoInteractions( - context.getBean(GameSessionCanonicalRealmCatalogRepository.class), - context.getBean(CanonicalInitialAdmissionRepository.class), - context.getBean(CanonicalGameInstanceLaunchAssociationRepository.class)); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(GameDesignPublishedRealmPolicyClient.class); + assertThat(context).hasSingleBean(CanonicalPlayerRouteReadService.class); + assertThat(context).hasSingleBean(CanonicalPublishedPlayerRouteReadService.class); + assertThat(context).hasSingleBean(CanonicalGameplayRosterSelectionService.class); + assertThat(context).hasSingleBean(CanonicalGameplayRosterClient.class); + assertThat(context) + .doesNotHaveBean( + net.firedevops.firemud.gamesession.service.CanonicalGameplayRosterReferenceOwner + .class); + var rosterClient = context.getBean(CanonicalGameplayRosterClient.class); + assertThat(Mockito.mockingDetails(rosterClient).isMock()).isFalse(); + var published = + support.net.firedevops.firemud.gamesession.PublishedRealmPolicyEvidenceFixture + .canonicalPublishedRoute(); + var route = published.route(); + var player = + net.firedevops.firemud.shared.v1.PlayerExecutionContext.newBuilder() + .setAccountId("66666666-6666-4666-8666-666666666666") + .setSessionId("dddddddd-dddd-4ddd-8ddd-dddddddddddd") + .setRequestId("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee") + .setTenantId(route.canonicalTenantId().toString()) + .setRealmId(route.realmId().toString()) + .setPlayableStateNamespaceId(route.playableStateNamespaceId().toString()) + .setPlayableStateScope(route.playableStateScope()) + .setGameInstanceId(route.canonicalGameInstanceId().toString()) + .build(); + assertThatThrownBy(() -> rosterClient.listPreseededRoster(published, player)) + .isInstanceOfSatisfying( + io.grpc.StatusRuntimeException.class, + failure -> + assertThat(failure.getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.UNAVAILABLE)); + verify(channel, never()).newCall(any(), any()); + assertThat( + Mockito.mockingDetails( + context.getBean(GameDesignPublishedRealmPolicyClient.class)) + .isMock()) + .isFalse(); + assertThat( + Mockito.mockingDetails(context.getBean(CanonicalPlayerRouteReadService.class)) + .isMock()) + .isFalse(); + assertThat( + Mockito.mockingDetails( + context.getBean(CanonicalPublishedPlayerRouteReadService.class)) + .isMock()) + .isFalse(); + verify(channelFactory) + .buildChannel(eq("game-design.test:7654"), eq(6565), eq(tlsProperties), eq(true)); + verify(channelFactory) + .buildChannel(eq("entity.test:7655"), eq(6565), eq(tlsProperties), eq(true)); + verifyNoInteractions( + context.getBean(GameSessionCanonicalRealmCatalogRepository.class), + context.getBean(CanonicalInitialAdmissionRepository.class), + context.getBean(CanonicalGameInstanceLaunchAssociationRepository.class)); + }); } @Test @@ -196,10 +193,9 @@ void enabledConfigurationRejectsInvalidNamespaceBeforeOpeningChannel(@TempDir Pa .withPropertyValues( "firemud.canonical-gameplay-roster-owner-read.enabled=true", "firemud.grpc.workload-namespace=games.invalid") - .run( - context -> { - assertThat(context).hasFailed(); - verifyNoInteractions(channelFactory); - }); + .run(context -> { + assertThat(context).hasFailed(); + verifyNoInteractions(channelFactory); + }); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolverTest.java index c5ceb6545f..4c3cfa628d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolverTest.java @@ -19,14 +19,12 @@ void rejectsInvalidOperatorDefaultsDuringConstruction() { Mockito.mock(SharedSettingsAuthorityReader.class); assertThatIllegalStateException() - .isThrownBy( - () -> - new EffectiveReconnectionSettingsResolver( - new FiremudReconnectionProperties( - new FiremudReconnectionProperties.Policy(45_000L, true), - new FiremudReconnectionProperties.Buffer( - 60_000L, 256, 8, 24, 70_000, 65_536)), - authorityReader)) + .isThrownBy(() -> + new EffectiveReconnectionSettingsResolver( + new FiremudReconnectionProperties( + new FiremudReconnectionProperties.Policy(45_000L, true), + new FiremudReconnectionProperties.Buffer(60_000L, 256, 8, 24, 70_000, 65_536)), + authorityReader)) .withMessage("Operator reconnection buffer hardMaxBytes must be at least softMaxBytes"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionAccountPublicJwksConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionAccountPublicJwksConfigurationTest.java index f5079c7290..7e4544454d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionAccountPublicJwksConfigurationTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionAccountPublicJwksConfigurationTest.java @@ -49,16 +49,15 @@ void disabledByDefaultAndWhenExplicitlyDisabled() { new ApplicationContextRunner() .withUserConfiguration(GameSessionAccountPublicJwksConfiguration.class); if (!enabled.isEmpty()) runner = runner.withPropertyValues(enabled); - runner.run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(AccountPublicJwksReadClient.class); - assertThat(context).doesNotHaveBean(GameSessionAccountPublicJwksSource.class); - assertThat(context).doesNotHaveBean(AccountPublicJwksCache.class); - assertThat(context).doesNotHaveBean(AccountAsymmetricJwtVerifier.class); - assertThat(context) - .doesNotHaveBean(GameSessionAccountPublicJwksConfiguration.PublicJwksRefresh.class); - }); + runner.run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(AccountPublicJwksReadClient.class); + assertThat(context).doesNotHaveBean(GameSessionAccountPublicJwksSource.class); + assertThat(context).doesNotHaveBean(AccountPublicJwksCache.class); + assertThat(context).doesNotHaveBean(AccountAsymmetricJwtVerifier.class); + assertThat(context) + .doesNotHaveBean(GameSessionAccountPublicJwksConfiguration.PublicJwksRefresh.class); + }); } } @@ -120,10 +119,8 @@ void cacheInitializesFromActualSourcePinAndRefreshesBeforeCompositionReturns() { "a".repeat(64)); when(source.sourceIdentity()).thenReturn(identity); when(source.load()).thenThrow(new SourceUnavailableException()); - assertThatThrownBy( - () -> - new GameSessionAccountPublicJwksConfiguration() - .accountPublicJwksCache(source, 2000)) + assertThatThrownBy(() -> + new GameSessionAccountPublicJwksConfiguration().accountPublicJwksCache(source, 2000)) .isInstanceOf(SourceUnavailableException.class); verify(source).sourceIdentity(); verify(source).load(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfigurationTest.java index 627f0ccb5c..b857515b80 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfigurationTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionGrpcRequestByteConfigurationTest.java @@ -87,11 +87,10 @@ void onlyGeneratedAcknowledgementAndConfirmationDescriptorsReceiveLargeAdmission ServerServiceDefinition.builder("test.Unrelated") .addMethod( ordinary, - io.grpc.stub.ServerCalls.asyncUnaryCall( - (request, response) -> { - response.onNext(Empty.getDefaultInstance()); - response.onCompleted(); - })) + io.grpc.stub.ServerCalls.asyncUnaryCall((request, response) -> { + response.onNext(Empty.getDefaultInstance()); + response.onCompleted(); + })) .build(), parsedMessages)); Server server = factory.createServer(); @@ -146,42 +145,38 @@ void onlyGeneratedAcknowledgementAndConfirmationDescriptorsReceiveLargeAdmission @Test void activeGameSessionPolicyFailsStartupWithoutSharedGuardOrWithPlainFactory() { var runner = productionRunner(false); - runner.run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasRootCauseInstanceOf( - org.springframework.beans.factory.NoSuchBeanDefinitionException.class); - }); + runner.run(context -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasRootCauseInstanceOf( + org.springframework.beans.factory.NoSuchBeanDefinitionException.class); + }); runner .withBean( GrpcServerFactory.class, () -> new ShadedNettyGrpcServerFactory( "127.0.0.1:0", List.of(), null, null, TlsServerCredentials.ClientAuth.NONE)) - .run( - context -> { - assertThat(context).hasFailed(); - assertThat(context.getStartupFailure()) - .hasRootCauseInstanceOf( - org.springframework.beans.factory.NoSuchBeanDefinitionException.class); - }); + .run(context -> { + assertThat(context).hasFailed(); + assertThat(context.getStartupFailure()) + .hasRootCauseInstanceOf( + org.springframework.beans.factory.NoSuchBeanDefinitionException.class); + }); } @Test void realProductionDiscoverySatisfiesRequiredGameSessionGuardAndClosedPolicy() { productionRunner(true) - .run( - context -> { - assertThat(context).hasNotFailed().hasSingleBean(GrpcServerFactory.class); - assertThat(context.getBean(GrpcServerFactory.class)) - .isExactlyInstanceOf(BoundedGrpcServerFactory.class); - assertThat(context.getBean(GrpcServerLifecycle.class).isRunning()).isTrue(); - assertThat(context.getBean(GrpcRequestBytePolicy.class).transportMaximumBytes()) - .isEqualTo( - CanonicalGameplayRosterRetirementEvidence - .MAX_PLAYER_CREATED_CONFIRMATION_BYTES); - }); + .run(context -> { + assertThat(context).hasNotFailed().hasSingleBean(GrpcServerFactory.class); + assertThat(context.getBean(GrpcServerFactory.class)) + .isExactlyInstanceOf(BoundedGrpcServerFactory.class); + assertThat(context.getBean(GrpcServerLifecycle.class).isRunning()).isTrue(); + assertThat(context.getBean(GrpcRequestBytePolicy.class).transportMaximumBytes()) + .isEqualTo( + CanonicalGameplayRosterRetirementEvidence.MAX_PLAYER_CREATED_CONFIRMATION_BYTES); + }); } private static byte[] rawRequest(int size) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfigurationTest.java index 0c9a99d052..92dc0b5b02 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfigurationTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/GameSessionStartSessionOperatorAuthorizationConfigurationTest.java @@ -37,160 +37,139 @@ class GameSessionStartSessionOperatorAuthorizationConfigurationTest { void ownerAuthorizationCompositionIsDisabledByDefault() { new ApplicationContextRunner() .withUserConfiguration(GameSessionStartSessionOperatorAuthorizationConfiguration.class) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context) - .doesNotHaveBean(GameSessionStartSessionOperatorAttemptRepository.class); - assertThat(context).doesNotHaveBean(StartSessionOperatorRedemptionClient.class); - assertThat(context) - .doesNotHaveBean(GameSessionStartSessionOperatorAuthorizationCoordinator.class); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .doesNotHaveBean(GameSessionStartSessionOperatorAttemptRepository.class); + assertThat(context).doesNotHaveBean(StartSessionOperatorRedemptionClient.class); + assertThat(context) + .doesNotHaveBean(GameSessionStartSessionOperatorAuthorizationCoordinator.class); + }); } @Test void enabledCompositionRequiresExplicitOwnerLeaseAndWorkloadNamespace() { - withTlsReloadDisabled( - () -> - new ApplicationContextRunner() - .withUserConfiguration( - GameSessionStartSessionOperatorAuthorizationConfiguration.class, - Dependencies.class) - .withPropertyValues( - OWNER_OPT_IN + "=true", - WORKLOAD_NAMESPACE + "=gameplay", - "firemud.grpc.cert-chain=test-cert", - "firemud.grpc.private-key=test-key", - "firemud.grpc.ca-cert=test-ca") - .run(context -> assertThat(context).hasFailed())); + withTlsReloadDisabled(() -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, Dependencies.class) + .withPropertyValues( + OWNER_OPT_IN + "=true", + WORKLOAD_NAMESPACE + "=gameplay", + "firemud.grpc.cert-chain=test-cert", + "firemud.grpc.private-key=test-key", + "firemud.grpc.ca-cert=test-ca") + .run(context -> assertThat(context).hasFailed())); - withTlsReloadDisabled( - () -> - new ApplicationContextRunner() - .withUserConfiguration( - GameSessionStartSessionOperatorAuthorizationConfiguration.class, - Dependencies.class) - .withPropertyValues( - OWNER_OPT_IN + "=true", - OWNER_CLAIM_LEASE + "=30s", - "firemud.grpc.cert-chain=test-cert", - "firemud.grpc.private-key=test-key", - "firemud.grpc.ca-cert=test-ca") - .run(context -> assertThat(context).hasFailed())); + withTlsReloadDisabled(() -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, Dependencies.class) + .withPropertyValues( + OWNER_OPT_IN + "=true", + OWNER_CLAIM_LEASE + "=30s", + "firemud.grpc.cert-chain=test-cert", + "firemud.grpc.private-key=test-key", + "firemud.grpc.ca-cert=test-ca") + .run(context -> assertThat(context).hasFailed())); } @Test void enabledCompositionRequiresMutualTlsPropertiesAndOwnerCollaborators() { - withTlsReloadDisabled( - () -> - new ApplicationContextRunner() - .withUserConfiguration( - GameSessionStartSessionOperatorAuthorizationConfiguration.class, - Dependencies.class) - .withPropertyValues( - OWNER_OPT_IN + "=true", - OWNER_CLAIM_LEASE + "=30s", - WORKLOAD_NAMESPACE + "=gameplay") - .run(context -> assertThat(context).hasFailed())); + withTlsReloadDisabled(() -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, Dependencies.class) + .withPropertyValues( + OWNER_OPT_IN + "=true", + OWNER_CLAIM_LEASE + "=30s", + WORKLOAD_NAMESPACE + "=gameplay") + .run(context -> assertThat(context).hasFailed())); - withTlsReloadDisabled( - () -> - new ApplicationContextRunner() - .withUserConfiguration( - GameSessionStartSessionOperatorAuthorizationConfiguration.class) - .withPropertyValues(completeOwnerProperties()) - .run(context -> assertThat(context).hasFailed())); + withTlsReloadDisabled(() -> + new ApplicationContextRunner() + .withUserConfiguration(GameSessionStartSessionOperatorAuthorizationConfiguration.class) + .withPropertyValues(completeOwnerProperties()) + .run(context -> assertThat(context).hasFailed())); } @Test void enabledCompositionRequiresItsTransactionManager() { - withTlsReloadDisabled( - () -> - new ApplicationContextRunner() - .withUserConfiguration( - GameSessionStartSessionOperatorAuthorizationConfiguration.class, - Dependencies.class) - .withPropertyValues(completeOwnerProperties()) - .withPropertyValues("test.start-session.transaction-manager-enabled=false") - .run(context -> assertThat(context).hasFailed())); + withTlsReloadDisabled(() -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, Dependencies.class) + .withPropertyValues(completeOwnerProperties()) + .withPropertyValues("test.start-session.transaction-manager-enabled=false") + .run(context -> assertThat(context).hasFailed())); } @Test void ownerClaimLeaseUsesRepositoryFiveMinuteBound() { - withTlsReloadDisabled( - () -> - new ApplicationContextRunner() - .withUserConfiguration( - GameSessionStartSessionOperatorAuthorizationConfiguration.class, - Dependencies.class) - .withPropertyValues( - OWNER_OPT_IN + "=true", - OWNER_CLAIM_LEASE + "=6m", - WORKLOAD_NAMESPACE + "=gameplay", - "firemud.grpc.cert-chain=test-cert", - "firemud.grpc.private-key=test-key", - "firemud.grpc.ca-cert=test-ca") - .run(context -> assertThat(context).hasFailed())); + withTlsReloadDisabled(() -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, Dependencies.class) + .withPropertyValues( + OWNER_OPT_IN + "=true", + OWNER_CLAIM_LEASE + "=6m", + WORKLOAD_NAMESPACE + "=gameplay", + "firemud.grpc.cert-chain=test-cert", + "firemud.grpc.private-key=test-key", + "firemud.grpc.ca-cert=test-ca") + .run(context -> assertThat(context).hasFailed())); } @Test void explicitCompositionUsesOwnerDependenciesAndManagedClientLifecycle() { - withTlsReloadDisabled( - () -> - new ApplicationContextRunner() - .withUserConfiguration( - GameSessionStartSessionOperatorAuthorizationConfiguration.class, - Dependencies.class) - .withPropertyValues(completeOwnerProperties()) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context) - .hasSingleBean(GameSessionStartSessionOperatorAttemptRepository.class); - assertThat(context).hasSingleBean(StartSessionOperatorRedemptionClient.class); - assertThat(context) - .hasSingleBean( - GameSessionStartSessionOperatorAuthorizationCoordinator.class); + withTlsReloadDisabled(() -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, Dependencies.class) + .withPropertyValues(completeOwnerProperties()) + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context) + .hasSingleBean(GameSessionStartSessionOperatorAttemptRepository.class); + assertThat(context).hasSingleBean(StartSessionOperatorRedemptionClient.class); + assertThat(context) + .hasSingleBean(GameSessionStartSessionOperatorAuthorizationCoordinator.class); - var channelFactory = context.getBean(ControlledGrpcChannelFactory.class); - assertThat(channelFactory.buildCount()).isEqualTo(1); - assertThat(channelFactory.lastTarget()).isEqualTo("account-service:6565"); - assertThat(channelFactory.lastDefaultPort()).isEqualTo(6565); - assertThat(channelFactory.lastKeepAlive()).isTrue(); - context.close(); - verify(channelFactory.channel()).shutdown(); - })); + var channelFactory = context.getBean(ControlledGrpcChannelFactory.class); + assertThat(channelFactory.buildCount()).isEqualTo(1); + assertThat(channelFactory.lastTarget()).isEqualTo("account-service:6565"); + assertThat(channelFactory.lastDefaultPort()).isEqualTo(6565); + assertThat(channelFactory.lastKeepAlive()).isTrue(); + context.close(); + verify(channelFactory.channel()).shutdown(); + })); } @Test void enabledCompositionUsesCanonicalTransactionManagerWhenMultipleArePresent() { - withTlsReloadDisabled( - () -> - new ApplicationContextRunner() - .withUserConfiguration( - GameSessionStartSessionOperatorAuthorizationConfiguration.class, - Dependencies.class, - AdditionalTransactionManager.class) - .withPropertyValues(completeOwnerProperties()) - .run( - context -> { - assertThat(context).hasNotFailed(); - var coordinator = - context.getBean( - GameSessionStartSessionOperatorAuthorizationCoordinator.class); - var ownerTransaction = - (TransactionTemplate) - ReflectionTestUtils.getField(coordinator, "ownerTransaction"); - var canonicalTransactionManager = - context.getBean("transactionManager", PlatformTransactionManager.class); - var otherTransactionManager = - context.getBean( - "otherTransactionManager", PlatformTransactionManager.class); + withTlsReloadDisabled(() -> + new ApplicationContextRunner() + .withUserConfiguration( + GameSessionStartSessionOperatorAuthorizationConfiguration.class, + Dependencies.class, + AdditionalTransactionManager.class) + .withPropertyValues(completeOwnerProperties()) + .run(context -> { + assertThat(context).hasNotFailed(); + var coordinator = + context.getBean(GameSessionStartSessionOperatorAuthorizationCoordinator.class); + var ownerTransaction = + (TransactionTemplate) + ReflectionTestUtils.getField(coordinator, "ownerTransaction"); + var canonicalTransactionManager = + context.getBean("transactionManager", PlatformTransactionManager.class); + var otherTransactionManager = + context.getBean("otherTransactionManager", PlatformTransactionManager.class); - assertThat(ownerTransaction.getTransactionManager()) - .isSameAs(canonicalTransactionManager) - .isNotSameAs(otherTransactionManager); - })); + assertThat(ownerTransaction.getTransactionManager()) + .isSameAs(canonicalTransactionManager) + .isNotSameAs(otherTransactionManager); + })); } private static String[] completeOwnerProperties() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/InitialGameplayLoginProtectedSourcesConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/InitialGameplayLoginProtectedSourcesConfigurationTest.java index e0c18fdfee..02aaecb47d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/InitialGameplayLoginProtectedSourcesConfigurationTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/InitialGameplayLoginProtectedSourcesConfigurationTest.java @@ -40,14 +40,12 @@ void sourcesAreDisabledByDefaultAndWhenExplicitlyDisabled() { new ApplicationContextRunner() .withUserConfiguration(InitialGameplayLoginProtectedSourcesConfiguration.class); if (!enabled.isEmpty()) runner = runner.withPropertyValues(enabled); - runner.run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(AccountAsymmetricJwtVerifier.class); - assertThat(context).doesNotHaveBean(InitialGameplayLoginRedisBinding.class); - assertThat(context) - .doesNotHaveBean(LettuceInitialGameplayLoginConnectionProvider.class); - }); + runner.run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(AccountAsymmetricJwtVerifier.class); + assertThat(context).doesNotHaveBean(InitialGameplayLoginRedisBinding.class); + assertThat(context).doesNotHaveBean(LettuceInitialGameplayLoginConnectionProvider.class); + }); } } @@ -95,9 +93,8 @@ void dedicatedUriRequiresExactTlsPrincipalDatabaseAndFiniteDeadline() { "rediss://gamesession_coord_app:secret@coordination.example.invalid:6380/0 bad" }) void rejectsAmbientPlaintextChangedOrAmbiguousCoordinationSources(String uri) { - assertThatThrownBy( - () -> - InitialGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri(uri, 875)) + assertThatThrownBy(() -> + InitialGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri(uri, 875)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Protected Game Session initial LOGIN sources required") .hasNoCause(); @@ -106,10 +103,9 @@ void rejectsAmbientPlaintextChangedOrAmbiguousCoordinationSources(String uri) { @ParameterizedTest @ValueSource(ints = {-1, 0, 60_001}) void rejectsUnboundedCommandDeadlines(int timeoutMillis) { - assertThatThrownBy( - () -> - InitialGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( - COORDINATION_URI, timeoutMillis)) + assertThatThrownBy(() -> + InitialGameplayLoginProtectedSourcesConfiguration.requiredCoordinationUri( + COORDINATION_URI, timeoutMillis)) .isInstanceOf(IllegalArgumentException.class) .hasNoCause(); } @@ -117,31 +113,27 @@ void rejectsUnboundedCommandDeadlines(int timeoutMillis) { @Test void sourceBindingRequiresExplicitProfileIdentityAndAcknowledgements() { var connections = mock(LettuceInitialGameplayLoginConnectionProvider.class); - assertThatThrownBy( - () -> - configuration.initialGameplayLoginRedisBinding( - connections, "", "REPLICATED", 1, 1, 875)) + assertThatThrownBy(() -> + configuration.initialGameplayLoginRedisBinding( + connections, "", "REPLICATED", 1, 1, 875)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Protected Coordination binding identity required") .hasNoCause(); - assertThatThrownBy( - () -> - configuration.initialGameplayLoginRedisBinding( - connections, "delivered-binding", "", 1, 1, 875)) + assertThatThrownBy(() -> + configuration.initialGameplayLoginRedisBinding( + connections, "delivered-binding", "", 1, 1, 875)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Protected Coordination profile is invalid") .hasNoCause(); - assertThatThrownBy( - () -> - configuration.initialGameplayLoginRedisBinding( - connections, "delivered-binding", "REPLICATED", 1, 0, 875)) + assertThatThrownBy(() -> + configuration.initialGameplayLoginRedisBinding( + connections, "delivered-binding", "REPLICATED", 1, 0, 875)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Explicit Coordination ACK policy is invalid") .hasNoCause(); - assertThatThrownBy( - () -> - configuration.initialGameplayLoginRedisBinding( - connections, "delivered-binding", "SINGLE_NODE_NO_FAILOVER", 1, 1, 875)) + assertThatThrownBy(() -> + configuration.initialGameplayLoginRedisBinding( + connections, "delivered-binding", "SINGLE_NODE_NO_FAILOVER", 1, 1, 875)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Explicit Coordination ACK policy is invalid") .hasNoCause(); @@ -151,22 +143,20 @@ void sourceBindingRequiresExplicitProfileIdentityAndAcknowledgements() { @Test void invalidBindingDiagnosticsDoNotRetainDeliveredValuesOrCauses() { var connections = mock(LettuceInitialGameplayLoginConnectionProvider.class); - assertThatThrownBy( - () -> - configuration.initialGameplayLoginRedisBinding( - connections, - "delivered-binding", - "rediss://user:do-not-log@private.example.invalid:6380/0", - 1, - 1, - 875)) + assertThatThrownBy(() -> + configuration.initialGameplayLoginRedisBinding( + connections, + "delivered-binding", + "rediss://user:do-not-log@private.example.invalid:6380/0", + 1, + 1, + 875)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Protected Coordination profile is invalid") .hasNoCause(); - assertThatThrownBy( - () -> - configuration.initialGameplayLoginRedisBinding( - connections, "do-not-log-binding\n", "REPLICATED", 1, 1, 875)) + assertThatThrownBy(() -> + configuration.initialGameplayLoginRedisBinding( + connections, "do-not-log-binding\n", "REPLICATED", 1, 1, 875)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Protected Coordination binding identity required") .hasNoCause(); @@ -183,20 +173,19 @@ void concreteRedisSourceDoesNotSupplyVerifierMaintenanceAuthorityOrLogin() { InitialGameplayLoginProtectedSourcesConfiguration.class, AuthenticatedGameplayRuntimeConfiguration.class) .withPropertyValues(completeProperties()) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(GameSessionJwtReadinessProbeOwnerClient.class); - assertThat(context).doesNotHaveBean(AccountPublicJwksCache.class); - assertThat(context).doesNotHaveBean(AccountAsymmetricJwtVerifier.class); - assertThat(context).hasSingleBean(InitialGameplayLoginRedisBinding.class); - assertThat(context) - .doesNotHaveBean(InitialGameplayLoginCoordinationQualification.class); - assertThat(context).doesNotHaveBean(InitialGameplayLoginOwner.class); - var binding = context.getBean(InitialGameplayLoginRedisBinding.class); - assertThat(binding.protectedBindingId()).isEqualTo("delivered-binding"); - assertThat(binding.acknowledgementPolicy().requiredReplicaAofCount()).isEqualTo(1); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(GameSessionJwtReadinessProbeOwnerClient.class); + assertThat(context).doesNotHaveBean(AccountPublicJwksCache.class); + assertThat(context).doesNotHaveBean(AccountAsymmetricJwtVerifier.class); + assertThat(context).hasSingleBean(InitialGameplayLoginRedisBinding.class); + assertThat(context) + .doesNotHaveBean(InitialGameplayLoginCoordinationQualification.class); + assertThat(context).doesNotHaveBean(InitialGameplayLoginOwner.class); + var binding = context.getBean(InitialGameplayLoginRedisBinding.class); + assertThat(binding.protectedBindingId()).isEqualTo("delivered-binding"); + assertThat(binding.acknowledgementPolicy().requiredReplicaAofCount()).isEqualTo(1); + }); verify(client, times(1)).shutdown(); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/InternalGrpcClientAuthConfigTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/InternalGrpcClientAuthConfigTest.java index 8a8b758a86..8fc62257be 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/InternalGrpcClientAuthConfigTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/InternalGrpcClientAuthConfigTest.java @@ -54,25 +54,24 @@ class InternalGrpcClientAuthConfigTest { @Test void serviceOverridesSharedStubCustomizerWithInternalOnlyBehavior() { - contextRunner.run( - ctx -> { - BlockingGrpcStubCustomizer customizer = ctx.getBean(BlockingGrpcStubCustomizer.class); - JwtUtil jwtUtil = ctx.getBean(JwtUtil.class); - CapturingChannel channel = new CapturingChannel(); - CapturingStub stub = new CapturingStub(channel, CallOptions.DEFAULT); - - CapturingStub customized = customizer.customize(stub); - - assertThat(customized).isNotSameAs(stub); - customized.invoke(); - String authorization = channel.lastAuthorization(); - assertThat(authorization).startsWith("Bearer "); - String token = authorization.substring(7); - assertThat(jwtUtil.parseToken(token).getPayload().getSubject()) - .isEqualTo("service:game-session-service"); - assertThat(jwtUtil.parseToken(token).getPayload().get("internalService", Boolean.class)) - .isTrue(); - }); + contextRunner.run(ctx -> { + BlockingGrpcStubCustomizer customizer = ctx.getBean(BlockingGrpcStubCustomizer.class); + JwtUtil jwtUtil = ctx.getBean(JwtUtil.class); + CapturingChannel channel = new CapturingChannel(); + CapturingStub stub = new CapturingStub(channel, CallOptions.DEFAULT); + + CapturingStub customized = customizer.customize(stub); + + assertThat(customized).isNotSameAs(stub); + customized.invoke(); + String authorization = channel.lastAuthorization(); + assertThat(authorization).startsWith("Bearer "); + String token = authorization.substring(7); + assertThat(jwtUtil.parseToken(token).getPayload().getSubject()) + .isEqualTo("service:game-session-service"); + assertThat(jwtUtil.parseToken(token).getPayload().get("internalService", Boolean.class)) + .isTrue(); + }); } private static final class CapturingChannel extends Channel { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwnerTest.java index 7e4d15a63e..bf5a7806e1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwnerTest.java @@ -169,10 +169,9 @@ void rejectsChangedPrivateAllocationAndChangedLifecycleStatus() { when(changedIdentity.launchOwner.readVerifiedFixtureLaunch(any())) .thenReturn(differentIdentity); - assertThatThrownBy( - () -> - changedIdentity.coordinator.prepareVerifiedFixtureLaunch( - changedIdentity.capability, changedIdentity.sourceReceipt)) + assertThatThrownBy(() -> + changedIdentity.coordinator.prepareVerifiedFixtureLaunch( + changedIdentity.capability, changedIdentity.sourceReceipt)) .isInstanceOf(IllegalStateException.class); Fixture changedStatus = fixture(true); @@ -185,10 +184,9 @@ void rejectsChangedPrivateAllocationAndChangedLifecycleStatus() { changedStatus.allocation.rowVersion()); when(changedStatus.launchOwner.readVerifiedFixtureLaunch(any())).thenReturn(running); - assertThatThrownBy( - () -> - changedStatus.coordinator.prepareVerifiedFixtureLaunch( - changedStatus.capability, changedStatus.sourceReceipt)) + assertThatThrownBy(() -> + changedStatus.coordinator.prepareVerifiedFixtureLaunch( + changedStatus.capability, changedStatus.sourceReceipt)) .isInstanceOf(IllegalStateException.class); } @@ -220,10 +218,8 @@ void rejectsReceiptWithChangedFixturePolicySealBeforeOwnerWrite() { fixture.sourceReceipt.creationEvidence(), changedSeal); - assertThatThrownBy( - () -> - fixture.coordinator.prepareVerifiedFixtureLaunch( - fixture.capability, changedReceipt)) + assertThatThrownBy(() -> + fixture.coordinator.prepareVerifiedFixtureLaunch(fixture.capability, changedReceipt)) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(fixture.launchOwner); } @@ -346,27 +342,24 @@ private static void stubFixtureLoaders( Fixture fixture, RunOwnedInitialAdmissionFixtureCapability.SourceReceipt... receipts) { loader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) + .when(() -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) .thenReturn(fixture.capability); AtomicInteger index = new AtomicInteger(); loader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(Path.class), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.capability), - same(fixture.grpcProperties))) + .when(() -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) .thenAnswer(invocation -> receipts[Math.min(index.getAndIncrement(), receipts.length - 1)]); loader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.toWireCapability( - any(RunOwnedInitialAdmissionFixtureCapability.class))) + .when(() -> + RunOwnedInitialAdmissionFixtureCapability.toWireCapability( + any(RunOwnedInitialAdmissionFixtureCapability.class))) .thenCallRealMethod(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java index 9226864629..505104304d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java @@ -96,13 +96,12 @@ void rejectsUnknownDuplicateMismatchedAndNoncanonicalCapabilityFields() { assertInvalid( validJson().replace("\"stateScope\": \"SHARED\"", "\"stateScope\": \"ISOLATED\"")); assertInvalid(validJson().replace(LEAF_SHA, "c".repeat(64))); - assertThatThrownBy( - () -> - RunOwnedInitialAdmissionFixtureCapability.parseAndValidate( - validJson().getBytes(java.nio.charset.StandardCharsets.UTF_8), - RUN_ID, - "other-project", - pins())) + assertThatThrownBy(() -> + RunOwnedInitialAdmissionFixtureCapability.parseAndValidate( + validJson().getBytes(java.nio.charset.StandardCharsets.UTF_8), + RUN_ID, + "other-project", + pins())) .isInstanceOf(RunOwnedInitialAdmissionFixtureCapability.InvalidCapabilityException.class); } @@ -578,23 +577,23 @@ private static String validSourceReceiptJson() { seal.requestDigest(), seal.evidenceDigest()); return """ - {%n\ - "schema": "%s",%n\ - "runId": "%s",%n\ - "composeProjectName": "%s",%n\ - "fixtureOperationId": "%s",%n\ - "ownerService": "%s",%n\ - "gameSessionUriSan": "%s",%n\ - "gameSessionLeafSha256": "%s",%n\ - "caCertificateSha256": "%s",%n\ - "worldManagementUriSan": "%s",%n\ - "worldManagementLeafSha256": "%s",%n\ - "sourceEvidence": %s,%n\ - "launchReadEvidence": %s,%n\ - "creationEvidence": %s,%n\ - "fixturePolicySeal": %s%n\ - }%n\ - """ + {%n\ + "schema": "%s",%n\ + "runId": "%s",%n\ + "composeProjectName": "%s",%n\ + "fixtureOperationId": "%s",%n\ + "ownerService": "%s",%n\ + "gameSessionUriSan": "%s",%n\ + "gameSessionLeafSha256": "%s",%n\ + "caCertificateSha256": "%s",%n\ + "worldManagementUriSan": "%s",%n\ + "worldManagementLeafSha256": "%s",%n\ + "sourceEvidence": %s,%n\ + "launchReadEvidence": %s,%n\ + "creationEvidence": %s,%n\ + "fixturePolicySeal": %s%n\ + }%n\ + """ .formatted( RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_SCHEMA, RUN_ID, @@ -715,8 +714,8 @@ private static String launchReadEvidenceJson( net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot versionState, LaunchDescriptor descriptor) { return """ - {"schema":"%s","gameTemplateId":17,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"}%n\ - """ + {"schema":"%s","gameTemplateId":17,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"}%n\ + """ .formatted( RunOwnedInitialAdmissionLaunchEvidence.SCHEMA, encode(bundle.toByteArray()), @@ -826,31 +825,31 @@ private static String encode(byte[] bytes) { private static String validJson() { return """ - {%n\ - "schema": "%s",%n\ - "runId": "%s",%n\ - "composeProjectName": "%s",%n\ - "operationId": "%s",%n\ - "tenantId": 7,%n\ - "gameTemplateId": 17,%n\ - "ownerAccountId": 27,%n\ - "worldSlug": "demo",%n\ - "worldDisplayName": "Demo World",%n\ - "realmSlug": "production",%n\ - "realmDisplayName": "Live Realm",%n\ - "visible": true,%n\ - "publicProductionRealm": true,%n\ - "requiresCharacterSelection": false,%n\ - "stateScope": "SHARED",%n\ - "characterCreationPolicy": "ALLOW_NEW",%n\ - "gameSessionLeafSha256": "%s",%n\ - "gameSessionUriSan": "%s",%n\ - "caCertificateSha256": "%s",%n\ - "worldManagementUriSan": "%s",%n\ - "worldManagementLeafSha256": "%s",%n\ - "claimDigest": "%s"%n\ - }%n\ - """ + {%n\ + "schema": "%s",%n\ + "runId": "%s",%n\ + "composeProjectName": "%s",%n\ + "operationId": "%s",%n\ + "tenantId": 7,%n\ + "gameTemplateId": 17,%n\ + "ownerAccountId": 27,%n\ + "worldSlug": "demo",%n\ + "worldDisplayName": "Demo World",%n\ + "realmSlug": "production",%n\ + "realmDisplayName": "Live Realm",%n\ + "visible": true,%n\ + "publicProductionRealm": true,%n\ + "requiresCharacterSelection": false,%n\ + "stateScope": "SHARED",%n\ + "characterCreationPolicy": "ALLOW_NEW",%n\ + "gameSessionLeafSha256": "%s",%n\ + "gameSessionUriSan": "%s",%n\ + "caCertificateSha256": "%s",%n\ + "worldManagementUriSan": "%s",%n\ + "worldManagementLeafSha256": "%s",%n\ + "claimDigest": "%s"%n\ + }%n\ + """ .formatted( RunOwnedInitialAdmissionFixtureCapability.CAPABILITY_SCHEMA, RUN_ID, @@ -879,13 +878,12 @@ private static X509Certificate certificate(String san, byte[] der, int basicCons } private static void assertInvalid(String json) { - assertThatThrownBy( - () -> - RunOwnedInitialAdmissionFixtureCapability.parseAndValidate( - json.getBytes(java.nio.charset.StandardCharsets.UTF_8), - RUN_ID, - PROJECT_NAME, - pins())) + assertThatThrownBy(() -> + RunOwnedInitialAdmissionFixtureCapability.parseAndValidate( + json.getBytes(java.nio.charset.StandardCharsets.UTF_8), + RUN_ID, + PROJECT_NAME, + pins())) .isInstanceOf(RunOwnedInitialAdmissionFixtureCapability.InvalidCapabilityException.class); } @@ -895,19 +893,17 @@ private static void assertInvalidSourceReceipt(String json) { private static void assertInvalidSourceReceipt(Supplier receiptJson) { byte[] bytes = receiptJson.get().getBytes(java.nio.charset.StandardCharsets.UTF_8); - assertThatThrownBy( - () -> - RunOwnedInitialAdmissionFixtureCapability.parseSourceReceipt( - bytes, RUN_ID, PROJECT_NAME, capability(), pins())) + assertThatThrownBy(() -> + RunOwnedInitialAdmissionFixtureCapability.parseSourceReceipt( + bytes, RUN_ID, PROJECT_NAME, capability(), pins())) .isInstanceOf( RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); } private static void assertInvalidSourceReceiptBytes(byte[] bytes) { - assertThatThrownBy( - () -> - RunOwnedInitialAdmissionFixtureCapability.parseSourceReceipt( - bytes, RUN_ID, PROJECT_NAME, capability(), pins())) + assertThatThrownBy(() -> + RunOwnedInitialAdmissionFixtureCapability.parseSourceReceipt( + bytes, RUN_ID, PROJECT_NAME, capability(), pins())) .isInstanceOf( RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); } @@ -926,11 +922,10 @@ private static void install( Path displaced, SeekableByteChannel openedChannel) { mockedFiles - .when( - () -> - Files.newByteChannel( - org.mockito.ArgumentMatchers.eq(receipt), - org.mockito.ArgumentMatchers.any(java.nio.file.OpenOption[].class))) + .when(() -> + Files.newByteChannel( + org.mockito.ArgumentMatchers.eq(receipt), + org.mockito.ArgumentMatchers.any(java.nio.file.OpenOption[].class))) .thenAnswer( new Answer<>() { @Override diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java index c7dcb6a6c0..c689ce9dd9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java @@ -158,16 +158,14 @@ void unresolvedOwnerProofDoesNotReleaseHoldOrCompensate() { void rejectsMismatchedWorldHoldBeforeAttachingOrCommitting() { Fixture fixture = fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - doAnswer( - invocation -> - AcquireInitialAdmissionBindHoldResponse.newBuilder() - .setHold( - hold( - InitialAdmissionBindHoldStatus - .INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING, - UUID.fromString("49de9f26-f314-40e1-96a7-5655c5e5b16e"), - fixture.request.get().requestDigest())) - .build()) + doAnswer(invocation -> + AcquireInitialAdmissionBindHoldResponse.newBuilder() + .setHold( + hold( + InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING, + UUID.fromString("49de9f26-f314-40e1-96a7-5655c5e5b16e"), + fixture.request.get().requestDigest())) + .build()) .when(fixture.worldClient) .acquireInitialAdmissionBindHold( anyLong(), @@ -263,11 +261,10 @@ void terminalWorldAbortUsesExactReadbackWithoutTryingToCommit() { Fixture fixture = fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_ABORTED); when(fixture.ownerService.read(any())) - .thenAnswer( - invocation -> { - InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); - return proof(binding, Outcome.ABORTED, ATTEMPT_ID, null, 0L, null, true); - }); + .thenAnswer(invocation -> { + InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); + return proof(binding, Outcome.ABORTED, ATTEMPT_ID, null, 0L, null, true); + }); assertThat(fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) .isEqualTo(RunOwnedInitialAdmissionFixtureCoordinator.BootstrapResult.ABORTED); @@ -308,20 +305,18 @@ void missingSourceReceiptRejectsBeforeLaunchOrOwnerMutation() { try (MockedStatic capabilityLoader = mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) + .when(() -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) .thenReturn(fixture.capability); capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(Path.class), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.capability), - same(fixture.grpcProperties))) + .when(() -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) .thenThrow(RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); fixture.coordinator.retryRunOwnedFixtureBootstrap(); @@ -343,20 +338,18 @@ void changedSourceReceiptAcrossRetriesIsRejectedBeforeSecondLaunch() { try (MockedStatic capabilityLoader = mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) + .when(() -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) .thenReturn(fixture.capability); capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(Path.class), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.capability), - same(fixture.grpcProperties))) + .when(() -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) .thenReturn(fixture.sourceReceipt, changedReceipt); fixture.coordinator.retryRunOwnedFixtureBootstrap(); @@ -383,20 +376,18 @@ void changedOwnerReadEvidenceAcrossRetriesIsRejectedBeforeSecondLaunch() { try (MockedStatic capabilityLoader = mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) + .when(() -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) .thenReturn(fixture.capability); capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(Path.class), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.capability), - same(fixture.grpcProperties))) + .when(() -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) .thenReturn(fixture.sourceReceipt, changedReceipt); fixture.coordinator.retryRunOwnedFixtureBootstrap(); @@ -424,20 +415,18 @@ void retryLogUsesAllowlistedDiagnosticsAndDoesNotExposeHostileDependencyMessage( try (MockedStatic capabilityLoader = mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) + .when(() -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) .thenReturn(fixture.capability); capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(Path.class), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.capability), - same(fixture.grpcProperties))) + .when(() -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) .thenReturn(fixture.sourceReceipt); fixture.coordinator.retryRunOwnedFixtureBootstrap(); @@ -463,20 +452,18 @@ void exhaustedRetryLogUsesAllowlistedDiagnosticsAndDoesNotExposeHostileDependenc try (MockedStatic capabilityLoader = mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) + .when(() -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) .thenReturn(fixture.capability); capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(Path.class), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.capability), - same(fixture.grpcProperties))) + .when(() -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) .thenReturn(fixture.sourceReceipt); for (int attempt = 0; attempt < 12; attempt++) { @@ -528,20 +515,18 @@ void exhaustedRetryBudgetStopsMutationAndFreshCoordinatorReplaysSameClaim() { try (MockedStatic capabilityLoader = mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) + .when(() -> + RunOwnedInitialAdmissionFixtureCapability.load( + any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) .thenReturn(fixture.capability); capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(Path.class), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.capability), - same(fixture.grpcProperties))) + .when(() -> + RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( + any(Path.class), + eq(RUN_ID), + eq(PROJECT_NAME), + same(fixture.capability), + same(fixture.grpcProperties))) .thenReturn(fixture.sourceReceipt); // Orchestration unit proof only; capability TLS and durable cross-service behavior have @@ -604,13 +589,12 @@ void exhaustedRetryBudgetStopsMutationAndFreshCoordinatorReplaysSameClaim() { .startRunOwnedInitialLaunch( launchRequests.capture(), any(RunOwnedInitialAdmissionLaunchEvidence.class)); assertThat(launchRequests.getAllValues()) - .allSatisfy( - request -> { - assertThat(request.tenantId()).isEqualTo(fixture.capability.tenantId()); - assertThat(request.gameTemplateId()).isEqualTo(fixture.capability.gameTemplateId()); - assertThat(request.ownerAccountId()).isEqualTo(fixture.capability.ownerAccountId()); - assertThat(request.controlPlaneRequestId()).isEqualTo(OPERATION_ID); - }); + .allSatisfy(request -> { + assertThat(request.tenantId()).isEqualTo(fixture.capability.tenantId()); + assertThat(request.gameTemplateId()).isEqualTo(fixture.capability.gameTemplateId()); + assertThat(request.ownerAccountId()).isEqualTo(fixture.capability.ownerAccountId()); + assertThat(request.controlPlaneRequestId()).isEqualTo(OPERATION_ID); + }); ArgumentCaptor ownerRequests = ArgumentCaptor.forClass(InitialAdmissionBindRequest.class); verify(fixture.worldClient, times(13)) @@ -727,12 +711,11 @@ private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { AtomicReference request = new AtomicReference<>(); when(ownerService.beginIntent(any())) - .thenAnswer( - invocation -> { - InitialAdmissionBindRequest received = invocation.getArgument(0); - request.set(received); - return attempt(received, catalog, null, null, Status.PENDING); - }); + .thenAnswer(invocation -> { + InitialAdmissionBindRequest received = invocation.getArgument(0); + request.set(received); + return attempt(received, catalog, null, null, Status.PENDING); + }); when(worldClient.acquireInitialAdmissionBindHold( anyLong(), anyLong(), @@ -744,33 +727,30 @@ private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { any(UUID.class), any(PlayableStateScope.class), anyLong())) - .thenAnswer( - invocation -> { - InitialAdmissionBindHoldStatus selectedStatus = holdStatus; - UUID namespaceId = invocation.getArgument(7); - String requestDigest = invocation.getArgument(5); - return AcquireInitialAdmissionBindHoldResponse.newBuilder() - .setHold(hold(selectedStatus, namespaceId, requestDigest)) - .build(); - }); + .thenAnswer(invocation -> { + InitialAdmissionBindHoldStatus selectedStatus = holdStatus; + UUID namespaceId = invocation.getArgument(7); + String requestDigest = invocation.getArgument(5); + return AcquireInitialAdmissionBindHoldResponse.newBuilder() + .setHold(hold(selectedStatus, namespaceId, requestDigest)) + .build(); + }); when(ownerService.attachHold(any())) - .thenAnswer( - invocation -> { - InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); - return attempt( - request.get(), - catalog, - UUID.fromString(binding.holdId()), - UUID.fromString(binding.holdFence()), - Status.PENDING); - }); + .thenAnswer(invocation -> { + InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); + return attempt( + request.get(), + catalog, + UUID.fromString(binding.holdId()), + UUID.fromString(binding.holdFence()), + Status.PENDING); + }); when(ownerService.commit(any())) - .thenAnswer( - invocation -> { - InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); - return proof( - binding, Outcome.COMMITTED, ATTEMPT_ID, "31", 1L, binding.requestDigest(), false); - }); + .thenAnswer(invocation -> { + InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); + return proof( + binding, Outcome.COMMITTED, ATTEMPT_ID, "31", 1L, binding.requestDigest(), false); + }); RunOwnedInitialAdmissionFixtureCoordinator coordinator = new RunOwnedInitialAdmissionFixtureCoordinator( true, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociationTest.java index 5308699e5c..50ce15b86a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociationTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociationTest.java @@ -63,24 +63,23 @@ void rejectsNonSharedAndNonProductionLaunchAssociations() { @Test void rejectsSelectorsAndCurrentRowVersionsThatDifferFromTheOwnerEvidence() { - assertThatThrownBy( - () -> - new CanonicalGameInstanceLaunchAssociation( - NAMESPACE, - 701L, - ASSOCIATION_ID, - TENANT_ID, - INSTANCE_ID, - "mars", - STATE_NAMESPACE_ID, - RealmEntryPolicy.StateScope.SHARED, - true, - "launch-request-1", - "descriptor-902", - 3L, - evidence(), - CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.STARTING, - 3L)) + assertThatThrownBy(() -> + new CanonicalGameInstanceLaunchAssociation( + NAMESPACE, + 701L, + ASSOCIATION_ID, + TENANT_ID, + INSTANCE_ID, + "mars", + STATE_NAMESPACE_ID, + RealmEntryPolicy.StateScope.SHARED, + true, + "launch-request-1", + "descriptor-902", + 3L, + evidence(), + CanonicalGameInstanceLaunchAssociation.CurrentGameInstanceStatus.STARTING, + 3L)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("does not match"); assertThatThrownBy( @@ -149,19 +148,17 @@ private static CompleteLaunchBindingEvidence evidence() { null); List participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - owner, - "902", - false, - null, - "publish-commit-902", - "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), - "GAME_LOGIC".equals(owner), - "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null)) + .map(owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + "902", + false, + null, + "publish-commit-902", + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema(owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null)) .toList(); AuthoredWorldReleaseAttestationEvidence attestation = AuthoredWorldReleaseAttestationEvidence.create( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java index 4453778fb0..b38fdb4fbe 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java @@ -127,21 +127,18 @@ void liveBorrowPreservesExactIdentityRefusesReentrancyAndReleasesAfterCallbackFa throws Exception { var result = decode(response(claims())); assertThat( - result.withLivePrivateResult( - borrowed -> { - assertThat(borrowed).isSameAs(result); - assertThatThrownBy(borrowed::close).isInstanceOf(IllegalStateException.class); - assertThatThrownBy(() -> borrowed.withLivePrivateResult(nested -> true)) - .isInstanceOf(IllegalStateException.class); - return borrowed.compactJwtBytes().length; - })) + result.withLivePrivateResult(borrowed -> { + assertThat(borrowed).isSameAs(result); + assertThatThrownBy(borrowed::close).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> borrowed.withLivePrivateResult(nested -> true)) + .isInstanceOf(IllegalStateException.class); + return borrowed.compactJwtBytes().length; + })) .isPositive(); - assertThatThrownBy( - () -> - result.withLivePrivateResult( - borrowed -> { - throw new IllegalStateException("controlled callback failure"); - })) + assertThatThrownBy(() -> + result.withLivePrivateResult(borrowed -> { + throw new IllegalStateException("controlled callback failure"); + })) .hasMessage("controlled callback failure"); result.close(); assertThatThrownBy(() -> result.withLivePrivateResult(borrowed -> true)) @@ -166,11 +163,10 @@ void directCloseDrainsAllBorrowersWithoutHoldingResultMonitorAndThenErasesBytes( try { assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); var closing = - executor.submit( - () -> { - closingThread.set(Thread.currentThread()); - result.close(); - }); + executor.submit(() -> { + closingThread.set(Thread.currentThread()); + result.close(); + }); long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); while (closingThread.get() == null || closingThread.get().getState() != Thread.State.WAITING) { @@ -203,21 +199,20 @@ private static boolean borrowUntilReleased( CountDownLatch entered, CountDownLatch release, byte[] expected) { - return result.withLivePrivateResult( - borrowed -> { - assertThat(borrowed).isSameAs(result); - entered.countDown(); - try { - if (!release.await(5, TimeUnit.SECONDS)) - throw new IllegalStateException("Borrow timed out"); - } catch (InterruptedException failure) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("Borrow interrupted", failure); - } - // Reads must still progress while close waits for this callback's pin. - assertThat(borrowed.compactJwtBytes()).containsExactly(expected); - return true; - }); + return result.withLivePrivateResult(borrowed -> { + assertThat(borrowed).isSameAs(result); + entered.countDown(); + try { + if (!release.await(5, TimeUnit.SECONDS)) + throw new IllegalStateException("Borrow timed out"); + } catch (InterruptedException failure) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Borrow interrupted", failure); + } + // Reads must still progress while close waits for this callback's pin. + assertThat(borrowed.compactJwtBytes()).containsExactly(expected); + return true; + }); } @ParameterizedTest @@ -454,10 +449,9 @@ private static CanonicalGameplayLoginResult decode(AuthenticateResponse wire) th private static void assertInvalid(AuthenticateResponse wire) throws Exception { var verifier = verifier(); - assertThatThrownBy( - () -> - CanonicalGameplayLoginResult.fromAuthenticatedResponse( - wire, request(), verifier, CLOCK)) + assertThatThrownBy(() -> + CanonicalGameplayLoginResult.fromAuthenticatedResponse( + wire, request(), verifier, CLOCK)) .isInstanceOf(CanonicalGameplayLoginResult.InvalidResultException.class) .hasMessage("Canonical LOGIN request or result is invalid"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequestTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequestTest.java index 8ee230ea6a..a4f335cc6d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequestTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionRequestTest.java @@ -52,49 +52,47 @@ void requestIdentityLimitCountsUnicodeCodePoints() { @Test void bothOriginsRequireTheirExactPriorPointerShape() { - assertThatThrownBy( - () -> - new CanonicalInitialAdmissionRequest( - "prod", - TENANT, - "green-hollow", - REALM, - PLAYABLE_NAMESPACE, - "SHARED", - GAME_INSTANCE, - CANONICAL_VERSION, - 7L, - 12L, - OriginKind.NO_PRIOR_POINTER, - 13L, - "gs-initial-admission-17", - noPriorRequest().requestDigest(), - HOLD_ID, - HOLD_FENCE, - "sha256:" + "c".repeat(64))) + assertThatThrownBy(() -> + new CanonicalInitialAdmissionRequest( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + GAME_INSTANCE, + CANONICAL_VERSION, + 7L, + 12L, + OriginKind.NO_PRIOR_POINTER, + 13L, + "gs-initial-admission-17", + noPriorRequest().requestDigest(), + HOLD_ID, + HOLD_FENCE, + "sha256:" + "c".repeat(64))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("must not carry"); - assertThatThrownBy( - () -> - new CanonicalInitialAdmissionRequest( - "prod", - TENANT, - "green-hollow", - REALM, - PLAYABLE_NAMESPACE, - "SHARED", - GAME_INSTANCE, - CANONICAL_VERSION, - 7L, - 12L, - OriginKind.EXPECT_CLOSED, - null, - "gs-initial-admission-17", - noPriorRequest().requestDigest(), - HOLD_ID, - HOLD_FENCE, - "sha256:" + "c".repeat(64))) + assertThatThrownBy(() -> + new CanonicalInitialAdmissionRequest( + "prod", + TENANT, + "green-hollow", + REALM, + PLAYABLE_NAMESPACE, + "SHARED", + GAME_INSTANCE, + CANONICAL_VERSION, + 7L, + 12L, + OriginKind.EXPECT_CLOSED, + null, + "gs-initial-admission-17", + noPriorRequest().requestDigest(), + HOLD_ID, + HOLD_FENCE, + "sha256:" + "c".repeat(64))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("requires a positive"); } @@ -124,37 +122,35 @@ void worldProofMustMatchCanonicalVersionOriginCatalogAndHoldBinding() { request.holdBindingDigest()); proof.requireMatches(request); - assertThatThrownBy( - () -> - new CanonicalInitialAdmissionWorldProof( - proof.initialAdmissionRequestId(), - proof.requestDigest(), - proof.targetNamespace(), - proof.canonicalTenantId(), - proof.worldSlug(), - proof.realmId(), - proof.playableStateNamespaceId(), - proof.playableStateScope(), - proof.canonicalGameInstanceId(), - uuid("66666666-6666-4666-8666-666666666666"), - proof.lifecycleState(), - proof.activeLifecycleEpoch(), - proof.originKind(), - proof.expectedCatalogRevision(), - proof.expectedPriorPointerVersion(), - proof.holdId(), - proof.holdFence(), - proof.holdBindingDigest()) - .requireMatches(request)) + assertThatThrownBy(() -> + new CanonicalInitialAdmissionWorldProof( + proof.initialAdmissionRequestId(), + proof.requestDigest(), + proof.targetNamespace(), + proof.canonicalTenantId(), + proof.worldSlug(), + proof.realmId(), + proof.playableStateNamespaceId(), + proof.playableStateScope(), + proof.canonicalGameInstanceId(), + uuid("66666666-6666-4666-8666-666666666666"), + proof.lifecycleState(), + proof.activeLifecycleEpoch(), + proof.originKind(), + proof.expectedCatalogRevision(), + proof.expectedPriorPointerVersion(), + proof.holdId(), + proof.holdFence(), + proof.holdBindingDigest()) + .requireMatches(request)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("does not match"); } @Test void unauthenticatedDefaultWorldVerifierNeverTreatsCallerTupleAsOwnerProof() { - assertThatThrownBy( - () -> - new DefaultDeniedCanonicalInitialAdmissionWorldVerifier().verify(noPriorRequest())) + assertThatThrownBy(() -> + new DefaultDeniedCanonicalInitialAdmissionWorldVerifier().verify(noPriorRequest())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("denied until authenticated World"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginDisposalResultTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginDisposalResultTest.java index aea49aece4..f4a3d3cf32 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginDisposalResultTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginDisposalResultTest.java @@ -77,9 +77,8 @@ void rejectsMismatchedMalformedAndExtendedResponses() { response().toBuilder().setDispositionValue(4).build(), response().toBuilder().setProofKindValue(3).build(), response().toBuilder().setUnknownFields(UNKNOWN).build())) { - assertThatThrownBy( - () -> - InitialGameplayLoginDisposalResult.fromAuthenticatedResponse(response, request())) + assertThatThrownBy(() -> + InitialGameplayLoginDisposalResult.fromAuthenticatedResponse(response, request())) .isInstanceOf(InitialGameplayLoginDisposalResult.InvalidResultException.class); } assertThatThrownBy( @@ -97,10 +96,8 @@ void rejectsCrossedOwnerNonissuanceAndPhysicalDenialProofs() { .setDispositionValue(disposition) .setProofKindValue(proof) .build(); - assertThatThrownBy( - () -> - InitialGameplayLoginDisposalResult.fromAuthenticatedResponse( - crossed, request())) + assertThatThrownBy(() -> + InitialGameplayLoginDisposalResult.fromAuthenticatedResponse(crossed, request())) .isInstanceOf(InitialGameplayLoginDisposalResult.InvalidResultException.class); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginJournalSnapshotTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginJournalSnapshotTest.java index 965b6bd2cb..052ede6160 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginJournalSnapshotTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/InitialGameplayLoginJournalSnapshotTest.java @@ -63,34 +63,30 @@ void absentFrozenWitnessCanCoexistWithSeparatelyRetainedLateWitness() { @Test void rejectsUnabandonedFreezeAndChangedOriginalCoordinates() { var request = InitialGameplayLoginJournalSnapshot.request(ORIGINAL, null); - assertThatThrownBy( - () -> - new InitialGameplayLoginJournalSnapshot( - ORIGINAL, false, Optional.empty(), Optional.of(request), Optional.empty())) + assertThatThrownBy(() -> + new InitialGameplayLoginJournalSnapshot( + ORIGINAL, false, Optional.empty(), Optional.of(request), Optional.empty())) .isInstanceOf(IllegalArgumentException.class); var changed = request.toBuilder().setCallerContextId(uuid(9).toString()).build(); - assertThatThrownBy( - () -> - new InitialGameplayLoginJournalSnapshot( - ORIGINAL, true, Optional.empty(), Optional.of(changed), Optional.empty())) + assertThatThrownBy(() -> + new InitialGameplayLoginJournalSnapshot( + ORIGINAL, true, Optional.empty(), Optional.of(changed), Optional.empty())) .isInstanceOf(IllegalArgumentException.class); } @Test void rejectsIncompleteWitnessAndMismatchedClosedDisposalPair() { - assertThatThrownBy( - () -> - InitialGameplayLoginJournalSnapshot.request( - ORIGINAL, witness().toBuilder().clearTokenSha256().build())) + assertThatThrownBy(() -> + InitialGameplayLoginJournalSnapshot.request( + ORIGINAL, witness().toBuilder().clearTokenSha256().build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new InitialGameplayLoginDisposalResult( - uuid(1), - uuid(2), - uuid(3), - InitialGameplayLoginDisposalResult.Disposition.PENDING, - InitialGameplayLoginDisposalResult.ProofKind.PHYSICAL_TOKEN_DENIAL)) + assertThatThrownBy(() -> + new InitialGameplayLoginDisposalResult( + uuid(1), + uuid(2), + uuid(3), + InitialGameplayLoginDisposalResult.Disposition.PENDING, + InitialGameplayLoginDisposalResult.ProofKind.PHYSICAL_TOKEN_DENIAL)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java index 0178c156d0..08d67895c4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java @@ -34,20 +34,19 @@ void sessionContextProbeReturnsUpWhenContextRoundTrips() { @SuppressWarnings("unchecked") RedisTemplate redisTemplate = mock(RedisTemplate.class); when(sessionContextService.findByTenantAndSessionId(anyLong(), anyLong())) - .thenAnswer( - invocation -> { - long sessionId = invocation.getArgument(1, Long.class); - long probeSequence = sessionId - PROBE_SESSION_ID_BASE; - return Optional.of( - new SessionContext( - sessionId, - 0L, - PROBE_ACCOUNT_ID, - PROBE_CHARACTER_ID, - 0L, - "readiness-room-" + probeSequence, - null)); - }); + .thenAnswer(invocation -> { + long sessionId = invocation.getArgument(1, Long.class); + long probeSequence = sessionId - PROBE_SESSION_ID_BASE; + return Optional.of( + new SessionContext( + sessionId, + 0L, + PROBE_ACCOUNT_ID, + PROBE_CHARACTER_ID, + 0L, + "readiness-room-" + probeSequence, + null)); + }); GameplayLocalPathReadinessProbe probe = new GameplayLocalPathReadinessProbe(sessionContextService, redisTemplate); @@ -83,10 +82,9 @@ void sessionContextProbeUsesCanonicalAccountIdentityAcceptedByRedisLookup() { .save(any(SessionContext.class)); RedisSessionContextService strictLookup = new RedisSessionContextService(redisTemplate, 1000L); when(sessionContextService.findByTenantAndSessionId(anyLong(), anyLong())) - .thenAnswer( - invocation -> - strictLookup.findByTenantAndSessionId( - invocation.getArgument(0, Long.class), invocation.getArgument(1, Long.class))); + .thenAnswer(invocation -> + strictLookup.findByTenantAndSessionId( + invocation.getArgument(0, Long.class), invocation.getArgument(1, Long.class))); GameplayLocalPathReadinessProbe probe = new GameplayLocalPathReadinessProbe(sessionContextService, redisTemplate); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/AccountInitialAdmissionProtectionBindingRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/AccountInitialAdmissionProtectionBindingRepositoryTest.java index f452933c2a..e589d31f6b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/AccountInitialAdmissionProtectionBindingRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/AccountInitialAdmissionProtectionBindingRepositoryTest.java @@ -97,14 +97,13 @@ void everyIndependentOwnerAssociationAndTerminalSubstitutionRefuses() { changes.put("intent_original_request", "another-original"); changes.put("original_request", "another-original"); changes.put("commit_proof_digest", "sha256:" + "f".repeat(64)); - changes.forEach( - (field, replacement) -> { - var values = fields(p, "COMMITTED"); - values.put(field, replacement); - assertThatThrownBy(() -> repository(values).read(NAMESPACE, OPERATION)) - .as(field) - .isInstanceOfAny(IllegalStateException.class, IllegalArgumentException.class); - }); + changes.forEach((field, replacement) -> { + var values = fields(p, "COMMITTED"); + values.put(field, replacement); + assertThatThrownBy(() -> repository(values).read(NAMESPACE, OPERATION)) + .as(field) + .isInstanceOfAny(IllegalStateException.class, IllegalArgumentException.class); + }); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java index 98b317b2c9..4be2714045 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepositoryTest.java @@ -130,17 +130,14 @@ void historicalReadRejectsWrongNamespaceAndAmbientTransactionsBeforeSql() { DSLContext dsl = mock(DSLContext.class); var repository = new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); - assertThatThrownBy( - () -> - repository.readHistoricalOriginalStartSessionOwnerEvidence( - historicalRequest("other"))) + assertThatThrownBy(() -> + repository.readHistoricalOriginalStartSessionOwnerEvidence(historicalRequest("other"))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("another Game Session namespace"); TransactionSynchronizationManager.setActualTransactionActive(true); - assertThatThrownBy( - () -> - repository.readHistoricalOriginalStartSessionOwnerEvidence( - historicalRequest(NAMESPACE))) + assertThatThrownBy(() -> + repository.readHistoricalOriginalStartSessionOwnerEvidence( + historicalRequest(NAMESPACE))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("committed owner read"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java index 604808d8e2..1fcdad6581 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java @@ -197,28 +197,25 @@ void possibleDispatchIsPersistedBeforeEvalAndMissingAfterwardNeverGetsAFreshCrea when(connection.async()).thenReturn(commands); doReturn(future("gamesession_coord_app")).when(commands).aclWhoami(); when(commands.scriptLoad(any(byte[].class))) - .thenAnswer( - invocation -> { - verify(repository, org.mockito.Mockito.never()).recordDispatchPossible(any(), any()); - return future( - java.util.HexFormat.of() - .formatHex( - java.security.MessageDigest.getInstance("SHA-1") - .digest(invocation.getArgument(0, byte[].class)))); - }); + .thenAnswer(invocation -> { + verify(repository, org.mockito.Mockito.never()).recordDispatchPossible(any(), any()); + return future( + java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-1") + .digest(invocation.getArgument(0, byte[].class)))); + }); when(commands.evalsha(any(), any(), any(byte[][].class), any(byte[][].class))) - .thenAnswer( - ignored -> { - verify(repository).recordDispatchPossible(requestId, before); - throw new IllegalStateException("controlled unknown EVAL outcome"); - }); + .thenAnswer(ignored -> { + verify(repository).recordDispatchPossible(requestId, before); + throw new IllegalStateException("controlled unknown EVAL outcome"); + }); AtomicInteger connectionAttempts = new AtomicInteger(); when(redis.connect(any(ByteArrayCodec.class))) - .thenAnswer( - ignored -> { - if (connectionAttempts.getAndIncrement() == 0) return connection; - throw new IllegalStateException("controlled lost readback connection"); - }); + .thenAnswer(ignored -> { + if (connectionAttempts.getAndIncrement() == 0) return connection; + throw new IllegalStateException("controlled lost readback connection"); + }); RedisScriptCatalog catalog = RedisScriptCatalog.fromContributions( List.of(new CanonicalGameplayAccountInitialBarrierRedisScriptContribution())); @@ -296,11 +293,10 @@ void exactSameOriginalOpenReplayIsReadOnlyAndReturnsCurrentTypedProof() throws E Map raw = new HashMap<>(); expected .fields() - .forEach( - (field, value) -> - raw.put( - field.getBytes(StandardCharsets.US_ASCII), - value.getBytes(StandardCharsets.US_ASCII))); + .forEach((field, value) -> + raw.put( + field.getBytes(StandardCharsets.US_ASCII), + value.getBytes(StandardCharsets.US_ASCII))); RedisClient redis = mock(RedisClient.class); StatefulRedisConnection connection = mock(StatefulRedisConnection.class); RedisAsyncCommands commands = mock(RedisAsyncCommands.class); @@ -393,11 +389,10 @@ void installedOpenCanBeResolvedByExactTargetAndOnlyPerformsFreshReadback() throw Map raw = new HashMap<>(); expected .fields() - .forEach( - (field, value) -> - raw.put( - field.getBytes(StandardCharsets.US_ASCII), - value.getBytes(StandardCharsets.US_ASCII))); + .forEach((field, value) -> + raw.put( + field.getBytes(StandardCharsets.US_ASCII), + value.getBytes(StandardCharsets.US_ASCII))); RedisClient redis = mock(RedisClient.class); StatefulRedisConnection connection = mock(StatefulRedisConnection.class); RedisAsyncCommands commands = mock(RedisAsyncCommands.class); @@ -583,11 +578,10 @@ void ambiguousDispatchRetryRequiresExactOpenReadbackBeforeCompletingOriginalRece Map raw = new HashMap<>(); expected .fields() - .forEach( - (field, value) -> - raw.put( - field.getBytes(StandardCharsets.US_ASCII), - value.getBytes(StandardCharsets.US_ASCII))); + .forEach((field, value) -> + raw.put( + field.getBytes(StandardCharsets.US_ASCII), + value.getBytes(StandardCharsets.US_ASCII))); RedisClient redis = mock(RedisClient.class); StatefulRedisConnection connection = mock(StatefulRedisConnection.class); RedisAsyncCommands commands = mock(RedisAsyncCommands.class); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValueTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValueTest.java index 8ce2a1fa43..822d017aba 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValueTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValueTest.java @@ -101,47 +101,45 @@ void currentOpenProofRequiresExactCapturedEpochOriginalAttemptAndNineFields() { assertThat(proof.originalAttemptFence()).isEqualTo(9L); assertThat(proof.sourceControlEpoch()).isEqualTo(BigInteger.valueOf(9)); assertThat(proof.exactFields()).containsEntry("ownerFenceEpoch", "9"); - assertThatThrownBy( - () -> - new CanonicalGameplayAccountInitialOpenProof.CurrentOpen( - initializerId, - requestId, - callerContextId, - 9, - accountId, - tenantId, - namespaceId, - proof.key(), - BigInteger.ONE, - BigInteger.ONE, - DIGEST, - DIGEST, - DIGEST, - 1_000L, - 31_000L, - value.fields())) + assertThatThrownBy(() -> + new CanonicalGameplayAccountInitialOpenProof.CurrentOpen( + initializerId, + requestId, + callerContextId, + 9, + accountId, + tenantId, + namespaceId, + proof.key(), + BigInteger.ONE, + BigInteger.ONE, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 31_000L, + value.fields())) .isInstanceOf(IllegalArgumentException.class); Map changed = new LinkedHashMap<>(value.fields()); changed.put("ownerFenceEpoch", "1"); - assertThatThrownBy( - () -> - new CanonicalGameplayAccountInitialOpenProof.CurrentOpen( - initializerId, - requestId, - callerContextId, - 9, - accountId, - tenantId, - namespaceId, - proof.key(), - BigInteger.ZERO, - BigInteger.ONE, - DIGEST, - DIGEST, - DIGEST, - 1_000L, - 31_000L, - changed)) + assertThatThrownBy(() -> + new CanonicalGameplayAccountInitialOpenProof.CurrentOpen( + initializerId, + requestId, + callerContextId, + 9, + accountId, + tenantId, + namespaceId, + proof.key(), + BigInteger.ZERO, + BigInteger.ONE, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 31_000L, + changed)) .isInstanceOf(IllegalArgumentException.class); } @@ -181,10 +179,9 @@ void initialKeyUsesCanonicalBarrierSerializationOnlyForItsPersistedOriginalTarge + accountId + ":" + namespaceId); - assertThatThrownBy( - () -> - CanonicalGameplayAccountInitialBarrierKey.forTarget( - assignment, UUID.randomUUID(), requestId)) + assertThatThrownBy(() -> + CanonicalGameplayAccountInitialBarrierKey.forTarget( + assignment, UUID.randomUUID(), requestId)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> CanonicalGameplaySessionRedisKeys.accountAdmissionBarrier(assignment)) .isInstanceOf(IllegalArgumentException.class); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwnerTest.java index 3e537bf58b..2a9f82f216 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountMemberRepairRedisOwnerTest.java @@ -61,10 +61,8 @@ void readbackHasNoCallerAccessibleConstructorOrFactory() { assertThat( Arrays.stream( CanonicalGameplayAccountMemberRepairRedisOwner.Readback.class.getDeclaredMethods())) - .noneMatch( - method -> - Modifier.isStatic(method.getModifiers()) - && !Modifier.isPrivate(method.getModifiers())); + .noneMatch(method -> + Modifier.isStatic(method.getModifiers()) && !Modifier.isPrivate(method.getModifiers())); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java index e10e0d5fd5..50bb287f01 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortOwnerTest.java @@ -50,10 +50,8 @@ void accountTimeoutRetainsTheOriginalNonAdmittingObligation() { verify(accountClient) .abort( eq("presented-initial-gsa"), - org.mockito.ArgumentMatchers.argThat( - bytes -> - java.util.Arrays.equals( - ORIGINAL_LEASE.getBytes(StandardCharsets.UTF_8), bytes)), + org.mockito.ArgumentMatchers.argThat(bytes -> + java.util.Arrays.equals(ORIGINAL_LEASE.getBytes(StandardCharsets.UTF_8), bytes)), eq(TRANSITION_ID)); verify(repository, never()).recordFirstNewAccountAbort(any(), any()); } @@ -69,10 +67,9 @@ void retainedTerminalReplayStillAuthenticatesTheCurrentCallerAndCannotCasOnFailu .thenReturn(terminalSource); when(client.abort(eq("expired-or-revoked-caller"), any(byte[].class), eq(TRANSITION_ID))) .thenThrow(new IllegalStateException("current caller refused")); - assertThatThrownBy( - () -> - new CanonicalGameplayAdmissionAbortOwner(repository, client) - .abortFirstNew(TRANSITION_ID, "expired-or-revoked-caller")) + assertThatThrownBy(() -> + new CanonicalGameplayAdmissionAbortOwner(repository, client) + .abortFirstNew(TRANSITION_ID, "expired-or-revoked-caller")) .hasMessage("current caller refused"); verify(client).abort(eq("expired-or-revoked-caller"), any(byte[].class), eq(TRANSITION_ID)); verify(repository, never()).recordFirstNewAccountAbort(any(), any()); @@ -98,10 +95,9 @@ void unknownAccountAbortWithoutSeparateTransitionEvidenceCannotClearTheCandidate when(repository.readFirstNewAdmissionAbortRetrySource(TRANSITION_ID)).thenReturn(provisional); when(client.abort(any(), any(), any())).thenReturn(operation); - assertThatThrownBy( - () -> - new CanonicalGameplayAdmissionAbortOwner(repository, client) - .abortFirstNew(TRANSITION_ID, "presented-initial-gsa")) + assertThatThrownBy(() -> + new CanonicalGameplayAdmissionAbortOwner(repository, client) + .abortFirstNew(TRANSITION_ID, "presented-initial-gsa")) .isInstanceOf(IllegalStateException.class) .hasMessage("Account ABORTED result lacks exact cleanup evidence"); verify(repository, never()).recordFirstNewAccountAbort(any(), any()); @@ -153,10 +149,9 @@ void ambientTransactionOrSynchronizationRefusesBeforeAnyOwnerInteraction() { .setActualTransactionActive(true); } try { - assertThatThrownBy( - () -> - new CanonicalGameplayAdmissionAbortOwner(repository, client) - .abortFirstNew(TRANSITION_ID, "presented-initial-gsa")) + assertThatThrownBy(() -> + new CanonicalGameplayAdmissionAbortOwner(repository, client) + .abortFirstNew(TRANSITION_ID, "presented-initial-gsa")) .hasMessage("First-NEW Account abort requires no ambient SQL scope"); org.mockito.Mockito.verifyNoInteractions(repository, client); } finally { @@ -200,10 +195,9 @@ void retainedAbortRejectsContradictoryAccountStatesOrChangedCleanupWithoutCas() } when(repository.readFirstNewAdmissionAbortRetrySource(TRANSITION_ID)).thenReturn(retained); when(client.abort(any(), any(), any())).thenReturn(operation); - assertThatThrownBy( - () -> - new CanonicalGameplayAdmissionAbortOwner(repository, client) - .abortFirstNew(TRANSITION_ID, "presented-initial-gsa")) + assertThatThrownBy(() -> + new CanonicalGameplayAdmissionAbortOwner(repository, client) + .abortFirstNew(TRANSITION_ID, "presented-initial-gsa")) .hasMessage("Account replay contradicts the retained definitive abort"); verify(repository, never()).recordFirstNewAccountAbort(any(), any()); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java index f09b40e6dd..4308f7f03c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionDecisionReadGrpcServiceTest.java @@ -639,10 +639,9 @@ void negativeDecisionMissingAndWithdrawnQualificationRemainUnavailable() { redis, catalog, fixture.repository(), tags, qualification); try (var codec = mockStatic(AccountGameplayAdmissionNeverAdmittedGrpcCodec.class)) { codec - .when( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseDecisionRequest( - fixture.request())) + .when(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseDecisionRequest( + fixture.request())) .thenReturn(fixture.selector()); new CanonicalGameplayAdmissionDecisionReadGrpcService( fixture.repository(), fixture.guard(), "test", owner) @@ -659,10 +658,9 @@ void negativeDecisionWithoutClosureOwnerRemainsUnavailableWithoutRepositoryRead( var fixture = validNegativeReadFixture(); try (var codec = mockStatic(AccountGameplayAdmissionNeverAdmittedGrpcCodec.class)) { codec - .when( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseDecisionRequest( - fixture.request())) + .when(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseDecisionRequest( + fixture.request())) .thenReturn(fixture.selector()); new CanonicalGameplayAdmissionDecisionReadGrpcService( fixture.repository(), fixture.guard(), "test") @@ -686,10 +684,9 @@ void negativeDecisionWithoutRetainedClosureIsDefinitiveFailedPrecondition() { redis, catalog, fixture.repository(), tags, qualification); try (var codec = mockStatic(AccountGameplayAdmissionNeverAdmittedGrpcCodec.class)) { codec - .when( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseDecisionRequest( - fixture.request())) + .when(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseDecisionRequest( + fixture.request())) .thenReturn(fixture.selector()); new CanonicalGameplayAdmissionDecisionReadGrpcService( fixture.repository(), fixture.guard(), "test", owner) @@ -752,15 +749,13 @@ void negativeDecisionEncodingFailuresRemainInternalIncludingAvailabilityShapedEx continueNegativeRead(fixture); try (var codec = mockStatic(AccountGameplayAdmissionNeverAdmittedGrpcCodec.class)) { codec - .when( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseDecisionRequest( - fixture.request())) + .when(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseDecisionRequest( + fixture.request())) .thenReturn(fixture.selector()); codec - .when( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.toDecisionResponse(any(), any())) + .when(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.toDecisionResponse(any(), any())) .thenThrow(failure); receiveNegative(fixture); } @@ -785,10 +780,9 @@ void negativeDecisionEncodesInsideClosureContinuationAndPublishesOnlyAfterItRetu .withCurrentClosedCandidate(eq(fixture.selector().transitionId()), any()); try (var codec = mockStatic(AccountGameplayAdmissionNeverAdmittedGrpcCodec.class)) { codec - .when( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseDecisionRequest( - fixture.request())) + .when(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseDecisionRequest( + fixture.request())) .thenReturn(fixture.selector()); codec .when( @@ -798,10 +792,9 @@ void negativeDecisionEncodesInsideClosureContinuationAndPublishesOnlyAfterItRetu var evidence = ArgumentCaptor.forClass( AccountGameplayAdmissionNeverAdmittedGrpcCodec.NegativeDecisionEvidence.class); - codec.verify( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.toDecisionResponse( - eq(fixture.selector()), evidence.capture())); + codec.verify(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.toDecisionResponse( + eq(fixture.selector()), evidence.capture())); assertThat(evidence.getValue().transitionId()).isEqualTo(fixture.selector().transitionId()); assertThat(evidence.getValue().abandonmentId()).isEqualTo(fixture.selector().abandonmentId()); assertThat(evidence.getValue().originalLeaseEvidence()) @@ -829,10 +822,9 @@ void negativeDecisionFinalQualificationWithdrawalDiscardsEncodedResponse() { var response = GetOriginalNewNeverAdmittedDecisionResponse.getDefaultInstance(); try (var codec = mockStatic(AccountGameplayAdmissionNeverAdmittedGrpcCodec.class)) { codec - .when( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseDecisionRequest( - fixture.request())) + .when(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseDecisionRequest( + fixture.request())) .thenReturn(fixture.selector()); codec .when( @@ -856,15 +848,13 @@ void negativeDecisionOnNextFailureSignalsOneErrorAndCompletionFailureHasNoSecond else doThrow(failure).when(fixture.observer()).onNext(response); try (var codec = mockStatic(AccountGameplayAdmissionNeverAdmittedGrpcCodec.class)) { codec - .when( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseDecisionRequest( - fixture.request())) + .when(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseDecisionRequest( + fixture.request())) .thenReturn(fixture.selector()); codec - .when( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.toDecisionResponse(any(), any())) + .when(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.toDecisionResponse(any(), any())) .thenReturn(response); if (completionFailure) assertThatThrownBy(() -> receiveNegative(fixture)).isSameAs(failure); else receiveNegative(fixture); @@ -1070,10 +1060,9 @@ void unexpectedResponseEncodingFailureTerminatesOnceWithInternalWithoutAnswer() () -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(fixture.request())) .thenReturn(fixture.selector()); codec - .when( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toResponse( - any(), any(), any(), any(), any(), any(), any(), any())) + .when(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toResponse( + any(), any(), any(), any(), any(), any(), any(), any())) .thenThrow(new IllegalStateException("private response codec details")); new CanonicalGameplayAdmissionDecisionReadGrpcService( fixture.repository(), fixture.guard(), "test") @@ -1139,10 +1128,9 @@ void onNextFailureSignalsOneErrorButCompletionFailureEscapesWithoutSecondTermina .when(() -> CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseRequest(request)) .thenReturn(selector); codec - .when( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toResponse( - any(), any(), any(), any(), any(), any(), any(), any())) + .when(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toResponse( + any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(response); Runnable receive = () -> @@ -1277,10 +1265,9 @@ private static void continueNegativeRead(NegativeReadFixture fixture) { private static void parseAndReceiveNegative(NegativeReadFixture fixture) { try (var codec = mockStatic(AccountGameplayAdmissionNeverAdmittedGrpcCodec.class)) { codec - .when( - () -> - AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseDecisionRequest( - fixture.request())) + .when(() -> + AccountGameplayAdmissionNeverAdmittedGrpcCodec.parseDecisionRequest( + fixture.request())) .thenReturn(fixture.selector()); receiveNegative(fixture); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java index 3e7673a4aa..801124ad5b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionPublishedReadGrpcServiceTest.java @@ -100,25 +100,21 @@ void resolverReadsActualTenantOwnerTwiceAndPassesItsUnchangedTargetToClosedEncod when(f.routes.readCurrentTarget(TENANT)).thenReturn(route); try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { codec - .when( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetResolutionRequest( - request)) + .when(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetResolutionRequest(request)) .thenReturn(f.selector); codec - .when( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( - eq(f.selector), any())) + .when(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( + eq(f.selector), any())) .thenReturn(response); f.service.resolvePublishedRealmAdmissionTarget(request, f.resolverObserver); var encoded = org.mockito.ArgumentCaptor.forClass( CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target.class); - codec.verify( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( - eq(f.selector), encoded.capture())); + codec.verify(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toTargetResolutionResponse( + eq(f.selector), encoded.capture())); assertThat(encoded.getValue()) .usingRecursiveComparison() .withComparatorForFields( @@ -126,10 +122,9 @@ void resolverReadsActualTenantOwnerTwiceAndPassesItsUnchangedTargetToClosedEncod "initialAdmissionOriginKind", "ownerProofOutcome") .isEqualTo(route); - codec.verify( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.requireRetainedTargetMatches( - eq(f.selector), eq(encoded.getValue()))); + codec.verify(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.requireRetainedTargetMatches( + eq(f.selector), eq(encoded.getValue()))); } verify(f.routes, times(2)).readCurrentTarget(TENANT); verify(f.resolverObserver).onNext(response); @@ -155,10 +150,9 @@ void resolverTargetChangeAndUnavailableStorageReturnNoSelectionEvidence() { } try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { codec - .when( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetResolutionRequest( - request)) + .when(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parseTargetResolutionRequest( + request)) .thenReturn(f.selector); f.service.resolvePublishedRealmAdmissionTarget(request, f.resolverObserver); } @@ -195,22 +189,18 @@ void strictReadUsesPublishedOwnerBetweenCompleteRouteReadsAndReturnsItsExactSour var encodedWorld = ArgumentCaptor.forClass(WorldCanonicalInstanceLifecycleEvidence.class); try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { codec - .when( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( - request)) + .when(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest(request)) .thenReturn(parsed); codec - .when( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( - eq(parsed), eq(source), any(), any())) + .when(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( + eq(parsed), eq(source), any(), any())) .thenReturn(response); f.service.getPublishedRealmAdmissionOwnerRead(request, f.publishedObserver); - codec.verify( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( - eq(parsed), eq(source), encodedTarget.capture(), encodedWorld.capture())); + codec.verify(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.toPublishedRealmResponse( + eq(parsed), eq(source), encodedTarget.capture(), encodedWorld.capture())); } assertThat(encodedTarget.getValue()) .usingRecursiveComparison() @@ -322,10 +312,8 @@ void strictReadPreservesUnavailableAndRejectsChangedRouteWithoutReturningSource( } try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { codec - .when( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( - request)) + .when(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest(request)) .thenReturn(parsed); f.service.getPublishedRealmAdmissionOwnerRead(request, f.publishedObserver); } @@ -377,10 +365,8 @@ void strictReadRejectsMissingInactiveWrongEpochAndUnavailableWorldWithoutPositiv } try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { codec - .when( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( - request)) + .when(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest(request)) .thenReturn(parsed); f.service.getPublishedRealmAdmissionOwnerRead(request, f.publishedObserver); } @@ -466,10 +452,8 @@ void strictReadRefusesAbsentMismatchedOrChangedLaunchAuthority(String change) { } try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { codec - .when( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( - request)) + .when(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest(request)) .thenReturn(parsed); f.service.getPublishedRealmAdmissionOwnerRead(request, f.publishedObserver); } @@ -497,10 +481,8 @@ void strictReadRefusesPublicationChangeAfterTheHealthyWorldRead() { mock(CanonicalGameplayRosterOwnerReadEvidence.class)); try (var codec = mockStatic(CanonicalGameplayAdmissionDecisionReadGrpcCodec.class)) { codec - .when( - () -> - CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest( - request)) + .when(() -> + CanonicalGameplayAdmissionDecisionReadGrpcCodec.parsePublishedRealmRequest(request)) .thenReturn(parsed); f.service.getPublishedRealmAdmissionOwnerRead(request, f.publishedObserver); } @@ -658,12 +640,11 @@ private CanonicalPlayableTarget configureStrictRoute( when(published.readCurrent(selector)) .thenReturn(mock(CanonicalGameplayRosterOwnerReadEvidence.class)); when(world.read(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - return worldEvidence(invocation.getArgument(0), "ACTIVE", 7); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return worldEvidence(invocation.getArgument(0), "ACTIVE", 7); + }); return current; } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayFreshNamespaceRedisReconcilerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayFreshNamespaceRedisReconcilerTest.java index ddbe01aad9..b046028360 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayFreshNamespaceRedisReconcilerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayFreshNamespaceRedisReconcilerTest.java @@ -87,9 +87,8 @@ void retainedLegacySourceRemainsUnchangedAndBlocksReconciliation() { redisWithScans(List.of(List.of(LEGACY_CONTEXT), List.of(LEGACY_CONTEXT))); CanonicalGameplayFreshNamespaceRedisReconciler reconciler = reconciler(redis); - assertThatThrownBy( - () -> - reconciler.rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + assertThatThrownBy(() -> + reconciler.rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("Complete empty legacy source inventory"); @@ -103,9 +102,8 @@ void retainedTargetOrUnknownNamespaceKeyRemainsUnchangedAndBlocksReconciliation( redisWithScans(scans(List.of(), List.of(), List.of(TARGET_KEY), List.of(TARGET_KEY))); CanonicalGameplayFreshNamespaceRedisReconciler reconciler = reconciler(redis); - assertThatThrownBy( - () -> - reconciler.rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + assertThatThrownBy(() -> + reconciler.rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("session or index family is retained or unknown"); @@ -151,10 +149,9 @@ void unsupportedIssuerProjectionIdentityIsDeniedWithoutMutation() { String malformed = "session:game:auth:issuer-generation:v1:" + issuerId; StringRedisTemplate redis = redisWithScans(scans(List.of(), List.of(), List.of(malformed))); - assertThatThrownBy( - () -> - reconciler(redis) - .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(2))) + assertThatThrownBy(() -> + reconciler(redis) + .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(2))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("unsupported issuer identity") .hasMessageContaining("preserve legacy UUID issuer keys"); @@ -180,9 +177,8 @@ void repeatedCanonicalIssuerVisitsAreDeduplicatedButRemainVisitBounded() { CanonicalGameplayFreshNamespaceRedisReconciler reconciler = new CanonicalGameplayFreshNamespaceRedisReconciler(redis, visitLimit); - assertThatThrownBy( - () -> - reconciler.rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(2))) + assertThatThrownBy(() -> + reconciler.rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(2))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("duplicate-safe visit bound"); @@ -195,20 +191,18 @@ void nonterminalCursorAndCursorFailureFailClosed() { StringRedisTemplate nonterminal = redisWithResults( List.of(ScanResult.empty(), ScanResult.empty(), ScanResult.withCursor(List.of(), 19L))); - assertThatThrownBy( - () -> - reconciler(nonterminal) - .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + assertThatThrownBy(() -> + reconciler(nonterminal) + .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("terminal cursor identity"); StringRedisTemplate failed = redisWithResults( List.of(ScanResult.empty(), ScanResult.empty(), ScanResult.failedCursor())); - assertThatThrownBy( - () -> - reconciler(failed) - .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + assertThatThrownBy(() -> + reconciler(failed) + .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("cursor failed before complete exhaustion"); verifyNoRedisMutationOrValueRead(nonterminal); @@ -227,9 +221,8 @@ void clusterConnectionIsRefusedBeforeLegacyScan() { invokeThroughRedisCallback(redis, connection); CanonicalGameplayFreshNamespaceRedisReconciler reconciler = reconciler(redis); - assertThatThrownBy( - () -> - reconciler.rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + assertThatThrownBy(() -> + reconciler.rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining( "Legacy Redis cluster scan cannot prove complete cluster-wide inventory"); @@ -246,10 +239,9 @@ void standaloneWrapperReportingClusterEnabledIsRefusedBeforeAnyNamespaceScan() { when(connection.serverCommands()).thenReturn(serverCommands); invokeThroughRedisCallback(redis, connection); - assertThatThrownBy( - () -> - reconciler(redis) - .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + assertThatThrownBy(() -> + reconciler(redis) + .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("standalone topology could not be proven"); @@ -266,10 +258,9 @@ void unavailableTopologyObservationIsRefusedBeforeAnyNamespaceScan() { when(connection.serverCommands()).thenReturn(serverCommands); invokeThroughRedisCallback(redis, connection); - assertThatThrownBy( - () -> - reconciler(redis) - .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + assertThatThrownBy(() -> + reconciler(redis) + .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("standalone topology could not be proven"); @@ -282,10 +273,9 @@ void firstAndSecondTargetInventoriesMustBeIdentical() { StringRedisTemplate redis = redisWithScans(scans(List.of(), List.of(), List.of(), List.of(TARGET_KEY))); - assertThatThrownBy( - () -> - reconciler(redis) - .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + assertThatThrownBy(() -> + reconciler(redis) + .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("changed between complete fenced scans"); @@ -298,10 +288,9 @@ void fenceDriftDuringTargetScanPreventsFurtherInventoryOrReadback() { StringRedisTemplate redis = redisWithScans(emptyScans(8)); TestCohort driftingCohort = new TestCohort(11); - assertThatThrownBy( - () -> - reconciler(redis) - .rebuildExact(driftingCohort, emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + assertThatThrownBy(() -> + reconciler(redis) + .rebuildExact(driftingCohort, emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("changed during reconciliation"); @@ -370,9 +359,8 @@ void scanBoundsFailClosedBeforeACompleteNamespaceClaim() { CanonicalGameplayFreshNamespaceRedisReconciler reconciler = new CanonicalGameplayFreshNamespaceRedisReconciler(redis, tightLimits); - assertThatThrownBy( - () -> - reconciler.rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + assertThatThrownBy(() -> + reconciler.rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("unique-key bound"); @@ -383,10 +371,9 @@ void scanBoundsFailClosedBeforeACompleteNamespaceClaim() { void keyLengthAndElapsedTimeBoundsFailClosed() { StringRedisTemplate longKeyRedis = redisWithScans(scans(List.of(), List.of(), List.of("session:game:" + "x".repeat(300)))); - assertThatThrownBy( - () -> - reconciler(longKeyRedis) - .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + assertThatThrownBy(() -> + reconciler(longKeyRedis) + .rebuildExact(cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("exceeds its byte bound"); @@ -396,10 +383,9 @@ void keyLengthAndElapsedTimeBoundsFailClosed() { 2, 20, 40, 256, Duration.ofNanos(1)); var timedReconciler = new CanonicalGameplayFreshNamespaceRedisReconciler(timedRedis, immediateDeadline); - assertThatThrownBy( - () -> - timedReconciler.rebuildExact( - cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) + assertThatThrownBy(() -> + timedReconciler.rebuildExact( + cohort(), emptyLegacySnapshot(), emptyCanonicalSnapshot(1))) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("time bound"); verify(timedRedis, never()).execute(any(RedisCallback.class)); @@ -447,14 +433,13 @@ private static RedisFixture redisFixtureWithResults(List scans) { RedisConnection connection = mock(RedisConnection.class); AtomicInteger scanIndex = new AtomicInteger(); when(connection.scan(any(ScanOptions.class))) - .thenAnswer( - ignored -> { - int index = scanIndex.getAndIncrement(); - if (index >= scans.size()) { - throw new AssertionError("unexpected additional Redis scan"); - } - return cursor(scans.get(index)); - }); + .thenAnswer(ignored -> { + int index = scanIndex.getAndIncrement(); + if (index >= scans.size()) { + throw new AssertionError("unexpected additional Redis scan"); + } + return cursor(scans.get(index)); + }); RedisServerCommands serverCommands = serverCommandsWithTopology("0"); when(connection.serverCommands()).thenReturn(serverCommands); invokeThroughRedisCallback(redis, connection); @@ -504,9 +489,8 @@ private static Cursor cursor(ScanResult result) { } else { when(cursor.hasNext()).thenAnswer(ignored -> index.get() < result.keys().size()); when(cursor.next()) - .thenAnswer( - ignored -> - result.keys().get(index.getAndIncrement()).getBytes(StandardCharsets.UTF_8)); + .thenAnswer(ignored -> + result.keys().get(index.getAndIncrement()).getBytes(StandardCharsets.UTF_8)); when(cursor.getCursorId()).thenReturn(result.terminalCursorId()); } return cursor; diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest.java index 547748b9eb..b949f2ead5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest.java @@ -63,22 +63,19 @@ void rejectsUnknownFieldsAndAnAccountOrGlobalCoverageAlias() throws Exception { ObjectNode unissuedAcknowledgement = original.deepCopy(); unissuedAcknowledgement.put("issuerBindingLocalAcknowledgementGeneration", "NOT_YET_ISSUED"); - assertThatThrownBy( - () -> - CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.decode( - JSON.writeValueAsBytes(unknown))) + assertThatThrownBy(() -> + CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.decode( + JSON.writeValueAsBytes(unknown))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("missing or unknown fields"); - assertThatThrownBy( - () -> - CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.decode( - JSON.writeValueAsBytes(globalCoverage))) + assertThatThrownBy(() -> + CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.decode( + JSON.writeValueAsBytes(globalCoverage))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("version or scope"); - assertThatThrownBy( - () -> - CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.decode( - JSON.writeValueAsBytes(unissuedAcknowledgement))) + assertThatThrownBy(() -> + CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.decode( + JSON.writeValueAsBytes(unissuedAcknowledgement))) .isInstanceOf(IllegalArgumentException.class); } @@ -98,26 +95,25 @@ void rejectsDifferentOriginalReservationProvenanceUnderTheSameBinding() { original.reservation().inventorySnapshotRevision().add(BigInteger.ONE), original.reservation().inventoryRevision()); - assertThatThrownBy( - () -> - new CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence( - original.operationId(), - original.issuerBindingLocalAcknowledgementGeneration(), - original.requestId(), - original.transitionId(), - original.candidateAccountIndexFence(), - original.issuerId(), - original.bindingRef(), - original.bindingGeneration(), - original.memberValueBytes(), - original.memberValueDigest(), - changedReservation, - original.anchor(), - original.memberOperation(), - original.currentSource(), - original.physicalReadback(), - original.capacity(), - original.sqlCurrentnessDigest())) + assertThatThrownBy(() -> + new CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence( + original.operationId(), + original.issuerBindingLocalAcknowledgementGeneration(), + original.requestId(), + original.transitionId(), + original.candidateAccountIndexFence(), + original.issuerId(), + original.bindingRef(), + original.bindingGeneration(), + original.memberValueBytes(), + original.memberValueDigest(), + changedReservation, + original.anchor(), + original.memberOperation(), + original.currentSource(), + original.physicalReadback(), + original.capacity(), + original.sqlCurrentnessDigest())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("exact member and proof tuples"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalFieldSetCodecTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalFieldSetCodecTest.java index 0f236fbc96..743def9a91 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalFieldSetCodecTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalFieldSetCodecTest.java @@ -38,10 +38,9 @@ void fieldSetCodecRejectsOneMoreThanTheLocalPhysicalFieldBound() { assertThatThrownBy( () -> CanonicalGameplayIssuerBootstrapCoverageRepository.encodeFieldSet(overLimit)) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( - fieldCountHeader(MAX_LOCAL_PHYSICAL_FIELD_COUNT + 1))) + assertThatThrownBy(() -> + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( + fieldCountHeader(MAX_LOCAL_PHYSICAL_FIELD_COUNT + 1))) .isInstanceOf(IllegalStateException.class) .hasMessage("Persisted issuer physical field count is outside its bound"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRedisKeysTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRedisKeysTest.java index 1dad8f16eb..35fd994315 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRedisKeysTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerRedisKeysTest.java @@ -83,10 +83,9 @@ void rejectsMismatchedOrOutOfLayoutPartitions() { CanonicalGameplayBindingRef bindingRef = CanonicalGameplayBindingRef.of("tenant-01", "instance-01", "session-01"); - assertThatThrownBy( - () -> - CanonicalGameplayIssuerRedisKeys.forBindingReference( - layout, bindingRef, BigInteger.valueOf(6))) + assertThatThrownBy(() -> + CanonicalGameplayIssuerRedisKeys.forBindingReference( + layout, bindingRef, BigInteger.valueOf(6))) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> CanonicalGameplayIssuerRedisKeys.forPartition(layout, BigInteger.valueOf(16))) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationOwnerTest.java index 281ebd69e4..8db79f62d5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyMigrationOwnerTest.java @@ -98,12 +98,11 @@ public void requireStillFenced( assertThatThrownBy(owner::migrate) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("remains fenced and unresolved") - .satisfies( - failure -> { - assertThat(failure.getCause()).isSameAs(originalAdapterFailure); - assertThat(originalAdapterFailure.getSuppressed()) - .containsExactly(blockPersistenceFailure); - }); + .satisfies(failure -> { + assertThat(failure.getCause()).isSameAs(originalAdapterFailure); + assertThat(originalAdapterFailure.getSuppressed()) + .containsExactly(blockPersistenceFailure); + }); verify(migration).begin(cohortId, writerFence, identity); verify(migration).block(operationId, "OWNER_ADAPTER_AMBIGUOUS"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyRedisSourceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyRedisSourceTest.java index 2ce791b758..56cf5592f0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyRedisSourceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayLegacyRedisSourceTest.java @@ -59,10 +59,9 @@ void clusterConnectionIsRefusedBeforeLegacyScanEvenWhenInfoClaimsStandalone() { when(connection.serverCommands()).thenReturn(serverCommands); invokeThroughRedisCallback(redis, connection); - assertThatThrownBy( - () -> - new CanonicalGameplayLegacyRedisSource(redis, limits()) - .captureEveryKnownFamily(cohort())) + assertThatThrownBy(() -> + new CanonicalGameplayLegacyRedisSource(redis, limits()) + .captureEveryKnownFamily(cohort())) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("cluster scan cannot prove complete cluster-wide inventory"); @@ -81,10 +80,9 @@ void unknownOrMissingStandaloneTopologyIsRefusedBeforeLegacyScan() { when(connection.serverCommands()).thenReturn(serverCommands); invokeThroughRedisCallback(redis, connection); - assertThatThrownBy( - () -> - new CanonicalGameplayLegacyRedisSource(redis, limits()) - .captureEveryKnownFamily(cohort())) + assertThatThrownBy(() -> + new CanonicalGameplayLegacyRedisSource(redis, limits()) + .captureEveryKnownFamily(cohort())) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("standalone topology could not be proven"); @@ -101,10 +99,9 @@ void topologyInfoFailureIsRefusedBeforeLegacyScan() { when(connection.serverCommands()).thenReturn(serverCommands); invokeThroughRedisCallback(redis, connection); - assertThatThrownBy( - () -> - new CanonicalGameplayLegacyRedisSource(redis, limits()) - .captureEveryKnownFamily(cohort())) + assertThatThrownBy(() -> + new CanonicalGameplayLegacyRedisSource(redis, limits()) + .captureEveryKnownFamily(cohort())) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("standalone topology could not be proven"); @@ -122,13 +119,12 @@ void unknownPrefixKeyMakesTheInventoryIncompleteAndNonAuthorizing() { assertThat(snapshot.everyEntryIsReconciled()).isFalse(); assertThat(snapshot.entries()) .singleElement() - .satisfies( - entry -> { - assertThat(entry.family()) - .isEqualTo(CanonicalGameplayLegacyMigrationSourceSnapshot.Family.UNCLASSIFIED); - assertThat(entry.disposition()) - .isEqualTo(CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition.UNKNOWN); - }); + .satisfies(entry -> { + assertThat(entry.family()) + .isEqualTo(CanonicalGameplayLegacyMigrationSourceSnapshot.Family.UNCLASSIFIED); + assertThat(entry.disposition()) + .isEqualTo(CanonicalGameplayLegacyMigrationSourceSnapshot.Disposition.UNKNOWN); + }); assertThat(snapshot.toString()).doesNotContain(FIRST_PARTY_CONTEXT); } @@ -164,10 +160,9 @@ void cursorFailureAndUniqueKeyLimitFailClosed() { when(brokenConnection.serverCommands()).thenReturn(brokenServerCommands); invokeThroughRedisCallback(brokenCursorRedis, brokenConnection); - assertThatThrownBy( - () -> - new CanonicalGameplayLegacyRedisSource(brokenCursorRedis, limits()) - .captureEveryKnownFamily(cohort())) + assertThatThrownBy(() -> + new CanonicalGameplayLegacyRedisSource(brokenCursorRedis, limits()) + .captureEveryKnownFamily(cohort())) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("cursor failed before complete exhaustion"); @@ -180,10 +175,9 @@ void cursorFailureAndUniqueKeyLimitFailClosed() { RedisServerCommands incompleteServerCommands = standaloneServerCommands(); when(incompleteConnection.serverCommands()).thenReturn(incompleteServerCommands); invokeThroughRedisCallback(incompleteCursorRedis, incompleteConnection); - assertThatThrownBy( - () -> - new CanonicalGameplayLegacyRedisSource(incompleteCursorRedis, limits()) - .captureEveryKnownFamily(cohort())) + assertThatThrownBy(() -> + new CanonicalGameplayLegacyRedisSource(incompleteCursorRedis, limits()) + .captureEveryKnownFamily(cohort())) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("terminal cursor identity"); @@ -193,10 +187,9 @@ void cursorFailureAndUniqueKeyLimitFailClosed() { List.of(TENANT_CONTEXT, SESSION_ALIAS), List.of(TENANT_CONTEXT, SESSION_ALIAS))); var tightLimits = new CanonicalGameplayLegacyRedisSource.ScanLimits(2, 1, 4, 256, Duration.ofSeconds(5)); - assertThatThrownBy( - () -> - new CanonicalGameplayLegacyRedisSource(overLimitRedis, tightLimits) - .captureEveryKnownFamily(cohort())) + assertThatThrownBy(() -> + new CanonicalGameplayLegacyRedisSource(overLimitRedis, tightLimits) + .captureEveryKnownFamily(cohort())) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("unique-key bound"); verify(overLimitRedis, times(1)).execute(any(RedisCallback.class)); @@ -207,10 +200,9 @@ void differentFirstAndSecondInventoriesAreRejected() { StringRedisTemplate redis = redisWithScans(List.of(List.of(TENANT_CONTEXT), List.of(SESSION_ALIAS))); - assertThatThrownBy( - () -> - new CanonicalGameplayLegacyRedisSource(redis, limits()) - .captureEveryKnownFamily(cohort())) + assertThatThrownBy(() -> + new CanonicalGameplayLegacyRedisSource(redis, limits()) + .captureEveryKnownFamily(cohort())) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) .hasMessageContaining("changed between complete fenced scans"); } @@ -223,10 +215,9 @@ void fenceDriftDuringABatchPreventsTheSecondScan() { var oneKeyPerFenceCheck = new CanonicalGameplayLegacyRedisSource.ScanLimits(1, 10, 10, 256, Duration.ofSeconds(5)); - assertThatThrownBy( - () -> - new CanonicalGameplayLegacyRedisSource(redis, oneKeyPerFenceCheck) - .captureEveryKnownFamily(driftingCohort)) + assertThatThrownBy(() -> + new CanonicalGameplayLegacyRedisSource(redis, oneKeyPerFenceCheck) + .captureEveryKnownFamily(driftingCohort)) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); verify(redis, times(1)).execute(any(RedisCallback.class)); } @@ -252,14 +243,13 @@ private static RedisFixture redisFixtureWithScans(List> scans) { RedisConnection connection = mock(RedisConnection.class); AtomicInteger scanIndex = new AtomicInteger(); when(connection.scan(any(ScanOptions.class))) - .thenAnswer( - ignored -> { - int index = scanIndex.getAndIncrement(); - if (index >= scans.size()) { - throw new AssertionError("unexpected third Redis scan"); - } - return cursor(scans.get(index)); - }); + .thenAnswer(ignored -> { + int index = scanIndex.getAndIncrement(); + if (index >= scans.size()) { + throw new AssertionError("unexpected third Redis scan"); + } + return cursor(scans.get(index)); + }); RedisServerCommands serverCommands = mock(RedisServerCommands.class); Properties clusterInformation = new Properties(); clusterInformation.setProperty("cluster_enabled", "0"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java index e9f021d946..25fdf065e3 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java @@ -80,13 +80,12 @@ void migrationSourceInventoryExcludesOneExplicitFlywaySchemaMarkerAndSortsSqlSou @Test void migrationSourceInventoryRejectsMultipleFlywaySchemaMarkers() { - assertThatThrownBy( - () -> - CanonicalGameplayMigrationDriverMain.migrationSourceInventory( - new MigrationInfo[] { - migration(CoreMigrationType.SCHEMA, null, null, null), - migration(CoreMigrationType.SCHEMA, null, null, null) - })) + assertThatThrownBy(() -> + CanonicalGameplayMigrationDriverMain.migrationSourceInventory( + new MigrationInfo[] { + migration(CoreMigrationType.SCHEMA, null, null, null), + migration(CoreMigrationType.SCHEMA, null, null, null) + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("schema marker was ambiguous"); } @@ -95,27 +94,24 @@ void migrationSourceInventoryRejectsMultipleFlywaySchemaMarkers() { void migrationSourceInventoryRetainsDuplicateAndMalformedNormalMigrationRejection() { MigrationInfo firstVersionOne = migration(CoreMigrationType.SQL, "1", "V1__first.sql", 11); MigrationInfo duplicateVersionOne = migration(CoreMigrationType.SQL, "1", "V1__second.sql", 12); - assertThatThrownBy( - () -> - CanonicalGameplayMigrationDriverMain.migrationSourceInventory( - new MigrationInfo[] {firstVersionOne, duplicateVersionOne})) + assertThatThrownBy(() -> + CanonicalGameplayMigrationDriverMain.migrationSourceInventory( + new MigrationInfo[] {firstVersionOne, duplicateVersionOne})) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("versions were ambiguous"); MigrationInfo missingVersion = migration(CoreMigrationType.SQL, null, "V1__missing_version.sql", 11); - assertThatThrownBy( - () -> - CanonicalGameplayMigrationDriverMain.migrationSourceInventory( - new MigrationInfo[] {missingVersion})) + assertThatThrownBy(() -> + CanonicalGameplayMigrationDriverMain.migrationSourceInventory( + new MigrationInfo[] {missingVersion})) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("identity was incomplete"); MigrationInfo missingScript = migration(CoreMigrationType.SQL, "1", null, 11); - assertThatThrownBy( - () -> - CanonicalGameplayMigrationDriverMain.migrationSourceInventory( - new MigrationInfo[] {missingScript})) + assertThatThrownBy(() -> + CanonicalGameplayMigrationDriverMain.migrationSourceInventory( + new MigrationInfo[] {missingScript})) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("identity was incomplete"); } @@ -132,25 +128,21 @@ void redisTlsObservationRequiresOnlyTheExactTlsEndpointAndDisabledPlainPort() { assertThat(observation) .containsExactlyInAnyOrderEntriesOf( Map.of("runId", runId, "tlsEnabled", true, "tlsPort", 6380, "trustCaSha256", caDigest)); - assertThatThrownBy( - () -> - CanonicalGameplayMigrationDriverMain.validatedRedisObservation( - runId, null, "6380", caDigest)) + assertThatThrownBy(() -> + CanonicalGameplayMigrationDriverMain.validatedRedisObservation( + runId, null, "6380", caDigest)) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - CanonicalGameplayMigrationDriverMain.validatedRedisObservation( - runId, "6379", "6380", caDigest)) + assertThatThrownBy(() -> + CanonicalGameplayMigrationDriverMain.validatedRedisObservation( + runId, "6379", "6380", caDigest)) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - CanonicalGameplayMigrationDriverMain.validatedRedisObservation( - runId, "0", "6379", caDigest)) + assertThatThrownBy(() -> + CanonicalGameplayMigrationDriverMain.validatedRedisObservation( + runId, "0", "6379", caDigest)) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - CanonicalGameplayMigrationDriverMain.validatedRedisObservation( - runId, "0", "6380", null)) + assertThatThrownBy(() -> + CanonicalGameplayMigrationDriverMain.validatedRedisObservation( + runId, "0", "6380", null)) .isInstanceOf(IllegalStateException.class); } @@ -164,10 +156,8 @@ void redisTopologyRequiresAnUnambiguousStandaloneServerObservation() { () -> CanonicalGameplayMigrationDriverMain.requireStandaloneRedisTopology(null)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("topology"); - assertThatThrownBy( - () -> - CanonicalGameplayMigrationDriverMain.requireStandaloneRedisTopology( - new Properties())) + assertThatThrownBy(() -> + CanonicalGameplayMigrationDriverMain.requireStandaloneRedisTopology(new Properties())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("topology"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSessionTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSessionTest.java index 5a1918e2b6..597e2c8f17 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSessionTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewAuthenticatedSessionTest.java @@ -91,10 +91,8 @@ void buildsNonPersistableTemplateAndAcceptsExactFinalCasReadback() throws Except .doesNotContain(fixture.compactJwt) .doesNotContain("\"lineageId\"") .doesNotContain("\"authTokenJti\""); - assertThatThrownBy( - () -> - CanonicalGameplayOriginalNewAuthenticatedSession.parseFinalized( - templateBytes, CLOCK)) + assertThatThrownBy(() -> + CanonicalGameplayOriginalNewAuthenticatedSession.parseFinalized(templateBytes, CLOCK)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Canonical ORIGINAL_NEW authenticated session is invalid"); @@ -141,12 +139,11 @@ void accountSignatureAndBoundClaimsMustMatchTheOriginalLeaseAndCredential() thro } try (Fixture unscoped = - fixture( - claims -> { - claims.remove("tenantId"); - claims.put("authorityTuple", unscopedTuple()); - claims.put("membershipVersion", Map.of()); - })) { + fixture(claims -> { + claims.remove("tenantId"); + claims.put("authorityTuple", unscopedTuple()); + claims.put("membershipVersion", Map.of()); + })) { assertVerifierDenies(unscoped); } @@ -160,21 +157,19 @@ void accountSignatureAndBoundClaimsMustMatchTheOriginalLeaseAndCredential() thro } try (Fixture expired = - fixture( - claims -> { - claims.put("exp", NOW_SECONDS - 1L); - claims.put("nbf", NOW_SECONDS - 5L); - })) { + fixture(claims -> { + claims.put("exp", NOW_SECONDS - 1L); + claims.put("nbf", NOW_SECONDS - 5L); + })) { assertVerifierDenies(expired); } try (Fixture futureIat = - fixture( - claims -> { - claims.put("iat", NOW_SECONDS + 6L); - claims.put("nbf", NOW_SECONDS + 6L); - claims.put("exp", NOW_SECONDS + 100L); - })) { + fixture(claims -> { + claims.put("iat", NOW_SECONDS + 6L); + claims.put("nbf", NOW_SECONDS + 6L); + claims.put("exp", NOW_SECONDS + 100L); + })) { assertVerifierDenies(futureIat); } @@ -218,21 +213,20 @@ void accountSignatureAndBoundClaimsMustMatchTheOriginalLeaseAndCredential() thro } try (Fixture wrongTuple = - fixture( - claims -> - claims.put( - "authorityTuple", - Map.of( - "issuerAuthGeneration", - "1", - "accountAuthorityGeneration", - "1", - "tenantAuthorityGeneration", - Map.of(TENANT_ID.toString(), "3"), - "membershipAuthorityGeneration", - Map.of(TENANT_ID.toString(), "3"), - "privateRealmGrantVersions", - List.of())))) { + fixture(claims -> + claims.put( + "authorityTuple", + Map.of( + "issuerAuthGeneration", + "1", + "accountAuthorityGeneration", + "1", + "tenantAuthorityGeneration", + Map.of(TENANT_ID.toString(), "3"), + "membershipAuthorityGeneration", + Map.of(TENANT_ID.toString(), "3"), + "privateRealmGrantVersions", + List.of())))) { assertVerifierDenies(wrongTuple); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateTest.java index c17fa46b67..9fb365ab0d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayOriginalNewCandidateTest.java @@ -124,15 +124,13 @@ void rejectsWrongLeaseBindingGenerationAndTargetWhenMatchingTheOriginalDecision( assertThat(candidate.matchesProvisionalSources(preparedEvidence(otherBinding))).isFalse(); assertThat(candidate.matchesProvisionalSources(preparedEvidence(otherGeneration))).isFalse(); - assertThatThrownBy( - () -> - CanonicalGameplayOriginalNewCandidate.fromOriginalSources( - preparedEvidence(original), otherBinding.decision())) + assertThatThrownBy(() -> + CanonicalGameplayOriginalNewCandidate.fromOriginalSources( + preparedEvidence(original), otherBinding.decision())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - CanonicalGameplayOriginalNewCandidate.fromOriginalSources( - preparedEvidence(original), otherGeneration.decision())) + assertThatThrownBy(() -> + CanonicalGameplayOriginalNewCandidate.fromOriginalSources( + preparedEvidence(original), otherGeneration.decision())) .isInstanceOf(IllegalArgumentException.class); } @@ -156,10 +154,9 @@ void refusesResumeAndRequiresRetryableTypedTransitionEvidence() { BigInteger.valueOf(7), BigInteger.valueOf(6), original.target()); - assertThatThrownBy( - () -> - CanonicalGameplayOriginalNewCandidate.fromOriginalSources( - preparedEvidence(original), resumeDecision)) + assertThatThrownBy(() -> + CanonicalGameplayOriginalNewCandidate.fromOriginalSources( + preparedEvidence(original), resumeDecision)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("public-production original NEW"); @@ -497,13 +494,12 @@ private static Map leaseCarrier( carrier.put( "outboxCheckpoints", streams.stream() - .map( - stream -> - Map.of( - "outboxStreamKey", - stream, - "outboxSequence", - stream.contains("tenant/") || stream.contains("membership/") ? "4" : "0")) + .map(stream -> + Map.of( + "outboxStreamKey", + stream, + "outboxSequence", + stream.contains("tenant/") || stream.contains("membership/") ? "4" : "0")) .toList()); carrier.put( "tokenIdentityEvidence", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepositoryTest.java index 7b175ce658..166acd976b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepositoryTest.java @@ -8,31 +8,26 @@ class CanonicalGameplayTenantGameplayTagRepositoryTest { @Test void acceptsOnlyBoundedOpaqueTagsWithoutRedisDelimitersOrHashTags() { - assertThatCode( - () -> - CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag( - "g2147483647-0123456789abcdef0123456789abcdef")) + assertThatCode(() -> + CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag( + "g2147483647-0123456789abcdef0123456789abcdef")) .doesNotThrowAnyException(); - assertThatThrownBy( - () -> - CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag( - "g1-{0123456789abcdef0123456789abcdef")) + assertThatThrownBy(() -> + CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag( + "g1-{0123456789abcdef0123456789abcdef")) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); - assertThatThrownBy( - () -> - CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag( - "g1-0123456789abcdef0123456789abcdef:other")) + assertThatThrownBy(() -> + CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag( + "g1-0123456789abcdef0123456789abcdef:other")) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); - assertThatThrownBy( - () -> - CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag( - "g0-0123456789abcdef0123456789abcdef")) + assertThatThrownBy(() -> + CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag( + "g0-0123456789abcdef0123456789abcdef")) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); - assertThatThrownBy( - () -> - CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag( - "g1-0123456789ABCDEF0123456789abcdef")) + assertThatThrownBy(() -> + CanonicalGameplayTenantGameplayTagRepository.requireCanonicalTag( + "g1-0123456789ABCDEF0123456789abcdef")) .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java index f112d6d3f0..b3968b2025 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryTest.java @@ -215,9 +215,8 @@ private static void assertMalformedProjection( CanonicalInitialAdmissionRepository.CurrentOpenPointer pointer, CanonicalInitialAdmissionOwnerProof proof, Class cause) { - assertThatThrownBy( - () -> - CanonicalInitialAdmissionRepository.snapshotDigestOrReconciliation(pointer, proof)) + assertThatThrownBy(() -> + CanonicalInitialAdmissionRepository.snapshotDigestOrReconciliation(pointer, proof)) .isInstanceOf( CanonicalInitialAdmissionRepository .CanonicalInitialAdmissionReconciliationRequiredException.class) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepositoryTest.java index bed811662f..8ce661f0c9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredActorCoreRetentionRepositoryTest.java @@ -27,10 +27,9 @@ void rejectsInvalidWorkloadNamespaceBeforeStorage() { DSLContext dsl = mock(DSLContext.class); PlatformTransactionManager transactionManager = mock(PlatformTransactionManager.class); - assertThatThrownBy( - () -> - new GameSessionAuthoredActorCoreRetentionRepository( - dsl, transactionManager, "Not a DNS label")) + assertThatThrownBy(() -> + new GameSessionAuthoredActorCoreRetentionRepository( + dsl, transactionManager, "Not a DNS label")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("workload namespace"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigestTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigestTest.java index ca61e68055..3e8f614554 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigestTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionAuthoredWorldIntakeDigestTest.java @@ -65,18 +65,16 @@ void rejectsMissingNilOrMalformedOperationAndDigestInputs() { .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> GameSessionAuthoredWorldIntakeDigest.requestDigest(REQUEST, null)) .isInstanceOf(NullPointerException.class); - assertThatThrownBy( - () -> - GameSessionAuthoredWorldIntakeDigest.receiptDigest( - new UUID(0, 0), source("x").requestDigest(), source("x").evidenceDigest())) + assertThatThrownBy(() -> + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + new UUID(0, 0), source("x").requestDigest(), source("x").evidenceDigest())) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> GameSessionAuthoredWorldIntakeDigest.receiptDigest(OPERATION, null, "sha256:x")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - GameSessionAuthoredWorldIntakeDigest.receiptDigest( - OPERATION, source("x").requestDigest(), "SHA256:" + "a".repeat(64))) + assertThatThrownBy(() -> + GameSessionAuthoredWorldIntakeDigest.receiptDigest( + OPERATION, source("x").requestDigest(), "SHA256:" + "a".repeat(64))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryTest.java index e501ca164b..00c8447902 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalAdmissionPointerRepositoryTest.java @@ -51,45 +51,40 @@ void requestAndReceiptDigestsMatchFixedOrderUtf8GoldenVectors() { @Test void requestRejectsNilIdentityAndNonCanonicalTargetNamespace() { - assertThatThrownBy( - () -> - new CreateCanonicalClosedAdmissionPointerRequest( - NIL_UUID, TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 1L, "actor", "reason")) + assertThatThrownBy(() -> + new CreateCanonicalClosedAdmissionPointerRequest( + NIL_UUID, TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 1L, "actor", "reason")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("non-nil UUID"); - assertThatThrownBy( - () -> - new CreateCanonicalClosedAdmissionPointerRequest( - uuid(1), "Canonical_Closed", uuid(2), uuid(3), uuid(4), 1L, "actor", "reason")) + assertThatThrownBy(() -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), "Canonical_Closed", uuid(2), uuid(3), uuid(4), 1L, "actor", "reason")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical DNS label"); - assertThatThrownBy( - () -> - new CreateCanonicalClosedAdmissionPointerRequest( - uuid(1), TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 0L, "actor", "reason")) + assertThatThrownBy(() -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 0L, "actor", "reason")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("catalogRevision must be positive"); } @Test void requestRejectsMalformedOrUnboundedAuditText() { - assertThatThrownBy( - () -> - new CreateCanonicalClosedAdmissionPointerRequest( - uuid(1), - TARGET_NAMESPACE, - uuid(2), - uuid(3), - uuid(4), - 1L, - "bad" + (char) 0xD800, - "reason")) + assertThatThrownBy(() -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), + TARGET_NAMESPACE, + uuid(2), + uuid(3), + uuid(4), + 1L, + "bad" + (char) 0xD800, + "reason")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("well-formed UTF-8"); - assertThatThrownBy( - () -> - new CreateCanonicalClosedAdmissionPointerRequest( - uuid(1), TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 1L, "actor", " ")) + assertThatThrownBy(() -> + new CreateCanonicalClosedAdmissionPointerRequest( + uuid(1), TARGET_NAMESPACE, uuid(2), uuid(3), uuid(4), 1L, "actor", " ")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("bounded and nonblank"); } @@ -122,23 +117,17 @@ void expectedClosedVersionCheckRequiresTheExactInitialPointerAndCatalogTuple() { updatedAt, catalog); - assertThatCode( - () -> - GameSessionCanonicalAdmissionPointerRepository.requireExpectedVersions( - origin, 1L, 1L)) + assertThatCode(() -> + GameSessionCanonicalAdmissionPointerRepository.requireExpectedVersions(origin, 1L, 1L)) .doesNotThrowAnyException(); - assertThatThrownBy( - () -> - GameSessionCanonicalAdmissionPointerRepository.requireExpectedVersions( - origin, 2L, 1L)) + assertThatThrownBy(() -> + GameSessionCanonicalAdmissionPointerRepository.requireExpectedVersions(origin, 2L, 1L)) .isInstanceOf( GameSessionCanonicalAdmissionPointerRepository .InvalidCanonicalClosedPointerEvidenceException.class) .hasMessageContaining("versions do not match"); - assertThatThrownBy( - () -> - GameSessionCanonicalAdmissionPointerRepository.requireExpectedVersions( - origin, 1L, 2L)) + assertThatThrownBy(() -> + GameSessionCanonicalAdmissionPointerRepository.requireExpectedVersions(origin, 1L, 2L)) .isInstanceOf( GameSessionCanonicalAdmissionPointerRepository .InvalidCanonicalClosedPointerEvidenceException.class) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java index c72dea5c2a..3a6632146a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionCanonicalRealmCatalogRepositoryTest.java @@ -60,21 +60,20 @@ void rejectsMissingPublicStatePrivateLifecycleAndMalformedUtf8Inputs() { assertThatThrownBy(() -> request("realm", "Display", "policy", true, true, "PRIVATE")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("stateScope"); - assertThatThrownBy( - () -> - new CreateCanonicalRealmCatalogRequest( - CREATE_REQUEST_ID, - NAMESPACE, - TENANT_ID, - INTAKE_OPERATION_ID, - "realm", - "Display", - true, - true, - "SHARED", - "policy", - uuid(5), - null)) + assertThatThrownBy(() -> + new CreateCanonicalRealmCatalogRequest( + CREATE_REQUEST_ID, + NAMESPACE, + TENANT_ID, + INTAKE_OPERATION_ID, + "realm", + "Display", + true, + true, + "SHARED", + "policy", + uuid(5), + null)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("private/playtest"); String malformedUtf8 = "bad" + (char) 0xD800; @@ -122,26 +121,25 @@ void requestDigestIsStableAndBindsEachCreationInputAndExactSourceReceipt() { @Test void snapshotRejectsTenantAndWorldSelectorsThatDifferFromPersistedSource() { IntakeReceipt source = sourceReceipt(); - assertThatThrownBy( - () -> - new CanonicalRealmCatalogSnapshot( - NAMESPACE, - TENANT_ID, - "different-tenant", - "authored-world", - uuid(7), - "realm", - "Realm", - true, - true, - "SHARED", - uuid(8), - "policy", - 1, - CREATE_REQUEST_ID, - "sha256:" + "a".repeat(64), - "sha256:" + "b".repeat(64), - source)) + assertThatThrownBy(() -> + new CanonicalRealmCatalogSnapshot( + NAMESPACE, + TENANT_ID, + "different-tenant", + "authored-world", + uuid(7), + "realm", + "Realm", + true, + true, + "SHARED", + uuid(8), + "policy", + 1, + CREATE_REQUEST_ID, + "sha256:" + "a".repeat(64), + "sha256:" + "b".repeat(64), + source)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("do not match"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionPrivateFreshRuntimeAllocationRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionPrivateFreshRuntimeAllocationRepositoryTest.java index af8faf4da0..90beffbcbd 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionPrivateFreshRuntimeAllocationRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionPrivateFreshRuntimeAllocationRepositoryTest.java @@ -26,33 +26,19 @@ void requestHasOnlyExpectedSourceIdentityAndRejectsNilOrInvalidBindings() { new Request(request, preparation, lifecycle, realm, 1, catalog, digest, selection, 1) .requestId()) .isEqualTo(request); - assertThatThrownBy( - () -> - new Request( - new UUID(0, 0), - preparation, - lifecycle, - realm, - 1, - catalog, - digest, - selection, - 1)) + assertThatThrownBy(() -> + new Request( + new UUID(0, 0), preparation, lifecycle, realm, 1, catalog, digest, selection, 1)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new Request( - request, preparation, lifecycle, realm, 0, catalog, digest, selection, 1)) + assertThatThrownBy(() -> + new Request(request, preparation, lifecycle, realm, 0, catalog, digest, selection, 1)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new Request( - request, preparation, lifecycle, realm, 1, catalog, digest, selection, 0)) + assertThatThrownBy(() -> + new Request(request, preparation, lifecycle, realm, 1, catalog, digest, selection, 0)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new Request( - request, preparation, lifecycle, realm, 1, catalog, "unbound", selection, 1)) + assertThatThrownBy(() -> + new Request( + request, preparation, lifecycle, realm, 1, catalog, "unbound", selection, 1)) .isInstanceOf(IllegalArgumentException.class); } @@ -73,10 +59,9 @@ void allocationAndCurrentReadRefuseMissingOwnerTransactionBeforeDatabaseAccess() 1); assertThatThrownBy(() -> owner.allocate(request)) .hasMessageContaining("writable owner transaction"); - assertThatThrownBy( - () -> - owner.readForWorldPreparation( - request.preparationRequestId(), request.playtestLifecycleId())) + assertThatThrownBy(() -> + owner.readForWorldPreparation( + request.preparationRequestId(), request.playtestLifecycleId())) .hasMessageContaining("writable owner read"); verifyNoInteractions(dsl); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionPrivatePreparationProtectionRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionPrivatePreparationProtectionRepositoryTest.java index fb68fd562d..fba1590363 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionPrivatePreparationProtectionRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionPrivatePreparationProtectionRepositoryTest.java @@ -142,13 +142,12 @@ void cancelledCallerNeverStartsATransaction() { .when(() -> PrivateWorldPreparationReadGrpcCodec.stableBytes(source)) .thenReturn(new byte[] {1}); context.cancel(null); - context.run( - () -> - assertThatThrownBy(() -> owner.acquire(UUID.randomUUID(), source)) - .isInstanceOf( - GameSessionPrivatePreparationProtectionRepository.ProtectionContendedException - .class) - .hasMessageContaining("cancelled")); + context.run(() -> + assertThatThrownBy(() -> owner.acquire(UUID.randomUUID(), source)) + .isInstanceOf( + GameSessionPrivatePreparationProtectionRepository.ProtectionContendedException + .class) + .hasMessageContaining("cancelled")); } verifyNoInteractions(dsl, transactions); } @@ -167,18 +166,16 @@ void cancellationDuringSerializationFailurePreventsRetry() { .when(() -> PrivateWorldPreparationReadGrpcCodec.stableBytes(source)) .thenReturn(new byte[] {1}); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - call -> { - context.cancel(null); - throw new IllegalStateException(new java.sql.SQLException("retry", "40001")); - }); - context.run( - () -> - assertThatThrownBy(() -> owner.acquire(UUID.randomUUID(), source)) - .isInstanceOf( - GameSessionPrivatePreparationProtectionRepository.ProtectionContendedException - .class) - .hasMessageContaining("cancelled")); + .thenAnswer(call -> { + context.cancel(null); + throw new IllegalStateException(new java.sql.SQLException("retry", "40001")); + }); + context.run(() -> + assertThatThrownBy(() -> owner.acquire(UUID.randomUUID(), source)) + .isInstanceOf( + GameSessionPrivatePreparationProtectionRepository.ProtectionContendedException + .class) + .hasMessageContaining("cancelled")); } verify(transactions).getTransaction(any()); verify(transactions).rollback(status); @@ -205,22 +202,20 @@ void cancellationDuringSourceReadPreventsInsert() { GameSessionPrivateWorldPreparationSourceReader.class, (mock, construction) -> when(mock.read(any())) - .thenAnswer( - call -> { - context.cancel(null); - return source; - }))) { + .thenAnswer(call -> { + context.cancel(null); + return source; + }))) { codec .when(() -> PrivateWorldPreparationReadGrpcCodec.stableBytes(source)) .thenReturn(new byte[] {1}); var owner = new GameSessionPrivatePreparationProtectionRepository(dsl, transactions); - context.run( - () -> - assertThatThrownBy(() -> owner.acquire(UUID.randomUUID(), source)) - .isInstanceOf( - GameSessionPrivatePreparationProtectionRepository.ProtectionContendedException - .class) - .hasMessageContaining("cancelled")); + context.run(() -> + assertThatThrownBy(() -> owner.acquire(UUID.randomUUID(), source)) + .isInstanceOf( + GameSessionPrivatePreparationProtectionRepository.ProtectionContendedException + .class) + .hasMessageContaining("cancelled")); verify(reader.constructed().getFirst()).read(any()); } verify(transactions).getTransaction(any()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogRepositoryTest.java index 371c80c1b0..741bb1fa97 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogRepositoryTest.java @@ -56,14 +56,12 @@ void invalidConfiguredSchemaOrNamespaceCannotReachSql() { DSLContext dsl = mock(DSLContext.class); var transactions = mock(PlatformTransactionManager.class); for (String schema : new String[] {"", "public;select", "MixedCase", "a".repeat(64)}) { - assertThatThrownBy( - () -> - new GameSessionRuntimeFamilyCatalogRepository(dsl, transactions, schema, "test")) + assertThatThrownBy(() -> + new GameSessionRuntimeFamilyCatalogRepository(dsl, transactions, schema, "test")) .isInstanceOf(IllegalArgumentException.class); } - assertThatThrownBy( - () -> - new GameSessionRuntimeFamilyCatalogRepository(dsl, transactions, "gs_owner", "BAD")) + assertThatThrownBy(() -> + new GameSessionRuntimeFamilyCatalogRepository(dsl, transactions, "gs_owner", "BAD")) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(dsl, transactions); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryTest.java index 5472a38e2a..03e069409f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionLaunchDescriptorRepositoryTest.java @@ -54,10 +54,9 @@ void claimPinInsertBindsOriginalAuthorizationExpiryAtDatabaseWriteBoundary() thr Mockito.mockingDetails(dsl).getInvocations().stream() .filter(invocation -> invocation.getMethod().getName().equals("fetchOne")) .filter(invocation -> invocation.getRawArguments()[0] instanceof String sql) - .filter( - invocation -> - ((String) invocation.getRawArguments()[0]) - .contains("INSERT INTO game_session_start_session_launch_descriptor_pin")) + .filter(invocation -> + ((String) invocation.getRawArguments()[0]) + .contains("INSERT INTO game_session_start_session_launch_descriptor_pin")) .findFirst() .orElseThrow(() -> new AssertionError("Missing descriptor claim INSERT")); Object[] rawArguments = insertCall.getRawArguments(); @@ -126,12 +125,10 @@ void continuationPinReadBindsTheLiveOwnerAndExactProjectionWithReferenceExpiry() Mockito.mockingDetails(dsl).getInvocations().stream() .filter(invocation -> invocation.getMethod().getName().equals("fetchOne")) .filter(invocation -> invocation.getRawArguments()[0] instanceof String sql) - .filter( - invocation -> - ((String) invocation.getRawArguments()[0]) - .contains("SELECT descriptor_pin.* FROM ") - && ((String) invocation.getRawArguments()[0]) - .contains("game_session_start_session_launch_descriptor_pin")) + .filter(invocation -> + ((String) invocation.getRawArguments()[0]).contains("SELECT descriptor_pin.* FROM ") + && ((String) invocation.getRawArguments()[0]) + .contains("game_session_start_session_launch_descriptor_pin")) .findFirst() .orElseThrow(() -> new AssertionError("Missing continuation descriptor SELECT")); Object[] rawArguments = selectCall.getRawArguments(); @@ -177,10 +174,9 @@ void postReadContinuationRechecksOriginalReferenceExpiryUsingDatabaseClock() thr Mockito.mockingDetails(dsl).getInvocations().stream() .filter(invocation -> invocation.getMethod().getName().equals("fetchOne")) .filter(invocation -> invocation.getRawArguments()[0] instanceof String sql) - .filter( - invocation -> - ((String) invocation.getRawArguments()[0]) - .equals("SELECT ?::timestamptz > clock_timestamp() AS unexpired")) + .filter(invocation -> + ((String) invocation.getRawArguments()[0]) + .equals("SELECT ?::timestamptz > clock_timestamp() AS unexpired")) .findFirst() .orElseThrow(() -> new AssertionError("Missing post-read authorization expiry check")); Object[] rawArguments = checkCall.getRawArguments(); @@ -196,10 +192,9 @@ void requiresTheExactOwnerClaimBeforeReading() { mock(GameSessionStartSessionTemplateAssociationRepository.class); var repository = new GameSessionStartSessionLaunchDescriptorRepository(dsl, associations); - assertThatThrownBy( - () -> - repository.findPinned( - (GameSessionStartSessionOperatorAttemptRepository.AttemptClaim) null)) + assertThatThrownBy(() -> + repository.findPinned( + (GameSessionStartSessionOperatorAttemptRepository.AttemptClaim) null)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("claim"); @@ -222,10 +217,9 @@ void requiresTypedDescriptorEvidenceBeforeOwnerReads() { java.util.UUID.fromString("04444444-4444-4444-8444-444444444444"), 7L); - assertThatThrownBy( - () -> - repository.pin( - (GameSessionStartSessionOperatorAttemptRepository.AttemptClaim) null, null)) + assertThatThrownBy(() -> + repository.pin( + (GameSessionStartSessionOperatorAttemptRepository.AttemptClaim) null, null)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("claim"); assertThatThrownBy(() -> repository.pin(claim, null)) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryTest.java index 7036635b98..f2d8874874 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryTest.java @@ -60,15 +60,13 @@ void currentOriginalAttemptReadRequiresTheCallerOwnedReadCommittedTransaction() void requiresAnExplicitlyBoundedClaimLease() { DSLContext dsl = mock(DSLContext.class); - assertThatThrownBy( - () -> - new GameSessionStartSessionOperatorAttemptRepository(dsl, java.time.Duration.ZERO)) + assertThatThrownBy(() -> + new GameSessionStartSessionOperatorAttemptRepository(dsl, java.time.Duration.ZERO)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("positive and at most five minutes"); - assertThatThrownBy( - () -> - new GameSessionStartSessionOperatorAttemptRepository( - dsl, java.time.Duration.ofMinutes(6))) + assertThatThrownBy(() -> + new GameSessionStartSessionOperatorAttemptRepository( + dsl, java.time.Duration.ofMinutes(6))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("positive and at most five minutes"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryTest.java index e22d088b8d..9222cb11b5 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionTemplateAssociationRepositoryTest.java @@ -27,10 +27,9 @@ void requiresTheExactOwnerClaimBeforeReading() { mock(GameSessionStartSessionOperatorAttemptRepository.class); var repository = new GameSessionStartSessionTemplateAssociationRepository(dsl, attempts); - assertThatThrownBy( - () -> - repository.findPinned( - (GameSessionStartSessionOperatorAttemptRepository.AttemptClaim) null)) + assertThatThrownBy(() -> + repository.findPinned( + (GameSessionStartSessionOperatorAttemptRepository.AttemptClaim) null)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("claim"); @@ -64,17 +63,16 @@ void requiresTypedAssociationEvidenceBeforeOwnerReads() { assertThatThrownBy(() -> repository.pinInitialOrValidateExactReplay(null, null)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("claim"); - assertThatThrownBy( - () -> - repository.pinInitialOrValidateExactReplay( - new GameSessionStartSessionOperatorAttemptRepository.AttemptClaim( - "world-runtime", - "operator-request", - java.util.UUID.fromString("02222222-2222-4222-8222-222222222222"), - java.util.UUID.fromString("03333333-3333-4333-8333-333333333333"), - java.util.UUID.fromString("04444444-4444-4444-8444-444444444444"), - 7L), - null)) + assertThatThrownBy(() -> + repository.pinInitialOrValidateExactReplay( + new GameSessionStartSessionOperatorAttemptRepository.AttemptClaim( + "world-runtime", + "operator-request", + java.util.UUID.fromString("02222222-2222-4222-8222-222222222222"), + java.util.UUID.fromString("03333333-3333-4333-8333-333333333333"), + java.util.UUID.fromString("04444444-4444-4444-8444-444444444444"), + 7L), + null)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("candidate"); @@ -169,11 +167,9 @@ void initialAssociationInsertSelectBindsTheOriginalAuthorizationExpiry() throws Mockito.mockingDetails(dsl).getInvocations().stream() .filter(invocation -> invocation.getMethod().getName().equals("fetchOne")) .filter(invocation -> invocation.getRawArguments()[0] instanceof String sql) - .filter( - invocation -> - ((String) invocation.getRawArguments()[0]) - .contains( - "INSERT INTO game_session_start_session_template_association_pin")) + .filter(invocation -> + ((String) invocation.getRawArguments()[0]) + .contains("INSERT INTO game_session_start_session_template_association_pin")) .findFirst() .orElseThrow(() -> new AssertionError("Missing initial association INSERT SELECT")); Object[] rawArguments = insertCall.getRawArguments(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java index b40717c618..281887c59b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java @@ -166,56 +166,53 @@ void springJooqTranslationClassifiesOnlyUniqueConstraintViolationsAsPointerConfl new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(JooqAutoConfiguration.class)) .withBean(DriverManagerDataSource.class, () -> dataSource) - .run( - context -> { - DSLContext dsl = context.getBean(DSLContext.class); - createSchema(dsl); - GameplayAdmissionPointerRepository repository = - new GameplayAdmissionPointerRepository(dsl); - repository.save(pointer(7L, 44L, "SHARED", "production")); - - AdmissionPointerConflictException saveConflict = - assertThrows( - AdmissionPointerConflictException.class, - () -> repository.save(pointer(7L, 45L, "SHARED", "production"))); - DataIntegrityViolationException translatedSaveFailure = - assertInstanceOf(DataIntegrityViolationException.class, saveConflict.getCause()); - assertEquals("23505", sqlState(translatedSaveFailure)); - assertNotNull(translatedSaveFailure.getCause()); - - GameplayAdmissionPointer seasonal = - repository.save(pointer(7L, 45L, "SHARED", "seasonal")); - seasonal.setRealmSlug("production"); - seasonal.setCatalogRevision(2L); - AdmissionPointerConflictException updateConflict = - assertThrows( - AdmissionPointerConflictException.class, - () -> repository.updateExisting(seasonal, 1L, 1L)); - DataIntegrityViolationException translatedUpdateFailure = - assertInstanceOf( - DataIntegrityViolationException.class, updateConflict.getCause()); - assertEquals("23505", sqlState(translatedUpdateFailure)); - assertNotNull(translatedUpdateFailure.getCause()); - assertEquals( - "seasonal", - repository - .findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "seasonal") - .orElseThrow() - .getRealmSlug()); - - GameplayAdmissionPointer invalid = pointer(8L, 55L, "SHARED", "production"); - invalid.setCatalogRevision(0L); - IllegalStateException checkViolation = - assertThrows(IllegalStateException.class, () -> repository.save(invalid)); - assertFalse(checkViolation instanceof AdmissionPointerConflictException); - DataIntegrityViolationException translatedCheckFailure = - assertInstanceOf( - DataIntegrityViolationException.class, checkViolation.getCause()); - String checkViolationSqlState = sqlState(translatedCheckFailure); - assertNotNull(checkViolationSqlState); - assertNotEquals("23505", checkViolationSqlState); - assertNotNull(translatedCheckFailure.getCause()); - }); + .run(context -> { + DSLContext dsl = context.getBean(DSLContext.class); + createSchema(dsl); + GameplayAdmissionPointerRepository repository = + new GameplayAdmissionPointerRepository(dsl); + repository.save(pointer(7L, 44L, "SHARED", "production")); + + AdmissionPointerConflictException saveConflict = + assertThrows( + AdmissionPointerConflictException.class, + () -> repository.save(pointer(7L, 45L, "SHARED", "production"))); + DataIntegrityViolationException translatedSaveFailure = + assertInstanceOf(DataIntegrityViolationException.class, saveConflict.getCause()); + assertEquals("23505", sqlState(translatedSaveFailure)); + assertNotNull(translatedSaveFailure.getCause()); + + GameplayAdmissionPointer seasonal = + repository.save(pointer(7L, 45L, "SHARED", "seasonal")); + seasonal.setRealmSlug("production"); + seasonal.setCatalogRevision(2L); + AdmissionPointerConflictException updateConflict = + assertThrows( + AdmissionPointerConflictException.class, + () -> repository.updateExisting(seasonal, 1L, 1L)); + DataIntegrityViolationException translatedUpdateFailure = + assertInstanceOf(DataIntegrityViolationException.class, updateConflict.getCause()); + assertEquals("23505", sqlState(translatedUpdateFailure)); + assertNotNull(translatedUpdateFailure.getCause()); + assertEquals( + "seasonal", + repository + .findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "seasonal") + .orElseThrow() + .getRealmSlug()); + + GameplayAdmissionPointer invalid = pointer(8L, 55L, "SHARED", "production"); + invalid.setCatalogRevision(0L); + IllegalStateException checkViolation = + assertThrows(IllegalStateException.class, () -> repository.save(invalid)); + assertFalse(checkViolation instanceof AdmissionPointerConflictException); + DataIntegrityViolationException translatedCheckFailure = + assertInstanceOf(DataIntegrityViolationException.class, checkViolation.getCause()); + String checkViolationSqlState = sqlState(translatedCheckFailure); + assertNotNull(checkViolationSqlState); + assertNotEquals("23505", checkViolationSqlState); + assertNotNull(translatedCheckFailure.getCause()); + }); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryTest.java index 9168b6e0a6..a6ab05ad9c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryTest.java @@ -119,18 +119,17 @@ void frozenAbsenceSurvivesLateVerifiedWitnessAndExactRetry() { ByteString.EMPTY, ByteString.EMPTY)); when(fixture.dsl.execute(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - String sql = invocation.getArgument(0); - assertThat(sql) - .contains("SET verified_token_jti") - .doesNotContain("retirement_request_bytes"); - fixture.columns.put("verified_token_jti", uuid(4)); - fixture.columns.put("verified_token_sha256", "a".repeat(64)); - fixture.columns.put("verified_token_generation", 1L); - fixture.columns.put("verified_issuance_fence", 19L); - return 1; - }); + .thenAnswer(invocation -> { + String sql = invocation.getArgument(0); + assertThat(sql) + .contains("SET verified_token_jti") + .doesNotContain("retirement_request_bytes"); + fixture.columns.put("verified_token_jti", uuid(4)); + fixture.columns.put("verified_token_sha256", "a".repeat(64)); + fixture.columns.put("verified_token_generation", 1L); + fixture.columns.put("verified_issuance_fence", 19L); + return 1; + }); writableTransaction(); var late = fixture.journal.recordVerifiedResult(ORIGINAL, result); assertThat(late.verifiedWitness()).isPresent(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwnerTest.java index fba42d6c7f..1a02b6b41b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceOwnerTest.java @@ -106,33 +106,29 @@ class CanonicalGameplayRosterReferenceOwnerTest { void controlledSource() { when(repository.find(request)).thenReturn(Optional.empty()); when(repository.begin(request)) - .thenAnswer( - ignored -> { - inside(); - return reserved; - }); + .thenAnswer(ignored -> { + inside(); + return reserved; + }); when(source.target()).thenReturn(target); when(source.sourceIdentity()).thenReturn(identity); when(source.route()).thenReturn(route); when(created.resolvePlayerCreatedRosterSource(any())) - .thenAnswer( - ignored -> { - outside(); - return source; - }); + .thenAnswer(ignored -> { + outside(); + return source; + }); when(admissions.readCurrentOpenSnapshotForRealm( "test", route.canonicalTenantId(), route.realmId())) - .thenAnswer( - ignored -> { - outside(); - return snapshot; - }); + .thenAnswer(ignored -> { + outside(); + return snapshot; + }); when(admissions.lockExactCurrentOpenSnapshot(snapshot)) - .thenAnswer( - ignored -> { - inside(); - return snapshot; - }); + .thenAnswer(ignored -> { + inside(); + return snapshot; + }); } @Test @@ -185,11 +181,10 @@ void preseededRequestsContinueThroughTheExistingPublishedSourceReader() { any( net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence.Request .class))) - .thenAnswer( - ignored -> { - outside(); - throw stale; - }); + .thenAnswer(ignored -> { + outside(); + throw stale; + }); assertThatThrownBy(() -> owner.begin(preseeded)).isSameAs(stale); verifyNoInteractions(created, admissions); verify(repository, never()).begin(any()); @@ -354,11 +349,10 @@ void createdReceiptWritesForwardDistinctCompleteValuesWithinShortTransactions() .setCreationOperationUuid(UUID.randomUUID().toString()) .build(); when(repository.recordPlayerCreated(request, roster)) - .thenAnswer( - ignored -> { - inside(); - return reserved; - }); + .thenAnswer(ignored -> { + inside(); + return reserved; + }); doAnswer( ignored -> { inside(); @@ -384,18 +378,15 @@ void ambientTransactionsRefuseBeforeSourceOrStorage() { try { TransactionSynchronizationManager.setActualTransactionActive(true); assertThatThrownBy(() -> owner.begin(request)).isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - owner.recordPlayerCreated( - request, CanonicalPlayerCreatedRosterResponse.getDefaultInstance())) + assertThatThrownBy(() -> + owner.recordPlayerCreated( + request, CanonicalPlayerCreatedRosterResponse.getDefaultInstance())) .isInstanceOf(IllegalStateException.class); TransactionSynchronizationManager.setActualTransactionActive(false); TransactionSynchronizationManager.initSynchronization(); - assertThatThrownBy( - () -> - owner.recordSelectedPlayerCreatedCharacter( - request, - CanonicalSelectedPlayerCreatedCharacterResponse.getDefaultInstance())) + assertThatThrownBy(() -> + owner.recordSelectedPlayerCreatedCharacter( + request, CanonicalSelectedPlayerCreatedCharacterResponse.getDefaultInstance())) .isInstanceOf(IllegalStateException.class); verifyNoInteractions(repository, created, published, admissions); } finally { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceRetentionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceRetentionServiceTest.java index 2b1d1a3420..7e3081505d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceRetentionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterReferenceRetentionServiceTest.java @@ -85,17 +85,15 @@ void boundedConfirmedReceiptCleanupAndHealthContinueAfterTargetFailure() { when(repository.purgeRetiredTarget(any())) .thenThrow(new IllegalStateException("Entity observation outstanding")); when(repository.purgeConfirmedRetirementAcknowledgements(2)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return 1; - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return 1; + }); when(repository.transferHealth()) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return new CanonicalGameplayRosterReferenceRepository.TransferHealth(19, 7); - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return new CanonicalGameplayRosterReferenceRepository.TransferHealth(19, 7); + }); when(repository.health()).thenReturn(new Health(0, 0)); service.sweep(); verify(repository).purgeConfirmedRetirementAcknowledgements(2); @@ -182,17 +180,15 @@ void unavailableTransferHealthReportsUnknownInsteadOfAHealthyZero() { void blockingHealthFailureInvalidatesHealthyGaugesAndLaterObservationRecoversThem() { when(repository.targetCandidates(null, 2)).thenReturn(List.of()); when(repository.health()) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return new Health(0, 0); - }) + .thenAnswer(ignored -> { + assertSqlTransaction(); + return new Health(0, 0); + }) .thenThrow(new IllegalStateException("blocking health unavailable")) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return new Health(13, 9); - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return new Health(13, 9); + }); var oldest = metrics.get("firemud.canonical.roster.reference.oldest_blocking_seconds").gauge(); var lag = metrics.get("firemud.canonical.roster.reference.cleanup_lag_seconds").gauge(); @@ -231,46 +227,40 @@ void candidateReadFailureRetriesTheSameCursorAndContinuesCleanupAndBothHealthSta var last = candidate(2, "ACTIVE"); var retired = candidate(3, "RETIRED"); when(repository.targetCandidates(null, 2)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return List.of(first, last); - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return List.of(first, last); + }); when(repository.targetCandidates(last.operationUuid(), 2)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - throw new IllegalStateException("candidate storage unavailable"); - }) + .thenAnswer(ignored -> { + assertSqlTransaction(); + throw new IllegalStateException("candidate storage unavailable"); + }) .thenThrow(new IllegalStateException("candidate storage still unavailable")) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return List.of(retired); - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return List.of(retired); + }); when(repository.purgeRetiredTarget(retired)).thenReturn(true); when(repository.purgeConfirmedRetirementAcknowledgements(2)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return 1; - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return 1; + }); when(repository.transferHealth()) .thenReturn(new CanonicalGameplayRosterReferenceRepository.TransferHealth(0, 0)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return new CanonicalGameplayRosterReferenceRepository.TransferHealth(19, 7); - }) + .thenAnswer(ignored -> { + assertSqlTransaction(); + return new CanonicalGameplayRosterReferenceRepository.TransferHealth(19, 7); + }) .thenThrow(new IllegalStateException("transfer health unavailable")) .thenReturn(new CanonicalGameplayRosterReferenceRepository.TransferHealth(23, 11)); when(repository.health()) .thenReturn(new Health(0, 0)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return new Health(13, 9); - }) + .thenAnswer(ignored -> { + assertSqlTransaction(); + return new Health(13, 9); + }) .thenThrow(new IllegalStateException("blocking health unavailable")) .thenReturn(new Health(17, 12)); var blocking = @@ -340,58 +330,49 @@ void boundedPagesPassProtectedAndUnavailableTargetsAndResetOnlyAfterAnEmptyPage( var eligible = candidate(3, "ACTIVE"); var retired = candidate(4, "RETIRED"); when(repository.targetCandidates(null, 2)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return List.of(protectedTarget, unavailable); - }) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return List.of(); - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return List.of(protectedTarget, unavailable); + }) + .thenAnswer(ignored -> { + assertSqlTransaction(); + return List.of(); + }); when(repository.targetCandidates(unavailable.operationUuid(), 2)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return List.of(eligible, retired); - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return List.of(eligible, retired); + }); when(repository.targetCandidates(retired.operationUuid(), 2)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return List.of(); - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return List.of(); + }); when(owner.retireTarget(protectedTarget.original())) - .thenAnswer( - ignored -> { - assertOutsideTransaction(); - return false; - }); + .thenAnswer(ignored -> { + assertOutsideTransaction(); + return false; + }); when(owner.retireTarget(unavailable.original())) - .thenAnswer( - ignored -> { - assertOutsideTransaction(); - throw new IllegalStateException("Owner unavailable"); - }); + .thenAnswer(ignored -> { + assertOutsideTransaction(); + throw new IllegalStateException("Owner unavailable"); + }); when(owner.retireTarget(eligible.original())) - .thenAnswer( - ignored -> { - assertOutsideTransaction(); - return true; - }); + .thenAnswer(ignored -> { + assertOutsideTransaction(); + return true; + }); when(repository.purgeRetiredTarget(retired)) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return true; - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return true; + }); when(repository.health()) - .thenAnswer( - ignored -> { - assertSqlTransaction(); - return new Health(91, 17); - }); + .thenAnswer(ignored -> { + assertSqlTransaction(); + return new Health(91, 17); + }); service.sweep(); verify(repository, never()).purgeRetiredTarget(any()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java index 937e42612b..9f7ad02e89 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java @@ -217,12 +217,11 @@ void deniesTenantNamespaceRealmAndInstanceContextMismatchesBeforeEntityRead() th @Test void rejectsAnEntitySnapshotWithAnotherAccountOrTargetBeforeSelectedRead() throws Exception { var accountMismatch = harness(oneActor()); - doAnswer( - invocation -> - rosterResponse( - invocation.getArgument(0), - uuid("12121212-1212-4212-8212-121212121212"), - oneActor())) + doAnswer(invocation -> + rosterResponse( + invocation.getArgument(0), + uuid("12121212-1212-4212-8212-121212121212"), + oneActor())) .when(accountMismatch.stub()) .listPreseededRoster(any()); @@ -1036,12 +1035,11 @@ void createdTransientAndUntrustedPeerFailuresNeverPrematurelyFinalize() throws E var calls = new AtomicInteger(); int failedPhase = phase; when(h.sources().resolvePlayerCreatedRosterSource(any())) - .thenAnswer( - call -> { - assertNoAmbientSql(); - if (calls.getAndIncrement() == failedPhase) throw failure; - return h.source(); - }); + .thenAnswer(call -> { + assertNoAmbientSql(); + if (calls.getAndIncrement() == failedPhase) throw failure; + return h.source(); + }); assertDenied( h.service().select(h.context(), null, null), CanonicalGameplayRosterSelectionService.Denial.ROUTE_UNAVAILABLE); @@ -1218,30 +1216,26 @@ private static CreatedHarness createdHarness(int actorCount) throws Exception { var sources = mock(GameSessionCharacterCreatePublicSourceService.class); var client = mock(CanonicalPlayerCreatedRosterClient.class); when(routes.readCurrentTarget(route.canonicalTenantId())) - .thenAnswer( - call -> { - assertNoAmbientSql(); - return route; - }); + .thenAnswer(call -> { + assertNoAmbientSql(); + return route; + }); when(sources.resolvePlayerCreatedRosterSource(any())) - .thenAnswer( - call -> { - assertNoAmbientSql(); - return source; - }); + .thenAnswer(call -> { + assertNoAmbientSql(); + return source; + }); when(client.listPlayerCreatedRoster(source, context)) - .thenAnswer( - call -> { - assertNoAmbientSql(); - return roster; - }); + .thenAnswer(call -> { + assertNoAmbientSql(); + return roster; + }); when(client.readSelectedPlayerCreatedCharacter(org.mockito.ArgumentMatchers.eq(roster), any())) - .thenAnswer( - call -> { - assertNoAmbientSql(); - PlayerExecutionContext selectedContext = call.getArgument(1); - return references.get(UUID.fromString(selectedContext.getCharacterId())); - }); + .thenAnswer(call -> { + assertNoAmbientSql(); + PlayerExecutionContext selectedContext = call.getArgument(1); + return references.get(UUID.fromString(selectedContext.getCharacterId())); + }); return new CreatedHarness( new CanonicalGameplayRosterSelectionService( routes, publications, preseeded, sources, client), @@ -1640,55 +1634,50 @@ private static CanonicalGameplayRosterClient rosterClient( .when(owner) .reserveSelectionInput(any(), any()); when(owner.begin(any())) - .thenAnswer( - call -> - net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence - .response( - call.getArgument(0), - 1L, - java.util.UUID.fromString("12121212-1212-4212-8212-121212121212"), - null)); + .thenAnswer(call -> + net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence.response( + call.getArgument(0), + 1L, + java.util.UUID.fromString("12121212-1212-4212-8212-121212121212"), + null)); when(owner.record(any(), any())) - .thenAnswer( - call -> { - net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest - request = call.getArgument(0); - CanonicalGameplayRosterResponse receipt = call.getArgument(1); - receipts.put(request.getOperationUuid(), receipt); - return net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence - .response( - request, - 1L, - java.util.UUID.fromString("12121212-1212-4212-8212-121212121212"), - receipt); - }); + .thenAnswer(call -> { + net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest request = + call.getArgument(0); + CanonicalGameplayRosterResponse receipt = call.getArgument(1); + receipts.put(request.getOperationUuid(), receipt); + return net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence + .response( + request, + 1L, + java.util.UUID.fromString("12121212-1212-4212-8212-121212121212"), + receipt); + }); when(owner.read(any())) - .thenAnswer( - call -> { - net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest - request = call.getArgument(0); - return net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence - .response( - request, - 1L, - java.util.UUID.fromString("12121212-1212-4212-8212-121212121212"), - receipts.get(request.getOperationUuid())); - }); + .thenAnswer(call -> { + net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest request = + call.getArgument(0); + return net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence + .response( + request, + 1L, + java.util.UUID.fromString("12121212-1212-4212-8212-121212121212"), + receipts.get(request.getOperationUuid())); + }); when(owner.selectOriginal(any(), any())) - .thenAnswer( - call -> { - net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest - request = call.getArgument(0); - UUID selectedCharacter = call.getArgument(1); - var original = owner.read(request); - return net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence - .requireResponse( - request, - original.toBuilder() - .setSelectionInput(selectionInputs.get(request.getOperationUuid())) - .setSelectedCharacterUuid(selectedCharacter.toString()) - .build()); - }); + .thenAnswer(call -> { + net.firedevops.firemud.gamesession.v1.GetCanonicalGameplayRosterReferenceRequest request = + call.getArgument(0); + UUID selectedCharacter = call.getArgument(1); + var original = owner.read(request); + return net.firedevops.firemud.common.world.CanonicalGameplayRosterReferenceEvidence + .requireResponse( + request, + original.toBuilder() + .setSelectionInput(selectionInputs.get(request.getOperationUuid())) + .setSelectedCharacterUuid(selectedCharacter.toString()) + .build()); + }); var ownerBeans = new org.springframework.beans.factory.support.StaticListableBeanFactory(); ownerBeans.addBean("controlledReferenceOwner", owner); var client = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java index 233be28ee5..cce6759f22 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java @@ -203,9 +203,8 @@ void abortedCurrentOwnerProofFailsWithoutReadingLaunchAssociation() { when(catalogRepository.readVisiblePublicProductionSnapshots(NAMESPACE)) .thenReturn(List.of(catalogSnapshot())); when(admissionRepository.readCurrentOpenSnapshotForRealm(NAMESPACE, TENANT, REALM)) - .thenAnswer( - invocation -> - new CanonicalInitialAdmissionRepository.CurrentOpenSnapshot(proof, "d".repeat(64))); + .thenAnswer(invocation -> + new CanonicalInitialAdmissionRepository.CurrentOpenSnapshot(proof, "d".repeat(64))); var service = routeReadService(catalogRepository, admissionRepository, launchRepository); assertThatThrownBy(service::readVisiblePublicProductionTargets) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableScreenBufferServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableScreenBufferServiceTest.java index 88e2b7d87b..86824c95d3 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableScreenBufferServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/DurableScreenBufferServiceTest.java @@ -246,11 +246,10 @@ void appendRetainsSingleEntryWhoseCanonicalStructuredEnvelopeExceedsHardLimit() verify(repository).saveAll(entries.capture()); assertThat(entries.getValue()) .singleElement() - .satisfies( - entry -> { - assertThat(entry.getPayloadJson()).isEqualTo(oversized.payloadJson()); - assertThat(entry.getByteSize()).isGreaterThan(2_000); - }); + .satisfies(entry -> { + assertThat(entry.getPayloadJson()).isEqualTo(oversized.payloadJson()); + assertThat(entry.getByteSize()).isGreaterThan(2_000); + }); verify(repository).updateExpiryByScope(TENANT_ID, GAME_INSTANCE_ID, CHARACTER_ID, null); verify(hotCache, never()).append(anyLong(), anyLong(), anyLong(), any()); verify(hotCache) @@ -258,10 +257,9 @@ void appendRetainsSingleEntryWhoseCanonicalStructuredEnvelopeExceedsHardLimit() eq(TENANT_ID), eq(GAME_INSTANCE_ID), eq(CHARACTER_ID), - org.mockito.ArgumentMatchers.argThat( - cached -> - cached.size() == 1 - && cached.getFirst().payloadJson().equals(oversized.payloadJson()))); + org.mockito.ArgumentMatchers.argThat(cached -> + cached.size() == 1 + && cached.getFirst().payloadJson().equals(oversized.payloadJson()))); } @Test @@ -291,10 +289,9 @@ void appendRefreshesExpiryAndReplacesExistingWindowWithOversizedEntry() { eq(TENANT_ID), eq(GAME_INSTANCE_ID), eq(CHARACTER_ID), - org.mockito.ArgumentMatchers.argThat( - cached -> - cached.size() == 1 - && cached.getFirst().payloadJson().equals(oversized.payloadJson()))); + org.mockito.ArgumentMatchers.argThat(cached -> + cached.size() == 1 + && cached.getFirst().payloadJson().equals(oversized.payloadJson()))); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java index 36cf229553..373aa47075 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java @@ -164,17 +164,12 @@ void successfulParseDoesNotIncrementFailureCounter() { private static void assertOnlyFixedFailureMetricTags(SimpleMeterRegistry registry) { assertThat(registry.getMeters()) - .allSatisfy( - meter -> { - assertThat(meter.getId().getName()) - .isEqualTo("gamesession.first_party_connect_context.parse.failures"); - assertThat(meter.getId().getTags()).hasSize(1); - assertThat(meter.getId().getTag("reason")) - .isIn( - "key_unavailable", - "invalid_envelope", - "owner_unavailable", - "target_mismatch"); - }); + .allSatisfy(meter -> { + assertThat(meter.getId().getName()) + .isEqualTo("gamesession.first_party_connect_context.parse.failures"); + assertThat(meter.getId().getTags()).hasSize(1); + assertThat(meter.getId().getTag("reason")) + .isIn("key_unavailable", "invalid_envelope", "owner_unavailable", "target_mismatch"); + }); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionAccountPublicJwksSourceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionAccountPublicJwksSourceTest.java index 7fa4fb52c4..51f1919eb8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionAccountPublicJwksSourceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionAccountPublicJwksSourceTest.java @@ -308,11 +308,10 @@ void matchedPublicationTransitionPreservesExpiryUntilALaterStableLoad() throws E var cache = fixture.cache(); cache.refresh(); fixture.advance(5); - fixture.afterAccountRead.set( - () -> { - fixture.publishNext(); - fixture.converge(); - }); + fixture.afterAccountRead.set(() -> { + fixture.publishNext(); + fixture.converge(); + }); if (proactive) { cache.refresh(); } else { @@ -335,11 +334,10 @@ void matchedTransitionDoesNotRenewExpiredCacheOrInstallAnUnknownKey() throws Exc var cache = fixture.cache(); cache.refresh(); fixture.advance(10); - fixture.afterAccountRead.set( - () -> { - fixture.publishNext(); - fixture.converge(); - }); + fixture.afterAccountRead.set(() -> { + fixture.publishNext(); + fixture.converge(); + }); assertThatThrownBy(() -> cache.keyFor("next")).isInstanceOf(SourceUnavailableException.class); cache.refresh(); assertThat(cache.keyFor("next")).isEqualTo(fixture.key); @@ -350,12 +348,11 @@ void matchedTransitionCannotQualifyStartupOrAReplacementIdentity() throws Except for (boolean qualified : new boolean[] {false, true}) { var fixture = new PublicationFixture(); if (qualified) fixture.source.load(); - fixture.afterAccountRead.set( - () -> { - fixture.publishNext(); - fixture.converge(); - if (qualified) fixture.pin.set(identity("test", "revision-2")); - }); + fixture.afterAccountRead.set(() -> { + fixture.publishNext(); + fixture.converge(); + if (qualified) fixture.pin.set(identity("test", "revision-2")); + }); assertInvalid(fixture.source); fixture.pin.set(identity("test", "revision-1")); assertInvalid(fixture.source); @@ -367,12 +364,11 @@ void transitionRequiresAnExactValidAuthenticatedNewSnapshot() throws Exception { for (boolean matched : new boolean[] {false, true}) { var fixture = new PublicationFixture(); fixture.source.load(); - fixture.afterAccountRead.set( - () -> { - fixture.current.set("{broken".getBytes(StandardCharsets.US_ASCII)); - fixture.mounted.set( - matched ? fixture.current.get() : publicJwks(fixture.key, "unexplained")); - }); + fixture.afterAccountRead.set(() -> { + fixture.current.set("{broken".getBytes(StandardCharsets.US_ASCII)); + fixture.mounted.set( + matched ? fixture.current.get() : publicJwks(fixture.key, "unexplained")); + }); assertInvalid(fixture.source); fixture.publishNext(); fixture.converge(); @@ -387,19 +383,17 @@ void matchedTransitionCannotHideUnsafeOrChangedProjectionOnRecheck() throws Exce fixture.source.load(); AtomicInteger projectionReads = new AtomicInteger(); when(fixture.projection.read()) - .thenAnswer( - invocation -> { - if (projectionReads.incrementAndGet() == 3) { - if (unsafe) throw new IllegalArgumentException("unsafe projection"); - return publicJwks(fixture.key, "unexplained"); - } - return fixture.mounted.get().clone(); - }); - fixture.afterAccountRead.set( - () -> { - fixture.publishNext(); - fixture.converge(); + .thenAnswer(invocation -> { + if (projectionReads.incrementAndGet() == 3) { + if (unsafe) throw new IllegalArgumentException("unsafe projection"); + return publicJwks(fixture.key, "unexplained"); + } + return fixture.mounted.get().clone(); }); + fixture.afterAccountRead.set(() -> { + fixture.publishNext(); + fixture.converge(); + }); assertInvalid(fixture.source); assertInvalid(fixture.source); } @@ -523,28 +517,25 @@ void cachedKeyDenialDoesNotWaitForBlockedSamePinRecoveryLoad() throws Exception fixture.recoveryEligible.set(true); var entered = new CountDownLatch(1); var release = new CountDownLatch(1); - fixture.beforeAccountRead.set( - () -> { - entered.countDown(); - try { - if (!release.await(3, TimeUnit.SECONDS)) - throw new IllegalStateException("test timeout"); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(interrupted); - } - }); + fixture.beforeAccountRead.set(() -> { + entered.countDown(); + try { + if (!release.await(3, TimeUnit.SECONDS)) throw new IllegalStateException("test timeout"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + }); try (var executor = Executors.newFixedThreadPool(2)) { var recovering = executor.submit(fixture.source::load); try { assertThat(entered.await(3, TimeUnit.SECONDS)).isTrue(); var denied = - executor.submit( - () -> { - assertThat(fixture.source.isPreparedDenied()).isTrue(); - assertThatThrownBy(() -> cache.keyFor("known")) - .isInstanceOf(SourcePreparedDenyException.class); - }); + executor.submit(() -> { + assertThat(fixture.source.isPreparedDenied()).isTrue(); + assertThatThrownBy(() -> cache.keyFor("known")) + .isInstanceOf(SourcePreparedDenyException.class); + }); denied.get(1, TimeUnit.SECONDS); cache.invalidateKid("known"); } finally { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java index 929a477e76..d36003a88d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceTest.java @@ -336,11 +336,10 @@ void authorizedExactRetryValidatesCurrentClaimBeforeReturningWithoutResolvingAga AttemptClaim claim = attemptClaim(request); AttemptSnapshot attempt = attemptSnapshot(tuple, accountProjection(tuple)); when(attemptRepository.validateCurrentClaim(claim)) - .thenAnswer( - ignored -> { - assertOwnerTransaction(); - return attempt; - }); + .thenAnswer(ignored -> { + assertOwnerTransaction(); + return attempt; + }); when(preparationRepository.readByControlPlaneRequestId(NAMESPACE, CONTROL_PLANE_REQUEST)) .thenReturn(Optional.of(original)); @@ -396,28 +395,24 @@ void rejectsAuthorizedActorTenantTemplateAndDescriptorOverrideSubstitutionBefore when(attemptRepository.validateCurrentClaim(claim)).thenReturn(authorizedAttempt); GameSessionCanonicalLaunchPreparationService authorizedService = authorizedService(); - assertThatThrownBy( - () -> - authorizedService.prepareAuthorized( - claim, requestVariant(request, uuid(98), TENANT, 71L, false, null))) + assertThatThrownBy(() -> + authorizedService.prepareAuthorized( + claim, requestVariant(request, uuid(98), TENANT, 71L, false, null))) .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) .hasMessageContaining("actor, tenant, or template"); - assertThatThrownBy( - () -> - authorizedService.prepareAuthorized( - claim, requestVariant(request, ACTOR, uuid(97), 71L, false, null))) + assertThatThrownBy(() -> + authorizedService.prepareAuthorized( + claim, requestVariant(request, ACTOR, uuid(97), 71L, false, null))) .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) .hasMessageContaining("actor, tenant, or template"); - assertThatThrownBy( - () -> - authorizedService.prepareAuthorized( - claim, requestVariant(request, ACTOR, TENANT, 72L, false, null))) + assertThatThrownBy(() -> + authorizedService.prepareAuthorized( + claim, requestVariant(request, ACTOR, TENANT, 72L, false, null))) .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) .hasMessageContaining("actor, tenant, or template"); - assertThatThrownBy( - () -> - authorizedService.prepareAuthorized( - claim, requestVariant(request, ACTOR, TENANT, 71L, true, 72L))) + assertThatThrownBy(() -> + authorizedService.prepareAuthorized( + claim, requestVariant(request, ACTOR, TENANT, 71L, true, 72L))) .isInstanceOf(LaunchPreparationConflictException.class) .hasMessageContaining("does not authorize launch descriptor overrides"); @@ -466,11 +461,10 @@ void authorizedPreparationChecksProjectionBeforeNetworkAndRevalidatesClaimAtComm CanonicalLaunchPreparationSnapshot prepared = snapshot(request, catalog, intake, descriptor); AttemptSnapshot exactAttempt = attemptSnapshot(tuple, accountProjection(tuple)); when(attemptRepository.validateCurrentClaim(claim)) - .thenAnswer( - ignored -> { - assertOwnerTransaction(); - return exactAttempt; - }); + .thenAnswer(ignored -> { + assertOwnerTransaction(); + return exactAttempt; + }); stubNewPreparation(request, source, intake, catalog, descriptor, prepared, true); assertThat(authorizedService().prepareAuthorized(claim, request)).isEqualTo(prepared); @@ -687,17 +681,15 @@ void descriptorAndIndependentReadbackMustBothMatchCompleteSharedEvidence() { when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) .thenReturn(Optional.of(intake)); when(descriptorClient.resolve(resolved.request())) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return resolved; - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return resolved; + }); when(descriptorClient.get(any(GetRequest.class))) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return changedReadback; - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return changedReadback; + }); assertThatThrownBy(() -> service.prepare(request)) .isInstanceOf(InvalidLaunchPreparationEvidenceException.class) @@ -1024,35 +1016,31 @@ private void stubNewPreparation( when(sourceRepository.read(SOURCE_INTAKE_OPERATION, TENANT, catalog.worldSlug(), NAMESPACE)) .thenReturn(Optional.of(intake)); when(descriptorClient.resolve(descriptor.request())) - .thenAnswer( - ignored -> { - if (verifyAuthorizedClaimRevalidation) { - verify(attemptRepository, times(1)).validateCurrentClaim(attemptClaim(request)); - } - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return descriptor; - }); + .thenAnswer(ignored -> { + if (verifyAuthorizedClaimRevalidation) { + verify(attemptRepository, times(1)).validateCurrentClaim(attemptClaim(request)); + } + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return descriptor; + }); when(descriptorClient.get(any(GetRequest.class))) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return descriptor; - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return descriptor; + }); when(preparationRepository.persistPrepared(request, catalog, intake, descriptor)) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) - .isFalse(); - assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); - assertThat(descriptor.authoredWorldSourceOperationId()) - .isEqualTo(sourceEvidence.operationId()); - if (verifyAuthorizedClaimRevalidation) { - verify(attemptRepository, times(2)).validateCurrentClaim(attemptClaim(request)); - } - return snapshot; - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(descriptor.authoredWorldSourceOperationId()) + .isEqualTo(sourceEvidence.operationId()); + if (verifyAuthorizedClaimRevalidation) { + verify(attemptRepository, times(2)).validateCurrentClaim(attemptClaim(request)); + } + return snapshot; + }); } private void resetRepositories() { @@ -1207,19 +1195,17 @@ private static CompleteLaunchBindingEvidence completeBinding( String publishCommitId = "publish-commit-902"; List participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - owner, - Long.toString(descriptor.versionId()), - false, - null, - publishCommitId, - "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), - "GAME_LOGIC".equals(owner), - "GAME_LOGIC".equals(owner) ? digest("d") : null)) + .map(owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + publishCommitId, + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema(owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? digest("d") : null)) .toList(); AuthoredWorldReleaseAttestationEvidence releaseAttestation = AuthoredWorldReleaseAttestationEvidence.create( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedLocalIdentityProviderTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedLocalIdentityProviderTest.java index b64d2cb9bb..2c81add681 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedLocalIdentityProviderTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessProtectedLocalIdentityProviderTest.java @@ -48,11 +48,10 @@ void returnsAccountSelectedCurrentMetadataBracketingTheAuthenticatedReadWithLoca Fixture fixture = new Fixture(); AtomicInteger uidReads = new AtomicInteger(); var provider = - fixture.provider( - () -> { - uidReads.incrementAndGet(); - return POD_UID; - }); + fixture.provider(() -> { + uidReads.incrementAndGet(); + return POD_UID; + }); var observation = provider.observe(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverProtoMapperTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverProtoMapperTest.java index 8ab13245b7..5f6b667ea3 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverProtoMapperTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionJwtReadinessReceiverProtoMapperTest.java @@ -29,15 +29,14 @@ void acceptsOnlyTheCanaryAndProductionProfilesWithTypedExpectedOutcomes() { PlayerBootstrapJwtProfileValidator.PROFILE, ReadinessProbeCoordinates.ExpectedOutcome.INAPPLICABLE_REJECT); - outcomes.forEach( - (profile, expectedOutcome) -> { - var parsed = mapper.parse(request(profile, expectedOutcome).build()); - assertThat(parsed.coordinates().getExpectedOutcome()).isEqualTo(expectedOutcome); - assertThat(parsed.expectedOutcome()).isEqualTo(expectedOutcome); - // Independent SHA-256 vector for the literal ASCII compact token below. - assertThat(parsed.compactTokenSha256()) - .isEqualTo("256d04db4e5e4ac308751ed0885b722b758630567c53a7125ed9fbd068e5c3f6"); - }); + outcomes.forEach((profile, expectedOutcome) -> { + var parsed = mapper.parse(request(profile, expectedOutcome).build()); + assertThat(parsed.coordinates().getExpectedOutcome()).isEqualTo(expectedOutcome); + assertThat(parsed.expectedOutcome()).isEqualTo(expectedOutcome); + // Independent SHA-256 vector for the literal ASCII compact token below. + assertThat(parsed.compactTokenSha256()) + .isEqualTo("256d04db4e5e4ac308751ed0885b722b758630567c53a7125ed9fbd068e5c3f6"); + }); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationServiceTest.java index 1c5e69a9c0..804c612c7f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionLaunchDescriptorContinuationServiceTest.java @@ -228,13 +228,12 @@ void changedOriginalSelectionAfterRemoteReadPreventsDescriptorPin() { StartSessionLaunchDescriptorGrpcCodec.Resolved resolved = mock(StartSessionLaunchDescriptorGrpcCodec.Resolved.class); when(fixture.descriptorReadClient.resolve(any(Request.class))) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - assertThat(fixture.transactionManager.startedTransactions).isEqualTo(1); - return resolved; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(fixture.transactionManager.startedTransactions).isEqualTo(1); + return resolved; + }); ReadStartSessionTemplateAssociationResponse originalWire = response(1L); ReadStartSessionTemplateAssociationResponse changedWire = response(2L); @@ -274,13 +273,12 @@ void exactUnchangedReplayReadsOutsideSqlAndPinsOnlyTheExistingOpaqueContinuation .thenReturn(Optional.of(original), Optional.of(original)); ReadRedeemedOperationProjectionResponse projection = redeemedProjection("original"); when(fixture.accountProjectionClient.read(fixture.tuple, ATTEMPT_ID, 8L)) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - assertThat(fixture.transactionManager.startedTransactions).isEqualTo(1); - return projection; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(fixture.transactionManager.startedTransactions).isEqualTo(1); + return projection; + }); StartSessionLaunchDescriptorGrpcCodec.Resolved resolved = mock(StartSessionLaunchDescriptorGrpcCodec.Resolved.class); PinnedLaunchDescriptorSnapshot pinned = @@ -292,13 +290,12 @@ void exactUnchangedReplayReadsOutsideSqlAndPinsOnlyTheExistingOpaqueContinuation RESPONSE_DIGEST, Instant.parse("2026-10-10T00:00:00Z")); when(fixture.descriptorReadClient.resolve(any(Request.class))) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - assertThat(fixture.transactionManager.startedTransactions).isEqualTo(1); - return resolved; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + assertThat(fixture.transactionManager.startedTransactions).isEqualTo(1); + return resolved; + }); when(fixture.descriptorRepository.pin(fixture.continuation, resolved)).thenReturn(pinned); ReadStartSessionTemplateAssociationResponse originalWire = response(1L); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorTest.java index 89cead5d34..72e3bf0e0e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameSessionStartSessionOperatorAuthorizationCoordinatorTest.java @@ -81,36 +81,32 @@ void commitsOwnerClaimBeforeOneAccountCallAndAttachesOnlyUnderSameCurrentClaim() List order = new ArrayList<>(); when(repository.reserve(tuple)) - .thenAnswer( - invocation -> { - assertWritableReadCommittedTransaction(); - order.add("reserve"); - return new ReservationResult( - ReservationDisposition.CLAIM_CREATED, reserved, Optional.of(claim)); - }); + .thenAnswer(invocation -> { + assertWritableReadCommittedTransaction(); + order.add("reserve"); + return new ReservationResult( + ReservationDisposition.CLAIM_CREATED, reserved, Optional.of(claim)); + }); when(redemptionClient.redeem(tuple, OPAQUE_REFERENCE, claim)) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(transactions.commitCount).isEqualTo(1); - order.add("account"); - return new StartSessionOperatorRedemptionClient.RedemptionResult( - claim, projection, false); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(transactions.commitCount).isEqualTo(1); + order.add("account"); + return new StartSessionOperatorRedemptionClient.RedemptionResult( + claim, projection, false); + }); when(repository.validateCurrentClaim(claim)) - .thenAnswer( - invocation -> { - assertWritableReadCommittedTransaction(); - order.add("validate"); - return reserved; - }); + .thenAnswer(invocation -> { + assertWritableReadCommittedTransaction(); + order.add("validate"); + return reserved; + }); when(repository.attachAccountRedemptionProjection(claim, projection)) - .thenAnswer( - invocation -> { - assertWritableReadCommittedTransaction(); - order.add("attach"); - return attached; - }); + .thenAnswer(invocation -> { + assertWritableReadCommittedTransaction(); + order.add("attach"); + return attached; + }); GameSessionStartSessionOperatorAuthorizationCoordinator.AuthorizationResult result = withPeer(peer(WORKLOAD), () -> coordinator.authorize(tuple, OPAQUE_REFERENCE)); @@ -120,14 +116,13 @@ void commitsOwnerClaimBeforeOneAccountCallAndAttachesOnlyUnderSameCurrentClaim() assertThat(transactions.rollbackCount).isZero(); assertThat(transactions.definitions) .hasSize(2) - .allSatisfy( - definition -> { - assertThat(definition.getPropagationBehavior()) - .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); - assertThat(definition.getIsolationLevel()) - .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); - assertThat(definition.isReadOnly()).isFalse(); - }); + .allSatisfy(definition -> { + assertThat(definition.getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + }); assertThat(result.progress()) .isEqualTo( GameSessionStartSessionOperatorAuthorizationCoordinator.Progress @@ -174,17 +169,15 @@ void rejectsWrongAuthenticatedPeerOrNamespaceBeforeOwnerAccess() throws Exceptio RecordingTransactionManager transactions = new RecordingTransactionManager(); var coordinator = coordinator(repository, redemptionClient, transactions); - assertThatThrownBy( - () -> - withPeer( - peer("spiffe://firemud/ns/world-runtime/sa/account-service"), - () -> coordinator.authorize(tuple, OPAQUE_REFERENCE))) + assertThatThrownBy(() -> + withPeer( + peer("spiffe://firemud/ns/world-runtime/sa/account-service"), + () -> coordinator.authorize(tuple, OPAQUE_REFERENCE))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withPeer( - peer("spiffe://firemud/ns/other-runtime/sa/logging-admin-service"), - () -> coordinator.authorize(tuple, OPAQUE_REFERENCE))) + assertThatThrownBy(() -> + withPeer( + peer("spiffe://firemud/ns/other-runtime/sa/logging-admin-service"), + () -> coordinator.authorize(tuple, OPAQUE_REFERENCE))) .isInstanceOf(SecurityException.class); assertThat(transactions.definitions).isEmpty(); @@ -202,13 +195,12 @@ void tupleConflictRollsBackClaimReservationAndNeverCallsAccount() throws Excepti new GameSessionStartSessionOperatorAttemptRepository .StartSessionOperatorAttemptConflictException("different immutable tuple")); - assertThatThrownBy( - () -> - withPeer( - peer(WORKLOAD), - () -> - coordinator(repository, redemptionClient, transactions) - .authorize(tuple, OPAQUE_REFERENCE))) + assertThatThrownBy(() -> + withPeer( + peer(WORKLOAD), + () -> + coordinator(repository, redemptionClient, transactions) + .authorize(tuple, OPAQUE_REFERENCE))) .isInstanceOf( GameSessionStartSessionOperatorAttemptRepository .StartSessionOperatorAttemptConflictException.class); @@ -251,13 +243,12 @@ void classifiesEveryGrpcStatusWithoutRetryingOrAttachingThePendingClaim() throws assertThat(result.claim()).contains(claim); assertThat(result.toString()).doesNotContain(OPAQUE_REFERENCE); } else { - assertThatThrownBy( - () -> - withPeer( - peer(WORKLOAD), - () -> - coordinator(repository, redemptionClient, transactions) - .authorize(tuple, OPAQUE_REFERENCE))) + assertThatThrownBy(() -> + withPeer( + peer(WORKLOAD), + () -> + coordinator(repository, redemptionClient, transactions) + .authorize(tuple, OPAQUE_REFERENCE))) .as("status %s", code) .isSameAs(failure); } @@ -299,13 +290,12 @@ void staleClaimDuringProjectionAttachmentCannotProduceAttachedProgress() throws new GameSessionStartSessionOperatorAttemptRepository .StaleStartSessionOperatorAttemptClaimException("claim expired before attachment")); - assertThatThrownBy( - () -> - withPeer( - peer(WORKLOAD), - () -> - coordinator(repository, redemptionClient, transactions) - .authorize(tuple, OPAQUE_REFERENCE))) + assertThatThrownBy(() -> + withPeer( + peer(WORKLOAD), + () -> + coordinator(repository, redemptionClient, transactions) + .authorize(tuple, OPAQUE_REFERENCE))) .isInstanceOf( GameSessionStartSessionOperatorAttemptRepository .StaleStartSessionOperatorAttemptClaimException.class); @@ -323,13 +313,12 @@ void refusesToRunInsideAmbientTransactionBeforeOwnerAccess() throws Exception { StartSessionOperatorRedemptionClient redemptionClient = mockRedemptionClient(); TransactionSynchronizationManager.setActualTransactionActive(true); - assertThatThrownBy( - () -> - withPeer( - peer(WORKLOAD), - () -> - coordinator(repository, redemptionClient, new RecordingTransactionManager()) - .authorize(tuple, OPAQUE_REFERENCE))) + assertThatThrownBy(() -> + withPeer( + peer(WORKLOAD), + () -> + coordinator(repository, redemptionClient, new RecordingTransactionManager()) + .authorize(tuple, OPAQUE_REFERENCE))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("ambient owner transaction"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java index 528fe70337..1497fa43d9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java @@ -66,10 +66,9 @@ void requireAdmittedRoutingBundleRejectsPartialRoutingClaimsWithCallerSpecificMe 22L, 41L, null, null, 123L, null, 1L, "R-1021", null, null, 1L, "world", null, 17L, null); - assertThatThrownBy( - () -> - GameplayAdmissionPointerSnapshots.requireAdmittedRoutingBundle( - partialRouting, "Game Logic request")) + assertThatThrownBy(() -> + GameplayAdmissionPointerSnapshots.requireAdmittedRoutingBundle( + partialRouting, "Game Logic request")) .isInstanceOf(IllegalStateException.class) .hasMessage("Incomplete admitted routing bundle on session context for Game Logic request"); } @@ -80,10 +79,9 @@ void requireAdmittedRoutingBundleRejectsMissingRoutingClaimsWithCallerSpecificMe new SessionContext( 22L, 41L, null, null, 123L, null, 1L, "R-1021", null, null, 1L, null, null, 0L, null); - assertThatThrownBy( - () -> - GameplayAdmissionPointerSnapshots.requireAdmittedRoutingBundle( - missingRouting, "Entity Management request")) + assertThatThrownBy(() -> + GameplayAdmissionPointerSnapshots.requireAdmittedRoutingBundle( + missingRouting, "Entity Management request")) .isInstanceOf(IllegalStateException.class) .hasMessage( "Missing admitted routing bundle on session context for Entity Management request"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwnerTest.java index 928e529417..4dc34616a6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginCleanupOwnerTest.java @@ -152,11 +152,10 @@ void uncertainDurableBoundaryStopsItsFollowingDispatch(String failure) { } else if (failure.equals("freeze-commit")) { fixture.transactions.failAtCommit = 2; } else { - doAnswer( - invocation -> - fixture.snapshot.frozenRetirementRequest().isPresent() - ? Optional.empty() - : Optional.of(fixture.snapshot)) + doAnswer(invocation -> + fixture.snapshot.frozenRetirementRequest().isPresent() + ? Optional.empty() + : Optional.of(fixture.snapshot)) .when(fixture.journal) .readCommitted(ORIGINAL); } @@ -390,85 +389,77 @@ private static final class Fixture { private Fixture() { when(journal.reserve(ORIGINAL)) - .thenAnswer( - invocation -> { - assertTransaction(); - events.add("reserve"); - return snapshot; - }); + .thenAnswer(invocation -> { + assertTransaction(); + events.add("reserve"); + return snapshot; + }); when(journal.readCommitted(ORIGINAL)) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - events.add("read"); - return Optional.of(snapshot); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + events.add("read"); + return Optional.of(snapshot); + }); when(journal.abandon(ORIGINAL)) - .thenAnswer( - invocation -> { - assertTransaction(); - events.add("abandon"); - snapshot = - snapshot( - ORIGINAL, - true, - snapshot.verifiedWitness(), - snapshot.frozenRetirementRequest(), - snapshot.retainedReceipt()); - return snapshot; - }); + .thenAnswer(invocation -> { + assertTransaction(); + events.add("abandon"); + snapshot = + snapshot( + ORIGINAL, + true, + snapshot.verifiedWitness(), + snapshot.frozenRetirementRequest(), + snapshot.retainedReceipt()); + return snapshot; + }); when(journal.freezeRetirementRequest(ORIGINAL)) - .thenAnswer( - invocation -> { - assertTransaction(); - events.add("freeze"); - snapshot = - snapshot( - ORIGINAL, - true, - snapshot.verifiedWitness(), - Optional.of( - snapshot - .frozenRetirementRequest() - .orElseGet( - () -> - InitialGameplayLoginJournalSnapshot.request( - ORIGINAL, snapshot.verifiedWitness().orElse(null)))), - snapshot.retainedReceipt()); - return snapshot; - }); + .thenAnswer(invocation -> { + assertTransaction(); + events.add("freeze"); + snapshot = + snapshot( + ORIGINAL, + true, + snapshot.verifiedWitness(), + Optional.of( + snapshot + .frozenRetirementRequest() + .orElseGet(() -> + InitialGameplayLoginJournalSnapshot.request( + ORIGINAL, snapshot.verifiedWitness().orElse(null)))), + snapshot.retainedReceipt()); + return snapshot; + }); when(journal.recordDisposalReceipt(any(), any())) - .thenAnswer( - invocation -> { - assertTransaction(); - events.add("receipt"); - snapshot = - snapshot( - ORIGINAL, - true, - snapshot.verifiedWitness(), - snapshot.frozenRetirementRequest(), - Optional.of(invocation.getArgument(1))); - return snapshot; - }); + .thenAnswer(invocation -> { + assertTransaction(); + events.add("receipt"); + snapshot = + snapshot( + ORIGINAL, + true, + snapshot.verifiedWitness(), + snapshot.frozenRetirementRequest(), + Optional.of(invocation.getArgument(1))); + return snapshot; + }); when(closure.withAcknowledgedClosure(any(), any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(snapshot.abandoned()).isTrue(); - events.add("closure"); - Function continuation = - invocation.getArgument(1); - return Optional.of(continuation.apply(new AcknowledgedClosure(ORIGINAL))); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(snapshot.abandoned()).isTrue(); + events.add("closure"); + Function continuation = + invocation.getArgument(1); + return Optional.of(continuation.apply(new AcknowledgedClosure(ORIGINAL))); + }); when(account.retireInitialGameplayLogin(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(snapshot.frozenRetirementRequest()).contains(invocation.getArgument(0)); - events.add("account"); - return response; - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(snapshot.frozenRetirementRequest()).contains(invocation.getArgument(0)); + events.add("account"); + return response; + }); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextStateTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextStateTest.java index 9993cf1147..a83991f9ed 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextStateTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextStateTest.java @@ -84,9 +84,8 @@ void rejectsMalformedAndOpenPayloads(String kind) { case "noncanonical" -> " " + valid; default -> throw new AssertionError(kind); }; - assertThatThrownBy( - () -> - InitialGameplayLoginContextState.decode(malformed.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + InitialGameplayLoginContextState.decode(malformed.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Initial LOGIN context is invalid"); } @@ -96,10 +95,9 @@ void rejectsInvalidUtf8AndOversizedPayloads() { assertThatThrownBy( () -> InitialGameplayLoginContextState.decode(new byte[] {(byte) 0xc0, (byte) 0xaf})) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - InitialGameplayLoginContextState.decode( - new byte[InitialGameplayLoginContextState.MAX_BYTES + 1])) + assertThatThrownBy(() -> + InitialGameplayLoginContextState.decode( + new byte[InitialGameplayLoginContextState.MAX_BYTES + 1])) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java index 5d78317387..78dd655d03 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java @@ -131,20 +131,18 @@ void ownedBorrowPinsExactResultAndRefusesReentrantLifecycleChanges() { var success = successfulOutcome(); var outcome = success.outcome(); var value = - outcome.withOwnedPrivateResult( - result -> { - assertThat(result).isSameAs(success.result()); - assertThatThrownBy(outcome::close).isInstanceOf(IllegalStateException.class); - assertThatThrownBy(result::close).isInstanceOf(IllegalStateException.class); - assertThat(result.compactJwtBytes()).isNotEmpty(); - assertThatThrownBy(outcome::takePrivateResult) - .isInstanceOf(IllegalStateException.class); - assertThatThrownBy(outcome::abandonOriginalAfterCustodyLoss) - .isInstanceOf(IllegalStateException.class); - assertThatThrownBy(() -> outcome.withOwnedPrivateResult(nested -> true)) - .isInstanceOf(IllegalStateException.class); - return "non-admitting"; - }); + outcome.withOwnedPrivateResult(result -> { + assertThat(result).isSameAs(success.result()); + assertThatThrownBy(outcome::close).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(result::close).isInstanceOf(IllegalStateException.class); + assertThat(result.compactJwtBytes()).isNotEmpty(); + assertThatThrownBy(outcome::takePrivateResult).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(outcome::abandonOriginalAfterCustodyLoss) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> outcome.withOwnedPrivateResult(nested -> true)) + .isInstanceOf(IllegalStateException.class); + return "non-admitting"; + }); assertThat(value).isEqualTo("non-admitting"); assertThat(success.result().compactJwtBytes()).isNotEmpty(); verify(success.fixture().cleanup, never()).abandonAndRetire(any()); @@ -160,12 +158,10 @@ void ownedBorrowPinsExactResultAndRefusesReentrantLifecycleChanges() { void callbackFailureReleasesBorrowWithoutTransferringOrRetiringTheResult() { var success = successfulOutcome(); var outcome = success.outcome(); - assertThatThrownBy( - () -> - outcome.withOwnedPrivateResult( - result -> { - throw new IllegalStateException("controlled callback failure"); - })) + assertThatThrownBy(() -> + outcome.withOwnedPrivateResult(result -> { + throw new IllegalStateException("controlled callback failure"); + })) .hasMessage("controlled callback failure"); assertThat(outcome.withOwnedPrivateResult(result -> result == success.result())) .isTrue(); @@ -185,28 +181,25 @@ void concurrentCloseWaitsForOwnedBorrowThenRetiresExactOriginal() throws Excepti var closing = new CountDownLatch(1); try (var executor = Executors.newFixedThreadPool(2)) { var borrowed = - executor.submit( - () -> - outcome.withOwnedPrivateResult( - result -> { - entered.countDown(); - try { - if (!release.await(5, TimeUnit.SECONDS)) - throw new IllegalStateException("test timeout"); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw new IllegalStateException(interrupted); - } - return result == success.result(); - })); + executor.submit(() -> + outcome.withOwnedPrivateResult(result -> { + entered.countDown(); + try { + if (!release.await(5, TimeUnit.SECONDS)) + throw new IllegalStateException("test timeout"); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(interrupted); + } + return result == success.result(); + })); try { assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); var closed = - executor.submit( - () -> { - closing.countDown(); - outcome.close(); - }); + executor.submit(() -> { + closing.countDown(); + outcome.close(); + }); assertThat(closing.await(5, TimeUnit.SECONDS)).isTrue(); assertThatThrownBy(() -> closed.get(100, TimeUnit.MILLISECONDS)) .isInstanceOf(TimeoutException.class); @@ -234,31 +227,28 @@ void lifecycleDrainKeepsBorrowedBytesLiveAndBlocksNewBorrows(String operation) t byte[] expected = success.result().compactJwtBytes(); try (var executor = Executors.newFixedThreadPool(2)) { var borrowed = - executor.submit( - () -> - outcome.withOwnedPrivateResult( - result -> { - assertThat(result).isSameAs(success.result()); - entered.countDown(); - await(release); - assertThat(result.compactJwtBytes()).containsExactly(expected); - return true; - })); + executor.submit(() -> + outcome.withOwnedPrivateResult(result -> { + assertThat(result).isSameAs(success.result()); + entered.countDown(); + await(release); + assertThat(result.compactJwtBytes()).containsExactly(expected); + return true; + })); try { assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); var mutation = - executor.submit( - () -> { - lifecycleThread.set(Thread.currentThread()); - return switch (operation) { - case "transfer" -> outcome.takePrivateResult().orElseThrow(); - case "abandon" -> outcome.abandonOriginalAfterCustodyLoss(); - default -> { - success.result().close(); - yield true; - } - }; - }); + executor.submit(() -> { + lifecycleThread.set(Thread.currentThread()); + return switch (operation) { + case "transfer" -> outcome.takePrivateResult().orElseThrow(); + case "abandon" -> outcome.abandonOriginalAfterCustodyLoss(); + default -> { + success.result().close(); + yield true; + } + }; + }); awaitWaiting(lifecycleThread); assertThatThrownBy(() -> outcome.withOwnedPrivateResult(result -> true)) .isInstanceOf(IllegalStateException.class); @@ -297,15 +287,14 @@ void heldOriginalCleanupRetriesOutsideOutcomeMonitorAndRefusesReentrantMutation( var accessed = new AtomicBoolean(); try (var executor = Executors.newSingleThreadExecutor()) { when(success.fixture().cleanup.abandonAndRetire(outcome.coordinates())) - .thenAnswer( - call -> { - assertThatThrownBy(outcome::close).isInstanceOf(IllegalStateException.class); - accessed.set( - executor - .submit(() -> outcome.custodyLossCleanup().isEmpty()) - .get(5, TimeUnit.SECONDS)); - return held(outcome.coordinates()); - }); + .thenAnswer(call -> { + assertThatThrownBy(outcome::close).isInstanceOf(IllegalStateException.class); + accessed.set( + executor + .submit(() -> outcome.custodyLossCleanup().isEmpty()) + .get(5, TimeUnit.SECONDS)); + return held(outcome.coordinates()); + }); outcome.close(); assertThat(accessed).isTrue(); assertThat(outcome.custodyLossCleanup().orElseThrow().status()) @@ -346,18 +335,16 @@ void directResultBorrowRefusesOwnerReentrancyWithoutChangingOwnedState() { var success = successfulOutcome(); success .result() - .withLivePrivateResult( - result -> { - assertThatThrownBy(success.outcome()::close) - .isInstanceOf(IllegalStateException.class); - assertThatThrownBy(success.outcome()::takePrivateResult) - .isInstanceOf(IllegalStateException.class); - assertThatThrownBy(success.outcome()::abandonOriginalAfterCustodyLoss) - .isInstanceOf(IllegalStateException.class); - assertThat(result.compactJwtBytes()).isNotEmpty(); - verify(success.fixture().cleanup, never()).abandonAndRetire(any()); - return true; - }); + .withLivePrivateResult(result -> { + assertThatThrownBy(success.outcome()::close).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(success.outcome()::takePrivateResult) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(success.outcome()::abandonOriginalAfterCustodyLoss) + .isInstanceOf(IllegalStateException.class); + assertThat(result.compactJwtBytes()).isNotEmpty(); + verify(success.fixture().cleanup, never()).abandonAndRetire(any()); + return true; + }); assertThat( success.outcome().withOwnedPrivateResult(result -> result == success.result())) .isTrue(); @@ -382,43 +369,40 @@ void directResultPinCannotWaitBehindOutcomeDrainThatIsWaitingForTheSamePin(boole // Daemon workers keep this logical-deadlock regression bounded even if the cycle returns. Thread.ofPlatform() .daemon() - .start( - () -> { - try { - borrowed.complete( - success - .result() - .withLivePrivateResult( - result -> { - entered.countDown(); - await(attemptLifecycle); - assertThatThrownBy(success.outcome()::close) - .isInstanceOf(IllegalStateException.class); - assertThatThrownBy(success.outcome()::takePrivateResult) - .isInstanceOf(IllegalStateException.class); - assertThatThrownBy(success.outcome()::abandonOriginalAfterCustodyLoss) - .isInstanceOf(IllegalStateException.class); - assertThat(result.compactJwtBytes()).isNotEmpty(); - return true; - })); - } catch (Throwable failure) { - borrowed.completeExceptionally(failure); - } - }); + .start(() -> { + try { + borrowed.complete( + success + .result() + .withLivePrivateResult(result -> { + entered.countDown(); + await(attemptLifecycle); + assertThatThrownBy(success.outcome()::close) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(success.outcome()::takePrivateResult) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(success.outcome()::abandonOriginalAfterCustodyLoss) + .isInstanceOf(IllegalStateException.class); + assertThat(result.compactJwtBytes()).isNotEmpty(); + return true; + })); + } catch (Throwable failure) { + borrowed.completeExceptionally(failure); + } + }); assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); Thread.ofPlatform() .daemon() - .start( - () -> { - closingThread.set(Thread.currentThread()); - try { - if (transferred) success.outcome().abandonOriginalAfterCustodyLoss(); - else success.outcome().close(); - closed.complete(null); - } catch (Throwable failure) { - closed.completeExceptionally(failure); - } - }); + .start(() -> { + closingThread.set(Thread.currentThread()); + try { + if (transferred) success.outcome().abandonOriginalAfterCustodyLoss(); + else success.outcome().close(); + closed.complete(null); + } catch (Throwable failure) { + closed.completeExceptionally(failure); + } + }); try { awaitWaiting(closingThread); assertThat(closed).isNotDone(); @@ -456,21 +440,18 @@ private static SuccessfulOutcome successfulOutcome() { var credentials = presentation(secret); var result = new AtomicReference(); when(fixture.account.authenticate(any(AuthenticateRequest.class), any())) - .thenAnswer( - invocation -> { - fixture.accountRequest = invocation.getArgument(0); - var retained = spy(controlledPrivateResult(fixture.coordinates)); - result.set(retained); - return retained; - }); + .thenAnswer(invocation -> { + fixture.accountRequest = invocation.getArgument(0); + var retained = spy(controlledPrivateResult(fixture.coordinates)); + result.set(retained); + return retained; + }); when(fixture.contexts.createPending(any())) - .thenAnswer( - invocation -> - Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); + .thenAnswer(invocation -> + Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); when(fixture.cleanup.recordVerifiedResult(any(), any())) - .thenAnswer( - invocation -> - snapshotWithWitness(invocation.getArgument(0), invocation.getArgument(1))); + .thenAnswer(invocation -> + snapshotWithWitness(invocation.getArgument(0), invocation.getArgument(1))); when(fixture.contexts.install(any(), any())) .thenAnswer(invocation -> Optional.of(installed(invocation.getArgument(0)))); when(fixture.cleanup.abandonAndRetire(any())) @@ -519,9 +500,8 @@ void ambiguousAuthenticateFailureSelectsCleanupAndNeverInstalls() { var fixture = new Fixture(); var secret = "transient-secret".toCharArray(); when(fixture.contexts.createPending(any())) - .thenAnswer( - invocation -> - Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); + .thenAnswer(invocation -> + Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); when(fixture.account.authenticate(any(AuthenticateRequest.class), any())) .thenThrow(Status.UNAVAILABLE.asRuntimeException()); when(fixture.cleanup.abandonAndRetire(any())) @@ -541,9 +521,8 @@ void callerCancellationWhileCredentialCustodyIsCurrentRemainsCancelled() { var fixture = new Fixture(); var credentials = presentation("transient-secret".toCharArray()); when(fixture.contexts.createPending(any())) - .thenAnswer( - invocation -> - Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); + .thenAnswer(invocation -> + Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); when(fixture.account.authenticate(any(AuthenticateRequest.class), any())) .thenThrow(Status.CANCELLED.asRuntimeException()); when(fixture.cleanup.abandonAndRetire(any())) @@ -561,15 +540,13 @@ void cancelledAccountCallAfterCredentialCustodyLossReportsCustodyLost() { var fixture = new Fixture(); var credentials = presentation("transient-secret".toCharArray()); when(fixture.contexts.createPending(any())) - .thenAnswer( - invocation -> - Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); + .thenAnswer(invocation -> + Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); when(fixture.account.authenticate(any(AuthenticateRequest.class), any())) - .thenAnswer( - invocation -> { - credentials.close(); - throw Status.CANCELLED.asRuntimeException(); - }); + .thenAnswer(invocation -> { + credentials.close(); + throw Status.CANCELLED.asRuntimeException(); + }); when(fixture.cleanup.abandonAndRetire(any())) .thenAnswer(invocation -> held(invocation.getArgument(0))); @@ -587,19 +564,16 @@ void lostCustodyAfterVerifiedAccountResponseRecordsWitnessThenCleansWithoutInsta var result = mock(CanonicalGameplayLoginResult.class); when(result.evidence()).thenAnswer(invocation -> evidence(fixture.coordinates)); when(fixture.contexts.createPending(any())) - .thenAnswer( - invocation -> - Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); + .thenAnswer(invocation -> + Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); when(fixture.account.authenticate(any(AuthenticateRequest.class), any())) - .thenAnswer( - invocation -> { - credentials.close(); - return result; - }); + .thenAnswer(invocation -> { + credentials.close(); + return result; + }); when(fixture.cleanup.recordVerifiedResult(any(), any())) - .thenAnswer( - invocation -> - snapshotWithWitness(invocation.getArgument(0), invocation.getArgument(1))); + .thenAnswer(invocation -> + snapshotWithWitness(invocation.getArgument(0), invocation.getArgument(1))); when(fixture.cleanup.abandonAndRetire(any())) .thenAnswer(invocation -> held(invocation.getArgument(0))); @@ -621,9 +595,8 @@ void unavailableWitnessReadbackStillUsesExactOriginalCleanupFreeze() { var result = mock(CanonicalGameplayLoginResult.class); when(result.evidence()).thenAnswer(invocation -> evidence(fixture.coordinates)); when(fixture.contexts.createPending(any())) - .thenAnswer( - invocation -> - Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); + .thenAnswer(invocation -> + Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); when(fixture.account.authenticate(any(AuthenticateRequest.class), any())).thenReturn(result); when(fixture.cleanup.recordVerifiedResult(any(), any())) .thenThrow(new IllegalStateException("journal readback unavailable")); @@ -647,14 +620,12 @@ void failedExactInstallClosesOriginalAndRetiresFromTheSameInvocationResult() { var result = mock(CanonicalGameplayLoginResult.class); when(result.evidence()).thenAnswer(invocation -> evidence(fixture.coordinates)); when(fixture.contexts.createPending(any())) - .thenAnswer( - invocation -> - Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); + .thenAnswer(invocation -> + Optional.of(InitialGameplayLoginContextState.pending(invocation.getArgument(0)))); when(fixture.account.authenticate(any(AuthenticateRequest.class), any())).thenReturn(result); when(fixture.cleanup.recordVerifiedResult(any(), any())) - .thenAnswer( - invocation -> - snapshotWithWitness(invocation.getArgument(0), invocation.getArgument(1))); + .thenAnswer(invocation -> + snapshotWithWitness(invocation.getArgument(0), invocation.getArgument(1))); when(fixture.contexts.install(any(), any())).thenReturn(Optional.empty()); when(fixture.cleanup.abandonAndRetire(any())) .thenAnswer(invocation -> held(invocation.getArgument(0))); @@ -742,17 +713,15 @@ private static final class Fixture { private Fixture() { when(cleanup.reserve(any())) - .thenAnswer( - invocation -> { - coordinates = invocation.getArgument(0); - return snapshot(coordinates); - }); + .thenAnswer(invocation -> { + coordinates = invocation.getArgument(0); + return snapshot(coordinates); + }); when(account.authenticate(any(AuthenticateRequest.class), any())) - .thenAnswer( - invocation -> { - accountRequest = invocation.getArgument(0); - return null; - }); + .thenAnswer(invocation -> { + accountRequest = invocation.getArgument(0); + return null; + }); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisAttemptClosureTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisAttemptClosureTest.java index b5a6a4ec8f..3da745c407 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisAttemptClosureTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginRedisAttemptClosureTest.java @@ -77,13 +77,12 @@ void lostQualificationBeforeContinuationNeverDispatches() { .thenReturn(Optional.of(InitialGameplayLoginContextState.closed(ORIGINAL))); doThrow(new IllegalStateException("qualification lost")).when(held).requireCurrent(); var adapter = new InitialGameplayLoginRedisAttemptClosure(client); - assertThatThrownBy( - () -> - adapter.withAcknowledgedClosure( - ORIGINAL, - receipt -> { - throw new AssertionError("No dispatch"); - })) + assertThatThrownBy(() -> + adapter.withAcknowledgedClosure( + ORIGINAL, + receipt -> { + throw new AssertionError("No dispatch"); + })) .isInstanceOf(IllegalStateException.class); verify(held).close(); } @@ -97,14 +96,13 @@ void continuationFailureIsNotHiddenOrRetriedAndExclusionIsReleased() { when(client.closeOriginal(ORIGINAL, held)) .thenReturn(Optional.of(InitialGameplayLoginContextState.closed(ORIGINAL))); var adapter = new InitialGameplayLoginRedisAttemptClosure(client); - assertThatThrownBy( - () -> - adapter.withAcknowledgedClosure( - ORIGINAL, - receipt -> { - calls.incrementAndGet(); - throw new IllegalStateException("Account unavailable"); - })) + assertThatThrownBy(() -> + adapter.withAcknowledgedClosure( + ORIGINAL, + receipt -> { + calls.incrementAndGet(); + throw new IllegalStateException("Account unavailable"); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("Account unavailable"); assertThat(calls).hasValue(1); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/LettuceInitialGameplayLoginConnectionProviderTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/LettuceInitialGameplayLoginConnectionProviderTest.java index 52febd0892..6d4da2d008 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/LettuceInitialGameplayLoginConnectionProviderTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/LettuceInitialGameplayLoginConnectionProviderTest.java @@ -93,14 +93,13 @@ void disposesConnectionThatFinishesAfterConcurrentProviderClose() throws Excepti var connectStarted = new CountDownLatch(1); var finishConnect = new CountDownLatch(1); when(client.connect(ByteArrayCodec.INSTANCE)) - .thenAnswer( - ignored -> { - connectStarted.countDown(); - if (!finishConnect.await(5, TimeUnit.SECONDS)) { - throw new AssertionError("test connection was not released"); - } - return connection; - }); + .thenAnswer(ignored -> { + connectStarted.countDown(); + if (!finishConnect.await(5, TimeUnit.SECONDS)) { + throw new AssertionError("test connection was not released"); + } + return connection; + }); var executor = Executors.newSingleThreadExecutor(); try (var factory = mockStatic(RedisClient.class)) { factory.when(() -> RedisClient.create(uri)).thenReturn(client); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java index 28f884ee4e..aa6b222810 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/directtext/DirectTextAuthenticatedLobbyTest.java @@ -78,13 +78,12 @@ void codecPreservesWholeIdentityTargetAndOriginalAccountTimesWithoutPrivateBytes assertThat(new String(bytes, StandardCharsets.UTF_8)) .doesNotContain("fixture-private-token", "password", "authToken", "compactJwt"); // Historical decode after expiry is still possible, but use cannot renew its deadline. - assertThatThrownBy( - () -> - restored.requireCurrent( - f.original, - f.result, - f.transport, - Clock.fixed(NOW.plusSeconds(60), ZoneOffset.UTC))) + assertThatThrownBy(() -> + restored.requireCurrent( + f.original, + f.result, + f.transport, + Clock.fixed(NOW.plusSeconds(60), ZoneOffset.UTC))) .isInstanceOf(IllegalArgumentException.class); verify(f.result, never()).close(); } @@ -247,20 +246,18 @@ void rejectsUnknownHiddenAndDuplicateProtobufData() { .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) .build(); var request = f.frozen.request(); - assertThatThrownBy( - () -> - DirectTextAuthenticatedLobbyJoin.decodeRequest( - request.toBuilder().setUnknownFields(unknown).build().toByteArray())) + assertThatThrownBy(() -> + DirectTextAuthenticatedLobbyJoin.decodeRequest( + request.toBuilder().setUnknownFields(unknown).build().toByteArray())) .isInstanceOf(IllegalArgumentException.class); var hidden = request.toBuilder() .setPlayerContext( request.getPlayerContext().toBuilder().setCharacterId(UUID.randomUUID().toString())) .build(); - assertThatThrownBy( - () -> - new DirectTextAuthenticatedLobbyJoin( - f.scope, hidden, State.NEVER_DISPATCHED, Optional.empty())) + assertThatThrownBy(() -> + new DirectTextAuthenticatedLobbyJoin( + f.scope, hidden, State.NEVER_DISPATCHED, Optional.empty())) .isInstanceOf(IllegalArgumentException.class); byte[] duplicate = new byte[request.getSerializedSize() * 2]; System.arraycopy(request.toByteArray(), 0, duplicate, 0, request.getSerializedSize()); @@ -279,13 +276,12 @@ void rejectsUnknownHiddenAndDuplicateProtobufData() { f.scope.recordId(), f.transport.proxyConnectionId(), f.result.evidence().tokenJti())) { - assertThatThrownBy( - () -> - new DirectTextAuthenticatedLobbyJoin( - f.scope, - DirectTextAuthenticatedLobbyJoin.requestFor(f.scope, reused), - State.NEVER_DISPATCHED, - Optional.empty())) + assertThatThrownBy(() -> + new DirectTextAuthenticatedLobbyJoin( + f.scope, + DirectTextAuthenticatedLobbyJoin.requestFor(f.scope, reused), + State.NEVER_DISPATCHED, + Optional.empty())) .isInstanceOf(IllegalArgumentException.class); } } @@ -315,11 +311,10 @@ void freshScopeIsRetainedAndIndependentlyReadAfterCommit() { when(f.selection.resolve(null, "public")).thenReturn(Optional.of(f.scope.publicTarget())); when(f.account.issueDirectTextConnectScope(any(), any())).thenReturn(scopeResponse()); when(f.repository.readCommittedScope(any())) - .thenAnswer( - call -> { - assertThat(f.events.getLast()).isEqualTo("COMMIT"); - return call.getArgument(0); - }); + .thenAnswer(call -> { + assertThat(f.events.getLast()).isEqualTo("COMMIT"); + return call.getArgument(0); + }); var retained = f.owner.realms(f.original, f.result, f.custody, null, "public"); assertThat(retained.issued().evaluatedAt()).isEqualTo(scopeResponse().getEvaluatedAt()); assertThat(retained.issued().connectScopeExpiresAt()) @@ -364,25 +359,23 @@ void futureLoginTimestampDeniesRealmPreparationBeforeEffects(String futureClaim) void committedExactRequestAndPossibleStatePrecedeAccountAndReplyPersistence() { var f = new Fixture(); when(f.account.joinPublicProductionMembership(any(), any(), any(), any())) - .thenAnswer( - call -> { - assertThat(f.events) - .containsSubsequence("FREEZE", "COMMIT", "READ", "CLAIM", "COMMIT", "READ"); - assertThat( - call.getArgument( - 0, net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)) - .isEqualTo(f.frozen.request().getPlayerContext()); - var context = + .thenAnswer(call -> { + assertThat(f.events) + .containsSubsequence("FREEZE", "COMMIT", "READ", "CLAIM", "COMMIT", "READ"); + assertThat( call.getArgument( - 0, net.firedevops.firemud.shared.v1.PlayerExecutionContext.class); - assertThat(context.getAccountId()).isEqualTo(ACCOUNT.toString()); - assertThat(context.getSessionId()).isEqualTo(f.transport.transportSessionId()); - assertThat(call.getArgument(1, String.class)) - .isEqualTo(f.scope.issued().connectScopeId()); - assertThat(call.getArgument(2, String.class)) - .isEqualTo(f.frozen.request().getRequestId()); - return positive(); - }); + 0, net.firedevops.firemud.shared.v1.PlayerExecutionContext.class)) + .isEqualTo(f.frozen.request().getPlayerContext()); + var context = + call.getArgument(0, net.firedevops.firemud.shared.v1.PlayerExecutionContext.class); + assertThat(context.getAccountId()).isEqualTo(ACCOUNT.toString()); + assertThat(context.getSessionId()).isEqualTo(f.transport.transportSessionId()); + assertThat(call.getArgument(1, String.class)) + .isEqualTo(f.scope.issued().connectScopeId()); + assertThat(call.getArgument(2, String.class)) + .isEqualTo(f.frozen.request().getRequestId()); + return positive(); + }); var observation = f.owner.join(f.original, f.result, f.custody); assertThat(observation.status()) .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.COMPLETED_CURRENT_NON_ADMITTING); @@ -422,12 +415,11 @@ void genericErrorsNeverFabricateTerminalCompletionOrRearm(String code) { void positiveReplyAfterCustodyLossIsRetainedButNeverAppliedToReplacementTransport() { var f = new Fixture(); when(f.account.joinPublicProductionMembership(any(), any(), any(), any())) - .thenAnswer( - call -> { - f.resetAfterCallback.set( - true); // Controlled reset at callback exit, not real receiving proof. - return positive(); - }); + .thenAnswer(call -> { + f.resetAfterCallback.set( + true); // Controlled reset at callback exit, not real receiving proof. + return positive(); + }); var observation = f.owner.join(f.original, f.result, f.custody); assertThat(observation.status()) .isEqualTo(DirectTextAuthenticatedLobbyOwner.Status.HISTORICAL_ONLY); @@ -457,29 +449,26 @@ void resetExpiredPrivateResultAndChangedTransportDenyBeforeEffects() { .isInstanceOf(IllegalStateException.class); verifyNoInteractions(f.repository, f.account); f.live.set(true); - assertThatThrownBy( - () -> - f.scope.requireCurrent( - f.original, - f.result, - new ObservedDirectTextTransport("42", f.transport.proxyConnectionId()), - CLOCK)) + assertThatThrownBy(() -> + f.scope.requireCurrent( + f.original, + f.result, + new ObservedDirectTextTransport("42", f.transport.proxyConnectionId()), + CLOCK)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - f.scope.requireCurrent( - f.original, - f.result, - new ObservedDirectTextTransport("00042", UUID.randomUUID()), - CLOCK)) + assertThatThrownBy(() -> + f.scope.requireCurrent( + f.original, + f.result, + new ObservedDirectTextTransport("00042", UUID.randomUUID()), + CLOCK)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - f.scope.requireCurrent( - f.original, - f.result, - f.transport, - Clock.fixed(NOW.plusSeconds(120), ZoneOffset.UTC))) + assertThatThrownBy(() -> + f.scope.requireCurrent( + f.original, + f.result, + f.transport, + Clock.fixed(NOW.plusSeconds(120), ZoneOffset.UTC))) .isInstanceOf(IllegalArgumentException.class); } @@ -547,27 +536,24 @@ public T withCurrent( retained.set(frozen); when(repository.current(any(), any(), any(), any())).thenReturn(scope); when(repository.freezeCurrentJoin(any(), any(), any(), any())) - .thenAnswer( - call -> { - events.add("FREEZE"); - return retained.get(); - }); + .thenAnswer(call -> { + events.add("FREEZE"); + return retained.get(); + }); when(repository.readCommittedJoin(any())) - .thenAnswer( - call -> { - events.add("READ"); - return retained.get(); - }); + .thenAnswer(call -> { + events.add("READ"); + return retained.get(); + }); when(repository.claimDispatch(any(), any(), any(), any())) - .thenAnswer( - call -> { - events.add("CLAIM"); - if (retained.get().state() != State.NEVER_DISPATCHED) return false; - retained.set( - new DirectTextAuthenticatedLobbyJoin( - scope, frozen.request(), State.DISPATCH_POSSIBLE, Optional.empty())); - return true; - }); + .thenAnswer(call -> { + events.add("CLAIM"); + if (retained.get().state() != State.NEVER_DISPATCHED) return false; + retained.set( + new DirectTextAuthenticatedLobbyJoin( + scope, frozen.request(), State.DISPATCH_POSSIBLE, Optional.empty())); + return true; + }); doAnswer( call -> { retained.set( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountInitialAdmissionSettlementReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountInitialAdmissionSettlementReadGrpcServiceTest.java index ccb6486f33..7501c0e6ae 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountInitialAdmissionSettlementReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountInitialAdmissionSettlementReadGrpcServiceTest.java @@ -105,11 +105,10 @@ void authenticatedAccountGetsExactBytesOverRealMtlsAndWrongPeersNeverReachOwner( for (String alias : List.of("world", "foreign")) { ManagedChannel channel = channel(pki, alias, server.getPort()); try { - assertThatThrownBy( - () -> - stub(channel) - .getAccountInitialAdmissionSettlement( - GetAccountInitialAdmissionSettlementRequest.getDefaultInstance())) + assertThatThrownBy(() -> + stub(channel) + .getAccountInitialAdmissionSettlement( + GetAccountInitialAdmissionSettlementRequest.getDefaultInstance())) .isInstanceOfSatisfying( StatusRuntimeException.class, error -> @@ -308,10 +307,8 @@ public void onCompleted() { Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer(NAMESPACE, "account-service")); var request = AccountInitialAdmissionSettlementReadGrpcCodec.toRequest(input, NAMESPACE); - assertThatThrownBy( - () -> - context.run( - () -> service().getAccountInitialAdmissionSettlement(request, observer))) + assertThatThrownBy(() -> + context.run(() -> service().getAccountInitialAdmissionSettlement(request, observer))) .isSameAs(failure); assertThat(callbacks) .containsExactlyElementsOf(failOnNext ? List.of("next") : List.of("next", "completed")); @@ -330,23 +327,22 @@ private Status invokeStatus( GrpcPeerIdentity peer, GetAccountInitialAdmissionSettlementRequest request) { AtomicReference error = new AtomicReference<>(); Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); - context.run( - () -> - service() - .getAccountInitialAdmissionSettlement( - request, - new StreamObserver<>() { - @Override - public void onNext(GetAccountInitialAdmissionSettlementResponse value) {} + context.run(() -> + service() + .getAccountInitialAdmissionSettlement( + request, + new StreamObserver<>() { + @Override + public void onNext(GetAccountInitialAdmissionSettlementResponse value) {} - @Override - public void onError(Throwable failure) { - error.set(Status.fromThrowable(failure)); - } + @Override + public void onError(Throwable failure) { + error.set(Status.fromThrowable(failure)); + } - @Override - public void onCompleted() {} - })); + @Override + public void onCompleted() {} + })); return error.get(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java index 2a00f7cd96..01d459832e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java @@ -42,11 +42,10 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { presenceService, resolver, recentPresenceService, pointerAuthorityService); when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), - org.mockito.ArgumentMatchers.argThat( - ids -> - ids != null - && ids.containsAll(List.of(ONLINE_ACCOUNT_ID, OFFLINE_ACCOUNT_ID)) - && ids.size() == 2))) + org.mockito.ArgumentMatchers.argThat(ids -> + ids != null + && ids.containsAll(List.of(ONLINE_ACCOUNT_ID, OFFLINE_ACCOUNT_ID)) + && ids.size() == 2))) .thenReturn( java.util.Map.of( OFFLINE_ACCOUNT_ID, @@ -62,11 +61,10 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { AccountRecentPresenceDisposition.TRANSPORT_LOSS))); when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), - org.mockito.ArgumentMatchers.argThat( - ids -> - ids != null - && ids.containsAll(List.of(ONLINE_ACCOUNT_ID, OFFLINE_ACCOUNT_ID)) - && ids.size() == 2))) + org.mockito.ArgumentMatchers.argThat(ids -> + ids != null + && ids.containsAll(List.of(ONLINE_ACCOUNT_ID, OFFLINE_ACCOUNT_ID)) + && ids.size() == 2))) .thenReturn( Map.of( ONLINE_ACCOUNT_ID, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AuthenticatedCanonicalInitialAdmissionWorldVerifierTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AuthenticatedCanonicalInitialAdmissionWorldVerifierTest.java index 60d514ce31..887bd88ac8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AuthenticatedCanonicalInitialAdmissionWorldVerifierTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AuthenticatedCanonicalInitialAdmissionWorldVerifierTest.java @@ -60,14 +60,13 @@ void returnsProofFromAuthenticatedWorldIdentityAndFreshActiveStateRead() { when(fixtures.worldClient.readIdentity(retained.holdRequest())) .thenReturn(retained.holdIdentity()); when(fixtures.worldClient.readState(any(), any())) - .thenAnswer( - invocation -> - worldState( - invocation.getArgument(0), - invocation.getArgument(1), - HoldStatus.PENDING, - "ACTIVE", - 2L)); + .thenAnswer(invocation -> + worldState( + invocation.getArgument(0), + invocation.getArgument(1), + HoldStatus.PENDING, + "ACTIVE", + 2L)); CanonicalInitialAdmissionWorldProof proof = fixtures.verifier.verify(expected); @@ -218,11 +217,10 @@ void rechecksAmbientTransactionAfterIdentityRpcBeforeStateRpc() { CanonicalInitialAdmissionIntentSnapshot retained = attachedSnapshot(); when(fixtures.repository.read(NAMESPACE, "request-1")).thenReturn(Optional.of(retained)); when(fixtures.worldClient.readIdentity(retained.holdRequest())) - .thenAnswer( - invocation -> { - TransactionSynchronizationManager.setActualTransactionActive(true); - return retained.holdIdentity(); - }); + .thenAnswer(invocation -> { + TransactionSynchronizationManager.setActualTransactionActive(true); + return retained.holdIdentity(); + }); assertThatThrownBy(() -> fixtures.verifier.verify(expectedRequest())) .isInstanceOf(IllegalStateException.class) @@ -254,14 +252,13 @@ private static Fixtures configuredFixtures( when(fixtures.worldClient.readIdentity(retained.holdRequest())) .thenReturn(retained.holdIdentity()); when(fixtures.worldClient.readState(any(), any())) - .thenAnswer( - invocation -> - worldState( - invocation.getArgument(0), - invocation.getArgument(1), - status, - lifecycleStatus, - lifecycleEpoch)); + .thenAnswer(invocation -> + worldState( + invocation.getArgument(0), + invocation.getArgument(1), + status, + lifecycleStatus, + lifecycleEpoch)); return fixtures; } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java index c0b64abd46..b99779ba1c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java @@ -128,12 +128,11 @@ void leavesUnexpectedQueueFailureRetryableForTheSameAdmissionIdentity() { 1L, 2L, "region-alpha", 7L, "dispatch-1")) .thenReturn(Optional.empty(), Optional.of(accepted), Optional.of(accepted)); when(gameplayCommandRepository.insertIfAbsentByIdempotencyIdentity(any())) - .thenAnswer( - invocation -> { - GameplayCommand command = invocation.getArgument(0); - command.setCommandId("auto-failed"); - return new GameplayCommandRepository.IdempotentInsertResult(command, true); - }); + .thenAnswer(invocation -> { + GameplayCommand command = invocation.getArgument(0); + command.setCommandId("auto-failed"); + return new GameplayCommandRepository.IdempotentInsertResult(command, true); + }); RuntimeRegionStatus ownership = new RuntimeRegionStatus(); ownership.setTenantId(1L); ownership.setGameInstanceId(2L); @@ -191,10 +190,8 @@ void durableAdmissionCommitsBeforeQueueMaterialization() { 1L, 2L, "region-alpha", 7L, "dispatch-1")) .thenReturn(Optional.empty()); when(gameplayCommandRepository.insertIfAbsentByIdempotencyIdentity(any())) - .thenAnswer( - invocation -> - new GameplayCommandRepository.IdempotentInsertResult( - invocation.getArgument(0), true)); + .thenAnswer(invocation -> + new GameplayCommandRepository.IdempotentInsertResult(invocation.getArgument(0), true)); RuntimeRegionStatus ownership = new RuntimeRegionStatus(); ownership.setTenantId(1L); ownership.setGameInstanceId(2L); @@ -300,10 +297,8 @@ void persistsTheExactScriptPatchBaseOnFreshAdmission() { request.tenantId(), request.regionId())) .thenReturn(Optional.of(ownership)); when(gameplayCommandRepository.insertIfAbsentByIdempotencyIdentity(any())) - .thenAnswer( - invocation -> - new GameplayCommandRepository.IdempotentInsertResult( - invocation.getArgument(0), true)); + .thenAnswer(invocation -> + new GameplayCommandRepository.IdempotentInsertResult(invocation.getArgument(0), true)); AdmissionResult result = AutomationGameplayCommandAdmissionSupport.admitIfAbsent( @@ -354,12 +349,11 @@ void acceptsAutomationCommandWithMalformedTargetEntityAndLeavesCharacterIdUnset( 1L, 2L, "region-alpha", 7L, "dispatch-1")) .thenReturn(Optional.empty()); when(gameplayCommandRepository.insertIfAbsentByIdempotencyIdentity(any())) - .thenAnswer( - invocation -> { - GameplayCommand inserted = invocation.getArgument(0); - inserted.setId(1L); - return new GameplayCommandRepository.IdempotentInsertResult(inserted, true); - }); + .thenAnswer(invocation -> { + GameplayCommand inserted = invocation.getArgument(0); + inserted.setId(1L); + return new GameplayCommandRepository.IdempotentInsertResult(inserted, true); + }); RuntimeRegionStatus ownership = new RuntimeRegionStatus(); ownership.setTenantId(1L); @@ -562,10 +556,8 @@ void remoteAutomationRetainsLegacyAdmissionWithoutLocalPinTuple() { when(runtimeRegionStatusRepository.findByTenantIdAndRegionId(1L, "region-alpha")) .thenReturn(Optional.of(ownership)); when(gameplayCommandRepository.insertIfAbsentByIdempotencyIdentity(any())) - .thenAnswer( - invocation -> - new GameplayCommandRepository.IdempotentInsertResult( - invocation.getArgument(0), true)); + .thenAnswer(invocation -> + new GameplayCommandRepository.IdempotentInsertResult(invocation.getArgument(0), true)); when(pointerAuthority.listByRuntimeTarget(1L, 2L)) .thenReturn(List.of(currentPointer("demo", "production", 17L))); @@ -639,10 +631,8 @@ void validatesRemoteFollowupRequiredFieldsUsingNormalizedSourceType() { when(pointerAuthority.listByRuntimeTarget(1L, 2L)) .thenReturn(List.of(currentPointer("demo", "production", 17L))); when(gameplayCommandRepository.insertIfAbsentByIdempotencyIdentity(any())) - .thenAnswer( - invocation -> - new GameplayCommandRepository.IdempotentInsertResult( - invocation.getArgument(0), true)); + .thenAnswer(invocation -> + new GameplayCommandRepository.IdempotentInsertResult(invocation.getArgument(0), true)); RuntimeRegionStatus ownership = new RuntimeRegionStatus(); ownership.setTenantId(1L); ownership.setGameInstanceId(2L); @@ -1429,39 +1419,36 @@ void concurrentExactAndChangedAdmissionsKeepOneRowAndOnlyExactRetryIsReusable() winner.setCommandId("auto-winner"); winner.setExecutionOutcome("STAGED"); when(gameplayCommandRepository.insertIfAbsentByIdempotencyIdentity(any())) - .thenAnswer( - invocation -> { - GameplayCommand candidate = invocation.getArgument(0); - if ("say hello".equals(candidate.getCommandText())) { - exactInserted.countDown(); - return new GameplayCommandRepository.IdempotentInsertResult(winner, true); - } - if (!exactInserted.await(5, TimeUnit.SECONDS)) { - throw new AssertionError("exact admission did not win the race"); - } - return new GameplayCommandRepository.IdempotentInsertResult(winner, false); - }); + .thenAnswer(invocation -> { + GameplayCommand candidate = invocation.getArgument(0); + if ("say hello".equals(candidate.getCommandText())) { + exactInserted.countDown(); + return new GameplayCommandRepository.IdempotentInsertResult(winner, true); + } + if (!exactInserted.await(5, TimeUnit.SECONDS)) { + throw new AssertionError("exact admission did not win the race"); + } + return new GameplayCommandRepository.IdempotentInsertResult(winner, false); + }); ExecutorService executor = Executors.newFixedThreadPool(2); try { Future exact = - executor.submit( - () -> - AutomationGameplayCommandAdmissionSupport.admitIfAbsent( - automationRequest(), - gameInstanceRepository, - gameplayCommandRepository, - runtimeRegionStatusRepository, - tickService)); + executor.submit(() -> + AutomationGameplayCommandAdmissionSupport.admitIfAbsent( + automationRequest(), + gameInstanceRepository, + gameplayCommandRepository, + runtimeRegionStatusRepository, + tickService)); Future changed = - executor.submit( - () -> - AutomationGameplayCommandAdmissionSupport.admitIfAbsent( - changedAdmissionRequests()[0], - gameInstanceRepository, - gameplayCommandRepository, - runtimeRegionStatusRepository, - tickService)); + executor.submit(() -> + AutomationGameplayCommandAdmissionSupport.admitIfAbsent( + changedAdmissionRequests()[0], + gameInstanceRepository, + gameplayCommandRepository, + runtimeRegionStatusRepository, + tickService)); AdmissionResult exactResult = exact.get(5, TimeUnit.SECONDS); AdmissionResult changedResult = changed.get(5, TimeUnit.SECONDS); @@ -2056,16 +2043,12 @@ private static GameInstance automationInstance() { private static GameInstanceRepository mockGameInstanceRepository() { GameInstanceRepository repository = mock(GameInstanceRepository.class); when(repository.findByTenantIdAndGameInstanceIdForUpdate(anyLong(), anyLong())) - .thenAnswer( - invocation -> - repository - .findById(invocation.getArgument(1, Long.class)) - .filter( - instance -> - instance.getTenantId() != null - && instance - .getTenantId() - .equals(invocation.getArgument(0, Long.class)))); + .thenAnswer(invocation -> + repository + .findById(invocation.getArgument(1, Long.class)) + .filter(instance -> + instance.getTenantId() != null + && instance.getTenantId().equals(invocation.getArgument(0, Long.class)))); return repository; } @@ -2109,10 +2092,8 @@ private static AdmissionResult admitWithCurrentPointers( request.automationDispatchId())) .thenReturn(Optional.empty()); when(gameplayCommandRepository.insertIfAbsentByIdempotencyIdentity(any())) - .thenAnswer( - invocation -> - new GameplayCommandRepository.IdempotentInsertResult( - invocation.getArgument(0), true)); + .thenAnswer(invocation -> + new GameplayCommandRepository.IdempotentInsertResult(invocation.getArgument(0), true)); RuntimeRegionStatus ownership = new RuntimeRegionStatus(); ownership.setTenantId(request.tenantId()); ownership.setGameInstanceId(request.gameInstanceId()); @@ -2232,10 +2213,8 @@ void remoteAutomationRejectsStaleTargetRoutingInsteadOfReplacingIt() { when(pointerAuthority.listByRuntimeTarget(1L, 9L)) .thenReturn(List.of(targetPointer("target-world", "target-realm", 23L))); when(gameplayCommandRepository.insertIfAbsentByIdempotencyIdentity(any())) - .thenAnswer( - invocation -> - new GameplayCommandRepository.IdempotentInsertResult( - invocation.getArgument(0), true)); + .thenAnswer(invocation -> + new GameplayCommandRepository.IdempotentInsertResult(invocation.getArgument(0), true)); DurableRemoteFollowupExecutionService.DurableRemoteFollowupExecutionResult result = service.execute(effect); @@ -2262,10 +2241,8 @@ void remoteGameplayRejectsStaleTargetRoutingInsteadOfReplacingIt() { when(pointerAuthority.listByRuntimeTarget(1L, 9L)) .thenReturn(List.of(targetPointer("target-world", "target-realm", 23L))); when(gameplayCommandRepository.insertIfAbsentByIdempotencyIdentity(any())) - .thenAnswer( - invocation -> - new GameplayCommandRepository.IdempotentInsertResult( - invocation.getArgument(0), true)); + .thenAnswer(invocation -> + new GameplayCommandRepository.IdempotentInsertResult(invocation.getArgument(0), true)); DurableRemoteFollowupExecutionService.DurableRemoteFollowupExecutionResult result = service.execute(effect); @@ -2415,18 +2392,17 @@ void remoteTriggerScriptEventIsDisabledAndExactReplaySkipsPointerReread() { RemoteCommandCoordinator coordinator = commandCoordinator("trigger-followup"); configureTargetAdmission(followup, coordinator, "trigger"); when(remoteFollowupRuntimeService.recordResult(any())) - .thenAnswer( - invocation -> { - followup.setStatus(RemoteFollowupRuntimeServiceImpl.FOLLOWUP_ABANDONED); - followup.setFailureCode("REMOTE_SCRIPT_EVENT_PIN_TUPLE_UNAVAILABLE"); - followup.setFailureMessage( - "Legacy remote trigger delivery is disabled until durable source and target script pin tuples are available"); - return new RemoteFollowupRuntimeService.ResultOutcome( - RemoteFollowupRuntimeServiceImpl.COORDINATOR_REMOTE_ABANDONED, - RemoteFollowupRuntimeServiceImpl.FOLLOWUP_ABANDONED, - false, - false); - }); + .thenAnswer(invocation -> { + followup.setStatus(RemoteFollowupRuntimeServiceImpl.FOLLOWUP_ABANDONED); + followup.setFailureCode("REMOTE_SCRIPT_EVENT_PIN_TUPLE_UNAVAILABLE"); + followup.setFailureMessage( + "Legacy remote trigger delivery is disabled until durable source and target script pin tuples are available"); + return new RemoteFollowupRuntimeService.ResultOutcome( + RemoteFollowupRuntimeServiceImpl.COORDINATOR_REMOTE_ABANDONED, + RemoteFollowupRuntimeServiceImpl.FOLLOWUP_ABANDONED, + false, + false); + }); DurableRemoteFollowupExecutionService.DurableRemoteFollowupExecutionResult first = service.execute(effect); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisherTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisherTest.java index ff127124c2..3d835ec452 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisherTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisherTest.java @@ -51,10 +51,8 @@ void logsTerminalTriggerRejectionsSeparatelyAndKeepsPublisherBestEffort( .thenThrow(new StatusRuntimeException(Status.fromCode(code).withDescription("rejected"))); ScriptEventPublisher publisher = publisherForTriggerTest(client); - assertThatCode( - () -> - publisher.publishCommandEvent( - sharedGameplayContext("R-1"), command("cmd-1", "LOOK"))) + assertThatCode(() -> + publisher.publishCommandEvent(sharedGameplayContext("R-1"), command("cmd-1", "LOOK"))) .doesNotThrowAnyException(); String capturedOutput = output.getOut() + output.getErr(); @@ -75,10 +73,8 @@ void logsTransientTriggerFailureResponseWithoutAdmittingEvent(CapturedOutput out when(client.triggerScriptEvent(Mockito.any())).thenReturn(unavailableResponse); ScriptEventPublisher publisher = publisherForTriggerTest(client); - assertThatCode( - () -> - publisher.publishCommandEvent( - sharedGameplayContext("R-1"), command("cmd-1", "LOOK"))) + assertThatCode(() -> + publisher.publishCommandEvent(sharedGameplayContext("R-1"), command("cmd-1", "LOOK"))) .doesNotThrowAnyException(); assertThat(unavailableResponse.getAdmitted()).isFalse(); @@ -594,11 +590,10 @@ void publishesRegionTransitionEventsWithDeterministicIds() { .containsOnly("7"); assertThat(captor.getAllValues()) .extracting(TriggerScriptEventRequest::getPayloadJson) - .allSatisfy( - payload -> { - assertThat(payload).contains("\"fromRegionId\":\"R-101\""); - assertThat(payload).contains("\"toRegionId\":\"R-102\""); - }); + .allSatisfy(payload -> { + assertThat(payload).contains("\"fromRegionId\":\"R-101\""); + assertThat(payload).contains("\"toRegionId\":\"R-102\""); + }); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcServiceTest.java index 8d061135c9..7ded247c7c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameInstanceLaunchAssociationReadGrpcServiceTest.java @@ -76,11 +76,9 @@ void clearAmbientState() { @Test void missingPeerAndWrongWorkloadAreRejectedBeforeParsingOrStorage() { var missingPeer = new RecordingObserver(); - Context.ROOT.run( - () -> - service.getCanonicalGameInstanceLaunchAssociation( - GetCanonicalGameInstanceLaunchAssociationRequest.getDefaultInstance(), - missingPeer)); + Context.ROOT.run(() -> + service.getCanonicalGameInstanceLaunchAssociation( + GetCanonicalGameInstanceLaunchAssociationRequest.getDefaultInstance(), missingPeer)); assertDenied(missingPeer, Status.Code.UNAUTHENTICATED); assertDenied( @@ -466,19 +464,17 @@ private static CompleteLaunchBindingEvidence binding(long templateId) { null); var participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - owner, - "902", - false, - null, - "publish-commit-902", - "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), - "GAME_LOGIC".equals(owner), - "GAME_LOGIC".equals(owner) ? digest('d') : null)) + .map(owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + "902", + false, + null, + "publish-commit-902", + "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema(owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? digest('d') : null)) .toList(); var attestation = AuthoredWorldReleaseAttestationEvidence.create( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java index 410ec50769..ddb98af268 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalGameplayRosterReferenceGrpcMtlsTest.java @@ -109,10 +109,9 @@ void exactEntityCertificateReadsOnlyPersistedOriginalAndMissingOperationsStayUna .CanonicalGameplayRosterReferenceRepository.OriginalUnavailableException()); assertThatThrownBy(() -> stub(channel.channel()).getCanonicalGameplayRosterReference(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); } } @@ -199,24 +198,23 @@ void authenticatedReferenceReadUsesActualOwnerCurrentSourceMismatchBoundary() th any( net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence.Request .class))) - .thenAnswer( - call -> { - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isActualTransactionActive()) - .isFalse(); - assertThat( - org.springframework.transaction.support.TransactionSynchronizationManager - .isSynchronizationActive()) - .isFalse(); - var evidence = - mock( - net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence - .class); - when(evidence.request()).thenReturn(call.getArgument(0)); - when(evidence.admissionPointerSnapshotDigest()).thenReturn("0".repeat(64)); - return evidence; - }); + .thenAnswer(call -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + .isFalse(); + var evidence = + mock( + net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence + .class); + when(evidence.request()).thenReturn(call.getArgument(0)); + when(evidence.admissionPointerSnapshotDigest()).thenReturn("0".repeat(64)); + return evidence; + }); // Real owner comparison and authenticated handler; repositories/source remain controlled // doubles. This does not establish SQL or genuine upstream source custody. var actualOwner = @@ -268,11 +266,10 @@ void authenticatedInvalidOwnerResponseDiffersFromMalformedCallerRequest() throws failure -> assertThat(failure.getStatus().getCode()) .isEqualTo(Status.Code.FAILED_PRECONDITION)); - assertThatThrownBy( - () -> - stub(channel.channel()) - .getCanonicalGameplayRosterReference( - request.toBuilder().setSchemaVersion(2).build())) + assertThatThrownBy(() -> + stub(channel.channel()) + .getCanonicalGameplayRosterReference( + request.toBuilder().setSchemaVersion(2).build())) .isInstanceOfSatisfying( StatusRuntimeException.class, failure -> @@ -304,10 +301,9 @@ void foreignNamespaceAndWrongServiceCertificatesCannotReachOriginalOwner() throw assertThatThrownBy( () -> stub(channel.channel()).getCanonicalGameplayRosterReference(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } } verifyNoInteractions(owner); @@ -320,10 +316,9 @@ void foreignGameSessionServerCertificateIsRejectedBeforeOriginalOwnerAccess() th assertThatThrownBy( () -> stub(channel.channel()).getCanonicalGameplayRosterReference(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); } verifyNoInteractions(owner); } @@ -351,38 +346,31 @@ void authenticatedRetirementAckAndConfirmationUseExactPeerAndValidateResponse() .thenReturn(ack.toBuilder().setObservationUuid(UUID.randomUUID().toString()).build()); assertThatThrownBy( () -> stub(channel.channel()).acknowledgeCanonicalGameplayRosterRetirement(request)) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); - assertThatThrownBy( - () -> - stub(channel.channel()) - .acknowledgeCanonicalGameplayRosterRetirement( - request.toBuilder().setSchemaVersion(2).build())) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.INVALID_ARGUMENT)); - assertThatThrownBy( - () -> - stub(channel.channel()) - .confirmCanonicalGameplayRosterRetirementAcknowledgement( - confirmation.toBuilder().setSchemaVersion(2).build())) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.INVALID_ARGUMENT)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + assertThatThrownBy(() -> + stub(channel.channel()) + .acknowledgeCanonicalGameplayRosterRetirement( + request.toBuilder().setSchemaVersion(2).build())) + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT)); + assertThatThrownBy(() -> + stub(channel.channel()) + .confirmCanonicalGameplayRosterRetirementAcknowledgement( + confirmation.toBuilder().setSchemaVersion(2).build())) + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT)); when(owner.confirmRetirementAcknowledgement(confirmation, principal)) .thenReturn(confirmed.toBuilder().setRequestDigest("f".repeat(64)).build()); - assertThatThrownBy( - () -> - stub(channel.channel()) - .confirmCanonicalGameplayRosterRetirementAcknowledgement(confirmation)) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + assertThatThrownBy(() -> + stub(channel.channel()) + .confirmCanonicalGameplayRosterRetirementAcknowledgement(confirmation)) + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); var cases = List.of( java.util.Map.entry( @@ -404,18 +392,13 @@ void authenticatedRetirementAckAndConfirmationUseExactPeerAndValidateResponse() .confirmRetirementAcknowledgement(confirmation, principal); assertThatThrownBy( () -> stub(channel.channel()).acknowledgeCanonicalGameplayRosterRetirement(request)) - .satisfies( - result -> - assertThat(Status.fromThrowable(result).getCode()) - .isEqualTo(failure.getValue())); - assertThatThrownBy( - () -> - stub(channel.channel()) - .confirmCanonicalGameplayRosterRetirementAcknowledgement(confirmation)) - .satisfies( - result -> - assertThat(Status.fromThrowable(result).getCode()) - .isEqualTo(failure.getValue())); + .satisfies(result -> + assertThat(Status.fromThrowable(result).getCode()).isEqualTo(failure.getValue())); + assertThatThrownBy(() -> + stub(channel.channel()) + .confirmCanonicalGameplayRosterRetirementAcknowledgement(confirmation)) + .satisfies(result -> + assertThat(Status.fromThrowable(result).getCode()).isEqualTo(failure.getValue())); } } } @@ -432,18 +415,15 @@ void retirementTransfersDenyWrongWorkloadAndNamespaceBeforeOwner() throws Except try (var channel = channel(identity)) { assertThatThrownBy( () -> stub(channel.channel()).acknowledgeCanonicalGameplayRosterRetirement(request)) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); - assertThatThrownBy( - () -> - stub(channel.channel()) - .confirmCanonicalGameplayRosterRetirementAcknowledgement(confirmation)) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + assertThatThrownBy(() -> + stub(channel.channel()) + .confirmCanonicalGameplayRosterRetirementAcknowledgement(confirmation)) + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } } verifyNoInteractions(owner); @@ -460,18 +440,15 @@ void missingTransferOwnerStaysUnavailableForBothMethods() throws Exception { try (var channel = channel("entity")) { assertThatThrownBy( () -> stub(channel.channel()).acknowledgeCanonicalGameplayRosterRetirement(request)) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); - assertThatThrownBy( - () -> - stub(channel.channel()) - .confirmCanonicalGameplayRosterRetirementAcknowledgement(confirmation)) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); + assertThatThrownBy(() -> + stub(channel.channel()) + .confirmCanonicalGameplayRosterRetirementAcknowledgement(confirmation)) + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); } verifyNoInteractions(owner); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java index c54efdcfa5..585aebd94b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java @@ -1545,11 +1545,10 @@ private CommandServiceImpl newCommandService( private RuntimeRegionStatusRepository defaultRuntimeRegionStatusRepository() { RuntimeRegionStatusRepository repository = Mockito.mock(RuntimeRegionStatusRepository.class); Mockito.when(repository.findByTenantIdAndGameInstanceId(Mockito.anyLong(), Mockito.anyLong())) - .thenAnswer( - invocation -> - Optional.of( - runtimeRegionStatus( - Long.toString(invocation.getArgument(1, Long.class)), 1L, false))); + .thenAnswer(invocation -> + Optional.of( + runtimeRegionStatus( + Long.toString(invocation.getArgument(1, Long.class)), 1L, false))); return repository; } @@ -1567,16 +1566,15 @@ private GameplayCommandRepository commandRepositorySavingArgument() { GameplayCommandRepository repository = Mockito.mock(GameplayCommandRepository.class); AtomicLong idSequence = new AtomicLong(); Mockito.when(repository.save(Mockito.any(GameplayCommand.class))) - .thenAnswer( - invocation -> { - GameplayCommand command = invocation.getArgument(0); - if (command.getId() == null) { - long id = idSequence.incrementAndGet(); - command.setId(id); - command.setEnqueueSeq(id); - } - return command; - }); + .thenAnswer(invocation -> { + GameplayCommand command = invocation.getArgument(0); + if (command.getId() == null) { + long id = idSequence.incrementAndGet(); + command.setId(id); + command.setEnqueueSeq(id); + } + return command; + }); return repository; } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index a22b4573f2..154c44baa4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -129,12 +129,11 @@ void upsertPointerAllowsCreateWhenExpectedVersionPairIsZero() { 1L, "demo", "production")) .thenReturn(Optional.empty()); when(pointerRepository.save(any(GameplayAdmissionPointer.class))) - .thenAnswer( - invocation -> { - GameplayAdmissionPointer pointer = invocation.getArgument(0); - pointer.setId(11L); - return pointer; - }); + .thenAnswer(invocation -> { + GameplayAdmissionPointer pointer = invocation.getArgument(0); + pointer.setId(11L); + return pointer; + }); when(eventRepository.save(any(GameplayAdmissionPointerEvent.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -560,22 +559,20 @@ void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { 7L, "demo", "production")) .thenAnswer(invocation -> Optional.ofNullable(currentPointer.get())); when(pointerRepository.save(any(GameplayAdmissionPointer.class))) - .thenAnswer( - invocation -> { - GameplayAdmissionPointer pointer = invocation.getArgument(0); - if (pointer.getId() == null) { - pointer.setId(11L); - } - currentPointer.set(pointer); - return pointer; - }); + .thenAnswer(invocation -> { + GameplayAdmissionPointer pointer = invocation.getArgument(0); + if (pointer.getId() == null) { + pointer.setId(11L); + } + currentPointer.set(pointer); + return pointer; + }); when(pointerRepository.updateExisting(any(GameplayAdmissionPointer.class), any(), any())) - .thenAnswer( - invocation -> { - GameplayAdmissionPointer pointer = invocation.getArgument(0); - currentPointer.set(pointer); - return pointer; - }); + .thenAnswer(invocation -> { + GameplayAdmissionPointer pointer = invocation.getArgument(0); + currentPointer.set(pointer); + return pointer; + }); when(eventRepository.save(any(GameplayAdmissionPointerEvent.class))) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -604,29 +601,27 @@ void concurrentSameTransitionWinnerPreventsDuplicateAuditForStaleExpectedRevisio java.util.concurrent.atomic.AtomicReference current = new java.util.concurrent.atomic.AtomicReference<>(existingPointerForTenant(7L)); when(pointerRepository.updateExisting(any(GameplayAdmissionPointer.class), any(), any())) - .thenAnswer( - invocation -> { - GameplayAdmissionPointer requested = invocation.getArgument(0); - Long expectedPointerVersion = invocation.getArgument(1); - Long expectedCatalogRevision = invocation.getArgument(2); - GameplayAdmissionPointer committed = current.get(); - if (!java.util.Objects.equals(committed.getPointerVersion(), expectedPointerVersion) - || !java.util.Objects.equals( - committed.getCatalogRevision(), expectedCatalogRevision)) { - throw new AdmissionPointerVersionMismatchException( - "Admission pointer changed before the requested version could be committed"); - } - current.set(requested); - return requested; - }); + .thenAnswer(invocation -> { + GameplayAdmissionPointer requested = invocation.getArgument(0); + Long expectedPointerVersion = invocation.getArgument(1); + Long expectedCatalogRevision = invocation.getArgument(2); + GameplayAdmissionPointer committed = current.get(); + if (!java.util.Objects.equals(committed.getPointerVersion(), expectedPointerVersion) + || !java.util.Objects.equals( + committed.getCatalogRevision(), expectedCatalogRevision)) { + throw new AdmissionPointerVersionMismatchException( + "Admission pointer changed before the requested version could be committed"); + } + current.set(requested); + return requested; + }); java.util.List events = new java.util.ArrayList<>(); when(eventRepository.save(any(GameplayAdmissionPointerEvent.class))) - .thenAnswer( - invocation -> { - GameplayAdmissionPointerEvent event = invocation.getArgument(0); - events.add(event); - return event; - }); + .thenAnswer(invocation -> { + GameplayAdmissionPointerEvent event = invocation.getArgument(0); + events.add(event); + return event; + }); GameplayAdmissionPointerSnapshot winner = service.upsertPointer(pointerMutation(45L, false, 1L, 1L, "concurrent-winner")); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java index 712ea4c73e..66deb9f999 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java @@ -83,22 +83,21 @@ void setUp() { commandId -> builtInMetadataResolver .resolve(commandId) - .or( - () -> - "wave".equalsIgnoreCase(commandId) - || "wave-salute".equalsIgnoreCase(commandId) + .or(() -> + "wave".equalsIgnoreCase(commandId) + || "wave-salute".equalsIgnoreCase(commandId) + ? Optional.of( + new TextCommandMetadataResolver.ResolvedTextCommandMetadata( + TextCommandDispatchGroup.AUTHORED, + TextCommandActionCategory.SOCIAL, + java.util.List.of(TextCommandActionTag.COMMUNICATION))) + : "taunt".equalsIgnoreCase(commandId) ? Optional.of( new TextCommandMetadataResolver.ResolvedTextCommandMetadata( - TextCommandDispatchGroup.AUTHORED, - TextCommandActionCategory.SOCIAL, - java.util.List.of(TextCommandActionTag.COMMUNICATION))) - : "taunt".equalsIgnoreCase(commandId) - ? Optional.of( - new TextCommandMetadataResolver.ResolvedTextCommandMetadata( - TextCommandDispatchGroup.ACTIVITY, - TextCommandActionCategory.GAMEPLAY, - java.util.List.of(TextCommandActionTag.COMBAT))) - : Optional.empty()), + TextCommandDispatchGroup.ACTIVITY, + TextCommandActionCategory.GAMEPLAY, + java.util.List.of(TextCommandActionTag.COMBAT))) + : Optional.empty()), durableGameplayReplayService, movementEffectIdempotencyService, playerOutputDeliveryService, @@ -910,22 +909,22 @@ void executeRejectsAuthoredSnapshotAboveTheSharedDurationLimitBeforeReplay() { private String authoredActionEffectsJson() { return """ - [{ - "effectKind": "APPLY_ACTION_STATE", - "schemaVersion": 1, - "targeting": "SELF", - "replayPolicy": "EFFECT_IDEMPOTENT", - "payload": { - "conditionKey": "SALUTING", - "durationSeconds": 30, - "effectPayload": { - "modifiers": [ - {"operation": "ADD", "target_key": "block_mitigation", "value": 1} - ] - } - } - }] - """; + [{ + "effectKind": "APPLY_ACTION_STATE", + "schemaVersion": 1, + "targeting": "SELF", + "replayPolicy": "EFFECT_IDEMPOTENT", + "payload": { + "conditionKey": "SALUTING", + "durationSeconds": 30, + "effectPayload": { + "modifiers": [ + {"operation": "ADD", "target_key": "block_mitigation", "value": 1} + ] + } + } + }] + """; } private GameplayCommand gameplayCommand(String commandName, String commandText) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableRemoteFollowupExecutionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableRemoteFollowupExecutionServiceTest.java index 06068788d1..c07bb77c57 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableRemoteFollowupExecutionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableRemoteFollowupExecutionServiceTest.java @@ -267,10 +267,8 @@ void executeEnqueuesAutomationCommandForSupportedPayloadKind() { .thenReturn(Optional.empty()); when(gameplayCommandRepository.insertIfAbsentByIdempotencyIdentity( org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> - new GameplayCommandRepository.IdempotentInsertResult( - invocation.getArgument(0), true)); + .thenAnswer(invocation -> + new GameplayCommandRepository.IdempotentInsertResult(invocation.getArgument(0), true)); DurableRemoteFollowupExecutionService.DurableRemoteFollowupExecutionResult result = service.execute(effect); @@ -442,19 +440,17 @@ private static Stream incompleteScopeMutations() { "targetRegionEpoch.zero", followup -> followup.setTargetRegionEpoch(0L), coordinator -> coordinator.setTargetRegionEpoch(0L))) - .flatMap( - mutation -> - Stream.of( - Arguments.of( - "followup." + mutation.name(), - (ScopeMutator) - (followup, coordinator) -> - mutation.followupMutation().accept(followup)), - Arguments.of( - "coordinator." + mutation.name(), - (ScopeMutator) - (followup, coordinator) -> - mutation.coordinatorMutation().accept(coordinator)))); + .flatMap(mutation -> + Stream.of( + Arguments.of( + "followup." + mutation.name(), + (ScopeMutator) + (followup, coordinator) -> mutation.followupMutation().accept(followup)), + Arguments.of( + "coordinator." + mutation.name(), + (ScopeMutator) + (followup, coordinator) -> + mutation.coordinatorMutation().accept(coordinator)))); } private static ScopeMutation scopeMutation( @@ -537,10 +533,8 @@ void executeUsesDurablePayloadAuthorityWhenPayloadJsonIsMalformed() { .thenReturn(Optional.empty()); when(gameplayCommandRepository.insertIfAbsentByIdempotencyIdentity( org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> - new GameplayCommandRepository.IdempotentInsertResult( - invocation.getArgument(0), true)); + .thenAnswer(invocation -> + new GameplayCommandRepository.IdempotentInsertResult(invocation.getArgument(0), true)); DurableRemoteFollowupExecutionService.DurableRemoteFollowupExecutionResult result = service.execute(effect); @@ -982,10 +976,8 @@ void executeRejectsConflictingDurableGameplayRowAndPayloadJson() { .thenReturn(Optional.empty()); when(gameplayCommandRepository.insertIfAbsentByIdempotencyIdentity( org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> - new GameplayCommandRepository.IdempotentInsertResult( - invocation.getArgument(0), true)); + .thenAnswer(invocation -> + new GameplayCommandRepository.IdempotentInsertResult(invocation.getArgument(0), true)); DurableRemoteFollowupExecutionService.DurableRemoteFollowupExecutionResult result = service.execute(effect); @@ -1211,10 +1203,8 @@ void executeEnqueuesAutomationCommandUsingRegionScopedOwnershipAuthority() { .thenReturn(Optional.empty()); when(gameplayCommandRepository.insertIfAbsentByIdempotencyIdentity( org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> - new GameplayCommandRepository.IdempotentInsertResult( - invocation.getArgument(0), true)); + .thenAnswer(invocation -> + new GameplayCommandRepository.IdempotentInsertResult(invocation.getArgument(0), true)); DurableRemoteFollowupExecutionService.DurableRemoteFollowupExecutionResult result = service.execute(effect); @@ -1287,10 +1277,8 @@ void executeEnqueuesGameplayCommandForSupportedPayloadKind() { .thenReturn(Optional.empty()); when(gameplayCommandRepository.insertIfAbsentByIdempotencyIdentity( org.mockito.ArgumentMatchers.any())) - .thenAnswer( - invocation -> - new GameplayCommandRepository.IdempotentInsertResult( - invocation.getArgument(0), true)); + .thenAnswer(invocation -> + new GameplayCommandRepository.IdempotentInsertResult(invocation.getArgument(0), true)); DurableRemoteFollowupExecutionService.DurableRemoteFollowupExecutionResult result = service.execute(effect); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java index bd16af4c2b..fa2bc298d4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java @@ -453,22 +453,20 @@ void runOwnedInitialLaunchRetryReconcilesAmbiguousPrepareOnTheSameInstance() { anyString(), anyLong(), any())) - .thenAnswer( - invocation -> { - if (prepareCalls.getAndIncrement() == 0) { - worldState.set( - runOwnedWorldSnapshot( - request, - invocation.getArgument(1, Long.class), - 1L, - WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING)); - throw new IllegalStateException("prepare response timed out"); - } - return net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse - .newBuilder() - .setWorldInstance(worldState.get()) - .build(); - }); + .thenAnswer(invocation -> { + if (prepareCalls.getAndIncrement() == 0) { + worldState.set( + runOwnedWorldSnapshot( + request, + invocation.getArgument(1, Long.class), + 1L, + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING)); + throw new IllegalStateException("prepare response timed out"); + } + return net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse.newBuilder() + .setWorldInstance(worldState.get()) + .build(); + }); IllegalStateException pending = assertThrows( @@ -669,14 +667,13 @@ void runOwnedInitialLaunchRejectsWorldDescriptorMismatchAndRetainsIdentity() { new StartSessionRequest( 1L, 3L, RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), 42L); AtomicReference worldState = configureRunOwnedWorld(request); - doAnswer( - invocation -> - GetWorldInstanceLifecycleResponse.newBuilder() - .setWorldInstance( - worldState.get().toBuilder() - .setPublishedReleaseBundleRef("prb:1:11:78") - .build()) - .build()) + doAnswer(invocation -> + GetWorldInstanceLifecycleResponse.newBuilder() + .setWorldInstance( + worldState.get().toBuilder() + .setPublishedReleaseBundleRef("prb:1:11:78") + .build()) + .build()) .when(worldManagementClient) .getWorldInstanceLifecycle(anyLong(), anyLong()); @@ -1675,57 +1672,52 @@ void stopSessionRejectsKnownNonActiveWorldLifecycle(WorldInstanceLifecycleStatus private void configureRepositoryPersistence() { when(repository.save(any(GameInstance.class))) - .thenAnswer( - invocation -> { - GameInstance input = invocation.getArgument(0); - if (input.getId() == null) { - input.setId(nextId.getAndIncrement()); - } - store.put(input.getId(), copyOf(input)); - return input; - }); + .thenAnswer(invocation -> { + GameInstance input = invocation.getArgument(0); + if (input.getId() == null) { + input.setId(nextId.getAndIncrement()); + } + store.put(input.getId(), copyOf(input)); + return input; + }); when(repository.findById(any(Long.class))) - .thenAnswer( - invocation -> { - Long id = invocation.getArgument(0); - GameInstance stored = store.get(id); - return stored == null ? Optional.empty() : Optional.of(copyOf(stored)); - }); + .thenAnswer(invocation -> { + Long id = invocation.getArgument(0); + GameInstance stored = store.get(id); + return stored == null ? Optional.empty() : Optional.of(copyOf(stored)); + }); when(repository.findByTenantIdAndRunOwnedStartRequestIdForUpdate(anyLong(), anyString())) - .thenAnswer( - invocation -> { - Long tenantId = invocation.getArgument(0); - String requestId = invocation.getArgument(1); - return store.values().stream() - .filter(instance -> tenantId.equals(instance.getTenantId())) - .filter(instance -> requestId.equals(instance.getRunOwnedStartRequestId())) - .findFirst() - .map(GameInstanceServiceImplTest::copyOf); - }); + .thenAnswer(invocation -> { + Long tenantId = invocation.getArgument(0); + String requestId = invocation.getArgument(1); + return store.values().stream() + .filter(instance -> tenantId.equals(instance.getTenantId())) + .filter(instance -> requestId.equals(instance.getRunOwnedStartRequestId())) + .findFirst() + .map(GameInstanceServiceImplTest::copyOf); + }); when(repository.findByTenantIdAndGameInstanceIdForUpdate(anyLong(), anyLong())) - .thenAnswer( - invocation -> { - Long tenantId = invocation.getArgument(0); - Long gameInstanceId = invocation.getArgument(1); - GameInstance stored = store.get(gameInstanceId); - return stored != null && tenantId.equals(stored.getTenantId()) - ? Optional.of(copyOf(stored)) - : Optional.empty(); - }); + .thenAnswer(invocation -> { + Long tenantId = invocation.getArgument(0); + Long gameInstanceId = invocation.getArgument(1); + GameInstance stored = store.get(gameInstanceId); + return stored != null && tenantId.equals(stored.getTenantId()) + ? Optional.of(copyOf(stored)) + : Optional.empty(); + }); when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus( any(Long.class), any(Long.class), any())) - .thenAnswer( - invocation -> { - Long tenantId = invocation.getArgument(0); - Long ownerAccountId = invocation.getArgument(1); - String status = invocation.getArgument(2); - return store.values().stream() - .filter(instance -> tenantId.equals(instance.getTenantId())) - .filter(instance -> ownerAccountId.equals(instance.getOwnerAccountId())) - .filter(instance -> status.equals(instance.getStatus())) - .findFirst() - .map(GameInstanceServiceImplTest::copyOf); - }); + .thenAnswer(invocation -> { + Long tenantId = invocation.getArgument(0); + Long ownerAccountId = invocation.getArgument(1); + String status = invocation.getArgument(2); + return store.values().stream() + .filter(instance -> tenantId.equals(instance.getTenantId())) + .filter(instance -> ownerAccountId.equals(instance.getOwnerAccountId())) + .filter(instance -> status.equals(instance.getStatus())) + .findFirst() + .map(GameInstanceServiceImplTest::copyOf); + }); org.mockito.Mockito.doAnswer( invocation -> { Long id = invocation.getArgument(0); @@ -1763,45 +1755,43 @@ private GameInstanceDto configureMappedDto(GameInstance entity) { private void configureLaunchPreflight() { when(gameDesignClient.resolveLaunchDescriptor(any(Long.class), any(Long.class), any())) - .thenAnswer( - invocation -> - ResolveLaunchDescriptorResponse.newBuilder() - .setLaunchDescriptor( - net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() - .setLaunchDescriptorId("ld-" + invocation.getArgument(2, String.class)) - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameTemplateId(invocation.getArgument(1, Long.class)) - .setControlPlaneRequestId(invocation.getArgument(2, String.class)) - .setVersionId(11L) - .setRuntimeFlagsJson("{}") - .setGenerationConfigRevision("genrev-11") - .setVersionStateEpoch(77L) - .setReleaseBundleId(77L) - .setPublishedReleaseBundleRef(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF) - .build()) - .build()); + .thenAnswer(invocation -> + ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor( + net.firedevops.firemud.gamedesign.v1.LaunchDescriptor.newBuilder() + .setLaunchDescriptorId("ld-" + invocation.getArgument(2, String.class)) + .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) + .setGameTemplateId(invocation.getArgument(1, Long.class)) + .setControlPlaneRequestId(invocation.getArgument(2, String.class)) + .setVersionId(11L) + .setRuntimeFlagsJson("{}") + .setGenerationConfigRevision("genrev-11") + .setVersionStateEpoch(77L) + .setReleaseBundleId(77L) + .setPublishedReleaseBundleRef(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF) + .build()) + .build()); when(gameDesignClient.resolveLaunchDescriptor( any(Long.class), any(Long.class), anyString(), any(AuthoredWorldSourceEvidence.class))) - .thenAnswer( - invocation -> { - long tenantId = invocation.getArgument(0, Long.class); - long gameTemplateId = invocation.getArgument(1, Long.class); - String controlPlaneRequestId = invocation.getArgument(2, String.class); - AuthoredWorldSourceEvidence sourceEvidence = invocation.getArgument(3); - LaunchDescriptor descriptor = runOwnedDescriptorOverride; - if (descriptor == null) { - descriptor = - RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( - new StartSessionRequest( - tenantId, gameTemplateId, controlPlaneRequestId, 42L), - sourceEvidence, - runOwnedBundleRef(tenantId)) - .launchDescriptor(); - } - return ResolveLaunchDescriptorResponse.newBuilder() - .setLaunchDescriptor(descriptor) - .build(); - }); + .thenAnswer(invocation -> { + long tenantId = invocation.getArgument(0, Long.class); + long gameTemplateId = invocation.getArgument(1, Long.class); + String controlPlaneRequestId = invocation.getArgument(2, String.class); + AuthoredWorldSourceEvidence sourceEvidence = invocation.getArgument(3); + LaunchDescriptor descriptor = runOwnedDescriptorOverride; + if (descriptor == null) { + descriptor = + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( + new StartSessionRequest( + tenantId, gameTemplateId, controlPlaneRequestId, 42L), + sourceEvidence, + runOwnedBundleRef(tenantId)) + .launchDescriptor(); + } + return ResolveLaunchDescriptorResponse.newBuilder() + .setLaunchDescriptor(descriptor) + .build(); + }); when(gameDesignClient.getPublishedReleaseBundle(any(Long.class), any(Long.class))) .thenReturn( GetPublishedReleaseBundleResponse.newBuilder() @@ -2176,106 +2166,93 @@ private void configureWorldActivation() { anyString(), anyLong(), any())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse.newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setGameTemplateId("3") - .setControlPlaneRequestId("cp") - .setLaunchDescriptorId("ld-cp") - .setVersionId("11") - .setReleaseBundleId("77") - .setGenerationConfigRevision("genrev-11") - .setPublishedReleaseBundleRef(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF) - .setVersionStateEpoch(77L) - .setLifecycleEpoch(1L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) - .build()) - .build()); + .thenAnswer(invocation -> + net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse.newBuilder() + .setWorldInstance( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot + .newBuilder() + .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) + .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) + .setGameTemplateId("3") + .setControlPlaneRequestId("cp") + .setLaunchDescriptorId("ld-cp") + .setVersionId("11") + .setReleaseBundleId("77") + .setGenerationConfigRevision("genrev-11") + .setPublishedReleaseBundleRef(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF) + .setVersionStateEpoch(77L) + .setLifecycleEpoch(1L) + .setStatus( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus + .WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) + .build()) + .build()); when(worldManagementClient.activatePreparedWorldInstance(anyLong(), anyLong(), anyLong())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse - .newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setGameTemplateId("3") - .setControlPlaneRequestId("cp") - .setLaunchDescriptorId("ld-cp") - .setVersionId("11") - .setReleaseBundleId("77") - .setGenerationConfigRevision("genrev-11") - .setPublishedReleaseBundleRef(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF) - .setVersionStateEpoch(77L) - .setLifecycleEpoch(2L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) - .build()) - .build()); + .thenAnswer(invocation -> + net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse + .newBuilder() + .setWorldInstance( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot + .newBuilder() + .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) + .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) + .setGameTemplateId("3") + .setControlPlaneRequestId("cp") + .setLaunchDescriptorId("ld-cp") + .setVersionId("11") + .setReleaseBundleId("77") + .setGenerationConfigRevision("genrev-11") + .setPublishedReleaseBundleRef(OPAQUE_PUBLISHED_RELEASE_BUNDLE_REF) + .setVersionStateEpoch(77L) + .setLifecycleEpoch(2L) + .setStatus( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus + .WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) + .build()) + .build()); when(worldManagementClient.failPreparedWorldInstance(anyLong(), anyLong(), anyLong(), any())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.FailPreparedWorldInstanceResponse - .newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setLifecycleEpoch(2L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_FAILED_PRE_ACTIVATION) - .build()) - .build()); + .thenAnswer(invocation -> + net.firedevops.firemud.worldmanagement.v1.FailPreparedWorldInstanceResponse.newBuilder() + .setWorldInstance( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot + .newBuilder() + .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) + .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) + .setLifecycleEpoch(2L) + .setStatus( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus + .WORLD_INSTANCE_LIFECYCLE_STATUS_FAILED_PRE_ACTIVATION) + .build()) + .build()); when(worldManagementClient.getWorldInstanceLifecycle(anyLong(), anyLong())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse - .newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setLifecycleEpoch(2L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) - .build()) - .build()); + .thenAnswer(invocation -> + net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse.newBuilder() + .setWorldInstance( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot + .newBuilder() + .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) + .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) + .setLifecycleEpoch(2L) + .setStatus( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus + .WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) + .build()) + .build()); when(worldManagementClient.terminateWorldInstance( anyLong(), anyLong(), anyLong(), anyString(), anyString())) - .thenAnswer( - invocation -> - net.firedevops.firemud.worldmanagement.v1.TerminateWorldInstanceResponse - .newBuilder() - .setWorldInstance( - net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot - .newBuilder() - .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) - .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) - .setLifecycleEpoch(4L) - .setStatus( - net.firedevops.firemud.worldmanagement.v1 - .WorldInstanceLifecycleStatus - .WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATED) - .build()) - .build()); + .thenAnswer(invocation -> + net.firedevops.firemud.worldmanagement.v1.TerminateWorldInstanceResponse.newBuilder() + .setWorldInstance( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot + .newBuilder() + .setTenantId(Long.toString(invocation.getArgument(0, Long.class))) + .setGameInstanceId(Long.toString(invocation.getArgument(1, Long.class))) + .setLifecycleEpoch(4L) + .setStatus( + net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus + .WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATED) + .build()) + .build()); } private AtomicReference configureRunOwnedWorld( @@ -2295,43 +2272,40 @@ private AtomicReference configureRunOwnedWorld( anyString(), anyLong(), any())) - .thenAnswer( - invocation -> { - if (worldState.get() == null) { - worldState.set( - runOwnedWorldSnapshot( - request, - invocation.getArgument(1, Long.class), - 1L, - WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING, - runOwnedBundleRef(request.tenantId()))); - } - return PrepareWorldInstanceResponse.newBuilder() - .setWorldInstance(worldState.get()) - .build(); - }); + .thenAnswer(invocation -> { + if (worldState.get() == null) { + worldState.set( + runOwnedWorldSnapshot( + request, + invocation.getArgument(1, Long.class), + 1L, + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING, + runOwnedBundleRef(request.tenantId()))); + } + return PrepareWorldInstanceResponse.newBuilder() + .setWorldInstance(worldState.get()) + .build(); + }); when(worldManagementClient.getWorldInstanceLifecycle(anyLong(), anyLong())) - .thenAnswer( - invocation -> - GetWorldInstanceLifecycleResponse.newBuilder() - .setWorldInstance(worldState.get()) - .build()); + .thenAnswer(invocation -> + GetWorldInstanceLifecycleResponse.newBuilder() + .setWorldInstance(worldState.get()) + .build()); when(worldManagementClient.activatePreparedWorldInstance(anyLong(), anyLong(), anyLong())) - .thenAnswer( - invocation -> { - WorldInstanceLifecycleSnapshot active = - runOwnedWorldSnapshot( - request, - invocation.getArgument(1, Long.class), - invocation.getArgument(2, Long.class) + 1L, - WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE, - runOwnedBundleRef(request.tenantId())); - worldState.set(active); - return net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse - .newBuilder() - .setWorldInstance(active) - .build(); - }); + .thenAnswer(invocation -> { + WorldInstanceLifecycleSnapshot active = + runOwnedWorldSnapshot( + request, + invocation.getArgument(1, Long.class), + invocation.getArgument(2, Long.class) + 1L, + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE, + runOwnedBundleRef(request.tenantId())); + worldState.set(active); + return net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse + .newBuilder() + .setWorldInstance(active) + .build(); + }); return worldState; } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index 7b8dac5a44..a848c574fc 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -136,45 +136,43 @@ private static GameDesignClient gameDesignClient() { Mockito.when( client.getPublishedScriptPatchVersion( Mockito.anyLong(), Mockito.anyString(), Mockito.anyLong())) - .thenAnswer( - invocation -> { - long requestedBaseVersionId = invocation.getArgument(2, Long.class); - if (requestedBaseVersionId <= 0L) { - throw new AssertionError( - "Game Design must not be called without an exact positive patch base"); - } - return GetPublishedScriptPatchVersionResponse.newBuilder() - .setScriptPatch( - PublishedScriptPatchVersion.newBuilder() - .setTenantId("1") - .setScriptPatchVersion(invocation.getArgument(1, String.class)) - .setVersionId(17L) - .setBaseVersionId(requestedBaseVersionId) - .setPublicationState( - net.firedevops.firemud.gamedesign.v1.VersionLifecycleState - .VERSION_LIFECYCLE_STATE_PUBLISHED) - .setLastChangedAtMs(150L) - .build()) - .build(); - }); + .thenAnswer(invocation -> { + long requestedBaseVersionId = invocation.getArgument(2, Long.class); + if (requestedBaseVersionId <= 0L) { + throw new AssertionError( + "Game Design must not be called without an exact positive patch base"); + } + return GetPublishedScriptPatchVersionResponse.newBuilder() + .setScriptPatch( + PublishedScriptPatchVersion.newBuilder() + .setTenantId("1") + .setScriptPatchVersion(invocation.getArgument(1, String.class)) + .setVersionId(17L) + .setBaseVersionId(requestedBaseVersionId) + .setPublicationState( + net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_PUBLISHED) + .setLastChangedAtMs(150L) + .build()) + .build(); + }); Mockito.when( client.getPublishedPluginVersion( Mockito.anyLong(), Mockito.anyString(), Mockito.anyString())) - .thenAnswer( - invocation -> - GetPublishedPluginVersionResponse.newBuilder() - .setPluginVersion( - PublishedPluginVersion.newBuilder() - .setPluginId(invocation.getArgument(1)) - .setPluginVersionId(invocation.getArgument(2)) - .setPublicationId(31L) - .setPublicationState( - net.firedevops.firemud.gamedesign.v1.VersionLifecycleState - .VERSION_LIFECYCLE_STATE_PUBLISHED) - .setStatusReason("signature_verified") - .setLastChangedAtMs(275L) - .build()) - .build()); + .thenAnswer(invocation -> + GetPublishedPluginVersionResponse.newBuilder() + .setPluginVersion( + PublishedPluginVersion.newBuilder() + .setPluginId(invocation.getArgument(1)) + .setPluginVersionId(invocation.getArgument(2)) + .setPublicationId(31L) + .setPublicationState( + net.firedevops.firemud.gamedesign.v1.VersionLifecycleState + .VERSION_LIFECYCLE_STATE_PUBLISHED) + .setStatusReason("signature_verified") + .setLastChangedAtMs(275L) + .build()) + .build()); return client; } @@ -6423,22 +6421,21 @@ void getRemoteFollowupResultCollapsesPartialCurrentRuntimeRoutingBundleAndMarksS Mockito.when( gameplayAdmissionPointerAuthorityService.listByRuntimeTarget( Mockito.eq(1L), Mockito.anyLong())) - .thenAnswer( - invocation -> - List.of( - new GameplayAdmissionPointerSnapshot( - "partial-world-" + invocation.getArgument(1, Long.class), - "Partial World", - null, - null, - 1L, - invocation.getArgument(1, Long.class), - 0L, - true, - true, - true, - "SHARED", - "interactive"))); + .thenAnswer(invocation -> + List.of( + new GameplayAdmissionPointerSnapshot( + "partial-world-" + invocation.getArgument(1, Long.class), + "Partial World", + null, + null, + 1L, + invocation.getArgument(1, Long.class), + 0L, + true, + true, + true, + "SHARED", + "interactive"))); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = remoteControlPlaneService( @@ -6890,24 +6887,23 @@ void listRemoteCommandCoordinatorsReturnsFilteredRowsForAdminCaller() { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(authorityService.listByRuntimeTarget(Mockito.eq(1L), Mockito.anyLong())) - .thenAnswer( - invocation -> { - long gameInstanceId = invocation.getArgument(1, Long.class); - return List.of( - new GameplayAdmissionPointerSnapshot( - "world-" + gameInstanceId, - "World " + gameInstanceId, - "realm-" + gameInstanceId, - "Realm " + gameInstanceId, - 1L, - gameInstanceId, - gameInstanceId + 100L, - true, - true, - true, - gameInstanceId % 2L == 0L ? "ISOLATED" : "SHARED", - "interactive")); - }); + .thenAnswer(invocation -> { + long gameInstanceId = invocation.getArgument(1, Long.class); + return List.of( + new GameplayAdmissionPointerSnapshot( + "world-" + gameInstanceId, + "World " + gameInstanceId, + "realm-" + gameInstanceId, + "Realm " + gameInstanceId, + 1L, + gameInstanceId, + gameInstanceId + 100L, + true, + true, + true, + gameInstanceId % 2L == 0L ? "ISOLATED" : "SHARED", + "interactive")); + }); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameDesignClient gameDesignClient = gameDesignClient(); GameSessionControlPlaneGrpcService service = @@ -7248,22 +7244,21 @@ void listRemoteCommandCoordinatorsCollapsesPartialCurrentRuntimeRoutingBundleAnd Mockito.when( gameplayAdmissionPointerAuthorityService.listByRuntimeTarget( Mockito.eq(1L), Mockito.anyLong())) - .thenAnswer( - invocation -> - List.of( - new GameplayAdmissionPointerSnapshot( - "partial-world-" + invocation.getArgument(1, Long.class), - "Partial World", - null, - null, - 1L, - invocation.getArgument(1, Long.class), - 0L, - true, - true, - true, - "SHARED", - "interactive"))); + .thenAnswer(invocation -> + List.of( + new GameplayAdmissionPointerSnapshot( + "partial-world-" + invocation.getArgument(1, Long.class), + "Partial World", + null, + null, + 1L, + invocation.getArgument(1, Long.class), + 0L, + true, + true, + true, + "SHARED", + "interactive"))); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = remoteControlPlaneService( @@ -7777,22 +7772,21 @@ void listRemoteCommandCoordinatorsCollapsesCurrentRuntimeRoutingWhenPointerLacks Mockito.when( gameplayAdmissionPointerAuthorityService.listByRuntimeTarget( Mockito.eq(1L), Mockito.anyLong())) - .thenAnswer( - invocation -> - List.of( - new GameplayAdmissionPointerSnapshot( - "world-" + invocation.getArgument(1, Long.class), - "World " + invocation.getArgument(1, Long.class), - "production", - "Production", - 1L, - 0L, - 17L, - true, - true, - true, - "SHARED", - "interactive"))); + .thenAnswer(invocation -> + List.of( + new GameplayAdmissionPointerSnapshot( + "world-" + invocation.getArgument(1, Long.class), + "World " + invocation.getArgument(1, Long.class), + "production", + "Production", + 1L, + 0L, + 17L, + true, + true, + true, + "SHARED", + "interactive"))); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = remoteControlPlaneService( @@ -7855,46 +7849,45 @@ public void onNext(ScheduleRemoteFollowupResponse value) { assertEquals(true, responseRef.get().getFollowupCreated()); Mockito.verify(runtimeService) .scheduleFollowup( - Mockito.argThat( - request -> - request.tenantId() == 1L - && "cmd-1".equals(request.commandId()) - && "coord-1".equals(request.coordinatorId()) - && request.originGameInstanceId() == 7L - && "region-a".equals(request.originRegionId()) - && request.originRegionEpoch() == 4L - && request.targetGameInstanceId() == 9L - && "region-b".equals(request.targetRegionId()) - && request.targetRegionEpoch() == 8L - && request.targetDueTickId() == 55L - && request.originDeadlineRegionEpoch() == 4L - && request.originDeadlineTickId() == 60L - && "late_result_safe_to_ignore".equals(request.lateResultPolicy()) - && "followup-1".equals(request.followupId()) - && "effect-1".equals(request.effectKey()) - && "entity-9".equals(request.targetEntityId()) - && request.payloadJson().contains("\"kind\":\"enqueue_automation_command\"") - && "enqueue_automation_command".equals(request.payloadKind()) - && "LOOK".equals(request.requestedCommand()) - && request.requiresSoloTick() - && "SHARED".equals(request.playableStateScope()) - && "demo".equals(request.worldSlug()) - && "production".equals(request.realmSlug()) - && Objects.equals(Long.valueOf(17L), request.pointerVersion()) - && "patch-1".equals(request.scriptPatchVersion()) - && Objects.equals(Long.valueOf(100L), request.scriptPatchBaseVersionId()) - && Objects.equals(Long.valueOf(3L), request.scriptPinEpoch()) - && "pin-request-1".equals(request.scriptPinControlPlaneRequestId()) - && "plugin-1".equals(request.pluginId()) - && "plugin-v1".equals(request.pluginVersionId()) - && "dispatch-1".equals(request.automationDispatchId()) - && "work-1".equals(request.automationWorkItemId()) - && "script-1".equals(request.scriptId()) - && "REMOTE_FOLLOWUP".equals(request.originSourceKind()) - && "TARGET_REGION_EXECUTED".equals(request.originSourceState()) - && Objects.equals(Long.valueOf(44L), request.originSourceOrdinal()) - && Objects.equals(Long.valueOf(55L), request.originSourceDueTickId()) - && Objects.equals(Long.valueOf(1700L), request.originSourceDueAtMs()))); + Mockito.argThat(request -> + request.tenantId() == 1L + && "cmd-1".equals(request.commandId()) + && "coord-1".equals(request.coordinatorId()) + && request.originGameInstanceId() == 7L + && "region-a".equals(request.originRegionId()) + && request.originRegionEpoch() == 4L + && request.targetGameInstanceId() == 9L + && "region-b".equals(request.targetRegionId()) + && request.targetRegionEpoch() == 8L + && request.targetDueTickId() == 55L + && request.originDeadlineRegionEpoch() == 4L + && request.originDeadlineTickId() == 60L + && "late_result_safe_to_ignore".equals(request.lateResultPolicy()) + && "followup-1".equals(request.followupId()) + && "effect-1".equals(request.effectKey()) + && "entity-9".equals(request.targetEntityId()) + && request.payloadJson().contains("\"kind\":\"enqueue_automation_command\"") + && "enqueue_automation_command".equals(request.payloadKind()) + && "LOOK".equals(request.requestedCommand()) + && request.requiresSoloTick() + && "SHARED".equals(request.playableStateScope()) + && "demo".equals(request.worldSlug()) + && "production".equals(request.realmSlug()) + && Objects.equals(Long.valueOf(17L), request.pointerVersion()) + && "patch-1".equals(request.scriptPatchVersion()) + && Objects.equals(Long.valueOf(100L), request.scriptPatchBaseVersionId()) + && Objects.equals(Long.valueOf(3L), request.scriptPinEpoch()) + && "pin-request-1".equals(request.scriptPinControlPlaneRequestId()) + && "plugin-1".equals(request.pluginId()) + && "plugin-v1".equals(request.pluginVersionId()) + && "dispatch-1".equals(request.automationDispatchId()) + && "work-1".equals(request.automationWorkItemId()) + && "script-1".equals(request.scriptId()) + && "REMOTE_FOLLOWUP".equals(request.originSourceKind()) + && "TARGET_REGION_EXECUTED".equals(request.originSourceState()) + && Objects.equals(Long.valueOf(44L), request.originSourceOrdinal()) + && Objects.equals(Long.valueOf(55L), request.originSourceDueTickId()) + && Objects.equals(Long.valueOf(1700L), request.originSourceDueAtMs()))); } @Test @@ -8911,13 +8904,12 @@ void listRemoteFollowupResultsPrefersDurableFollowupLinkForTargetCommandStatus() Mockito.mock( RemoteFollowupResultRepository.class, Mockito.withSettings() - .defaultAnswer( - invocation -> { - if ("findForControlPlane".equals(invocation.getMethod().getName())) { - return List.of(result); - } - return Mockito.RETURNS_DEFAULTS.answer(invocation); - })); + .defaultAnswer(invocation -> { + if ("findForControlPlane".equals(invocation.getMethod().getName())) { + return List.of(result); + } + return Mockito.RETURNS_DEFAULTS.answer(invocation); + })); Mockito.when( repository.findForControlPlane( Mockito.anyLong(), @@ -10099,11 +10091,10 @@ private static ListRemoteFollowupResultsResponse projectLinkedRemoteFollowupResu Mockito.mock( RemoteFollowupResultRepository.class, Mockito.withSettings() - .defaultAnswer( - invocation -> - "findForControlPlane".equals(invocation.getMethod().getName()) - ? List.of(result) - : Mockito.RETURNS_DEFAULTS.answer(invocation))); + .defaultAnswer(invocation -> + "findForControlPlane".equals(invocation.getMethod().getName()) + ? List.of(result) + : Mockito.RETURNS_DEFAULTS.answer(invocation))); RemoteFollowupRepository followupRepository = Mockito.mock(RemoteFollowupRepository.class); RemoteFollowup followup = new RemoteFollowup(); followup.setTenantId(1L); @@ -10179,27 +10170,25 @@ private static GameplayCommandRepository commandRepositorySavingArgument() { GameplayCommandRepository repository = Mockito.mock(GameplayCommandRepository.class); AtomicLong idSequence = new AtomicLong(); Mockito.when(repository.save(Mockito.any(GameplayCommand.class))) - .thenAnswer( - invocation -> { - GameplayCommand command = invocation.getArgument(0); - if (command.getId() == null) { - long id = idSequence.incrementAndGet(); - command.setId(id); - command.setEnqueueSeq(id); - } - return command; - }); + .thenAnswer(invocation -> { + GameplayCommand command = invocation.getArgument(0); + if (command.getId() == null) { + long id = idSequence.incrementAndGet(); + command.setId(id); + command.setEnqueueSeq(id); + } + return command; + }); Mockito.when(repository.insertIfAbsentByIdempotencyIdentity(Mockito.any(GameplayCommand.class))) - .thenAnswer( - invocation -> { - GameplayCommand command = invocation.getArgument(0); - if (command.getId() == null) { - long id = idSequence.incrementAndGet(); - command.setId(id); - command.setEnqueueSeq(id); - } - return new GameplayCommandRepository.IdempotentInsertResult(command, true); - }); + .thenAnswer(invocation -> { + GameplayCommand command = invocation.getArgument(0); + if (command.getId() == null) { + long id = idSequence.incrementAndGet(); + command.setId(id); + command.setEnqueueSeq(id); + } + return new GameplayCommandRepository.IdempotentInsertResult(command, true); + }); return repository; } @@ -10250,23 +10239,22 @@ private static WorldManagementClient worldManagementClient( String responseTenantId, String responseGameInstanceId, WorldInstanceLifecycleStatus status) { WorldManagementClient client = Mockito.mock(WorldManagementClient.class); Mockito.when(client.getWorldInstanceLifecycle(Mockito.anyLong(), Mockito.anyLong())) - .thenAnswer( - invocation -> - GetWorldInstanceLifecycleResponse.newBuilder() - .setWorldInstance( - WorldInstanceLifecycleSnapshot.newBuilder() - .setTenantId( - responseTenantId == null - ? Long.toString(invocation.getArgument(0)) - : responseTenantId) - .setGameInstanceId( - responseGameInstanceId == null - ? Long.toString(invocation.getArgument(1)) - : responseGameInstanceId) - .setLifecycleEpoch(1L) - .setStatus(status) - .build()) - .build()); + .thenAnswer(invocation -> + GetWorldInstanceLifecycleResponse.newBuilder() + .setWorldInstance( + WorldInstanceLifecycleSnapshot.newBuilder() + .setTenantId( + responseTenantId == null + ? Long.toString(invocation.getArgument(0)) + : responseTenantId) + .setGameInstanceId( + responseGameInstanceId == null + ? Long.toString(invocation.getArgument(1)) + : responseGameInstanceId) + .setLifecycleEpoch(1L) + .setStatus(status) + .build()) + .build()); return client; } @@ -10379,24 +10367,23 @@ private static ControlPlaneTestFixture remoteControlPlaneFixture( Mockito.when( gameplayAdmissionPointerAuthorityService.listByRuntimeTarget( Mockito.eq(1L), Mockito.anyLong())) - .thenAnswer( - invocation -> { - Long gameInstanceId = invocation.getArgument(1, Long.class); - return List.of( - new net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot( - "world-" + gameInstanceId, - "World " + gameInstanceId, - "realm-" + gameInstanceId, - "Realm " + gameInstanceId, - 1L, - gameInstanceId, - gameInstanceId + 100L, - true, - true, - true, - gameInstanceId % 2 == 0 ? "ISOLATED" : "SHARED", - "interactive")); - }); + .thenAnswer(invocation -> { + Long gameInstanceId = invocation.getArgument(1, Long.class); + return List.of( + new net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot( + "world-" + gameInstanceId, + "World " + gameInstanceId, + "realm-" + gameInstanceId, + "Realm " + gameInstanceId, + 1L, + gameInstanceId, + gameInstanceId + 100L, + true, + true, + true, + gameInstanceId % 2 == 0 ? "ISOLATED" : "SHARED", + "interactive")); + }); return remoteControlPlaneFixture( remoteFollowupRepository, remoteCommandCoordinatorRepository, @@ -10465,15 +10452,14 @@ private static ControlPlaneTestFixture remoteControlPlaneFixture( MeterRegistry meterRegistry) { GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); Mockito.when(gameInstanceRepository.findById(Mockito.anyLong())) - .thenAnswer( - invocation -> { - Long gameInstanceId = invocation.getArgument(0, Long.class); - GameInstance instance = runningGameInstance(); - instance.setId(gameInstanceId); - instance.setTenantId(1L); - instance.setVersionId(99L); - return Optional.of(instance); - }); + .thenAnswer(invocation -> { + Long gameInstanceId = invocation.getArgument(0, Long.class); + GameInstance instance = runningGameInstance(); + instance.setId(gameInstanceId); + instance.setTenantId(1L); + instance.setVersionId(99L); + return Optional.of(instance); + }); return controlPlaneFixture( gameInstanceRepository, gameplayCommandRepository == null diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionFixtureLaunchAssociationReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionFixtureLaunchAssociationReadGrpcServiceTest.java index ed0d110277..3cf85b82ed 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionFixtureLaunchAssociationReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionFixtureLaunchAssociationReadGrpcServiceTest.java @@ -232,25 +232,24 @@ private static Fixture fixture(boolean enabled, boolean withCoordinator) { withCoordinator ? mock(RunOwnedCanonicalLaunchPreparationOwner.class) : null; if (coordinator != null) { when(coordinator.loadFixedVerifiedEvidenceForWorldPeer()) - .thenAnswer( - invocation -> { - GrpcPeerIdentity peer = GrpcPeerIdentity.current(); - GrpcPeerCertificateEvidence certificate = GrpcPeerCertificateEvidence.current(); - if (peer == null - || !TARGET_NAMESPACE.equals(peer.namespace()) - || !"world-management-service".equals(peer.service()) - || !WORLD_URI.equals(peer.uri()) - || SessionContext.hasAuthenticatedCallerContext() - || certificate == null - || !evidence - .fixtureCapability() - .worldManagementLeafSha256() - .equals(certificate.leafSha256())) { - throw new AdminAuthorizationException( - "Fixed fixture read requires the exact World workload peer and leaf"); - } - return evidence; - }); + .thenAnswer(invocation -> { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + GrpcPeerCertificateEvidence certificate = GrpcPeerCertificateEvidence.current(); + if (peer == null + || !TARGET_NAMESPACE.equals(peer.namespace()) + || !"world-management-service".equals(peer.service()) + || !WORLD_URI.equals(peer.uri()) + || SessionContext.hasAuthenticatedCallerContext() + || certificate == null + || !evidence + .fixtureCapability() + .worldManagementLeafSha256() + .equals(certificate.leafSha256())) { + throw new AdminAuthorizationException( + "Fixed fixture read requires the exact World workload peer and leaf"); + } + return evidence; + }); when(coordinator.readFixedFixtureLaunch(same(evidence))).thenReturn(launch); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index c96852b557..6c4a62f475 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -1567,12 +1567,11 @@ public void onCompleted() {} Mockito.verify(ipLimiter).tryRegister("127.0.0.1", 1L); Mockito.verify(gameInstanceService) .startSession( - Mockito.argThat( - request -> - request.tenantId().equals(1L) - && request.gameTemplateId().equals(7L) - && request.controlPlaneRequestId().equals("cp-1") - && request.ownerAccountId().equals(42L)), + Mockito.argThat(request -> + request.tenantId().equals(1L) + && request.gameTemplateId().equals(7L) + && request.controlPlaneRequestId().equals("cp-1") + && request.ownerAccountId().equals(42L)), Mockito.eq(false)); } @@ -3569,24 +3568,23 @@ private static AuthorizeStartSessionResponse authorizeWithPeer( AtomicReference response = new AtomicReference<>(); Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .run( - () -> - service.authorizeStartSession( - request, - new StreamObserver<>() { - @Override - public void onNext(AuthorizeStartSessionResponse value) { - response.set(value); - } - - @Override - public void onError(Throwable error) { - fail(error); - } - - @Override - public void onCompleted() {} - })); + .run(() -> + service.authorizeStartSession( + request, + new StreamObserver<>() { + @Override + public void onNext(AuthorizeStartSessionResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable error) { + fail(error); + } + + @Override + public void onCompleted() {} + })); return response.get(); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionOperatorControlPlaneServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionOperatorControlPlaneServiceTest.java index 58b3cc46ec..fef0d4ca11 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionOperatorControlPlaneServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionOperatorControlPlaneServiceTest.java @@ -130,10 +130,9 @@ void rejectsEpochValueOnExpectUnpinnedBeforeOwnerReads() { .build(); assertThatIllegalArgumentException() - .isThrownBy( - () -> - newService(repository, tickService, gameDesign, automation) - .setPinnedScriptPatchVersion(1L, 7L, request)) + .isThrownBy(() -> + newService(repository, tickService, gameDesign, automation) + .setPinnedScriptPatchVersion(1L, 7L, request)) .withMessage("expected_current_pin script_pin_epoch must be absent for EXPECT_UNPINNED"); verifyNoInteractions(repository, gameDesign, automation); } @@ -155,10 +154,9 @@ void rejectsEpochValueOnUnconditionalBeforeOwnerReads() { .build(); assertThatIllegalArgumentException() - .isThrownBy( - () -> - newService(repository, tickService, gameDesign, automation) - .setPinnedScriptPatchVersion(1L, 7L, request)) + .isThrownBy(() -> + newService(repository, tickService, gameDesign, automation) + .setPinnedScriptPatchVersion(1L, 7L, request)) .withMessage("expected_current_pin script_pin_epoch must be absent for UNCONDITIONAL"); verifyNoInteractions(repository, gameDesign, automation); } @@ -181,10 +179,9 @@ void unconditionalRequiresPlatformAdminBeforeOwnerReads() { .build(); assertThatExceptionOfType(AdminAuthorizationException.class) - .isThrownBy( - () -> - newService(repository, tickService, gameDesign, automation) - .setPinnedScriptPatchVersion(1L, 7L, request)) + .isThrownBy(() -> + newService(repository, tickService, gameDesign, automation) + .setPinnedScriptPatchVersion(1L, 7L, request)) .withMessage("UNCONDITIONAL requires platformAdmin"); verifyNoInteractions(repository, gameDesign, automation); } @@ -885,23 +882,21 @@ void rejectsMalformedCurrentScriptPinBeforeMutation() { GameSessionOperatorControlPlaneService service = service(gameInstanceRepository, tickService); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.setPinnedScriptPatchVersion( - 1L, - 7L, - SetPinnedScriptPatchVersionRequest.newBuilder() - .setTargetScriptPatchVersion("patch-new") - .setControlPlaneRequestId("request-1") - .setActorPrincipal("operator") - .setReason("pin") - .setExpectedCurrentPin( - ExpectedCurrentPin.newBuilder() - .setKind( - ExpectedCurrentPin.Kind - .EXPECTED_CURRENT_PIN_KIND_EXPECT_UNPINNED) - .build()) - .build())) + .isThrownBy(() -> + service.setPinnedScriptPatchVersion( + 1L, + 7L, + SetPinnedScriptPatchVersionRequest.newBuilder() + .setTargetScriptPatchVersion("patch-new") + .setControlPlaneRequestId("request-1") + .setActorPrincipal("operator") + .setReason("pin") + .setExpectedCurrentPin( + ExpectedCurrentPin.newBuilder() + .setKind( + ExpectedCurrentPin.Kind.EXPECTED_CURRENT_PIN_KIND_EXPECT_UNPINNED) + .build()) + .build())) .withMessage( "SCRIPT_PIN_STATE_INVALID: patch, positive epoch, and request id must be present" + " together"); @@ -1033,15 +1028,14 @@ void rejectsBlankScriptPatchPinTargetBeforeRepositoryReadOrMutation() { gameInstanceRepository, tickService, gameDesignClient, gameSessionProperties); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.setPinnedScriptPatchVersion( - 1L, - 7L, - SetPinnedScriptPatchVersionRequest.newBuilder() - .setTargetScriptPatchVersion(" ") - .setControlPlaneRequestId("request-1") - .build())) + .isThrownBy(() -> + service.setPinnedScriptPatchVersion( + 1L, + 7L, + SetPinnedScriptPatchVersionRequest.newBuilder() + .setTargetScriptPatchVersion(" ") + .setControlPlaneRequestId("request-1") + .build())) .withMessage("target_script_patch_version is required"); verifyNoInteractions( @@ -1059,15 +1053,14 @@ void rejectsBlankScriptPatchRollbackTargetBeforeRepositoryReadOrMutation() { gameInstanceRepository, tickService, gameDesignClient, gameSessionProperties); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.rollbackScriptPatchVersion( - 1L, - 7L, - RollbackScriptPatchVersionRequest.newBuilder() - .setTargetScriptPatchVersion("") - .setControlPlaneRequestId("request-1") - .build())) + .isThrownBy(() -> + service.rollbackScriptPatchVersion( + 1L, + 7L, + RollbackScriptPatchVersionRequest.newBuilder() + .setTargetScriptPatchVersion("") + .setControlPlaneRequestId("request-1") + .build())) .withMessage("target_script_patch_version is required"); verifyNoInteractions( @@ -1081,19 +1074,17 @@ void rejectsUnrecognizedExpectedPinBeforeOwnerReadOrLedgerMutation() { GameSessionOperatorControlPlaneService service = service(gameInstanceRepository, tickService); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.setPinnedScriptPatchVersion( - 1L, - 7L, - SetPinnedScriptPatchVersionRequest.newBuilder() - .setTargetScriptPatchVersion("patch-new") - .setControlPlaneRequestId("request-1") - .setActorPrincipal("operator") - .setReason("pin") - .setExpectedCurrentPin( - ExpectedCurrentPin.newBuilder().setKindValue(99).build()) - .build())) + .isThrownBy(() -> + service.setPinnedScriptPatchVersion( + 1L, + 7L, + SetPinnedScriptPatchVersionRequest.newBuilder() + .setTargetScriptPatchVersion("patch-new") + .setControlPlaneRequestId("request-1") + .setActorPrincipal("operator") + .setReason("pin") + .setExpectedCurrentPin(ExpectedCurrentPin.newBuilder().setKindValue(99).build()) + .build())) .withMessage("expected_current_pin kind is required"); verifyNoInteractions(gameInstanceRepository, tickService); @@ -1106,23 +1097,21 @@ void rejectsOverlengthScriptPinInputsBeforeOwnerReadOrLedgerMutation() { GameSessionOperatorControlPlaneService service = service(gameInstanceRepository, tickService); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.setPinnedScriptPatchVersion( - 1L, - 7L, - SetPinnedScriptPatchVersionRequest.newBuilder() - .setTargetScriptPatchVersion("x".repeat(101)) - .setControlPlaneRequestId("request-1") - .setActorPrincipal("operator") - .setReason("pin") - .setExpectedCurrentPin( - ExpectedCurrentPin.newBuilder() - .setKind( - ExpectedCurrentPin.Kind - .EXPECTED_CURRENT_PIN_KIND_EXPECT_UNPINNED) - .build()) - .build())) + .isThrownBy(() -> + service.setPinnedScriptPatchVersion( + 1L, + 7L, + SetPinnedScriptPatchVersionRequest.newBuilder() + .setTargetScriptPatchVersion("x".repeat(101)) + .setControlPlaneRequestId("request-1") + .setActorPrincipal("operator") + .setReason("pin") + .setExpectedCurrentPin( + ExpectedCurrentPin.newBuilder() + .setKind( + ExpectedCurrentPin.Kind.EXPECTED_CURRENT_PIN_KIND_EXPECT_UNPINNED) + .build()) + .build())) .withMessage("target_script_patch_version must contain at most 100 characters"); verifyNoInteractions(gameInstanceRepository, tickService); @@ -1174,16 +1163,15 @@ void rejectsBlankScriptPinAuditMetadataBeforeRepositoryReadOrMutation() { GameSessionOperatorControlPlaneService service = service(gameInstanceRepository, tickService); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.setPinnedScriptPatchVersion( - 1L, - 7L, - SetPinnedScriptPatchVersionRequest.newBuilder() - .setTargetScriptPatchVersion("patch-new") - .setActorPrincipal("operator") - .setReason("pin") - .build())) + .isThrownBy(() -> + service.setPinnedScriptPatchVersion( + 1L, + 7L, + SetPinnedScriptPatchVersionRequest.newBuilder() + .setTargetScriptPatchVersion("patch-new") + .setActorPrincipal("operator") + .setReason("pin") + .build())) .withMessage("control_plane_request_id is required"); verifyNoInteractions(gameInstanceRepository, tickService); @@ -1196,16 +1184,15 @@ void rejectsBlankScriptRollbackAuditMetadataBeforeRepositoryReadOrMutation() { GameSessionOperatorControlPlaneService service = service(gameInstanceRepository, tickService); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.rollbackScriptPatchVersion( - 1L, - 7L, - RollbackScriptPatchVersionRequest.newBuilder() - .setTargetScriptPatchVersion("patch-old") - .setControlPlaneRequestId("request-1") - .setActorPrincipal("operator") - .build())) + .isThrownBy(() -> + service.rollbackScriptPatchVersion( + 1L, + 7L, + RollbackScriptPatchVersionRequest.newBuilder() + .setTargetScriptPatchVersion("patch-old") + .setControlPlaneRequestId("request-1") + .setActorPrincipal("operator") + .build())) .withMessage("reason is required"); verifyNoInteractions(gameInstanceRepository, tickService); @@ -1218,16 +1205,15 @@ void rejectsBlankScriptPinActorBeforeRepositoryReadOrMutation() { GameSessionOperatorControlPlaneService service = service(gameInstanceRepository, tickService); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.setPinnedScriptPatchVersion( - 1L, - 7L, - SetPinnedScriptPatchVersionRequest.newBuilder() - .setTargetScriptPatchVersion("patch-new") - .setControlPlaneRequestId("request-1") - .setReason("pin") - .build())) + .isThrownBy(() -> + service.setPinnedScriptPatchVersion( + 1L, + 7L, + SetPinnedScriptPatchVersionRequest.newBuilder() + .setTargetScriptPatchVersion("patch-new") + .setControlPlaneRequestId("request-1") + .setReason("pin") + .build())) .withMessage("actor_principal is required"); verifyNoInteractions(gameInstanceRepository, tickService); @@ -1240,17 +1226,16 @@ void rejectsBlankScriptPatchRollbackPurgeReasonBeforePersistence() { GameSessionOperatorControlPlaneService service = service(gameInstanceRepository, tickService); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.purgeQueuedTickCommandsForScriptPatch( - 1L, - 7L, - PurgeQueuedTickCommandsForScriptPatchRequest.newBuilder() - .setScriptPatchVersion("patch-1") - .setControlPlaneRequestId("request-1") - .setActorPrincipal("operator") - .setReason(" ") - .build())) + .isThrownBy(() -> + service.purgeQueuedTickCommandsForScriptPatch( + 1L, + 7L, + PurgeQueuedTickCommandsForScriptPatchRequest.newBuilder() + .setScriptPatchVersion("patch-1") + .setControlPlaneRequestId("request-1") + .setActorPrincipal("operator") + .setReason(" ") + .build())) .withMessage("reason is required"); verifyNoInteractions(gameInstanceRepository, tickService); @@ -1263,18 +1248,17 @@ void rejectsBlankPluginRollbackPurgeReasonBeforePersistence() { GameSessionOperatorControlPlaneService service = service(gameInstanceRepository, tickService); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.purgeQueuedTickCommandsForPluginVersion( - 1L, - 7L, - PurgeQueuedTickCommandsForPluginVersionRequest.newBuilder() - .setPluginId("plugin-1") - .setPluginVersionId("plugin-v1") - .setControlPlaneRequestId("request-1") - .setActorPrincipal("operator") - .setReason("") - .build())) + .isThrownBy(() -> + service.purgeQueuedTickCommandsForPluginVersion( + 1L, + 7L, + PurgeQueuedTickCommandsForPluginVersionRequest.newBuilder() + .setPluginId("plugin-1") + .setPluginVersionId("plugin-v1") + .setControlPlaneRequestId("request-1") + .setActorPrincipal("operator") + .setReason("") + .build())) .withMessage("reason is required"); verifyNoInteractions(gameInstanceRepository, tickService); @@ -1287,14 +1271,13 @@ void rejectsBlankPauseTicksReasonBeforePersistence() { GameSessionOperatorControlPlaneService service = service(gameInstanceRepository, tickService); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.pauseTicksForScope( - 1L, - PauseTicksForScopeRequest.newBuilder() - .setGameInstanceId("7") - .setReason(" ") - .build())) + .isThrownBy(() -> + service.pauseTicksForScope( + 1L, + PauseTicksForScopeRequest.newBuilder() + .setGameInstanceId("7") + .setReason(" ") + .build())) .withMessage("reason is required"); verifyNoInteractions(gameInstanceRepository, tickService); @@ -1307,14 +1290,13 @@ void rejectsBlankResumeTicksReasonBeforePersistence() { GameSessionOperatorControlPlaneService service = service(gameInstanceRepository, tickService); assertThatIllegalArgumentException() - .isThrownBy( - () -> - service.resumeTicksForScope( - 1L, - ResumeTicksForScopeRequest.newBuilder() - .setGameInstanceId("7") - .setReason("") - .build())) + .isThrownBy(() -> + service.resumeTicksForScope( + 1L, + ResumeTicksForScopeRequest.newBuilder() + .setGameInstanceId("7") + .setReason("") + .build())) .withMessage("reason is required"); verifyNoInteractions(gameInstanceRepository, tickService); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java index b4e8e1d9af..8672b58dba 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcMtlsTest.java @@ -112,10 +112,9 @@ void exactWorldAndAccountPeersReachCurrentHistoricalOwnerAndEmptyEvidenceDenies( client.init(); assertThatThrownBy(() -> client.read(REQUEST)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); } } org.mockito.Mockito.verify(owner, org.mockito.Mockito.times(2)) @@ -131,10 +130,9 @@ void trustedWrongServiceAndWrongNamespaceCertificatesNeverReachOwner() throws Ex client.init(); assertThatThrownBy(() -> client.read(REQUEST)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } } @@ -151,10 +149,9 @@ void trustedWrongServiceAndWrongNamespaceServerPeersAreRejectedBeforeOwnerAccess client.init(); assertThatThrownBy(() -> client.read(REQUEST)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); } stopReceiver(); } @@ -173,17 +170,15 @@ void missingClientCertificateIsRejectedByTlsBeforeOwnerAccess() throws Exception .build()) .build(); - assertThatThrownBy( - () -> - HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc.newBlockingStub( - noCertificateChannel) - .withDeadlineAfter(5, TimeUnit.SECONDS) - .readHistoricalOriginalStartSessionOwnerEvidence(toWireRequest())) - .satisfies( - failure -> - assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) - .as("server requires a trusted client certificate") - .isTrue()); + assertThatThrownBy(() -> + HistoricalOriginalStartSessionOwnerEvidenceReadServiceGrpc.newBlockingStub( + noCertificateChannel) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .readHistoricalOriginalStartSessionOwnerEvidence(toWireRequest())) + .satisfies(failure -> + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as("server requires a trusted client certificate") + .isTrue()); verifyNoInteractions(owner); } @@ -196,10 +191,9 @@ void authenticatedWorldPeerWithEndUserContextNeverReachesOwner() throws Exceptio client.init(); assertThatThrownBy(() -> client.read(REQUEST)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } verifyNoInteractions(owner); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java index ecdea2d272..1663eb1102 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java @@ -556,19 +556,18 @@ private static AuthoredWorldReleaseAttestationEvidence release( WorldPublishedStartLocationEvidence worldSelection) { var participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - owner, - Long.toString(descriptor.versionId()), - false, - null, - worldSelection.request().appliedCommitId(), - worldSelection.request().contentDigest(), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - "GAME_LOGIC".equals(owner), - "GAME_LOGIC".equals(owner) ? digest('f') : null)) + .map(owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + worldSelection.request().appliedCommitId(), + worldSelection.request().contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? digest('f') : null)) .toList(); return AuthoredWorldReleaseAttestationEvidence.create( descriptor.targetNamespace(), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java index 115eade73a..ed12d930e7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java @@ -23,63 +23,54 @@ void clearCallerContexts() { @Test void allowsOnlyExactSameNamespaceWorldAndAccountWorkloads() { - assertThatCode( - () -> - withPeer( - "world-management-service", - NAMESPACE, - () -> { - guard.requireHistoricalOwnerReadCaller(); - guard.requireConfiguredTargetNamespace(NAMESPACE); - })) + assertThatCode(() -> + withPeer( + "world-management-service", + NAMESPACE, + () -> { + guard.requireHistoricalOwnerReadCaller(); + guard.requireConfiguredTargetNamespace(NAMESPACE); + })) .doesNotThrowAnyException(); - assertThatCode( - () -> - withPeer( - "account-service", - NAMESPACE, - () -> { - guard.requireHistoricalOwnerReadCaller(); - guard.requireConfiguredTargetNamespace(NAMESPACE); - })) + assertThatCode(() -> + withPeer( + "account-service", + NAMESPACE, + () -> { + guard.requireHistoricalOwnerReadCaller(); + guard.requireConfiguredTargetNamespace(NAMESPACE); + })) .doesNotThrowAnyException(); } @Test void refusesOtherNamespacesWrongServicesAndAuthenticatedEndUserContext() { - assertThatThrownBy( - () -> - withPeer( - "world-management-service", "other", guard::requireHistoricalOwnerReadCaller)) + assertThatThrownBy(() -> + withPeer("world-management-service", "other", guard::requireHistoricalOwnerReadCaller)) .isInstanceOf(AdminAuthorizationException.class); - assertThatThrownBy( - () -> - withPeer( - "entity-management-service", - NAMESPACE, - guard::requireHistoricalOwnerReadCaller)) + assertThatThrownBy(() -> + withPeer( + "entity-management-service", NAMESPACE, guard::requireHistoricalOwnerReadCaller)) .isInstanceOf(AdminAuthorizationException.class); - assertThatThrownBy( - () -> - withPeer( - "world-management-service", - NAMESPACE, - () -> { - SessionContext.setContext( - "42", java.util.List.of("tenantAdmin"), java.util.Map.of()); - guard.requireHistoricalOwnerReadCaller(); - })) + assertThatThrownBy(() -> + withPeer( + "world-management-service", + NAMESPACE, + () -> { + SessionContext.setContext( + "42", java.util.List.of("tenantAdmin"), java.util.Map.of()); + guard.requireHistoricalOwnerReadCaller(); + })) .isInstanceOf(AdminAuthorizationException.class); } @Test void rejectsInconsistentPeerIdentityBeforeGuardInvocation() { - assertThatThrownBy( - () -> - new GrpcPeerIdentity( - "spiffe://firemud/ns/other/sa/world-management-service", - NAMESPACE, - "world-management-service")) + assertThatThrownBy(() -> + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/world-management-service", + NAMESPACE, + "world-management-service")) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java index 546815a95e..3fb13a59ce 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java @@ -135,21 +135,19 @@ void rejectsUnspecifiedAndUnrecognizedScopeBeforeOwnerRead() { InitialAdmissionBindOwnerProofReader reader = mock(InitialAdmissionBindOwnerProofReader.class); GameSessionControlPlaneGrpcService service = service(reader, NAMESPACE); AtomicReference unspecified = new AtomicReference<>(); - runAsWorldManagement( - () -> - unspecified.set( - invoke( - service, - request().toBuilder() - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED) - .build()))); + runAsWorldManagement(() -> + unspecified.set( + invoke( + service, + request().toBuilder() + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED) + .build()))); assertEquals("INVALID_ARGUMENT", unspecified.get().getError().getCode()); AtomicReference unrecognized = new AtomicReference<>(); - runAsWorldManagement( - () -> - unrecognized.set( - invoke(service, request().toBuilder().setPlayableStateScopeValue(999).build()))); + runAsWorldManagement(() -> + unrecognized.set( + invoke(service, request().toBuilder().setPlayableStateScopeValue(999).build()))); assertEquals("INVALID_ARGUMENT", unrecognized.get().getError().getCode()); verifyNoInteractions(reader); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java index 38a5487836..58f1f3706c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java @@ -55,21 +55,20 @@ void persistsStableCatalogAndIntentThenCommitsMatchingPointerAuditAndLedger() th assertThat(tx(harness, () -> harness.service.beginIntent(request))) .usingRecursiveComparison() .isEqualTo(intent); - assertThatThrownBy( - () -> - tx( - harness, - () -> - harness.service.beginIntent( - new InitialAdmissionBindRequest( - 17L, - "demo", - "production", - "bind-17-93", - "b".repeat(64), - 93L, - 44L, - 8L)))) + assertThatThrownBy(() -> + tx( + harness, + () -> + harness.service.beginIntent( + new InitialAdmissionBindRequest( + 17L, + "demo", + "production", + "bind-17-93", + "b".repeat(64), + 93L, + 44L, + 8L)))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("IDEMPOTENCY_CONFLICT"); @@ -123,26 +122,25 @@ void abortedAttemptIsDurableAndADelayedCommitCannotTurnItIntoPointer() throws Ex assertThat(delayedCommit.outcome()).isEqualTo(InitialAdmissionBindOwnerProof.Outcome.ABORTED); assertThat(harness.dsl.fetchCount(DSL.table("gameplay_admission_pointer"))).isZero(); assertThat(harness.dsl.fetchCount(DSL.table("gameplay_admission_pointer_event"))).isZero(); - assertThatThrownBy( - () -> - tx( - harness, - () -> - harness.service.attachHold( - new InitialAdmissionBindHoldBinding( - UUID.randomUUID().toString(), - UUID.randomUUID().toString(), - binding.tenantId(), - binding.realmUuid(), - binding.playableStateNamespaceUuid(), - binding.playableStateScope(), - binding.gameInstanceId(), - binding.versionId(), - binding.activeLifecycleEpoch(), - binding.initialAdmissionRequestId(), - binding.requestDigest(), - true, - binding.expectedCatalogRevision())))) + assertThatThrownBy(() -> + tx( + harness, + () -> + harness.service.attachHold( + new InitialAdmissionBindHoldBinding( + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + binding.tenantId(), + binding.realmUuid(), + binding.playableStateNamespaceUuid(), + binding.playableStateScope(), + binding.gameInstanceId(), + binding.versionId(), + binding.activeLifecycleEpoch(), + binding.initialAdmissionRequestId(), + binding.requestDigest(), + true, + binding.expectedCatalogRevision())))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("IDEMPOTENCY_CONFLICT"); } @@ -153,20 +151,19 @@ void exactCatalogRetryReusesIdsButChangedFixtureMetadataConflicts() throws Excep var catalog = tx(harness, () -> harness.service.registerPublicSharedFixtureCatalog(descriptor())); - assertThatThrownBy( - () -> - tx( - harness, - () -> - harness.service.registerPublicSharedFixtureCatalog( - new InitialAdmissionBindCatalogDescriptor( - 17L, - 700L, - "demo", - "Changed Demo Name", - "production", - "Production Realm", - true)))) + assertThatThrownBy(() -> + tx( + harness, + () -> + harness.service.registerPublicSharedFixtureCatalog( + new InitialAdmissionBindCatalogDescriptor( + 17L, + 700L, + "demo", + "Changed Demo Name", + "production", + "Production Realm", + true)))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("IDEMPOTENCY_CONFLICT"); assertThat(harness.catalogRepository.findByTenantId(17L).orElseThrow().realmId()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/IpConnectionLimiterImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/IpConnectionLimiterImplTest.java index a7123c4f01..e1b679277d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/IpConnectionLimiterImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/IpConnectionLimiterImplTest.java @@ -34,13 +34,12 @@ void enforcesMaxConnectionsPerIp() { org.mockito.Mockito.when(ops.get(anyString())) .thenAnswer(inv -> store.get(inv.getArgument(0, String.class))); org.mockito.Mockito.when(ops.decrement(anyString())) - .thenAnswer( - inv -> { - String key = inv.getArgument(0); - long val = Long.parseLong(store.getOrDefault(key, "0")) - 1; - store.put(key, Long.toString(val)); - return val; - }); + .thenAnswer(inv -> { + String key = inv.getArgument(0); + long val = Long.parseLong(store.getOrDefault(key, "0")) - 1; + store.put(key, Long.toString(val)); + return val; + }); doAnswer( inv -> { store.put(inv.getArgument(0), inv.getArgument(1)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadWorkloadGuardTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadWorkloadGuardTest.java index bb3edc3526..ccbf188a7a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadWorkloadGuardTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/OriginalStartSessionCurrentAttemptReadWorkloadGuardTest.java @@ -23,41 +23,37 @@ void clearCallerContext() { @Test void allowsOnlyExactSameNamespaceAccountWorkloadWithoutEndUserContext() { - assertThatCode( - () -> - withPeer( - "account-service", - NAMESPACE, - () -> { - guard.requireAccountCurrentAttemptReadCaller(); - guard.requireConfiguredTargetNamespace(NAMESPACE); - })) + assertThatCode(() -> + withPeer( + "account-service", + NAMESPACE, + () -> { + guard.requireAccountCurrentAttemptReadCaller(); + guard.requireConfiguredTargetNamespace(NAMESPACE); + })) .doesNotThrowAnyException(); } @Test void refusesWrongNamespaceWrongServiceEndUserContextAndTargetNamespace() { - assertThatThrownBy( - () -> - withPeer("account-service", "other", guard::requireAccountCurrentAttemptReadCaller)) + assertThatThrownBy(() -> + withPeer("account-service", "other", guard::requireAccountCurrentAttemptReadCaller)) .isInstanceOf(AdminAuthorizationException.class); - assertThatThrownBy( - () -> - withPeer( - "world-management-service", - NAMESPACE, - guard::requireAccountCurrentAttemptReadCaller)) + assertThatThrownBy(() -> + withPeer( + "world-management-service", + NAMESPACE, + guard::requireAccountCurrentAttemptReadCaller)) .isInstanceOf(AdminAuthorizationException.class); - assertThatThrownBy( - () -> - withPeer( - "account-service", - NAMESPACE, - () -> { - SessionContext.setContext( - "42", java.util.List.of("tenantAdmin"), java.util.Map.of()); - guard.requireAccountCurrentAttemptReadCaller(); - })) + assertThatThrownBy(() -> + withPeer( + "account-service", + NAMESPACE, + () -> { + SessionContext.setContext( + "42", java.util.List.of("tenantAdmin"), java.util.Map.of()); + guard.requireAccountCurrentAttemptReadCaller(); + })) .isInstanceOf(AdminAuthorizationException.class); assertThatThrownBy(() -> guard.requireConfiguredTargetNamespace("other")) .isInstanceOf(AdminAuthorizationException.class); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PrivateWorldPreparationReadGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PrivateWorldPreparationReadGrpcServiceTest.java index 917c5559a8..1ef3dc7382 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PrivateWorldPreparationReadGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/PrivateWorldPreparationReadGrpcServiceTest.java @@ -524,9 +524,9 @@ private static final class Fixture { final RealmEntryPolicy policy = RealmEntryPolicy.parse( """ - {"schemaVersion":1,"worldSlug":"world","worldDisplayName":"World","realmSlug":"private", - "realmDisplayName":"Private","visible":true,"publicProduction":false,"stateScope":"ISOLATED","entryPolicy":"PRESEEDED_ONLY"} - """, + {"schemaVersion":1,"worldSlug":"world","worldDisplayName":"World","realmSlug":"private", + "realmDisplayName":"Private","visible":true,"publicProduction":false,"stateScope":"ISOLATED","entryPolicy":"PRESEEDED_ONLY"} + """, JsonMapper.builder().build()); final GameSessionInitialPlaytestLifecycleRepository.SourceReference source = new GameSessionInitialPlaytestLifecycleRepository.SourceReference( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java index 8bc733ee97..72b8bb60d8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java @@ -766,11 +766,10 @@ private static SessionContext testContext() { @SuppressWarnings("unchecked") private static void stubTransactionExecution(RedisTemplate redisTemplate) { when(redisTemplate.execute(Mockito.any(SessionCallback.class))) - .thenAnswer( - invocation -> { - SessionCallback callback = invocation.getArgument(0); - return callback.execute((RedisOperations) redisTemplate); - }); + .thenAnswer(invocation -> { + SessionCallback callback = invocation.getArgument(0); + return callback.execute((RedisOperations) redisTemplate); + }); when(redisTemplate.exec()).thenReturn(List.of("OK")); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisDisconnectDeduplicationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisDisconnectDeduplicationServiceTest.java index 77065da275..199d54e8b6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisDisconnectDeduplicationServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisDisconnectDeduplicationServiceTest.java @@ -19,18 +19,17 @@ void shouldProcessAcceptsNewerDisconnectSequences() { ConcurrentMap store = new ConcurrentHashMap<>(); StringRedisTemplate redisTemplate = mock(StringRedisTemplate.class); when(redisTemplate.execute(any(), anyList(), any(), any())) - .thenAnswer( - invocation -> { - List keys = invocation.getArgument(1); - String key = keys.get(0); - long sequence = Long.parseLong(invocation.getArgument(2)); - Long current = store.get(key); - if (current == null || sequence > current) { - store.put(key, sequence); - return 1L; - } - return 0L; - }); + .thenAnswer(invocation -> { + List keys = invocation.getArgument(1); + String key = keys.get(0); + long sequence = Long.parseLong(invocation.getArgument(2)); + Long current = store.get(key); + if (current == null || sequence > current) { + store.put(key, sequence); + return 1L; + } + return 0L; + }); RedisDisconnectDeduplicationService service = new RedisDisconnectDeduplicationService(redisTemplate, 1500L); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java index d7fe7e55e8..6540b0910c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java @@ -57,12 +57,11 @@ void registerConnectedStoresPresenceAndIndexesByGameInstance() { verify(valueOperations) .set( org.mockito.Mockito.eq("gameplaypresence:session:1"), - argThat( - value -> - value instanceof net.firedevops.firemud.gamesession.service.GameplayPresence - && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) - .characterName() - .equals("Ben")), + argThat(value -> + value instanceof net.firedevops.firemud.gamesession.service.GameplayPresence + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .characterName() + .equals("Ben")), org.mockito.Mockito.eq(TTL)); verify(setOperations).add("gameplaypresence:22:7:sessions", "1"); verify(setOperations) @@ -102,12 +101,10 @@ void registerConnectedStoresPlayerForInvalidJwt() { verify(valueOperations) .set( org.mockito.Mockito.eq("gameplaypresence:session:1"), - argThat( - value -> - value instanceof net.firedevops.firemud.gamesession.service.GameplayPresence - && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) - .role() - == GameplayPresenceRole.PLAYER), + argThat(value -> + value instanceof net.firedevops.firemud.gamesession.service.GameplayPresence + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value).role() + == GameplayPresenceRole.PLAYER), org.mockito.Mockito.eq(TTL)); } @@ -128,12 +125,11 @@ void registerConnectedKeepsGlobalStaffInThePlayerRole() { verify(valueOperations) .set( org.mockito.Mockito.eq("gameplaypresence:session:1"), - argThat( - value -> - value - instanceof - net.firedevops.firemud.gamesession.service.GameplayPresence presence - && presence.role() == GameplayPresenceRole.PLAYER), + argThat(value -> + value + instanceof + net.firedevops.firemud.gamesession.service.GameplayPresence presence + && presence.role() == GameplayPresenceRole.PLAYER), org.mockito.Mockito.eq(TTL)); } @@ -154,12 +150,10 @@ void registerConnectedDoesNotPromoteScopedJwtRolesWithoutGameplayGrantEvidence() verify(valueOperations) .set( org.mockito.Mockito.eq("gameplaypresence:session:1"), - argThat( - value -> - value instanceof net.firedevops.firemud.gamesession.service.GameplayPresence - && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) - .role() - == GameplayPresenceRole.PLAYER), + argThat(value -> + value instanceof net.firedevops.firemud.gamesession.service.GameplayPresence + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value).role() + == GameplayPresenceRole.PLAYER), org.mockito.Mockito.eq(TTL)); } @@ -333,29 +327,26 @@ void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequest verify(valueOperations) .set( org.mockito.Mockito.eq("gameplaypresence:session:3"), - argThat( - value -> - value instanceof net.firedevops.firemud.gamesession.service.GameplayPresence - && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) - .accountId() - .equals(PLAYER_ACCOUNT_ID) - && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) - .playableStateScope() - .equals("ISOLATED") - && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) - .pointerVersion() - == 17L - && Long.valueOf(125L) - .equals( - ((net.firedevops.firemud.gamesession.service.GameplayPresence) - value) - .lastAcceptedCommandAtEpochMs()) - && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) - .lastMeaningfulActivityAtEpochMs() - == 90L - && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) - .role() - == GameplayPresenceRole.PLAYER), + argThat(value -> + value instanceof net.firedevops.firemud.gamesession.service.GameplayPresence + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .accountId() + .equals(PLAYER_ACCOUNT_ID) + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .playableStateScope() + .equals("ISOLATED") + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .pointerVersion() + == 17L + && Long.valueOf(125L) + .equals( + ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .lastAcceptedCommandAtEpochMs()) + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .lastMeaningfulActivityAtEpochMs() + == 90L + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value).role() + == GameplayPresenceRole.PLAYER), org.mockito.Mockito.eq(TTL)); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); verify(redisTemplate) @@ -391,32 +382,29 @@ void setExplicitAfkRefreshesPresenceRecord() { verify(valueOperations) .set( org.mockito.Mockito.eq("gameplaypresence:session:3"), - argThat( - value -> - value instanceof net.firedevops.firemud.gamesession.service.GameplayPresence - && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) - .accountId() - .equals(PLAYER_ACCOUNT_ID) - && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) - .playableStateScope() - .equals("ISOLATED") - && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) - .pointerVersion() - == 17L - && Long.valueOf(145L) - .equals( - ((net.firedevops.firemud.gamesession.service.GameplayPresence) - value) - .explicitAfkSinceEpochMs()) - && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) - .lastAcceptedCommandAtEpochMs() - == 90L - && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) - .lastMeaningfulActivityAtEpochMs() - == 95L - && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) - .role() - == GameplayPresenceRole.PLAYER), + argThat(value -> + value instanceof net.firedevops.firemud.gamesession.service.GameplayPresence + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .accountId() + .equals(PLAYER_ACCOUNT_ID) + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .playableStateScope() + .equals("ISOLATED") + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .pointerVersion() + == 17L + && Long.valueOf(145L) + .equals( + ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .explicitAfkSinceEpochMs()) + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .lastAcceptedCommandAtEpochMs() + == 90L + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value) + .lastMeaningfulActivityAtEpochMs() + == 95L + && ((net.firedevops.firemud.gamesession.service.GameplayPresence) value).role() + == GameplayPresenceRole.PLAYER), org.mockito.Mockito.eq(TTL)); verify(redisTemplate).expire("gameplaypresence:22:7:sessions", TTL); verify(redisTemplate) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java index 65da7b5e0b..5e083e764e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java @@ -38,11 +38,10 @@ class RedisMovementEffectIdempotencyServiceTest { void setUp() { when(redisTemplate.opsForValue()).thenReturn(valueOperations); when(redisTemplate.execute(Mockito.any(SessionCallback.class))) - .thenAnswer( - invocation -> { - SessionCallback callback = invocation.getArgument(0); - return callback.execute((RedisOperations) redisTemplate); - }); + .thenAnswer(invocation -> { + SessionCallback callback = invocation.getArgument(0); + return callback.execute((RedisOperations) redisTemplate); + }); when(redisTemplate.exec()).thenReturn(List.of(1L)); service = new RedisMovementEffectIdempotencyService(redisTemplate, TTL.toMillis()); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java index 0e7fd4d202..ef5ac6a748 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java @@ -44,11 +44,10 @@ class RedisSessionContextServiceTest { void setUp() { when(redisTemplate.opsForValue()).thenReturn(valueOperations); when(redisTemplate.execute(Mockito.any(SessionCallback.class))) - .thenAnswer( - invocation -> { - SessionCallback callback = invocation.getArgument(0); - return callback.execute((RedisOperations) redisTemplate); - }); + .thenAnswer(invocation -> { + SessionCallback callback = invocation.getArgument(0); + return callback.execute((RedisOperations) redisTemplate); + }); when(redisTemplate.exec()).thenReturn(List.of(1L)); service = new RedisSessionContextService(redisTemplate, TTL.toMillis()); } @@ -267,9 +266,8 @@ void saveCleansDistinctSessionAliasIndexesForSameTenantAndSession() { verify(redisTemplate).delete("sessionctx:10:identity:42:name:aliasold:context"); verify(redisTemplate, Mockito.atLeastOnce()) .watch( - Mockito.argThat( - (Collection keys) -> - keys.contains("sessionctx:10:identity:42:32:context"))); + Mockito.argThat((Collection keys) -> + keys.contains("sessionctx:10:identity:42:32:context"))); verify(valueOperations).set("sessionctx:10:1:context", incoming.withoutJwt(), TTL); verify(valueOperations).set("sessionctx:session:1:context", incoming.withoutJwt(), TTL); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImplTest.java index e7eedad883..414d1aa3d6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImplTest.java @@ -66,11 +66,9 @@ void setup() { when(gameplayCommandRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); lenient() .when(gameInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(anyLong(), anyLong())) - .thenAnswer( - invocation -> - Optional.of( - sourceGameInstance( - (Long) invocation.getArgument(1), 100L, 3L, "pin-request-1"))); + .thenAnswer(invocation -> + Optional.of( + sourceGameInstance((Long) invocation.getArgument(1), 100L, 3L, "pin-request-1"))); meterRegistry = new SimpleMeterRegistry(); service = new RemoteFollowupRuntimeServiceImpl( @@ -113,49 +111,47 @@ void scheduleFollowupCreatesCoordinatorAndFollowup() { assertEquals("PENDING", command.getGameplayResult()); verify(coordinatorRepository) .save( - argThat( - coordinator -> - "SHARED".equals(coordinator.getPlayableStateScope()) - && "dispatch-1".equals(coordinator.getAutomationDispatchId()) - && "work-1".equals(coordinator.getAutomationWorkItemId()) - && "script-1".equals(coordinator.getScriptId()) - && "patch-1".equals(coordinator.getScriptPatchVersion()) - && Long.valueOf(100L).equals(coordinator.getScriptPatchBaseVersionId()) - && "plugin-1".equals(coordinator.getPluginId()) - && "plugin-v1".equals(coordinator.getPluginVersionId()) - && "demo".equals(coordinator.getWorldSlug()) - && "production".equals(coordinator.getRealmSlug()) - && Long.valueOf(17L).equals(coordinator.getPointerVersion()))); + argThat(coordinator -> + "SHARED".equals(coordinator.getPlayableStateScope()) + && "dispatch-1".equals(coordinator.getAutomationDispatchId()) + && "work-1".equals(coordinator.getAutomationWorkItemId()) + && "script-1".equals(coordinator.getScriptId()) + && "patch-1".equals(coordinator.getScriptPatchVersion()) + && Long.valueOf(100L).equals(coordinator.getScriptPatchBaseVersionId()) + && "plugin-1".equals(coordinator.getPluginId()) + && "plugin-v1".equals(coordinator.getPluginVersionId()) + && "demo".equals(coordinator.getWorldSlug()) + && "production".equals(coordinator.getRealmSlug()) + && Long.valueOf(17L).equals(coordinator.getPointerVersion()))); verify(followupRepository) .save( - argThat( - followup -> - "SHARED".equals(followup.getPlayableStateScope()) - && "cmd-1".equals(followup.getCommandId()) - && "entity:entity-9".equals(followup.getClaimTargetAggregate()) - && "enqueue_automation_command".equals(followup.getPayloadKind()) - && "LOOK".equals(followup.getRequestedCommand()) - && followup.isRequiresSoloTick() - && "REMOTE_FOLLOWUP".equals(followup.getOriginSourceKind()) - && "TARGET_REGION_EXECUTED".equals(followup.getOriginSourceState()) - && Long.valueOf(44L).equals(followup.getOriginSourceOrdinal()) - && Long.valueOf(22L).equals(followup.getOriginSourceDueTickId()) - && Long.valueOf(1700L).equals(followup.getOriginSourceDueAtMs()) - && "REMOTE_FOLLOWUP".equals(followup.getQueueSourceKind()) - && "TARGET_REGION_SCHEDULED".equals(followup.getQueueSourceState()) - && followup.getQueueSourceOrdinal() == null - && Long.valueOf(22L).equals(followup.getQueueSourceDueTickId()) - && followup.getQueueSourceDueAtMs() == null - && "dispatch-1".equals(followup.getAutomationDispatchId()) - && "work-1".equals(followup.getAutomationWorkItemId()) - && "script-1".equals(followup.getScriptId()) - && "patch-1".equals(followup.getScriptPatchVersion()) - && Long.valueOf(100L).equals(followup.getScriptPatchBaseVersionId()) - && "plugin-1".equals(followup.getPluginId()) - && "plugin-v1".equals(followup.getPluginVersionId()) - && "demo".equals(followup.getWorldSlug()) - && "production".equals(followup.getRealmSlug()) - && Long.valueOf(17L).equals(followup.getPointerVersion()))); + argThat(followup -> + "SHARED".equals(followup.getPlayableStateScope()) + && "cmd-1".equals(followup.getCommandId()) + && "entity:entity-9".equals(followup.getClaimTargetAggregate()) + && "enqueue_automation_command".equals(followup.getPayloadKind()) + && "LOOK".equals(followup.getRequestedCommand()) + && followup.isRequiresSoloTick() + && "REMOTE_FOLLOWUP".equals(followup.getOriginSourceKind()) + && "TARGET_REGION_EXECUTED".equals(followup.getOriginSourceState()) + && Long.valueOf(44L).equals(followup.getOriginSourceOrdinal()) + && Long.valueOf(22L).equals(followup.getOriginSourceDueTickId()) + && Long.valueOf(1700L).equals(followup.getOriginSourceDueAtMs()) + && "REMOTE_FOLLOWUP".equals(followup.getQueueSourceKind()) + && "TARGET_REGION_SCHEDULED".equals(followup.getQueueSourceState()) + && followup.getQueueSourceOrdinal() == null + && Long.valueOf(22L).equals(followup.getQueueSourceDueTickId()) + && followup.getQueueSourceDueAtMs() == null + && "dispatch-1".equals(followup.getAutomationDispatchId()) + && "work-1".equals(followup.getAutomationWorkItemId()) + && "script-1".equals(followup.getScriptId()) + && "patch-1".equals(followup.getScriptPatchVersion()) + && Long.valueOf(100L).equals(followup.getScriptPatchBaseVersionId()) + && "plugin-1".equals(followup.getPluginId()) + && "plugin-v1".equals(followup.getPluginVersionId()) + && "demo".equals(followup.getWorldSlug()) + && "production".equals(followup.getRealmSlug()) + && Long.valueOf(17L).equals(followup.getPointerVersion()))); verify(valueOperations) .set("remote:{tenant:1:instance:8}:entity-9", "1", java.time.Duration.ofMillis(60_000L)); } @@ -356,42 +352,40 @@ void scheduleFollowupUsesRequestMetadataWhenCommandRowIsMissing() { assertTrue(outcome.followupCreated()); verify(coordinatorRepository) .save( - argThat( - coordinator -> - "SHARED".equals(coordinator.getPlayableStateScope()) - && "dispatch-1".equals(coordinator.getAutomationDispatchId()) - && "work-1".equals(coordinator.getAutomationWorkItemId()) - && "script-1".equals(coordinator.getScriptId()) - && "patch-1".equals(coordinator.getScriptPatchVersion()) - && "plugin-1".equals(coordinator.getPluginId()) - && "plugin-v1".equals(coordinator.getPluginVersionId()) - && "demo".equals(coordinator.getWorldSlug()) - && "production".equals(coordinator.getRealmSlug()) - && Long.valueOf(17L).equals(coordinator.getPointerVersion()))); + argThat(coordinator -> + "SHARED".equals(coordinator.getPlayableStateScope()) + && "dispatch-1".equals(coordinator.getAutomationDispatchId()) + && "work-1".equals(coordinator.getAutomationWorkItemId()) + && "script-1".equals(coordinator.getScriptId()) + && "patch-1".equals(coordinator.getScriptPatchVersion()) + && "plugin-1".equals(coordinator.getPluginId()) + && "plugin-v1".equals(coordinator.getPluginVersionId()) + && "demo".equals(coordinator.getWorldSlug()) + && "production".equals(coordinator.getRealmSlug()) + && Long.valueOf(17L).equals(coordinator.getPointerVersion()))); verify(followupRepository) .save( - argThat( - followup -> - "SHARED".equals(followup.getPlayableStateScope()) - && "cmd-1".equals(followup.getCommandId()) - && "entity:entity-9".equals(followup.getClaimTargetAggregate()) - && "enqueue_automation_command".equals(followup.getPayloadKind()) - && "LOOK".equals(followup.getRequestedCommand()) - && followup.isRequiresSoloTick() - && "REMOTE_FOLLOWUP".equals(followup.getQueueSourceKind()) - && "TARGET_REGION_SCHEDULED".equals(followup.getQueueSourceState()) - && followup.getQueueSourceOrdinal() == null - && Long.valueOf(22L).equals(followup.getQueueSourceDueTickId()) - && followup.getQueueSourceDueAtMs() == null - && "dispatch-1".equals(followup.getAutomationDispatchId()) - && "work-1".equals(followup.getAutomationWorkItemId()) - && "script-1".equals(followup.getScriptId()) - && "patch-1".equals(followup.getScriptPatchVersion()) - && "plugin-1".equals(followup.getPluginId()) - && "plugin-v1".equals(followup.getPluginVersionId()) - && "demo".equals(followup.getWorldSlug()) - && "production".equals(followup.getRealmSlug()) - && Long.valueOf(17L).equals(followup.getPointerVersion()))); + argThat(followup -> + "SHARED".equals(followup.getPlayableStateScope()) + && "cmd-1".equals(followup.getCommandId()) + && "entity:entity-9".equals(followup.getClaimTargetAggregate()) + && "enqueue_automation_command".equals(followup.getPayloadKind()) + && "LOOK".equals(followup.getRequestedCommand()) + && followup.isRequiresSoloTick() + && "REMOTE_FOLLOWUP".equals(followup.getQueueSourceKind()) + && "TARGET_REGION_SCHEDULED".equals(followup.getQueueSourceState()) + && followup.getQueueSourceOrdinal() == null + && Long.valueOf(22L).equals(followup.getQueueSourceDueTickId()) + && followup.getQueueSourceDueAtMs() == null + && "dispatch-1".equals(followup.getAutomationDispatchId()) + && "work-1".equals(followup.getAutomationWorkItemId()) + && "script-1".equals(followup.getScriptId()) + && "patch-1".equals(followup.getScriptPatchVersion()) + && "plugin-1".equals(followup.getPluginId()) + && "plugin-v1".equals(followup.getPluginVersionId()) + && "demo".equals(followup.getWorldSlug()) + && "production".equals(followup.getRealmSlug()) + && Long.valueOf(17L).equals(followup.getPointerVersion()))); } @Test @@ -556,20 +550,18 @@ void scheduleFollowupDropsPartialRoutingBundle() { assertTrue(outcome.followupCreated()); verify(coordinatorRepository) .save( - argThat( - coordinator -> - coordinator.getPlayableStateScope() == null - && coordinator.getWorldSlug() == null - && coordinator.getRealmSlug() == null - && coordinator.getPointerVersion() == null)); + argThat(coordinator -> + coordinator.getPlayableStateScope() == null + && coordinator.getWorldSlug() == null + && coordinator.getRealmSlug() == null + && coordinator.getPointerVersion() == null)); verify(followupRepository) .save( - argThat( - followup -> - followup.getPlayableStateScope() == null - && followup.getWorldSlug() == null - && followup.getRealmSlug() == null - && followup.getPointerVersion() == null)); + argThat(followup -> + followup.getPlayableStateScope() == null + && followup.getWorldSlug() == null + && followup.getRealmSlug() == null + && followup.getPointerVersion() == null)); } @Test @@ -629,20 +621,18 @@ void scheduleFollowupDropsPartialRoutingBundleWhenOnlyPointerVersionIsProvided() assertTrue(outcome.followupCreated()); verify(coordinatorRepository) .save( - argThat( - coordinator -> - coordinator.getPlayableStateScope() == null - && coordinator.getWorldSlug() == null - && coordinator.getRealmSlug() == null - && coordinator.getPointerVersion() == null)); + argThat(coordinator -> + coordinator.getPlayableStateScope() == null + && coordinator.getWorldSlug() == null + && coordinator.getRealmSlug() == null + && coordinator.getPointerVersion() == null)); verify(followupRepository) .save( - argThat( - followup -> - followup.getPlayableStateScope() == null - && followup.getWorldSlug() == null - && followup.getRealmSlug() == null - && followup.getPointerVersion() == null)); + argThat(followup -> + followup.getPlayableStateScope() == null + && followup.getWorldSlug() == null + && followup.getRealmSlug() == null + && followup.getPointerVersion() == null)); } @Test @@ -656,19 +646,17 @@ void scheduleFollowupAllowsRetryWhenPartialRequestCollapsedToStoredAbsentRouting 1L, 8L, "region-b", 8L, "effect-1")) .thenAnswer(invocation -> Optional.ofNullable(storedFollowup.get())); when(coordinatorRepository.save(any())) - .thenAnswer( - invocation -> { - RemoteCommandCoordinator coordinator = invocation.getArgument(0); - storedCoordinator.set(coordinator); - return coordinator; - }); + .thenAnswer(invocation -> { + RemoteCommandCoordinator coordinator = invocation.getArgument(0); + storedCoordinator.set(coordinator); + return coordinator; + }); when(followupRepository.save(any())) - .thenAnswer( - invocation -> { - RemoteFollowup followup = invocation.getArgument(0); - storedFollowup.set(followup); - return followup; - }); + .thenAnswer(invocation -> { + RemoteFollowup followup = invocation.getArgument(0); + storedFollowup.set(followup); + return followup; + }); when(gameplayCommandRepository.findByTenantIdAndGameInstanceIdAndCommandId(1L, 7L, "cmd-1")) .thenReturn(Optional.empty()); @@ -1333,24 +1321,22 @@ void scheduleFollowupUsesOriginInstanceWhenCommandIdIsReused() { .findByTenantIdAndOriginGameInstanceIdAndCommandId(1L, 8L, "cmd-1"); verify(coordinatorRepository) .save( - argThat( - coordinator -> - Long.valueOf(1L).equals(coordinator.getTenantId()) - && Long.valueOf(8L).equals(coordinator.getOriginGameInstanceId()) - && "cmd-1".equals(coordinator.getCommandId()) - && "followup-origin-8".equals(coordinator.getFollowupId()))); + argThat(coordinator -> + Long.valueOf(1L).equals(coordinator.getTenantId()) + && Long.valueOf(8L).equals(coordinator.getOriginGameInstanceId()) + && "cmd-1".equals(coordinator.getCommandId()) + && "followup-origin-8".equals(coordinator.getFollowupId()))); verify(followupRepository) .findByTenantIdAndTargetGameInstanceIdAndTargetRegionIdAndTargetRegionEpochAndEffectKey( 1L, 8L, "region-b", 8L, "effect-origin-8"); verify(followupRepository) .save( - argThat( - followup -> - Long.valueOf(1L).equals(followup.getTenantId()) - && Long.valueOf(8L).equals(followup.getOriginGameInstanceId()) - && "cmd-1".equals(followup.getCommandId()) - && "followup-origin-8".equals(followup.getFollowupId()) - && "effect-origin-8".equals(followup.getEffectKey()))); + argThat(followup -> + Long.valueOf(1L).equals(followup.getTenantId()) + && Long.valueOf(8L).equals(followup.getOriginGameInstanceId()) + && "cmd-1".equals(followup.getCommandId()) + && "followup-origin-8".equals(followup.getFollowupId()) + && "effect-origin-8".equals(followup.getEffectKey()))); verify(coordinatorRepository, never()).save(argThat(saved -> saved == existing)); verify(followupRepository, never()).save(argThat(saved -> saved == existingFollowup)); assertEquals(1L, existing.getTenantId()); @@ -1606,12 +1592,11 @@ void scheduleFollowupAcceptsExplicitPayloadAuthorityWithoutPayloadJson() { assertTrue(outcome.followupCreated()); verify(followupRepository) .save( - argThat( - followup -> - followup.getPayloadJson() == null - && "enqueue_automation_command".equals(followup.getPayloadKind()) - && "LOOK".equals(followup.getRequestedCommand()) - && followup.isRequiresSoloTick())); + argThat(followup -> + followup.getPayloadJson() == null + && "enqueue_automation_command".equals(followup.getPayloadKind()) + && "LOOK".equals(followup.getRequestedCommand()) + && followup.isRequiresSoloTick())); } @Test @@ -1632,18 +1617,17 @@ void scheduleFollowupAcceptsTriggerScriptEventPayload() { assertTrue(outcome.followupCreated()); verify(followupRepository) .save( - argThat( - followup -> - "trigger_script_event".equals(followup.getPayloadKind()) - && followup.getRequestedCommand() == null - && "321".equals(followup.getTargetEntityId()) - && "onEnterRegion".equals(followup.getEventType()) - && "v1".equals(followup.getEventSchemaVersion()) - && "remote-enter-1".equals(followup.getScriptEventId()) - && "game-session:onEnterRegion:9:8:remote-enter-1" - .equals(followup.getReadSnapshotToken()) - && "{\"fromRegionId\":\"R-101\",\"toRegionId\":\"R-102\"}" - .equals(followup.getEventPayloadJson()))); + argThat(followup -> + "trigger_script_event".equals(followup.getPayloadKind()) + && followup.getRequestedCommand() == null + && "321".equals(followup.getTargetEntityId()) + && "onEnterRegion".equals(followup.getEventType()) + && "v1".equals(followup.getEventSchemaVersion()) + && "remote-enter-1".equals(followup.getScriptEventId()) + && "game-session:onEnterRegion:9:8:remote-enter-1" + .equals(followup.getReadSnapshotToken()) + && "{\"fromRegionId\":\"R-101\",\"toRegionId\":\"R-102\"}" + .equals(followup.getEventPayloadJson()))); } @Test @@ -2047,25 +2031,24 @@ void recordResultPersistsTerminalTargetOutcomeWithoutMutatingPendingCoordinator( assertFalse(outcome.reconciledLateResult()); verify(resultRepository) .save( - argThat( - result -> - Long.valueOf(7L).equals(result.getOriginGameInstanceId()) - && Long.valueOf(8L).equals(result.getTargetGameInstanceId()) - && "SHARED".equals(result.getPlayableStateScope()) - && "cmd-1".equals(result.getCommandId()) - && "auto-1".equals(result.getResultCommandId()) - && "RATE_LIMIT".equals(result.getResultErrorCode()) - && "Target region rejected the command".equals(result.getResultMessage()) - && "dispatch-1".equals(result.getAutomationDispatchId()) - && "work-1".equals(result.getAutomationWorkItemId()) - && "script-1".equals(result.getScriptId()) - && "patch-1".equals(result.getScriptPatchVersion()) - && Long.valueOf(100L).equals(result.getScriptPatchBaseVersionId()) - && "plugin-1".equals(result.getPluginId()) - && "plugin-v1".equals(result.getPluginVersionId()) - && "demo".equals(result.getWorldSlug()) - && "production".equals(result.getRealmSlug()) - && Long.valueOf(17L).equals(result.getPointerVersion()))); + argThat(result -> + Long.valueOf(7L).equals(result.getOriginGameInstanceId()) + && Long.valueOf(8L).equals(result.getTargetGameInstanceId()) + && "SHARED".equals(result.getPlayableStateScope()) + && "cmd-1".equals(result.getCommandId()) + && "auto-1".equals(result.getResultCommandId()) + && "RATE_LIMIT".equals(result.getResultErrorCode()) + && "Target region rejected the command".equals(result.getResultMessage()) + && "dispatch-1".equals(result.getAutomationDispatchId()) + && "work-1".equals(result.getAutomationWorkItemId()) + && "script-1".equals(result.getScriptId()) + && "patch-1".equals(result.getScriptPatchVersion()) + && Long.valueOf(100L).equals(result.getScriptPatchBaseVersionId()) + && "plugin-1".equals(result.getPluginId()) + && "plugin-v1".equals(result.getPluginVersionId()) + && "demo".equals(result.getWorldSlug()) + && "production".equals(result.getRealmSlug()) + && Long.valueOf(17L).equals(result.getPointerVersion()))); verify(coordinatorRepository, never()).save(any()); } @@ -2125,12 +2108,11 @@ void recordResultDropsPartialStoredRoutingBundleFromResultProjection() { verify(resultRepository) .save( - argThat( - result -> - result.getPlayableStateScope() == null - && result.getWorldSlug() == null - && result.getRealmSlug() == null - && result.getPointerVersion() == null)); + argThat(result -> + result.getPlayableStateScope() == null + && result.getWorldSlug() == null + && result.getRealmSlug() == null + && result.getPointerVersion() == null)); } @Test @@ -2204,12 +2186,11 @@ void recordResultAcceptsExplicitAuthorityWithoutPayloadJson() { RemoteFollowupRuntimeServiceImpl.COORDINATOR_PENDING_REMOTE, outcome.coordinatorState()); verify(resultRepository) .save( - argThat( - result -> - result.getResultPayloadJson() == null - && "auto-1".equals(result.getResultCommandId()) - && "RATE_LIMIT".equals(result.getResultErrorCode()) - && "Target region rejected the command".equals(result.getResultMessage()))); + argThat(result -> + result.getResultPayloadJson() == null + && "auto-1".equals(result.getResultCommandId()) + && "RATE_LIMIT".equals(result.getResultErrorCode()) + && "Target region rejected the command".equals(result.getResultMessage()))); } @Test @@ -3003,26 +2984,25 @@ void abandonScopeInvalidFollowupPersistsCoordinatorScopedFailureResult() { verify(resultRepository) .save( - argThat( - result -> - "remote-result:followup-1".equals(result.getResultId()) - && "coord-1".equals(result.getCoordinatorId()) - && "followup-1".equals(result.getFollowupId()) - && Long.valueOf(7L).equals(result.getOriginGameInstanceId()) - && "region-a".equals(result.getOriginRegionId()) - && Long.valueOf(4L).equals(result.getOriginRegionEpoch()) - && Long.valueOf(8L).equals(result.getTargetGameInstanceId()) - && "region-b".equals(result.getTargetRegionId()) - && Long.valueOf(8L).equals(result.getTargetRegionEpoch()) - && "ABANDONED".equals(result.getOutcome()) - && "{}".equals(result.getResultPayloadJson()) - && "REMOTE_FOLLOWUP_SCOPE_INVALID".equals(result.getResultErrorCode()) - && "Remote followup execution scope does not match its coordinator" - .equals(result.getResultMessage()) - && "SHARED".equals(result.getPlayableStateScope()) - && "demo".equals(result.getWorldSlug()) - && "production".equals(result.getRealmSlug()) - && Long.valueOf(17L).equals(result.getPointerVersion()))); + argThat(result -> + "remote-result:followup-1".equals(result.getResultId()) + && "coord-1".equals(result.getCoordinatorId()) + && "followup-1".equals(result.getFollowupId()) + && Long.valueOf(7L).equals(result.getOriginGameInstanceId()) + && "region-a".equals(result.getOriginRegionId()) + && Long.valueOf(4L).equals(result.getOriginRegionEpoch()) + && Long.valueOf(8L).equals(result.getTargetGameInstanceId()) + && "region-b".equals(result.getTargetRegionId()) + && Long.valueOf(8L).equals(result.getTargetRegionEpoch()) + && "ABANDONED".equals(result.getOutcome()) + && "{}".equals(result.getResultPayloadJson()) + && "REMOTE_FOLLOWUP_SCOPE_INVALID".equals(result.getResultErrorCode()) + && "Remote followup execution scope does not match its coordinator" + .equals(result.getResultMessage()) + && "SHARED".equals(result.getPlayableStateScope()) + && "demo".equals(result.getWorldSlug()) + && "production".equals(result.getRealmSlug()) + && Long.valueOf(17L).equals(result.getPointerVersion()))); verify(coordinatorRepository, never()).save(any()); assertEquals(RemoteFollowupRuntimeServiceImpl.FOLLOWUP_ABANDONED, followup.getStatus()); assertEquals(null, followup.getClaimedTickBatchId()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java index 205d5acb55..0e349e88c8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TcpProxyServiceImplTest.java @@ -53,13 +53,12 @@ void validDisconnectHintIsAcknowledgedAfterReadOnlyInstanceValidation() { void notifyDisconnectRetainsGameplayLoggingContext() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); Mockito.when(repository.findById(12L)) - .thenAnswer( - ignored -> { - assertEquals("7", MDC.get("tenantId")); - assertEquals("12", MDC.get("gameInstanceId")); - assertEquals(null, MDC.get("characterId")); - return Optional.of(buildEntity(12L, 7L)); - }); + .thenAnswer(ignored -> { + assertEquals("7", MDC.get("tenantId")); + assertEquals("12", MDC.get("gameInstanceId")); + assertEquals(null, MDC.get("characterId")); + return Optional.of(buildEntity(12L, 7L)); + }); TcpProxyServiceImpl service = service(repository, new SimpleMeterRegistry(), acceptingDeduplication()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java index 51f0dc3518..ea91c0384c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java @@ -71,14 +71,13 @@ void setup() { gameplayCommandRepository = mock(GameplayCommandRepository.class); AtomicLong commandIds = new AtomicLong(); when(gameplayCommandRepository.save(any())) - .thenAnswer( - invocation -> { - GameplayCommand command = invocation.getArgument(0); - if (command.getId() == null) { - command.setId(commandIds.incrementAndGet()); - } - return command; - }); + .thenAnswer(invocation -> { + GameplayCommand command = invocation.getArgument(0); + if (command.getId() == null) { + command.setId(commandIds.incrementAndGet()); + } + return command; + }); tickBatchRepository = mock(TickBatchRepository.class); when(tickBatchRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); tickEffectRepository = mock(TickEffectRepository.class); @@ -86,12 +85,11 @@ void setup() { when(tickEffectRepository.saveAll(any())).thenAnswer(invocation -> invocation.getArgument(0)); runtimeRegionStatusRepository = mock(RuntimeRegionStatusRepository.class); when(runtimeRegionStatusRepository.commitDrainedBatch(any(), any())) - .thenAnswer( - invocation -> { - RuntimeRegionStatus expected = invocation.getArgument(0); - expected.setLastCommittedTickBatchId(invocation.getArgument(1)); - return Optional.of(expected); - }); + .thenAnswer(invocation -> { + RuntimeRegionStatus expected = invocation.getArgument(0); + expected.setLastCommittedTickBatchId(invocation.getArgument(1)); + return Optional.of(expected); + }); remoteFollowupDrainService = mock(RemoteFollowupDrainService.class); durableGameplayCommandExecutionService = mock(DurableGameplayCommandExecutionService.class); durableRemoteFollowupExecutionService = mock(DurableRemoteFollowupExecutionService.class); @@ -525,17 +523,15 @@ void executeDurableEffectsRequeuesAfterMidBatchStaleFenceAndContinuesNextBatch() Optional.of(currentOwnership)); when(tickEffectRepository.findByTickBatchIdAndStatusOrderByIdAsc( "tb-stale-mid-batch", "DRAINED")) - .thenAnswer( - invocation -> - List.of(appliedEffect, staleEffect).stream() - .filter(effect -> "DRAINED".equals(effect.getStatus())) - .toList()); + .thenAnswer(invocation -> + List.of(appliedEffect, staleEffect).stream() + .filter(effect -> "DRAINED".equals(effect.getStatus())) + .toList()); when(tickEffectRepository.findByTickBatchIdAndStatusOrderByIdAsc("tb-subsequent", "DRAINED")) - .thenAnswer( - invocation -> - List.of(subsequentEffect).stream() - .filter(effect -> "DRAINED".equals(effect.getStatus())) - .toList()); + .thenAnswer(invocation -> + List.of(subsequentEffect).stream() + .filter(effect -> "DRAINED".equals(effect.getStatus())) + .toList()); when(gameplayCommandRepository.findByTenantIdAndGameInstanceIdAndCommandId( 1L, 2L, "cmd-applied")) .thenReturn(Optional.of(appliedCommand)); @@ -700,11 +696,10 @@ void remoteFailureAbandonsOnlyUnfinishedEffectsAfterLaterFailure() { .thenReturn(List.of(appliedEffect, remainingEffect)); when(tickEffectRepository.findByTickBatchIdAndStatusOrderByIdAsc( "tb-remote-partial", "DRAINED")) - .thenAnswer( - invocation -> - List.of(appliedEffect, remainingEffect).stream() - .filter(effect -> "DRAINED".equals(effect.getStatus())) - .toList()); + .thenAnswer(invocation -> + List.of(appliedEffect, remainingEffect).stream() + .filter(effect -> "DRAINED".equals(effect.getStatus())) + .toList()); when(durableRemoteFollowupExecutionService.execute(appliedEffect)) .thenReturn( new DurableRemoteFollowupExecutionService.DurableRemoteFollowupExecutionResult( @@ -953,10 +948,9 @@ void restorePendingProjectionCompletesAfterPostCommitRequeueBookkeepingFailure() .when(gameplayCommandRepository) .findByTenantIdAndGameInstanceIdAndCommandIdIn(1L, 2L, List.of("cmd-2")); - assertDoesNotThrow( - () -> - service.restorePendingProjection( - activeLease, 1L, 2L, List.of(sealed, redisOnly), List.of(sealed))); + assertDoesNotThrow(() -> + service.restorePendingProjection( + activeLease, 1L, 2L, List.of(sealed, redisOnly), List.of(sealed))); verify(redisTemplate).execute(any(), any(), any(Object[].class)); assertEquals( @@ -1059,10 +1053,9 @@ void restorePendingProjectionBoundsRequeueMetricSourceLabels() { assertTrue( meterRegistry.getMeters().stream() .filter(meter -> "tick_requeued_action_total".equals(meter.getId().getName())) - .allMatch( - meter -> - java.util.Set.of("player", "automation", "remote_followup", "unknown") - .contains(meter.getId().getTag("source")))); + .allMatch(meter -> + java.util.Set.of("player", "automation", "remote_followup", "unknown") + .contains(meter.getId().getTag("source")))); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java index 6f12e16184..44cd1c2230 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java @@ -81,14 +81,13 @@ void setup() { gameplayCommandRepository = mock(GameplayCommandRepository.class); AtomicLong commandIds = new AtomicLong(); when(gameplayCommandRepository.save(any())) - .thenAnswer( - invocation -> { - GameplayCommand command = invocation.getArgument(0); - if (command.getId() == null) { - command.setId(commandIds.incrementAndGet()); - } - return command; - }); + .thenAnswer(invocation -> { + GameplayCommand command = invocation.getArgument(0); + if (command.getId() == null) { + command.setId(commandIds.incrementAndGet()); + } + return command; + }); when(gameplayCommandRepository.markAcceptedCommandStaged( any(Long.class), any(Long.class), any(String.class), any(Instant.class))) .thenReturn(true); @@ -104,15 +103,14 @@ void setup() { .thenAnswer(invocation -> invocation.getArgument(0)); when(runtimeRegionStatusRepository.claimObservedOwnership( any(), any(String.class), any(String.class), any(String.class), any(Instant.class))) - .thenAnswer( - invocation -> { - RuntimeRegionStatus status = invocation.getArgument(0); - status.setOwnerService(invocation.getArgument(1)); - status.setOwnerInstanceId(invocation.getArgument(2)); - status.setExecutorFence(invocation.getArgument(3)); - status.setUpdatedAt(invocation.getArgument(4)); - return Optional.of(status); - }); + .thenAnswer(invocation -> { + RuntimeRegionStatus status = invocation.getArgument(0); + status.setOwnerService(invocation.getArgument(1)); + status.setOwnerInstanceId(invocation.getArgument(2)); + status.setExecutorFence(invocation.getArgument(3)); + status.setUpdatedAt(invocation.getArgument(4)); + return Optional.of(status); + }); when(runtimeRegionStatusRepository.advanceOwnershipEpoch(any())) .thenAnswer(invocation -> invocation.getArgument(0)); sessionAuthenticationService = mock(SessionAuthenticationService.class); @@ -273,9 +271,8 @@ void enqueueCommandRemovesPayloadWhenTransactionRollsBack() { verify(listOps, never()).remove(any(), anyLong(), any()); TransactionSynchronizationManager.getSynchronizations() - .forEach( - synchronization -> - synchronization.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK)); + .forEach(synchronization -> + synchronization.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK)); verify(listOps).remove("gamesession:tick:queue:1:2", -1, "N|cmd-rollback|look"); } finally { @@ -296,9 +293,8 @@ void enqueueCommandFailsClosedWhenQueueLeaseIsLostBeforeCommit() { TransactionSynchronizationManager.getSynchronizations() .forEach(synchronization -> synchronization.beforeCommit(false))); TransactionSynchronizationManager.getSynchronizations() - .forEach( - synchronization -> - synchronization.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK)); + .forEach(synchronization -> + synchronization.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK)); verify(listOps).remove("gamesession:tick:queue:1:2", -1, "N|cmd-lease-loss|look"); } finally { @@ -528,9 +524,8 @@ void purgeRemovesQueuePayloadOnlyAfterTransactionCommit() { verify(listOps).remove("gamesession:tick:queue:1:2", 0, "N|cmd-rollback|say recover"); verify(listOps).remove("gamesession:tick:pending:1:2", 0, "N|cmd-rollback|say recover"); TransactionSynchronizationManager.getSynchronizations() - .forEach( - synchronization -> - synchronization.afterCompletion(TransactionSynchronization.STATUS_COMMITTED)); + .forEach(synchronization -> + synchronization.afterCompletion(TransactionSynchronization.STATUS_COMMITTED)); } finally { TransactionSynchronizationManager.clearSynchronization(); } @@ -583,10 +578,9 @@ void purgeStopsPostCommitCleanupWhenRedisCleanupLosesLease() throws Exception { 1L, 2L, "region-1", "patch-1", "rollback", logger)); org.mockito.Mockito.clearInvocations(scriptTemplate); - assertDoesNotThrow( - () -> - TransactionSynchronizationManager.getSynchronizations() - .forEach(TransactionSynchronization::afterCommit)); + assertDoesNotThrow(() -> + TransactionSynchronizationManager.getSynchronizations() + .forEach(TransactionSynchronization::afterCommit)); verify(scriptTemplate, times(1)) .execute( @@ -606,9 +600,8 @@ void purgeStopsPostCommitCleanupWhenRedisCleanupLosesLease() throws Exception { any(TickQueueControlService.QueueUnavailableException.class)); } finally { TransactionSynchronizationManager.getSynchronizations() - .forEach( - synchronization -> - synchronization.afterCompletion(TransactionSynchronization.STATUS_COMMITTED)); + .forEach(synchronization -> + synchronization.afterCompletion(TransactionSynchronization.STATUS_COMMITTED)); TransactionSynchronizationManager.clearSynchronization(); } } @@ -640,10 +633,9 @@ void purgeSkipsMalformedCommandIdDuringPostCommitCleanupAndContinues() { service.purgeQueuedAutomationCommandsForScriptPatch( 1L, 2L, "region-1", "patch-1", "rollback", logger)); - assertDoesNotThrow( - () -> - TransactionSynchronizationManager.getSynchronizations() - .forEach(TransactionSynchronization::afterCommit)); + assertDoesNotThrow(() -> + TransactionSynchronizationManager.getSynchronizations() + .forEach(TransactionSynchronization::afterCommit)); verify(listOps) .remove("gamesession:tick:queue:1:2", 0, "N|cmd-valid-after-malformed|say continue"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressServiceTest.java index 257f674332..3f82335223 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressServiceTest.java @@ -72,12 +72,11 @@ void setup() { setField(service, "tickDurationMs", 1000L); setField(service, "maxRemoteFollowupsPerTick", 16); when(runtimeRegionStatusRepository.advanceLastCommittedTickId(any())) - .thenAnswer( - invocation -> { - RuntimeRegionStatus expected = invocation.getArgument(0); - expected.setLastCommittedTickId(expected.getLastCommittedTickId() + 1L); - return Optional.of(expected); - }); + .thenAnswer(invocation -> { + RuntimeRegionStatus expected = invocation.getArgument(0); + expected.setLastCommittedTickId(expected.getLastCommittedTickId() + 1L); + return Optional.of(expected); + }); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java index 4ce64ecf3c..f25b59d215 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java @@ -98,15 +98,14 @@ void setup() { mock(net.firedevops.firemud.gamesession.repository.GameplayCommandRepository.class); AtomicLong commandIds = new AtomicLong(); when(gameplayCommandRepository.save(any())) - .thenAnswer( - invocation -> { - net.firedevops.firemud.gamesession.entity.GameplayCommand command = - invocation.getArgument(0); - if (command.getId() == null) { - command.setId(commandIds.incrementAndGet()); - } - return command; - }); + .thenAnswer(invocation -> { + net.firedevops.firemud.gamesession.entity.GameplayCommand command = + invocation.getArgument(0); + if (command.getId() == null) { + command.setId(commandIds.incrementAndGet()); + } + return command; + }); when(gameplayCommandRepository.markAcceptedCommandStaged( any(Long.class), any(Long.class), any(String.class), any(Instant.class))) .thenReturn(true); @@ -225,54 +224,45 @@ void setup() { .thenAnswer(invocation -> invocation.getArgument(0)); when(runtimeRegionStatusRepository.claimObservedOwnership( any(), any(String.class), any(String.class), any(String.class), any(Instant.class))) - .thenAnswer( - invocation -> { - net.firedevops.firemud.gamesession.entity.RuntimeRegionStatus status = - invocation.getArgument(0); - status.setOwnerService(invocation.getArgument(1)); - status.setOwnerInstanceId(invocation.getArgument(2)); - status.setUpdatedAt(invocation.getArgument(4)); - return Optional.of(status); - }); + .thenAnswer(invocation -> { + net.firedevops.firemud.gamesession.entity.RuntimeRegionStatus status = + invocation.getArgument(0); + status.setOwnerService(invocation.getArgument(1)); + status.setOwnerInstanceId(invocation.getArgument(2)); + status.setUpdatedAt(invocation.getArgument(4)); + return Optional.of(status); + }); when(runtimeRegionStatusRepository.advanceOwnershipEpoch(any())) .thenAnswer(invocation -> invocation.getArgument(0)); when(runtimeRegionStatusRepository.advanceLastCommittedTickId(any())) - .thenAnswer( - invocation -> { - net.firedevops.firemud.gamesession.entity.RuntimeRegionStatus expected = - invocation.getArgument(0); - expected.setLastCommittedTickId(expected.getLastCommittedTickId() + 1L); - return Optional.of(expected); - }); + .thenAnswer(invocation -> { + net.firedevops.firemud.gamesession.entity.RuntimeRegionStatus expected = + invocation.getArgument(0); + expected.setLastCommittedTickId(expected.getLastCommittedTickId() + 1L); + return Optional.of(expected); + }); when(runtimeRegionStatusRepository.commitDrainedBatch(any(), any())) - .thenAnswer( - invocation -> { - net.firedevops.firemud.gamesession.entity.RuntimeRegionStatus expected = - invocation.getArgument(0); - expected.setLastCommittedTickBatchId(invocation.getArgument(1)); - return Optional.of(expected); - }); + .thenAnswer(invocation -> { + net.firedevops.firemud.gamesession.entity.RuntimeRegionStatus expected = + invocation.getArgument(0); + expected.setLastCommittedTickBatchId(invocation.getArgument(1)); + return Optional.of(expected); + }); when(runtimeRegionStatusRepository.findByTenantIdAndGameInstanceId(anyLong(), anyLong())) - .thenAnswer( - invocation -> - Optional.of( - runtimeOwnership( - invocation.getArgument(0), - invocation.getArgument(1), - 1L, - "fence-a", - false))); + .thenAnswer(invocation -> + Optional.of( + runtimeOwnership( + invocation.getArgument(0), invocation.getArgument(1), 1L, "fence-a", false))); when(runtimeRegionStatusRepository.findByTenantIdAndRegionId(anyLong(), any())) - .thenAnswer( - invocation -> - Optional.of( - runtimeOwnershipByRegionId( - invocation.getArgument(0), - 2L, - invocation.getArgument(1), - 1L, - "fence-a", - false))); + .thenAnswer(invocation -> + Optional.of( + runtimeOwnershipByRegionId( + invocation.getArgument(0), + 2L, + invocation.getArgument(1), + 1L, + "fence-a", + false))); when(tickBatchRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); when(tickEffectRepository.findByTickBatchId(any())).thenReturn(List.of()); when(tickEffectRepository.saveAll(any())).thenAnswer(invocation -> invocation.getArgument(0)); @@ -310,11 +300,10 @@ void processTickUsesGameplayNamespacedLockAndPendingKeys() { void processTickPassesExactLeaseFenceToCommitScript() { List leaseTokens = new ArrayList<>(); when(lockValueOps.setIfAbsent(any(String.class), any(String.class), any(Duration.class))) - .thenAnswer( - invocation -> { - leaseTokens.add(invocation.getArgument(1)); - return true; - }); + .thenAnswer(invocation -> { + leaseTokens.add(invocation.getArgument(1)); + return true; + }); RedisScript commitMarker = mock(RedisScript.class); setField(service, "commitScript", commitMarker); List> commitKeys = new ArrayList<>(); @@ -354,11 +343,10 @@ void processTickPassesExactLeaseFenceToCommitScript() { void processTickPassesExactLeaseFenceToStageScript() { List leaseTokens = new ArrayList<>(); when(lockValueOps.setIfAbsent(any(String.class), any(String.class), any(Duration.class))) - .thenAnswer( - invocation -> { - leaseTokens.add(invocation.getArgument(1)); - return true; - }); + .thenAnswer(invocation -> { + leaseTokens.add(invocation.getArgument(1)); + return true; + }); RedisScript stageMarker = mock(RedisScript.class); setField(service, "stageScript", stageMarker); setField(service, "tickMaxCommands", 50); @@ -587,11 +575,10 @@ void processTickDoesNotAbandonBatchAfterStaleRollbackResult() { List rollbackArguments = new ArrayList<>(); List leaseTokens = new ArrayList<>(); when(lockValueOps.setIfAbsent(any(String.class), any(String.class), any(Duration.class))) - .thenAnswer( - invocation -> { - leaseTokens.add(invocation.getArgument(1)); - return true; - }); + .thenAnswer(invocation -> { + leaseTokens.add(invocation.getArgument(1)); + return true; + }); List savedBatchStatuses = new ArrayList<>(); doAnswer( invocation -> { @@ -762,42 +749,38 @@ void processTickDrainsClaimedRemoteFollowupsIntoDurableBatchEffects() { org.junit.jupiter.api.Assertions.assertTrue( batchCaptor.getAllValues().stream() .filter(batch -> "REMOTE_FOLLOWUP_DRAIN".equals(batch.getBatchSource())) - .anyMatch( - batch -> - batch.getSelectedWorkManifestJson().contains("\"sourceOrdinal\":1") - && batch.getSelectedWorkManifestJson().contains("\"sourceDueTickId\":10") - && batch.getSelectedWorkManifestJson().contains("\"commandId\":\"cmd-1\"") - && batch - .getSelectedWorkManifestJson() - .contains("\"automationDispatchId\":\"dispatch-1\"") - && batch - .getSelectedWorkManifestJson() - .contains("\"scriptPatchVersion\":\"patch-1\"") - && batch.getSelectedWorkManifestJson().contains("\"worldSlug\":\"demo\"") - && batch.getSelectedWorkManifestJson().contains("\"pointerVersion\":17") - && batch - .getSelectedWorkManifestJson() - .contains("\"originSourceKind\":\"REMOTE_FOLLOWUP\"") - && batch - .getSelectedWorkManifestJson() - .contains("\"originSourceOrdinal\":44") - && batch.getSelectedWorkManifestJson().contains("\"payloadKind\":\"noop\"") - && batch.getSelectedWorkManifestJson().contains("\"requiresSoloTick\":true") - && batch - .getSelectedWorkManifestJson() - .contains("\"requestedCommand\":\"LOOK\""))); + .anyMatch(batch -> + batch.getSelectedWorkManifestJson().contains("\"sourceOrdinal\":1") + && batch.getSelectedWorkManifestJson().contains("\"sourceDueTickId\":10") + && batch.getSelectedWorkManifestJson().contains("\"commandId\":\"cmd-1\"") + && batch + .getSelectedWorkManifestJson() + .contains("\"automationDispatchId\":\"dispatch-1\"") + && batch + .getSelectedWorkManifestJson() + .contains("\"scriptPatchVersion\":\"patch-1\"") + && batch.getSelectedWorkManifestJson().contains("\"worldSlug\":\"demo\"") + && batch.getSelectedWorkManifestJson().contains("\"pointerVersion\":17") + && batch + .getSelectedWorkManifestJson() + .contains("\"originSourceKind\":\"REMOTE_FOLLOWUP\"") + && batch.getSelectedWorkManifestJson().contains("\"originSourceOrdinal\":44") + && batch.getSelectedWorkManifestJson().contains("\"payloadKind\":\"noop\"") + && batch.getSelectedWorkManifestJson().contains("\"requiresSoloTick\":true") + && batch + .getSelectedWorkManifestJson() + .contains("\"requestedCommand\":\"LOOK\""))); } @Test void enqueueCommandAddsGameplayLoggingContextWhenSessionIsBound() { when(listOps.rightPush(any(String.class), any(Object.class))) - .thenAnswer( - ignored -> { - org.junit.jupiter.api.Assertions.assertEquals("9", MDC.get("tenantId")); - org.junit.jupiter.api.Assertions.assertNull(MDC.get("gameInstanceId")); - org.junit.jupiter.api.Assertions.assertNull(MDC.get("characterId")); - return 1L; - }); + .thenAnswer(ignored -> { + org.junit.jupiter.api.Assertions.assertEquals("9", MDC.get("tenantId")); + org.junit.jupiter.api.Assertions.assertNull(MDC.get("gameInstanceId")); + org.junit.jupiter.api.Assertions.assertNull(MDC.get("characterId")); + return 1L; + }); service.enqueueCommand(9L, 2L, "cmd-ctx", "look", false); @@ -1453,10 +1436,9 @@ void processTickRejectsStaleOwnershipBeforeDrainCommit() { verify(tickBatchRepository, org.mockito.Mockito.atLeastOnce()).save(batchCaptor.capture()); org.junit.jupiter.api.Assertions.assertTrue( batchCaptor.getAllValues().stream() - .anyMatch( - batch -> - "ABANDONED".equals(batch.getStatus()) - && "STALE_EXECUTOR_FENCE".equals(batch.getFailureCode()))); + .anyMatch(batch -> + "ABANDONED".equals(batch.getStatus()) + && "STALE_EXECUTOR_FENCE".equals(batch.getFailureCode()))); verify(tickEffectRepository).saveAll(any()); verify(remoteFollowupDrainService) .releaseClaimedFollowups( @@ -2208,18 +2190,16 @@ void processTickRequeuesRedisOnlyEntriesWhenReplayFallsBackToSealedManifest() { assertPendingProjectionRestoreInvocation(scriptCaptor, keyCaptor); org.junit.jupiter.api.Assertions.assertTrue( savedSnapshots.stream() - .anyMatch( - saved -> - "cmd-2".equals(saved.getCommandId()) - && "RETRY_QUEUED".equals(saved.getExecutionOutcome()) - && "GAMEPLAY_RETRY".equals(saved.getQueueSourceKind()) - && "REDIS_RETRY_QUEUED".equals(saved.getQueueSourceState()))); + .anyMatch(saved -> + "cmd-2".equals(saved.getCommandId()) + && "RETRY_QUEUED".equals(saved.getExecutionOutcome()) + && "GAMEPLAY_RETRY".equals(saved.getQueueSourceKind()) + && "REDIS_RETRY_QUEUED".equals(saved.getQueueSourceState()))); org.junit.jupiter.api.Assertions.assertFalse( savedSnapshots.stream() - .anyMatch( - saved -> - "cmd-2".equals(saved.getCommandId()) - && "DRAINED".equals(saved.getExecutionOutcome()))); + .anyMatch(saved -> + "cmd-2".equals(saved.getCommandId()) + && "DRAINED".equals(saved.getExecutionOutcome()))); org.junit.jupiter.api.Assertions.assertEquals( 1.0, meterRegistry diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java index a07ce05598..f335756f77 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java @@ -71,14 +71,13 @@ void setup() { gameplayCommandRepository = mock(GameplayCommandRepository.class); AtomicLong commandIds = new AtomicLong(); when(gameplayCommandRepository.save(any())) - .thenAnswer( - invocation -> { - GameplayCommand command = invocation.getArgument(0); - if (command.getId() == null) { - command.setId(commandIds.incrementAndGet()); - } - return command; - }); + .thenAnswer(invocation -> { + GameplayCommand command = invocation.getArgument(0); + if (command.getId() == null) { + command.setId(commandIds.incrementAndGet()); + } + return command; + }); remoteFollowupRepository = mock(RemoteFollowupRepository.class); tickBatchRepository = mock(TickBatchRepository.class); when(tickBatchRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); @@ -168,18 +167,16 @@ void setup() { when(runtimeRegionStatusRepository.save(any())) .thenAnswer(invocation -> invocation.getArgument(0)); when(runtimeRegionStatusRepository.commitDrainedBatch(any(), any())) - .thenAnswer( - invocation -> { - RuntimeRegionStatus expected = invocation.getArgument(0); - expected.setLastCommittedTickBatchId(invocation.getArgument(1)); - return Optional.of(expected); - }); + .thenAnswer(invocation -> { + RuntimeRegionStatus expected = invocation.getArgument(0); + expected.setLastCommittedTickBatchId(invocation.getArgument(1)); + return Optional.of(expected); + }); when(tickEffectRepository.findByTickBatchId(anyString())) - .thenAnswer( - invocation -> - savedEffects.stream() - .filter(effect -> invocation.getArgument(0).equals(effect.getTickBatchId())) - .toList()); + .thenAnswer(invocation -> + savedEffects.stream() + .filter(effect -> invocation.getArgument(0).equals(effect.getTickBatchId())) + .toList()); } @Test @@ -1936,11 +1933,10 @@ public T execute(TransactionCallback action) { assertTrue(events.indexOf("redis-reconcile") > finalTransactionCommit); org.junit.jupiter.api.Assertions.assertTrue( savedSnapshots.stream() - .anyMatch( - saved -> - "cmd-2".equals(saved.getCommandId()) - && "RETRY_QUEUED".equals(saved.getExecutionOutcome()) - && "GAMEPLAY_RETRY".equals(saved.getQueueSourceKind()))); + .anyMatch(saved -> + "cmd-2".equals(saved.getCommandId()) + && "RETRY_QUEUED".equals(saved.getExecutionOutcome()) + && "GAMEPLAY_RETRY".equals(saved.getQueueSourceKind()))); } @Test @@ -2161,32 +2157,27 @@ void postDrainRemoteEffectFailurePreservesTerminalEffectsAndReleasesRemainingCla .save(any()); when(tickBatchRepository.findByTenantIdAndGameInstanceIdAndStatusOrderByCompletedAtAsc( 1L, 2L, "DRAINED")) - .thenAnswer( - invocation -> - savedBatches.isEmpty() - ? List.of() - : List.of(savedBatches.get(savedBatches.size() - 1))); + .thenAnswer(invocation -> + savedBatches.isEmpty() + ? List.of() + : List.of(savedBatches.get(savedBatches.size() - 1))); when(tickEffectRepository.findByTickBatchIdAndStatusOrderByIdAsc(anyString(), eq("DRAINED"))) - .thenAnswer( - invocation -> - savedEffects.stream() - .filter( - effect -> - invocation.getArgument(0, String.class).equals(effect.getTickBatchId())) - .filter( - effect -> - invocation.getArgument(1, String.class).equals(effect.getStatus())) - .toList()); + .thenAnswer(invocation -> + savedEffects.stream() + .filter(effect -> + invocation.getArgument(0, String.class).equals(effect.getTickBatchId())) + .filter( + effect -> invocation.getArgument(1, String.class).equals(effect.getStatus())) + .toList()); when(durableRemoteFollowupExecutionService.execute(any())) - .thenAnswer( - invocation -> { - TickEffect effect = invocation.getArgument(0); - if ("followup-1".equals(effect.getEffectKey())) { - return new DurableRemoteFollowupExecutionService - .DurableRemoteFollowupExecutionResult("APPLIED", null, null); - } - throw new IllegalStateException("remote effect failed"); - }); + .thenAnswer(invocation -> { + TickEffect effect = invocation.getArgument(0); + if ("followup-1".equals(effect.getEffectKey())) { + return new DurableRemoteFollowupExecutionService.DurableRemoteFollowupExecutionResult( + "APPLIED", null, null); + } + throw new IllegalStateException("remote effect failed"); + }); assertThrows( IllegalStateException.class, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/testsupport/GameplayStructuredCommandAssertionsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/testsupport/GameplayStructuredCommandAssertionsTest.java index 1f6783e46d..91abd6af8e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/testsupport/GameplayStructuredCommandAssertionsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/testsupport/GameplayStructuredCommandAssertionsTest.java @@ -104,10 +104,9 @@ void requireStructuredCommandFailsOnUnexpectedActionMetadata() { {"eventType":"command_result","commandType":"LOOK","commandId":"look","actionCategory":"META","actionTags":["UI"]} """); - assertThatThrownBy( - () -> - GameplayStructuredCommandAssertions.requireStructuredCommand( - json, "LOOK", "look", "SESSION", "UI")) + assertThatThrownBy(() -> + GameplayStructuredCommandAssertions.requireStructuredCommand( + json, "LOOK", "look", "SESSION", "UI")) .isInstanceOf(AssertionError.class) .hasMessageContaining("Expected actionCategory=SESSION"); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java index a07611335c..e451ac2463 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextCommandReceiverTest.java @@ -351,13 +351,11 @@ private Fixture fixture() { var connection = mock(AuthenticatedDirectTextSessions.Connection.class); when(sessions.require(socket)).thenReturn(connection); when(connection.withLogin(any())) - .thenAnswer( - invocation -> { - BiFunction< - InitialGameplayLoginAttemptCoordinates, CanonicalGameplayLoginResult, Object> - action = invocation.getArgument(0); - return action.apply(null, null); - }); + .thenAnswer(invocation -> { + BiFunction + action = invocation.getArgument(0); + return action.apply(null, null); + }); connection.menu = mock(DirectTextWorldSelectionService.SelectionSnapshot.class); connection.selectedScope = mock(DirectTextAuthenticatedLobbyScope.class); var target = mock(CanonicalPlayableTarget.class); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java index f5601452a6..0f86ec969a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedDirectTextSessionsTest.java @@ -158,16 +158,15 @@ void exactConnectionOwnsIdenticalPrivateResultOnlyInsideBorrow() throws Exceptio connection.login(fixture.owner(), "player@example.test", secret); assertThat(secret).containsOnly('\0'); assertThat( - connection.withLogin( - (original, result) -> { - assertThat(result).isSameAs(fixture.result()); - assertThatThrownBy(() -> sessions.close(socket, CloseStatus.NORMAL)) - .isInstanceOf(IllegalStateException.class); - assertThatThrownBy(sessions::closeAll).isInstanceOf(IllegalStateException.class); - assertThat(sessions.require(socket)).isSameAs(connection); - return connection.withCurrent( - original, result, transport -> transport.transportSessionId().equals("42")); - })) + connection.withLogin((original, result) -> { + assertThat(result).isSameAs(fixture.result()); + assertThatThrownBy(() -> sessions.close(socket, CloseStatus.NORMAL)) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(sessions::closeAll).isInstanceOf(IllegalStateException.class); + assertThat(sessions.require(socket)).isSameAs(connection); + return connection.withCurrent( + original, result, transport -> transport.transportSessionId().equals("42")); + })) .isTrue(); assertThatThrownBy( () -> connection.withCurrent(fixture.original(), fixture.result(), transport -> true)) @@ -187,38 +186,33 @@ void selectionFailuresPropagateThroughCustodyWithoutDiscardingExactLogin() throw connection.login(fixture.owner(), "player@example.test", "secret".toCharArray()); var unknown = new DirectTextWorldSelectionService.UnknownWorldSelectorException(); - assertThatThrownBy( - () -> - connection.withLogin( - (original, result) -> - connection.withCurrent( - original, - result, - transport -> { - throw unknown; - }))) + assertThatThrownBy(() -> + connection.withLogin((original, result) -> + connection.withCurrent( + original, + result, + transport -> { + throw unknown; + }))) .isSameAs(unknown); var expired = new DirectTextWorldSelectionService.ExpiredWorldSelectionException(); - assertThatThrownBy( - () -> - connection.withLogin( - (original, result) -> - connection.withCurrent( - original, - result, - transport -> { - throw expired; - }))) + assertThatThrownBy(() -> + connection.withLogin((original, result) -> + connection.withCurrent( + original, + result, + transport -> { + throw expired; + }))) .isSameAs(expired); assertThat( - connection.withLogin( - (original, result) -> { - assertThat(result).isSameAs(fixture.result()); - return connection.withCurrent( - original, result, transport -> transport.transportSessionId().equals("42")); - })) + connection.withLogin((original, result) -> { + assertThat(result).isSameAs(fixture.result()); + return connection.withCurrent( + original, result, transport -> transport.transportSessionId().equals("42")); + })) .isTrue(); sessions.close(socket, CloseStatus.NORMAL); @@ -236,14 +230,12 @@ void disconnectRevokesBeforeDrainingAndCleansOnlyAfterBorrowReturns() throws Exc var release = new CountDownLatch(1); try (var executor = Executors.newFixedThreadPool(2)) { var borrower = - executor.submit( - () -> - connection.withLogin( - (original, result) -> { - entered.countDown(); - await(release); - return true; - })); + executor.submit(() -> + connection.withLogin((original, result) -> { + entered.countDown(); + await(release); + return true; + })); assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); var closer = executor.submit(() -> sessions.close(socket, CloseStatus.NORMAL)); for (int i = 0; i < 1000 && connection.isCurrent(); i++) Thread.sleep(1); @@ -274,14 +266,12 @@ void replacementCannotActivateBeforeOldGenerationDrainsOrReconstructOldLogin() t var replacement = socket(); try (var executor = Executors.newFixedThreadPool(2)) { var borrower = - executor.submit( - () -> - connection.withLogin( - (original, result) -> { - entered.countDown(); - await(release); - return true; - })); + executor.submit(() -> + connection.withLogin((original, result) -> { + entered.countDown(); + await(release); + return true; + })); assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); var replacing = executor.submit(() -> sessions.open(replacement)); for (int i = 0; i < 1000 && connection.isCurrent(); i++) Thread.sleep(1); @@ -319,14 +309,12 @@ void overlappingReplacementsDrainTheWholePredecessorChainBeforeActivation() thro var latest = socket(); try (var executor = Executors.newFixedThreadPool(3)) { var borrower = - executor.submit( - () -> - originalConnection.withLogin( - (coordinates, result) -> { - entered.countDown(); - await(release); - return true; - })); + executor.submit(() -> + originalConnection.withLogin((coordinates, result) -> { + entered.countDown(); + await(release); + return true; + })); assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); var firstReplacement = executor.submit(() -> sessions.open(middle)); for (int i = 0; i < 1000 && originalConnection.isCurrent(); i++) Thread.sleep(1); @@ -376,14 +364,12 @@ void shutdownRevokesEveryGenerationBeforeDrainingAndRefusesNewConnections() thro var release = new CountDownLatch(1); try (var executor = Executors.newFixedThreadPool(2)) { var borrower = - executor.submit( - () -> - firstConnection.withLogin( - (original, result) -> { - entered.countDown(); - await(release); - return true; - })); + executor.submit(() -> + firstConnection.withLogin((original, result) -> { + entered.countDown(); + await(release); + return true; + })); assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue(); var shutdown = executor.submit(sessions::closeAll); for (int i = 0; i < 1000 && firstConnection.isCurrent(); i++) Thread.sleep(1); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedGameplayListenerConfigurationTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedGameplayListenerConfigurationTest.java index 840e613c65..d256ff85ba 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedGameplayListenerConfigurationTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/AuthenticatedGameplayListenerConfigurationTest.java @@ -76,36 +76,34 @@ void physicalDedicatedConnectorRequiresClientTlsAndExactGatewayIdentity() throws var received = new AtomicInteger(); var filter = config.authenticatedGameplayPathFilter(port); var web = - factory.getWebServer( - context -> { - var servlet = - context.addServlet( - "custody", - new HttpServlet() { - @Override - protected void doGet( - HttpServletRequest request, HttpServletResponse response) - throws java.io.IOException, jakarta.servlet.ServletException { - filter.doFilter( - request, - response, - (incoming, outgoing) -> { - try { - AuthenticatedDirectTextIngress.authenticate( - new ServletServerHttpRequest((HttpServletRequest) incoming), - port, - "test", - "42"); - received.incrementAndGet(); - ((HttpServletResponse) outgoing).setStatus(200); - } catch (IllegalArgumentException rejected) { - ((HttpServletResponse) outgoing).setStatus(403); - } - }); - } - }); - servlet.addMapping("/*"); - }); + factory.getWebServer(context -> { + var servlet = + context.addServlet( + "custody", + new HttpServlet() { + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws java.io.IOException, jakarta.servlet.ServletException { + filter.doFilter( + request, + response, + (incoming, outgoing) -> { + try { + AuthenticatedDirectTextIngress.authenticate( + new ServletServerHttpRequest((HttpServletRequest) incoming), + port, + "test", + "42"); + received.incrementAndGet(); + ((HttpServletResponse) outgoing).setStatus(200); + } catch (IllegalArgumentException rejected) { + ((HttpServletResponse) outgoing).setStatus(403); + } + }); + } + }); + servlet.addMapping("/*"); + }); web.start(); try { assertThat(call("gateway", port, "/ws/game/tcp").statusCode()).isEqualTo(200); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java index ecbbdab0dd..bad15bffaf 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java @@ -206,9 +206,8 @@ void authenticatedResponseUsesOnlyHandshakeLocaleWithoutReadingRetainedContext( null); verify(session) .sendMessage( - argThat( - message -> - "ERROR INVALID_CREDENTIALS Invalid credentials".equals(message.getPayload()))); + argThat(message -> + "ERROR INVALID_CREDENTIALS Invalid credentials".equals(message.getPayload()))); verify(session, never()).close(any()); Mockito.verifyNoInteractions( interpreter, sessionAuthenticationService, sessionContextService, authenticatedSessions); @@ -296,10 +295,9 @@ void afterConnectionEstablishedRejectsInvalidFirstPartyConnectContextAsExpected( verify(session) .close( - argThat( - status -> - status.getCode() == CloseStatus.POLICY_VIOLATION.getCode() - && "CONNECT_CONTEXT_INVALID".equals(status.getReason()))); + argThat(status -> + status.getCode() == CloseStatus.POLICY_VIOLATION.getCode() + && "CONNECT_CONTEXT_INVALID".equals(status.getReason()))); verify(firstPartyConnectContextRegistry, never()).register(Mockito.anyLong(), Mockito.any()); verify(sessionContextService, never()).save(Mockito.any()); } @@ -395,10 +393,9 @@ void messageStopsWhenFirstPartyBootstrapContextCannotBeRestored() throws Excepti verify(session) .close( - argThat( - status -> - status.getCode() == CloseStatus.POLICY_VIOLATION.getCode() - && "CONNECT_CONTEXT_INVALID".equals(status.getReason()))); + argThat(status -> + status.getCode() == CloseStatus.POLICY_VIOLATION.getCode() + && "CONNECT_CONTEXT_INVALID".equals(status.getReason()))); verify(interpreter, never()) .interpret(Mockito.anyString(), Mockito.any(TextCommand.class), Mockito.anyBoolean()); verify(session, never()).sendMessage(any()); @@ -427,10 +424,9 @@ void establishmentClosesGenericTransportWithoutReplacingIncumbentWhenPointerRead verify(session) .close( - argThat( - status -> - status.getCode() == 1013 - && "ADMISSION_POINTER_AUTHORITY_UNAVAILABLE".equals(status.getReason()))); + argThat(status -> + status.getCode() == 1013 + && "ADMISSION_POINTER_AUTHORITY_UNAVAILABLE".equals(status.getReason()))); verify(activeTransportSessionRegistry, never()).register(41L, session); verify(activeTransportSessionRegistry, never()).unregister(Mockito.anyLong(), Mockito.any()); } @@ -457,10 +453,9 @@ void messageStopsWhenGenericBootstrapPointerReadFails() throws Exception { verify(session) .close( - argThat( - status -> - status.getCode() == 1013 - && "ADMISSION_POINTER_AUTHORITY_UNAVAILABLE".equals(status.getReason()))); + argThat(status -> + status.getCode() == 1013 + && "ADMISSION_POINTER_AUTHORITY_UNAVAILABLE".equals(status.getReason()))); verify(interpreter, never()) .interpret(Mockito.anyString(), Mockito.any(TextCommand.class), Mockito.anyBoolean()); verify(session, never()).sendMessage(any()); @@ -485,10 +480,8 @@ void establishmentClosesUnavailableTransportAndCleansMdcBeforeLaterHealthyConnec verify(session) .close( - argThat( - status -> - status.getCode() == 1013 - && "backend_unavailable".equals(status.getReason()))); + argThat(status -> + status.getCode() == 1013 && "backend_unavailable".equals(status.getReason()))); verify(activeTransportSessionRegistry, never()).register(41L, session); verify(activeTransportSessionRegistry, never()).unregister(Mockito.anyLong(), Mockito.any()); verify(sessionContextService, never()).save(Mockito.any()); @@ -531,10 +524,8 @@ void messageClosesTransportWhenRetainedContextCannotBeRead() throws Exception { verify(session) .close( - argThat( - status -> - status.getCode() == 1013 - && "backend_unavailable".equals(status.getReason()))); + argThat(status -> + status.getCode() == 1013 && "backend_unavailable".equals(status.getReason()))); verify(parser, never()).parse(Mockito.anyString()); verify(interpreter, never()) .interpret(Mockito.anyString(), Mockito.any(TextCommand.class), Mockito.anyBoolean()); @@ -588,15 +579,14 @@ void afterConnectionEstablishedRepairsGenericBootstrapShellFromSingularRuntimeAu verify(sessionContextService) .save( - argThat( - context -> - context.sessionId() == 41L - && context.tenantId() == 22L - && context.bootstrapGameInstanceId() == 7L - && "demo".equals(context.worldSlug()) - && "production".equals(context.realmSlug()) - && context.pointerVersion() == 3L - && "SHARED".equals(context.playableStateScope()))); + argThat(context -> + context.sessionId() == 41L + && context.tenantId() == 22L + && context.bootstrapGameInstanceId() == 7L + && "demo".equals(context.worldSlug()) + && "production".equals(context.realmSlug()) + && context.pointerVersion() == 3L + && "SHARED".equals(context.playableStateScope()))); verify(activeTransportSessionRegistry).register(41L, session); } @@ -636,14 +626,13 @@ void afterConnectionEstablishedRepairsPartialRoutingTupleFromSingularRuntimeAuth verify(sessionContextService) .save( - argThat( - context -> - context.sessionId() == 41L - && context.tenantId() == 22L - && context.bootstrapGameInstanceId() == 7L - && "demo".equals(context.worldSlug()) - && "production".equals(context.realmSlug()) - && context.pointerVersion() == 8L)); + argThat(context -> + context.sessionId() == 41L + && context.tenantId() == 22L + && context.bootstrapGameInstanceId() == 7L + && "demo".equals(context.worldSlug()) + && "production".equals(context.realmSlug()) + && context.pointerVersion() == 8L)); verify(activeTransportSessionRegistry).register(41L, session); } @@ -689,18 +678,17 @@ void afterConnectionEstablishedDropsGenericBootstrapRoutingWhenRuntimeAuthorityI verify(sessionContextService) .save( - argThat( - context -> - context.sessionId() == 41L - && context.tenantId() == 22L - && context.characterId() == 0L - && context.characterName() == null - && context.gameInstanceId() == 0L - && context.roomInstanceId() == null - && context.bootstrapGameInstanceId() == 7L - && context.worldSlug() == null - && context.realmSlug() == null - && context.pointerVersion() == 0L)); + argThat(context -> + context.sessionId() == 41L + && context.tenantId() == 22L + && context.characterId() == 0L + && context.characterName() == null + && context.gameInstanceId() == 0L + && context.roomInstanceId() == null + && context.bootstrapGameInstanceId() == 7L + && context.worldSlug() == null + && context.realmSlug() == null + && context.pointerVersion() == 0L)); } @Test @@ -752,18 +740,17 @@ void afterConnectionEstablishedDropsPartialRoutingTupleWhenRuntimeAuthorityIsAmb verify(sessionContextService) .save( - argThat( - context -> - context.sessionId() == 41L - && context.tenantId() == 22L - && context.characterId() == 0L - && context.characterName() == null - && context.gameInstanceId() == 0L - && context.roomInstanceId() == null - && context.bootstrapGameInstanceId() == 7L - && context.worldSlug() == null - && context.realmSlug() == null - && context.pointerVersion() == 0L)); + argThat(context -> + context.sessionId() == 41L + && context.tenantId() == 22L + && context.characterId() == 0L + && context.characterName() == null + && context.gameInstanceId() == 0L + && context.roomInstanceId() == null + && context.bootstrapGameInstanceId() == 7L + && context.worldSlug() == null + && context.realmSlug() == null + && context.pointerVersion() == 0L)); } @Test @@ -877,15 +864,14 @@ void afterConnectionEstablishedSkipsGenericBootstrapWhenBootstrapGameInstanceIsN verify(sessionContextService) .save( - argThat( - context -> - context.sessionId() == 41L - && context.tenantId() == 22L - && context.bootstrapGameInstanceId() == 7L - && context.worldSlug() == null - && context.realmSlug() == null - && context.pointerVersion() == 0L - && context.playableStateScope() == null)); + argThat(context -> + context.sessionId() == 41L + && context.tenantId() == 22L + && context.bootstrapGameInstanceId() == 7L + && context.worldSlug() == null + && context.realmSlug() == null + && context.pointerVersion() == 0L + && context.playableStateScope() == null)); } @Test @@ -912,14 +898,13 @@ void afterConnectionEstablishedClearsGenericBootstrapRoutingWhenRuntimeAuthority verify(sessionContextService) .save( - argThat( - context -> - context.sessionId() == 41L - && context.tenantId() == 22L - && context.bootstrapGameInstanceId() == 7L - && context.worldSlug() == null - && context.realmSlug() == null - && context.pointerVersion() == 0L)); + argThat(context -> + context.sessionId() == 41L + && context.tenantId() == 22L + && context.bootstrapGameInstanceId() == 7L + && context.worldSlug() == null + && context.realmSlug() == null + && context.pointerVersion() == 0L)); } @Test @@ -974,16 +959,15 @@ void afterConnectionEstablishedClearsGenericBootstrapRoutingWhenRuntimeAuthority .clearGameplayBinding(existing, "BOOTSTRAP_ROUTE_CHANGED"); verify(sessionContextService) .save( - argThat( - context -> - context.sessionId() == 41L - && context.tenantId() == 22L - && context.accountId() == null - && context.bootstrapGameInstanceId() == 7L - && "demo".equals(context.worldSlug()) - && "production".equals(context.realmSlug()) - && context.pointerVersion() == 2L - && "SHARED".equals(context.playableStateScope()))); + argThat(context -> + context.sessionId() == 41L + && context.tenantId() == 22L + && context.accountId() == null + && context.bootstrapGameInstanceId() == 7L + && "demo".equals(context.worldSlug()) + && "production".equals(context.realmSlug()) + && context.pointerVersion() == 2L + && "SHARED".equals(context.playableStateScope()))); } @Test @@ -1051,15 +1035,14 @@ void afterConnectionEstablishedClearsGenericBootstrapRoutingWhenRuntimeAuthority .clearGameplayBinding(existing, "BOOTSTRAP_ROUTE_CHANGED"); verify(sessionContextService) .save( - argThat( - context -> - context.sessionId() == 41L - && context.tenantId() == 22L - && context.accountId() == null - && context.bootstrapGameInstanceId() == 7L - && context.worldSlug() == null - && context.realmSlug() == null - && context.pointerVersion() == 0L)); + argThat(context -> + context.sessionId() == 41L + && context.tenantId() == 22L + && context.accountId() == null + && context.bootstrapGameInstanceId() == 7L + && context.worldSlug() == null + && context.realmSlug() == null + && context.pointerVersion() == 0L)); } @Test @@ -1626,14 +1609,13 @@ void handleMessageBootstrapsGenericSessionContextBeforeInterpretingWhenMissing() verify(sessionContextService) .save( - argThat( - context -> - context.sessionId() == 41L - && context.tenantId() == 22L - && context.bootstrapGameInstanceId() == 7L - && context.worldSlug() == null - && context.realmSlug() == null - && context.pointerVersion() == 0L)); + argThat(context -> + context.sessionId() == 41L + && context.tenantId() == 22L + && context.bootstrapGameInstanceId() == 7L + && context.worldSlug() == null + && context.realmSlug() == null + && context.pointerVersion() == 0L)); org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(sessionContextService, interpreter); inOrder.verify(sessionContextService).save(any(SessionContext.class)); inOrder.verify(interpreter).interpret("41", command, false); @@ -1699,15 +1681,14 @@ void handleMessageRepairsPartialGenericBootstrapRoutingFromSingularRuntimeAuthor verify(sessionContextService) .save( - argThat( - context -> - context.sessionId() == 41L - && context.tenantId() == 22L - && context.bootstrapGameInstanceId() == 7L - && "demo".equals(context.worldSlug()) - && "production".equals(context.realmSlug()) - && context.pointerVersion() == 8L - && "SHARED".equals(context.playableStateScope()))); + argThat(context -> + context.sessionId() == 41L + && context.tenantId() == 22L + && context.bootstrapGameInstanceId() == 7L + && "demo".equals(context.worldSlug()) + && "production".equals(context.realmSlug()) + && context.pointerVersion() == 8L + && "SHARED".equals(context.playableStateScope()))); org.mockito.InOrder inOrder = org.mockito.Mockito.inOrder(sessionContextService, interpreter); inOrder.verify(sessionContextService).save(any(SessionContext.class)); inOrder.verify(interpreter).interpret("41", command, false); @@ -1857,14 +1838,13 @@ void handleMessageClearsPartialGenericBootstrapRoutingWhenAuthorityIsAmbiguous() verify(sessionContextService) .save( - argThat( - context -> - context.sessionId() == 41L - && context.tenantId() == 22L - && context.bootstrapGameInstanceId() == 7L - && context.worldSlug() == null - && context.realmSlug() == null - && context.pointerVersion() == 0L)); + argThat(context -> + context.sessionId() == 41L + && context.tenantId() == 22L + && context.bootstrapGameInstanceId() == 7L + && context.worldSlug() == null + && context.realmSlug() == null + && context.pointerVersion() == 0L)); } private static GameplayAdmissionPointerSnapshot pointer( @@ -1952,9 +1932,8 @@ void failedFirstPartyBootstrapSaveUnregistersContextBeforeClosingUnavailableTran order .verify(session) .close( - Mockito.argThat( - (CloseStatus status) -> - status.getCode() == 1013 && "backend_unavailable".equals(status.getReason()))); + Mockito.argThat((CloseStatus status) -> + status.getCode() == 1013 && "backend_unavailable".equals(status.getReason()))); verify(activeTransportSessionRegistry, never()).register(Mockito.anyLong(), any()); assertThat(saveFailure.getSuppressed()).isEmpty(); } @@ -1974,10 +1953,9 @@ void failedFirstPartyBootstrapSaveUnregistersContextBeforeClosingInvalidTranspor order .verify(session) .close( - Mockito.argThat( - (CloseStatus status) -> - status.getCode() == CloseStatus.POLICY_VIOLATION.getCode() - && "CONNECT_CONTEXT_INVALID".equals(status.getReason()))); + Mockito.argThat((CloseStatus status) -> + status.getCode() == CloseStatus.POLICY_VIOLATION.getCode() + && "CONNECT_CONTEXT_INVALID".equals(status.getReason()))); verify(activeTransportSessionRegistry, never()).register(Mockito.anyLong(), any()); assertThat(saveFailure.getSuppressed()).isEmpty(); } diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java index b8b5033eaf..fb75fdd15e 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java @@ -80,21 +80,19 @@ private static List fromPointers( } } return grouped.entrySet().stream() - .map( - world -> - new GameplayWorldCatalog.WorldView( - world.getKey(), - displayNames.get(world.getKey()), - world.getValue().entrySet().stream() - .map( - realm -> { - if (realm.getValue().size() != 1) { - throw new IllegalArgumentException( - "test catalog contains a duplicate world/realm selector"); - } - return toRealmView(realm.getValue().getFirst()); - }) - .toList())) + .map(world -> + new GameplayWorldCatalog.WorldView( + world.getKey(), + displayNames.get(world.getKey()), + world.getValue().entrySet().stream() + .map(realm -> { + if (realm.getValue().size() != 1) { + throw new IllegalArgumentException( + "test catalog contains a duplicate world/realm selector"); + } + return toRealmView(realm.getValue().getFirst()); + }) + .toList())) .toList(); } diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java index 567cfb67bf..cd86623351 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/EntityManagementStubServer.java @@ -128,18 +128,14 @@ public void listCharactersByAccount( == PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) { response.addAllCharacters( characters.get().stream() - .filter( - character -> - request.getTenantId().equals(character.getTenantId()) - && request - .getAccountId() - .equals(character.getAccountId())) - .map( - character -> - character.toBuilder() - .setPlayableStateScope( - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .build()) + .filter(character -> + request.getTenantId().equals(character.getTenantId()) + && request.getAccountId().equals(character.getAccountId())) + .map(character -> + character.toBuilder() + .setPlayableStateScope( + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .build()) .toList()); } responseObserver.onNext(response.build()); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/SocialGroupsStubServer.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/SocialGroupsStubServer.java index 8719442eeb..b325997824 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/SocialGroupsStubServer.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/SocialGroupsStubServer.java @@ -369,11 +369,10 @@ private void upsertRosterEntry(String friendAccountId) { friendPresenceResponse.get().getPresencesList().stream() .filter(entry -> entry.getFriendAccountId().equals(friendAccountId)) .findFirst() - .orElseGet( - () -> - net.firedevops.firemud.socialgroups.v1.FriendPresenceEntry.newBuilder() - .setFriendAccountId(friendAccountId) - .build()); + .orElseGet(() -> + net.firedevops.firemud.socialgroups.v1.FriendPresenceEntry.newBuilder() + .setFriendAccountId(friendAccountId) + .build()); rosterEntries.put( friendAccountId, FriendRosterEntry.newBuilder() diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java index 76b14825d7..614fd13aeb 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testing/ControlledPlayerCreatedOriginalOwnerFixture.java @@ -212,14 +212,13 @@ public ControlledPlayerCreatedOriginalOwnerFixture( new AuthoredInitialActorCoreReadEvidence.ReadResult( exactRequest, exact, upstream.descriptor(), upstream.projections()); var descriptors = new GameSessionStartSessionLaunchDescriptorRepository(dsl, selections); - transactions.execute( - ignored -> - descriptors.pin( - claim, - new StartSessionLaunchDescriptorGrpcCodec.Resolved( - exact, - new StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome( - authored.descriptor())))); + transactions.execute(ignored -> + descriptors.pin( + claim, + new StartSessionLaunchDescriptorGrpcCodec.Resolved( + exact, + new StartSessionLaunchDescriptorGrpcCodec.DescriptorOutcome( + authored.descriptor())))); var source = association.worldReceipt().source(); var intakeRepository = new GameSessionAuthoredWorldSourceRepository(dsl); var intake = @@ -227,11 +226,10 @@ public ControlledPlayerCreatedOriginalOwnerFixture( transactions.execute(ignored -> intakeRepository.register(UUID.randomUUID(), source))); var tenantAssociation = Objects.requireNonNull( - transactions.execute( - ignored -> - new GameSessionFreshTenantAssociationRepository(dsl) - .associateFresh( - UUID.randomUUID(), namespace, intake, creationEvidence(source)))); + transactions.execute(ignored -> + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + UUID.randomUUID(), namespace, intake, creationEvidence(source)))); var policySet = supplied.policySet(); var realmPolicy = policySet.policies().stream() @@ -336,72 +334,68 @@ public ControlledPlayerCreatedOriginalOwnerFixture( StartSessionTemplateAssociationReadGrpcCodec.toRequest(exactRequest).toByteArray(), authored.canonicalBytes(), authored.digest()); - transactions.execute( - ignored -> { - attempts.readCurrentOriginalAttempt(currentAttemptRequest); - return retention.retainInOwnerTransaction(retained); - }); + transactions.execute(ignored -> { + attempts.readCurrentOriginalAttempt(currentAttemptRequest); + return retention.retainInOwnerTransaction(retained); + }); migrateLatest(); routeReader = new CanonicalPlayerRouteReadService(namespace, catalogs, admissions, launches); var gameDesign = mock(AuthoredInitialActorCoreReadClient.class); when(gameDesign.read(any())) - .thenAnswer( - call -> { - requireOutsideSql(); - if (!new AuthoredInitialActorCoreReadEvidence.ReadRequest(authored.request()) - .equals(call.getArgument(0))) - throw new IllegalArgumentException("Controlled authored replay selector changed"); - return authored; - }); + .thenAnswer(call -> { + requireOutsideSql(); + if (!new AuthoredInitialActorCoreReadEvidence.ReadRequest(authored.request()) + .equals(call.getArgument(0))) + throw new IllegalArgumentException("Controlled authored replay selector changed"); + return authored; + }); var world = mock(WorldCanonicalInstanceLifecycleClient.class); when(world.read(any())) - .thenAnswer( - call -> { - requireOutsideSql(); - controlledWorldLifecycleReads.incrementAndGet(); - var requested = (WorldCanonicalInstanceLifecycleEvidence.Request) call.getArgument(0); - var base = supplied.world(); - var expected = base.request(); - if (!requested.equals( - new WorldCanonicalInstanceLifecycleEvidence.Request( - expected.schemaVersion(), - requested.readRequestId(), - expected.targetNamespace(), - expected.canonicalTenantId(), - expected.worldSlug(), - expected.canonicalGameInstanceId(), - expected.playableStateNamespaceId(), - expected.playableStateScope(), - expected.publicProduction(), - expected.controlPlaneRequestId(), - expected.canonicalVersionId(), - expected.expectedDescriptorRequestDigest(), - expected.expectedDescriptorResultDigest(), - expected.expectedReleaseAttestationDigest()))) - throw new IllegalArgumentException("Controlled World selector changed"); - return new WorldCanonicalInstanceLifecycleEvidence( - requested, - base.launchBinding(), - base.startLocation(), - base.runtimeRoomInstanceId(), - base.lifecycleStatus(), - base.lifecycleEpoch(), - base.rowVersion(), - base.captureId(), - base.graphSha256(), - base.preparationInputDigest(), - base.operationalRegionAssignments()); - }); + .thenAnswer(call -> { + requireOutsideSql(); + controlledWorldLifecycleReads.incrementAndGet(); + var requested = (WorldCanonicalInstanceLifecycleEvidence.Request) call.getArgument(0); + var base = supplied.world(); + var expected = base.request(); + if (!requested.equals( + new WorldCanonicalInstanceLifecycleEvidence.Request( + expected.schemaVersion(), + requested.readRequestId(), + expected.targetNamespace(), + expected.canonicalTenantId(), + expected.worldSlug(), + expected.canonicalGameInstanceId(), + expected.playableStateNamespaceId(), + expected.playableStateScope(), + expected.publicProduction(), + expected.controlPlaneRequestId(), + expected.canonicalVersionId(), + expected.expectedDescriptorRequestDigest(), + expected.expectedDescriptorResultDigest(), + expected.expectedReleaseAttestationDigest()))) + throw new IllegalArgumentException("Controlled World selector changed"); + return new WorldCanonicalInstanceLifecycleEvidence( + requested, + base.launchBinding(), + base.startLocation(), + base.runtimeRoomInstanceId(), + base.lifecycleStatus(), + base.lifecycleEpoch(), + base.rowVersion(), + base.captureId(), + base.graphSha256(), + base.preparationInputDigest(), + base.operationalRegionAssignments()); + }); var policies = mock(GameDesignPublishedRealmPolicyClient.class); when(policies.listPublishedRealmEntryPolicies(any(), any())) - .thenAnswer( - call -> { - requireOutsideSql(); - if (!source.canonicalTenantId().equals(call.getArgument(0)) - || !association.canonicalVersionId().equals(call.getArgument(1))) - throw new IllegalArgumentException("Controlled published policy selector changed"); - return policySet; - }); + .thenAnswer(call -> { + requireOutsideSql(); + if (!source.canonicalTenantId().equals(call.getArgument(0)) + || !association.canonicalVersionId().equals(call.getArgument(1))) + throw new IllegalArgumentException("Controlled published policy selector changed"); + return policySet; + }); sourceReader = new GameSessionCharacterCreatePublicSourceService( namespace, @@ -602,16 +596,15 @@ private static RealmPolicyPublishedEvidence.PublishedSet internalPolicies( set.policyCount(), set.policySetDigest(), set.policies().stream() - .map( - item -> - new RealmPolicyPublishedEvidence.Policy( - item.policyId(), - new RealmPolicySource.Policy( - item.sourceCommitId(), - item.sourceRevisionId(), - item.logicalRevisionId(), - item.policy()), - item.policyDigest())) + .map(item -> + new RealmPolicyPublishedEvidence.Policy( + item.policyId(), + new RealmPolicySource.Policy( + item.sourceCommitId(), + item.sourceRevisionId(), + item.logicalRevisionId(), + item.policy()), + item.policyDigest())) .toList()); } @@ -731,61 +724,60 @@ private CanonicalRealmCatalogSnapshot seedPriorCatalog( source.provenanceKind(), "source_evidence_digest", source.evidenceDigest()); - transactions.executeWithoutResult( - ignored -> { - var shared = new LinkedHashMap<>(sourceColumns); - shared.putAll( - map( - "tenant_id", - null, - "playable_state_namespace_id", - playableNamespace, - "canonical_tenant_id", - request.canonicalTenantId(), - "target_namespace", - request.targetNamespace())); - insert("gameplay_tenant_shared_playable_state_namespace", shared); - var catalog = new LinkedHashMap<>(sourceColumns); - catalog.putAll( - map( - "target_namespace", - request.targetNamespace(), - "canonical_tenant_id", - request.canonicalTenantId(), - "tenant_slug", - source.tenantSlug(), - "world_slug", - source.worldSlug(), - "realm_id", - realm, - "realm_slug", - request.realmSlug(), - "realm_display_name", - request.realmDisplayName(), - "visible", - true, - "public_production", - true, - "state_scope", - "SHARED", - "playable_state_namespace_id", - playableNamespace, - "character_creation_policy", - "PLAYER_CREATED", - "catalog_revision", - 1L, - "creation_request_id", - request.requestId(), - "request_digest", - requestDigest, - "receipt_digest", - receipt, - "source_world_display_name", - source.worldDisplayName(), - "complete_policy_set_evidence", - policyBytes)); - insert("game_session_canonical_realm_catalog", catalog); - }); + transactions.executeWithoutResult(ignored -> { + var shared = new LinkedHashMap<>(sourceColumns); + shared.putAll( + map( + "tenant_id", + null, + "playable_state_namespace_id", + playableNamespace, + "canonical_tenant_id", + request.canonicalTenantId(), + "target_namespace", + request.targetNamespace())); + insert("gameplay_tenant_shared_playable_state_namespace", shared); + var catalog = new LinkedHashMap<>(sourceColumns); + catalog.putAll( + map( + "target_namespace", + request.targetNamespace(), + "canonical_tenant_id", + request.canonicalTenantId(), + "tenant_slug", + source.tenantSlug(), + "world_slug", + source.worldSlug(), + "realm_id", + realm, + "realm_slug", + request.realmSlug(), + "realm_display_name", + request.realmDisplayName(), + "visible", + true, + "public_production", + true, + "state_scope", + "SHARED", + "playable_state_namespace_id", + playableNamespace, + "character_creation_policy", + "PLAYER_CREATED", + "catalog_revision", + 1L, + "creation_request_id", + request.requestId(), + "request_digest", + requestDigest, + "receipt_digest", + receipt, + "source_world_display_name", + source.worldDisplayName(), + "complete_policy_set_evidence", + policyBytes)); + insert("game_session_canonical_realm_catalog", catalog); + }); return new CanonicalRealmCatalogSnapshot( request.targetNamespace(), source.canonicalTenantId(), @@ -819,122 +811,121 @@ private long seedPriorLaunch( var tupleSource = catalog.sourceIntakeReceipt(); String bindingJson = JSON.writeValueAsString(binding); return Objects.requireNonNull( - transactions.execute( - ignored -> { - var runtime = - map( - "tenant_id", - tenantId, - "runtime_version", - Long.toString(descriptor.versionId()), - "owner_account_uuid", - tuple.preAuthorizationTuple().actor().accountId(), - "status", - "STARTING", - "row_version", - 0L, - "game_template_id", - descriptor.gameTemplateId(), - "launch_descriptor_id", - descriptor.launchDescriptorId(), - "version_id", - descriptor.versionId(), - "release_bundle_id", - descriptor.releaseBundleId(), - "version_state_epoch", - descriptor.versionStateEpoch(), - "generation_config_revision", - descriptor.generationConfigRevision(), - "run_owned_start_request_id", - tuple.controlPlaneRequestId(), - "run_owned_start_request_digest", - tuple.mutationDigest(), - "run_owned_start_published_release_bundle_ref", - descriptor.publishedReleaseBundleRef(), - "game_instance_uuid", - instance); - var fields = new LinkedHashMap, Object>(); - runtime.forEach((key, value) -> fields.put(DSL.field(DSL.name(key)), value)); - long allocated = - dsl.insertInto(DSL.table("game_instances")) - .set(fields) - .returning(DSL.field("id", Long.class)) - .fetchSingle() - .get("id", Long.class); - insert( - "game_session_canonical_instance_launch", - map( - "target_namespace", - catalog.targetNamespace(), - "control_plane_request_id", - tuple.controlPlaneRequestId(), - "game_session_tenant_id", - tenantId, - "canonical_tenant_id", - catalog.tenantId(), - "tenant_association_operation_id", - associationOperation, - "tenant_association_request_id", - tenantSource.requestId(), - "tenant_source_schema_version", - tenantSource.schemaVersion(), - "tenant_source_target_namespace", - tenantSource.targetNamespace(), - "tenant_source_request_id", - tenantSource.requestId(), - "tenant_source_canonical_tenant_id", - tenantSource.canonicalTenantId(), - "tenant_source_game_row_id", - tenantSource.sourceGameRowId(), - "tenant_source_game_tenant_key", - tenantSource.sourceGameTenantKey(), - "tenant_source_provenance_kind", - tenantSource.provenanceKind(), - "tenant_association_kind", - "FRESH_SOURCE_BOUND", - "game_instance_id", - allocated, - "game_instance_uuid", - instance, - "canonical_realm_id", - catalog.realmId(), - "world_slug", - catalog.worldSlug(), - "playable_state_namespace_id", - catalog.playableStateNamespaceId(), - "playable_state_scope", - "SHARED", - "public_production", - true, - "captured_starting_row_version", - 0L, - "game_template_id", - descriptor.gameTemplateId(), - "launch_descriptor_id", - descriptor.launchDescriptorId(), - "version_id", - descriptor.versionId(), - "release_bundle_id", - descriptor.releaseBundleId(), - "generation_config_revision", - descriptor.generationConfigRevision(), - "version_state_epoch", - descriptor.versionStateEpoch(), - "complete_launch_binding_evidence", - org.jooq.JSONB.valueOf(bindingJson), - "original_start_session_tuple", - tuple.canonicalBytes(), - "catalog_creation_request_id", - catalog.creationRequestId(), - "catalog_revision", - catalog.catalogRevision(), - "catalog_source_intake_operation_id", - tupleSource.operationId(), - "catalog_source_intake_request_id", - tupleSource.intakeRequestId())); - dsl.execute("UPDATE game_instances SET status='RUNNING' WHERE id=?", allocated); - return allocated; - })); + transactions.execute(ignored -> { + var runtime = + map( + "tenant_id", + tenantId, + "runtime_version", + Long.toString(descriptor.versionId()), + "owner_account_uuid", + tuple.preAuthorizationTuple().actor().accountId(), + "status", + "STARTING", + "row_version", + 0L, + "game_template_id", + descriptor.gameTemplateId(), + "launch_descriptor_id", + descriptor.launchDescriptorId(), + "version_id", + descriptor.versionId(), + "release_bundle_id", + descriptor.releaseBundleId(), + "version_state_epoch", + descriptor.versionStateEpoch(), + "generation_config_revision", + descriptor.generationConfigRevision(), + "run_owned_start_request_id", + tuple.controlPlaneRequestId(), + "run_owned_start_request_digest", + tuple.mutationDigest(), + "run_owned_start_published_release_bundle_ref", + descriptor.publishedReleaseBundleRef(), + "game_instance_uuid", + instance); + var fields = new LinkedHashMap, Object>(); + runtime.forEach((key, value) -> fields.put(DSL.field(DSL.name(key)), value)); + long allocated = + dsl.insertInto(DSL.table("game_instances")) + .set(fields) + .returning(DSL.field("id", Long.class)) + .fetchSingle() + .get("id", Long.class); + insert( + "game_session_canonical_instance_launch", + map( + "target_namespace", + catalog.targetNamespace(), + "control_plane_request_id", + tuple.controlPlaneRequestId(), + "game_session_tenant_id", + tenantId, + "canonical_tenant_id", + catalog.tenantId(), + "tenant_association_operation_id", + associationOperation, + "tenant_association_request_id", + tenantSource.requestId(), + "tenant_source_schema_version", + tenantSource.schemaVersion(), + "tenant_source_target_namespace", + tenantSource.targetNamespace(), + "tenant_source_request_id", + tenantSource.requestId(), + "tenant_source_canonical_tenant_id", + tenantSource.canonicalTenantId(), + "tenant_source_game_row_id", + tenantSource.sourceGameRowId(), + "tenant_source_game_tenant_key", + tenantSource.sourceGameTenantKey(), + "tenant_source_provenance_kind", + tenantSource.provenanceKind(), + "tenant_association_kind", + "FRESH_SOURCE_BOUND", + "game_instance_id", + allocated, + "game_instance_uuid", + instance, + "canonical_realm_id", + catalog.realmId(), + "world_slug", + catalog.worldSlug(), + "playable_state_namespace_id", + catalog.playableStateNamespaceId(), + "playable_state_scope", + "SHARED", + "public_production", + true, + "captured_starting_row_version", + 0L, + "game_template_id", + descriptor.gameTemplateId(), + "launch_descriptor_id", + descriptor.launchDescriptorId(), + "version_id", + descriptor.versionId(), + "release_bundle_id", + descriptor.releaseBundleId(), + "generation_config_revision", + descriptor.generationConfigRevision(), + "version_state_epoch", + descriptor.versionStateEpoch(), + "complete_launch_binding_evidence", + org.jooq.JSONB.valueOf(bindingJson), + "original_start_session_tuple", + tuple.canonicalBytes(), + "catalog_creation_request_id", + catalog.creationRequestId(), + "catalog_revision", + catalog.catalogRevision(), + "catalog_source_intake_operation_id", + tupleSource.operationId(), + "catalog_source_intake_request_id", + tupleSource.intakeRequestId())); + dsl.execute("UPDATE game_instances SET status='RUNNING' WHERE id=?", allocated); + return allocated; + })); } private void seedPriorCommittedAdmission( @@ -979,122 +970,121 @@ private void seedPriorCommittedAdmission( UUID.randomUUID(), UUID.randomUUID(), "sha256:" + "e".repeat(64)); - transactions.executeWithoutResult( - ignored -> { - var pendingAt = dsl.fetchSingle("SELECT clock_timestamp()").get(0, OffsetDateTime.class); - insert( - "game_session_canonical_initial_admission_attempt", - map( - "target_namespace", - request.targetNamespace(), - "initial_admission_request_id", - requestId, - "request_digest", - digest, - "canonical_tenant_id", - catalog.tenantId(), - "world_slug", - catalog.worldSlug(), - "realm_id", - catalog.realmId(), - "playable_state_namespace_id", - catalog.playableStateNamespaceId(), - "playable_state_scope", - "SHARED", - "canonical_game_instance_id", - association.gameInstanceUuid(), - "game_session_tenant_id", - association.gameSessionTenantId(), - "game_instance_id", - launch.gameInstanceId(), - "canonical_version_id", - version, - "runtime_version_id", - launch.runtimeVersionId(), - "expected_catalog_revision", - 1L, - "origin_kind", - request.originKind().name(), - "active_lifecycle_epoch", - epoch, - "hold_id", - request.holdId(), - "hold_fence", - request.holdFence(), - "hold_binding_digest", - request.holdBindingDigest(), - "status", - "PENDING", - "created_at", - pendingAt, - "updated_at", - pendingAt)); - var now = - dsl.fetchSingle("SELECT clock_timestamp()").get(0, OffsetDateTime.class).toInstant(); - long audit = - events.appendCanonicalInitialAdmissionOpen(request, catalog, launch, 1L, 1L, now); - String columns = - "world_slug,realm_slug,world_display_name,realm_display_name,tenant_id,game_instance_id," - + "pointer_version,visible,requires_character_selection,state_scope,character_creation_policy,last_updated_by," - + "last_update_reason,created_at,updated_at,public_production_realm,catalog_revision,realm_id," - + "playable_state_namespace_id,representation_version,target_namespace,canonical_tenant_id,admission_state," - + "canonical_game_instance_id,canonical_version_id,runtime_version_id,initial_admission_request_id," - + "initial_admission_request_digest,initial_admission_origin_kind,initial_admission_prior_pointer_version," - + "initial_admission_active_epoch,initial_admission_hold_id,initial_admission_hold_fence,initial_admission_hold_binding_digest"; - String eventColumns = - columns - .replace("last_updated_by", "actor_principal") - .replace("last_update_reason", "reason") - .replace("created_at", "occurred_at") - .replace("updated_at", "occurred_at"); - long pointer = - dsl.fetchSingle( - "INSERT INTO gameplay_admission_pointer (" - + columns - + ") SELECT " - + eventColumns - + " FROM gameplay_admission_pointer_event WHERE id=? RETURNING id", - audit) - .get("id", Long.class); - String proof = - binaryFrame( - "gs-canonical-initial-admission-commit-proof/v1", - digest, - requestId, - request.targetNamespace(), - catalog.tenantId().toString(), - catalog.worldSlug(), - catalog.realmId().toString(), - catalog.playableStateNamespaceId().toString(), - "SHARED", - association.gameInstanceUuid().toString(), - version.toString(), - Long.toString(launch.runtimeVersionId()), - Long.toString(epoch), - "1", - request.originKind().name(), - "", - request.holdId().toString(), - request.holdFence().toString(), - request.holdBindingDigest(), - "1", - Long.toString(audit), - "", - "", - "", - now.toString()); - dsl.execute( - "UPDATE game_session_canonical_initial_admission_attempt SET status='COMMITTED',pointer_id=?," - + "pointer_version=1,audit_event_id=?,commit_proof_digest=?,terminal_at=?::timestamptz,updated_at=?::timestamptz " - + "WHERE target_namespace=? AND initial_admission_request_id=?", - pointer, - audit, - proof, - now.atOffset(ZoneOffset.UTC), - now.atOffset(ZoneOffset.UTC), + transactions.executeWithoutResult(ignored -> { + var pendingAt = dsl.fetchSingle("SELECT clock_timestamp()").get(0, OffsetDateTime.class); + insert( + "game_session_canonical_initial_admission_attempt", + map( + "target_namespace", request.targetNamespace(), - requestId); - }); + "initial_admission_request_id", + requestId, + "request_digest", + digest, + "canonical_tenant_id", + catalog.tenantId(), + "world_slug", + catalog.worldSlug(), + "realm_id", + catalog.realmId(), + "playable_state_namespace_id", + catalog.playableStateNamespaceId(), + "playable_state_scope", + "SHARED", + "canonical_game_instance_id", + association.gameInstanceUuid(), + "game_session_tenant_id", + association.gameSessionTenantId(), + "game_instance_id", + launch.gameInstanceId(), + "canonical_version_id", + version, + "runtime_version_id", + launch.runtimeVersionId(), + "expected_catalog_revision", + 1L, + "origin_kind", + request.originKind().name(), + "active_lifecycle_epoch", + epoch, + "hold_id", + request.holdId(), + "hold_fence", + request.holdFence(), + "hold_binding_digest", + request.holdBindingDigest(), + "status", + "PENDING", + "created_at", + pendingAt, + "updated_at", + pendingAt)); + var now = + dsl.fetchSingle("SELECT clock_timestamp()").get(0, OffsetDateTime.class).toInstant(); + long audit = + events.appendCanonicalInitialAdmissionOpen(request, catalog, launch, 1L, 1L, now); + String columns = + "world_slug,realm_slug,world_display_name,realm_display_name,tenant_id,game_instance_id," + + "pointer_version,visible,requires_character_selection,state_scope,character_creation_policy,last_updated_by," + + "last_update_reason,created_at,updated_at,public_production_realm,catalog_revision,realm_id," + + "playable_state_namespace_id,representation_version,target_namespace,canonical_tenant_id,admission_state," + + "canonical_game_instance_id,canonical_version_id,runtime_version_id,initial_admission_request_id," + + "initial_admission_request_digest,initial_admission_origin_kind,initial_admission_prior_pointer_version," + + "initial_admission_active_epoch,initial_admission_hold_id,initial_admission_hold_fence,initial_admission_hold_binding_digest"; + String eventColumns = + columns + .replace("last_updated_by", "actor_principal") + .replace("last_update_reason", "reason") + .replace("created_at", "occurred_at") + .replace("updated_at", "occurred_at"); + long pointer = + dsl.fetchSingle( + "INSERT INTO gameplay_admission_pointer (" + + columns + + ") SELECT " + + eventColumns + + " FROM gameplay_admission_pointer_event WHERE id=? RETURNING id", + audit) + .get("id", Long.class); + String proof = + binaryFrame( + "gs-canonical-initial-admission-commit-proof/v1", + digest, + requestId, + request.targetNamespace(), + catalog.tenantId().toString(), + catalog.worldSlug(), + catalog.realmId().toString(), + catalog.playableStateNamespaceId().toString(), + "SHARED", + association.gameInstanceUuid().toString(), + version.toString(), + Long.toString(launch.runtimeVersionId()), + Long.toString(epoch), + "1", + request.originKind().name(), + "", + request.holdId().toString(), + request.holdFence().toString(), + request.holdBindingDigest(), + "1", + Long.toString(audit), + "", + "", + "", + now.toString()); + dsl.execute( + "UPDATE game_session_canonical_initial_admission_attempt SET status='COMMITTED',pointer_id=?," + + "pointer_version=1,audit_event_id=?,commit_proof_digest=?,terminal_at=?::timestamptz,updated_at=?::timestamptz " + + "WHERE target_namespace=? AND initial_admission_request_id=?", + pointer, + audit, + proof, + now.atOffset(ZoneOffset.UTC), + now.atOffset(ZoneOffset.UTC), + request.targetNamespace(), + requestId); + }); } private void insert(String table, Map values) { diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java index 94341287c7..c8e6d99561 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java @@ -218,63 +218,57 @@ public long freshGameplayBaseline( TransactionTemplate baselineReset = new TransactionTemplate(gameSession.bean(PlatformTransactionManager.class)); BaselineTruncateGuardStates originalGuardStates = - baselineReset.execute( - status -> { - BaselineTruncateGuardStates originalStates = - new BaselineTruncateGuardStates( - requireOriginalTruncateGuardState( - jdbc, BaselineTruncateGuard.CANONICAL_LAUNCH), - requireOriginalTruncateGuardState( - jdbc, BaselineTruncateGuard.AUTHORED_ACTOR_CORE), - requireOriginalTruncateGuardState( - jdbc, BaselineTruncateGuard.HUMAN_RUNTIME_COMPLETION)); - disableTruncateGuard(jdbc, BaselineTruncateGuard.CANONICAL_LAUNCH); - requireTruncateGuardState(jdbc, BaselineTruncateGuard.CANONICAL_LAUNCH, "D"); - disableTruncateGuard(jdbc, BaselineTruncateGuard.AUTHORED_ACTOR_CORE); - requireTruncateGuardState(jdbc, BaselineTruncateGuard.AUTHORED_ACTOR_CORE, "D"); - disableTruncateGuard(jdbc, BaselineTruncateGuard.HUMAN_RUNTIME_COMPLETION); - requireTruncateGuardState(jdbc, BaselineTruncateGuard.HUMAN_RUNTIME_COMPLETION, "D"); - jdbc.execute( - """ - TRUNCATE TABLE - game_session_canonical_human_runtime_completion, - gs_original_start_session_authored_actor_core_retention, - game_session_canonical_closed_admission_pointer_request, - gameplay_initial_admission_bind_attempt, - game_session_canonical_initial_admission_intent, - game_session_canonical_initial_admission_attempt, - gameplay_admission_pointer_event, - gameplay_admission_pointer, - game_session_canonical_instance_launch, - game_instances - RESTART IDENTITY - """); - // PostgreSQL rolls back this transactional trigger change if TRUNCATE fails, - // preserving - // the real guard failure instead of masking it with a re-enable attempt on an aborted - // transaction. - restoreTruncateGuard( - jdbc, BaselineTruncateGuard.CANONICAL_LAUNCH, originalStates.canonicalLaunch()); - requireTruncateGuardState( - jdbc, BaselineTruncateGuard.CANONICAL_LAUNCH, originalStates.canonicalLaunch()); - restoreTruncateGuard( - jdbc, - BaselineTruncateGuard.AUTHORED_ACTOR_CORE, - originalStates.authoredActorCore()); - requireTruncateGuardState( - jdbc, - BaselineTruncateGuard.AUTHORED_ACTOR_CORE, - originalStates.authoredActorCore()); - restoreTruncateGuard( - jdbc, - BaselineTruncateGuard.HUMAN_RUNTIME_COMPLETION, - originalStates.humanRuntimeCompletion()); - requireTruncateGuardState( - jdbc, - BaselineTruncateGuard.HUMAN_RUNTIME_COMPLETION, - originalStates.humanRuntimeCompletion()); - return originalStates; - }); + baselineReset.execute(status -> { + BaselineTruncateGuardStates originalStates = + new BaselineTruncateGuardStates( + requireOriginalTruncateGuardState(jdbc, BaselineTruncateGuard.CANONICAL_LAUNCH), + requireOriginalTruncateGuardState( + jdbc, BaselineTruncateGuard.AUTHORED_ACTOR_CORE), + requireOriginalTruncateGuardState( + jdbc, BaselineTruncateGuard.HUMAN_RUNTIME_COMPLETION)); + disableTruncateGuard(jdbc, BaselineTruncateGuard.CANONICAL_LAUNCH); + requireTruncateGuardState(jdbc, BaselineTruncateGuard.CANONICAL_LAUNCH, "D"); + disableTruncateGuard(jdbc, BaselineTruncateGuard.AUTHORED_ACTOR_CORE); + requireTruncateGuardState(jdbc, BaselineTruncateGuard.AUTHORED_ACTOR_CORE, "D"); + disableTruncateGuard(jdbc, BaselineTruncateGuard.HUMAN_RUNTIME_COMPLETION); + requireTruncateGuardState(jdbc, BaselineTruncateGuard.HUMAN_RUNTIME_COMPLETION, "D"); + jdbc.execute( + """ + TRUNCATE TABLE + game_session_canonical_human_runtime_completion, + gs_original_start_session_authored_actor_core_retention, + game_session_canonical_closed_admission_pointer_request, + gameplay_initial_admission_bind_attempt, + game_session_canonical_initial_admission_intent, + game_session_canonical_initial_admission_attempt, + gameplay_admission_pointer_event, + gameplay_admission_pointer, + game_session_canonical_instance_launch, + game_instances + RESTART IDENTITY + """); + // PostgreSQL rolls back this transactional trigger change if TRUNCATE fails, + // preserving + // the real guard failure instead of masking it with a re-enable attempt on an aborted + // transaction. + restoreTruncateGuard( + jdbc, BaselineTruncateGuard.CANONICAL_LAUNCH, originalStates.canonicalLaunch()); + requireTruncateGuardState( + jdbc, BaselineTruncateGuard.CANONICAL_LAUNCH, originalStates.canonicalLaunch()); + restoreTruncateGuard( + jdbc, BaselineTruncateGuard.AUTHORED_ACTOR_CORE, originalStates.authoredActorCore()); + requireTruncateGuardState( + jdbc, BaselineTruncateGuard.AUTHORED_ACTOR_CORE, originalStates.authoredActorCore()); + restoreTruncateGuard( + jdbc, + BaselineTruncateGuard.HUMAN_RUNTIME_COMPLETION, + originalStates.humanRuntimeCompletion()); + requireTruncateGuardState( + jdbc, + BaselineTruncateGuard.HUMAN_RUNTIME_COMPLETION, + originalStates.humanRuntimeCompletion()); + return originalStates; + }); requireTruncateGuardState( jdbc, BaselineTruncateGuard.CANONICAL_LAUNCH, originalGuardStates.canonicalLaunch()); requireTruncateGuardState( diff --git a/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java b/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java index c0febd630d..a3eaccacd2 100644 --- a/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java +++ b/services/game-session-service/src/testFixtures/java/support/net/firedevops/firemud/gamesession/PublishedRealmPolicyEvidenceFixture.java @@ -116,15 +116,14 @@ public static Fixture fixture( var committed = committedFreshGraphReadback(terminalReadRequest); List tuples = draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) + .map(unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) .toList(); var worldRequest = new Request( @@ -171,36 +170,29 @@ public static Fixture fixture( } List policies = specs.stream() - .map( - spec -> { - RealmEntryPolicy policy = policy(spec); - UUID policyId = - stableUuid("policy/" + canonicalVersionId + "/" + spec.realmSlug()); - UUID revisionId = - stableUuid("revision/" + canonicalVersionId + "/" + spec.realmSlug()); - String logicalRevisionId = - "realm-policy/" + spec.worldSlug() + "/" + spec.realmSlug(); - String policyDigest = - PublishedRealmEntryPolicySetEvidence.policyDigest( - policyId, - target, - versionNumber, - release.publishedReleaseBundleRef(), - release.contentDigest(), - workflow, - DIGEST, - draft.commitId(), - revisionId, - logicalRevisionId, - policy); - return new PublishedRealmEntryPolicyEvidence( + .map(spec -> { + RealmEntryPolicy policy = policy(spec); + UUID policyId = stableUuid("policy/" + canonicalVersionId + "/" + spec.realmSlug()); + UUID revisionId = + stableUuid("revision/" + canonicalVersionId + "/" + spec.realmSlug()); + String logicalRevisionId = + "realm-policy/" + spec.worldSlug() + "/" + spec.realmSlug(); + String policyDigest = + PublishedRealmEntryPolicySetEvidence.policyDigest( policyId, + target, + versionNumber, + release.publishedReleaseBundleRef(), + release.contentDigest(), + workflow, + DIGEST, draft.commitId(), revisionId, logicalRevisionId, - policy, - policyDigest); - }) + policy); + return new PublishedRealmEntryPolicyEvidence( + policyId, draft.commitId(), revisionId, logicalRevisionId, policy, policyDigest); + }) .toList(); byte[] capture = capture(operation, draft, "43", specs, policies); String setDigest = @@ -559,16 +551,14 @@ private static DraftAuthorizationFenceBinding.OwnerReadback committedFreshGraphR result.put( "appliedEpochs", draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - Map.of( - "aggregateType", unit.aggregateType(), - "aggregateId", unit.aggregateId(), - "scopeType", unit.scopeType(), - "scopeId", unit.scopeId(), - "expectedEpoch", unit.expectedEpoch(), - "resultingEpoch", - Long.toString(Long.parseLong(unit.expectedEpoch()) + 1))) + .map(unit -> + Map.of( + "aggregateType", unit.aggregateType(), + "aggregateId", unit.aggregateId(), + "scopeType", unit.scopeType(), + "scopeId", unit.scopeId(), + "expectedEpoch", unit.expectedEpoch(), + "resultingEpoch", Long.toString(Long.parseLong(unit.expectedEpoch()) + 1))) .toList()); byte[] resultBytes = canonical(JSON.valueToTree(result)); return new DraftAuthorizationFenceBinding.OwnerReadback( @@ -629,20 +619,18 @@ private static byte[] capture( try { List> entries = java.util.stream.IntStream.range(0, specs.size()) - .mapToObj( - index -> { - Map source = new LinkedHashMap<>(); - source.put("commitId", policies.get(index).sourceCommitId().toString()); - source.put("revisionId", policies.get(index).sourceRevisionId().toString()); - source.put("logicalRevisionId", policies.get(index).logicalRevisionId()); - try { - source.put( - "policy", JSON.readTree(policies.get(index).policy().canonicalJson())); - } catch (Exception impossible) { - throw new IllegalStateException(impossible); - } - return source; - }) + .mapToObj(index -> { + Map source = new LinkedHashMap<>(); + source.put("commitId", policies.get(index).sourceCommitId().toString()); + source.put("revisionId", policies.get(index).sourceRevisionId().toString()); + source.put("logicalRevisionId", policies.get(index).logicalRevisionId()); + try { + source.put("policy", JSON.readTree(policies.get(index).policy().canonicalJson())); + } catch (Exception impossible) { + throw new IllegalStateException(impossible); + } + return source; + }) .toList(); var snapshot = new LinkedHashMap(); snapshot.put("schema", PublishedRealmEntryPolicySetEvidence.SNAPSHOT_SCHEMA); @@ -669,25 +657,19 @@ private static ReleaseContent release( var request = operation.world().request(); List participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new Participant( - owner, - Long.toString( - operation - .account() - .input() - .selection() - .target() - .gameDesignVersionRowId()), - null, - request.appliedCommitId(), - owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - owner.equals("GAME_LOGIC") ? DIGEST : null, - null, - null)) + .map(owner -> + new Participant( + owner, + Long.toString( + operation.account().input().selection().target().gameDesignVersionRowId()), + null, + request.appliedCommitId(), + owner.equals("WORLD_MANAGEMENT") ? request.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + owner.equals("GAME_LOGIC") ? DIGEST : null, + null, + null)) .toList(); return new ReleaseContent( request.canonicalTenantId(), diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java index a3dde2ad68..b9a166f3b6 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialService.java @@ -966,13 +966,12 @@ private static boolean certificateRequestOwnedBy( List owners = request.getMetadata().getOwnerReferences(); return owners != null && owners.stream() - .anyMatch( - owner -> - Boolean.TRUE.equals(owner.getController()) - && "cert-manager.io/v1".equals(owner.getApiVersion()) - && "Certificate".equals(owner.getKind()) - && certificate.name().equals(owner.getName()) - && certificate.uid().equals(owner.getUid())); + .anyMatch(owner -> + Boolean.TRUE.equals(owner.getController()) + && "cert-manager.io/v1".equals(owner.getApiVersion()) + && "Certificate".equals(owner.getKind()) + && certificate.name().equals(owner.getName()) + && certificate.uid().equals(owner.getUid())); } static Map issuerReference(GenericKubernetesResource resource) { @@ -1000,10 +999,8 @@ private static boolean readyCondition(Object conditions) { && conditionList.stream() .filter(Map.class::isInstance) .map(Map.class::cast) - .anyMatch( - condition -> - "Ready".equals(condition.get("type")) - && "True".equals(condition.get("status"))); + .anyMatch(condition -> + "Ready".equals(condition.get("type")) && "True".equals(condition.get("status"))); } private static void requireCertManagerSourceBinding( @@ -1026,13 +1023,11 @@ private static void requireCertManagerSourceBinding( if (ownerReferences != null && ownerReferences.stream() .filter(reference -> Boolean.TRUE.equals(reference.getController())) - .anyMatch( - reference -> - !"cert-manager.io/v1".equals(reference.getApiVersion()) - || !"Certificate".equals(reference.getKind()) - || !certificateName.equals(reference.getName()) - || (certificate != null - && !certificate.uid().equals(reference.getUid())))) { + .anyMatch(reference -> + !"cert-manager.io/v1".equals(reference.getApiVersion()) + || !"Certificate".equals(reference.getKind()) + || !certificateName.equals(reference.getName()) + || (certificate != null && !certificate.uid().equals(reference.getUid())))) { throw new IllegalStateException("identity source Secret has an invalid Certificate owner"); } } @@ -1230,12 +1225,11 @@ static CertificateRevision readyRevision(GenericKubernetesResource resource) { conditionList.stream() .filter(Map.class::isInstance) .map(Map.class::cast) - .anyMatch( - condition -> - "Ready".equals(condition.get("type")) - && "True".equals(condition.get("status")) - && Long.valueOf(generation) - .equals(positiveLong(condition.get("observedGeneration")))); + .anyMatch(condition -> + "Ready".equals(condition.get("type")) + && "True".equals(condition.get("status")) + && Long.valueOf(generation) + .equals(positiveLong(condition.get("observedGeneration")))); return ready ? new CertificateRevision(revision, generation) : null; } diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeService.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeService.java index aaf073bfe0..7ce142210c 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeService.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeService.java @@ -88,11 +88,10 @@ public static boolean hasExpectedIdentityNamespaceMetadata( expectedLabels.entrySet().stream() .allMatch(entry -> entry.getValue().equals(labels.get(entry.getKey()))) && labels.entrySet().stream() - .allMatch( - entry -> - entry.getValue().equals(expectedLabels.get(entry.getKey())) - || ("kubernetes.io/metadata.name".equals(entry.getKey()) - && plan.identityNamespace().equals(entry.getValue()))); + .allMatch(entry -> + entry.getValue().equals(expectedLabels.get(entry.getKey())) + || ("kubernetes.io/metadata.name".equals(entry.getKey()) + && plan.identityNamespace().equals(entry.getValue()))); if (!plan.identityNamespace().equals(namespace.getMetadata().getName()) || (namespace.getMetadata().getGenerateName() != null && !namespace.getMetadata().getGenerateName().isBlank()) diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionService.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionService.java index 70fc1ccbb6..e4bb2d8b7c 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionService.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionService.java @@ -310,11 +310,10 @@ public static String revisionForData(Map data) { MessageDigest digest = MessageDigest.getInstance("SHA-256"); data.entrySet().stream() .sorted(Map.Entry.comparingByKey()) - .forEach( - entry -> { - updateLengthPrefixed(digest, entry.getKey().getBytes(StandardCharsets.UTF_8)); - updateLengthPrefixed(digest, Base64.getDecoder().decode(entry.getValue())); - }); + .forEach(entry -> { + updateLengthPrefixed(digest, entry.getKey().getBytes(StandardCharsets.UTF_8)); + updateLengthPrefixed(digest, Base64.getDecoder().decode(entry.getValue())); + }); return "sha256:" + HexFormat.of().formatHex(digest.digest()); } catch (NoSuchAlgorithmException exception) { throw new IllegalStateException("unable to calculate material revision", exception); diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java index da3836b682..8053e8ef8a 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbe.java @@ -413,16 +413,15 @@ ProbeResult probe( private static RunningProbe startProbe(ProbeName name, Callable operation) { ProbeAttempt attempt = new ProbeAttempt(); FutureTask task = - new FutureTask<>( - () -> { - CURRENT_ATTEMPT.set(attempt); - try { - return operation.call(); - } finally { - attempt.closeOpenSocket(); - CURRENT_ATTEMPT.remove(); - } - }); + new FutureTask<>(() -> { + CURRENT_ATTEMPT.set(attempt); + try { + return operation.call(); + } finally { + attempt.closeOpenSocket(); + CURRENT_ATTEMPT.remove(); + } + }); Thread.ofVirtual().name("served-environment-probe-" + name.label()).start(task); return new RunningProbe(name, task, attempt); } @@ -656,14 +655,13 @@ static SSLContext grpcSslContext(Secret material, String expectedTrustAnchor) th List anchors = certificates(requiredData(material, "ca.crt")); X509Certificate anchor = anchors.stream() - .filter( - certificate -> { - try { - return normalizedAnchor.equals(fingerprint(certificate)); - } catch (Exception exception) { - throw new IllegalArgumentException("gRPC trust anchor is invalid", exception); - } - }) + .filter(certificate -> { + try { + return normalizedAnchor.equals(fingerprint(certificate)); + } catch (Exception exception) { + throw new IllegalArgumentException("gRPC trust anchor is invalid", exception); + } + }) .findFirst() .orElseThrow(() -> new IllegalArgumentException("gRPC trust anchor mismatch")); diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java index e5447bfe97..8e0e1e72c1 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconciler.java @@ -879,12 +879,11 @@ static boolean retiredStatusIsCurrent(HostedEnvironmentIdentity resource) { return false; } return resource.getStatus().getConditions().stream() - .anyMatch( - condition -> - "Ready".equals(condition.getType()) - && "False".equals(condition.getStatus()) - && java.util.Objects.equals( - resource.getMetadata().getGeneration(), condition.getObservedGeneration())); + .anyMatch(condition -> + "Ready".equals(condition.getType()) + && "False".equals(condition.getStatus()) + && java.util.Objects.equals( + resource.getMetadata().getGeneration(), condition.getObservedGeneration())); } static UpdateControl finishRetirement( diff --git a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/security/GrpcTransportBundleGenerator.java b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/security/GrpcTransportBundleGenerator.java index 612669e199..cb3b6dac4c 100644 --- a/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/security/GrpcTransportBundleGenerator.java +++ b/services/hosted-environment-identity-controller/src/main/java/net/firedevops/firemud/hostedidentity/security/GrpcTransportBundleGenerator.java @@ -210,13 +210,12 @@ Secret generate( public static List grpcDnsNames(EnvironmentIdentityPlan plan) { return plan.grpcConsumers().stream() - .flatMap( - service -> - java.util.stream.Stream.of( - service, - service + "." + plan.runtimeNamespace(), - service + "." + plan.runtimeNamespace() + ".svc", - service + "." + plan.runtimeNamespace() + ".svc.cluster.local")) + .flatMap(service -> + java.util.stream.Stream.of( + service, + service + "." + plan.runtimeNamespace(), + service + "." + plan.runtimeNamespace() + ".svc", + service + "." + plan.runtimeNamespace() + ".svc.cluster.local")) .distinct() .sorted() .toList(); diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialServiceTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialServiceTest.java index b4e98dcc23..5acc949fd0 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialServiceTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/CertificateMaterialServiceTest.java @@ -369,9 +369,8 @@ void certificateRepairTreatsConflictAsTransientButPropagatesOtherFailures() { .when(lockedReplacementResource) .replace(); - assertDoesNotThrow( - () -> - CertificateMaterialService.applyCertificate(client, plan.identityNamespace(), desired)); + assertDoesNotThrow(() -> + CertificateMaterialService.applyCertificate(client, plan.identityNamespace(), desired)); existingSpec.put("secretName", "another-obsolete-secret-name"); KubernetesClientException failure = new KubernetesClientException("forbidden", 403, null); diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeServiceTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeServiceTest.java index 9219701a37..39e1200c12 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeServiceTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/HostedIdentityScopeServiceTest.java @@ -891,12 +891,11 @@ private static List admittedRuntimeDeploymentNames() throws IOException scopeRoleAdmissionExpression(RUNTIME_SCOPE_MARKER, "runtime-scope"); List deploymentRules = celExistsRuleBodies(runtimeScopeExpression).stream() - .filter( - rule -> - Optional.of(List.of("apps")).equals(celListEquality(rule, "apiGroups")) - && Optional.of(List.of("deployments")) - .equals(celListEquality(rule, "resources")) - && celListEquality(rule, "resourceNames").isPresent()) + .filter(rule -> + Optional.of(List.of("apps")).equals(celListEquality(rule, "apiGroups")) + && Optional.of(List.of("deployments")) + .equals(celListEquality(rule, "resources")) + && celListEquality(rule, "resourceNames").isPresent()) .toList(); assertEquals( 1, deploymentRules.size(), "runtime deployment matcher must have exactly one rule"); @@ -915,13 +914,11 @@ private static List admittedIdentitySecretNames( scopeRoleAdmissionExpression(IDENTITY_SCOPE_MARKER, "identity-scope"); List secretRules = celExistsRuleBodies(identityScopeExpression).stream() - .filter( - rule -> - Optional.of(List.of("")).equals(celListEquality(rule, "apiGroups")) - && Optional.of(List.of("secrets")) - .equals(celListEquality(rule, "resources")) - && Optional.of(verbs).equals(celListEquality(rule, "verbs")) - && celListExpressions(rule, "resourceNames").isPresent()) + .filter(rule -> + Optional.of(List.of("")).equals(celListEquality(rule, "apiGroups")) + && Optional.of(List.of("secrets")).equals(celListEquality(rule, "resources")) + && Optional.of(verbs).equals(celListEquality(rule, "verbs")) + && celListExpressions(rule, "resourceNames").isPresent()) .toList(); assertEquals( 1, @@ -942,10 +939,9 @@ private static String scopeRoleAdmissionExpression(String marker, String scopeDe .filter(Objects::nonNull) .map(Map.class::cast) .filter(document -> "ValidatingAdmissionPolicy".equals(document.get("kind"))) - .filter( - document -> - "firemud-hosted-identity-scope-roles" - .equals(((Map) document.get("metadata")).get("name"))) + .filter(document -> + "firemud-hosted-identity-scope-roles" + .equals(((Map) document.get("metadata")).get("name"))) .findFirst() .orElseThrow(() -> new AssertionError("scope-role admission policy must exist")); } @@ -1004,12 +1000,11 @@ private static Optional> celListEquality(String expression, String } return Optional.of( expressions.get().stream() - .map( - element -> { - var literal = CEL_STRING_LITERAL.matcher(element); - assertTrue(literal.matches(), "CEL list element must be a string literal"); - return literal.group(1); - }) + .map(element -> { + var literal = CEL_STRING_LITERAL.matcher(element); + assertTrue(literal.matches(), "CEL list element must be a string literal"); + return literal.group(1); + }) .toList()); } diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/RuntimeProfileServiceTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/RuntimeProfileServiceTest.java index b3364ee938..c03ca33824 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/RuntimeProfileServiceTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/RuntimeProfileServiceTest.java @@ -741,24 +741,22 @@ void publicRuntimeRejectsExternalIps() { @Test void canonicalTcpProxyServicePassesForPublicAndPrivateModes() { var publicPlan = planner.plan("pr-42"); - assertDoesNotThrow( - () -> - validateTcpProxyService( - publicPlan, - previewRuntimeNamespace("a".repeat(40), "a".repeat(40), "32002"), - tcpProxyService("NodePort", 32002))); + assertDoesNotThrow(() -> + validateTcpProxyService( + publicPlan, + previewRuntimeNamespace("a".repeat(40), "a".repeat(40), "32002"), + tcpProxyService("NodePort", 32002))); var privatePlan = planner.plan("pr-42"); - assertDoesNotThrow( - () -> - validateTcpProxyService( - privatePlan, - previewRuntimeNamespace( - "a".repeat(40), - "a".repeat(40), - null, - HostedIdentityContract.PRIVATE_PREVIEW_EXPOSURE_MODE), - tcpProxyService("ClusterIP", null))); + assertDoesNotThrow(() -> + validateTcpProxyService( + privatePlan, + previewRuntimeNamespace( + "a".repeat(40), + "a".repeat(40), + null, + HostedIdentityContract.PRIVATE_PREVIEW_EXPOSURE_MODE), + tcpProxyService("ClusterIP", null))); } @Test @@ -770,12 +768,11 @@ void runtimeProfileAcceptsKubernetesDefaultedProtocolAndTargetPort() { 32002, new ServicePortBuilder().withName("tcp-2323").withPort(2323).build()); - assertDoesNotThrow( - () -> - validateTcpProxyService( - plan, - previewRuntimeNamespace("a".repeat(40), "a".repeat(40), "32002"), - defaultedPortService)); + assertDoesNotThrow(() -> + validateTcpProxyService( + plan, + previewRuntimeNamespace("a".repeat(40), "a".repeat(40), "32002"), + defaultedPortService)); } @Test diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionServiceTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionServiceTest.java index 19d4d1c78e..d85be8a2fe 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionServiceTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/kubernetes/SecretProjectionServiceTest.java @@ -1428,17 +1428,12 @@ void caRotationValidatesOnlyTheSelectedNewSourceAndPinsOtherSharedRoles() { org.mockito.ArgumentMatchers.anyBoolean(), org.mockito.ArgumentMatchers.anyBoolean(), org.mockito.ArgumentMatchers.anyString())) - .thenAnswer( - invocation -> { - Secret source = invocation.getArgument(0); - String spki = source == selectedGatewaySource ? "3".repeat(64) : "2".repeat(64); - return new SecretMaterialValidator.MaterialSummary( - "1".repeat(64), - spki, - java.time.Instant.EPOCH, - java.time.Instant.MAX, - "4".repeat(64)); - }); + .thenAnswer(invocation -> { + Secret source = invocation.getArgument(0); + String spki = source == selectedGatewaySource ? "3".repeat(64) : "2".repeat(64); + return new SecretMaterialValidator.MaterialSummary( + "1".repeat(64), spki, java.time.Instant.EPOCH, java.time.Instant.MAX, "4".repeat(64)); + }); GrpcTransportBundleGenerator generator = mock(GrpcTransportBundleGenerator.class); CertificateMaterialService service = new CertificateMaterialService( diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java index f05eef0094..f2801f8d3d 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/probe/ServedEnvironmentProbeTest.java @@ -777,46 +777,45 @@ private static HostedEnvironmentProbeFixture bridgeFixture( private static CompletableFuture serveBridge( SSLServerSocket server, BridgeResponse response) { - return CompletableFuture.supplyAsync( - () -> { - try (SSLSocket peer = (SSLSocket) server.accept()) { - peer.startHandshake(); - String request = readRequest(peer.getInputStream()); - if (response == BridgeResponse.NO_RESPONSE) { - return request; - } - String nonce = requestHeader(request, "Sec-WebSocket-Key"); - String accept = - response == BridgeResponse.MALFORMED_ACCEPT - ? "not-the-request-accept" - : websocketAccept(nonce); - StringBuilder payload = - new StringBuilder() - .append( - response == BridgeResponse.BAD_STATUS - ? "HTTP/1.1 200 OK" - : response == BridgeResponse.FORBIDDEN - ? "HTTP/1.1 403 Forbidden" - : "HTTP/1.1 101 Switching Protocols") - .append("\r\n"); - if (response != BridgeResponse.MISSING_UPGRADE) { - payload.append("Upgrade: websocket\r\n"); - } - if (response != BridgeResponse.MISSING_CONNECTION) { - payload.append("Connection: Upgrade\r\n"); - } - if (response != BridgeResponse.MISSING_ACCEPT) { - payload.append("Sec-WebSocket-Accept: ").append(accept).append("\r\n"); - } - payload.append("\r\n"); - OutputStream output = peer.getOutputStream(); - output.write(payload.toString().getBytes(StandardCharsets.ISO_8859_1)); - output.flush(); - return request; - } catch (Exception exception) { - throw new IllegalStateException(exception); - } - }); + return CompletableFuture.supplyAsync(() -> { + try (SSLSocket peer = (SSLSocket) server.accept()) { + peer.startHandshake(); + String request = readRequest(peer.getInputStream()); + if (response == BridgeResponse.NO_RESPONSE) { + return request; + } + String nonce = requestHeader(request, "Sec-WebSocket-Key"); + String accept = + response == BridgeResponse.MALFORMED_ACCEPT + ? "not-the-request-accept" + : websocketAccept(nonce); + StringBuilder payload = + new StringBuilder() + .append( + response == BridgeResponse.BAD_STATUS + ? "HTTP/1.1 200 OK" + : response == BridgeResponse.FORBIDDEN + ? "HTTP/1.1 403 Forbidden" + : "HTTP/1.1 101 Switching Protocols") + .append("\r\n"); + if (response != BridgeResponse.MISSING_UPGRADE) { + payload.append("Upgrade: websocket\r\n"); + } + if (response != BridgeResponse.MISSING_CONNECTION) { + payload.append("Connection: Upgrade\r\n"); + } + if (response != BridgeResponse.MISSING_ACCEPT) { + payload.append("Sec-WebSocket-Accept: ").append(accept).append("\r\n"); + } + payload.append("\r\n"); + OutputStream output = peer.getOutputStream(); + output.write(payload.toString().getBytes(StandardCharsets.ISO_8859_1)); + output.flush(); + return request; + } catch (Exception exception) { + throw new IllegalStateException(exception); + } + }); } private static String readRequest(InputStream input) throws IOException { @@ -884,14 +883,13 @@ private static SSLServerSocket mutualTlsServer( } private static CompletableFuture acceptOne(SSLServerSocket server) { - return CompletableFuture.runAsync( - () -> { - try (SSLSocket peer = (SSLSocket) server.accept()) { - peer.startHandshake(); - } catch (Exception exception) { - throw new IllegalStateException(exception); - } - }); + return CompletableFuture.runAsync(() -> { + try (SSLSocket peer = (SSLSocket) server.accept()) { + peer.startHandshake(); + } catch (Exception exception) { + throw new IllegalStateException(exception); + } + }); } private static EnvironmentIdentityPlan withConsumers( diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java index 85ccd905a5..5fda7de47c 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/reconcile/HostedIdentityReconcilerSafetyTest.java @@ -218,18 +218,17 @@ void workloadIdentityProjectionMustBeAcceptedBeforeReadiness() { new java.util.LinkedHashMap<>(); when(fixture.projections.acknowledge( any(), any(), anyString(), anyString(), anyLong(), anyLong(), anyString(), any())) - .thenAnswer( - invocation -> { - String role = invocation.getArgument(2, String.class); - String revision = invocation.getArgument(3, String.class); - SecretProjectionService.ProjectionResult result = - HostedIdentityContract.grpcPublicationRole("game-logic-service").equals(role) - ? SecretProjectionService.ProjectionResult.awaiting( - "awaiting-acceptance", revision) - : SecretProjectionService.ProjectionResult.synced(revision); - acknowledgedProjections.put(role, result); - return result; - }); + .thenAnswer(invocation -> { + String role = invocation.getArgument(2, String.class); + String revision = invocation.getArgument(3, String.class); + SecretProjectionService.ProjectionResult result = + HostedIdentityContract.grpcPublicationRole("game-logic-service").equals(role) + ? SecretProjectionService.ProjectionResult.awaiting( + "awaiting-acceptance", revision) + : SecretProjectionService.ProjectionResult.synced(revision); + acknowledgedProjections.put(role, result); + return result; + }); UpdateControl result = fixture.reconcile(); @@ -253,11 +252,10 @@ void workloadIdentityProjectionMustBeAcceptedBeforeReadiness() { .state()); assertTrue( acknowledgedProjections.entrySet().stream() - .filter( - entry -> - !entry - .getKey() - .equals(HostedIdentityContract.grpcPublicationRole("game-logic-service"))) + .filter(entry -> + !entry + .getKey() + .equals(HostedIdentityContract.grpcPublicationRole("game-logic-service"))) .allMatch(entry -> entry.getValue().isSynced())); verify(fixture.rollout) .sync( @@ -731,12 +729,11 @@ void identityProjectionFenceNamesTheProtectedAction(CapturedOutput output) { anyString(), anyString(), any())) - .thenAnswer( - invocation -> { - Runnable guard = invocation.getArgument(8); - guard.run(); - throw new AssertionError("runtime-profile guard unexpectedly passed"); - }); + .thenAnswer(invocation -> { + Runnable guard = invocation.getArgument(8); + guard.run(); + throw new AssertionError("runtime-profile guard unexpectedly passed"); + }); UpdateControl result = fixture.reconcile(); @@ -882,12 +879,11 @@ void projectionAcknowledgementFenceNamesTheProtectedAction() { .thenReturn(new ServedEnvironmentProbe.ProbeResult(true, "served")); when(fixture.projections.acknowledge( any(), any(), anyString(), anyString(), anyLong(), anyLong(), anyString(), any())) - .thenAnswer( - invocation -> { - Runnable guard = invocation.getArgument(7); - guard.run(); - throw new AssertionError("runtime-profile guard unexpectedly passed"); - }); + .thenAnswer(invocation -> { + Runnable guard = invocation.getArgument(7); + guard.run(); + throw new AssertionError("runtime-profile guard unexpectedly passed"); + }); UpdateControl result = fixture.reconcile(); @@ -2629,13 +2625,12 @@ private DeploymentHeadGateFixture(RuntimeProfileService.RuntimeProfile runtimePr when(batch.grpcGatewayClient()) .thenReturn(material(plan, HostedIdentityContract.GRPC_GATEWAY_CLIENT_ROLE, "e")); when(batch.grpcPublication(anyString())) - .thenAnswer( - invocation -> { - String workload = invocation.getArgument(0, String.class); - String fingerprintDigit = grpcPublicationFixtureFingerprintDigit(workload); - return material( - plan, HostedIdentityContract.grpcPublicationRole(workload), fingerprintDigit); - }); + .thenAnswer(invocation -> { + String workload = invocation.getArgument(0, String.class); + String fingerprintDigit = grpcPublicationFixtureFingerprintDigit(workload); + return material( + plan, HostedIdentityContract.grpcPublicationRole(workload), fingerprintDigit); + }); when(projections.project( org.mockito.ArgumentMatchers.eq(client), org.mockito.ArgumentMatchers.eq(plan), @@ -2646,10 +2641,9 @@ private DeploymentHeadGateFixture(RuntimeProfileService.RuntimeProfile runtimePr anyString(), anyString(), any())) - .thenAnswer( - invocation -> - SecretProjectionService.ProjectionResult.synced( - "revision-" + invocation.getArgument(2, String.class))); + .thenAnswer(invocation -> + SecretProjectionService.ProjectionResult.synced( + "revision-" + invocation.getArgument(2, String.class))); reconciler = new HostedIdentityReconciler( diff --git a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/SecretMaterialValidatorTest.java b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/SecretMaterialValidatorTest.java index 009eece233..067593af06 100644 --- a/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/SecretMaterialValidatorTest.java +++ b/services/hosted-environment-identity-controller/src/test/java/net/firedevops/firemud/hostedidentity/security/SecretMaterialValidatorTest.java @@ -120,10 +120,9 @@ void generatedGrpcBundleHasTransportUsagesAndNoPerWorkloadIdentityClaim() throws assertNotNull(subjectAlternativeNames); assertTrue( subjectAlternativeNames.stream() - .allMatch( - subjectAlternativeName -> - subjectAlternativeName.size() == 2 - && Integer.valueOf(2).equals(subjectAlternativeName.get(0)))); + .allMatch(subjectAlternativeName -> + subjectAlternativeName.size() == 2 + && Integer.valueOf(2).equals(subjectAlternativeName.get(0)))); assertEquals( GrpcTransportBundleGenerator.grpcDnsNames(plan), subjectAlternativeNames.stream() @@ -1252,11 +1251,10 @@ private static Replacement stubReplacement( ReplaceDeletable lockedResource = mock(ReplaceDeletable.class); AtomicReference holder = new AtomicReference<>(); when(identityClient.identitySecrets().resource(org.mockito.ArgumentMatchers.any(Secret.class))) - .thenAnswer( - invocation -> { - holder.set(invocation.getArgument(0, Secret.class)); - return resource; - }); + .thenAnswer(invocation -> { + holder.set(invocation.getArgument(0, Secret.class)); + return resource; + }); when(resource.lockResourceVersion(resourceVersion)).thenReturn(lockedResource); when(lockedResource.replace()).thenAnswer(invocation -> holder.get()); return new Replacement(resource, lockedResource, holder); diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerController.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerController.java index 089419ad02..47ead1d18e 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerController.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerController.java @@ -43,13 +43,12 @@ public ResponseEntity>> listAudit( @PathVariable String tenantId, @PathVariable String worldSlug, @PathVariable String realmSlug) { - return LoggingAdminRequestReaders.withBadRequest( - () -> { - long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); - return ResponseEntity.ok( - ApiResponse.success( - admissionPointerService.listPointerAudit(parsedTenantId, worldSlug, realmSlug))); - }); + return LoggingAdminRequestReaders.withBadRequest(() -> { + long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); + return ResponseEntity.ok( + ApiResponse.success( + admissionPointerService.listPointerAudit(parsedTenantId, worldSlug, realmSlug))); + }); } @GetMapping("/runtime-state/{tenantId}/{gameInstanceId}") @@ -58,15 +57,14 @@ public ResponseEntity>> listAudit( description = "Read canonical current runtime state and current admission pointers") public ResponseEntity> getRuntimeState( @PathVariable String tenantId, @PathVariable String gameInstanceId) { - return LoggingAdminRequestReaders.withBadRequest( - () -> { - long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); - long parsedGameInstanceId = - LoggingAdminRequestReaders.requirePositiveLong(gameInstanceId, "gameInstanceId"); - return ResponseEntity.ok( - ApiResponse.success( - admissionPointerService.getRuntimeState(parsedTenantId, parsedGameInstanceId))); - }); + return LoggingAdminRequestReaders.withBadRequest(() -> { + long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); + long parsedGameInstanceId = + LoggingAdminRequestReaders.requirePositiveLong(gameInstanceId, "gameInstanceId"); + return ResponseEntity.ok( + ApiResponse.success( + admissionPointerService.getRuntimeState(parsedTenantId, parsedGameInstanceId))); + }); } @GetMapping("/version-upgrades/{tenantId}/{preparationId}") @@ -75,14 +73,12 @@ public ResponseEntity> getRuntimeState( description = "Read a prepared version upgrade compatibility proof") public ResponseEntity> getPreparedVersionUpgrade( @PathVariable String tenantId, @PathVariable String preparationId) { - return LoggingAdminRequestReaders.withBadRequest( - () -> { - long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); - return ResponseEntity.ok( - ApiResponse.success( - admissionPointerService.getPreparedVersionUpgrade( - parsedTenantId, preparationId))); - }); + return LoggingAdminRequestReaders.withBadRequest(() -> { + long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); + return ResponseEntity.ok( + ApiResponse.success( + admissionPointerService.getPreparedVersionUpgrade(parsedTenantId, preparationId))); + }); } @GetMapping("/version-upgrades/{tenantId}/{sourceGameInstanceId}/compatibility/{targetVersionId}") @@ -95,18 +91,17 @@ public ResponseEntity> getPreparedVersion @PathVariable String tenantId, @PathVariable String sourceGameInstanceId, @PathVariable String targetVersionId) { - return LoggingAdminRequestReaders.withBadRequest( - () -> { - long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); - long parsedSourceGameInstanceId = - LoggingAdminRequestReaders.requirePositiveLong( - sourceGameInstanceId, "sourceGameInstanceId"); - long parsedTargetVersionId = - LoggingAdminRequestReaders.requirePositiveLong(targetVersionId, "targetVersionId"); - return ResponseEntity.ok( - ApiResponse.success( - admissionPointerService.validateInstanceCutoverCompatibility( - parsedTenantId, parsedSourceGameInstanceId, parsedTargetVersionId))); - }); + return LoggingAdminRequestReaders.withBadRequest(() -> { + long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); + long parsedSourceGameInstanceId = + LoggingAdminRequestReaders.requirePositiveLong( + sourceGameInstanceId, "sourceGameInstanceId"); + long parsedTargetVersionId = + LoggingAdminRequestReaders.requirePositiveLong(targetVersionId, "targetVersionId"); + return ResponseEntity.ok( + ApiResponse.success( + admissionPointerService.validateInstanceCutoverCompatibility( + parsedTenantId, parsedSourceGameInstanceId, parsedTargetVersionId))); + }); } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/GameSessionPinController.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/GameSessionPinController.java index 2061a80442..75677dda8f 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/GameSessionPinController.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/GameSessionPinController.java @@ -26,16 +26,15 @@ public GameSessionPinController(GameSessionPinService gameSessionPinService) { description = "Read current pinned script patch version for one runtime") public ResponseEntity> getPinnedScriptPatchVersion( @PathVariable String tenantId, @PathVariable String gameInstanceId) { - return LoggingAdminRequestReaders.withBadRequest( - () -> { - long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); - long parsedGameInstanceId = - LoggingAdminRequestReaders.requirePositiveLong(gameInstanceId, "gameInstanceId"); - return ResponseEntity.ok( - ApiResponse.success( - gameSessionPinService.getPinnedScriptPatchVersion( - parsedTenantId, parsedGameInstanceId))); - }); + return LoggingAdminRequestReaders.withBadRequest(() -> { + long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); + long parsedGameInstanceId = + LoggingAdminRequestReaders.requirePositiveLong(gameInstanceId, "gameInstanceId"); + return ResponseEntity.ok( + ApiResponse.success( + gameSessionPinService.getPinnedScriptPatchVersion( + parsedTenantId, parsedGameInstanceId))); + }); } @GetMapping("/{tenantId}/{gameInstanceId}/convergence") @@ -44,15 +43,14 @@ public ResponseEntity> getPinnedScriptP description = "Read persisted Game Session pin convergence for one runtime") public ResponseEntity> getGameSessionPinConvergence( @PathVariable String tenantId, @PathVariable String gameInstanceId) { - return LoggingAdminRequestReaders.withBadRequest( - () -> { - long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); - long parsedGameInstanceId = - LoggingAdminRequestReaders.requirePositiveLong(gameInstanceId, "gameInstanceId"); - return ResponseEntity.ok( - ApiResponse.success( - gameSessionPinService.getGameSessionPinConvergence( - parsedTenantId, parsedGameInstanceId))); - }); + return LoggingAdminRequestReaders.withBadRequest(() -> { + long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); + long parsedGameInstanceId = + LoggingAdminRequestReaders.requirePositiveLong(gameInstanceId, "gameInstanceId"); + return ResponseEntity.ok( + ApiResponse.success( + gameSessionPinService.getGameSessionPinConvergence( + parsedTenantId, parsedGameInstanceId))); + }); } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/GameplayCommandController.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/GameplayCommandController.java index 7ab88673f6..45feb5c221 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/GameplayCommandController.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/GameplayCommandController.java @@ -28,15 +28,14 @@ public ResponseEntity> getGameplayCommandS @PathVariable String tenantId, @PathVariable String gameInstanceId, @PathVariable String commandId) { - return LoggingAdminRequestReaders.withBadRequest( - () -> { - long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); - long parsedGameInstanceId = - LoggingAdminRequestReaders.requirePositiveLong(gameInstanceId, "gameInstanceId"); - return ResponseEntity.ok( - ApiResponse.success( - gameplayCommandStatusService.getGameplayCommandStatus( - parsedTenantId, parsedGameInstanceId, commandId))); - }); + return LoggingAdminRequestReaders.withBadRequest(() -> { + long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); + long parsedGameInstanceId = + LoggingAdminRequestReaders.requirePositiveLong(gameInstanceId, "gameInstanceId"); + return ResponseEntity.ok( + ApiResponse.success( + gameplayCommandStatusService.getGameplayCommandStatus( + parsedTenantId, parsedGameInstanceId, commandId))); + }); } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/RemoteCommandCoordinatorController.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/RemoteCommandCoordinatorController.java index 9fc92b5c2a..32ae6c99e9 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/RemoteCommandCoordinatorController.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/RemoteCommandCoordinatorController.java @@ -30,14 +30,13 @@ public RemoteCommandCoordinatorController( listRemoteCommandCoordinators( @PathVariable String tenantId, @ModelAttribute RemoteCommandCoordinatorListRequest request) { - return LoggingAdminRequestReaders.withBadRequest( - () -> { - long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); - return ResponseEntity.ok( - ApiResponse.success( - remoteCommandCoordinatorService.listRemoteCommandCoordinators( - parsedTenantId, request))); - }); + return LoggingAdminRequestReaders.withBadRequest(() -> { + long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); + return ResponseEntity.ok( + ApiResponse.success( + remoteCommandCoordinatorService.listRemoteCommandCoordinators( + parsedTenantId, request))); + }); } @GetMapping("/{tenantId}/{coordinatorId}") @@ -46,13 +45,12 @@ public RemoteCommandCoordinatorController( description = "Read canonical remote command coordinator by tenant-qualified coordinator id") public ResponseEntity> getRemoteCommandCoordinator( @PathVariable String tenantId, @PathVariable String coordinatorId) { - return LoggingAdminRequestReaders.withBadRequest( - () -> { - long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); - return ResponseEntity.ok( - ApiResponse.success( - remoteCommandCoordinatorService.getRemoteCommandCoordinator( - parsedTenantId, coordinatorId))); - }); + return LoggingAdminRequestReaders.withBadRequest(() -> { + long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); + return ResponseEntity.ok( + ApiResponse.success( + remoteCommandCoordinatorService.getRemoteCommandCoordinator( + parsedTenantId, coordinatorId))); + }); } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupController.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupController.java index f296259bd7..4066df3cc0 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupController.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupController.java @@ -27,13 +27,11 @@ public RemoteFollowupController(RemoteFollowupService remoteFollowupService) { description = "Read canonical remote followup by tenant-qualified followup id") public ResponseEntity> getRemoteFollowup( @PathVariable String tenantId, @PathVariable String followupId) { - return LoggingAdminRequestReaders.withBadRequest( - () -> { - long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); - return ResponseEntity.ok( - ApiResponse.success( - remoteFollowupService.getRemoteFollowup(parsedTenantId, followupId))); - }); + return LoggingAdminRequestReaders.withBadRequest(() -> { + long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); + return ResponseEntity.ok( + ApiResponse.success(remoteFollowupService.getRemoteFollowup(parsedTenantId, followupId))); + }); } @GetMapping("/{tenantId}") @@ -43,12 +41,10 @@ public ResponseEntity> getRemoteFollowup( "List canonical remote followups for a tenant with durable control-plane filters") public ResponseEntity>> listRemoteFollowups( @PathVariable String tenantId, @ModelAttribute RemoteFollowupListRequest request) { - return LoggingAdminRequestReaders.withBadRequest( - () -> { - long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); - return ResponseEntity.ok( - ApiResponse.success( - remoteFollowupService.listRemoteFollowups(parsedTenantId, request))); - }); + return LoggingAdminRequestReaders.withBadRequest(() -> { + long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); + return ResponseEntity.ok( + ApiResponse.success(remoteFollowupService.listRemoteFollowups(parsedTenantId, request))); + }); } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupResultController.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupResultController.java index 84749e6178..9b44b55cbb 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupResultController.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupResultController.java @@ -27,13 +27,12 @@ public RemoteFollowupResultController(RemoteFollowupResultService remoteFollowup description = "Read canonical remote followup result by tenant-qualified result id") public ResponseEntity> getRemoteFollowupResult( @PathVariable String tenantId, @PathVariable String resultId) { - return LoggingAdminRequestReaders.withBadRequest( - () -> { - long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); - return ResponseEntity.ok( - ApiResponse.success( - remoteFollowupResultService.getRemoteFollowupResult(parsedTenantId, resultId))); - }); + return LoggingAdminRequestReaders.withBadRequest(() -> { + long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); + return ResponseEntity.ok( + ApiResponse.success( + remoteFollowupResultService.getRemoteFollowupResult(parsedTenantId, resultId))); + }); } @GetMapping("/{tenantId}") @@ -44,12 +43,11 @@ public ResponseEntity> getRemoteFollowupRes public ResponseEntity>> listRemoteFollowupResults( @PathVariable String tenantId, @ModelAttribute RemoteFollowupResultListRequest request) { - return LoggingAdminRequestReaders.withBadRequest( - () -> { - long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); - return ResponseEntity.ok( - ApiResponse.success( - remoteFollowupResultService.listRemoteFollowupResults(parsedTenantId, request))); - }); + return LoggingAdminRequestReaders.withBadRequest(() -> { + long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); + return ResponseEntity.ok( + ApiResponse.success( + remoteFollowupResultService.listRemoteFollowupResults(parsedTenantId, request))); + }); } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/SagaDashboardController.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/SagaDashboardController.java index d3daae19de..40a5205e6b 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/SagaDashboardController.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/SagaDashboardController.java @@ -50,11 +50,10 @@ public ResponseEntity>> listSteps(@PathVariable St ApiResponse.error( new ErrorDetail("SAGA_DASHBOARD_UNAVAILABLE", "Saga dashboard is unavailable"))); } - return LoggingAdminRequestReaders.withBadRequest( - () -> - ResponseEntity.ok( - ApiResponse.success( - sagaDashboardService.listSteps( - LoggingAdminRequestReaders.requirePositiveLong(id, "id"))))); + return LoggingAdminRequestReaders.withBadRequest(() -> + ResponseEntity.ok( + ApiResponse.success( + sagaDashboardService.listSteps( + LoggingAdminRequestReaders.requirePositiveLong(id, "id"))))); } } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/TickRemediationController.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/TickRemediationController.java index 1f8e4889d0..7c079fe81a 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/TickRemediationController.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/controller/TickRemediationController.java @@ -40,39 +40,36 @@ public ResponseEntity> getRuntimeOwnershi @PathVariable String tenantId, @RequestParam(required = false) String gameInstanceId, @RequestParam(required = false) String regionId) { - return LoggingAdminRequestReaders.withBadRequest( - () -> { - long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); - String normalizedGameInstanceId = - LoggingAdminRequestReaders.requireOptionalPositiveLongText( - gameInstanceId, "gameInstanceId"); - return ResponseEntity.ok( - ApiResponse.success( - tickRemediationService.getRuntimeOwnershipStatus( - parsedTenantId, normalizedGameInstanceId, regionId))); - }); + return LoggingAdminRequestReaders.withBadRequest(() -> { + long parsedTenantId = LoggingAdminRequestReaders.requireTenantAccess(tenantId); + String normalizedGameInstanceId = + LoggingAdminRequestReaders.requireOptionalPositiveLongText( + gameInstanceId, "gameInstanceId"); + return ResponseEntity.ok( + ApiResponse.success( + tickRemediationService.getRuntimeOwnershipStatus( + parsedTenantId, normalizedGameInstanceId, regionId))); + }); } @PostMapping("/pause") @Timed(value = "tickRemediationPause", description = "Pause ticks for a scoped runtime target") public ResponseEntity> pause( @Valid @RequestBody TickRemediationRequest request) { - return LoggingAdminRequestReaders.withBadRequest( - () -> { - validateAuthorizedTenantRequest(request, request.tenantId()); - return unavailableResponse(); - }); + return LoggingAdminRequestReaders.withBadRequest(() -> { + validateAuthorizedTenantRequest(request, request.tenantId()); + return unavailableResponse(); + }); } @PostMapping("/resume") @Timed(value = "tickRemediationResume", description = "Resume ticks for a scoped runtime target") public ResponseEntity> resume( @Valid @RequestBody TickRemediationRequest request) { - return LoggingAdminRequestReaders.withBadRequest( - () -> { - validateAuthorizedTenantRequest(request, request.tenantId()); - return unavailableResponse(); - }); + return LoggingAdminRequestReaders.withBadRequest(() -> { + validateAuthorizedTenantRequest(request, request.tenantId()); + return unavailableResponse(); + }); } private ResponseEntity> unavailableResponse() { diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java index a72aee9a6c..3c08af165a 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationService.java @@ -234,18 +234,17 @@ public Optional acquireAuthorizationRecoveryClaim( Optional acquired = repository.acquireRecoveryClaim( tuple, recoveryOwnerId, epochMillis(now), epochMillis(now.plus(CLAIM_TTL))); - return acquired.map( - result -> - new RecoveryAcquisition( - result.snapshot(), - new ClaimHandle( - tuple, - tuple.mutationDigest(), - result.reservationOwnerId(), - recoveryOwnerId, - result.snapshot().reservationClaimFence(), - result.snapshot().claimFence(), - result.snapshot().claimPurpose()))); + return acquired.map(result -> + new RecoveryAcquisition( + result.snapshot(), + new ClaimHandle( + tuple, + tuple.mutationDigest(), + result.reservationOwnerId(), + recoveryOwnerId, + result.snapshot().reservationClaimFence(), + result.snapshot().claimFence(), + result.snapshot().claimPurpose()))); } /** diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java index 229b42fbf7..22c0fc3678 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/AccountAuditReceiptRepository.java @@ -55,10 +55,9 @@ public AccountAuditReceiptInsertResult insertIfAbsent( .execute(); AccountAuditReceipt receipt = findByIdentity(request, tenantKey) - .orElseThrow( - () -> - new IllegalStateException( - "Account audit receipt identity conflict did not resolve to a receipt")); + .orElseThrow(() -> + new IllegalStateException( + "Account audit receipt identity conflict did not resolve to a receipt")); return new AccountAuditReceiptInsertResult(receipt, inserted == 1); } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java index 458ec5c22d..c73e164238 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java @@ -82,36 +82,35 @@ public AcquireResult acquire( } String tupleJson = tuple.canonicalJson(); String mutationDigest = tuple.mutationDigest(); - return dsl.transactionResult( - configuration -> { - DSLContext tx = DSL.using(configuration); - int inserted = - tx.insertInto(TABLE) - .set(TABLE.CONTROL_PLANE_REQUEST_ID, tuple.controlPlaneRequestId()) - .set(TABLE.PRE_AUTHORIZATION_TUPLE_JSON, tupleJson) - .set(TABLE.MUTATION_DIGEST, mutationDigest) - .set(TABLE.PHASE, Phase.ACCOUNT_AUTHORIZATION.name()) - .set(TABLE.STATE, State.RESERVED.name()) - .set(TABLE.RESERVATION_OWNER_ID, ownerId) - .set(TABLE.RESERVATION_CLAIM_FENCE, 1L) - .set(TABLE.CLAIM_OWNER_ID, ownerId) - .set(TABLE.CLAIM_FENCE, 1L) - .set(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, expiresAtEpochMillis) - .set(TABLE.CLAIM_STATE, ClaimState.ACTIVE.name()) - .set(CLAIM_PURPOSE, ClaimPurpose.ORIGINAL.name()) - .set(TABLE.CREATED_AT_EPOCH_MS, nowEpochMillis) - .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) - .onConflict(TABLE.CONTROL_PLANE_REQUEST_ID) - .doNothing() - .execute(); - Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); - if (row == null) { - throw new IllegalStateException("reservation row was not visible after acquire"); - } - Snapshot snapshot = toSnapshot(row); - requireExactTuple(row, tuple, mutationDigest); - return new AcquireResult(snapshot, inserted == 1); - }); + return dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + int inserted = + tx.insertInto(TABLE) + .set(TABLE.CONTROL_PLANE_REQUEST_ID, tuple.controlPlaneRequestId()) + .set(TABLE.PRE_AUTHORIZATION_TUPLE_JSON, tupleJson) + .set(TABLE.MUTATION_DIGEST, mutationDigest) + .set(TABLE.PHASE, Phase.ACCOUNT_AUTHORIZATION.name()) + .set(TABLE.STATE, State.RESERVED.name()) + .set(TABLE.RESERVATION_OWNER_ID, ownerId) + .set(TABLE.RESERVATION_CLAIM_FENCE, 1L) + .set(TABLE.CLAIM_OWNER_ID, ownerId) + .set(TABLE.CLAIM_FENCE, 1L) + .set(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, expiresAtEpochMillis) + .set(TABLE.CLAIM_STATE, ClaimState.ACTIVE.name()) + .set(CLAIM_PURPOSE, ClaimPurpose.ORIGINAL.name()) + .set(TABLE.CREATED_AT_EPOCH_MS, nowEpochMillis) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .onConflict(TABLE.CONTROL_PLANE_REQUEST_ID) + .doNothing() + .execute(); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw new IllegalStateException("reservation row was not visible after acquire"); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + return new AcquireResult(snapshot, inserted == 1); + }); } public Optional find(String controlPlaneRequestId) { @@ -123,15 +122,14 @@ public Optional find(String controlPlaneRequestId) { public Optional findExact(StartSessionPreAuthorizationReservationTuple tuple) { return find(tuple.controlPlaneRequestId()) - .map( - snapshot -> { - if (!snapshot.tuple().canonicalJson().equals(tuple.canonicalJson()) - || !snapshot.mutationDigest().equals(tuple.mutationDigest())) { - throw new StartSessionPreAuthorizationReservationService - .IdempotencyConflictException(tuple.controlPlaneRequestId()); - } - return snapshot; - }); + .map(snapshot -> { + if (!snapshot.tuple().canonicalJson().equals(tuple.canonicalJson()) + || !snapshot.mutationDigest().equals(tuple.mutationDigest())) { + throw new StartSessionPreAuthorizationReservationService.IdempotencyConflictException( + tuple.controlPlaneRequestId()); + } + return snapshot; + }); } /** Reads an exact, current Account-authorization claim without locking or changing the row. */ @@ -198,48 +196,46 @@ public TransitionResult markAuthorizationPending( currentClaimOwnerId, currentClaimFence, nowEpochMillis); - return dsl.transactionResult( - configuration -> { - DSLContext tx = DSL.using(configuration); - int updated = - tx.update(TABLE) - .set(TABLE.STATE, State.AUTHORIZATION_PENDING.name()) - .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) - .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) - .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) - .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) - .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) - .and(TABLE.STATE.eq(State.RESERVED.name())) - .and(TABLE.RESERVATION_OWNER_ID.eq(reservationOwnerId)) - .and(TABLE.RESERVATION_CLAIM_FENCE.eq(reservationClaimFence)) - .and(TABLE.CLAIM_OWNER_ID.eq(currentClaimOwnerId)) - .and(TABLE.CLAIM_FENCE.eq(currentClaimFence)) - .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) - .and( - CLAIM_PURPOSE.in( - ClaimPurpose.ORIGINAL.name(), - ClaimPurpose.RESERVED_RECOVERY_ISSUE.name())) - .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) - .execute(); - Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); - if (row == null) { - throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( - tuple.controlPlaneRequestId()); - } - Snapshot snapshot = toSnapshot(row); - requireExactTuple(row, tuple, mutationDigest); - if (updated == 1) { - return new TransitionResult(snapshot, true); - } - if (isCurrentClaim(row, currentClaimOwnerId, currentClaimFence, nowEpochMillis) - && snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION - && snapshot.state() == State.AUTHORIZATION_PENDING - && isIssueClaimPurpose(snapshot.claimPurpose())) { - return new TransitionResult(snapshot, false); - } - throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( - tuple.controlPlaneRequestId()); - }); + return dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + int updated = + tx.update(TABLE) + .set(TABLE.STATE, State.AUTHORIZATION_PENDING.name()) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) + .and(TABLE.STATE.eq(State.RESERVED.name())) + .and(TABLE.RESERVATION_OWNER_ID.eq(reservationOwnerId)) + .and(TABLE.RESERVATION_CLAIM_FENCE.eq(reservationClaimFence)) + .and(TABLE.CLAIM_OWNER_ID.eq(currentClaimOwnerId)) + .and(TABLE.CLAIM_FENCE.eq(currentClaimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and( + CLAIM_PURPOSE.in( + ClaimPurpose.ORIGINAL.name(), ClaimPurpose.RESERVED_RECOVERY_ISSUE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) + .execute(); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + if (updated == 1) { + return new TransitionResult(snapshot, true); + } + if (isCurrentClaim(row, currentClaimOwnerId, currentClaimFence, nowEpochMillis) + && snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.state() == State.AUTHORIZATION_PENDING + && isIssueClaimPurpose(snapshot.claimPurpose())) { + return new TransitionResult(snapshot, false); + } + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + }); } /** Original-claim overload retained for focused repository tests and original callers. */ @@ -287,73 +283,70 @@ public AuthorizationTransitionResult completeAuthorization( tuple.controlPlaneRequestId()); } - return dsl.transactionResult( - configuration -> { - DSLContext tx = DSL.using(configuration); - Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); - if (row == null) { - throw stale(tuple); - } - Snapshot snapshot = toSnapshot(row); - requireExactTuple(row, tuple, mutationDigest); - requireExactLiveClaim( - row, - snapshot, - reservationOwnerId, - reservationClaimFence, - currentClaimOwnerId, - currentClaimFence, - nowEpochMillis); - - if (snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION - && snapshot.state() == State.AUTHORIZATION_PENDING) { - if (!isPendingAuthorizationClaimPurpose(snapshot.claimPurpose())) { - throw stale(tuple); - } - int updated = - tx.update(TABLE) - .set(TABLE.STATE, State.AUTHORIZED.name()) - .set(POST_AUTHORIZATION_TUPLE_JSON, postAuthorizationTupleJson) - .set(OWNER_EXECUTION_HANDOFF_ID, (UUID) null) - .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) - .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) - .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) - .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) - .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) - .and(TABLE.STATE.eq(State.AUTHORIZATION_PENDING.name())) - .and(TABLE.RESERVATION_OWNER_ID.eq(reservationOwnerId)) - .and(TABLE.RESERVATION_CLAIM_FENCE.eq(reservationClaimFence)) - .and(TABLE.CLAIM_OWNER_ID.eq(currentClaimOwnerId)) - .and(TABLE.CLAIM_FENCE.eq(currentClaimFence)) - .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) - .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) - .and(POST_AUTHORIZATION_TUPLE_JSON.isNull()) - .execute(); - if (updated != 1) { - throw stale(tuple); - } - return new AuthorizationTransitionResult( - toAuthorizedSnapshot( - selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true)), - true); - } + return dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw stale(tuple); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + requireExactLiveClaim( + row, + snapshot, + reservationOwnerId, + reservationClaimFence, + currentClaimOwnerId, + currentClaimFence, + nowEpochMillis); + + if (snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && snapshot.state() == State.AUTHORIZATION_PENDING) { + if (!isPendingAuthorizationClaimPurpose(snapshot.claimPurpose())) { + throw stale(tuple); + } + int updated = + tx.update(TABLE) + .set(TABLE.STATE, State.AUTHORIZED.name()) + .set(POST_AUTHORIZATION_TUPLE_JSON, postAuthorizationTupleJson) + .set(OWNER_EXECUTION_HANDOFF_ID, (UUID) null) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) + .and(TABLE.STATE.eq(State.AUTHORIZATION_PENDING.name())) + .and(TABLE.RESERVATION_OWNER_ID.eq(reservationOwnerId)) + .and(TABLE.RESERVATION_CLAIM_FENCE.eq(reservationClaimFence)) + .and(TABLE.CLAIM_OWNER_ID.eq(currentClaimOwnerId)) + .and(TABLE.CLAIM_FENCE.eq(currentClaimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) + .and(POST_AUTHORIZATION_TUPLE_JSON.isNull()) + .execute(); + if (updated != 1) { + throw stale(tuple); + } + return new AuthorizationTransitionResult( + toAuthorizedSnapshot(selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true)), + true); + } - if ((snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION - && snapshot.state() == State.AUTHORIZED) - || (snapshot.phase() == Phase.OWNER_EXECUTION - && snapshot.state() == State.OWNER_EXECUTION_PENDING)) { - if (snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION - && !isAuthorizedResponseClaimPurpose(snapshot.claimPurpose())) { - throw stale(tuple); - } - String persistedTuple = row.get(POST_AUTHORIZATION_TUPLE_JSON); - if (!postAuthorizationTupleJson.equals(persistedTuple)) { - throw conflict(tuple); - } - return new AuthorizationTransitionResult(toAuthorizedSnapshot(row), false); - } + if ((snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION && snapshot.state() == State.AUTHORIZED) + || (snapshot.phase() == Phase.OWNER_EXECUTION + && snapshot.state() == State.OWNER_EXECUTION_PENDING)) { + if (snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION + && !isAuthorizedResponseClaimPurpose(snapshot.claimPurpose())) { throw stale(tuple); - }); + } + String persistedTuple = row.get(POST_AUTHORIZATION_TUPLE_JSON); + if (!postAuthorizationTupleJson.equals(persistedTuple)) { + throw conflict(tuple); + } + return new AuthorizationTransitionResult(toAuthorizedSnapshot(row), false); + } + throw stale(tuple); + }); } /** @@ -391,78 +384,75 @@ public OwnerExecutionTransitionResult beginOwnerExecution( tuple.controlPlaneRequestId()); } - return dsl.transactionResult( - configuration -> { - DSLContext tx = DSL.using(configuration); - Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); - if (row == null) { - throw stale(tuple); - } - Snapshot snapshot = toSnapshot(row); - requireExactTuple(row, tuple, mutationDigest); - requireExactLiveClaim( - row, - snapshot, - reservationOwnerId, - reservationClaimFence, - currentClaimOwnerId, - currentClaimFence, - nowEpochMillis); - boolean mayBeginOwnerExecution = - snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION - && snapshot.state() == State.AUTHORIZED; - boolean mayReplayOwnerExecution = - snapshot.phase() == Phase.OWNER_EXECUTION - && snapshot.state() == State.OWNER_EXECUTION_PENDING; - if (!mayBeginOwnerExecution && !mayReplayOwnerExecution) { - throw stale(tuple); - } - if (mayBeginOwnerExecution && !isOwnerHandoffClaimPurpose(snapshot.claimPurpose())) { - throw stale(tuple); - } - String persistedTuple = row.get(POST_AUTHORIZATION_TUPLE_JSON); - if (!postAuthorizationTupleJson.equals(persistedTuple)) { - throw conflict(tuple); - } - - if (mayBeginOwnerExecution) { - int updated = - tx.update(TABLE) - .set(TABLE.PHASE, Phase.OWNER_EXECUTION.name()) - .set(TABLE.STATE, State.OWNER_EXECUTION_PENDING.name()) - .set(OWNER_EXECUTION_HANDOFF_ID, handoffId) - .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) - .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) - .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) - .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) - .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) - .and(TABLE.STATE.eq(State.AUTHORIZED.name())) - .and(TABLE.RESERVATION_OWNER_ID.eq(reservationOwnerId)) - .and(TABLE.RESERVATION_CLAIM_FENCE.eq(reservationClaimFence)) - .and(TABLE.CLAIM_OWNER_ID.eq(currentClaimOwnerId)) - .and(TABLE.CLAIM_FENCE.eq(currentClaimFence)) - .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) - .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) - .and(POST_AUTHORIZATION_TUPLE_JSON.eq(postAuthorizationTupleJson)) - .and(OWNER_EXECUTION_HANDOFF_ID.isNull()) - .execute(); - if (updated != 1) { - throw stale(tuple); - } - return new OwnerExecutionTransitionResult( - toAuthorizedSnapshot( - selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true)), - true); - } + return dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw stale(tuple); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + requireExactLiveClaim( + row, + snapshot, + reservationOwnerId, + reservationClaimFence, + currentClaimOwnerId, + currentClaimFence, + nowEpochMillis); + boolean mayBeginOwnerExecution = + snapshot.phase() == Phase.ACCOUNT_AUTHORIZATION && snapshot.state() == State.AUTHORIZED; + boolean mayReplayOwnerExecution = + snapshot.phase() == Phase.OWNER_EXECUTION + && snapshot.state() == State.OWNER_EXECUTION_PENDING; + if (!mayBeginOwnerExecution && !mayReplayOwnerExecution) { + throw stale(tuple); + } + if (mayBeginOwnerExecution && !isOwnerHandoffClaimPurpose(snapshot.claimPurpose())) { + throw stale(tuple); + } + String persistedTuple = row.get(POST_AUTHORIZATION_TUPLE_JSON); + if (!postAuthorizationTupleJson.equals(persistedTuple)) { + throw conflict(tuple); + } - if (mayReplayOwnerExecution) { - if (!handoffId.equals(row.get(OWNER_EXECUTION_HANDOFF_ID))) { - throw conflict(tuple); - } - return new OwnerExecutionTransitionResult(toAuthorizedSnapshot(row), false); - } + if (mayBeginOwnerExecution) { + int updated = + tx.update(TABLE) + .set(TABLE.PHASE, Phase.OWNER_EXECUTION.name()) + .set(TABLE.STATE, State.OWNER_EXECUTION_PENDING.name()) + .set(OWNER_EXECUTION_HANDOFF_ID, handoffId) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) + .and(TABLE.STATE.eq(State.AUTHORIZED.name())) + .and(TABLE.RESERVATION_OWNER_ID.eq(reservationOwnerId)) + .and(TABLE.RESERVATION_CLAIM_FENCE.eq(reservationClaimFence)) + .and(TABLE.CLAIM_OWNER_ID.eq(currentClaimOwnerId)) + .and(TABLE.CLAIM_FENCE.eq(currentClaimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) + .and(POST_AUTHORIZATION_TUPLE_JSON.eq(postAuthorizationTupleJson)) + .and(OWNER_EXECUTION_HANDOFF_ID.isNull()) + .execute(); + if (updated != 1) { throw stale(tuple); - }); + } + return new OwnerExecutionTransitionResult( + toAuthorizedSnapshot(selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true)), + true); + } + + if (mayReplayOwnerExecution) { + if (!handoffId.equals(row.get(OWNER_EXECUTION_HANDOFF_ID))) { + throw conflict(tuple); + } + return new OwnerExecutionTransitionResult(toAuthorizedSnapshot(row), false); + } + throw stale(tuple); + }); } /** Read-only storage snapshot of the exact full post-authorization tuple and any handoff. */ @@ -495,36 +485,35 @@ public Snapshot renew( Objects.requireNonNull(expectedPhase, "expectedPhase is required"); Objects.requireNonNull(expectedState, "expectedState is required"); requireBoundedClaim(ownerId, nowEpochMillis, expiresAtEpochMillis); - return dsl.transactionResult( - configuration -> { - DSLContext tx = DSL.using(configuration); - int updated = - tx.update(TABLE) - .set(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, expiresAtEpochMillis) - .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) - .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) - .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) - .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) - .and(TABLE.PHASE.eq(expectedPhase.name())) - .and(TABLE.STATE.eq(expectedState.name())) - .and(TABLE.CLAIM_OWNER_ID.eq(ownerId)) - .and(TABLE.CLAIM_FENCE.eq(claimFence)) - .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) - .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) - .execute(); - Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); - if (row == null) { - throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( - tuple.controlPlaneRequestId()); - } - Snapshot snapshot = toSnapshot(row); - requireExactTuple(row, tuple, mutationDigest); - if (updated != 1) { - throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( - tuple.controlPlaneRequestId()); - } - return snapshot; - }); + return dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + int updated = + tx.update(TABLE) + .set(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, expiresAtEpochMillis) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(expectedPhase.name())) + .and(TABLE.STATE.eq(expectedState.name())) + .and(TABLE.CLAIM_OWNER_ID.eq(ownerId)) + .and(TABLE.CLAIM_FENCE.eq(claimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.gt(nowEpochMillis)) + .execute(); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + if (updated != 1) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + return snapshot; + }); } public Snapshot expireClaim( @@ -539,43 +528,42 @@ public Snapshot expireClaim( requireClaimOwner(ownerId, claimFence, nowEpochMillis); Objects.requireNonNull(expectedPhase, "expectedPhase is required"); Objects.requireNonNull(expectedState, "expectedState is required"); - return dsl.transactionResult( - configuration -> { - DSLContext tx = DSL.using(configuration); - int updated = - tx.update(TABLE) - .setNull(TABLE.CLAIM_OWNER_ID) - .set(TABLE.CLAIM_FENCE, TABLE.CLAIM_FENCE.add(1L)) - .set(TABLE.CLAIM_STATE, ClaimState.EXPIRED.name()) - .set(CLAIM_PURPOSE, (String) null) - .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) - .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) - .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) - .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) - .and(TABLE.PHASE.eq(expectedPhase.name())) - .and(TABLE.STATE.eq(expectedState.name())) - .and(TABLE.CLAIM_OWNER_ID.eq(ownerId)) - .and(TABLE.CLAIM_FENCE.eq(claimFence)) - .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) - .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.le(nowEpochMillis)) - .execute(); - Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); - if (row == null) { - throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( - tuple.controlPlaneRequestId()); - } - Snapshot snapshot = toSnapshot(row); - requireExactTuple(row, tuple, mutationDigest); - if (updated == 1) { - return snapshot; - } - if (isCurrentClaim(row, ownerId, claimFence, nowEpochMillis)) { - throw new StartSessionPreAuthorizationReservationService - .ReservationClaimNotExpiredException(tuple.controlPlaneRequestId()); - } - throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( - tuple.controlPlaneRequestId()); - }); + return dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + int updated = + tx.update(TABLE) + .setNull(TABLE.CLAIM_OWNER_ID) + .set(TABLE.CLAIM_FENCE, TABLE.CLAIM_FENCE.add(1L)) + .set(TABLE.CLAIM_STATE, ClaimState.EXPIRED.name()) + .set(CLAIM_PURPOSE, (String) null) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(expectedPhase.name())) + .and(TABLE.STATE.eq(expectedState.name())) + .and(TABLE.CLAIM_OWNER_ID.eq(ownerId)) + .and(TABLE.CLAIM_FENCE.eq(claimFence)) + .and(TABLE.CLAIM_STATE.eq(ClaimState.ACTIVE.name())) + .and(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.le(nowEpochMillis)) + .execute(); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + if (updated == 1) { + return snapshot; + } + if (isCurrentClaim(row, ownerId, claimFence, nowEpochMillis)) { + throw new StartSessionPreAuthorizationReservationService + .ReservationClaimNotExpiredException(tuple.controlPlaneRequestId()); + } + throw new StartSessionPreAuthorizationReservationService.StaleReservationClaimException( + tuple.controlPlaneRequestId()); + }); } public Optional acquireRecoveryClaim( @@ -586,74 +574,72 @@ public Optional acquireRecoveryClaim( requireMutationCapability(); requireBoundedClaim(recoveryOwnerId, nowEpochMillis, expiresAtEpochMillis); String mutationDigest = tuple.mutationDigest(); - return dsl.transactionResult( - configuration -> { - DSLContext tx = DSL.using(configuration); - Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); - if (row == null) { - return Optional.empty(); - } - Snapshot snapshot = toSnapshot(row); - requireExactTuple(row, tuple, mutationDigest); - ClaimPurpose recoveryPurpose = recoveryPurpose(snapshot.phase(), snapshot.state()); - if (recoveryPurpose == null) { - return Optional.empty(); - } - UUID reservationOwnerId = row.get(TABLE.RESERVATION_OWNER_ID); - UUID previousOwnerId = row.get(TABLE.CLAIM_OWNER_ID); - String previousClaimState = row.get(TABLE.CLAIM_STATE); - long previousFence = row.get(TABLE.CLAIM_FENCE); - long previousExpiry = row.get(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS); - if (!ClaimState.EXPIRED.name().equals(previousClaimState) - && !(ClaimState.ACTIVE.name().equals(previousClaimState) - && previousExpiry <= nowEpochMillis)) { - return Optional.empty(); - } - if (reservationOwnerId.equals(recoveryOwnerId) - || recoveryOwnerId.equals(previousOwnerId)) { - return Optional.empty(); - } - if (snapshot.state() == State.AUTHORIZED) { - toAuthorizedSnapshot(row); - } - long recoveryFence = Math.addExact(previousFence, 1L); - int updated = - tx.update(TABLE) - .set(TABLE.CLAIM_OWNER_ID, recoveryOwnerId) - .set(TABLE.CLAIM_FENCE, recoveryFence) - .set(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, expiresAtEpochMillis) - .set(TABLE.CLAIM_STATE, ClaimState.ACTIVE.name()) - .set(CLAIM_PURPOSE, recoveryPurpose.name()) - .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) - .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) - .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) - .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) - .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) - .and(TABLE.STATE.eq(snapshot.state().name())) - .and(TABLE.CLAIM_FENCE.eq(previousFence)) - .and(TABLE.CLAIM_STATE.eq(previousClaimState)) - .and( - previousOwnerId == null - ? TABLE.CLAIM_OWNER_ID.isNull() - : TABLE.CLAIM_OWNER_ID.eq(previousOwnerId)) - .and( - snapshot.claimPurpose() == null - ? CLAIM_PURPOSE.isNull() - : CLAIM_PURPOSE.eq(snapshot.claimPurpose().name())) - .and( - ClaimState.EXPIRED.name().equals(previousClaimState) - ? DSL.trueCondition() - : TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.le(nowEpochMillis)) - .execute(); - if (updated != 1) { - return Optional.empty(); - } - Record updatedRow = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); - if (updatedRow == null) { - throw new IllegalStateException("recovery claim row disappeared after update"); - } - return Optional.of(new RecoveryClaimResult(toSnapshot(updatedRow), reservationOwnerId)); - }); + return dsl.transactionResult(configuration -> { + DSLContext tx = DSL.using(configuration); + Record row = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (row == null) { + return Optional.empty(); + } + Snapshot snapshot = toSnapshot(row); + requireExactTuple(row, tuple, mutationDigest); + ClaimPurpose recoveryPurpose = recoveryPurpose(snapshot.phase(), snapshot.state()); + if (recoveryPurpose == null) { + return Optional.empty(); + } + UUID reservationOwnerId = row.get(TABLE.RESERVATION_OWNER_ID); + UUID previousOwnerId = row.get(TABLE.CLAIM_OWNER_ID); + String previousClaimState = row.get(TABLE.CLAIM_STATE); + long previousFence = row.get(TABLE.CLAIM_FENCE); + long previousExpiry = row.get(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS); + if (!ClaimState.EXPIRED.name().equals(previousClaimState) + && !(ClaimState.ACTIVE.name().equals(previousClaimState) + && previousExpiry <= nowEpochMillis)) { + return Optional.empty(); + } + if (reservationOwnerId.equals(recoveryOwnerId) || recoveryOwnerId.equals(previousOwnerId)) { + return Optional.empty(); + } + if (snapshot.state() == State.AUTHORIZED) { + toAuthorizedSnapshot(row); + } + long recoveryFence = Math.addExact(previousFence, 1L); + int updated = + tx.update(TABLE) + .set(TABLE.CLAIM_OWNER_ID, recoveryOwnerId) + .set(TABLE.CLAIM_FENCE, recoveryFence) + .set(TABLE.CLAIM_EXPIRES_AT_EPOCH_MS, expiresAtEpochMillis) + .set(TABLE.CLAIM_STATE, ClaimState.ACTIVE.name()) + .set(CLAIM_PURPOSE, recoveryPurpose.name()) + .set(TABLE.UPDATED_AT_EPOCH_MS, nowEpochMillis) + .where(TABLE.CONTROL_PLANE_REQUEST_ID.eq(tuple.controlPlaneRequestId())) + .and(TABLE.PRE_AUTHORIZATION_TUPLE_JSON.eq(tuple.canonicalJson())) + .and(TABLE.MUTATION_DIGEST.eq(mutationDigest)) + .and(TABLE.PHASE.eq(Phase.ACCOUNT_AUTHORIZATION.name())) + .and(TABLE.STATE.eq(snapshot.state().name())) + .and(TABLE.CLAIM_FENCE.eq(previousFence)) + .and(TABLE.CLAIM_STATE.eq(previousClaimState)) + .and( + previousOwnerId == null + ? TABLE.CLAIM_OWNER_ID.isNull() + : TABLE.CLAIM_OWNER_ID.eq(previousOwnerId)) + .and( + snapshot.claimPurpose() == null + ? CLAIM_PURPOSE.isNull() + : CLAIM_PURPOSE.eq(snapshot.claimPurpose().name())) + .and( + ClaimState.EXPIRED.name().equals(previousClaimState) + ? DSL.trueCondition() + : TABLE.CLAIM_EXPIRES_AT_EPOCH_MS.le(nowEpochMillis)) + .execute(); + if (updated != 1) { + return Optional.empty(); + } + Record updatedRow = selectFullRowByRequestId(tx, tuple.controlPlaneRequestId(), true); + if (updatedRow == null) { + throw new IllegalStateException("recovery claim row disappeared after update"); + } + return Optional.of(new RecoveryClaimResult(toSnapshot(updatedRow), reservationOwnerId)); + }); } private StartSessionPostAuthorizationExecutionTuple decodePostAuthorizationTuple(String json) { diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java index 0816ee7720..5d638f4184 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java @@ -215,15 +215,14 @@ public InstanceCutoverCompatibilityDto validateInstanceCutoverCompatibility( response.getCheckedAtMs() <= 0 ? null : Instant.ofEpochMilli(response.getCheckedAtMs()), response.getRemapSetId().isBlank() ? null : response.getRemapSetId(), response.getParticipantResultsList().stream() - .map( - participant -> - new InstanceCutoverCompatibilityDto.CutoverParticipantResultDto( - participant.getParticipant(), - toCutoverResultName(participant.getResult().name()), - participant.getReasonsList(), - participant.getStateClassesCheckedList(), - participant.getCheckedFamiliesList(), - participant.getHasS2Rows())) + .map(participant -> + new InstanceCutoverCompatibilityDto.CutoverParticipantResultDto( + participant.getParticipant(), + toCutoverResultName(participant.getResult().name()), + participant.getReasonsList(), + participant.getStateClassesCheckedList(), + participant.getCheckedFamiliesList(), + participant.getHasS2Rows())) .toList()); } @@ -321,15 +320,14 @@ private PreparedVersionUpgradeDto toDto(PreparedVersionUpgrade preparation) { ? null : Instant.ofEpochMilli(preparation.getCheckedAtMs()), preparation.getParticipantResultsList().stream() - .map( - participant -> - new PreparedVersionUpgradeDto.CutoverParticipantResultDto( - participant.getParticipant(), - toCutoverResultName(participant.getResult().name()), - participant.getReasonsList(), - participant.getStateClassesCheckedList(), - participant.getCheckedFamiliesList(), - participant.getHasS2Rows())) + .map(participant -> + new PreparedVersionUpgradeDto.CutoverParticipantResultDto( + participant.getParticipant(), + toCutoverResultName(participant.getResult().name()), + participant.getReasonsList(), + participant.getStateClassesCheckedList(), + participant.getCheckedFamiliesList(), + participant.getHasS2Rows())) .toList(), preparation.getControlPlaneRequestId(), preparation.getExecutedTargetGameInstanceId().isBlank() diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImpl.java index 255b2acc4e..b459d8c79e 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/ModerationServiceImpl.java @@ -67,10 +67,9 @@ public ModerationPolicyDecisionDto evaluatePolicy(long tenantId, UUID accountId, .findActivePolicyActions(tenantId, accountId, blockingActions, Instant.now()) .stream() .findFirst() - .map( - action -> - new ModerationPolicyDecisionDto( - false, action.getAction(), action.getReason(), action.getExpiresAt())) + .map(action -> + new ModerationPolicyDecisionDto( + false, action.getAction(), action.getReason(), action.getExpiresAt())) .orElseGet(() -> new ModerationPolicyDecisionDto(true, "", "", null)); } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/RemoteCommandCoordinatorServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/RemoteCommandCoordinatorServiceImpl.java index b7f81eab21..72af4be6a0 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/RemoteCommandCoordinatorServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/RemoteCommandCoordinatorServiceImpl.java @@ -66,16 +66,15 @@ public List listRemoteCommandCoordinators( gameSessionControlPlaneClient.listRemoteCommandCoordinators(toRequest(tenantId, request)); requireNoError(response.getError()); return response.getCoordinatorsList().stream() - .map( - coordinator -> { - long responseTenantId = parseLong(coordinator.getTenantId(), "tenant_id"); - if (responseTenantId != tenantId) { - throw new ResponseStatusException( - HttpStatus.INTERNAL_SERVER_ERROR, - "control-plane remote command coordinator list response did not match requested tenant_id"); - } - return toDto(coordinator); - }) + .map(coordinator -> { + long responseTenantId = parseLong(coordinator.getTenantId(), "tenant_id"); + if (responseTenantId != tenantId) { + throw new ResponseStatusException( + HttpStatus.INTERNAL_SERVER_ERROR, + "control-plane remote command coordinator list response did not match requested tenant_id"); + } + return toDto(coordinator); + }) .toList(); } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/RemoteFollowupResultServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/RemoteFollowupResultServiceImpl.java index 429c4ebb6b..980f2373c6 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/RemoteFollowupResultServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/RemoteFollowupResultServiceImpl.java @@ -65,16 +65,15 @@ public List listRemoteFollowupResults( gameSessionControlPlaneClient.listRemoteFollowupResults(toRequest(tenantId, request)); requireNoError(response.getError()); return response.getResultsList().stream() - .map( - result -> { - long responseTenantId = parseLong(result.getTenantId(), "tenant_id"); - if (responseTenantId != tenantId) { - throw new ResponseStatusException( - HttpStatus.INTERNAL_SERVER_ERROR, - "control-plane remote followup result list response did not match requested tenant_id"); - } - return toDto(result); - }) + .map(result -> { + long responseTenantId = parseLong(result.getTenantId(), "tenant_id"); + if (responseTenantId != tenantId) { + throw new ResponseStatusException( + HttpStatus.INTERNAL_SERVER_ERROR, + "control-plane remote followup result list response did not match requested tenant_id"); + } + return toDto(result); + }) .toList(); } diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/RemoteFollowupServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/RemoteFollowupServiceImpl.java index 8fc8395307..c313712dec 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/RemoteFollowupServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/RemoteFollowupServiceImpl.java @@ -64,16 +64,15 @@ public List listRemoteFollowups( gameSessionControlPlaneClient.listRemoteFollowups(toRequest(tenantId, request)); requireNoError(response.getError()); return response.getFollowupsList().stream() - .map( - followup -> { - long responseTenantId = parseLong(followup.getTenantId(), "tenant_id"); - if (responseTenantId != tenantId) { - throw new ResponseStatusException( - HttpStatus.INTERNAL_SERVER_ERROR, - "control-plane remote followup list response did not match requested tenant_id"); - } - return toDto(followup); - }) + .map(followup -> { + long responseTenantId = parseLong(followup.getTenantId(), "tenant_id"); + if (responseTenantId != tenantId) { + throw new ResponseStatusException( + HttpStatus.INTERNAL_SERVER_ERROR, + "control-plane remote followup list response did not match requested tenant_id"); + } + return toDto(followup); + }) .toList(); } diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java index 75cb52b632..979406ca6c 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/LoggingAdminApplicationIntegrationTest.java @@ -254,9 +254,8 @@ void receiptFailureRollsBackTheAlreadyInsertedAuditProjection() { "CREATE TRIGGER fail_test_account_audit_receipt BEFORE INSERT ON account_audit_receipts " + "FOR EACH ROW EXECUTE FUNCTION fail_test_account_audit_receipt()"); try { - assertThatThrownBy( - () -> - logEventService.createLogEvent(tenantAuditRequest(eventId, "{\"accountId\":93}"))) + assertThatThrownBy(() -> + logEventService.createLogEvent(tenantAuditRequest(eventId, "{\"accountId\":93}"))) .isInstanceOf(AuditStorageUnavailableException.class); assertThat(dsl.fetchCount(LOG_EVENTS, LOG_EVENTS.AUDIT_EVENT_ID.eq(eventId))).isZero(); assertThat( @@ -427,17 +426,16 @@ void forwardAuditMigrationsPreserveRetainedRowsAndEnforceReceiptAndProjectionChe "retained negative tenant projection", "retained zero tenant legacy row", "retained zero tenant projection")) - .extracting( - row -> - List.of( - row.get("tenant_id", Long.class), - row.get("tenant_key", Long.class), - row.get("audit_event_id", String.class) == null - ? "" - : row.get("audit_event_id", String.class), - row.get("type", String.class), - row.get("message", String.class), - row.get("timestamp", LocalDateTime.class))) + .extracting(row -> + List.of( + row.get("tenant_id", Long.class), + row.get("tenant_key", Long.class), + row.get("audit_event_id", String.class) == null + ? "" + : row.get("audit_event_id", String.class), + row.get("type", String.class), + row.get("message", String.class), + row.get("timestamp", LocalDateTime.class))) .containsExactly( List.of( -9L, @@ -548,15 +546,14 @@ void forwardAuditMigrationsPreserveRetainedRowsAndEnforceReceiptAndProjectionChe .isFalse(); for (String invalidDigest : List.of("sha256:" + "A".repeat(64), "sha256:" + "g".repeat(64))) { - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE " - + schema - + ".account_audit_receipts SET payload_digest = ? " - + "WHERE receipt_id = ?", - invalidDigest, - retainedInvalidReceiptId)) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE " + + schema + + ".account_audit_receipts SET payload_digest = ? " + + "WHERE receipt_id = ?", + invalidDigest, + retainedInvalidReceiptId)) .isInstanceOf(DataIntegrityViolationException.class) .hasMessageContaining("chk_account_audit_receipt_digest_format"); } @@ -570,28 +567,26 @@ void forwardAuditMigrationsPreserveRetainedRowsAndEnforceReceiptAndProjectionChe .isEqualTo(retainedInvalidDigest); byte[] validPayload = "{\"afterMigration\":true}".getBytes(StandardCharsets.UTF_8); - assertThatThrownBy( - () -> - insertMigrationReceipt( - schema, - UUID.fromString("80000000-0000-4000-8000-000000000001"), - "70000000-0000-4000-8000-000000000001", - "sha256:" + "A".repeat(64), - validPayload, - "COMMITTED", - "ACCEPTED")) + assertThatThrownBy(() -> + insertMigrationReceipt( + schema, + UUID.fromString("80000000-0000-4000-8000-000000000001"), + "70000000-0000-4000-8000-000000000001", + "sha256:" + "A".repeat(64), + validPayload, + "COMMITTED", + "ACCEPTED")) .isInstanceOf(DataIntegrityViolationException.class) .hasMessageContaining("chk_account_audit_receipt_digest_format"); - assertThatThrownBy( - () -> - insertMigrationReceipt( - schema, - UUID.fromString("80000000-0000-4000-8000-000000000002"), - "70000000-0000-4000-8000-000000000002", - "sha256:" + "g".repeat(64), - validPayload, - "COMMITTED", - "ACCEPTED")) + assertThatThrownBy(() -> + insertMigrationReceipt( + schema, + UUID.fromString("80000000-0000-4000-8000-000000000002"), + "70000000-0000-4000-8000-000000000002", + "sha256:" + "g".repeat(64), + validPayload, + "COMMITTED", + "ACCEPTED")) .isInstanceOf(DataIntegrityViolationException.class) .hasMessageContaining("chk_account_audit_receipt_digest_format"); @@ -694,28 +689,26 @@ void forwardAuditMigrationsPreserveRetainedRowsAndEnforceReceiptAndProjectionChe invalidTenantId == 0 ? "60000000-0000-4000-8000-000000000003" : "60000000-0000-4000-8000-000000000004"; - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO " - + schema - + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message) " - + "VALUES ('tenant', ?, ?, ?, 'ACCOUNT_AUDIT', 'invalid tenant projection')", - invalidTenantId, - invalidTenantId, - eventId)) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO " + + schema + + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message) " + + "VALUES ('tenant', ?, ?, ?, 'ACCOUNT_AUDIT', 'invalid tenant projection')", + invalidTenantId, + invalidTenantId, + eventId)) .isInstanceOf(DataIntegrityViolationException.class) .hasMessageContaining("chk_log_events_tenant_audit_positive_tenant_id"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE " - + schema - + ".log_events SET tenant_id = ?, tenant_key = ? " - + "WHERE audit_event_id = ?", - invalidTenantId, - invalidTenantId, - "60000000-0000-4000-8000-000000000001")) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE " + + schema + + ".log_events SET tenant_id = ?, tenant_key = ? " + + "WHERE audit_event_id = ?", + invalidTenantId, + invalidTenantId, + "60000000-0000-4000-8000-000000000001")) .isInstanceOf(DataIntegrityViolationException.class) .hasMessageContaining("chk_log_events_tenant_audit_positive_tenant_id"); } @@ -737,14 +730,13 @@ void forwardAuditMigrationsPreserveRetainedRowsAndEnforceReceiptAndProjectionChe legacyTenantId); } - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO " - + schema - + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message) " - + "VALUES ('tenant', 73, 74, '50000000-0000-4000-8000-000000000001', " - + "'ACCOUNT_AUDIT', 'mismatched key')")) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO " + + schema + + ".log_events (scope, tenant_id, tenant_key, audit_event_id, type, message) " + + "VALUES ('tenant', 73, 74, '50000000-0000-4000-8000-000000000001', " + + "'ACCOUNT_AUDIT', 'mismatched key')")) .isInstanceOf(DataIntegrityViolationException.class) .hasMessageContaining("chk_log_events_scope_tenant"); } finally { @@ -1021,27 +1013,24 @@ void publicReportPersistenceControllerMappingIsAbsent() { assertThat( requestMappingHandlerMapping.getHandlerMethods().keySet().stream() .flatMap(mapping -> mapping.getPatternValues().stream())) - .noneMatch( - pattern -> - pattern.equals("/reports") - || pattern.startsWith("/reports/") - || pattern.equals("/admin/reports") - || pattern.startsWith("/admin/reports/")); + .noneMatch(pattern -> + pattern.equals("/reports") + || pattern.startsWith("/reports/") + || pattern.equals("/admin/reports") + || pattern.startsWith("/admin/reports/")); } @Test void publicTargetOnlyAdmissionPointerWriteMappingsAreAbsent() { assertThat(requestMappingHandlerMapping.getHandlerMethods().keySet()) - .noneMatch( - mapping -> - (mapping.getMethodsCondition().getMethods().isEmpty() - || mapping.getMethodsCondition().getMethods().contains(RequestMethod.POST)) - && mapping.getPatternValues().stream() - .anyMatch( - path -> - path.equals("/admission-pointers") - || path.equals("/admission-pointers/cutover") - || path.equals("/admission-pointers/version-upgrades"))); + .noneMatch(mapping -> + (mapping.getMethodsCondition().getMethods().isEmpty() + || mapping.getMethodsCondition().getMethods().contains(RequestMethod.POST)) + && mapping.getPatternValues().stream() + .anyMatch(path -> + path.equals("/admission-pointers") + || path.equals("/admission-pointers/cutover") + || path.equals("/admission-pointers/version-upgrades"))); } @Test @@ -1055,10 +1044,9 @@ void externallyGatedOperatorWriteMappingsRemainMapped() { }) { assertThat(requestMappingHandlerMapping.getHandlerMethods().keySet()) .as("path %s", path) - .anyMatch( - mapping -> - mapping.getMethodsCondition().getMethods().contains(RequestMethod.POST) - && mapping.getPatternValues().contains(path)); + .anyMatch(mapping -> + mapping.getMethodsCondition().getMethods().contains(RequestMethod.POST) + && mapping.getPatternValues().contains(path)); } } diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ModerationAccountUuidMigrationPostgresIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ModerationAccountUuidMigrationPostgresIntegrationTest.java index 2bcd713099..5a521f01a8 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ModerationAccountUuidMigrationPostgresIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/ModerationAccountUuidMigrationPostgresIntegrationTest.java @@ -69,10 +69,9 @@ void emptySchemaMigratesAndKeepsExactUuidWithoutChangingPolicyFields() { jdbc.queryForObject( "SELECT action || ':' || reason FROM moderation_actions", String.class)) .isEqualTo("chat_mute:abuse"); - assertThatThrownBy( - () -> - jdbc.update( - "INSERT INTO moderation_actions (tenant_id, account_id, action) VALUES (1, '00000000-0000-0000-0000-000000000000', 'ban')")) + assertThatThrownBy(() -> + jdbc.update( + "INSERT INTO moderation_actions (tenant_id, account_id, action) VALUES (1, '00000000-0000-0000-0000-000000000000', 'ban')")) .hasMessageContaining("moderation_actions_account_id_non_nil"); } diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java index b795b7f886..7bdd5480a9 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java @@ -109,14 +109,13 @@ void concurrentExactAcquiresPersistOneDurableReservationOwner() throws Exception try { for (int index = 0; index < callerCount; index++) { futures.add( - executor.submit( - () -> { - ready.countDown(); - if (!start.await(5, TimeUnit.SECONDS)) { - throw new IllegalStateException("concurrent acquire gate timed out"); - } - return acquire(tuple, UUID.randomUUID()); - })); + executor.submit(() -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("concurrent acquire gate timed out"); + } + return acquire(tuple, UUID.randomUUID()); + })); } assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); start.countDown(); @@ -247,35 +246,33 @@ void activeClaimsRequirePurposeWhileExpiredClaimsKeepNullPurpose() { tuple("postgres-null-purpose-insert", "active claim purpose insert guard"); UUID rejectedOwner = UUID.fromString("cd2900f9-2a8b-4dd3-a495-15180eb78f67"); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO start_session_pre_authorization_reservations (" - + "control_plane_request_id, pre_authorization_tuple_json, mutation_digest, phase, state, " - + "reservation_owner_id, reservation_claim_fence, claim_owner_id, claim_fence, " - + "claim_expires_at_epoch_ms, claim_state, claim_purpose, created_at_epoch_ms, " - + "updated_at_epoch_ms, post_authorization_execution_tuple_json, owner_execution_handoff_id) " - + "VALUES (?, ?, ?, 'ACCOUNT_AUTHORIZATION', 'RESERVED', ?, 1, ?, 1, ?, 'ACTIVE', NULL, ?, ?, NULL, NULL)", - rejectedInsertTuple.controlPlaneRequestId(), - rejectedInsertTuple.canonicalJson(), - rejectedInsertTuple.mutationDigest(), - rejectedOwner, - rejectedOwner, - NOW_EPOCH_MILLIS + 30_000L, - NOW_EPOCH_MILLIS, - NOW_EPOCH_MILLIS)); + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO start_session_pre_authorization_reservations (" + + "control_plane_request_id, pre_authorization_tuple_json, mutation_digest, phase, state, " + + "reservation_owner_id, reservation_claim_fence, claim_owner_id, claim_fence, " + + "claim_expires_at_epoch_ms, claim_state, claim_purpose, created_at_epoch_ms, " + + "updated_at_epoch_ms, post_authorization_execution_tuple_json, owner_execution_handoff_id) " + + "VALUES (?, ?, ?, 'ACCOUNT_AUTHORIZATION', 'RESERVED', ?, 1, ?, 1, ?, 'ACTIVE', NULL, ?, ?, NULL, NULL)", + rejectedInsertTuple.controlPlaneRequestId(), + rejectedInsertTuple.canonicalJson(), + rejectedInsertTuple.mutationDigest(), + rejectedOwner, + rejectedOwner, + NOW_EPOCH_MILLIS + 30_000L, + NOW_EPOCH_MILLIS, + NOW_EPOCH_MILLIS)); assertThat(dsl.fetchCount(START_SESSION_PRE_AUTHORIZATION_RESERVATIONS)).isZero(); StartSessionPreAuthorizationReservationTuple tuple = tuple("postgres-null-purpose-update", "active claim purpose update guard"); UUID owner = UUID.fromString("dd58a5f2-c3b9-4b95-b9f8-396dece825b8"); repository.acquire(tuple, owner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE start_session_pre_authorization_reservations SET claim_purpose = NULL " - + "WHERE control_plane_request_id = ?", - tuple.controlPlaneRequestId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE start_session_pre_authorization_reservations SET claim_purpose = NULL " + + "WHERE control_plane_request_id = ?", + tuple.controlPlaneRequestId())) .isInstanceOf(RuntimeException.class); assertThat(repository.findExact(tuple).orElseThrow().claimPurpose()) .isEqualTo(ClaimPurpose.ORIGINAL); @@ -360,17 +357,16 @@ void expiryRecoveryFencesStaleOwnerAndCannotInventTerminalOutcome() { assertThat(expired.reservationClaimFence()).isEqualTo(1L); assertThat(expired.state()).isEqualTo(State.AUTHORIZATION_PENDING); - assertThatThrownBy( - () -> - repository.renew( - tuple, - tuple.mutationDigest(), - originalOwner, - 1L, - Phase.ACCOUNT_AUTHORIZATION, - State.AUTHORIZATION_PENDING, - NOW_EPOCH_MILLIS + 30_001L, - NOW_EPOCH_MILLIS + 60_001L)) + assertThatThrownBy(() -> + repository.renew( + tuple, + tuple.mutationDigest(), + originalOwner, + 1L, + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZATION_PENDING, + NOW_EPOCH_MILLIS + 30_001L, + NOW_EPOCH_MILLIS + 60_001L)) .isInstanceOf( StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); @@ -457,16 +453,15 @@ void expiredReservedRecoveryMayIssueOnlyAfterSameReservationBecomesPending() { assertThat(issueEvidence.snapshot().state()).isEqualTo(State.AUTHORIZATION_PENDING); assertThat(issueEvidence.snapshot().claimPurpose()) .isEqualTo(ClaimPurpose.RESERVED_RECOVERY_ISSUE); - assertThatThrownBy( - () -> - repository.readCurrentClaim( - tuple, - reservationOwner, - 1L, - recoveryOwner, - 3L, - ReadPurpose.RECOVER, - NOW_EPOCH_MILLIS + 30_003L)) + assertThatThrownBy(() -> + repository.readCurrentClaim( + tuple, + reservationOwner, + 1L, + recoveryOwner, + 3L, + ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS + 30_003L)) .isInstanceOf( StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); assertThat( @@ -510,15 +505,14 @@ void concurrentExpiredPendingRecoveryClaimsHaveOneFenceWinner() throws Exception for (int index = 0; index < contenders; index++) { UUID recoveryOwner = UUID.randomUUID(); futures.add( - executor.submit( - () -> { - ready.countDown(); - if (!start.await(5, TimeUnit.SECONDS)) { - throw new IllegalStateException("concurrent recovery gate timed out"); - } - return repository.acquireRecoveryClaim( - tuple, recoveryOwner, NOW_EPOCH_MILLIS + 30_001L, NOW_EPOCH_MILLIS + 60_001L); - })); + executor.submit(() -> { + ready.countDown(); + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("concurrent recovery gate timed out"); + } + return repository.acquireRecoveryClaim( + tuple, recoveryOwner, NOW_EPOCH_MILLIS + 30_001L, NOW_EPOCH_MILLIS + 60_001L); + })); } assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); start.countDown(); @@ -588,30 +582,28 @@ void expiredAuthorizedRecoveryReadsOnlyOriginalResponseAndHandsOffOnce() { assertThat(originalResponseLookup.snapshot().state()).isEqualTo(State.AUTHORIZED); assertThat(originalResponseLookup.snapshot().claimPurpose()) .isEqualTo(ClaimPurpose.AUTHORIZED_RESPONSE_RECOVERY); - assertThatThrownBy( - () -> - repository.readCurrentClaim( - tuple, - reservationOwner, - 1L, - recoveryOwner, - recovery.snapshot().claimFence(), - ReadPurpose.ISSUE, - NOW_EPOCH_MILLIS + 30_002L)) + assertThatThrownBy(() -> + repository.readCurrentClaim( + tuple, + reservationOwner, + 1L, + recoveryOwner, + recovery.snapshot().claimFence(), + ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS + 30_002L)) .isInstanceOf( StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); - assertThatThrownBy( - () -> - repository.completeAuthorization( - tuple, - tuple.mutationDigest(), - reservationOwner, - 1L, - recoveryOwner, - recovery.snapshot().claimFence(), - postTuple(tuple, reservationOwner, 1L, "arfp/v1/other-key/" + "c".repeat(64)) - .canonicalJson(), - NOW_EPOCH_MILLIS + 30_003L)) + assertThatThrownBy(() -> + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + recoveryOwner, + recovery.snapshot().claimFence(), + postTuple(tuple, reservationOwner, 1L, "arfp/v1/other-key/" + "c".repeat(64)) + .canonicalJson(), + NOW_EPOCH_MILLIS + 30_003L)) .isInstanceOf( StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); @@ -744,60 +736,55 @@ void exactAuthorizationEnrichmentAndOwnerHandoffAreDurableBeforeDispatch() { assertThat(repository.findAuthorizedExact(tuple)) .isPresent() .get() - .satisfies( - snapshot -> { - assertThat(snapshot.postAuthorizationTuple().canonicalBytes()) - .containsExactly(postTuple.canonicalBytes()); - assertThat(snapshot.handoff()).isEqualTo(firstHandoff.snapshot().handoff()); - assertThat(snapshot.reservationOwnerId()).isEqualTo(reservationOwner); - assertThat(snapshot.currentClaimOwnerId()).isEqualTo(reservationOwner); - }); - - assertThatThrownBy( - () -> - repository.beginOwnerExecution( - tuple, - tuple.mutationDigest(), - reservationOwner, - 1L, - reservationOwner, - 1L, - postTuple.canonicalJson(), - UUID.fromString("53d31d97-a8c3-48a1-9815-b3e3228bb6f2"), - NOW_EPOCH_MILLIS + 5_500L)) + .satisfies(snapshot -> { + assertThat(snapshot.postAuthorizationTuple().canonicalBytes()) + .containsExactly(postTuple.canonicalBytes()); + assertThat(snapshot.handoff()).isEqualTo(firstHandoff.snapshot().handoff()); + assertThat(snapshot.reservationOwnerId()).isEqualTo(reservationOwner); + assertThat(snapshot.currentClaimOwnerId()).isEqualTo(reservationOwner); + }); + + assertThatThrownBy(() -> + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + UUID.fromString("53d31d97-a8c3-48a1-9815-b3e3228bb6f2"), + NOW_EPOCH_MILLIS + 5_500L)) .isInstanceOf( StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); StartSessionPostAuthorizationExecutionTuple changedFingerprint = postTuple(tuple, reservationOwner, 1L, "arfp/v1/other-key/" + "c".repeat(64)); - assertThatThrownBy( - () -> - repository.beginOwnerExecution( - tuple, - tuple.mutationDigest(), - reservationOwner, - 1L, - reservationOwner, - 1L, - changedFingerprint.canonicalJson(), - handoffId, - NOW_EPOCH_MILLIS + 6_000L)) + assertThatThrownBy(() -> + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + changedFingerprint.canonicalJson(), + handoffId, + NOW_EPOCH_MILLIS + 6_000L)) .isInstanceOf( StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE start_session_pre_authorization_reservations " - + "SET post_authorization_execution_tuple_json = ? " - + "WHERE control_plane_request_id = ?", - postTuple.canonicalJson() + " ", - tuple.controlPlaneRequestId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE start_session_pre_authorization_reservations " + + "SET post_authorization_execution_tuple_json = ? " + + "WHERE control_plane_request_id = ?", + postTuple.canonicalJson() + " ", + tuple.controlPlaneRequestId())) .isInstanceOf(RuntimeException.class); - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM start_session_pre_authorization_reservations " - + "WHERE control_plane_request_id = ?", - tuple.controlPlaneRequestId())) + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM start_session_pre_authorization_reservations " + + "WHERE control_plane_request_id = ?", + tuple.controlPlaneRequestId())) .isInstanceOf(RuntimeException.class); assertThatThrownBy( () -> dsl.execute("TRUNCATE TABLE start_session_pre_authorization_reservations")) @@ -813,33 +800,31 @@ void phaseMismatchExpiredClaimAndChangedTupleCannotEnrichOrDispatch() { postTuple(tuple, reservationOwner, 1L, FINGERPRINT); repository.acquire(tuple, reservationOwner, NOW_EPOCH_MILLIS, NOW_EPOCH_MILLIS + 30_000L); - assertThatThrownBy( - () -> - repository.completeAuthorization( - tuple, - tuple.mutationDigest(), - reservationOwner, - 1L, - reservationOwner, - 1L, - postTuple.canonicalJson(), - NOW_EPOCH_MILLIS + 1_000L)) + assertThatThrownBy(() -> + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + NOW_EPOCH_MILLIS + 1_000L)) .isInstanceOf( StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); repository.markAuthorizationPending( tuple, tuple.mutationDigest(), reservationOwner, 1L, NOW_EPOCH_MILLIS + 2_000L); - assertThatThrownBy( - () -> - repository.completeAuthorization( - tuple, - tuple.mutationDigest(), - reservationOwner, - 1L, - reservationOwner, - 1L, - postTuple.canonicalJson(), - NOW_EPOCH_MILLIS + 30_000L)) + assertThatThrownBy(() -> + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + NOW_EPOCH_MILLIS + 30_000L)) .isInstanceOf( StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); @@ -847,31 +832,29 @@ void phaseMismatchExpiredClaimAndChangedTupleCannotEnrichOrDispatch() { tuple(tuple.controlPlaneRequestId(), "changed action tuple"); StartSessionPostAuthorizationExecutionTuple changedPostTuple = postTuple(changedTuple, reservationOwner, 1L, FINGERPRINT); - assertThatThrownBy( - () -> - repository.completeAuthorization( - tuple, - tuple.mutationDigest(), - reservationOwner, - 1L, - reservationOwner, - 1L, - changedPostTuple.canonicalJson(), - NOW_EPOCH_MILLIS + 3_000L)) + assertThatThrownBy(() -> + repository.completeAuthorization( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + changedPostTuple.canonicalJson(), + NOW_EPOCH_MILLIS + 3_000L)) .isInstanceOf( StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); - assertThatThrownBy( - () -> - repository.beginOwnerExecution( - tuple, - tuple.mutationDigest(), - reservationOwner, - 1L, - reservationOwner, - 1L, - postTuple.canonicalJson(), - UUID.fromString("f80cc7af-327c-44ab-96cc-23a84ff0ab4a"), - NOW_EPOCH_MILLIS + 4_000L)) + assertThatThrownBy(() -> + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + UUID.fromString("f80cc7af-327c-44ab-96cc-23a84ff0ab4a"), + NOW_EPOCH_MILLIS + 4_000L)) .isInstanceOf( StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); assertThat(repository.findExact(tuple).orElseThrow().state()) @@ -939,32 +922,30 @@ void recoveryClaimMayEnrichTheOriginalResponseButCannotReplaceOriginalFence() { .isEqualTo(1L); assertThat(recoveryHandoff.snapshot().reservationSnapshot().claimFence()).isEqualTo(3L); - assertThatThrownBy( - () -> - repository.beginOwnerExecution( - tuple, - tuple.mutationDigest(), - reservationOwner, - 1L, - reservationOwner, - 1L, - postTuple.canonicalJson(), - UUID.fromString("d3f21a41-f718-4d82-9438-411377a10852"), - NOW_EPOCH_MILLIS + 30_003L)) + assertThatThrownBy(() -> + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + UUID.fromString("d3f21a41-f718-4d82-9438-411377a10852"), + NOW_EPOCH_MILLIS + 30_003L)) .isInstanceOf( StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); - assertThatThrownBy( - () -> - repository.beginOwnerExecution( - tuple, - tuple.mutationDigest(), - reservationOwner, - 1L, - recoveryOwner, - recovery.snapshot().claimFence() - 1L, - postTuple.canonicalJson(), - UUID.fromString("d3f21a41-f718-4d82-9438-411377a10852"), - NOW_EPOCH_MILLIS + 30_005L)) + assertThatThrownBy(() -> + repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + recoveryOwner, + recovery.snapshot().claimFence() - 1L, + postTuple.canonicalJson(), + UUID.fromString("d3f21a41-f718-4d82-9438-411377a10852"), + NOW_EPOCH_MILLIS + 30_005L)) .isInstanceOf( StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); } @@ -999,28 +980,27 @@ void concurrentExactOwnerHandoffCasReturnsOnlyOneDispatchWinner() throws Excepti try { for (int index = 0; index < contenders; index++) { futures.add( - executor.submit( - () -> { - ready.countDown(); - try { - if (!start.await(5, TimeUnit.SECONDS)) { - throw new IllegalStateException("owner handoff gate timed out"); - } - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - throw interrupted; - } - return repository.beginOwnerExecution( - tuple, - tuple.mutationDigest(), - reservationOwner, - 1L, - reservationOwner, - 1L, - postTuple.canonicalJson(), - handoffId, - NOW_EPOCH_MILLIS + 3_000L); - })); + executor.submit(() -> { + ready.countDown(); + try { + if (!start.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("owner handoff gate timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw interrupted; + } + return repository.beginOwnerExecution( + tuple, + tuple.mutationDigest(), + reservationOwner, + 1L, + reservationOwner, + 1L, + postTuple.canonicalJson(), + handoffId, + NOW_EPOCH_MILLIS + 3_000L); + })); } boolean allReady; try { @@ -1117,56 +1097,52 @@ void currentClaimReadReturnsExactIssueAndRecoverySnapshotsAndRejectsStaleInputs( assertThat(recoveryRead.snapshot().claimPurpose()) .isEqualTo(ClaimPurpose.AUTHORIZATION_RECOVERY); - assertThatThrownBy( - () -> - repository.readCurrentClaim( - tuple, - originalOwner, - 1L, - recoveryOwner, - 3L, - ReadPurpose.ISSUE, - NOW_EPOCH_MILLIS + 30_003L)) + assertThatThrownBy(() -> + repository.readCurrentClaim( + tuple, + originalOwner, + 1L, + recoveryOwner, + 3L, + ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS + 30_003L)) .isInstanceOf( StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); - assertThatThrownBy( - () -> - repository.readCurrentClaim( - tuple, - originalOwner, - 1L, - originalOwner, - 1L, - ReadPurpose.ISSUE, - NOW_EPOCH_MILLIS + 30_002L)) + assertThatThrownBy(() -> + repository.readCurrentClaim( + tuple, + originalOwner, + 1L, + originalOwner, + 1L, + ReadPurpose.ISSUE, + NOW_EPOCH_MILLIS + 30_002L)) .isInstanceOf( StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); - assertThatThrownBy( - () -> - repository.readCurrentClaim( - tuple, - originalOwner, - 1L, - recoveryOwner, - 3L, - ReadPurpose.RECOVER, - NOW_EPOCH_MILLIS + 60_001L)) + assertThatThrownBy(() -> + repository.readCurrentClaim( + tuple, + originalOwner, + 1L, + recoveryOwner, + 3L, + ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS + 60_001L)) .isInstanceOf( StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); StartSessionPreAuthorizationReservationTuple tamperedTuple = tuple(requestId, "tampered tuple fixture"); - assertThatThrownBy( - () -> - repository.readCurrentClaim( - tamperedTuple, - originalOwner, - 1L, - recoveryOwner, - 3L, - ReadPurpose.RECOVER, - NOW_EPOCH_MILLIS + 30_002L)) + assertThatThrownBy(() -> + repository.readCurrentClaim( + tamperedTuple, + originalOwner, + 1L, + recoveryOwner, + 3L, + ReadPurpose.RECOVER, + NOW_EPOCH_MILLIS + 30_002L)) .isInstanceOf( StartSessionPreAuthorizationReservationService.IdempotencyConflictException.class); } @@ -1176,13 +1152,12 @@ void immutableDigestGuardRejectsMutationAndReservationEvidenceRemainsReadable() StartSessionPreAuthorizationReservationTuple tuple = tuple("postgres-integrity-04", "integrity fixture"); acquire(tuple, UUID.randomUUID()); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE start_session_pre_authorization_reservations SET mutation_digest = ? " - + "WHERE control_plane_request_id = ?", - "0".repeat(64), - tuple.controlPlaneRequestId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE start_session_pre_authorization_reservations SET mutation_digest = ? " + + "WHERE control_plane_request_id = ?", + "0".repeat(64), + tuple.controlPlaneRequestId())) .isInstanceOf(RuntimeException.class); assertThat(repository.find(tuple.controlPlaneRequestId()).orElseThrow().mutationDigest()) .isEqualTo(tuple.mutationDigest()); diff --git a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionReservationEvidenceGrpcMutualTlsIntegrationTest.java b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionReservationEvidenceGrpcMutualTlsIntegrationTest.java index 03b85afcf5..0892c80a45 100644 --- a/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionReservationEvidenceGrpcMutualTlsIntegrationTest.java +++ b/services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionReservationEvidenceGrpcMutualTlsIntegrationTest.java @@ -363,13 +363,12 @@ private static void assertHandshakeRejected( rejectionEvidence.clear(); RawClientTls clientTls = rawClientTls(pki, clientIdentity); Throwable failure = - catchThrowable( - () -> { - try (SSLSocket socket = clientSocket(server, clientTls.context())) { - socket.startHandshake(); - socket.getInputStream().read(); - } - }); + catchThrowable(() -> { + try (SSLSocket socket = clientSocket(server, clientTls.context())) { + socket.startHandshake(); + socket.getInputStream().read(); + } + }); assertThat(failure).as(description).isNotNull(); if (clientIdentity.certificate() != null) { clientTls.assertIdentitySelected(clientIdentity, ACCOUNT_URI); diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java index 3b699a6ed4..828b12e0b9 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientMtlsTest.java @@ -225,15 +225,14 @@ void rejectsWrongLoggingCallerServiceAndNamespaceAtSyntheticAccountBoundary() th client = newClient(caller); client.initialize(); - assertThatThrownBy( - () -> - client.issueHuman( - tuple("wrong-caller-" + caller.alias()), - CONTROL_UI_JWT, - RESERVATION_OWNER_ID, - 8L, - CLAIM_OWNER_ID, - 9L)) + assertThatThrownBy(() -> + client.issueHuman( + tuple("wrong-caller-" + caller.alias()), + CONTROL_UI_JWT, + RESERVATION_OWNER_ID, + 8L, + CLAIM_OWNER_ID, + 9L)) .isInstanceOf(StatusRuntimeException.class) .hasMessageContaining("PERMISSION_DENIED"); assertThat(rpcCalls).hasValue(1); @@ -343,10 +342,8 @@ void deniesIssueAndRecoveryBeforeNetworkUnderSqlOrSynchronization() throws Excep var tuple = tuple("pre-network-denial-01"); TransactionSynchronizationManager.setActualTransactionActive(true); - assertThatThrownBy( - () -> - client.issueHuman( - tuple, CONTROL_UI_JWT, RESERVATION_OWNER_ID, 1L, CLAIM_OWNER_ID, 2L)) + assertThatThrownBy(() -> + client.issueHuman(tuple, CONTROL_UI_JWT, RESERVATION_OWNER_ID, 1L, CLAIM_OWNER_ID, 2L)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("no ambient SQL"); TransactionSynchronizationManager.clear(); @@ -375,23 +372,20 @@ void syntheticMutualTlsRejectsMissingClientCertificateWithSharedTlsAssertion() t trustOnlyContext.init(null, trustManagers.getTrustManagers(), new SecureRandom()); Throwable failure = - catchThrowable( - () -> { - try (SSLSocket socket = - (SSLSocket) - trustOnlyContext - .getSocketFactory() - .createSocket("127.0.0.1", server.getPort())) { - socket.setSoTimeout(2_000); - SSLParameters parameters = socket.getSSLParameters(); - parameters.setEndpointIdentificationAlgorithm("HTTPS"); - parameters.setProtocols(new String[] {"TLSv1.3"}); - parameters.setApplicationProtocols(new String[] {"h2"}); - socket.setSSLParameters(parameters); - socket.startHandshake(); - socket.getInputStream().read(); - } - }); + catchThrowable(() -> { + try (SSLSocket socket = + (SSLSocket) + trustOnlyContext.getSocketFactory().createSocket("127.0.0.1", server.getPort())) { + socket.setSoTimeout(2_000); + SSLParameters parameters = socket.getSSLParameters(); + parameters.setEndpointIdentificationAlgorithm("HTTPS"); + parameters.setProtocols(new String[] {"TLSv1.3"}); + parameters.setApplicationProtocols(new String[] {"h2"}); + socket.setSSLParameters(parameters); + socket.startHandshake(); + socket.getInputStream().read(); + } + }); assertThat(failure).isInstanceOf(SSLHandshakeException.class); assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue(); @@ -402,15 +396,14 @@ private void assertWrongServerIdentity(TestIdentity serverIdentity) throws Excep startServer(serverIdentity, UnaryOperator.identity(), UnaryOperator.identity()); client = newClient(pki.loggingClient()); client.initialize(); - assertThatThrownBy( - () -> - client.issueHuman( - tuple("wrong-server-" + serverIdentity.alias()), - CONTROL_UI_JWT, - RESERVATION_OWNER_ID, - 10L, - CLAIM_OWNER_ID, - 11L)) + assertThatThrownBy(() -> + client.issueHuman( + tuple("wrong-server-" + serverIdentity.alias()), + CONTROL_UI_JWT, + RESERVATION_OWNER_ID, + 10L, + CLAIM_OWNER_ID, + 11L)) .isInstanceOf(StatusRuntimeException.class) .hasMessageContaining("UNAUTHENTICATED"); assertThat(rpcCalls).hasValue(0); @@ -418,15 +411,14 @@ private void assertWrongServerIdentity(TestIdentity serverIdentity) throws Excep } private void assertInvalidResponse() { - assertThatThrownBy( - () -> - client.issueHuman( - tuple("invalid-account-result-01"), - CONTROL_UI_JWT, - RESERVATION_OWNER_ID, - 12L, - CLAIM_OWNER_ID, - 13L)) + assertThatThrownBy(() -> + client.issueHuman( + tuple("invalid-account-result-01"), + CONTROL_UI_JWT, + RESERVATION_OWNER_ID, + 12L, + CLAIM_OWNER_ID, + 13L)) .isInstanceOf(IllegalStateException.class); assertThat(rpcCalls).hasValue(1); } diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java index 893486931a..0e00daf92d 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java @@ -151,19 +151,15 @@ void issueAndRecoverUseExactTupleAndClaimIdentityAndReturnValidatedOriginalBytes var credentialsCaptor = ArgumentCaptor.forClass(CallCredentials.class); verify(stub, times(2)).withCallCredentials(credentialsCaptor.capture()); assertThat(credentialsCaptor.getAllValues()) - .allSatisfy( - credentials -> - assertThat(credentials) - .isInstanceOf(GrpcServerPeerIdentityCallCredentials.class)); + .allSatisfy(credentials -> + assertThat(credentials).isInstanceOf(GrpcServerPeerIdentityCallCredentials.class)); var interceptorCaptor = ArgumentCaptor.forClass(ClientInterceptor[].class); verify(stub, times(2)).withInterceptors(interceptorCaptor.capture()); assertThat(interceptorCaptor.getAllValues()) - .allSatisfy( - interceptors -> { - assertThat(interceptors).hasSize(1); - assertThat(interceptors[0]) - .isInstanceOf(GrpcServerPeerIdentityClientInterceptor.class); - }); + .allSatisfy(interceptors -> { + assertThat(interceptors).hasSize(1); + assertThat(interceptors[0]).isInstanceOf(GrpcServerPeerIdentityClientInterceptor.class); + }); assertThat(StartSessionOperatorAuthorizationClient.accountServerUri("world-runtime")) .isEqualTo("spiffe://firemud/ns/world-runtime/sa/account-service"); } @@ -362,10 +358,8 @@ void rejectsInvalidCallerTupleFenceAndTokenBeforeCallingAccount() throws Excepti StartSessionPreAuthorizationReservationTuple tuple = tuple("client-invalid-request"); try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { - assertThatThrownBy( - () -> - client.issueHuman( - tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 0L, CLAIM_OWNER, 1L)) + assertThatThrownBy(() -> + client.issueHuman(tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 0L, CLAIM_OWNER, 1L)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> client.issueHuman(tuple, "bad token\n", RESERVATION_OWNER, 1L, CLAIM_OWNER, 1L)) @@ -401,10 +395,8 @@ void refusesIssueAndRecoverWithoutReadableFileBackedMtlsBeforeCallingAccount() t for (CommonGrpcClientProperties invalidTls : List.of(plaintext, missing, classpath, directoryInsteadOfCertificate, incomplete)) { try (TestClient client = new TestClient(stub, invalidTls)) { - assertThatThrownBy( - () -> - client.issueHuman( - tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + assertThatThrownBy(() -> + client.issueHuman(tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) .isInstanceOf(IllegalStateException.class); assertThatThrownBy(() -> client.recover(tuple, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) .isInstanceOf(IllegalStateException.class); @@ -427,10 +419,8 @@ void unavailableAccountResponseRemainsUnavailableWithoutCreatingFallback() throw try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { Throwable failure = - catchThrowable( - () -> - client.issueHuman( - tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)); + catchThrowable(() -> + client.issueHuman(tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)); assertThat(failure).isInstanceOf(StatusRuntimeException.class); assertThat(((StatusRuntimeException) failure).getStatus().getCode()) .isEqualTo(Status.Code.UNAVAILABLE); @@ -449,10 +439,8 @@ void deniesIssueAndRecoverBeforeAccountUnderSqlOrSynchronization() throws Except try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { TransactionSynchronizationManager.setActualTransactionActive(true); try { - assertThatThrownBy( - () -> - client.issueHuman( - tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + assertThatThrownBy(() -> + client.issueHuman(tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("no ambient SQL or synchronization"); } finally { @@ -537,10 +525,8 @@ private void assertRejected( when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); when(stub.issueHumanOperatorAuthorizationReference(any())).thenReturn(response); try (TestClient client = new TestClient(stub, fileBackedTlsProperties())) { - assertThatThrownBy( - () -> - client.issueHuman( - tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) + assertThatThrownBy(() -> + client.issueHuman(tuple, CONTROL_UI_TOKEN, RESERVATION_OWNER, 9L, CLAIM_OWNER, 11L)) .isInstanceOf(IllegalStateException.class); } } diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfigurationTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfigurationTest.java index 37aa24396a..5d8a05d15c 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfigurationTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/config/StartSessionOperatorAuthorizationConfigurationTest.java @@ -47,13 +47,12 @@ void compositionIsAbsentWhenOptInIsMissingOrFalse() { StartSessionOperatorAuthorizationConfiguration.class, SharedGrpcConfiguration.class, ReservationService.class) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(StartSessionOperatorAuthorizationClient.class); - assertThat(context).doesNotHaveBean(StartSessionAuthorizationCoordinator.class); - assertThat(context.getBean(ControlledGrpcChannelFactory.class).calls()).isEmpty(); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(StartSessionOperatorAuthorizationClient.class); + assertThat(context).doesNotHaveBean(StartSessionAuthorizationCoordinator.class); + assertThat(context.getBean(ControlledGrpcChannelFactory.class).calls()).isEmpty(); + }); new ApplicationContextRunner() .withUserConfiguration( @@ -61,81 +60,73 @@ void compositionIsAbsentWhenOptInIsMissingOrFalse() { SharedGrpcConfiguration.class, ReservationService.class) .withPropertyValues(ENABLED + "=false") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).doesNotHaveBean(StartSessionOperatorAuthorizationClient.class); - assertThat(context).doesNotHaveBean(StartSessionAuthorizationCoordinator.class); - assertThat(context.getBean(ControlledGrpcChannelFactory.class).calls()).isEmpty(); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(StartSessionOperatorAuthorizationClient.class); + assertThat(context).doesNotHaveBean(StartSessionAuthorizationCoordinator.class); + assertThat(context.getBean(ControlledGrpcChannelFactory.class).calls()).isEmpty(); + }); } @Test void enabledCompositionRequiresReservationProviderAndFileBackedMtls(@TempDir Path tlsDirectory) throws IOException { String[] tlsProperties = fileBackedTlsProperties(tlsDirectory); - withTlsReloadDisabled( - () -> - contextRunner() - .withUserConfiguration( - StartSessionOperatorAuthorizationConfiguration.class, - SharedGrpcConfiguration.class) - .withPropertyValues( - concat( - new String[] { - ENABLED + "=true", - WORKLOAD_NAMESPACE + "=gameplay", - ACCOUNT_ENDPOINT + "=account-service.gameplay.svc:6565" - }, - tlsProperties)) - .run(context -> assertThat(context).hasFailed())); + withTlsReloadDisabled(() -> + contextRunner() + .withUserConfiguration( + StartSessionOperatorAuthorizationConfiguration.class, SharedGrpcConfiguration.class) + .withPropertyValues( + concat( + new String[] { + ENABLED + "=true", + WORKLOAD_NAMESPACE + "=gameplay", + ACCOUNT_ENDPOINT + "=account-service.gameplay.svc:6565" + }, + tlsProperties)) + .run(context -> assertThat(context).hasFailed())); - withTlsReloadDisabled( - () -> - contextRunner() - .withUserConfiguration( - StartSessionOperatorAuthorizationConfiguration.class, - SharedGrpcConfiguration.class, - ReservationService.class) - .withPropertyValues(ENABLED + "=true", WORKLOAD_NAMESPACE + "=gameplay") - .run(context -> assertThat(context).hasFailed())); + withTlsReloadDisabled(() -> + contextRunner() + .withUserConfiguration( + StartSessionOperatorAuthorizationConfiguration.class, + SharedGrpcConfiguration.class, + ReservationService.class) + .withPropertyValues(ENABLED + "=true", WORKLOAD_NAMESPACE + "=gameplay") + .run(context -> assertThat(context).hasFailed())); } @Test void enabledCompositionRequiresCanonicalWorkloadNamespace(@TempDir Path tlsDirectory) throws IOException { String[] tlsProperties = fileBackedTlsProperties(tlsDirectory); - withTlsReloadDisabled( - () -> - contextRunner() - .withUserConfiguration( - StartSessionOperatorAuthorizationConfiguration.class, - SharedGrpcConfiguration.class, - ReservationService.class) - .withPropertyValues( - concat( - new String[] { - ENABLED + "=true", ACCOUNT_ENDPOINT + "=account-service:6565" - }, - tlsProperties)) - .run(context -> assertThat(context).hasFailed())); + withTlsReloadDisabled(() -> + contextRunner() + .withUserConfiguration( + StartSessionOperatorAuthorizationConfiguration.class, + SharedGrpcConfiguration.class, + ReservationService.class) + .withPropertyValues( + concat( + new String[] {ENABLED + "=true", ACCOUNT_ENDPOINT + "=account-service:6565"}, + tlsProperties)) + .run(context -> assertThat(context).hasFailed())); - withTlsReloadDisabled( - () -> - contextRunner() - .withUserConfiguration( - StartSessionOperatorAuthorizationConfiguration.class, - SharedGrpcConfiguration.class, - ReservationService.class) - .withPropertyValues( - concat( - new String[] { - ENABLED + "=true", - WORKLOAD_NAMESPACE + "=Gameplay", - ACCOUNT_ENDPOINT + "=account-service:6565" - }, - tlsProperties)) - .run(context -> assertThat(context).hasFailed())); + withTlsReloadDisabled(() -> + contextRunner() + .withUserConfiguration( + StartSessionOperatorAuthorizationConfiguration.class, + SharedGrpcConfiguration.class, + ReservationService.class) + .withPropertyValues( + concat( + new String[] { + ENABLED + "=true", + WORKLOAD_NAMESPACE + "=Gameplay", + ACCOUNT_ENDPOINT + "=account-service:6565" + }, + tlsProperties)) + .run(context -> assertThat(context).hasFailed())); } @Test @@ -144,51 +135,47 @@ void explicitCompositionUsesManagedClientLifecycleAndCapturedChannelConfiguratio String[] tlsProperties = fileBackedTlsProperties(tlsDirectory); AtomicBoolean channelShutdown = new AtomicBoolean(); - withTlsReloadDisabled( - () -> - contextRunner() - .withUserConfiguration( - StartSessionOperatorAuthorizationConfiguration.class, - SharedGrpcConfiguration.class, - ReservationService.class) - .withPropertyValues( - concat( - new String[] { - ENABLED + "=true", - WORKLOAD_NAMESPACE + "=gameplay", - ACCOUNT_ENDPOINT + "=account-service.gameplay.svc:6565" - }, - tlsProperties)) - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context) - .hasSingleBean(StartSessionOperatorAuthorizationClient.class); - assertThat(context).hasSingleBean(StartSessionAuthorizationCoordinator.class); + withTlsReloadDisabled(() -> + contextRunner() + .withUserConfiguration( + StartSessionOperatorAuthorizationConfiguration.class, + SharedGrpcConfiguration.class, + ReservationService.class) + .withPropertyValues( + concat( + new String[] { + ENABLED + "=true", + WORKLOAD_NAMESPACE + "=gameplay", + ACCOUNT_ENDPOINT + "=account-service.gameplay.svc:6565" + }, + tlsProperties)) + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(StartSessionOperatorAuthorizationClient.class); + assertThat(context).hasSingleBean(StartSessionAuthorizationCoordinator.class); - ControlledGrpcChannelFactory channelFactory = - context.getBean(ControlledGrpcChannelFactory.class); - assertThat(channelFactory.calls()).hasSize(1); - ChannelCall call = channelFactory.calls().get(0); - assertThat(call.target()).isEqualTo("account-service.gameplay.svc:6565"); - assertThat(call.defaultPort()).isEqualTo(6565); - assertThat(call.keepAlive()).isTrue(); - assertThat(call.tlsProperties().isPlaintext()).isFalse(); - assertThat(call.tlsProperties().getCertChain()) - .isEqualTo(tlsProperties[0].substring((CERT_CHAIN + "=").length())); + ControlledGrpcChannelFactory channelFactory = + context.getBean(ControlledGrpcChannelFactory.class); + assertThat(channelFactory.calls()).hasSize(1); + ChannelCall call = channelFactory.calls().get(0); + assertThat(call.target()).isEqualTo("account-service.gameplay.svc:6565"); + assertThat(call.defaultPort()).isEqualTo(6565); + assertThat(call.keepAlive()).isTrue(); + assertThat(call.tlsProperties().isPlaintext()).isFalse(); + assertThat(call.tlsProperties().getCertChain()) + .isEqualTo(tlsProperties[0].substring((CERT_CHAIN + "=").length())); - context.close(); - channelShutdown.set(channelFactory.channelWasShutdown()); - })); + context.close(); + channelShutdown.set(channelFactory.channelWasShutdown()); + })); assertThat(channelShutdown.get()).isTrue(); } private static ApplicationContextRunner contextRunner() { return new ApplicationContextRunner() - .withInitializer( - context -> - context.getBeanFactory().setConversionService(new ApplicationConversionService())); + .withInitializer(context -> + context.getBeanFactory().setConversionService(new ApplicationConversionService())); } private static String[] fileBackedTlsProperties(Path tlsDirectory) throws IOException { @@ -266,11 +253,10 @@ private static final class ControlledGrpcChannelFactory extends GrpcChannelFacto private ControlledGrpcChannelFactory() { when(channel.shutdown()) - .thenAnswer( - invocation -> { - channelWasShutdown.set(true); - return channel; - }); + .thenAnswer(invocation -> { + channelWasShutdown.set(true); + return channel; + }); } @Override diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupControllerTest.java index e9a3a050a4..e5425ce2ef 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/RemoteFollowupControllerTest.java @@ -91,14 +91,13 @@ void getRemoteFollowupRejectsMalformedTenantIdBeforeDispatch() throws Exception void listRemoteFollowupsReturnsCanonicalRows() throws Exception { when(remoteFollowupService.listRemoteFollowups( org.mockito.ArgumentMatchers.eq(2L), - org.mockito.ArgumentMatchers.argThat( - request -> - "SCHEDULED".equals(request.getStatus()) - && "enqueue_automation_command".equals(request.getPayloadKind()) - && "ops".equals(request.getWorldSlug()) - && "preview".equals(request.getRealmSlug()) - && Long.valueOf(29L).equals(request.getPointerVersion()) - && Integer.valueOf(10).equals(request.getLimit())))) + org.mockito.ArgumentMatchers.argThat(request -> + "SCHEDULED".equals(request.getStatus()) + && "enqueue_automation_command".equals(request.getPayloadKind()) + && "ops".equals(request.getWorldSlug()) + && "preview".equals(request.getRealmSlug()) + && Long.valueOf(29L).equals(request.getPointerVersion()) + && Integer.valueOf(10).equals(request.getLimit())))) .thenReturn(List.of(remoteFollowupDto())); SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java index fe9a6f0b38..33cb2d35a7 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java @@ -128,12 +128,11 @@ void onlyReservationWinnerIssuesAndOnlyDurableOwnerPendingReturnsTransientRefere eq(1L), any(UUID.class), eq(1L))) - .thenAnswer( - invocation -> - authorizationReference( - tuple, - (UUID) invocation.getArgument(2), - ((Number) invocation.getArgument(3)).longValue())); + .thenAnswer(invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, true); Result first = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); @@ -242,10 +241,8 @@ void rejectsAmbientTransactionAndSynchronizationBeforeReservationWork() { StartSessionPreAuthorizationReservationTuple tuple = tuple("coordinator-ambient-sql"); TransactionSynchronizationManager.setActualTransactionActive(true); try { - assertThatThrownBy( - () -> - coordinator.begin( - tuple.controlPlaneRequestId(), tuple.action(), CONTROL_UI_TOKEN)) + assertThatThrownBy(() -> + coordinator.begin(tuple.controlPlaneRequestId(), tuple.action(), CONTROL_UI_TOKEN)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("no ambient SQL or synchronization"); } finally { @@ -276,21 +273,20 @@ void nullReferenceAndWrongWorkloadCannotCompleteOrHandoff() throws Exception { anyLong(), any(UUID.class), anyLong())) - .thenAnswer( - invocation -> { - AuthorizationReference response = - authorizationReference( - tuple, - (UUID) invocation.getArgument(2), - ((Number) invocation.getArgument(3)).longValue()); - if (caseName.equals("null-reference")) { - when(response.operatorAuthorizationReference()).thenReturn(null); - } else { - when(response.authenticatedLoggingWorkloadIdentity()) - .thenReturn("spiffe://firemud/ns/other/sa/logging-admin-service"); - } - return response; - }); + .thenAnswer(invocation -> { + AuthorizationReference response = + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue()); + if (caseName.equals("null-reference")) { + when(response.operatorAuthorizationReference()).thenReturn(null); + } else { + when(response.authenticatedLoggingWorkloadIdentity()) + .thenReturn("spiffe://firemud/ns/other/sa/logging-admin-service"); + } + return response; + }); Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); assertThat(result.progress()).isEqualTo(Progress.AUTHORIZATION_OUTCOME_UNKNOWN); assertThat(result.pendingReason()) @@ -354,19 +350,16 @@ void namespaceJwtAndHumanTenantAdminGuardsRunBeforeStorage() { action.mutation(), action.auditReason()); - assertThatThrownBy( - () -> - coordinator.begin( - tuple.controlPlaneRequestId(), wrongNamespaceAction, CONTROL_UI_TOKEN)) + assertThatThrownBy(() -> + coordinator.begin( + tuple.controlPlaneRequestId(), wrongNamespaceAction, CONTROL_UI_TOKEN)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("configured workload namespace"); assertThatThrownBy(() -> coordinator.begin(tuple.controlPlaneRequestId(), action, "not-a-jwt")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("JWT envelope is malformed"); - assertThatThrownBy( - () -> - coordinator.begin( - tuple.controlPlaneRequestId(), action, CONTROL_UI_TOKEN + ".extra")) + assertThatThrownBy(() -> + coordinator.begin(tuple.controlPlaneRequestId(), action, CONTROL_UI_TOKEN + ".extra")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("JWT envelope is malformed"); @@ -458,12 +451,11 @@ void missingIndependentAuthorizedReadbackLeavesAuthorizationUnknownAndDoesNotHan stubInitialReservation(tuple); when(accountClient.issueHuman( eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) - .thenAnswer( - invocation -> - authorizationReference( - tuple, - (UUID) invocation.getArgument(2), - ((Number) invocation.getArgument(3)).longValue())); + .thenAnswer(invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, true); when(repository.findAuthorizedExact(eq(tuple))).thenReturn(Optional.empty()); @@ -486,37 +478,35 @@ void conflictingIndependentAuthorizedReadbackCannotAdvanceOwnerPending() throws stubInitialReservation(tuple); when(accountClient.issueHuman( eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) - .thenAnswer( - invocation -> - authorizationReference( - tuple, - (UUID) invocation.getArgument(2), - ((Number) invocation.getArgument(3)).longValue())); + .thenAnswer(invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, true); when(repository.findAuthorizedExact(eq(tuple))) - .thenAnswer( - invocation -> { - AuthorizedSnapshot exact = exactReadback.get(); - Snapshot snapshot = exact.reservationSnapshot(); - Snapshot substituted = - new Snapshot( - snapshot.tuple(), - snapshot.mutationDigest(), - snapshot.phase(), - snapshot.state(), - snapshot.reservationClaimFence(), - snapshot.claimFence(), - snapshot.claimExpiresAtEpochMillis() + 1L, - snapshot.claimState(), - snapshot.claimPurpose()); - return Optional.of( - new AuthorizedSnapshot( - substituted, - exact.postAuthorizationTuple(), - exact.reservationOwnerId(), - exact.currentClaimOwnerId(), - exact.handoff())); - }); + .thenAnswer(invocation -> { + AuthorizedSnapshot exact = exactReadback.get(); + Snapshot snapshot = exact.reservationSnapshot(); + Snapshot substituted = + new Snapshot( + snapshot.tuple(), + snapshot.mutationDigest(), + snapshot.phase(), + snapshot.state(), + snapshot.reservationClaimFence(), + snapshot.claimFence(), + snapshot.claimExpiresAtEpochMillis() + 1L, + snapshot.claimState(), + snapshot.claimPurpose()); + return Optional.of( + new AuthorizedSnapshot( + substituted, + exact.postAuthorizationTuple(), + exact.reservationOwnerId(), + exact.currentClaimOwnerId(), + exact.handoff())); + }); Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); @@ -542,12 +532,11 @@ void recoveryUsesOriginalOwnerAndFreshFenceAndNeverCallsIssue() throws Exception pending, ORIGINAL_OWNER))); when(accountClient.recover( eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), any(UUID.class), eq(3L))) - .thenAnswer( - invocation -> - authorizationReference( - tuple, - (UUID) invocation.getArgument(1), - ((Number) invocation.getArgument(2)).longValue())); + .thenAnswer(invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(1), + ((Number) invocation.getArgument(2)).longValue())); stubAuthorizationEnrichment(tuple, true, true); Result result = coordinator.recover(tuple); @@ -604,12 +593,11 @@ void issueHumanAndDispatchForwardsOnlyAfterDurableOwnerPendingAndOnlyOnce() thro eq(1L), any(UUID.class), eq(1L))) - .thenAnswer( - invocation -> - authorizationReference( - tuple, - (UUID) invocation.getArgument(2), - ((Number) invocation.getArgument(3)).longValue())); + .thenAnswer(invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, true); GameSessionClient ownerClient = mock(GameSessionClient.class); StartSessionOwnerHandoffResult ownerEcho = ownerEcho(tuple); @@ -685,12 +673,11 @@ void recoverAndDispatchForwardsTheOriginalRecoveredOperationOnce() throws Except pending, ORIGINAL_OWNER))); when(accountClient.recover( eq(shared(tuple)), eq(ORIGINAL_OWNER), eq(1L), any(UUID.class), eq(3L))) - .thenAnswer( - invocation -> - authorizationReference( - tuple, - (UUID) invocation.getArgument(1), - ((Number) invocation.getArgument(2)).longValue())); + .thenAnswer(invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(1), + ((Number) invocation.getArgument(2)).longValue())); stubAuthorizationEnrichment(tuple, true, true); GameSessionClient ownerClient = mock(GameSessionClient.class); StartSessionOwnerHandoffResult ownerEcho = ownerEcho(tuple); @@ -785,12 +772,11 @@ void ambiguousOwnerDispatchPropagatesAndExactDuplicateDoesNotRedeliver() throws alreadyPending, true)); when(accountClient.issueHuman( eq(shared(tuple)), anyString(), any(UUID.class), eq(1L), any(UUID.class), eq(1L))) - .thenAnswer( - invocation -> - authorizationReference( - tuple, - (UUID) invocation.getArgument(2), - ((Number) invocation.getArgument(3)).longValue())); + .thenAnswer(invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, true); GameSessionClient ownerClient = mock(GameSessionClient.class); io.grpc.StatusRuntimeException ambiguous = Status.UNAVAILABLE.asRuntimeException(); @@ -816,12 +802,11 @@ void ownerPendingDuplicateCasDoesNotReturnTransientHandoff() throws Exception { stubInitialReservation(tuple); when(accountClient.issueHuman( eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) - .thenAnswer( - invocation -> - authorizationReference( - tuple, - (UUID) invocation.getArgument(2), - ((Number) invocation.getArgument(3)).longValue())); + .thenAnswer(invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, false); Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); @@ -851,12 +836,11 @@ void ownerPendingTransitionFailureNeverReturnsTransientPayload() throws Exceptio stubInitialReservation(tuple); when(accountClient.issueHuman( eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) - .thenAnswer( - invocation -> - authorizationReference( - tuple, - (UUID) invocation.getArgument(2), - ((Number) invocation.getArgument(3)).longValue())); + .thenAnswer(invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); stubAuthorizationEnrichment(tuple, true, true); when(repository.beginOwnerExecution( eq(tuple), @@ -956,12 +940,11 @@ void mismatchedResponseTupleAndStaleClaimAfterAccountReturnAreNotForwarded() thr stubInitialReservation(tuple); when(accountClient.issueHuman( eq(shared(tuple)), anyString(), any(UUID.class), anyLong(), any(UUID.class), anyLong())) - .thenAnswer( - invocation -> - authorizationReference( - substituted, - (UUID) invocation.getArgument(2), - ((Number) invocation.getArgument(3)).longValue())); + .thenAnswer(invocation -> + authorizationReference( + substituted, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); Result invalidAccountResult = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); @@ -984,12 +967,11 @@ void mismatchedResponseTupleAndStaleClaimAfterAccountReturnAreNotForwarded() thr anyLong(), any(UUID.class), anyLong())) - .thenAnswer( - invocation -> - authorizationReference( - staleTuple, - (UUID) invocation.getArgument(2), - ((Number) invocation.getArgument(3)).longValue())); + .thenAnswer(invocation -> + authorizationReference( + staleTuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue())); when(repository.completeAuthorization( eq(staleTuple), eq(staleTuple.mutationDigest()), @@ -1039,13 +1021,12 @@ void sourceFenceAndLinearizationMismatchesNeverReachLoggingCompletion() throws E anyLong(), any(UUID.class), anyLong())) - .thenAnswer( - invocation -> - authorizationReference( - tuple, - (UUID) invocation.getArgument(2), - ((Number) invocation.getArgument(3)).longValue(), - alteredReference)); + .thenAnswer(invocation -> + authorizationReference( + tuple, + (UUID) invocation.getArgument(2), + ((Number) invocation.getArgument(3)).longValue(), + alteredReference)); Result result = coordinator.issueHuman(tuple, CONTROL_UI_TOKEN); @@ -1108,36 +1089,34 @@ private void stubAuthorizationEnrichment( anyLong(), anyString(), eq(NOW_MILLIS))) - .thenAnswer( - invocation -> { - UUID reservationOwner = invocation.getArgument(2); - long reservationFence = invocation.getArgument(3); - UUID currentOwner = invocation.getArgument(4); - long currentFence = invocation.getArgument(5); - String exactPostTupleJson = invocation.getArgument(6); - StartSessionPostAuthorizationExecutionTuple postTuple = - StartSessionPostAuthorizationExecutionTuple.decode( - exactPostTupleJson.getBytes(java.nio.charset.StandardCharsets.UTF_8)); - Snapshot authorized = - new Snapshot( - tuple, - tuple.mutationDigest(), - Phase.ACCOUNT_AUTHORIZATION, - State.AUTHORIZED, - reservationFence, - currentFence, - NOW_MILLIS + 30_000L, - ClaimState.ACTIVE, - currentOwner.equals(reservationOwner) && currentFence == reservationFence - ? ClaimPurpose.ORIGINAL - : ClaimPurpose.AUTHORIZATION_RECOVERY); - AuthorizedSnapshot authorizedSnapshot = - new AuthorizedSnapshot( - authorized, postTuple, reservationOwner, currentOwner, null); - exactReadback.set(authorizedSnapshot); - return new StartSessionPreAuthorizationReservationRepository - .AuthorizationTransitionResult(authorizedSnapshot, transitioned); - }); + .thenAnswer(invocation -> { + UUID reservationOwner = invocation.getArgument(2); + long reservationFence = invocation.getArgument(3); + UUID currentOwner = invocation.getArgument(4); + long currentFence = invocation.getArgument(5); + String exactPostTupleJson = invocation.getArgument(6); + StartSessionPostAuthorizationExecutionTuple postTuple = + StartSessionPostAuthorizationExecutionTuple.decode( + exactPostTupleJson.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + Snapshot authorized = + new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.ACCOUNT_AUTHORIZATION, + State.AUTHORIZED, + reservationFence, + currentFence, + NOW_MILLIS + 30_000L, + ClaimState.ACTIVE, + currentOwner.equals(reservationOwner) && currentFence == reservationFence + ? ClaimPurpose.ORIGINAL + : ClaimPurpose.AUTHORIZATION_RECOVERY); + AuthorizedSnapshot authorizedSnapshot = + new AuthorizedSnapshot(authorized, postTuple, reservationOwner, currentOwner, null); + exactReadback.set(authorizedSnapshot); + return new StartSessionPreAuthorizationReservationRepository + .AuthorizationTransitionResult(authorizedSnapshot, transitioned); + }); when(repository.findAuthorizedExact(eq(tuple))) .thenAnswer(invocation -> Optional.ofNullable(exactReadback.get())); when(repository.beginOwnerExecution( @@ -1150,41 +1129,40 @@ private void stubAuthorizationEnrichment( anyString(), any(UUID.class), eq(NOW_MILLIS))) - .thenAnswer( - invocation -> { - UUID reservationOwner = invocation.getArgument(2); - long reservationFence = invocation.getArgument(3); - UUID currentOwner = invocation.getArgument(4); - long currentFence = invocation.getArgument(5); - String exactPostTupleJson = invocation.getArgument(6); - UUID handoffId = invocation.getArgument(7); - StartSessionPostAuthorizationExecutionTuple postTuple = - StartSessionPostAuthorizationExecutionTuple.decode( - exactPostTupleJson.getBytes(java.nio.charset.StandardCharsets.UTF_8)); - Snapshot ownerPending = - new Snapshot( - tuple, - tuple.mutationDigest(), - Phase.OWNER_EXECUTION, - State.OWNER_EXECUTION_PENDING, - reservationFence, - currentFence, - NOW_MILLIS + 30_000L, - ClaimState.ACTIVE, - currentOwner.equals(reservationOwner) && currentFence == reservationFence - ? ClaimPurpose.ORIGINAL - : ClaimPurpose.AUTHORIZATION_RECOVERY); - AuthorizedSnapshot ownerPendingSnapshot = - new AuthorizedSnapshot( - ownerPending, - postTuple, - reservationOwner, - currentOwner, - new OwnerExecutionHandoff(handoffId)); - exactReadback.set(ownerPendingSnapshot); - return new StartSessionPreAuthorizationReservationRepository - .OwnerExecutionTransitionResult(ownerPendingSnapshot, mayDispatch); - }); + .thenAnswer(invocation -> { + UUID reservationOwner = invocation.getArgument(2); + long reservationFence = invocation.getArgument(3); + UUID currentOwner = invocation.getArgument(4); + long currentFence = invocation.getArgument(5); + String exactPostTupleJson = invocation.getArgument(6); + UUID handoffId = invocation.getArgument(7); + StartSessionPostAuthorizationExecutionTuple postTuple = + StartSessionPostAuthorizationExecutionTuple.decode( + exactPostTupleJson.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + Snapshot ownerPending = + new Snapshot( + tuple, + tuple.mutationDigest(), + Phase.OWNER_EXECUTION, + State.OWNER_EXECUTION_PENDING, + reservationFence, + currentFence, + NOW_MILLIS + 30_000L, + ClaimState.ACTIVE, + currentOwner.equals(reservationOwner) && currentFence == reservationFence + ? ClaimPurpose.ORIGINAL + : ClaimPurpose.AUTHORIZATION_RECOVERY); + AuthorizedSnapshot ownerPendingSnapshot = + new AuthorizedSnapshot( + ownerPending, + postTuple, + reservationOwner, + currentOwner, + new OwnerExecutionHandoff(handoffId)); + exactReadback.set(ownerPendingSnapshot); + return new StartSessionPreAuthorizationReservationRepository + .OwnerExecutionTransitionResult(ownerPendingSnapshot, mayDispatch); + }); } private static AuthorizationReference authorizationReference( diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java index 163abcea2a..fabab29e3f 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationServiceTest.java @@ -301,28 +301,26 @@ void currentClaimReadRejectsWrongPurposeFreshnessAndExpiredSnapshots() { new StartSessionPreAuthorizationReservationRepository.CurrentClaimResult( lookupOnlyRecovery, reservationOwnerId, recoveryOwnerId))); - assertThatThrownBy( - () -> - service.readCurrentClaimEvidence( - requestId, - tuple, - reservationOwnerId, - 1L, - recoveryOwnerId, - 3L, - StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE)) + assertThatThrownBy(() -> + service.readCurrentClaimEvidence( + requestId, + tuple, + reservationOwnerId, + 1L, + recoveryOwnerId, + 3L, + StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE)) .isInstanceOf( StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); - assertThatThrownBy( - () -> - service.readCurrentClaimEvidence( - requestId, - tuple, - reservationOwnerId, - 1L, - reservationOwnerId, - 1L, - StartSessionPreAuthorizationReservationService.ReadPurpose.RECOVER)) + assertThatThrownBy(() -> + service.readCurrentClaimEvidence( + requestId, + tuple, + reservationOwnerId, + 1L, + reservationOwnerId, + 1L, + StartSessionPreAuthorizationReservationService.ReadPurpose.RECOVER)) .isInstanceOf( StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); verify(repository) @@ -359,16 +357,15 @@ void currentClaimReadRejectsWrongPurposeFreshnessAndExpiredSnapshots() { new StartSessionPreAuthorizationReservationRepository.CurrentClaimResult( expired, reservationOwnerId, reservationOwnerId))); - assertThatThrownBy( - () -> - service.readCurrentClaimEvidence( - requestId, - tuple, - reservationOwnerId, - 1L, - reservationOwnerId, - 1L, - StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE)) + assertThatThrownBy(() -> + service.readCurrentClaimEvidence( + requestId, + tuple, + reservationOwnerId, + 1L, + reservationOwnerId, + 1L, + StartSessionPreAuthorizationReservationService.ReadPurpose.ISSUE)) .isInstanceOf( StartSessionPreAuthorizationReservationService.StaleReservationClaimException.class); } diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTupleTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTupleTest.java index 85c8e3a164..f7593b231a 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTupleTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionPreAuthorizationReservationTupleTest.java @@ -78,10 +78,9 @@ void rejectsMissingHumanAuthorityAndDoesNotAcceptOtherRoleAsTenantAdmin() { StartSessionOperatorAction action = action(StartSessionOperatorAction.ClientIp.absent()); SessionContext.setContext(ACTOR_ID.toString(), List.of(), Map.of(), false, null, null); - assertThatThrownBy( - () -> - StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( - "start-session-request-03", action)) + assertThatThrownBy(() -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-03", action)) .isInstanceOf(IllegalArgumentException.class); SessionContext.setContext( @@ -91,10 +90,9 @@ void rejectsMissingHumanAuthorityAndDoesNotAcceptOtherRoleAsTenantAdmin() { false, null, null); - assertThatThrownBy( - () -> - StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( - "start-session-request-03", action)) + assertThatThrownBy(() -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-03", action)) .isInstanceOf(IllegalArgumentException.class); } @@ -108,10 +106,9 @@ void rejectsInternalOrWrongTenantAuthority() { true, "logging-admin-service", "instance-1"); - assertThatThrownBy( - () -> - StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( - "start-session-request-04", action)) + assertThatThrownBy(() -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-04", action)) .isInstanceOf(IllegalArgumentException.class); SessionContext.setContext( @@ -121,10 +118,9 @@ void rejectsInternalOrWrongTenantAuthority() { false, null, null); - assertThatThrownBy( - () -> - StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( - "start-session-request-04", action)) + assertThatThrownBy(() -> + StartSessionPreAuthorizationReservationTuple.fromCurrentTenantAdmin( + "start-session-request-04", action)) .isInstanceOf(IllegalArgumentException.class); } @@ -136,14 +132,12 @@ void rejectsNonCanonicalAndUnsupportedPersistedTupleShapes() { "start-session-request-05", action(StartSessionOperatorAction.ClientIp.absent())) .canonicalJson(); - assertThatThrownBy( - () -> - StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(" " + canonicalJson)) + assertThatThrownBy(() -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson(" " + canonicalJson)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( - canonicalJson.replace("\"presence\":\"ABSENT\"", "\"presence\":\"NULL\""))) + assertThatThrownBy(() -> + StartSessionPreAuthorizationReservationTuple.fromCanonicalJson( + canonicalJson.replace("\"presence\":\"ABSENT\"", "\"presence\":\"NULL\""))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AccountAuditPeerGrpcMtlsTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AccountAuditPeerGrpcMtlsTest.java index cec5e8cc57..69284a386d 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AccountAuditPeerGrpcMtlsTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AccountAuditPeerGrpcMtlsTest.java @@ -111,15 +111,13 @@ static void createTrustedWorkloadCertificatesAndSelectProductionAuthInterceptor( .withPropertyValues( "firemud.auth.jwt-secret=" + JWT_SECRET, "firemud.auth.grpc.public-methods[0]=" + CLAIM_EVIDENCE_METHOD) - .run( - context -> { - assertThat(context).hasSingleBean(AuthTokenInterceptor.class); - assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) - .containsExactly(CLAIM_EVIDENCE_METHOD); - authInterceptor = context.getBean(AuthTokenInterceptor.class); - assertThat(authInterceptor) - .isSameAs(context.getBean("accountAuditAuthTokenInterceptor")); - }); + .run(context -> { + assertThat(context).hasSingleBean(AuthTokenInterceptor.class); + assertThat(context.getBean(GrpcAuthProperties.class).getPublicMethods()) + .containsExactly(CLAIM_EVIDENCE_METHOD); + authInterceptor = context.getBean(AuthTokenInterceptor.class); + assertThat(authInterceptor).isSameAs(context.getBean("accountAuditAuthTokenInterceptor")); + }); } @Test diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java index 9c03c0067f..9f5fa35ccf 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java @@ -304,12 +304,11 @@ void setPointerUsesSessionAccountIdAsActorPrincipal() { assertEquals(4L, result.catalogRevision()); verify(gameSessionControlPlaneClient) .setAdmissionPointer( - org.mockito.ArgumentMatchers.argThat( - request -> - request.getActorPrincipal().equals(ACCOUNT_UUID) - && request.getExpectedPointerVersion() == 3L - && request.getExpectedCatalogRevision() == 4L - && request.getPreparedVersionUpgradeId().equals("pvu-1"))); + org.mockito.ArgumentMatchers.argThat(request -> + request.getActorPrincipal().equals(ACCOUNT_UUID) + && request.getExpectedPointerVersion() == 3L + && request.getExpectedCatalogRevision() == 4L + && request.getPreparedVersionUpgradeId().equals("pvu-1"))); } @Test @@ -400,12 +399,11 @@ void executePreparedVersionCutoverUsesSessionAccountIdAsActorPrincipal() { assertEquals(4L, result.catalogRevision()); verify(gameSessionControlPlaneClient) .executePreparedVersionCutover( - org.mockito.ArgumentMatchers.argThat( - request -> - request.getActorPrincipal().equals(ACCOUNT_UUID) - && request.getPreparedVersionUpgradeId().equals("pvu-1") - && request.getExpectedPointerVersion() == 3L - && request.getExpectedCatalogRevision() == 4L)); + org.mockito.ArgumentMatchers.argThat(request -> + request.getActorPrincipal().equals(ACCOUNT_UUID) + && request.getPreparedVersionUpgradeId().equals("pvu-1") + && request.getExpectedPointerVersion() == 3L + && request.getExpectedCatalogRevision() == 4L)); } @Test @@ -518,12 +516,11 @@ void prepareVersionUpgradeReturnsDurablePreparation() { assertEquals("COMPATIBLE", result.result()); verify(gameSessionControlPlaneClient) .prepareVersionUpgrade( - org.mockito.ArgumentMatchers.argThat( - request -> - request.getTenantId().equals("2") - && request.getSourceGameInstanceId().equals("7") - && request.getTargetVersionId().equals("9") - && request.getControlPlaneRequestId().equals("req-prepare"))); + org.mockito.ArgumentMatchers.argThat(request -> + request.getTenantId().equals("2") + && request.getSourceGameInstanceId().equals("7") + && request.getTargetVersionId().equals("9") + && request.getControlPlaneRequestId().equals("req-prepare"))); } @Test @@ -560,10 +557,8 @@ void getPreparedVersionUpgradeMapsUnavailableAuthorityToServiceUnavailable() { assertEquals("prepared version-upgrade proof authority unavailable", ex.getReason()); verify(gameSessionControlPlaneClient) .getPreparedVersionUpgrade( - org.mockito.ArgumentMatchers.argThat( - request -> - request.getTenantId().equals("2") - && request.getPreparationId().equals("pvu-1"))); + org.mockito.ArgumentMatchers.argThat(request -> + request.getTenantId().equals("2") && request.getPreparationId().equals("pvu-1"))); } @Test diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java index f41f8635aa..b09233f109 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java @@ -86,31 +86,28 @@ void auditMethodsBypassJwtRequirementButOtherMethodsRemainProtected() { "firemud.auth.jwt-secret=testsecretkeytestsecretkeytest1234", "firemud.auth.grpc.public-methods[0]=logging_admin.v1.LoggingAdminService/Ping", "firemud.auth.grpc.public-methods[1]=logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence") - .run( - context -> { - assertThat(context).hasSingleBean(AuthTokenInterceptor.class); - GrpcAuthProperties properties = context.getBean(GrpcAuthProperties.class); - assertThat(properties.getPublicMethods()) - .containsExactly( - "logging_admin.v1.LoggingAdminService/Ping", - "logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence"); - AuthTokenInterceptor interceptor = context.getBean(AuthTokenInterceptor.class); - assertTrue( - passesWithoutBearer( - interceptor, "logging_admin.v1.LoggingAdminService/CreateLogEvent")); - assertTrue( - passesWithoutBearer( - interceptor, "logging_admin.v1.LoggingAdminService/ReadLogEventReceipt")); - assertTrue( - passesWithoutBearer(interceptor, "logging_admin.v1.LoggingAdminService/Ping")); - assertTrue( - passesWithoutBearer( - interceptor, - "logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence")); - assertFalse( - passesWithoutBearer( - interceptor, "logging_admin.v1.LoggingAdminService/QueryLogs")); - }); + .run(context -> { + assertThat(context).hasSingleBean(AuthTokenInterceptor.class); + GrpcAuthProperties properties = context.getBean(GrpcAuthProperties.class); + assertThat(properties.getPublicMethods()) + .containsExactly( + "logging_admin.v1.LoggingAdminService/Ping", + "logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence"); + AuthTokenInterceptor interceptor = context.getBean(AuthTokenInterceptor.class); + assertTrue( + passesWithoutBearer( + interceptor, "logging_admin.v1.LoggingAdminService/CreateLogEvent")); + assertTrue( + passesWithoutBearer( + interceptor, "logging_admin.v1.LoggingAdminService/ReadLogEventReceipt")); + assertTrue(passesWithoutBearer(interceptor, "logging_admin.v1.LoggingAdminService/Ping")); + assertTrue( + passesWithoutBearer( + interceptor, + "logging_admin.v1.StartSessionReservationEvidenceService/ReadCurrentClaimEvidence")); + assertFalse( + passesWithoutBearer(interceptor, "logging_admin.v1.LoggingAdminService/QueryLogs")); + }); } @Test diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/RemoteCommandCoordinatorServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/RemoteCommandCoordinatorServiceImplTest.java index 867d0eaa2c..0a3ce589f0 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/RemoteCommandCoordinatorServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/RemoteCommandCoordinatorServiceImplTest.java @@ -166,14 +166,13 @@ void listRemoteCommandCoordinatorsBuildsBoundedFilterRequestAndMapsRows() { request.setCommandId("cmd-123"); request.setLimit(5); when(gameSessionControlPlaneClient.listRemoteCommandCoordinators( - argThat( - grpcRequest -> - "2".equals(grpcRequest.getTenantId()) - && "7".equals(grpcRequest.getOriginGameInstanceId()) - && "target-region".equals(grpcRequest.getTargetRegionId()) - && "PENDING_REMOTE".equals(grpcRequest.getState()) - && "cmd-123".equals(grpcRequest.getCommandId()) - && grpcRequest.getLimit() == 5))) + argThat(grpcRequest -> + "2".equals(grpcRequest.getTenantId()) + && "7".equals(grpcRequest.getOriginGameInstanceId()) + && "target-region".equals(grpcRequest.getTargetRegionId()) + && "PENDING_REMOTE".equals(grpcRequest.getState()) + && "cmd-123".equals(grpcRequest.getCommandId()) + && grpcRequest.getLimit() == 5))) .thenReturn( net.firedevops.firemud.gamesession.v1.ListRemoteCommandCoordinatorsResponse.newBuilder() .addCoordinators(remoteCoordinator("2", "coord-123")) diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/RemoteFollowupResultServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/RemoteFollowupResultServiceImplTest.java index f45f737cb7..9d4d84101b 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/RemoteFollowupResultServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/RemoteFollowupResultServiceImplTest.java @@ -210,62 +210,59 @@ void listRemoteFollowupResultsBuildsCanonicalFilterRequestAndMapsRows() { request.setLimit(25); when(gameSessionControlPlaneClient.listRemoteFollowupResults( - argThat( - grpcRequest -> - "2".equals(grpcRequest.getTenantId()) - && "coord-1".equals(grpcRequest.getCoordinatorId()) - && "rf-1".equals(grpcRequest.getFollowupId()) - && "7".equals(grpcRequest.getOriginGameInstanceId()) - && "region-a".equals(grpcRequest.getOriginRegionId()) - && grpcRequest.getOriginRegionEpoch() == 3L - && "9".equals(grpcRequest.getTargetGameInstanceId()) - && "region-b".equals(grpcRequest.getTargetRegionId()) - && grpcRequest.getTargetRegionEpoch() == 4L - && "region-origin-current" - .equals(grpcRequest.getCurrentOriginRuntimeRegionId()) - && grpcRequest.getCurrentOriginRuntimeRegionEpoch() == 13L - && "7".equals(grpcRequest.getCurrentOriginRuntimeGameInstanceId()) - && "region-target-current" - .equals(grpcRequest.getCurrentTargetRuntimeRegionId()) - && grpcRequest.getCurrentTargetRuntimeRegionEpoch() == 14L - && "9".equals(grpcRequest.getCurrentTargetRuntimeGameInstanceId()) - && "REMOTE_APPLIED".equals(grpcRequest.getOutcome()) - && "script-1".equals(grpcRequest.getScriptId()) - && "plugin-1".equals(grpcRequest.getPluginId()) - && "patch-1".equals(grpcRequest.getScriptPatchVersion()) - && "plugin-v1".equals(grpcRequest.getPluginVersionId()) - && grpcRequest.getPlayableStateScope() - == PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED - && "demo".equals(grpcRequest.getWorldSlug()) - && "production".equals(grpcRequest.getRealmSlug()) - && grpcRequest.getPointerVersion() == 17L - && "RATE_LIMIT".equals(grpcRequest.getResultErrorCode()) - && "work-1".equals(grpcRequest.getAutomationWorkItemId()) - && "auto-1".equals(grpcRequest.getResultCommandId()) - && "APPLIED".equals(grpcRequest.getResultCommandExecutionOutcome()) - && "SUCCESS".equals(grpcRequest.getResultCommandGameplayResult()) - && "npc-7".equals(grpcRequest.getTargetEntityId()) - && "entity:npc-7".equals(grpcRequest.getClaimTargetAggregate()) - && "remote-followup:dispatch-1".equals(grpcRequest.getEffectKey()) - && "REMOTE_REJECTED".equals(grpcRequest.getFailureCode()) - && "trigger_script_event".equals(grpcRequest.getPayloadKind()) - && "REMOTE_FOLLOWUP".equals(grpcRequest.getOriginSourceKind()) - && "SCHEDULED".equals(grpcRequest.getOriginSourceState()) - && "onEnterRegion".equals(grpcRequest.getEventType()) - && "remote-enter-1".equals(grpcRequest.getScriptEventId()) - && "Target region rejected the remote gameplay command" - .equals(grpcRequest.getResultMessage()) - && grpcRequest.getRequiresSoloTick() - && "REMOTE_FOLLOWUP".equals(grpcRequest.getQueueSourceKind()) - && "TARGET_REGION_CLAIMED".equals(grpcRequest.getQueueSourceState()) - && grpcRequest.getQueueSourceOrdinal() == 3L - && grpcRequest.getQueueSourceDueTickId() == 55L - && grpcRequest.getQueueSourceDueAtMs() == 1700L - && "late_result_safe_to_ignore".equals(grpcRequest.getLateResultPolicy()) - && "tick-batch-7".equals(grpcRequest.getClaimedTickBatchId()) - && "dispatch-1".equals(grpcRequest.getAutomationDispatchId()) - && "cmd-1".equals(grpcRequest.getCommandId()) - && grpcRequest.getLimit() == 25))) + argThat(grpcRequest -> + "2".equals(grpcRequest.getTenantId()) + && "coord-1".equals(grpcRequest.getCoordinatorId()) + && "rf-1".equals(grpcRequest.getFollowupId()) + && "7".equals(grpcRequest.getOriginGameInstanceId()) + && "region-a".equals(grpcRequest.getOriginRegionId()) + && grpcRequest.getOriginRegionEpoch() == 3L + && "9".equals(grpcRequest.getTargetGameInstanceId()) + && "region-b".equals(grpcRequest.getTargetRegionId()) + && grpcRequest.getTargetRegionEpoch() == 4L + && "region-origin-current".equals(grpcRequest.getCurrentOriginRuntimeRegionId()) + && grpcRequest.getCurrentOriginRuntimeRegionEpoch() == 13L + && "7".equals(grpcRequest.getCurrentOriginRuntimeGameInstanceId()) + && "region-target-current".equals(grpcRequest.getCurrentTargetRuntimeRegionId()) + && grpcRequest.getCurrentTargetRuntimeRegionEpoch() == 14L + && "9".equals(grpcRequest.getCurrentTargetRuntimeGameInstanceId()) + && "REMOTE_APPLIED".equals(grpcRequest.getOutcome()) + && "script-1".equals(grpcRequest.getScriptId()) + && "plugin-1".equals(grpcRequest.getPluginId()) + && "patch-1".equals(grpcRequest.getScriptPatchVersion()) + && "plugin-v1".equals(grpcRequest.getPluginVersionId()) + && grpcRequest.getPlayableStateScope() + == PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + && "demo".equals(grpcRequest.getWorldSlug()) + && "production".equals(grpcRequest.getRealmSlug()) + && grpcRequest.getPointerVersion() == 17L + && "RATE_LIMIT".equals(grpcRequest.getResultErrorCode()) + && "work-1".equals(grpcRequest.getAutomationWorkItemId()) + && "auto-1".equals(grpcRequest.getResultCommandId()) + && "APPLIED".equals(grpcRequest.getResultCommandExecutionOutcome()) + && "SUCCESS".equals(grpcRequest.getResultCommandGameplayResult()) + && "npc-7".equals(grpcRequest.getTargetEntityId()) + && "entity:npc-7".equals(grpcRequest.getClaimTargetAggregate()) + && "remote-followup:dispatch-1".equals(grpcRequest.getEffectKey()) + && "REMOTE_REJECTED".equals(grpcRequest.getFailureCode()) + && "trigger_script_event".equals(grpcRequest.getPayloadKind()) + && "REMOTE_FOLLOWUP".equals(grpcRequest.getOriginSourceKind()) + && "SCHEDULED".equals(grpcRequest.getOriginSourceState()) + && "onEnterRegion".equals(grpcRequest.getEventType()) + && "remote-enter-1".equals(grpcRequest.getScriptEventId()) + && "Target region rejected the remote gameplay command" + .equals(grpcRequest.getResultMessage()) + && grpcRequest.getRequiresSoloTick() + && "REMOTE_FOLLOWUP".equals(grpcRequest.getQueueSourceKind()) + && "TARGET_REGION_CLAIMED".equals(grpcRequest.getQueueSourceState()) + && grpcRequest.getQueueSourceOrdinal() == 3L + && grpcRequest.getQueueSourceDueTickId() == 55L + && grpcRequest.getQueueSourceDueAtMs() == 1700L + && "late_result_safe_to_ignore".equals(grpcRequest.getLateResultPolicy()) + && "tick-batch-7".equals(grpcRequest.getClaimedTickBatchId()) + && "dispatch-1".equals(grpcRequest.getAutomationDispatchId()) + && "cmd-1".equals(grpcRequest.getCommandId()) + && grpcRequest.getLimit() == 25))) .thenReturn( ListRemoteFollowupResultsResponse.newBuilder().addResults(remoteResult("2")).build()); diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/RemoteFollowupServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/RemoteFollowupServiceImplTest.java index 0456b09210..b5cbc61a8b 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/RemoteFollowupServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/RemoteFollowupServiceImplTest.java @@ -186,61 +186,58 @@ void listRemoteFollowupsBuildsCanonicalFilterRequestAndMapsRows() { request.setFailureCode("NONE"); when(gameSessionControlPlaneClient.listRemoteFollowups( - argThat( - grpcRequest -> - "2".equals(grpcRequest.getTenantId()) - && "region-b".equals(grpcRequest.getTargetRegionId()) - && "SCHEDULED".equals(grpcRequest.getStatus()) - && "7".equals(grpcRequest.getOriginGameInstanceId()) - && "region-a".equals(grpcRequest.getOriginRegionId()) - && "9".equals(grpcRequest.getTargetGameInstanceId()) - && grpcRequest.getTargetRegionEpoch() == 4L - && "rf-1".equals(grpcRequest.getFollowupId()) - && "script-1".equals(grpcRequest.getScriptId()) - && "plugin-1".equals(grpcRequest.getPluginId()) - && "dispatch-1".equals(grpcRequest.getAutomationDispatchId()) - && "cmd-1".equals(grpcRequest.getCommandId()) - && grpcRequest.getLimit() == 25 - && grpcRequest.getOriginRegionEpoch() == 3L - && "patch-1".equals(grpcRequest.getScriptPatchVersion()) - && "plugin-v1".equals(grpcRequest.getPluginVersionId()) - && grpcRequest.getPlayableStateScope() - == PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED - && "ops".equals(grpcRequest.getWorldSlug()) - && "preview".equals(grpcRequest.getRealmSlug()) - && grpcRequest.getPointerVersion() == 29L - && "enqueue_automation_command".equals(grpcRequest.getPayloadKind()) - && "REMOTE_FOLLOWUP".equals(grpcRequest.getOriginSourceKind()) - && "work-1".equals(grpcRequest.getAutomationWorkItemId()) - && "entity-9".equals(grpcRequest.getTargetEntityId()) - && "damage:1".equals(grpcRequest.getEffectKey()) - && grpcRequest.getRequiresSoloTick() - && "onEnterRegion".equals(grpcRequest.getEventType()) - && "evt-1".equals(grpcRequest.getScriptEventId()) - && "target-cmd-1".equals(grpcRequest.getTargetCommandId()) - && "APPLIED".equals(grpcRequest.getTargetCommandExecutionOutcome()) - && "SUCCESS".equals(grpcRequest.getTargetCommandGameplayResult()) - && "91".equals(grpcRequest.getClaimedTickBatchId()) - && "LOOK".equals(grpcRequest.getRequestedCommand()) - && "TARGET_REGION_EXECUTED".equals(grpcRequest.getOriginSourceState()) - && grpcRequest.getOriginDeadlineRegionEpoch() == 3L - && grpcRequest.getOriginDeadlineTickId() == 88L - && "late_result_safe_to_ignore".equals(grpcRequest.getLateResultPolicy()) - && "entity:entity-9".equals(grpcRequest.getClaimTargetAggregate()) - && "region-origin-current" - .equals(grpcRequest.getCurrentOriginRuntimeRegionId()) - && grpcRequest.getCurrentOriginRuntimeRegionEpoch() == 13L - && "region-target-current" - .equals(grpcRequest.getCurrentTargetRuntimeRegionId()) - && grpcRequest.getCurrentTargetRuntimeRegionEpoch() == 14L - && "REMOTE_FOLLOWUP".equals(grpcRequest.getQueueSourceKind()) - && "TARGET_REGION_CLAIMED".equals(grpcRequest.getQueueSourceState()) - && grpcRequest.getQueueSourceOrdinal() == 2L - && grpcRequest.getQueueSourceDueTickId() == 55L - && grpcRequest.getQueueSourceDueAtMs() == 1700L - && "7".equals(grpcRequest.getCurrentOriginRuntimeGameInstanceId()) - && "9".equals(grpcRequest.getCurrentTargetRuntimeGameInstanceId()) - && "NONE".equals(grpcRequest.getFailureCode())))) + argThat(grpcRequest -> + "2".equals(grpcRequest.getTenantId()) + && "region-b".equals(grpcRequest.getTargetRegionId()) + && "SCHEDULED".equals(grpcRequest.getStatus()) + && "7".equals(grpcRequest.getOriginGameInstanceId()) + && "region-a".equals(grpcRequest.getOriginRegionId()) + && "9".equals(grpcRequest.getTargetGameInstanceId()) + && grpcRequest.getTargetRegionEpoch() == 4L + && "rf-1".equals(grpcRequest.getFollowupId()) + && "script-1".equals(grpcRequest.getScriptId()) + && "plugin-1".equals(grpcRequest.getPluginId()) + && "dispatch-1".equals(grpcRequest.getAutomationDispatchId()) + && "cmd-1".equals(grpcRequest.getCommandId()) + && grpcRequest.getLimit() == 25 + && grpcRequest.getOriginRegionEpoch() == 3L + && "patch-1".equals(grpcRequest.getScriptPatchVersion()) + && "plugin-v1".equals(grpcRequest.getPluginVersionId()) + && grpcRequest.getPlayableStateScope() + == PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED + && "ops".equals(grpcRequest.getWorldSlug()) + && "preview".equals(grpcRequest.getRealmSlug()) + && grpcRequest.getPointerVersion() == 29L + && "enqueue_automation_command".equals(grpcRequest.getPayloadKind()) + && "REMOTE_FOLLOWUP".equals(grpcRequest.getOriginSourceKind()) + && "work-1".equals(grpcRequest.getAutomationWorkItemId()) + && "entity-9".equals(grpcRequest.getTargetEntityId()) + && "damage:1".equals(grpcRequest.getEffectKey()) + && grpcRequest.getRequiresSoloTick() + && "onEnterRegion".equals(grpcRequest.getEventType()) + && "evt-1".equals(grpcRequest.getScriptEventId()) + && "target-cmd-1".equals(grpcRequest.getTargetCommandId()) + && "APPLIED".equals(grpcRequest.getTargetCommandExecutionOutcome()) + && "SUCCESS".equals(grpcRequest.getTargetCommandGameplayResult()) + && "91".equals(grpcRequest.getClaimedTickBatchId()) + && "LOOK".equals(grpcRequest.getRequestedCommand()) + && "TARGET_REGION_EXECUTED".equals(grpcRequest.getOriginSourceState()) + && grpcRequest.getOriginDeadlineRegionEpoch() == 3L + && grpcRequest.getOriginDeadlineTickId() == 88L + && "late_result_safe_to_ignore".equals(grpcRequest.getLateResultPolicy()) + && "entity:entity-9".equals(grpcRequest.getClaimTargetAggregate()) + && "region-origin-current".equals(grpcRequest.getCurrentOriginRuntimeRegionId()) + && grpcRequest.getCurrentOriginRuntimeRegionEpoch() == 13L + && "region-target-current".equals(grpcRequest.getCurrentTargetRuntimeRegionId()) + && grpcRequest.getCurrentTargetRuntimeRegionEpoch() == 14L + && "REMOTE_FOLLOWUP".equals(grpcRequest.getQueueSourceKind()) + && "TARGET_REGION_CLAIMED".equals(grpcRequest.getQueueSourceState()) + && grpcRequest.getQueueSourceOrdinal() == 2L + && grpcRequest.getQueueSourceDueTickId() == 55L + && grpcRequest.getQueueSourceDueAtMs() == 1700L + && "7".equals(grpcRequest.getCurrentOriginRuntimeGameInstanceId()) + && "9".equals(grpcRequest.getCurrentTargetRuntimeGameInstanceId()) + && "NONE".equals(grpcRequest.getFailureCode())))) .thenReturn( ListRemoteFollowupsResponse.newBuilder().addFollowups(remoteFollowup("2")).build()); diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcServiceTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcServiceTest.java index c503a3a8c9..b5e04adf04 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcServiceTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/StartSessionReservationEvidenceGrpcServiceTest.java @@ -192,10 +192,9 @@ void deniesMissingUnknownWrongServiceCrossNamespaceAndUnconfiguredPeersBeforeRea GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(ACCOUNT_URI).orElseThrow(); Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .run( - () -> - unconfigured.readCurrentClaimEvidence( - request(tuple, RESERVATION_OWNER_ID, 1L, issuePurpose()), observer)); + .run(() -> + unconfigured.readCurrentClaimEvidence( + request(tuple, RESERVATION_OWNER_ID, 1L, issuePurpose()), observer)); assertThat(status(observer)).isEqualTo(Status.Code.PERMISSION_DENIED); StartSessionReservationEvidenceGrpcService missingApprovalFile = @@ -431,10 +430,9 @@ public void ping(PingRequest request, StreamObserver observer) { try { ReadCurrentClaimEvidenceRequest evidenceRequest = request(tuple(REQUEST_ID)); assertThat( - transportStatus( - () -> - StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel) - .readCurrentClaimEvidence(evidenceRequest))) + transportStatus(() -> + StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel) + .readCurrentClaimEvidence(evidenceRequest))) .isEqualTo(Status.Code.PERMISSION_DENIED); Metadata invalidJwtHeader = new Metadata(); @@ -442,19 +440,16 @@ public void ping(PingRequest request, StreamObserver observer) { Metadata.Key.of("Authorization", Metadata.ASCII_STRING_MARSHALLER), "Bearer deliberately-invalid"); assertThat( - transportStatus( - () -> - StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel) - .withInterceptors( - MetadataUtils.newAttachHeadersInterceptor(invalidJwtHeader)) - .readCurrentClaimEvidence(evidenceRequest))) + transportStatus(() -> + StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel) + .withInterceptors(MetadataUtils.newAttachHeadersInterceptor(invalidJwtHeader)) + .readCurrentClaimEvidence(evidenceRequest))) .isEqualTo(Status.Code.PERMISSION_DENIED); assertThat( - transportStatus( - () -> - LoggingAdminServiceGrpc.newBlockingStub(channel) - .ping(PingRequest.getDefaultInstance()))) + transportStatus(() -> + LoggingAdminServiceGrpc.newBlockingStub(channel) + .ping(PingRequest.getDefaultInstance()))) .isEqualTo(Status.Code.UNAUTHENTICATED); verifyNoInteractions(reservationService); } finally { diff --git a/services/logging-admin-service/src/testFixtures/java/net/firedevops/firemud/loggingadmin/StartSessionReservationMutationTestFixtures.java b/services/logging-admin-service/src/testFixtures/java/net/firedevops/firemud/loggingadmin/StartSessionReservationMutationTestFixtures.java index 6f4e357b00..b3e2aeefcc 100644 --- a/services/logging-admin-service/src/testFixtures/java/net/firedevops/firemud/loggingadmin/StartSessionReservationMutationTestFixtures.java +++ b/services/logging-admin-service/src/testFixtures/java/net/firedevops/firemud/loggingadmin/StartSessionReservationMutationTestFixtures.java @@ -129,9 +129,8 @@ private static Class capabilityType(Class owner) { return Arrays.stream(owner.getDeclaredClasses()) .filter(candidate -> candidate.getSimpleName().equals(MUTATION_CAPABILITY)) .findFirst() - .orElseThrow( - () -> - new IllegalStateException("private mutation capability is missing from " + owner)); + .orElseThrow(() -> + new IllegalStateException("private mutation capability is missing from " + owner)); } private static Object instantiateCapability(Class capabilityType) { diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/controller/FriendController.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/controller/FriendController.java index 9e97006e25..2e8d4136a3 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/controller/FriendController.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/controller/FriendController.java @@ -61,14 +61,13 @@ public ResponseEntity> removeFriend( @PathVariable String friendAccountId, @RequestParam String tenantId, @RequestParam String accountId) { - return withBadRequest( - () -> { - String parsedFriendAccountId = requireFriendAccountId(friendAccountId); - AccountScope scope = requireAccountScope(tenantId, accountId); - socialAccessGuard.requireAccountAccess(scope.tenantId(), scope.accountId()); - friendService.removeFriend(scope.tenantId(), scope.accountId(), parsedFriendAccountId); - return ResponseEntity.ok(ApiResponse.success(null)); - }); + return withBadRequest(() -> { + String parsedFriendAccountId = requireFriendAccountId(friendAccountId); + AccountScope scope = requireAccountScope(tenantId, accountId); + socialAccessGuard.requireAccountAccess(scope.tenantId(), scope.accountId()); + friendService.removeFriend(scope.tenantId(), scope.accountId(), parsedFriendAccountId); + return ResponseEntity.ok(ApiResponse.success(null)); + }); } @GetMapping("/{friendAccountId}") @@ -76,45 +75,41 @@ public ResponseEntity> getFriend( @PathVariable String friendAccountId, @RequestParam String tenantId, @RequestParam String accountId) { - return withBadRequest( - () -> { - String parsedFriendAccountId = requireFriendAccountId(friendAccountId); - AccountScope scope = requireAccountScope(tenantId, accountId); - socialAccessGuard.requireAccountAccess(scope.tenantId(), scope.accountId()); - return friendService - .getFriend(scope.tenantId(), scope.accountId(), parsedFriendAccountId) - .map(dto -> ResponseEntity.ok(ApiResponse.success(dto))) - .orElseGet( - () -> - ResponseEntity.status(HttpStatus.NOT_FOUND) - .body( - ApiResponse.error( - new ErrorDetail( - "FRIEND_NOT_FOUND", - "Friend not found for accountId=" + parsedFriendAccountId)))); - }); + return withBadRequest(() -> { + String parsedFriendAccountId = requireFriendAccountId(friendAccountId); + AccountScope scope = requireAccountScope(tenantId, accountId); + socialAccessGuard.requireAccountAccess(scope.tenantId(), scope.accountId()); + return friendService + .getFriend(scope.tenantId(), scope.accountId(), parsedFriendAccountId) + .map(dto -> ResponseEntity.ok(ApiResponse.success(dto))) + .orElseGet(() -> + ResponseEntity.status(HttpStatus.NOT_FOUND) + .body( + ApiResponse.error( + new ErrorDetail( + "FRIEND_NOT_FOUND", + "Friend not found for accountId=" + parsedFriendAccountId)))); + }); } @GetMapping("/entry/{ordinal}") public ResponseEntity> getFriendByOrdinal( @PathVariable String ordinal, @RequestParam String tenantId, @RequestParam String accountId) { - return withBadRequest( - () -> { - int parsedOrdinal = requireOrdinal(ordinal); - AccountScope scope = requireAccountScope(tenantId, accountId); - socialAccessGuard.requireAccountAccess(scope.tenantId(), scope.accountId()); - return friendService - .getFriendByOrdinal(scope.tenantId(), scope.accountId(), parsedOrdinal) - .map(dto -> ResponseEntity.ok(ApiResponse.success(dto))) - .orElseGet( - () -> - ResponseEntity.status(HttpStatus.NOT_FOUND) - .body( - ApiResponse.error( - new ErrorDetail( - "FRIEND_NOT_FOUND", - "Friend not found for ordinal=" + parsedOrdinal)))); - }); + return withBadRequest(() -> { + int parsedOrdinal = requireOrdinal(ordinal); + AccountScope scope = requireAccountScope(tenantId, accountId); + socialAccessGuard.requireAccountAccess(scope.tenantId(), scope.accountId()); + return friendService + .getFriendByOrdinal(scope.tenantId(), scope.accountId(), parsedOrdinal) + .map(dto -> ResponseEntity.ok(ApiResponse.success(dto))) + .orElseGet(() -> + ResponseEntity.status(HttpStatus.NOT_FOUND) + .body( + ApiResponse.error( + new ErrorDetail( + "FRIEND_NOT_FOUND", + "Friend not found for ordinal=" + parsedOrdinal)))); + }); } @GetMapping @@ -122,49 +117,45 @@ public ResponseEntity> listFriends( @RequestParam String tenantId, @RequestParam String accountId, @RequestParam(defaultValue = "ALL") FriendRosterFilter filter) { - return withBadRequest( - () -> { - AccountScope scope = requireAccountScope(tenantId, accountId); - socialAccessGuard.requireAccountAccess(scope.tenantId(), scope.accountId()); - return ResponseEntity.ok( - ApiResponse.success( - friendService.listFriends(scope.tenantId(), scope.accountId(), filter))); - }); + return withBadRequest(() -> { + AccountScope scope = requireAccountScope(tenantId, accountId); + socialAccessGuard.requireAccountAccess(scope.tenantId(), scope.accountId()); + return ResponseEntity.ok( + ApiResponse.success( + friendService.listFriends(scope.tenantId(), scope.accountId(), filter))); + }); } @GetMapping("/summary") public ResponseEntity> getFriendRosterSummary( @RequestParam String tenantId, @RequestParam String accountId) { - return withBadRequest( - () -> { - AccountScope scope = requireAccountScope(tenantId, accountId); - socialAccessGuard.requireAccountAccess(scope.tenantId(), scope.accountId()); - return ResponseEntity.ok( - ApiResponse.success( - friendService.getFriendRosterSummary(scope.tenantId(), scope.accountId()))); - }); + return withBadRequest(() -> { + AccountScope scope = requireAccountScope(tenantId, accountId); + socialAccessGuard.requireAccountAccess(scope.tenantId(), scope.accountId()); + return ResponseEntity.ok( + ApiResponse.success( + friendService.getFriendRosterSummary(scope.tenantId(), scope.accountId()))); + }); } @DeleteMapping("/entry/{ordinal}") public ResponseEntity> removeFriendByOrdinal( @PathVariable String ordinal, @RequestParam String tenantId, @RequestParam String accountId) { - return withBadRequest( - () -> { - int parsedOrdinal = requireOrdinal(ordinal); - AccountScope scope = requireAccountScope(tenantId, accountId); - socialAccessGuard.requireAccountAccess(scope.tenantId(), scope.accountId()); - return friendService - .removeFriendByOrdinal(scope.tenantId(), scope.accountId(), parsedOrdinal) - .map(dto -> ResponseEntity.ok(ApiResponse.success(dto))) - .orElseGet( - () -> - ResponseEntity.status(HttpStatus.NOT_FOUND) - .body( - ApiResponse.error( - new ErrorDetail( - "FRIEND_NOT_FOUND", - "Friend not found for ordinal=" + parsedOrdinal)))); - }); + return withBadRequest(() -> { + int parsedOrdinal = requireOrdinal(ordinal); + AccountScope scope = requireAccountScope(tenantId, accountId); + socialAccessGuard.requireAccountAccess(scope.tenantId(), scope.accountId()); + return friendService + .removeFriendByOrdinal(scope.tenantId(), scope.accountId(), parsedOrdinal) + .map(dto -> ResponseEntity.ok(ApiResponse.success(dto))) + .orElseGet(() -> + ResponseEntity.status(HttpStatus.NOT_FOUND) + .body( + ApiResponse.error( + new ErrorDetail( + "FRIEND_NOT_FOUND", + "Friend not found for ordinal=" + parsedOrdinal)))); + }); } @GetMapping("/presence") @@ -172,31 +163,29 @@ public ResponseEntity> listFriendPresence( @RequestParam String tenantId, @RequestParam String accountId, @RequestParam(defaultValue = "ALL") FriendRosterFilter filter) { - return withBadRequest( - () -> { - AccountScope scope = requireAccountScope(tenantId, accountId); - socialAccessGuard.requireAccountAccess(scope.tenantId(), scope.accountId()); - return ResponseEntity.ok( - ApiResponse.success( - friendService.listFriendPresence(scope.tenantId(), scope.accountId(), filter))); - }); + return withBadRequest(() -> { + AccountScope scope = requireAccountScope(tenantId, accountId); + socialAccessGuard.requireAccountAccess(scope.tenantId(), scope.accountId()); + return ResponseEntity.ok( + ApiResponse.success( + friendService.listFriendPresence(scope.tenantId(), scope.accountId(), filter))); + }); } @GetMapping("/visibility") public ResponseEntity> getFriendPresencePolicy( @RequestParam String tenantId, @RequestParam String accountId) { - return withBadRequest( - () -> { - AccountScope scope = requireAccountScope(tenantId, accountId); - socialAccessGuard.requireAccountAccess(scope.tenantId(), scope.accountId()); - try { - return ResponseEntity.ok( - ApiResponse.success( - friendService.getFriendPresencePolicy(scope.tenantId(), scope.accountId()))); - } catch (IllegalStateException ex) { - return unavailable(ex); - } - }); + return withBadRequest(() -> { + AccountScope scope = requireAccountScope(tenantId, accountId); + socialAccessGuard.requireAccountAccess(scope.tenantId(), scope.accountId()); + try { + return ResponseEntity.ok( + ApiResponse.success( + friendService.getFriendPresencePolicy(scope.tenantId(), scope.accountId()))); + } catch (IllegalStateException ex) { + return unavailable(ex); + } + }); } @PutMapping("/visibility") diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogRepository.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogRepository.java index c6db12aa7a..eedff2aa6c 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogRepository.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/runtimecatalog/SocialRuntimeFamilyCatalogRepository.java @@ -46,29 +46,28 @@ public SocialRuntimeFamilyCatalogRepository( public Evidence read(Request request) { requireIndependent(request); byte[] committed = - capture.execute( - status -> { - SocialRuntimeFamilyCatalog catalog = currentCatalog(); - byte[] requestBytes = SocialRuntimeFamilyCatalogCodec.requestBytes(request); - Evidence proposed = new Evidence(request, UUID.randomUUID(), catalog); - byte[] evidenceBytes = SocialRuntimeFamilyCatalogCodec.evidenceBytes(proposed); - dsl.execute( - "INSERT INTO " - + table("social_runtime_family_catalog_snapshot") - + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," - + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)" - + " ON CONFLICT (read_request_id) DO NOTHING", - request.readRequestId(), - request.targetNamespace(), - requestBytes, - SocialRuntimeFamilyCatalog.sha256(requestBytes), - proposed.snapshotId(), - catalog.catalogEpoch(), - catalog.digest(), - evidenceBytes, - proposed.digest()); - return retained(request, catalog); - }); + capture.execute(status -> { + SocialRuntimeFamilyCatalog catalog = currentCatalog(); + byte[] requestBytes = SocialRuntimeFamilyCatalogCodec.requestBytes(request); + Evidence proposed = new Evidence(request, UUID.randomUUID(), catalog); + byte[] evidenceBytes = SocialRuntimeFamilyCatalogCodec.evidenceBytes(proposed); + dsl.execute( + "INSERT INTO " + + table("social_runtime_family_catalog_snapshot") + + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," + + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)" + + " ON CONFLICT (read_request_id) DO NOTHING", + request.readRequestId(), + request.targetNamespace(), + requestBytes, + SocialRuntimeFamilyCatalog.sha256(requestBytes), + proposed.snapshotId(), + catalog.catalogEpoch(), + catalog.digest(), + evidenceBytes, + proposed.digest()); + return retained(request, catalog); + }); Evidence result = readExact(request); if (!Arrays.equals(committed, SocialRuntimeFamilyCatalogCodec.evidenceBytes(result))) { throw new CatalogConflictException("Committed Social catalog readback changed"); @@ -79,10 +78,8 @@ public Evidence read(Request request) { /** Reads existing exact evidence only; drift or missing evidence is never empty success. */ public Evidence readExact(Request request) { requireIndependent(request); - return readback.execute( - status -> - SocialRuntimeFamilyCatalogCodec.evidenceFromStored( - retained(request, currentCatalog()))); + return readback.execute(status -> + SocialRuntimeFamilyCatalogCodec.evidenceFromStored(retained(request, currentCatalog()))); } private SocialRuntimeFamilyCatalog currentCatalog() { diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java index fa2b75e09d..e5ed4908a7 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImpl.java @@ -96,10 +96,9 @@ public ChatMessageDto sendMessage(SendMessageRequestDto request) { enforceChatPolicy(request.tenantId(), request.senderAccountId()); String filtered = profanityFilter.filter(request.content()); if (!filtered.equals(request.content())) { - runAfterCommit( - () -> - safeReportModeration( - request.tenantId(), request.senderAccountId(), "Filtered profanity")); + runAfterCommit(() -> + safeReportModeration( + request.tenantId(), request.senderAccountId(), "Filtered profanity")); } ChatMessage message = new ChatMessage(); @@ -124,21 +123,20 @@ public ChatMessageDto sendMessage(SendMessageRequestDto request) { .map(mapper::toDto) .orElseThrow(() -> ex); } - runAfterCommit( - () -> { - publishCounter.increment(); - try { - String key = historyKey(request); - ChatProperties.ChatCacheSettings settings = settingsFor(request); - - redisTemplate.opsForList().leftPush(key, saved.getContent()); - redisTemplate.expire(key, java.time.Duration.ofSeconds(settings.historyTtlSeconds())); - redisTemplate.opsForList().trim(key, 0, settings.maxMessages() - 1); - } catch (Exception e) { - redisErrorCounter.increment(); - logger.warn("Failed to publish chat message to Redis", e); - } - }); + runAfterCommit(() -> { + publishCounter.increment(); + try { + String key = historyKey(request); + ChatProperties.ChatCacheSettings settings = settingsFor(request); + + redisTemplate.opsForList().leftPush(key, saved.getContent()); + redisTemplate.expire(key, java.time.Duration.ofSeconds(settings.historyTtlSeconds())); + redisTemplate.opsForList().trim(key, 0, settings.maxMessages() - 1); + } catch (Exception e) { + redisErrorCounter.increment(); + logger.warn("Failed to publish chat message to Redis", e); + } + }); return mapper.toDto(saved); } diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java index 946b15a328..d659381a40 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImpl.java @@ -54,16 +54,15 @@ public FriendLinkDto addFriend(AddFriendRequest request) { .findFirstByTenantIdAndAccountIdAndFriendAccountIdAndStatus( request.tenantId(), request.accountId(), request.friendAccountId(), "active") .map(this::toDto) - .orElseGet( - () -> { - AccountFriendLink link = new AccountFriendLink(); - link.setTenantId(request.tenantId()); - link.setAccountId(request.accountId()); - link.setFriendAccountId(request.friendAccountId()); - link.setStatus("active"); - link.setCreatedAt(Instant.now()); - return toDto(accountFriendLinkRepository.save(link)); - }); + .orElseGet(() -> { + AccountFriendLink link = new AccountFriendLink(); + link.setTenantId(request.tenantId()); + link.setAccountId(request.accountId()); + link.setFriendAccountId(request.friendAccountId()); + link.setStatus("active"); + link.setCreatedAt(Instant.now()); + return toDto(accountFriendLinkRepository.save(link)); + }); } @Override @@ -82,9 +81,8 @@ public void removeFriend(long tenantId, String accountId, String friendAccountId public Optional getFriend( long tenantId, String accountId, String friendAccountId) { return listFriends(tenantId, accountId, FriendRosterFilter.ALL).friends().stream() - .filter( - entry -> - entry.friendAccountId() != null && entry.friendAccountId().equals(friendAccountId)) + .filter(entry -> + entry.friendAccountId() != null && entry.friendAccountId().equals(friendAccountId)) .findFirst(); } @@ -163,9 +161,8 @@ private FriendRosterSnapshot loadFriendRoster( .orElseGet(Map::of); List presenceAccountIds = friendAccountIds.stream() - .filter( - friendAccountId -> - canQueryPresence(visibilityPolicyFor(friendAccountId, visibilityPolicies))) + .filter(friendAccountId -> + canQueryPresence(visibilityPolicyFor(friendAccountId, visibilityPolicies))) .toList(); Map byAccountId = loadFriendPresenceByAccountId(tenantId, accountId, presenceAccountIds, visibilityPolicies); diff --git a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImpl.java b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImpl.java index a1ce27184c..28c7d11948 100644 --- a/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImpl.java +++ b/services/social-groups-service/src/main/java/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImpl.java @@ -57,10 +57,8 @@ public GuildDto createGuild(CreateGuildRequest request) { guild.setName(request.name()); guild.setCreatedAt(Instant.now()); Guild saved = guildRepository.save(guild); - runAfterCommit( - () -> - logLifecycle( - request.tenantId(), saved.getId(), request.ownerAccountId(), "CREATE", null)); + runAfterCommit(() -> + logLifecycle(request.tenantId(), saved.getId(), request.ownerAccountId(), "CREATE", null)); return guildMapper.toDto(saved); } @@ -102,14 +100,13 @@ public GuildMemberDto addMember(AddGuildMemberRequest request) { member.setRole(request.role()); GuildMember saved = guildMemberRepository.save(member); member.setId(saved.getId()); - runAfterCommit( - () -> - logLifecycle( - request.tenantId(), - request.guildId(), - request.accountId(), - "ADD_MEMBER", - request.role())); + runAfterCommit(() -> + logLifecycle( + request.tenantId(), + request.guildId(), + request.accountId(), + "ADD_MEMBER", + request.role())); return guildMemberMapper.toDto(member); } @@ -129,14 +126,13 @@ public GuildMemberDto updateMemberRole(UpdateGuildMemberRoleRequest request) { .orElseThrow(); member.setRole(request.role()); guildMemberRepository.save(member); - runAfterCommit( - () -> - logLifecycle( - request.tenantId(), - request.guildId(), - request.accountId(), - "UPDATE_MEMBER_ROLE", - request.role())); + runAfterCommit(() -> + logLifecycle( + request.tenantId(), + request.guildId(), + request.accountId(), + "UPDATE_MEMBER_ROLE", + request.role())); return guildMemberMapper.toDto(member); } diff --git a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java index 034bb865cc..c667b912be 100644 --- a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java +++ b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/SocialGroupsApplicationIntegrationTest.java @@ -121,17 +121,16 @@ void setUpClients() { Mockito.when( TEST_ACCOUNT_CLIENT.getPresenceVisibilityPolicies( Mockito.anyLong(), Mockito.anyCollection())) - .thenAnswer( - invocation -> { - java.util.Collection accountIds = invocation.getArgument(1); - return accountIds.stream() - .collect( - java.util.stream.Collectors.toMap( - accountId -> accountId, - ignored -> - net.firedevops.firemud.socialgroups.dto - .FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY)); - }); + .thenAnswer(invocation -> { + java.util.Collection accountIds = invocation.getArgument(1); + return accountIds.stream() + .collect( + java.util.stream.Collectors.toMap( + accountId -> accountId, + ignored -> + net.firedevops.firemud.socialgroups.dto + .FriendPresenceVisibilityPolicyValue.FRIENDS_ONLY)); + }); Mockito.when(TEST_ACCOUNT_CLIENT.getPresenceVisibilityPolicy(1L, accountUuid(2L))) .thenReturn( java.util.Optional.of( diff --git a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialAccountUuidMigrationPostgresIntegrationTest.java b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialAccountUuidMigrationPostgresIntegrationTest.java index 49de538f58..a6c52141da 100644 --- a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialAccountUuidMigrationPostgresIntegrationTest.java +++ b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialAccountUuidMigrationPostgresIntegrationTest.java @@ -180,12 +180,11 @@ void emptyLegacyFrontierConvergesAndTypedRepositoriesRoundTripCanonicalAccountUu MailMessageRepository mails = new MailMessageRepository(dsl); mails.save(mail); assertThat(mails.save(mail).getRecipientAccountId()).isEqualTo(accountUuid(2L)); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO friend_links (tenant_id, account_id, friend_account_id, status) VALUES (7, ?::uuid, ?::uuid, 'active')", - "00000000-0000-0000-0000-000000000000", - accountUuid(2L))) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO friend_links (tenant_id, account_id, friend_account_id, status) VALUES (7, ?::uuid, ?::uuid, 'active')", + "00000000-0000-0000-0000-000000000000", + accountUuid(2L))) .hasMessageContaining("ck_friend_account_uuid_non_nil"); assertThatThrownBy( () -> members.findFirstByTenantIdAndGuildIdAndAccountId(7L, guild.getId(), "2")) diff --git a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java index c769a6767d..103679f79d 100644 --- a/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/social-groups-service/src/test/java/integration/net/firedevops/firemud/socialgroups/repository/SocialRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -72,33 +72,28 @@ void configuredFlywayHistoryNameIsTheInstalledHistoryFamilyAndExactHistorySource try (Fixture f = fixture(null, history)) { var evidence = f.owner().read(request()); assertThat(evidence.catalog().families()) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo(history); - assertThat(family.freshDisposition()) - .isEqualTo(FreshDisposition.MIGRATION_HISTORY_ONLY); - }); + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo(history); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.MIGRATION_HISTORY_ONLY); + }); assertThat(evidence.catalog().schemaFacts()) - .anySatisfy( - fact -> { - assertThat(fact.kind()).isEqualTo(FactKind.TABLE); - assertThat(fact.identity()).isEqualTo(history); - }) - .anySatisfy( - fact -> { - assertThat(fact.kind()).isEqualTo(FactKind.MIGRATION); - assertThat(fact.identity()).isEqualTo("catalog-installation:1004"); - }) - .anySatisfy( - fact -> { - assertThat(fact.kind()).isEqualTo(FactKind.MIGRATION); - assertThat(fact.identity()).isEqualTo("catalog-installation:1005"); - }) - .anySatisfy( - fact -> { - assertThat(fact.kind()).isEqualTo(FactKind.MIGRATION); - assertThat(fact.identity()).isEqualTo("catalog-installation:1006"); - }); + .anySatisfy(fact -> { + assertThat(fact.kind()).isEqualTo(FactKind.TABLE); + assertThat(fact.identity()).isEqualTo(history); + }) + .anySatisfy(fact -> { + assertThat(fact.kind()).isEqualTo(FactKind.MIGRATION); + assertThat(fact.identity()).isEqualTo("catalog-installation:1004"); + }) + .anySatisfy(fact -> { + assertThat(fact.kind()).isEqualTo(FactKind.MIGRATION); + assertThat(fact.identity()).isEqualTo("catalog-installation:1005"); + }) + .anySatisfy(fact -> { + assertThat(fact.kind()).isEqualTo(FactKind.MIGRATION); + assertThat(fact.identity()).isEqualTo("catalog-installation:1006"); + }); assertThat(f.owner().readExact(evidence.request())).isEqualTo(evidence); assertThat( f.dsl @@ -137,36 +132,31 @@ void actualCombinedSocialSagaCensusClassifiesEveryInstalledTableWithoutRowInfere .isEqualTo( catalog.schemaFacts().stream().filter(fact -> fact.kind() == FactKind.TABLE).count()); assertThat(catalog.families()) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo("account_friend_links"); - assertThat(family.freshDisposition()) - .isEqualTo(FreshDisposition.ACCOUNT_PAIR_SCOPE_DRIFT); - }) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo("guild_storage_items"); - assertThat(family.freshDisposition()) - .isEqualTo(FreshDisposition.ENTITY_VALUE_OWNERSHIP_DRIFT_BLOCKING); - assertThat(family.targetOwner()) - .isEqualTo(SocialRuntimeFamilyCatalog.TargetOwner.ENTITY_MANAGEMENT_SERVICE); - }) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo("saga_instance"); - assertThat(family.freshDisposition()) - .isEqualTo(FreshDisposition.SAGA_ADOPTER_UNRESOLVED); - }) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo("chat_messages.effect_id"); - assertThat(family.role()).isEqualTo(SocialRuntimeFamilyCatalog.Role.EFFECT_REPLAY); - }); + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo("account_friend_links"); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.ACCOUNT_PAIR_SCOPE_DRIFT); + }) + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo("guild_storage_items"); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.ENTITY_VALUE_OWNERSHIP_DRIFT_BLOCKING); + assertThat(family.targetOwner()) + .isEqualTo(SocialRuntimeFamilyCatalog.TargetOwner.ENTITY_MANAGEMENT_SERVICE); + }) + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo("saga_instance"); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.SAGA_ADOPTER_UNRESOLVED); + }) + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo("chat_messages.effect_id"); + assertThat(family.role()).isEqualTo(SocialRuntimeFamilyCatalog.Role.EFFECT_REPLAY); + }); assertThat(catalog.families()) - .noneMatch( - family -> - family.familyId().equals("guild_storage_items.item_name") - || family.familyId().equals("guild_storage_items.quantity")); + .noneMatch(family -> + family.familyId().equals("guild_storage_items.item_name") + || family.familyId().equals("guild_storage_items.quantity")); assertThat(catalog.unimplementedContracts()) .containsExactly( SocialRuntimeFamilyCatalog.ContractGap.CHAT_RESTRICTION_AND_REVISION, @@ -276,10 +266,9 @@ void forwardMigrationRetainsPopulatedSocialSagaRowsAndEveryPriorHistoryRow() thr var catalog = f.owner().read(request()).catalog(); assertThat(catalog.catalogEpoch()).isEqualTo(3); assertThat(catalog.families()) - .anySatisfy( - family -> - assertThat(family.freshDisposition()) - .isEqualTo(FreshDisposition.ENTITY_VALUE_OWNERSHIP_DRIFT_BLOCKING)); + .anySatisfy(family -> + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.ENTITY_VALUE_OWNERSHIP_DRIFT_BLOCKING)); assertThat(f.retainedRows()).isEqualTo(rowsBefore); assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(3); assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(1); @@ -410,22 +399,21 @@ void changedClassificationMigrationHistoryOrUnsuccessfulInstallationRefusesOldSo f.dsl.execute("UPDATE " + f.history + " SET success=false WHERE version='1004'"); assertThatThrownBy(() -> f.owner().read(request())) .hasMessageContaining("No durable Social catalog epoch"); - assertThatThrownBy( - () -> - f.dsl.execute( - "INSERT INTO social_runtime_family_catalog_snapshot" - + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," - + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest)" - + " VALUES (?,?,?,?,?,?,?,?,?)", - proposalRequest.readRequestId(), - proposalRequest.targetNamespace(), - requestBytes, - SocialRuntimeFamilyCatalog.sha256(requestBytes), - proposal.snapshotId(), - proposal.catalog().catalogEpoch(), - proposal.catalog().digest(), - evidenceBytes, - proposal.digest())) + assertThatThrownBy(() -> + f.dsl.execute( + "INSERT INTO social_runtime_family_catalog_snapshot" + + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," + + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest)" + + " VALUES (?,?,?,?,?,?,?,?,?)", + proposalRequest.readRequestId(), + proposalRequest.targetNamespace(), + requestBytes, + SocialRuntimeFamilyCatalog.sha256(requestBytes), + proposal.snapshotId(), + proposal.catalog().catalogEpoch(), + proposal.catalog().digest(), + evidenceBytes, + proposal.digest())) .hasMessageContaining("Social schema/classification changed"); assertThat(f.count("social_runtime_family_catalog_snapshot")).isEqualTo(1); } @@ -448,17 +436,15 @@ void immutableMetadataAndSnapshotsRefuseMutationAndIncorrectEpochSeals() throws assertThatThrownBy( () -> f.dsl.execute("UPDATE social_runtime_family_catalog_epoch SET catalog_epoch=2")) .hasMessageContaining("immutable"); - assertThatThrownBy( - () -> - f.dsl.execute( - "UPDATE social_runtime_family_classification SET fresh_disposition='CATALOG_ONLY'" - + " WHERE family_id='account_friend_links'")) + assertThatThrownBy(() -> + f.dsl.execute( + "UPDATE social_runtime_family_classification SET fresh_disposition='CATALOG_ONLY'" + + " WHERE family_id='account_friend_links'")) .hasMessageContaining("immutable"); - assertThatThrownBy( - () -> - f.dsl.execute( - "INSERT INTO social_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 4,catalog_bytes,catalog_digest FROM social_runtime_family_catalog_epoch WHERE catalog_epoch=3")) + assertThatThrownBy(() -> + f.dsl.execute( + "INSERT INTO social_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" + + " SELECT 4,catalog_bytes,catalog_digest FROM social_runtime_family_catalog_epoch WHERE catalog_epoch=3")) .hasMessageContaining("exact classified installed schema"); assertThat(f.count("social_runtime_family_catalog_epoch")).isEqualTo(3); } @@ -478,10 +464,9 @@ void actualProducerReturnsCompleteCorrelatedEvidenceWithoutCallerContextOrRuntim try { Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .run( - () -> - service.readSocialRuntimeFamilyCatalog( - SocialRuntimeFamilyCatalogCodec.toRequest(read), collector)); + .run(() -> + service.readSocialRuntimeFamilyCatalog( + SocialRuntimeFamilyCatalogCodec.toRequest(read), collector)); } finally { SessionContext.clear(); } @@ -511,21 +496,20 @@ void viewSecurityOptionsInvalidateReadRetryAndFreshCaptureWithoutChangingRetaine var original = f.owner().read(read); assertThat(original.catalog().catalogEpoch()).isEqualTo(3); assertThat(original.catalog().schemaFacts()) - .anySatisfy( - fact -> { - assertThat(fact.kind()).isEqualTo(FactKind.VIEW); - assertThat(fact.identity()).isEqualTo("catalog_security_probe"); - assertThat(fact.definitionDigest()) - .isEqualTo( - f.dsl - .fetchSingle( - "SELECT 'sha256:'||encode(sha256(convert_to(" - + "jsonb_build_array(pg_get_viewdef(c.oid,true),c.reloptions)::text,'UTF8')),'hex')" - + " FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace" - + " WHERE n.nspname=? AND c.relname='catalog_security_probe'", - f.schema) - .get(0, String.class)); - }); + .anySatisfy(fact -> { + assertThat(fact.kind()).isEqualTo(FactKind.VIEW); + assertThat(fact.identity()).isEqualTo("catalog_security_probe"); + assertThat(fact.definitionDigest()) + .isEqualTo( + f.dsl + .fetchSingle( + "SELECT 'sha256:'||encode(sha256(convert_to(" + + "jsonb_build_array(pg_get_viewdef(c.oid,true),c.reloptions)::text,'UTF8')),'hex')" + + " FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace" + + " WHERE n.nspname=? AND c.relname='catalog_security_probe'", + f.schema) + .get(0, String.class)); + }); assertThat(f.owner().read(read)).isEqualTo(original); assertThat(f.owner().readExact(read)).isEqualTo(original); String definition = @@ -603,15 +587,14 @@ void catalogViewOptionsUpgradeRetainsV1004DataHistoryEpochAndSnapshot() throws E ? "V1004__social_owner_runtime_family_catalog.sql" : "V1005__social_catalog_view_options.sql"; assertThat(current.catalog().schemaFacts()) - .anySatisfy( - fact -> { - assertThat(fact.kind()).isEqualTo(FactKind.MIGRATION); - assertThat(fact.identity()).isEqualTo("catalog-installation:" + version); - assertThat(fact.definitionDigest()) - .isEqualTo( - SocialRuntimeFamilyCatalog.sha256( - script.getBytes(java.nio.charset.StandardCharsets.UTF_8))); - }); + .anySatisfy(fact -> { + assertThat(fact.kind()).isEqualTo(FactKind.MIGRATION); + assertThat(fact.identity()).isEqualTo("catalog-installation:" + version); + assertThat(fact.definitionDigest()) + .isEqualTo( + SocialRuntimeFamilyCatalog.sha256( + script.getBytes(java.nio.charset.StandardCharsets.UTF_8))); + }); } flyway(f.source, f.schema, f.history, "1005").validate(); } @@ -693,10 +676,8 @@ void poisonedFramesWithCorrectIndependentDigestsRefuseWithoutConsumingRequestIde String insertedNamespace = namespace; String retained = f.catalogRows("social_runtime_family_catalog_snapshot"); // Each forged frame gets its own correct digest; a hash-only constraint cannot reject it. - assertThatThrownBy( - () -> - f.insertSnapshot( - proposal, insertedNamespace, insertedRequest, insertedEvidence)) + assertThatThrownBy(() -> + f.insertSnapshot(proposal, insertedNamespace, insertedRequest, insertedEvidence)) .as(vector) .hasMessageContaining("complete exact request and evidence"); assertThat(f.catalogRows("social_runtime_family_catalog_snapshot")).isEqualTo(retained); @@ -758,11 +739,10 @@ void exactFramesUpgradeRetainsV1005RowsHistoryEpochsAndSnapshot() throws Excepti .toList()) .contains( "catalog-installation:1004", "catalog-installation:1005", "catalog-installation:1006") - .noneMatch( - identity -> - identity.contains(":1004:") - || identity.contains(":1005:") - || identity.contains(":1006:")); + .noneMatch(identity -> + identity.contains(":1004:") + || identity.contains(":1005:") + || identity.contains(":1006:")); for (var marker : Map.of( "1004", "V1004__social_owner_runtime_family_catalog.sql", @@ -770,15 +750,14 @@ void exactFramesUpgradeRetainsV1005RowsHistoryEpochsAndSnapshot() throws Excepti "1006", "V1006__social_catalog_snapshot_exact_frames.sql") .entrySet()) { assertThat(current.catalog().schemaFacts()) - .anySatisfy( - fact -> { - assertThat(fact.kind()).isEqualTo(FactKind.MIGRATION); - assertThat(fact.identity()).isEqualTo("catalog-installation:" + marker.getKey()); - assertThat(fact.definitionDigest()) - .isEqualTo( - SocialRuntimeFamilyCatalog.sha256( - marker.getValue().getBytes(java.nio.charset.StandardCharsets.UTF_8))); - }); + .anySatisfy(fact -> { + assertThat(fact.kind()).isEqualTo(FactKind.MIGRATION); + assertThat(fact.identity()).isEqualTo("catalog-installation:" + marker.getKey()); + assertThat(fact.definitionDigest()) + .isEqualTo( + SocialRuntimeFamilyCatalog.sha256( + marker.getValue().getBytes(java.nio.charset.StandardCharsets.UTF_8))); + }); } flyway(f.source, f.schema, f.history, null).validate(); } diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/AccountClientTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/AccountClientTest.java index 255cd39820..9571d4ddcf 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/AccountClientTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/client/AccountClientTest.java @@ -76,21 +76,19 @@ void batchesPresenceVisibilityPolicyReadsAtTheAccountServiceLimit() throws Excep mock(AccountServiceGrpc.AccountServiceBlockingStub.class); when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); when(stub.listPresenceVisibilityPolicies(any())) - .thenAnswer( - invocation -> { - ListPresenceVisibilityPoliciesRequest request = invocation.getArgument(0); - return ListPresenceVisibilityPoliciesResponse.newBuilder() - .addAllPolicies( - request.getAccountIdsList().stream() - .map( - accountId -> - PresenceVisibilityPolicyEntry.newBuilder() - .setAccountId(accountId) - .setPolicy("FRIENDS_ONLY") - .build()) - .toList()) - .build(); - }); + .thenAnswer(invocation -> { + ListPresenceVisibilityPoliciesRequest request = invocation.getArgument(0); + return ListPresenceVisibilityPoliciesResponse.newBuilder() + .addAllPolicies( + request.getAccountIdsList().stream() + .map(accountId -> + PresenceVisibilityPolicyEntry.newBuilder() + .setAccountId(accountId) + .setPolicy("FRIENDS_ONLY") + .build()) + .toList()) + .build(); + }); AccountClient client = newClient(stub); List accountIds = LongStream.rangeClosed(1L, 101L).mapToObj(AccountUuidFixtures::accountUuid).toList(); @@ -354,22 +352,20 @@ void laterPolicyBatchFailureRedactsEarlierSuccessfulBatch() throws Exception { when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); AtomicInteger calls = new AtomicInteger(); when(stub.listPresenceVisibilityPolicies(any())) - .thenAnswer( - invocation -> { - if (calls.getAndIncrement() == 0) { - ListPresenceVisibilityPoliciesRequest request = invocation.getArgument(0); - return ListPresenceVisibilityPoliciesResponse.newBuilder() - .addAllPolicies( - request.getAccountIdsList().stream() - .map(accountId -> policyEntry(accountId, "FRIENDS_ONLY")) - .toList()) - .build(); - } - return ListPresenceVisibilityPoliciesResponse.newBuilder() - .setError( - ErrorDetail.newBuilder().setCode("UNAVAILABLE").setMessage("Retry later")) - .build(); - }); + .thenAnswer(invocation -> { + if (calls.getAndIncrement() == 0) { + ListPresenceVisibilityPoliciesRequest request = invocation.getArgument(0); + return ListPresenceVisibilityPoliciesResponse.newBuilder() + .addAllPolicies( + request.getAccountIdsList().stream() + .map(accountId -> policyEntry(accountId, "FRIENDS_ONLY")) + .toList()) + .build(); + } + return ListPresenceVisibilityPoliciesResponse.newBuilder() + .setError(ErrorDetail.newBuilder().setCode("UNAVAILABLE").setMessage("Retry later")) + .build(); + }); AccountClient client = newClient(stub); assertThat( @@ -417,11 +413,10 @@ void uuidProfileResponseRemainsReadableWithCanonicalRequestSelectors() throws Ex ArgumentCaptor.forClass(net.firedevops.firemud.account.v1.GetProfileRequest.class); verify(stub, times(2)).getProfile(reads.capture()); assertThat(reads.getAllValues()) - .allSatisfy( - request -> { - assertThat(request.getTenantId()).isEqualTo("11"); - assertThat(request.getAccountId()).isEqualTo(accountUuid(2L)); - }); + .allSatisfy(request -> { + assertThat(request.getTenantId()).isEqualTo("11"); + assertThat(request.getAccountId()).isEqualTo(accountUuid(2L)); + }); ArgumentCaptor update = ArgumentCaptor.forClass(net.firedevops.firemud.account.v1.UpdateProfileRequest.class); verify(stub).updateProfile(update.capture()); diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java index 23ad67b6b2..ad46e356e2 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/ChatServiceImplTest.java @@ -71,12 +71,11 @@ void setup() { props); service.init(); when(repository.save(any(ChatMessage.class))) - .thenAnswer( - inv -> { - ChatMessage m = inv.getArgument(0); - m.setId(1L); - return m; - }); + .thenAnswer(inv -> { + ChatMessage m = inv.getArgument(0); + m.setId(1L); + return m; + }); } @Test diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java index f6fe1ceab5..a31a236265 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/FriendServiceImplTest.java @@ -45,11 +45,10 @@ void setUp() { gameSessionClient = Mockito.mock(GameSessionClient.class); accountClient = Mockito.mock(AccountClient.class); when(accountClient.getPresenceVisibilityPolicies(anyLong(), anyCollection())) - .thenAnswer( - invocation -> { - Collection accountIds = invocation.getArgument(1); - return friendsOnlyPolicies(accountIds); - }); + .thenAnswer(invocation -> { + Collection accountIds = invocation.getArgument(1); + return friendsOnlyPolicies(accountIds); + }); service = new FriendServiceImpl(accountRepository, gameSessionClient, accountClient); } @@ -69,12 +68,11 @@ void addFriendCreatesAccountScopedLink() { 11L, accountUuid(2L), accountUuid(3L), "active")) .thenReturn(java.util.Optional.empty()); when(accountRepository.save(any(AccountFriendLink.class))) - .thenAnswer( - invocation -> { - AccountFriendLink link = invocation.getArgument(0); - link.setId(7L); - return link; - }); + .thenAnswer(invocation -> { + AccountFriendLink link = invocation.getArgument(0); + link.setId(7L); + return link; + }); FriendLinkDto result = service.addFriend(request); diff --git a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImplTest.java b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImplTest.java index 073535f20b..ce114ad808 100644 --- a/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImplTest.java +++ b/services/social-groups-service/src/test/java/unit/net/firedevops/firemud/socialgroups/service/impl/GuildServiceImplTest.java @@ -163,13 +163,11 @@ void throwingLifecycleAppenderCannotFailAlreadyCommittedMutation() { performLifecycle("ADD_MEMBER"); verify(memberRepository).save(any(GuildMember.class)); org.junit.jupiter.api.Assertions.assertFalse(attempted.get()); - org.junit.jupiter.api.Assertions.assertDoesNotThrow( - () -> - org.springframework.transaction.support.TransactionSynchronizationManager - .getSynchronizations() - .forEach( - org.springframework.transaction.support.TransactionSynchronization - ::afterCommit)); + org.junit.jupiter.api.Assertions.assertDoesNotThrow(() -> + org.springframework.transaction.support.TransactionSynchronizationManager + .getSynchronizations() + .forEach( + org.springframework.transaction.support.TransactionSynchronization::afterCommit)); org.junit.jupiter.api.Assertions.assertTrue(attempted.get()); } finally { org.springframework.transaction.support.TransactionSynchronizationManager @@ -183,12 +181,11 @@ private void performLifecycle(String action) { switch (action) { case "CREATE" -> { when(guildRepository.save(any(Guild.class))) - .thenAnswer( - invocation -> { - Guild guild = invocation.getArgument(0); - guild.setId(2L); - return guild; - }); + .thenAnswer(invocation -> { + Guild guild = invocation.getArgument(0); + guild.setId(2L); + return guild; + }); service.createGuild(new CreateGuildRequest(1L, accountUuid(3L), "guild")); } case "ADD_MEMBER" -> { diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListener.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListener.java index a378b2b591..375c9f6ac2 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListener.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListener.java @@ -121,12 +121,11 @@ private void scheduleProfileExpiry() { } long delayMillis = Math.max(1L, untilExpiry.toMillis()); expiryExecutor = - Executors.newSingleThreadScheduledExecutor( - runnable -> { - Thread thread = new Thread(runnable, "tcp-proxy-trust-profile-expiry"); - thread.setDaemon(true); - return thread; - }); + Executors.newSingleThreadScheduledExecutor(runnable -> { + Thread thread = new Thread(runnable, "tcp-proxy-trust-profile-expiry"); + thread.setDaemon(true); + return thread; + }); expiryTask = expiryExecutor.schedule( () -> { diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/controller/GatewayController.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/controller/GatewayController.java index 336dd6d182..caace7818b 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/controller/GatewayController.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/controller/GatewayController.java @@ -37,10 +37,9 @@ public Mono>> upsert(@RequestBody Gatew public Mono>> remove(@PathVariable String routeId) { return routeService .remove(routeId) - .map( - removed -> - removed - ? ResponseEntity.ok(ApiResponse.success("removed")) - : ResponseEntity.ok(ApiResponse.success("notFound"))); + .map(removed -> + removed + ? ResponseEntity.ok(ApiResponse.success("removed")) + : ResponseEntity.ok(ApiResponse.success("notFound"))); } } diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilter.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilter.java index 4a0d2b9135..9d1f992247 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilter.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/HeaderTrustFilter.java @@ -127,42 +127,38 @@ public Mono filter(ServerWebExchange exchange, WebFilterChain chain) { ServerWebExchange mutated = exchange .mutate() - .request( - request -> - request.headers( - headers -> { - stripGatewayOwnedHeaders(headers, isGameplayRoute); - - if (canonicalLocale != null) { - headers.set(HDR_FIREMUD_LOCALE, canonicalLocale); - } - - if (canonicalClientIp != null) { - headers.set(HDR_CLIENT_IP, canonicalClientIp); - } - - if (trustedTcpProxy) { - if (incomingProxyConnectionId != null - && !incomingProxyConnectionId.isBlank()) { - headers.set(HDR_PROXY_CONNECTION_ID, incomingProxyConnectionId); - } - if (incomingProxyGameInstanceId != null - && !incomingProxyGameInstanceId.isBlank()) { - headers.set(HDR_GAME_INSTANCE_ID, incomingProxyGameInstanceId); - } - if (incomingProxyTenantId != null && !incomingProxyTenantId.isBlank()) { - headers.set(HDR_TENANT_ID, incomingProxyTenantId); - } - if (isSessionRoute) { - if (canonicalRoutingBundle != null) { - headers.set(HDR_WORLD_SLUG, canonicalRoutingBundle.worldSlug()); - headers.set(HDR_REALM_SLUG, canonicalRoutingBundle.realmSlug()); - headers.set( - HDR_POINTER_VERSION, canonicalRoutingBundle.pointerVersion()); - } - } - } - })) + .request(request -> + request.headers(headers -> { + stripGatewayOwnedHeaders(headers, isGameplayRoute); + + if (canonicalLocale != null) { + headers.set(HDR_FIREMUD_LOCALE, canonicalLocale); + } + + if (canonicalClientIp != null) { + headers.set(HDR_CLIENT_IP, canonicalClientIp); + } + + if (trustedTcpProxy) { + if (incomingProxyConnectionId != null && !incomingProxyConnectionId.isBlank()) { + headers.set(HDR_PROXY_CONNECTION_ID, incomingProxyConnectionId); + } + if (incomingProxyGameInstanceId != null + && !incomingProxyGameInstanceId.isBlank()) { + headers.set(HDR_GAME_INSTANCE_ID, incomingProxyGameInstanceId); + } + if (incomingProxyTenantId != null && !incomingProxyTenantId.isBlank()) { + headers.set(HDR_TENANT_ID, incomingProxyTenantId); + } + if (isSessionRoute) { + if (canonicalRoutingBundle != null) { + headers.set(HDR_WORLD_SLUG, canonicalRoutingBundle.worldSlug()); + headers.set(HDR_REALM_SLUG, canonicalRoutingBundle.realmSlug()); + headers.set(HDR_POINTER_VERSION, canonicalRoutingBundle.pointerVersion()); + } + } + } + })) .build(); return chain.filter(mutated); @@ -235,9 +231,8 @@ private void stripGatewayOwnedHeaders( List.copyOf(headers.headerNames()).stream() .filter( name -> name.regionMatches(true, 0, HDR_FIREMUD_PREFIX, 0, HDR_FIREMUD_PREFIX.length())) - .filter( - name -> - !preserveGameplayConnectTokenCarrier || !name.equalsIgnoreCase(HDR_CONNECT_TOKEN)) + .filter(name -> + !preserveGameplayConnectTokenCarrier || !name.equalsIgnoreCase(HDR_CONNECT_TOKEN)) .forEach(headers::remove); headers.remove(HDR_CLIENT_IP); diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/service/impl/GatewayManagementGrpcService.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/service/impl/GatewayManagementGrpcService.java index ef4c96179e..ac05f9bd1b 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/service/impl/GatewayManagementGrpcService.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/service/impl/GatewayManagementGrpcService.java @@ -65,22 +65,20 @@ public void upsertRoute( } buildUpsertRouteResponse(request) .toFuture() - .whenComplete( - (response, error) -> { - if (error != null) { - responseObserver.onNext( - UpsertRouteResponse.newBuilder() - .setSuccess(false) - .setError( - GrpcAppErrors.internal( - meterRegistry, logger, "UpsertRoute", unwrap(error))) - .build()); - responseObserver.onCompleted(); - return; - } - responseObserver.onNext(response); - responseObserver.onCompleted(); - }); + .whenComplete((response, error) -> { + if (error != null) { + responseObserver.onNext( + UpsertRouteResponse.newBuilder() + .setSuccess(false) + .setError( + GrpcAppErrors.internal(meterRegistry, logger, "UpsertRoute", unwrap(error))) + .build()); + responseObserver.onCompleted(); + return; + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + }); } @Override @@ -102,92 +100,84 @@ public void removeRoute( } buildRemoveRouteResponse(request) .toFuture() - .whenComplete( - (response, error) -> { - if (error != null) { - responseObserver.onNext( - RemoveRouteResponse.newBuilder() - .setSuccess(false) - .setError( - GrpcAppErrors.internal( - meterRegistry, logger, "RemoveRoute", unwrap(error))) - .build()); - responseObserver.onCompleted(); - return; - } - responseObserver.onNext(response); - responseObserver.onCompleted(); - }); - } - - private Mono buildUpsertRouteResponse(UpsertRouteRequest request) { - return Mono.defer( - () -> { - if (request.getRouteId().isBlank() || request.getUri().isBlank()) { - return Mono.just( - UpsertRouteResponse.newBuilder() + .whenComplete((response, error) -> { + if (error != null) { + responseObserver.onNext( + RemoveRouteResponse.newBuilder() .setSuccess(false) .setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "UpsertRoute", - "INVALID_ARGUMENT", - "routeId and uri are required")) + GrpcAppErrors.internal(meterRegistry, logger, "RemoveRoute", unwrap(error))) .build()); + responseObserver.onCompleted(); + return; } - GatewayRoute route = - new GatewayRoute( - request.getRouteId(), - request.getUri(), - request.getPredicatesList(), - request.getFiltersList()); - return routeService - .upsert(route) - .map(ignored -> UpsertRouteResponse.newBuilder().setSuccess(true).build()) - .onErrorResume( - IllegalArgumentException.class, - ex -> - Mono.just( - UpsertRouteResponse.newBuilder() - .setSuccess(false) - .setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "UpsertRoute", - "INVALID_ARGUMENT", - ex.getMessage())) - .build())) - .onErrorResume( - Exception.class, - ex -> - Mono.just( - UpsertRouteResponse.newBuilder() - .setSuccess(false) - .setError( - GrpcAppErrors.internal(meterRegistry, logger, "UpsertRoute", ex)) - .build())); + responseObserver.onNext(response); + responseObserver.onCompleted(); }); } + private Mono buildUpsertRouteResponse(UpsertRouteRequest request) { + return Mono.defer(() -> { + if (request.getRouteId().isBlank() || request.getUri().isBlank()) { + return Mono.just( + UpsertRouteResponse.newBuilder() + .setSuccess(false) + .setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "UpsertRoute", + "INVALID_ARGUMENT", + "routeId and uri are required")) + .build()); + } + GatewayRoute route = + new GatewayRoute( + request.getRouteId(), + request.getUri(), + request.getPredicatesList(), + request.getFiltersList()); + return routeService + .upsert(route) + .map(ignored -> UpsertRouteResponse.newBuilder().setSuccess(true).build()) + .onErrorResume( + IllegalArgumentException.class, + ex -> + Mono.just( + UpsertRouteResponse.newBuilder() + .setSuccess(false) + .setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "UpsertRoute", + "INVALID_ARGUMENT", + ex.getMessage())) + .build())) + .onErrorResume( + Exception.class, + ex -> + Mono.just( + UpsertRouteResponse.newBuilder() + .setSuccess(false) + .setError( + GrpcAppErrors.internal(meterRegistry, logger, "UpsertRoute", ex)) + .build())); + }); + } + private Mono buildRemoveRouteResponse(RemoveRouteRequest request) { return routeService .remove(request.getRouteId()) - .map( - removed -> - removed - ? RemoveRouteResponse.newBuilder().setSuccess(true).build() - : RemoveRouteResponse.newBuilder() - .setSuccess(false) - .setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "RemoveRoute", - "NOT_FOUND", - "route not found")) - .build()) + .map(removed -> + removed + ? RemoveRouteResponse.newBuilder().setSuccess(true).build() + : RemoveRouteResponse.newBuilder() + .setSuccess(false) + .setError( + GrpcAppErrors.error( + meterRegistry, logger, "RemoveRoute", "NOT_FOUND", "route not found")) + .build()) .onErrorResume( IllegalArgumentException.class, ex -> diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/service/impl/GatewayRouteServiceImpl.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/service/impl/GatewayRouteServiceImpl.java index 3166fc041e..03ca4c729b 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/service/impl/GatewayRouteServiceImpl.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/service/impl/GatewayRouteServiceImpl.java @@ -54,12 +54,11 @@ public Mono upsert(GatewayRoute route) { .save(Mono.just(definition)) .doOnSuccess(ignored -> publisher.publishEvent(new RefreshRoutesEvent(this))) .then( - Mono.fromSupplier( - () -> { - routes.put(route.routeId(), route); - logger.info("Upserted route {} -> {}", route.routeId(), route.uri()); - return route; - })); + Mono.fromSupplier(() -> { + routes.put(route.routeId(), route); + logger.info("Upserted route {} -> {}", route.routeId(), route.uri()); + return route; + })); } @Override @@ -69,19 +68,17 @@ public Mono remove(String routeId) { .delete(Mono.just(routeId)) .doOnSuccess(ignored -> publisher.publishEvent(new RefreshRoutesEvent(this))) .thenReturn(true) - .doOnNext( - removed -> { - routes.remove(routeId); - logger.info("Removed route {}", routeId); - }) + .doOnNext(removed -> { + routes.remove(routeId); + logger.info("Removed route {}", routeId); + }) .onErrorResume( NotFoundException.class, ex -> - Mono.fromSupplier( - () -> { - routes.remove(routeId); - logger.info("Route {} not found", routeId); - return false; - })); + Mono.fromSupplier(() -> { + routes.remove(routeId); + logger.info("Route {} not found", routeId); + return false; + })); } } diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java index b1d0e4d719..cee1d1e7c0 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClient.java @@ -109,24 +109,21 @@ void reload() throws IOException { .build(); HttpClient http = HttpClient.newConnection() - .secure( - spec -> - spec.sslContext(context) - .handlerConfigurator( - handler -> { - SSLParameters parameters = handler.engine().getSSLParameters(); - parameters.setEndpointIdentificationAlgorithm("HTTPS"); - handler.engine().setSSLParameters(parameters); - })) - .doOnRequest( - (request, connection) -> { - SslHandler handler = connection.channel().pipeline().get(SslHandler.class); - if (handler == null - || GrpcPeerIdentity.fromSslSession(handler.engine().getSession()) - .filter(identity -> expectedPeer.equals(identity.uri())) - .isEmpty()) - throw new IllegalStateException("Authenticated Game Session peer required"); - }); + .secure(spec -> + spec.sslContext(context) + .handlerConfigurator(handler -> { + SSLParameters parameters = handler.engine().getSSLParameters(); + parameters.setEndpointIdentificationAlgorithm("HTTPS"); + handler.engine().setSSLParameters(parameters); + })) + .doOnRequest((request, connection) -> { + SslHandler handler = connection.channel().pipeline().get(SslHandler.class); + if (handler == null + || GrpcPeerIdentity.fromSslSession(handler.engine().getSession()) + .filter(identity -> expectedPeer.equals(identity.uri())) + .isEmpty()) + throw new IllegalStateException("Authenticated Game Session peer required"); + }); ReactorNettyWebSocketClient newClient = new ReactorNettyWebSocketClient(http); beforePublish.run(); synchronized (publicationLock) { @@ -141,15 +138,13 @@ private boolean isClosed() { } public Mono execute(HttpHeaders headers, WebSocketHandler handler) { - return Mono.defer( - () -> { - ReactorNettyWebSocketClient current = client; - if (current == null) { - return Mono.error( - new IllegalStateException("Authenticated gameplay client unavailable")); - } - return current.execute(upstream, headers, handler); - }); + return Mono.defer(() -> { + ReactorNettyWebSocketClient current = client; + if (current == null) { + return Mono.error(new IllegalStateException("Authenticated gameplay client unavailable")); + } + return current.execute(upstream, headers, handler); + }); } public URI upstream() { diff --git a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java index 569d8fbd30..aa8d7b37c4 100644 --- a/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java +++ b/services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java @@ -157,12 +157,11 @@ public Mono handle(WebSocketSession downstream) { .onErrorResume( GameplayBridgeTerminalCloseException.class, terminal -> closeDownstream(state, terminal.closeClassification())) - .doFinally( - signal -> { - state.downstreamClosed.set(true); - state.inboundToUpstream.tryEmitComplete(); - state.outboundToClient.tryEmitComplete(); - }); + .doFinally(signal -> { + state.downstreamClosed.set(true); + state.inboundToUpstream.tryEmitComplete(); + state.outboundToClient.tryEmitComplete(); + }); Mono upstreamLoop = connectWithRetry(downstream, upstreamConnector, state, 0); return Mono.when(downstreamSend, downstreamReceive, upstreamLoop) @@ -255,9 +254,8 @@ private Mono connectWithRetry( downstream.getId()); } return Mono.delay(Duration.ofMillis(properties.reconnectDelayMs())) - .flatMap( - ignored -> - connectWithRetry(downstream, upstreamConnector, state, attempt + 1)); + .flatMap(ignored -> + connectWithRetry(downstream, upstreamConnector, state, attempt + 1)); }) .onErrorResume( GameplayBridgeTerminalCloseException.class, @@ -380,36 +378,32 @@ private Mono closeDownstream( state.outboundToClient.tryEmitComplete(); return Mono.defer(() -> state.downstream.close(closeClassification.status())) .timeout(DOWNSTREAM_CLOSE_TIMEOUT) - .doOnSuccess( - unused -> { - gameplayWebSocketObservability.recordClose(closeClassification); - try (RuntimeLoggingContext ignored = - openLoggingContext(state.downstream)) { - LOG.info( - "Gameplay websocket closed reason={} subreason={} bridge_shutdown_class={} code={}", - closeClassification.reason(), - closeClassification.subreason(), - closeClassification.bridgeShutdownClass(), - closeClassification.status().getCode()); - } - }) - .doOnError( - error -> { - GameplayWebSocketObservability.CloseClassification failedClose = - closeClassification.asUnattributedFailure(); - gameplayWebSocketObservability.recordClose(failedClose); - try (RuntimeLoggingContext ignored = - openLoggingContext(state.downstream)) { - LOG.warn( - "Gameplay websocket close failed reason={} subreason={} bridge_shutdown_class={} code={} error={}", - failedClose.reason(), - failedClose.subreason(), - failedClose.bridgeShutdownClass(), - failedClose.status().getCode(), - error.getMessage(), - error); - } - }); + .doOnSuccess(unused -> { + gameplayWebSocketObservability.recordClose(closeClassification); + try (RuntimeLoggingContext ignored = openLoggingContext(state.downstream)) { + LOG.info( + "Gameplay websocket closed reason={} subreason={} bridge_shutdown_class={} code={}", + closeClassification.reason(), + closeClassification.subreason(), + closeClassification.bridgeShutdownClass(), + closeClassification.status().getCode()); + } + }) + .doOnError(error -> { + GameplayWebSocketObservability.CloseClassification failedClose = + closeClassification.asUnattributedFailure(); + gameplayWebSocketObservability.recordClose(failedClose); + try (RuntimeLoggingContext ignored = openLoggingContext(state.downstream)) { + LOG.warn( + "Gameplay websocket close failed reason={} subreason={} bridge_shutdown_class={} code={} error={}", + failedClose.reason(), + failedClose.subreason(), + failedClose.bridgeShutdownClass(), + failedClose.status().getCode(), + error.getMessage(), + error); + } + }); }) .cache(); if (state.closeOperation.compareAndSet(null, closeOperation)) { @@ -459,13 +453,12 @@ private static String firstNonBlank(String primary, String fallback) { private HttpHeaders buildUpstreamHeaders(WebSocketSession downstream) { HttpHeaders headers = new HttpHeaders(); HttpHeaders source = downstream.getHandshakeInfo().getHeaders(); - FORWARDED_HEADERS.forEach( - name -> { - String value = source.getFirst(name); - if (StringUtils.hasText(value)) { - headers.set(name, value); - } - }); + FORWARDED_HEADERS.forEach(name -> { + String value = source.getFirst(name); + if (StringUtils.hasText(value)) { + headers.set(name, value); + } + }); if (!StringUtils.hasText(headers.getFirst(TRANSPORT_SESSION_HEADER))) { headers.set( TRANSPORT_SESSION_HEADER, Long.toUnsignedString(stablePositiveLong(downstream.getId()))); diff --git a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java index 6c191efea1..efd3ede4af 100644 --- a/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java +++ b/services/spring-cloud-gateway/src/test/java/integration/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTlsListenerAdmissionIntegrationTest.java @@ -174,12 +174,9 @@ void websocketUpgradePromotesOnlyTheConfiguredClientWorkload() throws Exception assertThat(admittedHeaders.get().getFirst("X-Firemud-Connect-Token")).isNull(); assertThat(admittedHeaders.get().getFirst("X-Firemud-Transport-Session-Id")).isNull(); - assertThatThrownBy( - () -> - connect( - port, - bridgeHeaders, - clientContext("wrong-client.pem", "wrong-client-key.pem"))) + assertThatThrownBy(() -> + connect( + port, bridgeHeaders, clientContext("wrong-client.pem", "wrong-client-key.pem"))) .isInstanceOf(RuntimeException.class) .hasMessageContaining("403 Forbidden"); assertThat(admittedConnections).hasValue(1); @@ -190,13 +187,12 @@ void websocketUpgradePromotesOnlyTheConfiguredClientWorkload() throws Exception HttpHeaders noFrameHeaders = bridgeHeaders(); noFrameHeaders.set("X-Proxy-Connection-Id", NO_FRAME_PROXY_CONNECTION_ID); - assertThatThrownBy( - () -> - connect( - port, - noFrameHeaders, - clientContext("tcp-proxy-client.pem", "tcp-proxy-client-key.pem"), - Duration.ofSeconds(1))) + assertThatThrownBy(() -> + connect( + port, + noFrameHeaders, + clientContext("tcp-proxy-client.pem", "tcp-proxy-client-key.pem"), + Duration.ofSeconds(1))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Timeout on blocking read"); } diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfigTest.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfigTest.java index 91ff0d08db..370bb283f1 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfigTest.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GameplayWebSocketBridgeConfigTest.java @@ -63,18 +63,17 @@ class GameplayWebSocketBridgeConfigTest { @Test void gameplayWebSocketPathIsOwnedByGatewayCode() { - contextRunner.run( - context -> { - assertThat(context).hasSingleBean(GameplayWebSocketBridgeHandler.class); - assertThat(context).hasSingleBean(SimpleUrlHandlerMapping.class); - assertThat(context).hasSingleBean(WebSocketHandlerAdapter.class); - - SimpleUrlHandlerMapping mapping = context.getBean(SimpleUrlHandlerMapping.class); - assertThat(mapping.getUrlMap()).containsKeys("/ws/game", "/ws/game/**"); - assertThat(mapping.getUrlMap().get("/ws/game")) - .isInstanceOf(WebHandler.class) - .isSameAs(mapping.getUrlMap().get("/ws/game/**")); - }); + contextRunner.run(context -> { + assertThat(context).hasSingleBean(GameplayWebSocketBridgeHandler.class); + assertThat(context).hasSingleBean(SimpleUrlHandlerMapping.class); + assertThat(context).hasSingleBean(WebSocketHandlerAdapter.class); + + SimpleUrlHandlerMapping mapping = context.getBean(SimpleUrlHandlerMapping.class); + assertThat(mapping.getUrlMap()).containsKeys("/ws/game", "/ws/game/**"); + assertThat(mapping.getUrlMap().get("/ws/game")) + .isInstanceOf(WebHandler.class) + .isSameAs(mapping.getUrlMap().get("/ws/game/**")); + }); } @Test @@ -84,22 +83,20 @@ void authenticatedGameplayClientIsOmittedForUnsetBlankOrExplicitFalseEndpoint() for (String endpoint : new String[] {"", " \t ", "false"}) { contextRunner - .withInitializer( - applicationContext -> - applicationContext - .getEnvironment() - .getPropertySources() - .addFirst( - new MapPropertySource( - "test-authenticated-upstream", - Map.of( - "firemud.gateway.gameplay.bridge.authenticated-upstream-url", - endpoint)))) - .run( - context -> - assertThat(context) - .as("endpoint=%s", endpoint) - .doesNotHaveBean(AuthenticatedGameplayWebSocketClient.class)); + .withInitializer(applicationContext -> + applicationContext + .getEnvironment() + .getPropertySources() + .addFirst( + new MapPropertySource( + "test-authenticated-upstream", + Map.of( + "firemud.gateway.gameplay.bridge.authenticated-upstream-url", + endpoint)))) + .run(context -> + assertThat(context) + .as("endpoint=%s", endpoint) + .doesNotHaveBean(AuthenticatedGameplayWebSocketClient.class)); } } @@ -116,42 +113,39 @@ void malformedNonblankAuthenticatedEndpointFailsFast(@TempDir Path dir) throws E "firemud.gateway.gameplay.bridge.tls.cert-chain=" + certificate, "firemud.gateway.gameplay.bridge.tls.private-key=" + privateKey, "firemud.gateway.gameplay.bridge.tls.ca-cert=" + caCertificate) - .run( - context -> - assertThat(context) - .hasFailed() - .getFailure() - .hasRootCauseMessage("Dedicated authenticated gameplay wss endpoint required")); + .run(context -> + assertThat(context) + .hasFailed() + .getFailure() + .hasRootCauseMessage("Dedicated authenticated gameplay wss endpoint required")); } @Test void gameplayWebSocketMappingUsesPathPatternSemanticsForMatrixParameters() { - contextRunner.run( - context -> { - SimpleUrlHandlerMapping mapping = context.getBean(SimpleUrlHandlerMapping.class); - Object handler = mapping.getUrlMap().get("/ws/game"); - assertThat(handler).isInstanceOf(WebHandler.class); - - for (String path : - new String[] {"/ws/game;probe", "/ws;probe/game", "/ws/game;probe/child"}) { - assertThat( - mapping - .getHandler( - MockServerWebExchange.from(MockServerHttpRequest.get(path).build())) - .block()) - .as("path=%s", path) - .isSameAs(handler); - } - - assertThat( - mapping - .getHandler( - MockServerWebExchange.from( - MockServerHttpRequest.get("/ws/game%3Bprobe").build())) - .block()) - .as("encoded semicolon is not a matrix parameter accepted by PathPattern") - .isNull(); - }); + contextRunner.run(context -> { + SimpleUrlHandlerMapping mapping = context.getBean(SimpleUrlHandlerMapping.class); + Object handler = mapping.getUrlMap().get("/ws/game"); + assertThat(handler).isInstanceOf(WebHandler.class); + + for (String path : + new String[] {"/ws/game;probe", "/ws;probe/game", "/ws/game;probe/child"}) { + assertThat( + mapping + .getHandler(MockServerWebExchange.from(MockServerHttpRequest.get(path).build())) + .block()) + .as("path=%s", path) + .isSameAs(handler); + } + + assertThat( + mapping + .getHandler( + MockServerWebExchange.from( + MockServerHttpRequest.get("/ws/game%3Bprobe").build())) + .block()) + .as("encoded semicolon is not a matrix parameter accepted by PathPattern") + .isNull(); + }); } @Test @@ -161,11 +155,10 @@ void mappedWebHandlerBindsOnlyVerifiedTcpProxyOriginBeforeDelegatingUpgrade() th when(session.getAttributes()).thenReturn(new HashMap<>()); AtomicReference received = new AtomicReference<>(); when(handler.handle(session)) - .thenAnswer( - invocation -> { - received.set(VerifiedTcpProxyOrigin.from(session)); - return Mono.empty(); - }); + .thenAnswer(invocation -> { + received.set(VerifiedTcpProxyOrigin.from(session)); + return Mono.empty(); + }); X509Certificate certificate; try (InputStream input = Objects.requireNonNull(getClass().getResourceAsStream("/certs/tcp-proxy-client.pem"))) { @@ -207,9 +200,8 @@ void mappedWebHandlerBindsOnlyVerifiedTcpProxyOriginBeforeDelegatingUpgrade() th HandshakeWebSocketService.class, (upgrade, construction) -> when(upgrade.handleRequest(any(), any())) - .thenAnswer( - invocation -> - invocation.getArgument(1).handle(session)))) { + .thenAnswer(invocation -> + invocation.getArgument(1).handle(session)))) { SimpleUrlHandlerMapping mapping = (SimpleUrlHandlerMapping) new GameplayWebSocketBridgeConfig().gameplayWebSocketBridgeMapping(handler); diff --git a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java index d980fa953c..e2ae9dac71 100644 --- a/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java +++ b/services/spring-cloud-gateway/src/test/java/net/firedevops/firemud/springcloudgateway/config/GatewayRouteTestSupport.java @@ -92,9 +92,7 @@ private static PredicateDefinition predicate( return route(gatewayProperties, routeId).getPredicates().stream() .filter(predicate -> predicateName.equalsIgnoreCase(predicate.getName())) .findFirst() - .orElseThrow( - () -> - new AssertionError( - "Expected " + predicateName + " predicate for route " + routeId)); + .orElseThrow(() -> + new AssertionError("Expected " + predicateName + " predicate for route " + routeId)); } } diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayTcpProxyListenerPropertiesTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayTcpProxyListenerPropertiesTest.java index f5f0a3741f..0b7aa75d1b 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayTcpProxyListenerPropertiesTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/GatewayTcpProxyListenerPropertiesTest.java @@ -51,12 +51,11 @@ void bindsEmptyMigrationDnsExpiryAsNull() { void rejectsMalformedInstantDuringBinding() { StandardEnvironment environment = environmentWithExpiry("not-an-instant"); - assertThatThrownBy( - () -> - Binder.get(environment) - .bind( - "firemud.gateway.tcp-proxy-listener", - Bindable.ofInstance(new GatewayTcpProxyListenerProperties()))) + assertThatThrownBy(() -> + Binder.get(environment) + .bind( + "firemud.gateway.tcp-proxy-listener", + Bindable.ofInstance(new GatewayTcpProxyListenerProperties()))) .isInstanceOf(BindException.class) .hasMessageContaining("expires-at"); } diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListenerTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListenerTest.java index acb405c05d..25cfa07c0f 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListenerTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/config/TcpProxyTlsListenerTest.java @@ -185,11 +185,10 @@ void startupPreservesCheckedFailureWhenCleanupFails() throws Exception { Throwable startupFailure; try (MockedStatic mocked = Mockito.mockStatic(SslContextBuilder.class)) { mocked - .when( - () -> - SslContextBuilder.forServer( - Path.of(properties.getCertificateChainPath()).toFile(), - Path.of(properties.getPrivateKeyPath()).toFile())) + .when(() -> + SslContextBuilder.forServer( + Path.of(properties.getCertificateChainPath()).toFile(), + Path.of(properties.getPrivateKeyPath()).toFile())) .thenReturn(builder); startupFailure = catchThrowable(listener::start); } @@ -197,11 +196,10 @@ void startupPreservesCheckedFailureWhenCleanupFails() throws Exception { assertThat(startupFailure) .isInstanceOf(IllegalStateException.class) .hasMessage("Unable to start TCP Proxy internal TLS listener") - .satisfies( - failure -> { - assertThat(failure.getCause()).isNotNull(); - assertThat(failure.getCause().getSuppressed()).containsExactly(cleanupFailure); - }); + .satisfies(failure -> { + assertThat(failure.getCause()).isNotNull(); + assertThat(failure.getCause().getSuppressed()).containsExactly(cleanupFailure); + }); } @Test diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java index a6c8e6db94..31a15777cc 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java @@ -415,15 +415,13 @@ private static ServerWebExchange withRequestHeader( ServerWebExchange exchange, String headerName, String headerValue) { return exchange .mutate() - .request( - request -> - request.headers( - headers -> { - headers.remove(headerName); - if (headerValue != null) { - headers.set(headerName, headerValue); - } - })) + .request(request -> + request.headers(headers -> { + headers.remove(headerName); + if (headerValue != null) { + headers.set(headerName, headerValue); + } + })) .build(); } } diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTrustPolicyTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTrustPolicyTest.java index 41f5756891..31b90ab6fc 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTrustPolicyTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/TcpProxyTrustPolicyTest.java @@ -253,10 +253,9 @@ void legacyPlaintextTrustIsRejectedOutsideExplicitLocalOrTestProfile() { legacy.getTcpProxy().setAllowInsecureHeadersFromTrustedCidrs(true); legacy.getTcpProxy().setInsecureTrustedCidrs(List.of("127.0.0.1/32")); - assertThatThrownBy( - () -> - new TcpProxyTrustPolicy( - new GatewayTcpProxyListenerProperties(), legacy, 8080, CLOCK, Set.of("prod"))) + assertThatThrownBy(() -> + new TcpProxyTrustPolicy( + new GatewayTcpProxyListenerProperties(), legacy, 8080, CLOCK, Set.of("prod"))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("restricted to explicit test/dev/local profiles"); } @@ -268,10 +267,9 @@ void legacyPlaintextTrustRejectsMixedOrEmptyActiveProfiles() { legacy.getTcpProxy().setInsecureTrustedCidrs(List.of("127.0.0.1/32")); for (Set activeProfiles : List.of(Set.of("test", "prod"), Set.of())) { - assertThatThrownBy( - () -> - new TcpProxyTrustPolicy( - new GatewayTcpProxyListenerProperties(), legacy, 8080, CLOCK, activeProfiles)) + assertThatThrownBy(() -> + new TcpProxyTrustPolicy( + new GatewayTcpProxyListenerProperties(), legacy, 8080, CLOCK, activeProfiles)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("restricted to explicit test/dev/local profiles"); } @@ -299,10 +297,9 @@ void legacyPlaintextTrustRejectsDefaultRoutesForIpv4AndIpv6() { legacy.getTcpProxy().setAllowInsecureHeadersFromTrustedCidrs(true); legacy.getTcpProxy().setInsecureTrustedCidrs(List.of(cidr)); - assertThatThrownBy( - () -> - new TcpProxyTrustPolicy( - new GatewayTcpProxyListenerProperties(), legacy, 8080, CLOCK, Set.of("test"))) + assertThatThrownBy(() -> + new TcpProxyTrustPolicy( + new GatewayTcpProxyListenerProperties(), legacy, 8080, CLOCK, Set.of("test"))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("contains an invalid source CIDR"); } diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java index 1c233e2a11..84921c7407 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/AuthenticatedGameplayWebSocketClientTest.java @@ -90,11 +90,10 @@ void localClientRequiresItsDedicatedGatewayIdentityAndClientUsage() throws Excep "test", "wss://localhost:8444/ws/game/tcp")) { assertThatThrownBy(client::initialize).isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - client - .execute(new HttpHeaders(), socket -> Mono.empty()) - .block(Duration.ofSeconds(5))) + assertThatThrownBy(() -> + client + .execute(new HttpHeaders(), socket -> Mono.empty()) + .block(Duration.ofSeconds(5))) .isInstanceOf(IllegalStateException.class); } } @@ -114,10 +113,9 @@ void executionSignalsUnavailableWhenClosedBeforeOrAfterAssembly() throws Excepti for (Mono execution : List.of(assembled, client.execute(new HttpHeaders(), socket -> Mono.empty()))) { StepVerifier.create(execution) - .expectErrorMatches( - error -> - error instanceof IllegalStateException - && "Authenticated gameplay client unavailable".equals(error.getMessage())) + .expectErrorMatches(error -> + error instanceof IllegalStateException + && "Authenticated gameplay client unavailable".equals(error.getMessage())) .verify(Duration.ofSeconds(5)); } } @@ -149,14 +147,13 @@ void lateReloadCannotRepublishClientAfterClose() throws Exception { client.initialize(); AtomicReference reloadFailure = new AtomicReference<>(); Thread lateReload = - new Thread( - () -> { - try { - client.reload(); - } catch (Exception failure) { - reloadFailure.set(failure); - } - }); + new Thread(() -> { + try { + client.reload(); + } catch (Exception failure) { + reloadFailure.set(failure); + } + }); lateReload.start(); try { assertThat(candidateBuilt.await(5, TimeUnit.SECONDS)).isTrue(); @@ -170,10 +167,9 @@ void lateReloadCannotRepublishClientAfterClose() throws Exception { assertThat(lateReload.isAlive()).isFalse(); assertThat(reloadFailure.get()).isNull(); StepVerifier.create(client.execute(new HttpHeaders(), socket -> Mono.empty())) - .expectErrorMatches( - error -> - error instanceof IllegalStateException - && "Authenticated gameplay client unavailable".equals(error.getMessage())) + .expectErrorMatches(error -> + error instanceof IllegalStateException + && "Authenticated gameplay client unavailable".equals(error.getMessage())) .verify(Duration.ofSeconds(5)); } } @@ -204,11 +200,10 @@ void closedClientFollowsBridgeCloseAndReleasesActiveRegistration() throws Except when(downstream.receive()) .thenReturn(closed.asMono().thenMany(Flux.empty())); when(downstream.close(any(CloseStatus.class))) - .thenAnswer( - invocation -> { - closed.tryEmitEmpty(); - return Mono.empty(); - }); + .thenAnswer(invocation -> { + closed.tryEmitEmpty(); + return Mono.empty(); + }); GameplayWebSocketBridgeHandler bridge = new GameplayWebSocketBridgeHandler( ordinaryClient, @@ -243,13 +238,11 @@ private void exchange(String identity, AtomicInteger requests, boolean accepted) .host("127.0.0.1") .port(0) .secure(spec -> spec.sslContext(tls)) - .handle( - (request, response) -> { - requests.incrementAndGet(); - return response.sendWebsocket( - (inbound, outbound) -> - outbound.sendString(reactor.core.publisher.Mono.just("ready"))); - }) + .handle((request, response) -> { + requests.incrementAndGet(); + return response.sendWebsocket((inbound, outbound) -> + outbound.sendString(reactor.core.publisher.Mono.just("ready"))); + }) .bindNow(); try (var client = new AuthenticatedGameplayWebSocketClient( diff --git a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java index a64b873ac1..8523fcbf45 100644 --- a/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java +++ b/services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandlerTest.java @@ -95,11 +95,10 @@ void bridgeGeneratesTransportSessionIdWhenTrustedAdmissionProvidesNone() { when(downstream.send(any())).thenReturn(Mono.never()); when(downstream.receive()).thenReturn(Flux.never()); when(client.execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class))) - .thenAnswer( - invocation -> { - upstreamHeaders.set(invocation.getArgument(1)); - return Mono.never(); - }); + .thenAnswer(invocation -> { + upstreamHeaders.set(invocation.getArgument(1)); + return Mono.never(); + }); GameplayWebSocketBridgeHandler handler = new GameplayWebSocketBridgeHandler( @@ -213,14 +212,13 @@ void downstreamClosureDuringReconnectBackoffSkipsNextUpstreamExecution( when(upstream.receive()).thenReturn(Flux.empty()); when(upstream.closeStatus()).thenReturn(Mono.empty()); when(client.execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class))) - .thenAnswer( - invocation -> { - if (!failAfterTransportConnect) { - return Mono.error(new IllegalStateException("connection failed")); - } - WebSocketHandler upstreamHandler = invocation.getArgument(2); - return upstreamHandler.handle(upstream); - }); + .thenAnswer(invocation -> { + if (!failAfterTransportConnect) { + return Mono.error(new IllegalStateException("connection failed")); + } + WebSocketHandler upstreamHandler = invocation.getArgument(2); + return upstreamHandler.handle(upstream); + }); GameplayWebSocketBridgeHandler handler = new GameplayWebSocketBridgeHandler( @@ -231,12 +229,11 @@ void downstreamClosureDuringReconnectBackoffSkipsNextUpstreamExecution( "spring-cloud-gateway", "gateway-test", null, Instant.EPOCH, null, null, null)); StepVerifier.withVirtualTime(() -> handler.handle(downstream)) - .then( - () -> { - verify(client) - .execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class)); - downstreamClosed.tryEmitEmpty(); - }) + .then(() -> { + verify(client) + .execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class)); + downstreamClosed.tryEmitEmpty(); + }) .thenAwait(Duration.ofSeconds(2)) .expectComplete() .verify(Duration.ofSeconds(5)); @@ -420,11 +417,10 @@ void actualLocalShutdownClosesEstablishedBridgeWithPlannedDrain() { when(upstream.receive()).thenReturn(Flux.never()); when(upstream.closeStatus()).thenReturn(Mono.empty()); when(client.execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class))) - .thenAnswer( - invocation -> { - WebSocketHandler upstreamHandler = invocation.getArgument(2); - return upstreamHandler.handle(upstream); - }); + .thenAnswer(invocation -> { + WebSocketHandler upstreamHandler = invocation.getArgument(2); + return upstreamHandler.handle(upstream); + }); GameplayWebSocketBridgeHandler handler = new GameplayWebSocketBridgeHandler( @@ -485,11 +481,10 @@ void closeWriteFailureRecordsUnattributedClassificationAndCompletesStopCallback( when(upstream.receive()).thenReturn(Flux.never()); when(upstream.closeStatus()).thenReturn(Mono.empty()); when(client.execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class))) - .thenAnswer( - invocation -> { - WebSocketHandler upstreamHandler = invocation.getArgument(2); - return upstreamHandler.handle(upstream); - }); + .thenAnswer(invocation -> { + WebSocketHandler upstreamHandler = invocation.getArgument(2); + return upstreamHandler.handle(upstream); + }); GameplayWebSocketBridgeHandler handler = new GameplayWebSocketBridgeHandler( @@ -547,11 +542,10 @@ void neverCompletingCloseIsBoundedAndRecordsUnattributedClassification() { when(upstream.receive()).thenReturn(Flux.never()); when(upstream.closeStatus()).thenReturn(Mono.empty()); when(client.execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class))) - .thenAnswer( - invocation -> { - WebSocketHandler upstreamHandler = invocation.getArgument(2); - return upstreamHandler.handle(upstream); - }); + .thenAnswer(invocation -> { + WebSocketHandler upstreamHandler = invocation.getArgument(2); + return upstreamHandler.handle(upstream); + }); GameplayWebSocketBridgeHandler handler = new GameplayWebSocketBridgeHandler( @@ -611,11 +605,10 @@ void repeatedStopCallbacksWaitForTheSamePendingCloseWrite() { when(upstream.receive()).thenReturn(Flux.never()); when(upstream.closeStatus()).thenReturn(Mono.empty()); when(client.execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class))) - .thenAnswer( - invocation -> { - WebSocketHandler upstreamHandler = invocation.getArgument(2); - return upstreamHandler.handle(upstream); - }); + .thenAnswer(invocation -> { + WebSocketHandler upstreamHandler = invocation.getArgument(2); + return upstreamHandler.handle(upstream); + }); GameplayWebSocketBridgeHandler handler = new GameplayWebSocketBridgeHandler( @@ -631,19 +624,17 @@ void repeatedStopCallbacksWaitForTheSamePendingCloseWrite() { StepVerifier.create(handler.handle(downstream)) .expectSubscription() .thenAwait(Duration.ofMillis(100)) - .then( - () -> { - handler.stop(() -> firstShutdownComplete.set(true)); - handler.stop(() -> secondShutdownComplete.set(true)); - assertThat(firstShutdownComplete).isFalse(); - assertThat(secondShutdownComplete).isFalse(); - closeWrite.tryEmitEmpty(); - }) - .then( - () -> { - assertThat(firstShutdownComplete).isTrue(); - assertThat(secondShutdownComplete).isTrue(); - }) + .then(() -> { + handler.stop(() -> firstShutdownComplete.set(true)); + handler.stop(() -> secondShutdownComplete.set(true)); + assertThat(firstShutdownComplete).isFalse(); + assertThat(secondShutdownComplete).isFalse(); + closeWrite.tryEmitEmpty(); + }) + .then(() -> { + assertThat(firstShutdownComplete).isTrue(); + assertThat(secondShutdownComplete).isTrue(); + }) .thenCancel() .verify(); @@ -682,30 +673,28 @@ void actualDownstreamBufferOverflowRecordsSlowClientClassification() { when(downstream.getHandshakeInfo()).thenReturn(handshakeInfo); when(handshakeInfo.getHeaders()).thenReturn(headers); when(downstream.send(any())) - .thenAnswer( - invocation -> { - Publisher outbound = invocation.getArgument(0); - Flux.from(outbound) - .subscribe( - new BaseSubscriber<>() { - @Override - protected void hookOnSubscribe(Subscription subscription) { - // Keep the outbound sink subscribed without consuming its first item. - } - }); - return Mono.never(); - }); + .thenAnswer(invocation -> { + Publisher outbound = invocation.getArgument(0); + Flux.from(outbound) + .subscribe( + new BaseSubscriber<>() { + @Override + protected void hookOnSubscribe(Subscription subscription) { + // Keep the outbound sink subscribed without consuming its first item. + } + }); + return Mono.never(); + }); when(downstream.receive()).thenReturn(Flux.never()); when(downstream.close(any(CloseStatus.class))).thenReturn(Mono.empty()); when(upstream.send(any())).thenReturn(Mono.never()); when(upstream.receive()).thenReturn(Flux.just(firstPayload, secondPayload)); when(upstream.closeStatus()).thenReturn(Mono.empty()); when(client.execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class))) - .thenAnswer( - invocation -> { - WebSocketHandler upstreamHandler = invocation.getArgument(2); - return upstreamHandler.handle(upstream); - }); + .thenAnswer(invocation -> { + WebSocketHandler upstreamHandler = invocation.getArgument(2); + return upstreamHandler.handle(upstream); + }); GameplayWebSocketBridgeHandler handler = new GameplayWebSocketBridgeHandler( @@ -764,21 +753,19 @@ void inboundBufferWithoutUpstreamSubscriberClosesBackendUnavailable() { when(downstream.send(any())).thenReturn(Mono.never()); when(downstream.receive()).thenReturn(downstreamMessages.asFlux()); when(downstream.close(any(CloseStatus.class))) - .thenAnswer( - invocation -> { - closeStatus.set(invocation.getArgument(0)); - closeInvoked.countDown(); - return closeWrite.asMono(); - }); + .thenAnswer(invocation -> { + closeStatus.set(invocation.getArgument(0)); + closeInvoked.countDown(); + return closeWrite.asMono(); + }); when(upstream.send(any())).thenReturn(Mono.never()); when(upstream.receive()).thenReturn(Flux.never()); when(upstream.closeStatus()).thenReturn(Mono.empty()); when(client.execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class))) - .thenAnswer( - invocation -> { - WebSocketHandler upstreamHandler = invocation.getArgument(2); - return upstreamHandler.handle(upstream); - }); + .thenAnswer(invocation -> { + WebSocketHandler upstreamHandler = invocation.getArgument(2); + return upstreamHandler.handle(upstream); + }); GameplayWebSocketBridgeHandler handler = new GameplayWebSocketBridgeHandler( @@ -790,19 +777,17 @@ void inboundBufferWithoutUpstreamSubscriberClosesBackendUnavailable() { StepVerifier.create(handler.handle(downstream)) .expectSubscription() - .then( - () -> { - assertThat(downstreamMessages.tryEmitNext(payload)).isEqualTo(Sinks.EmitResult.OK); - downstreamMessages.tryEmitNext(payload); - }) - .then( - () -> { - awaitClose(closeInvoked); - assertThat(closeStatus.get()).isNotNull(); - assertThat(closeStatus.get().getCode()).isEqualTo(1013); - assertThat(closeStatus.get().getReason()).isEqualTo("backend_unavailable"); - closeWrite.tryEmitEmpty(); - }) + .then(() -> { + assertThat(downstreamMessages.tryEmitNext(payload)).isEqualTo(Sinks.EmitResult.OK); + downstreamMessages.tryEmitNext(payload); + }) + .then(() -> { + awaitClose(closeInvoked); + assertThat(closeStatus.get()).isNotNull(); + assertThat(closeStatus.get().getCode()).isEqualTo(1013); + assertThat(closeStatus.get().getReason()).isEqualTo("backend_unavailable"); + closeWrite.tryEmitEmpty(); + }) .thenCancel() .verify(); } @@ -829,34 +814,31 @@ void inboundBufferOverflowClosesBackendUnavailable() { when(downstream.send(any())).thenReturn(Mono.never()); when(downstream.receive()).thenReturn(downstreamMessages.asFlux()); when(downstream.close(any(CloseStatus.class))) - .thenAnswer( - invocation -> { - closeStatus.set(invocation.getArgument(0)); - closeInvoked.countDown(); - return closeWrite.asMono(); - }); + .thenAnswer(invocation -> { + closeStatus.set(invocation.getArgument(0)); + closeInvoked.countDown(); + return closeWrite.asMono(); + }); when(upstream.send(any())) - .thenAnswer( - invocation -> { - Publisher outbound = invocation.getArgument(0); - Flux.from(outbound) - .subscribe( - new BaseSubscriber<>() { - @Override - protected void hookOnSubscribe(Subscription subscription) { - // Keep the inbound sink subscribed without consuming its buffer. - } - }); - return Mono.never(); - }); + .thenAnswer(invocation -> { + Publisher outbound = invocation.getArgument(0); + Flux.from(outbound) + .subscribe( + new BaseSubscriber<>() { + @Override + protected void hookOnSubscribe(Subscription subscription) { + // Keep the inbound sink subscribed without consuming its buffer. + } + }); + return Mono.never(); + }); when(upstream.receive()).thenReturn(Flux.never()); when(upstream.closeStatus()).thenReturn(Mono.empty()); when(client.execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class))) - .thenAnswer( - invocation -> { - WebSocketHandler upstreamHandler = invocation.getArgument(2); - return upstreamHandler.handle(upstream); - }); + .thenAnswer(invocation -> { + WebSocketHandler upstreamHandler = invocation.getArgument(2); + return upstreamHandler.handle(upstream); + }); GameplayWebSocketBridgeHandler handler = new GameplayWebSocketBridgeHandler( @@ -868,20 +850,17 @@ protected void hookOnSubscribe(Subscription subscription) { StepVerifier.create(handler.handle(downstream)) .expectSubscription() - .then( - () -> { - assertThat(downstreamMessages.tryEmitNext(firstPayload)) - .isEqualTo(Sinks.EmitResult.OK); - downstreamMessages.tryEmitNext(secondPayload); - }) - .then( - () -> { - awaitClose(closeInvoked); - assertThat(closeStatus.get()).isNotNull(); - assertThat(closeStatus.get().getCode()).isEqualTo(1013); - assertThat(closeStatus.get().getReason()).isEqualTo("backend_unavailable"); - closeWrite.tryEmitEmpty(); - }) + .then(() -> { + assertThat(downstreamMessages.tryEmitNext(firstPayload)).isEqualTo(Sinks.EmitResult.OK); + downstreamMessages.tryEmitNext(secondPayload); + }) + .then(() -> { + awaitClose(closeInvoked); + assertThat(closeStatus.get()).isNotNull(); + assertThat(closeStatus.get().getCode()).isEqualTo(1013); + assertThat(closeStatus.get().getReason()).isEqualTo("backend_unavailable"); + closeWrite.tryEmitEmpty(); + }) .thenCancel() .verify(); } @@ -903,30 +882,28 @@ void liveNonOverflowDownstreamEmissionUsesInternalClassification() { when(downstream.getHandshakeInfo()).thenReturn(handshakeInfo); when(handshakeInfo.getHeaders()).thenReturn(headers); when(downstream.send(any())) - .thenAnswer( - invocation -> { - Publisher outbound = invocation.getArgument(0); - Flux.from(outbound) - .subscribe( - new BaseSubscriber<>() { - @Override - protected void hookOnSubscribe(Subscription subscription) { - subscription.cancel(); - } - }); - return Mono.never(); - }); + .thenAnswer(invocation -> { + Publisher outbound = invocation.getArgument(0); + Flux.from(outbound) + .subscribe( + new BaseSubscriber<>() { + @Override + protected void hookOnSubscribe(Subscription subscription) { + subscription.cancel(); + } + }); + return Mono.never(); + }); when(downstream.receive()).thenReturn(Flux.never()); when(downstream.close(any(CloseStatus.class))).thenReturn(Mono.empty()); when(upstream.send(any())).thenReturn(Mono.never()); when(upstream.receive()).thenReturn(Flux.just(payload)); when(upstream.closeStatus()).thenReturn(Mono.empty()); when(client.execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class))) - .thenAnswer( - invocation -> { - WebSocketHandler upstreamHandler = invocation.getArgument(2); - return upstreamHandler.handle(upstream); - }); + .thenAnswer(invocation -> { + WebSocketHandler upstreamHandler = invocation.getArgument(2); + return upstreamHandler.handle(upstream); + }); GameplayWebSocketBridgeHandler handler = new GameplayWebSocketBridgeHandler( @@ -985,11 +962,10 @@ void actualBridgeCloseRecordsPlannedDrainAttribution() { when(upstream.receive()).thenReturn(Flux.empty()); when(upstream.closeStatus()).thenReturn(Mono.just(plannedDrain)); when(client.execute(any(URI.class), any(HttpHeaders.class), any(WebSocketHandler.class))) - .thenAnswer( - invocation -> { - WebSocketHandler upstreamHandler = invocation.getArgument(2); - return upstreamHandler.handle(upstream); - }); + .thenAnswer(invocation -> { + WebSocketHandler upstreamHandler = invocation.getArgument(2); + return upstreamHandler.handle(upstream); + }); GameplayWebSocketBridgeHandler handler = new GameplayWebSocketBridgeHandler( diff --git a/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/health/GatewayGameplayReadinessProbe.java b/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/health/GatewayGameplayReadinessProbe.java index d209885b45..d09fcf6a63 100644 --- a/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/health/GatewayGameplayReadinessProbe.java +++ b/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/health/GatewayGameplayReadinessProbe.java @@ -173,17 +173,16 @@ private synchronized void refresh() { // Apply timeout to a dependent future; the timeout callback below cancels the original. .whenComplete((ignoredResult, ignoredError) -> {}) .orTimeout(requestTimeoutNanos, TimeUnit.NANOSECONDS) - .whenComplete( - (result, error) -> { - synchronized (this) { - if (error instanceof TimeoutException) { - request.cancel(true); - } - if (inFlight.compareAndSet(request, null) && !closed.get()) { - ready.set(error == null && Boolean.TRUE.equals(result)); - } - } - }); + .whenComplete((result, error) -> { + synchronized (this) { + if (error instanceof TimeoutException) { + request.cancel(true); + } + if (inFlight.compareAndSet(request, null) && !closed.get()) { + ready.set(error == null && Boolean.TRUE.equals(result)); + } + } + }); } private synchronized void close() { diff --git a/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/GatewayWebSocketClient.java b/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/GatewayWebSocketClient.java index f1bfc0ef34..f635111afa 100644 --- a/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/GatewayWebSocketClient.java +++ b/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/GatewayWebSocketClient.java @@ -248,12 +248,11 @@ public CompletableFuture connect( } CompletableFuture connection = builder.buildAsync(gatewayUri, releasingListener); - connection.whenComplete( - (ignored, error) -> { - if (error != null && !connection.isCancelled()) { - recordFailure(classifyFailure(error)); - } - }); + connection.whenComplete((ignored, error) -> { + if (error != null && !connection.isCancelled()) { + recordFailure(classifyFailure(error)); + } + }); return new ConnectionFuture(connection, releasingListener); } catch (RuntimeException error) { if (releasingListener == null) { @@ -288,32 +287,30 @@ public CompletableFuture isReadyAsync() { return CompletableFuture.completedFuture(false); } CompletableFuture readiness = new CompletableFuture<>(); - responseFuture.whenComplete( - (response, error) -> { - boolean ready = false; - try { - try { - if (error == null) { - ready = - response.statusCode() >= 200 - && response.statusCode() < 300 - && hasUsableCertificateWatcher(); - } else if (!readiness.isCancelled()) { - recordFailure(classifyFailure(error)); - } - } finally { - readiness.complete(ready); - } - } finally { - generation.release(); - } - }); - readiness.whenComplete( - (ignored, error) -> { - if (readiness.isCancelled()) { - responseFuture.cancel(true); + responseFuture.whenComplete((response, error) -> { + boolean ready = false; + try { + try { + if (error == null) { + ready = + response.statusCode() >= 200 + && response.statusCode() < 300 + && hasUsableCertificateWatcher(); + } else if (!readiness.isCancelled()) { + recordFailure(classifyFailure(error)); } - }); + } finally { + readiness.complete(ready); + } + } finally { + generation.release(); + } + }); + readiness.whenComplete((ignored, error) -> { + if (readiness.isCancelled()) { + responseFuture.cancel(true); + } + }); return readiness; } @@ -958,18 +955,17 @@ static final class ConnectionFuture extends CompletableFuture { CompletableFuture handshake, ReleasingWebSocketListener releasingListener) { this.handshake = Objects.requireNonNull(handshake, "handshake"); this.releasingListener = Objects.requireNonNull(releasingListener, "releasingListener"); - handshake.whenComplete( - (webSocket, error) -> { - if (error != null) { - releasingListener.release(); - completeExceptionally(error); - return; - } - WebSocket wrapped = releasingListener.wrap(webSocket); - if (!complete(wrapped)) { - wrapped.abort(); - } - }); + handshake.whenComplete((webSocket, error) -> { + if (error != null) { + releasingListener.release(); + completeExceptionally(error); + return; + } + WebSocket wrapped = releasingListener.wrap(webSocket); + if (!complete(wrapped)) { + wrapped.abort(); + } + }); } @Override diff --git a/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java b/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java index a5d6de6d6a..796b23f8d9 100644 --- a/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java +++ b/services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java @@ -451,17 +451,16 @@ private void sendHeartbeat() { CompletableFuture pingFuture = socket.sendPing(ByteBuffer.wrap(new byte[] {1, 2, 3, 4})); outstandingSends.add(pingFuture); - pingFuture.whenComplete( - (ws, error) -> { - try (CombinedLoggingContext ignored = openLoggingContext()) { - outstandingSends.remove(pingFuture); - sample.stop(heartbeatTimer); - if (error != null) { - logger.warn("Gateway heartbeat failed; triggering reconnect", error); - handleGatewayDisconnect(); - } - } - }); + pingFuture.whenComplete((ws, error) -> { + try (CombinedLoggingContext ignored = openLoggingContext()) { + outstandingSends.remove(pingFuture); + sample.stop(heartbeatTimer); + if (error != null) { + logger.warn("Gateway heartbeat failed; triggering reconnect", error); + handleGatewayDisconnect(); + } + } + }); } private void drainBuffer() { @@ -479,26 +478,25 @@ private void drainBuffer() { inFlightSend = sendFuture; outstandingSends.add(sendFuture); } - sendFuture.whenComplete( - (ws, error) -> { - try (CombinedLoggingContext ignored = openLoggingContext()) { - synchronized (bufferLifecycleLock) { - outstandingSends.remove(sendFuture); - if (error == null) { - inFlightSend = null; - buffer.poll(); - } - } - if (error == null) { - touchActivity(); - } else { - logger.warn("Gateway send failed; scheduling reconnect", error); - handleGatewayDisconnect(); - } - updateBufferDepthGauge(); - drainBuffer(); + sendFuture.whenComplete((ws, error) -> { + try (CombinedLoggingContext ignored = openLoggingContext()) { + synchronized (bufferLifecycleLock) { + outstandingSends.remove(sendFuture); + if (error == null) { + inFlightSend = null; + buffer.poll(); } - }); + } + if (error == null) { + touchActivity(); + } else { + logger.warn("Gateway send failed; scheduling reconnect", error); + handleGatewayDisconnect(); + } + updateBufferDepthGauge(); + drainBuffer(); + } + }); } @Override @@ -768,16 +766,15 @@ private void connectToGateway() { connection.cancel(true); return; } - connection.whenComplete( - (socket, error) -> { - if (!inFlightGatewayConnection.compareAndSet(connection, null) || error == null) { - return; - } - try (CombinedLoggingContext ignored = openLoggingContext()) { - logger.error("WebSocket connection to {} failed", gatewayWsUrl, error); - handleGatewaySetupFailure(error); - } - }); + connection.whenComplete((socket, error) -> { + if (!inFlightGatewayConnection.compareAndSet(connection, null) || error == null) { + return; + } + try (CombinedLoggingContext ignored = openLoggingContext()) { + logger.error("WebSocket connection to {} failed", gatewayWsUrl, error); + handleGatewaySetupFailure(error); + } + }); } private void handleGatewayDisconnect() { @@ -957,47 +954,42 @@ private void notifyDisconnectAsync() { return; } long sequence = disconnectSequence.incrementAndGet(); - CompletableFuture.supplyAsync( - () -> - eventService.notifyDisconnect( - sessionContext.gameInstanceId(), - sessionContext.tenantId(), - proxyConnectionId, - sequence)) - .thenAccept( - response -> - handleDisconnectResponse( - response, sessionContext.gameInstanceId(), sessionContext.tenantId())) - .exceptionally( - failure -> { - try (CombinedLoggingContext ignored = openLoggingContext()) { - Status.Code status = Status.fromThrowable(failure).getCode(); - if (isExpectedShutdownDisconnectFailure(status)) { - logger.debug( - "Suppressing expected shutdown-path disconnect notification failure for session {} tenant {} status={}", - sessionContext.gameInstanceId(), - sessionContext.tenantId(), - status, - failure); - meterRegistry - .counter( - EXPECTED_SHUTDOWN_DISCONNECT_NOTIFY_FAILURE_METRIC, - "status", - status.name()) - .increment(); - return null; - } - logger.warn( - "Failed to notify Game Session Service about disconnect for session {} tenant {}", - sessionContext.gameInstanceId(), - sessionContext.tenantId(), - failure); - meterRegistry - .counter(DISCONNECT_NOTIFY_TRANSPORT_FAILURE_METRIC, "status", status.name()) - .increment(); - } + CompletableFuture.supplyAsync(() -> + eventService.notifyDisconnect( + sessionContext.gameInstanceId(), + sessionContext.tenantId(), + proxyConnectionId, + sequence)) + .thenAccept(response -> + handleDisconnectResponse( + response, sessionContext.gameInstanceId(), sessionContext.tenantId())) + .exceptionally(failure -> { + try (CombinedLoggingContext ignored = openLoggingContext()) { + Status.Code status = Status.fromThrowable(failure).getCode(); + if (isExpectedShutdownDisconnectFailure(status)) { + logger.debug( + "Suppressing expected shutdown-path disconnect notification failure for session {} tenant {} status={}", + sessionContext.gameInstanceId(), + sessionContext.tenantId(), + status, + failure); + meterRegistry + .counter( + EXPECTED_SHUTDOWN_DISCONNECT_NOTIFY_FAILURE_METRIC, "status", status.name()) + .increment(); return null; - }); + } + logger.warn( + "Failed to notify Game Session Service about disconnect for session {} tenant {}", + sessionContext.gameInstanceId(), + sessionContext.tenantId(), + failure); + meterRegistry + .counter(DISCONNECT_NOTIFY_TRANSPORT_FAILURE_METRIC, "status", status.name()) + .increment(); + } + return null; + }); } private void handleDisconnectResponse( diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java index d094b4989c..00b3aeb21d 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java @@ -162,11 +162,10 @@ void telnetLoginAndLookMatchTransportFlowWithoutSession() throws Exception { .matches(GameplayTranscriptMatchers.matchesCanonicalLookWithOptionalPrompt()); assertThat(accountStub().capturedAuthenticateRequests()) - .anyMatch( - request -> - request.getEmail().equals(GameplayTelnetScenarios.DEMO_LOGIN_EMAIL) - && request.getPassword().equals(GameplayTelnetScenarios.DEMO_PASSWORD) - && request.getDescriptorForType().findFieldByName("tenant_id") == null); + .anyMatch(request -> + request.getEmail().equals(GameplayTelnetScenarios.DEMO_LOGIN_EMAIL) + && request.getPassword().equals(GameplayTelnetScenarios.DEMO_PASSWORD) + && request.getDescriptorForType().findFieldByName("tenant_id") == null); } @Test @@ -252,16 +251,12 @@ void telnetAndGatewayWebSocketCanMoveNorthOnSharedRuntime() throws Exception { assertThat( sessionContextService.findByGameplayName( TENANT_ID, DEMO_WORLD_INSTANCE_ID, "Emberline")) - .hasValueSatisfying( - context -> - assertThat(context.roomInstanceId()) - .isEqualTo(LookTestFixtures.DESTINATION_ROOM_ID)); + .hasValueSatisfying(context -> + assertThat(context.roomInstanceId()).isEqualTo(LookTestFixtures.DESTINATION_ROOM_ID)); assertThat( sessionContextService.findByGameplayName(TENANT_ID, DEMO_WORLD_INSTANCE_ID, "Sora")) - .hasValueSatisfying( - context -> - assertThat(context.roomInstanceId()) - .isEqualTo(LookTestFixtures.DESTINATION_ROOM_ID)); + .hasValueSatisfying(context -> + assertThat(context.roomInstanceId()).isEqualTo(LookTestFixtures.DESTINATION_ROOM_ID)); } } diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionCrossServiceIntegrationTest.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionCrossServiceIntegrationTest.java index c1e3e02dec..ba5779ceca 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionCrossServiceIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionCrossServiceIntegrationTest.java @@ -125,19 +125,18 @@ void telnetWorldsCanBeBrowsedBeforeLoginAndPlay() throws Exception { assertThat(GAME_SESSION_STUB.stub().receivedCommands()) .contains("WORLDS", "LOGIN demo@example.com swordfish", "PLAY demo", "look"); assertThat(GAME_SESSION_STUB.stub().receivedHandshakeHeaders()) - .anySatisfy( - headers -> { - assertLoopbackAddress(headers.getFirst("X-Client-IP")); - assertLoopbackAddress(headers.getFirst("X-Proxy-Client-IP")); - assertThat(headers.getFirst("X-Proxy-Connection-Id")).isNotBlank(); - assertThat(headers.getFirst("X-Game-Instance-Id")).isEqualTo("1"); - assertThat(headers.getFirst("X-Proxy-Game-Instance-Id")).isEqualTo("1"); - assertThat(headers.getFirst("X-Tenant-Id")).isEqualTo("1"); - assertThat(headers.getFirst("X-Proxy-Tenant-Id")).isEqualTo("1"); - assertThat(headers.getFirst("X-World-Slug")).isEqualTo("demo"); - assertThat(headers.getFirst("X-Realm-Slug")).isEqualTo("production"); - assertThat(headers.getFirst("X-Pointer-Version")).isEqualTo("1"); - }); + .anySatisfy(headers -> { + assertLoopbackAddress(headers.getFirst("X-Client-IP")); + assertLoopbackAddress(headers.getFirst("X-Proxy-Client-IP")); + assertThat(headers.getFirst("X-Proxy-Connection-Id")).isNotBlank(); + assertThat(headers.getFirst("X-Game-Instance-Id")).isEqualTo("1"); + assertThat(headers.getFirst("X-Proxy-Game-Instance-Id")).isEqualTo("1"); + assertThat(headers.getFirst("X-Tenant-Id")).isEqualTo("1"); + assertThat(headers.getFirst("X-Proxy-Tenant-Id")).isEqualTo("1"); + assertThat(headers.getFirst("X-World-Slug")).isEqualTo("demo"); + assertThat(headers.getFirst("X-Realm-Slug")).isEqualTo("production"); + assertThat(headers.getFirst("X-Pointer-Version")).isEqualTo("1"); + }); } private static void assertLoopbackAddress(String address) { diff --git a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/stub/GatewayStubApplication.java b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/stub/GatewayStubApplication.java index 91ebdc1835..72897fa015 100644 --- a/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/stub/GatewayStubApplication.java +++ b/services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/stub/GatewayStubApplication.java @@ -98,13 +98,12 @@ private ProxyingWebSocketHandler(WebSocketClient client, URI targetUri) { public Mono handle(WebSocketSession inbound) { HttpHeaders outboundHeaders = new HttpHeaders(); HttpHeaders inboundHeaders = inbound.getHandshakeInfo().getHeaders(); - FORWARDED_HEADER_NAMES.forEach( - headerName -> { - var values = inboundHeaders.get(headerName); - if (values != null) { - values.forEach(value -> outboundHeaders.add(headerName, value)); - } - }); + FORWARDED_HEADER_NAMES.forEach(headerName -> { + var values = inboundHeaders.get(headerName); + if (values != null) { + values.forEach(value -> outboundHeaders.add(headerName, value)); + } + }); return client.execute( targetUri, diff --git a/services/tcp-proxy-service/src/test/java/integration/net/firedevops/firemud/tcpproxy/telnet/TlsMisconfigurationIntegrationTest.java b/services/tcp-proxy-service/src/test/java/integration/net/firedevops/firemud/tcpproxy/telnet/TlsMisconfigurationIntegrationTest.java index a9802927e2..8792bde539 100644 --- a/services/tcp-proxy-service/src/test/java/integration/net/firedevops/firemud/tcpproxy/telnet/TlsMisconfigurationIntegrationTest.java +++ b/services/tcp-proxy-service/src/test/java/integration/net/firedevops/firemud/tcpproxy/telnet/TlsMisconfigurationIntegrationTest.java @@ -19,19 +19,18 @@ class TlsMisconfigurationIntegrationTest { @Test void tlsMisconfigurationFailsFastWithClearMessage() { - assertThatThrownBy( - () -> - new SpringApplicationBuilder(TestConfig.class) - .web(WebApplicationType.NONE) - .properties( - "TCP_PROXY_PORT=0", - "TCP_PROXY_TLS_ENABLED=true", - "GATEWAY_WS_URL=ws://localhost/ws/game", - "TCP_PROXY_TLS_CERT=/nonexistent/cert.pem", - "TCP_PROXY_TLS_KEY=/nonexistent/key.pem", - "spring.flyway.enabled=false", - "spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration") - .run()) + assertThatThrownBy(() -> + new SpringApplicationBuilder(TestConfig.class) + .web(WebApplicationType.NONE) + .properties( + "TCP_PROXY_PORT=0", + "TCP_PROXY_TLS_ENABLED=true", + "GATEWAY_WS_URL=ws://localhost/ws/game", + "TCP_PROXY_TLS_CERT=/nonexistent/cert.pem", + "TCP_PROXY_TLS_KEY=/nonexistent/key.pem", + "spring.flyway.enabled=false", + "spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration") + .run()) .hasRootCauseInstanceOf(IllegalStateException.class) .hasRootCauseMessage( "TCP proxy TLS configuration invalid: certificate or key file does not exist or is unreadable"); diff --git a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/config/InternalGrpcClientAuthConfigTest.java b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/config/InternalGrpcClientAuthConfigTest.java index 3679cda178..9ae596eaa2 100644 --- a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/config/InternalGrpcClientAuthConfigTest.java +++ b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/config/InternalGrpcClientAuthConfigTest.java @@ -55,23 +55,22 @@ class InternalGrpcClientAuthConfigTest { @Test void serviceOverridesSharedStubCustomizerWithInternalOnlyBehavior() { - contextRunner.run( - ctx -> { - BlockingGrpcStubCustomizer customizer = ctx.getBean(BlockingGrpcStubCustomizer.class); - CapturingChannel channel = new CapturingChannel(); - CapturingStub stub = new CapturingStub(channel, CallOptions.DEFAULT); - - CapturingStub customized = customizer.customize(stub); - - assertThat(customized).isNotSameAs(stub); - customized.invoke(); - String authorization = channel.lastAuthorization(); - assertThat(authorization).startsWith("Bearer "); - String token = authorization.substring(7); - String payloadJson = jwtPayload(token); - assertThat(payloadJson).contains("\"sub\":\"service:tcp-proxy-service\""); - assertThat(payloadJson).contains("\"internalService\":true"); - }); + contextRunner.run(ctx -> { + BlockingGrpcStubCustomizer customizer = ctx.getBean(BlockingGrpcStubCustomizer.class); + CapturingChannel channel = new CapturingChannel(); + CapturingStub stub = new CapturingStub(channel, CallOptions.DEFAULT); + + CapturingStub customized = customizer.customize(stub); + + assertThat(customized).isNotSameAs(stub); + customized.invoke(); + String authorization = channel.lastAuthorization(); + assertThat(authorization).startsWith("Bearer "); + String token = authorization.substring(7); + String payloadJson = jwtPayload(token); + assertThat(payloadJson).contains("\"sub\":\"service:tcp-proxy-service\""); + assertThat(payloadJson).contains("\"internalService\":true"); + }); } private static String jwtPayload(String token) { diff --git a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/health/GatewayGameplayReadinessProbeTest.java b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/health/GatewayGameplayReadinessProbeTest.java index 32d50a79cd..2e1ddbce83 100644 --- a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/health/GatewayGameplayReadinessProbeTest.java +++ b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/health/GatewayGameplayReadinessProbeTest.java @@ -122,19 +122,18 @@ void timedOutPollClearsInFlightAndLaterPollingRetries() throws Exception { AtomicInteger invocationCount = new AtomicInteger(); CopyOnWriteArrayList> retryFutures = new CopyOnWriteArrayList<>(); when(client.isReadyAsync()) - .thenAnswer( - invocation -> { - int invocationNumber = invocationCount.incrementAndGet(); - if (invocationNumber == 1) { - return healthy; - } - if (invocationNumber == 2) { - return stalled; - } - CompletableFuture freshRetry = new CompletableFuture<>(); - retryFutures.add(freshRetry); - return freshRetry; - }); + .thenAnswer(invocation -> { + int invocationNumber = invocationCount.incrementAndGet(); + if (invocationNumber == 1) { + return healthy; + } + if (invocationNumber == 2) { + return stalled; + } + CompletableFuture freshRetry = new CompletableFuture<>(); + retryFutures.add(freshRetry); + return freshRetry; + }); try (GatewayGameplayReadinessProbe probe = startedProbe(client, Duration.ofMillis(20), Duration.ofMillis(100))) { verify(client, timeout(1000)).isReadyAsync(); diff --git a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/service/TcpProxyEventClientTest.java b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/service/TcpProxyEventClientTest.java index 0e6d2b21f5..a60a39ead6 100644 --- a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/service/TcpProxyEventClientTest.java +++ b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/service/TcpProxyEventClientTest.java @@ -128,33 +128,31 @@ void initRegistersCertificateWatcherBeforeInitialChannelBuild(@TempDir Path temp java.util.concurrent.atomic.AtomicInteger buildCount = new java.util.concurrent.atomic.AtomicInteger(); when(channelFactory.buildChannel(any(), any(Integer.class), any(), any(Boolean.class), any())) - .thenAnswer( - ignored -> { - int currentBuild = buildCount.incrementAndGet(); - if (currentBuild == 1) { - initialBuildStarted.countDown(); - if (!releaseInitialBuild.await(5, TimeUnit.SECONDS)) { - throw new AssertionError("timed out waiting to release initial channel build"); - } - } else if (currentBuild == 2) { - reloadBuildStarted.countDown(); - } - return mock(io.grpc.ManagedChannel.class); - }); + .thenAnswer(ignored -> { + int currentBuild = buildCount.incrementAndGet(); + if (currentBuild == 1) { + initialBuildStarted.countDown(); + if (!releaseInitialBuild.await(5, TimeUnit.SECONDS)) { + throw new AssertionError("timed out waiting to release initial channel build"); + } + } else if (currentBuild == 2) { + reloadBuildStarted.countDown(); + } + return mock(io.grpc.ManagedChannel.class); + }); TcpProxyEventClient client = new TcpProxyEventClient( endpoints, tlsProps, channelFactory, resolver, BlockingGrpcStubCustomizer.noop()); AtomicReference initFailure = new AtomicReference<>(); Thread initThread = - new Thread( - () -> { - try { - client.init(); - } catch (Throwable failure) { - initFailure.set(failure); - } - }); + new Thread(() -> { + try { + client.init(); + } catch (Throwable failure) { + initFailure.set(failure); + } + }); initThread.start(); try { org.junit.jupiter.api.Assertions.assertTrue( @@ -292,14 +290,13 @@ void closeDuringReloadDiscardsUnpublishedReplacementChannel() throws Exception { CountDownLatch buildStarted = new CountDownLatch(1); CountDownLatch releaseBuild = new CountDownLatch(1); when(channelFactory.buildChannel(any(), any(Integer.class), any(), any(Boolean.class), any())) - .thenAnswer( - ignored -> { - buildStarted.countDown(); - if (!releaseBuild.await(5, TimeUnit.SECONDS)) { - throw new AssertionError("timed out waiting to release replacement build"); - } - return replacementChannel; - }); + .thenAnswer(ignored -> { + buildStarted.countDown(); + if (!releaseBuild.await(5, TimeUnit.SECONDS)) { + throw new AssertionError("timed out waiting to release replacement build"); + } + return replacementChannel; + }); GrpcTlsMaterialResolver resolver = mock(GrpcTlsMaterialResolver.class); when(resolver.resolve(tlsProps)).thenReturn(null); TcpProxyEventClient client = @@ -310,14 +307,13 @@ void closeDuringReloadDiscardsUnpublishedReplacementChannel() throws Exception { AtomicReference reloadFailure = new AtomicReference<>(); Thread reloadThread = - new Thread( - () -> { - try { - invokeReloadChannel(client); - } catch (Throwable e) { - reloadFailure.set(e); - } - }); + new Thread(() -> { + try { + invokeReloadChannel(client); + } catch (Throwable e) { + reloadFailure.set(e); + } + }); reloadThread.start(); try { org.junit.jupiter.api.Assertions.assertTrue(buildStarted.await(5, TimeUnit.SECONDS)); diff --git a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/telnet/GatewayWebSocketClientTest.java b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/telnet/GatewayWebSocketClientTest.java index 5449ddfc11..1b161272e4 100644 --- a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/telnet/GatewayWebSocketClientTest.java +++ b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/telnet/GatewayWebSocketClientTest.java @@ -586,18 +586,17 @@ public MockResponse dispatch(RecordedRequest request) throws InterruptedExceptio HttpClient initialClient = (HttpClient) client.clientIdentity(); CompletableFuture readiness = client.isReadyAsync(); CompletableFuture completionObserver = - readiness.thenAccept( - ignored -> { - completionObserverEntered.countDown(); - try { - if (!releaseCompletionObserver.await(5, TimeUnit.SECONDS)) { - throw new AssertionError("completion observer was not released"); - } - } catch (InterruptedException error) { - Thread.currentThread().interrupt(); - throw new AssertionError("completion observer was interrupted", error); - } - }); + readiness.thenAccept(ignored -> { + completionObserverEntered.countDown(); + try { + if (!releaseCompletionObserver.await(5, TimeUnit.SECONDS)) { + throw new AssertionError("completion observer was not released"); + } + } catch (InterruptedException error) { + Thread.currentThread().interrupt(); + throw new AssertionError("completion observer was interrupted", error); + } + }); try { assertNotNull(server.takeRequest(5, TimeUnit.SECONDS)); diff --git a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandlerTest.java b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandlerTest.java index 7c0f8c53ef..4ff75492a9 100644 --- a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandlerTest.java +++ b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandlerTest.java @@ -509,12 +509,11 @@ void disconnectWaitsForLockProtectedSendInitiation() throws Exception { CountDownLatch allowSend = new CountDownLatch(1); CompletableFuture sendFuture = new CompletableFuture<>(); when(socket.sendText(anyString(), eq(true))) - .thenAnswer( - invocation -> { - sendEntered.countDown(); - assertTrue(allowSend.await(5, TimeUnit.SECONDS)); - return sendFuture; - }); + .thenAnswer(invocation -> { + sendEntered.countDown(); + assertTrue(allowSend.await(5, TimeUnit.SECONDS)); + return sendFuture; + }); handler.channelRead0(ctx, "look"); assertEquals(1, handler.getBufferedSize()); @@ -523,26 +522,24 @@ void disconnectWaitsForLockProtectedSendInitiation() throws Exception { drainBuffer.setAccessible(true); AtomicReference drainFailure = new AtomicReference<>(); Thread drainThread = - new Thread( - () -> { - try { - drainBuffer.invoke(handler); - } catch (Throwable error) { - drainFailure.set(error); - } - }); + new Thread(() -> { + try { + drainBuffer.invoke(handler); + } catch (Throwable error) { + drainFailure.set(error); + } + }); drainThread.start(); assertTrue(sendEntered.await(5, TimeUnit.SECONDS)); CountDownLatch disconnectStarted = new CountDownLatch(1); CountDownLatch disconnectFinished = new CountDownLatch(1); Thread disconnectThread = - new Thread( - () -> { - disconnectStarted.countDown(); - handler.channelInactive(ctx); - disconnectFinished.countDown(); - }); + new Thread(() -> { + disconnectStarted.countDown(); + handler.channelInactive(ctx); + disconnectFinished.countDown(); + }); disconnectThread.start(); assertTrue(disconnectStarted.await(5, TimeUnit.SECONDS)); assertFalse(disconnectFinished.await(100, TimeUnit.MILLISECONDS)); @@ -810,11 +807,10 @@ void unacknowledgedGatewayCloseAbortsAfterGracePeriod() throws Exception { AtomicReference fallback = new AtomicReference<>(); when(context.executor()).thenReturn(executor); when(executor.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))) - .thenAnswer( - invocation -> { - fallback.set(invocation.getArgument(0)); - return task; - }); + .thenAnswer(invocation -> { + fallback.set(invocation.getArgument(0)); + return task; + }); ((AtomicReference) fieldValue(handler, "webSocket")).set(socket); setField(handler, "context", context); @@ -838,11 +834,10 @@ void acknowledgedGatewayCloseCancelsFallbackAndLateFallbackCannotAbortReplacemen AtomicReference fallback = new AtomicReference<>(); when(context.executor()).thenReturn(executor); when(executor.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))) - .thenAnswer( - invocation -> { - fallback.set(invocation.getArgument(0)); - return task; - }); + .thenAnswer(invocation -> { + fallback.set(invocation.getArgument(0)); + return task; + }); ((AtomicReference) fieldValue(handler, "webSocket")).set(socket); setField(handler, "context", context); setField(handler, "closing", true); @@ -1709,14 +1704,13 @@ void gatewayDisconnectFailClosesTelnet() { List scheduledTasks = new ArrayList<>(); EventExecutor executor = mock(EventExecutor.class); when(executor.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class))) - .thenAnswer( - invocation -> { - Runnable command = invocation.getArgument(0); - long delay = invocation.getArgument(1); - TimeUnit unit = invocation.getArgument(2); - scheduledTasks.add(new ScheduledTask(command, unit.toMillis(delay))); - return mockScheduledFutureTyped(); - }); + .thenAnswer(invocation -> { + Runnable command = invocation.getArgument(0); + long delay = invocation.getArgument(1); + TimeUnit unit = invocation.getArgument(2); + scheduledTasks.add(new ScheduledTask(command, unit.toMillis(delay))); + return mockScheduledFutureTyped(); + }); when(executor.scheduleAtFixedRate( any(Runnable.class), anyLong(), anyLong(), any(TimeUnit.class))) .thenReturn(mockScheduledFutureTyped()); diff --git a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/testsupport/GameplayTelnetDriverTest.java b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/testsupport/GameplayTelnetDriverTest.java index 8a9e32b437..8d31126cdb 100644 --- a/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/testsupport/GameplayTelnetDriverTest.java +++ b/services/tcp-proxy-service/src/test/java/unit/net/firedevops/firemud/tcpproxy/testsupport/GameplayTelnetDriverTest.java @@ -49,19 +49,18 @@ void enterGameplayAndWaitReadyFailsWhenLookContentNeverArrives() throws Exceptio void readBlockContainingFailsWhenStreamClosesAfterMatch() throws Exception { try (ServerSocket server = new ServerSocket(0)) { Thread serverThread = - new Thread( - () -> { - try (Socket socket = server.accept(); - PrintWriter writer = - new PrintWriter( - new OutputStreamWriter( - socket.getOutputStream(), StandardCharsets.ISO_8859_1), - true)) { - writer.println("LOOK READY"); - } catch (IOException ignored) { - // The client may close the socket while the test is cleaning up. - } - }); + new Thread(() -> { + try (Socket socket = server.accept(); + PrintWriter writer = + new PrintWriter( + new OutputStreamWriter( + socket.getOutputStream(), StandardCharsets.ISO_8859_1), + true)) { + writer.println("LOOK READY"); + } catch (IOException ignored) { + // The client may close the socket while the test is cleaning up. + } + }); serverThread.start(); try (GameplayTelnetDriver driver = @@ -83,22 +82,21 @@ void readBlockContainingFailsWhenTimeoutOccursAfterMatch() throws Exception { try (ServerSocket server = new ServerSocket(0)) { CountDownLatch responseFlushed = new CountDownLatch(1); Thread serverThread = - new Thread( - () -> { - try (Socket socket = server.accept(); - PrintWriter writer = - new PrintWriter( - new OutputStreamWriter( - socket.getOutputStream(), StandardCharsets.ISO_8859_1), - true)) { - writer.println("LOOK READY"); - responseFlushed.countDown(); - socket.setSoTimeout(5_000); - socket.getInputStream().read(); - } catch (IOException ignored) { - // The client may close the socket while the test is cleaning up. - } - }); + new Thread(() -> { + try (Socket socket = server.accept(); + PrintWriter writer = + new PrintWriter( + new OutputStreamWriter( + socket.getOutputStream(), StandardCharsets.ISO_8859_1), + true)) { + writer.println("LOOK READY"); + responseFlushed.countDown(); + socket.setSoTimeout(5_000); + socket.getInputStream().read(); + } catch (IOException ignored) { + // The client may close the socket while the test is cleaning up. + } + }); serverThread.start(); try (GameplayTelnetDriver driver = diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/GenerationRuleServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/GenerationRuleServiceImpl.java index 5c89f42006..4dd056b59f 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/GenerationRuleServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/GenerationRuleServiceImpl.java @@ -30,10 +30,9 @@ public GenerationRuleDto saveRule(GenerationRuleDto dto) { existing = repository .findByTenantIdAndVersionIdAndId(dto.tenantId(), dto.versionId(), dto.id()) - .orElseThrow( - () -> - new WorldDesignPublicationFenceRepository.ConflictException( - "Generation rule does not belong to the locked tenant and Version")); + .orElseThrow(() -> + new WorldDesignPublicationFenceRepository.ConflictException( + "Generation rule does not belong to the locked tenant and Version")); } GenerationRule entity = mapper.toEntity(dto); if (existing != null) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java index b90eca438c..73a93fe9e0 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java @@ -213,10 +213,9 @@ private InitialAdmissionBindHoldDto markReconciliationRequired( return holdRepository .markReconciliationRequired(hold, normalizedErrorCode, clock.instant()) .map(this::toDto) - .orElseThrow( - () -> - new IllegalStateException( - "INITIAL_ADMISSION_BIND_HOLD_STALE: reconciliation update lost")); + .orElseThrow(() -> + new IllegalStateException( + "INITIAL_ADMISSION_BIND_HOLD_STALE: reconciliation update lost")); } private void validateRequest(InitialAdmissionBindHoldRequest request) { @@ -315,28 +314,23 @@ private InitialAdmissionBindHold requireLockedHold(String holdId) { requireCanonicalUuid(holdId, "holdId"); return holdRepository .findByHoldIdForUpdate(holdId) - .orElseThrow( - () -> - new IllegalArgumentException( - "INITIAL_ADMISSION_BIND_HOLD_NOT_FOUND: hold not found")); + .orElseThrow(() -> + new IllegalArgumentException("INITIAL_ADMISSION_BIND_HOLD_NOT_FOUND: hold not found")); } private InitialAdmissionBindHold requireHold(String holdId) { requireCanonicalUuid(holdId, "holdId"); return holdRepository .findByHoldId(holdId) - .orElseThrow( - () -> - new IllegalArgumentException( - "INITIAL_ADMISSION_BIND_HOLD_NOT_FOUND: hold not found")); + .orElseThrow(() -> + new IllegalArgumentException("INITIAL_ADMISSION_BIND_HOLD_NOT_FOUND: hold not found")); } private WorldInstance requireLockedWorldInstance(long tenantId, long gameInstanceId) { return worldInstanceRepository .findByTenantIdAndGameInstanceIdForUpdate(tenantId, gameInstanceId) - .orElseThrow( - () -> - new IllegalArgumentException("WORLD_INSTANCE_NOT_FOUND: world instance not found")); + .orElseThrow(() -> + new IllegalArgumentException("WORLD_INSTANCE_NOT_FOUND: world instance not found")); } private boolean isTerminal(String status) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/RegionServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/RegionServiceImpl.java index 74a618cb54..362009fecb 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/RegionServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/RegionServiceImpl.java @@ -42,10 +42,9 @@ public RegionDto moveRegion(Long tenantId, Long regionId, Integer shardId) { regionRepository .findByIdForUpdate(regionId) .filter(r -> tenantId.equals(r.getTenantId()) && versionId.equals(r.getVersionId())) - .orElseThrow( - () -> - new WorldDesignPublicationFenceRepository.ConflictException( - "Region tenant or Version changed before the publication owner lock")); + .orElseThrow(() -> + new WorldDesignPublicationFenceRepository.ConflictException( + "Region tenant or Version changed before the publication owner lock")); region.setShardId(shardId); return regionMapper.toDto(regionRepository.save(region)); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/TemporalWorldLifecycleWorkflowImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/TemporalWorldLifecycleWorkflowImpl.java index 56667d8cda..0b07bb20d6 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/TemporalWorldLifecycleWorkflowImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/TemporalWorldLifecycleWorkflowImpl.java @@ -33,11 +33,10 @@ public class TemporalWorldLifecycleWorkflowImpl implements TemporalWorldLifecycl public WorldInstanceLifecycleSnapshotDto run(PreparedWorldInstanceRequest request) { currentSnapshot = activities.prepareWorldInstance(request); while (!completed) { - Workflow.await( - () -> - pendingActivateEpoch != null - || pendingFailEpoch != null - || pendingTerminateEpoch != null); + Workflow.await(() -> + pendingActivateEpoch != null + || pendingFailEpoch != null + || pendingTerminateEpoch != null); if (pendingActivateEpoch != null) { currentSnapshot = activities.activatePreparedWorldInstance( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java index ec3273d92f..5bc18abc66 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java @@ -448,10 +448,9 @@ private void deleteExistingSpawnBindingsInScope( .findByTenantIdAndVersionIdOrderByIdAsc(request.tenantId(), request.versionId()) .stream() .filter(binding -> bindingWithinScope(binding, scopeType, scopeId)) - .filter( - binding -> - !StringUtils.hasText(request.aggregateId()) - || !binding.getId().equals(parseId(request.aggregateId(), "aggregate_id"))) + .filter(binding -> + !StringUtils.hasText(request.aggregateId()) + || !binding.getId().equals(parseId(request.aggregateId(), "aggregate_id"))) .toList(); if (!inScopeBindings.isEmpty()) { worldEntitySpawnBindingRepository.deleteAll(inScopeBindings); @@ -473,11 +472,10 @@ private GenerationRule resolveGenerationRuleForMutation( request.scopeType(), requireNormalizedScopeId(request), ruleName) - .map( - existing -> { - validateExpectedAggregateEpoch(request, existing.getId()); - return existing; - }) + .map(existing -> { + validateExpectedAggregateEpoch(request, existing.getId()); + return existing; + }) .orElseGet(GenerationRule::new); } failIfSeedAppendOnlyUpdate(request); @@ -568,10 +566,9 @@ private void deleteExistingGeneratedRowsInScope(WorldDesignMutationRequestDto re roomExitRepository .findByTenantIdAndVersionIdOrderByIdAsc(request.tenantId(), request.versionId()) .stream() - .filter( - exit -> - roomWithinScope(exit.getFromRoom(), scopeType, scopeId) - || roomWithinScope(exit.getToRoom(), scopeType, scopeId)) + .filter(exit -> + roomWithinScope(exit.getFromRoom(), scopeType, scopeId) + || roomWithinScope(exit.getToRoom(), scopeType, scopeId)) .toList(); if (!inScopeExits.isEmpty()) { roomExitRepository.deleteAll(inScopeExits); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java index 5f72bf0be7..8ffc3e8cd5 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImpl.java @@ -85,80 +85,73 @@ private WorldDraftDesignDigest getDraftDesignDigest( regionRepository .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) .stream() - .map( - region -> - Map.of( - "id", region.getId(), - "shardId", region.getShardId(), - "name", region.getName(), - "weather", value(region.getWeather()), - "generationSeed", region.getGenerationSeed(), - "generatorType", value(region.getGeneratorType()), - "generatorParams", value(region.getGeneratorParams()), - "spacingMultiplier", region.getSpacingMultiplier())) + .map(region -> + Map.of( + "id", region.getId(), + "shardId", region.getShardId(), + "name", region.getName(), + "weather", value(region.getWeather()), + "generationSeed", region.getGenerationSeed(), + "generatorType", value(region.getGeneratorType()), + "generatorParams", value(region.getGeneratorParams()), + "spacingMultiplier", region.getSpacingMultiplier())) .toList(), "zones", zoneRepository.findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey).stream() - .map( - zone -> - Map.of( - "id", zone.getId(), - "regionId", zone.getRegion().getId(), - "name", zone.getName())) + .map(zone -> + Map.of( + "id", zone.getId(), + "regionId", zone.getRegion().getId(), + "name", zone.getName())) .toList(), "rooms", roomRepository.findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey).stream() - .map( - room -> - Map.of( - "id", room.getId(), - "zoneId", room.getZone().getId(), - "name", room.getName(), - "description", value(room.getDescription()), - "nameLocalizedVariantsJson", - value(room.getNameLocalizedVariantsJson()), - "descriptionLocalizedVariantsJson", - value(room.getDescriptionLocalizedVariantsJson()))) + .map(room -> + Map.of( + "id", room.getId(), + "zoneId", room.getZone().getId(), + "name", room.getName(), + "description", value(room.getDescription()), + "nameLocalizedVariantsJson", value(room.getNameLocalizedVariantsJson()), + "descriptionLocalizedVariantsJson", + value(room.getDescriptionLocalizedVariantsJson()))) .toList(), "roomExits", roomExitRepository .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) .stream() - .map( - roomExit -> - Map.of( - "id", roomExit.getId(), - "fromRoomId", roomExit.getFromRoom().getId(), - "toRoomId", roomExit.getToRoom().getId(), - "direction", roomExit.getDirection(), - "cost", roomExit.getCost())) + .map(roomExit -> + Map.of( + "id", roomExit.getId(), + "fromRoomId", roomExit.getFromRoom().getId(), + "toRoomId", roomExit.getToRoom().getId(), + "direction", roomExit.getDirection(), + "cost", roomExit.getCost())) .toList(), "generationRules", generationRuleRepository .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) .stream() - .map( - rule -> - Map.of( - "id", rule.getId(), - "name", rule.getName(), - "scopeType", value(rule.getScopeType()), - "scopeId", value(rule.getScopeId()), - "value", value(rule.getValue()))) + .map(rule -> + Map.of( + "id", rule.getId(), + "name", rule.getName(), + "scopeType", value(rule.getScopeType()), + "scopeId", value(rule.getScopeId()), + "value", value(rule.getValue()))) .toList(), "worldEntitySpawnBindings", worldEntitySpawnBindingRepository .findByTenantIdAndVersionIdOrderByIdAsc(tenantKey, versionKey) .stream() - .map( - binding -> - Map.of( - "id", binding.getId(), - "roomId", binding.getRoom().getId(), - "entityTemplateType", binding.getEntityTemplateType(), - "entityReference", entityReference(binding), - "spawnCount", binding.getSpawnCount(), - "respawnDelaySeconds", binding.getRespawnDelaySeconds())) + .map(binding -> + Map.of( + "id", binding.getId(), + "roomId", binding.getRoom().getId(), + "entityTemplateType", binding.getEntityTemplateType(), + "entityReference", entityReference(binding), + "spawnCount", binding.getSpawnCount(), + "respawnDelaySeconds", binding.getRespawnDelaySeconds())) .toList()); int schemaVersion = DIGEST_SCHEMA_VERSION; if (inboundSourceClosure != null) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImpl.java index c8fa789db0..3c5f3e17ea 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImpl.java @@ -63,10 +63,9 @@ public WorldEventDto scheduleEvent(WorldEventDto dto) { RegionInstance regionInstance = regionInstanceRepository .findById(dto.regionId()) - .orElseThrow( - () -> - new IllegalArgumentException( - "REGION_INSTANCE_NOT_FOUND: runtime region instance not found")); + .orElseThrow(() -> + new IllegalArgumentException( + "REGION_INSTANCE_NOT_FOUND: runtime region instance not found")); if (dto.tenantId() == null || dto.gameInstanceId() == null || regionInstance.getTenantId() == null diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java index e0b10ea562..48cc2d1228 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java @@ -506,46 +506,40 @@ WorldInstanceLifecycleSnapshotDto prepareRunOwnedFixture( // GS response bytes; that retained response, rather than a fresh read nonce, seals the plan. RunOwnedWorldFixedPresetResources.plan(fixtureEvidence, sourceReceipt, versionIdentity); WorldCanonicalInstanceAssociation allocated = - executeFixtureOwnerTransaction( - () -> { + executeFixtureOwnerTransaction(() -> { + owners + .associationRepository() + .lockRunOwnedFixtureInOwnerTransaction(fixtureEvidence, originalGameSessionRequest); + owners + .publicationFenceRepository() + .lockOpen( + new OwnerBinding( + sourceReceipt.targetNamespace(), + sourceReceipt.canonicalTenantId(), + versionIdentity.canonicalVersionId(), + versionIdentity.operationId(), + versionIdentity.gameDesignVersionId(), + sourceReceipt.intakeRequestId(), + sourceReceipt.operationId(), + sourceReceipt.requestDigest(), + sourceReceipt.sourceOperationId(), + sourceReceipt.sourceEvidenceDigest(), + sourceReceipt.receiptDigest())); + WorldCanonicalInstanceAssociation association = owners .associationRepository() - .lockRunOwnedFixtureInOwnerTransaction( - fixtureEvidence, originalGameSessionRequest); - owners - .publicationFenceRepository() - .lockOpen( - new OwnerBinding( - sourceReceipt.targetNamespace(), - sourceReceipt.canonicalTenantId(), - versionIdentity.canonicalVersionId(), - versionIdentity.operationId(), - versionIdentity.gameDesignVersionId(), - sourceReceipt.intakeRequestId(), - sourceReceipt.operationId(), - sourceReceipt.requestDigest(), - sourceReceipt.sourceOperationId(), - sourceReceipt.sourceEvidenceDigest(), - sourceReceipt.receiptDigest())); - WorldCanonicalInstanceAssociation association = - owners - .associationRepository() - .allocateRunOwnedFixtureInOwnerTransaction( - fixtureEvidence, - originalGameSessionRequest, - sourceReceipt, - versionIdentity); - var retainedPlan = - RunOwnedWorldFixedPresetResources.plan( - association, sourceReceipt, versionIdentity); - RunOwnedWorldFixedPresetResources.materialize( - dsl, - fixtureEvidence, - retainedPlan, - association.worldInstanceId(), - association.worldPrivateKeys().gameInstanceId()); - return association; - }); + .allocateRunOwnedFixtureInOwnerTransaction( + fixtureEvidence, originalGameSessionRequest, sourceReceipt, versionIdentity); + var retainedPlan = + RunOwnedWorldFixedPresetResources.plan(association, sourceReceipt, versionIdentity); + RunOwnedWorldFixedPresetResources.materialize( + dsl, + fixtureEvidence, + retainedPlan, + association.worldInstanceId(), + association.worldPrivateKeys().gameInstanceId()); + return association; + }); WorldCanonicalInstanceAssociation committed = owners .associationRepository() @@ -559,10 +553,9 @@ WorldInstanceLifecycleSnapshotDto prepareRunOwnedFixture( WorldInstance materialized = worldInstanceRepository .findById(committed.worldInstanceId()) - .orElseThrow( - () -> - new IllegalStateException( - "RUN_OWNED_WORLD_INSTANCE_MISSING: committed fixture World row is missing")); + .orElseThrow(() -> + new IllegalStateException( + "RUN_OWNED_WORLD_INSTANCE_MISSING: committed fixture World row is missing")); var keys = committed.worldPrivateKeys(); PreparedWorldInstanceRequest worldRequest = new PreparedWorldInstanceRequest( @@ -985,20 +978,18 @@ public WorldInstanceLifecycleSnapshotDto failPreparedWorldInstance( requireNoAmbientFixtureReadTransaction(); RunOwnedWorldLaunchEvidence fixtureEvidence = runOwnedWorldLaunchEvidenceProvider.requireAuthenticatedEvidence(); - return executeOwnedLifecycleTransaction( - () -> - failPreparedWorldInstanceOwned( - tenantId, gameInstanceId, expectedLifecycleEpoch, reason, fixtureEvidence)); + return executeOwnedLifecycleTransaction(() -> + failPreparedWorldInstanceOwned( + tenantId, gameInstanceId, expectedLifecycleEpoch, reason, fixtureEvidence)); } if (prepareTransactionOperations == null) { return failPreparedWorldInstanceOwned( tenantId, gameInstanceId, expectedLifecycleEpoch, reason, null); } return Objects.requireNonNull( - prepareTransactionOperations.execute( - status -> - failPreparedWorldInstanceOwned( - tenantId, gameInstanceId, expectedLifecycleEpoch, reason, null)), + prepareTransactionOperations.execute(status -> + failPreparedWorldInstanceOwned( + tenantId, gameInstanceId, expectedLifecycleEpoch, reason, null)), "Ordinary failure transaction returned no World snapshot"); } @@ -1056,15 +1047,14 @@ public WorldInstanceLifecycleSnapshotDto terminateWorldInstance( } RunOwnedWorldLaunchEvidence fixtureEvidence = configuredFixtureEvidence(); WorldInstance worldInstance = - executeOwnedLifecycleTransaction( - () -> - beginOrResumeTermination( - tenantId, - gameInstanceId, - expectedLifecycleEpoch, - terminationRequestId, - reason, - fixtureEvidence)); + executeOwnedLifecycleTransaction(() -> + beginOrResumeTermination( + tenantId, + gameInstanceId, + expectedLifecycleEpoch, + terminationRequestId, + reason, + fixtureEvidence)); if (STATUS_TERMINATED.equals(worldInstance.getStatus())) { return snapshot(worldInstance); } @@ -1078,28 +1068,26 @@ public WorldInstanceLifecycleSnapshotDto terminateWorldInstance( cleanupResponse.getError().getCode() + ": " + cleanupResponse.getError().getMessage()); } WorldInstanceLifecycleSnapshotDto terminatedSnapshot = - executeOwnedLifecycleTransaction( - () -> { - WorldInstance finalWorldInstance = - requireLockedWorldInstance(tenantId, gameInstanceId); - requireLegacyFixtureLifecycleOwner(finalWorldInstance, fixtureEvidence); - if (!terminationRequestId.equals(finalWorldInstance.getTerminationRequestId())) { - throw new IllegalArgumentException( - "INVALID_WORLD_INSTANCE_STATE: world instance termination request changed before finalization"); - } - if (STATUS_TERMINATED.equals(finalWorldInstance.getStatus())) { - return snapshot(finalWorldInstance); - } - if (!STATUS_TERMINATING.equals(finalWorldInstance.getStatus())) { - throw new IllegalArgumentException( - "INVALID_WORLD_INSTANCE_STATE: world instance is not terminating during finalization"); - } - cleanupWorldRuntimeState(tenantId, gameInstanceId); - finalWorldInstance.setStatus(STATUS_TERMINATED); - finalWorldInstance.setLifecycleEpoch(finalWorldInstance.getLifecycleEpoch() + 1L); - finalWorldInstance.setTerminatedAt(Instant.now()); - return snapshot(worldInstanceRepository.save(finalWorldInstance)); - }); + executeOwnedLifecycleTransaction(() -> { + WorldInstance finalWorldInstance = requireLockedWorldInstance(tenantId, gameInstanceId); + requireLegacyFixtureLifecycleOwner(finalWorldInstance, fixtureEvidence); + if (!terminationRequestId.equals(finalWorldInstance.getTerminationRequestId())) { + throw new IllegalArgumentException( + "INVALID_WORLD_INSTANCE_STATE: world instance termination request changed before finalization"); + } + if (STATUS_TERMINATED.equals(finalWorldInstance.getStatus())) { + return snapshot(finalWorldInstance); + } + if (!STATUS_TERMINATING.equals(finalWorldInstance.getStatus())) { + throw new IllegalArgumentException( + "INVALID_WORLD_INSTANCE_STATE: world instance is not terminating during finalization"); + } + cleanupWorldRuntimeState(tenantId, gameInstanceId); + finalWorldInstance.setStatus(STATUS_TERMINATED); + finalWorldInstance.setLifecycleEpoch(finalWorldInstance.getLifecycleEpoch() + 1L); + finalWorldInstance.setTerminatedAt(Instant.now()); + return snapshot(worldInstanceRepository.save(finalWorldInstance)); + }); logger.info( "Terminated world instance tenant={} gameInstanceId={} terminationRequestId={}", tenantId, @@ -1158,9 +1146,8 @@ private T executeOwnedLifecycleTransaction(java.util.function.Supplier op private WorldInstance requireLockedWorldInstance(long tenantId, long gameInstanceId) { return worldInstanceRepository .findByTenantIdAndGameInstanceIdForUpdate(tenantId, gameInstanceId) - .orElseThrow( - () -> - new IllegalArgumentException("WORLD_INSTANCE_NOT_FOUND: world instance not found")); + .orElseThrow(() -> + new IllegalArgumentException("WORLD_INSTANCE_NOT_FOUND: world instance not found")); } private void cleanupWorldRuntimeState(long tenantId, long gameInstanceId) { @@ -1266,9 +1253,8 @@ private void validateAttestedLaunchInputs(PreparedWorldInstanceRequest request) private WorldInstance requireWorldInstance(long tenantId, long gameInstanceId) { return worldInstanceRepository .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) - .orElseThrow( - () -> - new IllegalArgumentException("WORLD_INSTANCE_NOT_FOUND: world instance not found")); + .orElseThrow(() -> + new IllegalArgumentException("WORLD_INSTANCE_NOT_FOUND: world instance not found")); } private void materializeRoomTopology( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldUpgradeValidationServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldUpgradeValidationServiceImpl.java index 1ed498f122..1565b537a0 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldUpgradeValidationServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldUpgradeValidationServiceImpl.java @@ -57,10 +57,9 @@ public WorldUpgradeValidationResultDto validateWorldUpgradeMappings( var worldInstance = worldInstanceRepository .findByTenantIdAndGameInstanceId(tenantId, sourceGameInstanceId) - .orElseThrow( - () -> - new IllegalArgumentException( - "NOT_FOUND: world instance not found for source game instance")); + .orElseThrow(() -> + new IllegalArgumentException( + "NOT_FOUND: world instance not found for source game instance")); long regionCount = regionInstanceRepository.countByTenantIdAndGameInstanceId(tenantId, sourceGameInstanceId); long zoneCount = diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcService.java index 4e41e7a5cd..b791863e34 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcService.java @@ -96,9 +96,8 @@ public void readInitialPlayerLocation( response = service .read(selection) - .map( - retained -> - CanonicalInitialPlayerLocationGrpcCodec.toResponse(selection, retained)); + .map(retained -> + CanonicalInitialPlayerLocationGrpcCodec.toResponse(selection, retained)); } catch (StatusRuntimeException rejected) { reportOwnerFailure( responseObserver, rejected, "World initial-player location read is unavailable"); @@ -176,9 +175,8 @@ public void readInitialPlayerLocationRegion( final Optional response; try { response = - retainedRegion.map( - retained -> - CanonicalInitialPlayerLocationGrpcCodec.toRegionResponse(selection, retained)); + retainedRegion.map(retained -> + CanonicalInitialPlayerLocationGrpcCodec.toRegionResponse(selection, retained)); } catch (IllegalStateException inconsistent) { fail( responseObserver, diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcService.java index 71625f2840..514070ab43 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcService.java @@ -28,8 +28,8 @@ /** * Opt-in gRPC adapter for authenticated authored-source intake and exact receipt readback. World - * binds the trusted namespace locally, and each method independently requires the exact same- - * namespace Game Design mTLS peer. + * binds the trusted namespace locally, and each method independently requires the exact + * same-namespace Game Design mTLS peer. */ public final class WorldAuthoredSourceIntakeGrpcService extends WorldAuthoredSourceIntakeServiceGrpc.WorldAuthoredSourceIntakeServiceImplBase { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java index d1c46d6b69..5ddf6ff0fa 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeService.java @@ -251,10 +251,9 @@ public WorldAuthoredSourceIntakeReceipt intakeRunOwnedFixture( WorldAuthoredSourceIntakeReceipt readback = repository .read(workloadNamespace, intakeRequestId) - .orElseThrow( - () -> - new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( - "Run-owned fixture source intake is missing after its owner commit")); + .orElseThrow(() -> + new WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException( + "Run-owned fixture source intake is missing after its owner commit")); requireReceiptForRequest( readback, intakeRequestId, diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java index 3263814463..fa008f6c5a 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityService.java @@ -401,10 +401,9 @@ private WorldAuthoredSourceIntakeReceipt readExactSourceIntake( worldSlug, sourceOperationId, sourceEvidenceDigest) - .orElseThrow( - () -> - new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( - "World Version identity requires an exact committed fresh source intake")); + .orElseThrow(() -> + new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "World Version identity requires an exact committed fresh source intake")); requireExactFreshSourceIntake( sourceReceipt, canonicalTenantId, worldSlug, sourceOperationId, sourceEvidenceDigest); return sourceReceipt; diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReader.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReader.java index eef2e438ff..6e1bd9a7e9 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReader.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReader.java @@ -131,10 +131,9 @@ public WorldCanonicalAuthoredGraph read(WorldDraftTopologyCommitPlan plan, byte[ throw invalid("Canonical graph content differs from exact typed original payload"); } if (expected.properties().stream() - .anyMatch( - entry -> - entry.getValue().isIntegralNumber() - && !actual.get(entry.getKey()).isIntegralNumber())) { + .anyMatch(entry -> + entry.getValue().isIntegralNumber() + && !actual.get(entry.getKey()).isIntegralNumber())) { throw invalid( "Canonical graph private selectors and integer content require integer representation"); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopology.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopology.java index 20ee3b41a1..78857d3d56 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopology.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopology.java @@ -43,15 +43,14 @@ public record Request(WorldDraftTopologyCommitPlan plan, CaptureRequest freeze) freeze.publishWorkflowId()); var expected = plan.binding().affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) + .map(unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) .toList(); if (expected.size() != freeze.suppliedOwnedAffectedTuples().size() || !new java.util.HashSet<>(expected) diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java index 80345c9c78..1ec76bbd64 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyRepository.java @@ -203,10 +203,9 @@ WorldCanonicalFrozenTopology capture(Request request) { Long.toString(provenance.localVersionKey()), graph .inboundSourceClosure() - .orElseThrow( - () -> - new ConflictException( - "Selected graph capture requires its exact original inbound closure"))) + .orElseThrow(() -> + new ConflictException( + "Selected graph capture requires its exact original inbound closure"))) : digestService.getDraftDesignDigest( Long.toString(provenance.localTenantKey()), Long.toString(provenance.localVersionKey())); @@ -436,19 +435,18 @@ private void cancel(Status reason) { try { Thread.ofVirtual() .name("world-frozen-topology-cancel") - .start( - () -> { - synchronized (ownership) { - try { - if (active != null) active.cancel(); - } catch (SQLException ignored) { - // Deadline refusal is delivered; the JDBC query timeout also remains. - } finally { - cancellationFinished = true; - releaseSlot(); - } - } - }); + .start(() -> { + synchronized (ownership) { + try { + if (active != null) active.cancel(); + } catch (SQLException ignored) { + // Deadline refusal is delivered; the JDBC query timeout also remains. + } finally { + cancellationFinished = true; + releaseSlot(); + } + } + }); } catch (RuntimeException | Error startFailure) { synchronized (ownership) { // No cancellation worker owns resources. JDBC's timeout remains the backstop, and diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java index 61b41b74de..71e71536e1 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java @@ -60,138 +60,133 @@ public HoldIdentity acquire( Objects.requireNonNull(lifecycleRequest, "lifecycleRequest"); requireNoAmbientTransaction("Canonical World hold acquisition"); requireLifecycleTarget(request, lifecycleRequest); - return writeTransaction.execute( - status -> { - requireWritableOwnerTransaction(); - WorldCanonicalInstanceAssociation association = - associationRepository - .readOwnerAssociationInActivationTransaction(request.canonicalGameInstanceId()) - .orElseThrow( - () -> - new InvalidHoldEvidenceException( - "Canonical World association is unavailable")); - requireAssociationTarget(request, association); - if (association.isRunOwnedFixture()) { - throw new InvalidHoldEvidenceException( - "Run-owned fixture rows cannot acquire canonical initial-admission holds"); - } - requireLifecycleRequestAssociation(lifecycleRequest, association); - LockedWorldLifecycle lockedLifecycle = lockWorldLifecycleRow(request, association); + return writeTransaction.execute(status -> { + requireWritableOwnerTransaction(); + WorldCanonicalInstanceAssociation association = + associationRepository + .readOwnerAssociationInActivationTransaction(request.canonicalGameInstanceId()) + .orElseThrow(() -> + new InvalidHoldEvidenceException("Canonical World association is unavailable")); + requireAssociationTarget(request, association); + if (association.isRunOwnedFixture()) { + throw new InvalidHoldEvidenceException( + "Run-owned fixture rows cannot acquire canonical initial-admission holds"); + } + requireLifecycleRequestAssociation(lifecycleRequest, association); + LockedWorldLifecycle lockedLifecycle = lockWorldLifecycleRow(request, association); - long localTenantKey = association.worldPrepareFields().privateTenantKey(); - Record existing = - dsl.fetchOne( - "SELECT * FROM initial_admission_bind_hold " - + "WHERE tenant_id=? AND initial_admission_request_id=? FOR UPDATE", - localTenantKey, - request.initialAdmissionRequestId()); - if (existing != null) { - HoldIdentity identity = requireStoredIdentity(existing, request); - String existingStatus = required(existing, "status", String.class); - if ("PENDING".equals(existingStatus)) { - if (!"ACTIVE".equals(lockedLifecycle.status()) - || lockedLifecycle.epoch() != request.activeLifecycleEpoch()) { - throw new InvalidHoldEvidenceException( - "Pending canonical World hold lost its exact ACTIVE lifecycle epoch"); - } - } else if (!"COMMITTED".equals(existingStatus) && !"ABORTED".equals(existingStatus)) { - throw new InvalidHoldEvidenceException( - "Retained canonical World hold has an unsupported status"); - } - return identity; - } + long localTenantKey = association.worldPrepareFields().privateTenantKey(); + Record existing = + dsl.fetchOne( + "SELECT * FROM initial_admission_bind_hold " + + "WHERE tenant_id=? AND initial_admission_request_id=? FOR UPDATE", + localTenantKey, + request.initialAdmissionRequestId()); + if (existing != null) { + HoldIdentity identity = requireStoredIdentity(existing, request); + String existingStatus = required(existing, "status", String.class); + if ("PENDING".equals(existingStatus)) { if (!"ACTIVE".equals(lockedLifecycle.status()) || lockedLifecycle.epoch() != request.activeLifecycleEpoch()) { throw new InvalidHoldEvidenceException( - "Canonical World hold requires the exact current ACTIVE lifecycle epoch"); - } - - WorldCanonicalInstanceLifecycleEvidence lifecycle = - lifecycleRepository - .readForActivationInOwnerTransaction(lifecycleRequest) - .orElseThrow( - () -> - new InvalidHoldEvidenceException( - "Exact canonical World lifecycle evidence is unavailable")); - if (!"ACTIVE".equals(lifecycle.lifecycleStatus()) - || lifecycle.lifecycleEpoch() != request.activeLifecycleEpoch()) { - throw new InvalidHoldEvidenceException( - "Canonical World hold requires the exact current ACTIVE lifecycle evidence"); + "Pending canonical World hold lost its exact ACTIVE lifecycle epoch"); } + } else if (!"COMMITTED".equals(existingStatus) && !"ABORTED".equals(existingStatus)) { + throw new InvalidHoldEvidenceException( + "Retained canonical World hold has an unsupported status"); + } + return identity; + } + if (!"ACTIVE".equals(lockedLifecycle.status()) + || lockedLifecycle.epoch() != request.activeLifecycleEpoch()) { + throw new InvalidHoldEvidenceException( + "Canonical World hold requires the exact current ACTIVE lifecycle epoch"); + } - Record activeForRealm = - dsl.fetchOne( - "SELECT hold_id FROM initial_admission_bind_hold " - + "WHERE tenant_id=? AND realm_uuid=? " - + "AND status IN ('PENDING','RECONCILIATION_REQUIRED') LIMIT 1", - localTenantKey, - request.realmId()); - if (activeForRealm != null) { - throw new HoldConflictException( - "A nonterminal initial-admission hold already owns this canonical realm"); - } + WorldCanonicalInstanceLifecycleEvidence lifecycle = + lifecycleRepository + .readForActivationInOwnerTransaction(lifecycleRequest) + .orElseThrow(() -> + new InvalidHoldEvidenceException( + "Exact canonical World lifecycle evidence is unavailable")); + if (!"ACTIVE".equals(lifecycle.lifecycleStatus()) + || lifecycle.lifecycleEpoch() != request.activeLifecycleEpoch()) { + throw new InvalidHoldEvidenceException( + "Canonical World hold requires the exact current ACTIVE lifecycle evidence"); + } - UUID holdId = UUID.randomUUID(); - UUID holdFence = UUID.randomUUID(); - byte[] canonicalRequestBytes = request.canonicalRequestBytes(); - dsl.execute( - "INSERT INTO initial_admission_bind_hold (" - + "hold_id,hold_fence,tenant_id,realm_uuid,playable_state_namespace_uuid," - + "playable_state_scope,game_instance_id,version_id,active_lifecycle_epoch," - + "initial_admission_request_id,request_digest,expected_no_prior_pointer," - + "expected_catalog_revision,status,diagnostic_expires_at,canonical_target_namespace," - + "canonical_tenant_id,canonical_world_slug,canonical_game_instance_id," - + "canonical_version_id,initial_admission_origin,expected_prior_pointer_version," - + "canonical_request_bytes,hold_binding_digest) " - + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,'PENDING',CURRENT_TIMESTAMP + INTERVAL '15 minutes',?,?,?,?,?,?,?,?,?)", - holdId, - holdFence, + Record activeForRealm = + dsl.fetchOne( + "SELECT hold_id FROM initial_admission_bind_hold " + + "WHERE tenant_id=? AND realm_uuid=? " + + "AND status IN ('PENDING','RECONCILIATION_REQUIRED') LIMIT 1", localTenantKey, - request.realmId(), - request.playableStateNamespaceId(), - request.playableStateScope(), - association.worldPrepareFields().privateGameInstanceKey(), - association.worldPrepareFields().localVersionKey(), - request.activeLifecycleEpoch(), - request.initialAdmissionRequestId(), - request.initialAdmissionRequestDigest(), - request.initialAdmissionOrigin() - == WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, - request.expectedCatalogRevision(), - request.targetNamespace(), - request.canonicalTenantId(), - request.worldSlug(), - request.canonicalGameInstanceId(), - request.canonicalVersionId(), - request.initialAdmissionOrigin().name(), - request.expectedPriorPointerVersion(), - canonicalRequestBytes, - request.holdBindingDigest()); - return new HoldIdentity(request, holdId, holdFence); - }); + request.realmId()); + if (activeForRealm != null) { + throw new HoldConflictException( + "A nonterminal initial-admission hold already owns this canonical realm"); + } + + UUID holdId = UUID.randomUUID(); + UUID holdFence = UUID.randomUUID(); + byte[] canonicalRequestBytes = request.canonicalRequestBytes(); + dsl.execute( + "INSERT INTO initial_admission_bind_hold (" + + "hold_id,hold_fence,tenant_id,realm_uuid,playable_state_namespace_uuid," + + "playable_state_scope,game_instance_id,version_id,active_lifecycle_epoch," + + "initial_admission_request_id,request_digest,expected_no_prior_pointer," + + "expected_catalog_revision,status,diagnostic_expires_at,canonical_target_namespace," + + "canonical_tenant_id,canonical_world_slug,canonical_game_instance_id," + + "canonical_version_id,initial_admission_origin,expected_prior_pointer_version," + + "canonical_request_bytes,hold_binding_digest) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,'PENDING',CURRENT_TIMESTAMP + INTERVAL '15 minutes',?,?,?,?,?,?,?,?,?)", + holdId, + holdFence, + localTenantKey, + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + association.worldPrepareFields().privateGameInstanceKey(), + association.worldPrepareFields().localVersionKey(), + request.activeLifecycleEpoch(), + request.initialAdmissionRequestId(), + request.initialAdmissionRequestDigest(), + request.initialAdmissionOrigin() + == WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + request.expectedCatalogRevision(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + request.initialAdmissionOrigin().name(), + request.expectedPriorPointerVersion(), + canonicalRequestBytes, + request.holdBindingDigest()); + return new HoldIdentity(request, holdId, holdFence); + }); } /** Historical immutable identity read. Absence is not an abort or a release signal. */ public Optional readIdentity(Request request) { Objects.requireNonNull(request, "request"); requireNoAmbientTransaction("Canonical World hold identity read"); - return readTransaction.execute( - status -> { - requireReadOnlyRepeatableReadOwnerTransaction(); - Record row = - dsl.fetchOne( - "SELECT * FROM initial_admission_bind_hold " - + "WHERE canonical_target_namespace=? AND canonical_tenant_id=? " - + "AND canonical_world_slug=? AND canonical_game_instance_id=? " - + "AND initial_admission_request_id=? AND canonical_request_bytes=?", - request.targetNamespace(), - request.canonicalTenantId(), - request.worldSlug(), - request.canonicalGameInstanceId(), - request.initialAdmissionRequestId(), - request.canonicalRequestBytes()); - return row == null ? Optional.empty() : Optional.of(requireStoredIdentity(row, request)); - }); + return readTransaction.execute(status -> { + requireReadOnlyRepeatableReadOwnerTransaction(); + Record row = + dsl.fetchOne( + "SELECT * FROM initial_admission_bind_hold " + + "WHERE canonical_target_namespace=? AND canonical_tenant_id=? " + + "AND canonical_world_slug=? AND canonical_game_instance_id=? " + + "AND initial_admission_request_id=? AND canonical_request_bytes=?", + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.canonicalGameInstanceId(), + request.initialAdmissionRequestId(), + request.canonicalRequestBytes()); + return row == null ? Optional.empty() : Optional.of(requireStoredIdentity(row, request)); + }); } /** Read-only same-snapshot observation of durable hold status and current World lifecycle. */ @@ -201,36 +196,32 @@ public Optional readState( Objects.requireNonNull(lifecycleRequest, "lifecycleRequest"); requireNoAmbientTransaction("Canonical World hold state read"); requireLifecycleTarget(identity.request(), lifecycleRequest); - return readTransaction.execute( - status -> { - requireReadOnlyRepeatableReadOwnerTransaction(); - Record row = - dsl.fetchOne( - "SELECT * FROM initial_admission_bind_hold WHERE hold_id=? AND hold_fence=?", - identity.holdId(), - identity.holdFence()); - if (row == null) return Optional.empty(); - requireStoredIdentity(row, identity.request(), identity); - WorldCanonicalInstanceAssociation association = - associationRepository - .readOwnerAssociationInOwnerTransaction( - identity.request().canonicalGameInstanceId()) - .orElseThrow( - () -> - new InvalidHoldEvidenceException( - "Canonical World association is unavailable in the hold snapshot")); - requireAssociationTarget(identity.request(), association); - WorldCanonicalInstanceLifecycleEvidence lifecycle = - lifecycleRepository - .readForCurrentLocationInOwnerTransaction(lifecycleRequest) - .orElseThrow( - () -> - new InvalidHoldEvidenceException( - "Canonical World lifecycle is unavailable in the hold snapshot")); - return Optional.of( - new WorldCanonicalInitialAdmissionHoldState( - identity, parseStatus(required(row, "status", String.class)), lifecycle)); - }); + return readTransaction.execute(status -> { + requireReadOnlyRepeatableReadOwnerTransaction(); + Record row = + dsl.fetchOne( + "SELECT * FROM initial_admission_bind_hold WHERE hold_id=? AND hold_fence=?", + identity.holdId(), + identity.holdFence()); + if (row == null) return Optional.empty(); + requireStoredIdentity(row, identity.request(), identity); + WorldCanonicalInstanceAssociation association = + associationRepository + .readOwnerAssociationInOwnerTransaction(identity.request().canonicalGameInstanceId()) + .orElseThrow(() -> + new InvalidHoldEvidenceException( + "Canonical World association is unavailable in the hold snapshot")); + requireAssociationTarget(identity.request(), association); + WorldCanonicalInstanceLifecycleEvidence lifecycle = + lifecycleRepository + .readForCurrentLocationInOwnerTransaction(lifecycleRequest) + .orElseThrow(() -> + new InvalidHoldEvidenceException( + "Canonical World lifecycle is unavailable in the hold snapshot")); + return Optional.of( + new WorldCanonicalInitialAdmissionHoldState( + identity, parseStatus(required(row, "status", String.class)), lifecycle)); + }); } /** Applies only an exact terminal Game Session owner proof through the guarded SQL finalizer. */ @@ -250,54 +241,53 @@ void settle(HoldIdentity identity, GameSessionCanonicalInitialAdmissionOwnerProo String proofBytesDigest = prefixedDigest(proofBytes); String ownerProofDigest = proof.proofDigest().substring("sha256:".length()); - writeTransaction.executeWithoutResult( - status -> { - requireWritableOwnerTransaction(); - // Keep the preliminary status check unlocked. The guarded finalizer locks the actual - // World lifecycle row first and the hold second, matching acquisition and termination. - Record held = - dsl.fetchOne( - "SELECT * FROM initial_admission_bind_hold WHERE hold_id=?", identity.holdId()); - if (held == null) { - throw new InvalidHoldEvidenceException("Canonical World hold identity is not retained"); - } - requireStoredIdentity(held, identity.request(), identity); - String currentStatus = required(held, "status", String.class); - if ("COMMITTED".equals(currentStatus) || "ABORTED".equals(currentStatus)) { - byte[] currentProof = held.get("canonical_owner_proof_bytes", byte[].class); - String currentDigest = held.get("canonical_owner_proof_digest", String.class); - if (currentStatus.equals(proof.outcome().name()) - && Arrays.equals(currentProof, proofBytes) - && proofBytesDigest.equals(currentDigest)) { - return; - } - throw new InvalidHoldEvidenceException( - "Canonical World hold is already settled by a different terminal proof"); - } - if (!"PENDING".equals(currentStatus)) { - throw new InvalidHoldEvidenceException( - "Canonical World hold is not in its exact pending state"); - } - - Long pointerVersion = proof.committedPointerVersion(); - String auditEventId = - proof.auditEventId() == null ? null : Long.toString(proof.auditEventId()); + writeTransaction.executeWithoutResult(status -> { + requireWritableOwnerTransaction(); + // Keep the preliminary status check unlocked. The guarded finalizer locks the actual + // World lifecycle row first and the hold second, matching acquisition and termination. + Record held = dsl.fetchOne( - "SELECT world_finalize_canonical_initial_admission_hold(" - + "?::uuid,?::uuid,?::text,?::text,?::text,?::text,?::bigint," - + "?::timestamptz,?::boolean,?::bytea,?::text)", - identity.holdId(), - identity.holdFence(), - proof.outcome().name(), - identity.request().initialAdmissionRequestId(), - ownerProofDigest, - auditEventId, - pointerVersion, - OffsetDateTime.ofInstant(proof.terminalAt(), ZoneOffset.UTC), - proof.positiveDurableAbort(), - proofBytes, - proofBytesDigest); - }); + "SELECT * FROM initial_admission_bind_hold WHERE hold_id=?", identity.holdId()); + if (held == null) { + throw new InvalidHoldEvidenceException("Canonical World hold identity is not retained"); + } + requireStoredIdentity(held, identity.request(), identity); + String currentStatus = required(held, "status", String.class); + if ("COMMITTED".equals(currentStatus) || "ABORTED".equals(currentStatus)) { + byte[] currentProof = held.get("canonical_owner_proof_bytes", byte[].class); + String currentDigest = held.get("canonical_owner_proof_digest", String.class); + if (currentStatus.equals(proof.outcome().name()) + && Arrays.equals(currentProof, proofBytes) + && proofBytesDigest.equals(currentDigest)) { + return; + } + throw new InvalidHoldEvidenceException( + "Canonical World hold is already settled by a different terminal proof"); + } + if (!"PENDING".equals(currentStatus)) { + throw new InvalidHoldEvidenceException( + "Canonical World hold is not in its exact pending state"); + } + + Long pointerVersion = proof.committedPointerVersion(); + String auditEventId = + proof.auditEventId() == null ? null : Long.toString(proof.auditEventId()); + dsl.fetchOne( + "SELECT world_finalize_canonical_initial_admission_hold(" + + "?::uuid,?::uuid,?::text,?::text,?::text,?::text,?::bigint," + + "?::timestamptz,?::boolean,?::bytea,?::text)", + identity.holdId(), + identity.holdFence(), + proof.outcome().name(), + identity.request().initialAdmissionRequestId(), + ownerProofDigest, + auditEventId, + pointerVersion, + OffsetDateTime.ofInstant(proof.terminalAt(), ZoneOffset.UTC), + proof.positiveDurableAbort(), + proofBytes, + proofBytesDigest); + }); } private static void requireTerminalProof( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java index 24c189645b..d1497de7f9 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialPlayerLocationRepository.java @@ -263,10 +263,9 @@ public Result store(Request request) { Boolean retained = writeTransaction.execute(status -> storeInOwnerTransaction(request)); if (!Boolean.TRUE.equals(retained)) return Result.unregistered(); return read(request) - .orElseThrow( - () -> - new InvalidInitialLocationReadbackException( - "World initial-location operation disappeared after owner commit")); + .orElseThrow(() -> + new InvalidInitialLocationReadbackException( + "World initial-location operation disappeared after owner commit")); } /** Reads only the exact retained operation and its associated location row, when APPLIED. */ @@ -274,11 +273,10 @@ public Optional read(Request request) { Objects.requireNonNull(request, "request"); requireNoActiveTransaction("World canonical initial-location result read"); return Optional.ofNullable( - readTransaction.execute( - status -> { - requireReadOnlyRepeatableReadTransaction(); - return readInOwnerTransaction(request).orElse(null); - })); + readTransaction.execute(status -> { + requireReadOnlyRepeatableReadTransaction(); + return readInOwnerTransaction(request).orElse(null); + })); } /** @@ -295,20 +293,18 @@ public Optional readByOperationId(UUID operationId, RequestSelector sele } requireNoActiveTransaction("World canonical initial-location operation read"); return Optional.ofNullable( - readTransaction.execute( - status -> { - requireReadOnlyRepeatableReadTransaction(); - Record operation = readOperation(operationId); - if (operation == null) return null; - Request retainedRequest = retainedRequest(operation, operationId); - ParsedRequest parsed = parseRequest(retainedRequest); - selector.requireMatches(parsed); - return readInOwnerTransaction(retainedRequest) - .orElseThrow( - () -> - invalidReadback( - "Retained World initial-location operation disappeared during readback")); - })); + readTransaction.execute(status -> { + requireReadOnlyRepeatableReadTransaction(); + Record operation = readOperation(operationId); + if (operation == null) return null; + Request retainedRequest = retainedRequest(operation, operationId); + ParsedRequest parsed = parseRequest(retainedRequest); + selector.requireMatches(parsed); + return readInOwnerTransaction(retainedRequest) + .orElseThrow(() -> + invalidReadback( + "Retained World initial-location operation disappeared during readback")); + })); } /** @@ -320,54 +316,51 @@ public Optional readInitialPlayerLocationRegion(RequestSelector se Objects.requireNonNull(selector, "selector"); requireNoActiveTransaction("World canonical initial-location region read"); return Optional.ofNullable( - readTransaction.execute( - status -> { - requireReadOnlyRepeatableReadTransaction(); - Record operation = readOperation(selector.operationId()); - if (operation == null) return null; - Request retainedRequest = retainedRequest(operation, selector.operationId()); - ParsedRequest parsed = parseRequest(retainedRequest); - selector.requireMatches(parsed); - Result placement = - readInOwnerTransaction(retainedRequest) - .orElseThrow( - () -> - invalidReadback( - "Retained World initial-location operation disappeared during region read")); - if (placement.outcome() != Outcome.APPLIED - || placement.startLocation() == null - || placement.runtimeRoomInstanceId() == null) { - throw invalidReadback( - "Initial-location region consequence requires the retained APPLIED placement"); - } - - WorldCanonicalInstanceLifecycleEvidence retainedLifecycle = - WorldCanonicalInstanceLifecycleEvidence.fromStored( - retainedRequest.originalLifecycleEvidenceBytes()); - WorldCanonicalInstanceLifecycleEvidence currentLifecycle; - try { - currentLifecycle = - lifecycleRepository - .readForCurrentLocationInOwnerTransaction(retainedLifecycle.request()) - .orElse(null); - } catch ( - WorldCanonicalInstanceLifecycleReadRepository.InvalidLifecycleEvidenceException - invalid) { - throw invalidReadback( - "Current World lifecycle evidence is inconsistent with initial placement", - invalid); - } - requireCurrentLifecycle(retainedLifecycle, currentLifecycle, placement, parsed); - RegionMapping mapping = - readInitialRegionMapping(retainedRequest, placement, parsed, currentLifecycle); - return new RegionResult( - placement, - mapping.worldInstanceId(), - mapping.runtimeRoomInstanceId(), - mapping.canonicalRegionInstanceId(), - mapping.operationalRegionId(), - currentLifecycle); - })); + readTransaction.execute(status -> { + requireReadOnlyRepeatableReadTransaction(); + Record operation = readOperation(selector.operationId()); + if (operation == null) return null; + Request retainedRequest = retainedRequest(operation, selector.operationId()); + ParsedRequest parsed = parseRequest(retainedRequest); + selector.requireMatches(parsed); + Result placement = + readInOwnerTransaction(retainedRequest) + .orElseThrow(() -> + invalidReadback( + "Retained World initial-location operation disappeared during region read")); + if (placement.outcome() != Outcome.APPLIED + || placement.startLocation() == null + || placement.runtimeRoomInstanceId() == null) { + throw invalidReadback( + "Initial-location region consequence requires the retained APPLIED placement"); + } + + WorldCanonicalInstanceLifecycleEvidence retainedLifecycle = + WorldCanonicalInstanceLifecycleEvidence.fromStored( + retainedRequest.originalLifecycleEvidenceBytes()); + WorldCanonicalInstanceLifecycleEvidence currentLifecycle; + try { + currentLifecycle = + lifecycleRepository + .readForCurrentLocationInOwnerTransaction(retainedLifecycle.request()) + .orElse(null); + } catch ( + WorldCanonicalInstanceLifecycleReadRepository.InvalidLifecycleEvidenceException + invalid) { + throw invalidReadback( + "Current World lifecycle evidence is inconsistent with initial placement", invalid); + } + requireCurrentLifecycle(retainedLifecycle, currentLifecycle, placement, parsed); + RegionMapping mapping = + readInitialRegionMapping(retainedRequest, placement, parsed, currentLifecycle); + return new RegionResult( + placement, + mapping.worldInstanceId(), + mapping.runtimeRoomInstanceId(), + mapping.canonicalRegionInstanceId(), + mapping.operationalRegionId(), + currentLifecycle); + })); } private Request retainedRequest(Record operation, UUID operationId) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java index 1f2176b0dc..48ec6c0817 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepository.java @@ -58,21 +58,20 @@ public Optional readResult( Objects.requireNonNull(request, "request"); requireNoActiveTransaction("World canonical activation result read"); return Optional.ofNullable( - readTransaction.execute( - status -> { - requireReadOnlyRepeatableReadTransaction(); - // The old request-only transport path may replay retained V43 proofs, but it must - // not disclose a new V65 protected terminal without the exact Account protection - // identity that binds the receipt. - if (dsl.fetchOne( - "SELECT 1 FROM world_canonical_instance_activation_fence " - + "WHERE activation_request_id=?", - request.activationRequestId()) - != null) { - return null; - } - return readResultInCurrentTransaction(request).orElse(null); - })); + readTransaction.execute(status -> { + requireReadOnlyRepeatableReadTransaction(); + // The old request-only transport path may replay retained V43 proofs, but it must + // not disclose a new V65 protected terminal without the exact Account protection + // identity that binds the receipt. + if (dsl.fetchOne( + "SELECT 1 FROM world_canonical_instance_activation_fence " + + "WHERE activation_request_id=?", + request.activationRequestId()) + != null) { + return null; + } + return readResultInCurrentTransaction(request).orElse(null); + })); } /** @@ -84,44 +83,42 @@ public Optional readTermina Objects.requireNonNull(protection, "protection"); requireNoActiveTransaction("World original StartSession activation terminal read"); return Optional.ofNullable( - readTransaction.execute( - status -> { - requireReadOnlyRepeatableReadTransaction(); - Record row = - activationFence( - protection.request().worldActivationRequest().activationRequestId()); - if (row == null) return null; - requireSameProtectionIdentity(row, protection); - String state = required(row, "operation_state", String.class); - if ("PENDING".equals(state)) return null; - byte[] terminalBytes = required(row, "terminal_evidence_bytes", byte[].class); - if (!required(row, "terminal_evidence_digest", String.class) - .equals(digest(terminalBytes))) { - throw new InvalidActivationEvidenceException( - "Stored original StartSession activation terminal digest is inconsistent"); - } - try { - WorldOriginalStartSessionActivationTerminalEvidence terminal = - WorldOriginalStartSessionActivationTerminalEvidence.decode(terminalBytes); - if (terminal.worldActivationFence() - != required(row, "world_activation_fence", Long.class) - || !terminal - .activationRequestId() - .equals(protection.request().worldActivationRequest().activationRequestId()) - || !terminal - .accountProtectionEvidence() - .requestDigest() - .equals(protection.requestDigest()) - || !terminal.outcome().name().equals(state)) { - throw new InvalidActivationEvidenceException( - "Stored World activation terminal differs from its durable operation fence"); - } - return terminal; - } catch (IllegalArgumentException invalid) { - throw new InvalidActivationEvidenceException( - "Stored World activation terminal evidence is invalid", invalid); - } - })); + readTransaction.execute(status -> { + requireReadOnlyRepeatableReadTransaction(); + Record row = + activationFence(protection.request().worldActivationRequest().activationRequestId()); + if (row == null) return null; + requireSameProtectionIdentity(row, protection); + String state = required(row, "operation_state", String.class); + if ("PENDING".equals(state)) return null; + byte[] terminalBytes = required(row, "terminal_evidence_bytes", byte[].class); + if (!required(row, "terminal_evidence_digest", String.class) + .equals(digest(terminalBytes))) { + throw new InvalidActivationEvidenceException( + "Stored original StartSession activation terminal digest is inconsistent"); + } + try { + WorldOriginalStartSessionActivationTerminalEvidence terminal = + WorldOriginalStartSessionActivationTerminalEvidence.decode(terminalBytes); + if (terminal.worldActivationFence() + != required(row, "world_activation_fence", Long.class) + || !terminal + .activationRequestId() + .equals(protection.request().worldActivationRequest().activationRequestId()) + || !terminal + .accountProtectionEvidence() + .requestDigest() + .equals(protection.requestDigest()) + || !terminal.outcome().name().equals(state)) { + throw new InvalidActivationEvidenceException( + "Stored World activation terminal differs from its durable operation fence"); + } + return terminal; + } catch (IllegalArgumentException invalid) { + throw new InvalidActivationEvidenceException( + "Stored World activation terminal evidence is invalid", invalid); + } + })); } /** @@ -135,85 +132,84 @@ public Optional readProtectedActivationByAcquisitio Objects.requireNonNull(input, "activation protection acquisition input"); requireNoActiveTransaction("World protected activation recovery read"); return Optional.ofNullable( - readTransaction.execute( - status -> { - requireReadOnlyRepeatableReadTransaction(); - var activation = input.worldActivationRequest(); - UUID activationId = activation.activationRequestId(); - UUID gameInstanceId = activation.canonicalGameInstanceId(); - var matchingRows = - dsl.fetch( - "SELECT * FROM world_canonical_instance_activation_fence " - + "WHERE activation_request_id=? OR canonical_game_instance_id=?", - activationId, - gameInstanceId); - if (matchingRows.size() > 1) { - throw new ActivationConflictException( - "Multiple World activation fences match the original request or canonical instance"); - } - Record row = matchingRows.isEmpty() ? null : matchingRows.get(0); - if (row != null) { - byte[] firstEvidenceBytes = - required(row, "account_protection_evidence_bytes", byte[].class); - if (!required(row, "account_protection_evidence_digest", String.class) - .equals(digest(firstEvidenceBytes))) { - throw new InvalidActivationEvidenceException( - "Stored Account activation protection digest is inconsistent"); - } - AccountStartSessionActivationProtectionEvidence firstProtection; - try { - firstProtection = - AccountStartSessionActivationProtectionEvidence.decode(firstEvidenceBytes); - } catch (IllegalArgumentException invalid) { - throw new InvalidActivationEvidenceException( - "Stored Account activation protection is invalid", invalid); - } - requireSameProtectionIdentity(row, firstProtection); - requireSameAcquisitionInput(input, firstProtection); - String state = required(row, "operation_state", String.class); - if ("PENDING".equals(state)) return ProtectedActivationReadback.pendingReadback(); - byte[] terminalBytes = required(row, "terminal_evidence_bytes", byte[].class); - if (!required(row, "terminal_evidence_digest", String.class) - .equals(digest(terminalBytes))) { - throw new InvalidActivationEvidenceException( - "Stored World activation terminal digest is inconsistent"); - } - WorldOriginalStartSessionActivationTerminalEvidence terminal = - decodeTerminal(terminalBytes); - byte[] resultBytes = required(row, "terminal_result_bytes", byte[].class); - if (!required(row, "terminal_result_digest", String.class) - .equals(digest(resultBytes))) { - throw new InvalidActivationEvidenceException( - "Stored World activation result digest is inconsistent"); - } - if (!Arrays.equals( - firstProtection.canonicalBytes(), - terminal.accountProtectionEvidence().canonicalBytes()) - || !Arrays.equals(resultBytes, terminal.activationResult().canonicalBytes()) - || !terminal.activationRequestId().equals(activationId) - || !terminal.outcome().name().equals(state) - || terminal.worldActivationFence() - != required(row, "world_activation_fence", Long.class)) { - throw new InvalidActivationEvidenceException( - "Stored World terminal differs from its original protected activation"); - } - return ProtectedActivationReadback.terminal(terminal); - } - - // V43-only results are retained history, not upgradeable protected receipts. Fail - // locally before asking Account to create a new protection operation. - if (!dsl.fetch( - "SELECT 1 FROM world_canonical_instance_activation_operation " - + "WHERE activation_request_id=? " - + "OR (canonical_game_instance_id=? AND outcome='COMMITTED')", - activationId, - gameInstanceId) - .isEmpty()) { - throw new ActivationConflictException( - "A retained legacy World activation result cannot be upgraded to protected activation"); - } - return null; - })); + readTransaction.execute(status -> { + requireReadOnlyRepeatableReadTransaction(); + var activation = input.worldActivationRequest(); + UUID activationId = activation.activationRequestId(); + UUID gameInstanceId = activation.canonicalGameInstanceId(); + var matchingRows = + dsl.fetch( + "SELECT * FROM world_canonical_instance_activation_fence " + + "WHERE activation_request_id=? OR canonical_game_instance_id=?", + activationId, + gameInstanceId); + if (matchingRows.size() > 1) { + throw new ActivationConflictException( + "Multiple World activation fences match the original request or canonical instance"); + } + Record row = matchingRows.isEmpty() ? null : matchingRows.get(0); + if (row != null) { + byte[] firstEvidenceBytes = + required(row, "account_protection_evidence_bytes", byte[].class); + if (!required(row, "account_protection_evidence_digest", String.class) + .equals(digest(firstEvidenceBytes))) { + throw new InvalidActivationEvidenceException( + "Stored Account activation protection digest is inconsistent"); + } + AccountStartSessionActivationProtectionEvidence firstProtection; + try { + firstProtection = + AccountStartSessionActivationProtectionEvidence.decode(firstEvidenceBytes); + } catch (IllegalArgumentException invalid) { + throw new InvalidActivationEvidenceException( + "Stored Account activation protection is invalid", invalid); + } + requireSameProtectionIdentity(row, firstProtection); + requireSameAcquisitionInput(input, firstProtection); + String state = required(row, "operation_state", String.class); + if ("PENDING".equals(state)) return ProtectedActivationReadback.pendingReadback(); + byte[] terminalBytes = required(row, "terminal_evidence_bytes", byte[].class); + if (!required(row, "terminal_evidence_digest", String.class) + .equals(digest(terminalBytes))) { + throw new InvalidActivationEvidenceException( + "Stored World activation terminal digest is inconsistent"); + } + WorldOriginalStartSessionActivationTerminalEvidence terminal = + decodeTerminal(terminalBytes); + byte[] resultBytes = required(row, "terminal_result_bytes", byte[].class); + if (!required(row, "terminal_result_digest", String.class) + .equals(digest(resultBytes))) { + throw new InvalidActivationEvidenceException( + "Stored World activation result digest is inconsistent"); + } + if (!Arrays.equals( + firstProtection.canonicalBytes(), + terminal.accountProtectionEvidence().canonicalBytes()) + || !Arrays.equals(resultBytes, terminal.activationResult().canonicalBytes()) + || !terminal.activationRequestId().equals(activationId) + || !terminal.outcome().name().equals(state) + || terminal.worldActivationFence() + != required(row, "world_activation_fence", Long.class)) { + throw new InvalidActivationEvidenceException( + "Stored World terminal differs from its original protected activation"); + } + return ProtectedActivationReadback.terminal(terminal); + } + + // V43-only results are retained history, not upgradeable protected receipts. Fail + // locally before asking Account to create a new protection operation. + if (!dsl.fetch( + "SELECT 1 FROM world_canonical_instance_activation_operation " + + "WHERE activation_request_id=? " + + "OR (canonical_game_instance_id=? AND outcome='COMMITTED')", + activationId, + gameInstanceId) + .isEmpty()) { + throw new ActivationConflictException( + "A retained legacy World activation result cannot be upgraded to protected activation"); + } + return null; + })); } static void requireSameAcquisitionInput( @@ -262,23 +258,21 @@ private static ProtectedActivationReadback terminal( */ private ActivationIntent beginProtectedActivation( AccountStartSessionActivationProtectionEvidence protection) { - return writeTransaction.execute( - status -> { - requireWritableTransaction(); - lockActivationOperation(protection); - UUID activationId = protection.request().worldActivationRequest().activationRequestId(); - Record prior = activationFenceForUpdate(activationId); - if (prior != null) { - requireSameProtectionIdentity(prior, protection); - return intent(prior, false); - } - requireNoLegacyActivationResult(protection); - requireLocalProtectedActivationBinding(protection, true); - Record inserted = insertActivationFence(protection); - return intent( - Objects.requireNonNull(inserted, "World activation fence insert returned no row"), - true); - }); + return writeTransaction.execute(status -> { + requireWritableTransaction(); + lockActivationOperation(protection); + UUID activationId = protection.request().worldActivationRequest().activationRequestId(); + Record prior = activationFenceForUpdate(activationId); + if (prior != null) { + requireSameProtectionIdentity(prior, protection); + return intent(prior, false); + } + requireNoLegacyActivationResult(protection); + requireLocalProtectedActivationBinding(protection, true); + Record inserted = insertActivationFence(protection); + return intent( + Objects.requireNonNull(inserted, "World activation fence insert returned no row"), true); + }); } /** @@ -311,103 +305,96 @@ public WorldOriginalStartSessionActivationTerminalEvidence activateProtected( while (true) { attempts++; try { - writeTransaction.execute( - status -> { - requireWritableTransaction(); - held.requireHeld(); - lockActivationOperation(firstProtection); - Record fence = activationFenceForUpdate(request.activationRequestId()); - if (fence == null) { - throw new InvalidActivationEvidenceException( - "Protected World activation lost its durable operation fence"); - } - requireSameProtectionIdentity(fence, firstProtection); - String state = required(fence, "operation_state", String.class); - if (!"PENDING".equals(state)) return null; - - WorldCanonicalInstanceLifecycleEvidence current = - lifecycleRepository - .readForActivationInOwnerTransaction(request.preparing().request()) - .orElseThrow( - () -> - new ActivationConflictException( - "Protected World activation no longer has its exact materialized owner association")); - requireLocalProtectedActivationBinding( - firstProtection, false, required(fence, "world_execution_fence", Long.class)); - requireLeaseStillValidAfterLocalLockWait(fence); - - Optional oldResult = - readResultInCurrentTransaction(request); - if (oldResult.isPresent()) { - throw new ActivationConflictException( - "A legacy or independently terminal World activation result cannot be upgraded to Account-protected proof"); - } - boolean exactPrecondition = exactPreparingPrecondition(request, current); - if (!exactPrecondition) { - WorldCanonicalInstanceActivation.Result aborted = - new WorldCanonicalInstanceActivation.Result( - request, - WorldCanonicalInstanceActivation.Outcome.ABORTED, - "PRECONDITION_FAILED", - current); - insertResult(request, aborted); - completeActivationFence( - fence, - firstProtection, - aborted, - WorldCanonicalInstanceActivation.Outcome.ABORTED); - held.requireHeld(); - return null; - } - - WorldCanonicalInstanceLifecycleEvidence predicted = - nextActiveEvidence(request, current); - WorldCanonicalInstanceActivation.Result committed = - new WorldCanonicalInstanceActivation.Result( - request, WorldCanonicalInstanceActivation.Outcome.COMMITTED, null, predicted); - insertResult(request, committed); - held.requireHeld(); - // V43's exact execution manifest predicts this row with the transaction timestamp. - int updated = - dsl.execute( - "UPDATE world_instance SET status='ACTIVE', lifecycle_epoch=lifecycle_epoch+1, " - + "row_version=row_version+1, updated_at=CURRENT_TIMESTAMP " - + "WHERE id=(SELECT world_instance_id FROM world_canonical_instance_association " - + "WHERE canonical_game_instance_id=? AND schema_version=2 " - + "AND canonical_realm_id=? AND catalog_revision=?) " - + "AND canonical_game_instance_id=? AND canonical_realm_id=? AND catalog_revision=? " - + "AND status='PREPARING' AND lifecycle_epoch=? AND row_version=?", - request.canonicalGameInstanceId(), - firstProtection.request().launchAssociation().canonicalRealmId(), - firstProtection.request().launchAssociation().catalogRevision(), - request.canonicalGameInstanceId(), - firstProtection.request().launchAssociation().canonicalRealmId(), - firstProtection.request().launchAssociation().catalogRevision(), - request.expectedLifecycleEpoch(), - request.expectedRowVersion()); - if (updated != 1) { - throw new ActivationConflictException( - "Protected World lifecycle changed before its exact activation compare-and-set"); - } - WorldCanonicalInstanceLifecycleEvidence actual = - lifecycleRepository - .readForActivationInOwnerTransaction(request.preparing().request()) - .orElseThrow( - () -> - new InvalidActivationEvidenceException( - "Protected World activation lost its owner readback")); - if (!Arrays.equals(predicted.canonicalBytes(), actual.canonicalBytes())) { - throw new InvalidActivationEvidenceException( - "Protected World activation result differs from its exact committed owner readback"); - } - completeActivationFence( - fence, - firstProtection, - committed, - WorldCanonicalInstanceActivation.Outcome.COMMITTED); - held.requireHeld(); - return null; - }); + writeTransaction.execute(status -> { + requireWritableTransaction(); + held.requireHeld(); + lockActivationOperation(firstProtection); + Record fence = activationFenceForUpdate(request.activationRequestId()); + if (fence == null) { + throw new InvalidActivationEvidenceException( + "Protected World activation lost its durable operation fence"); + } + requireSameProtectionIdentity(fence, firstProtection); + String state = required(fence, "operation_state", String.class); + if (!"PENDING".equals(state)) return null; + + WorldCanonicalInstanceLifecycleEvidence current = + lifecycleRepository + .readForActivationInOwnerTransaction(request.preparing().request()) + .orElseThrow(() -> + new ActivationConflictException( + "Protected World activation no longer has its exact materialized owner association")); + requireLocalProtectedActivationBinding( + firstProtection, false, required(fence, "world_execution_fence", Long.class)); + requireLeaseStillValidAfterLocalLockWait(fence); + + Optional oldResult = + readResultInCurrentTransaction(request); + if (oldResult.isPresent()) { + throw new ActivationConflictException( + "A legacy or independently terminal World activation result cannot be upgraded to Account-protected proof"); + } + boolean exactPrecondition = exactPreparingPrecondition(request, current); + if (!exactPrecondition) { + WorldCanonicalInstanceActivation.Result aborted = + new WorldCanonicalInstanceActivation.Result( + request, + WorldCanonicalInstanceActivation.Outcome.ABORTED, + "PRECONDITION_FAILED", + current); + insertResult(request, aborted); + completeActivationFence( + fence, firstProtection, aborted, WorldCanonicalInstanceActivation.Outcome.ABORTED); + held.requireHeld(); + return null; + } + + WorldCanonicalInstanceLifecycleEvidence predicted = nextActiveEvidence(request, current); + WorldCanonicalInstanceActivation.Result committed = + new WorldCanonicalInstanceActivation.Result( + request, WorldCanonicalInstanceActivation.Outcome.COMMITTED, null, predicted); + insertResult(request, committed); + held.requireHeld(); + // V43's exact execution manifest predicts this row with the transaction timestamp. + int updated = + dsl.execute( + "UPDATE world_instance SET status='ACTIVE', lifecycle_epoch=lifecycle_epoch+1, " + + "row_version=row_version+1, updated_at=CURRENT_TIMESTAMP " + + "WHERE id=(SELECT world_instance_id FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id=? AND schema_version=2 " + + "AND canonical_realm_id=? AND catalog_revision=?) " + + "AND canonical_game_instance_id=? AND canonical_realm_id=? AND catalog_revision=? " + + "AND status='PREPARING' AND lifecycle_epoch=? AND row_version=?", + request.canonicalGameInstanceId(), + firstProtection.request().launchAssociation().canonicalRealmId(), + firstProtection.request().launchAssociation().catalogRevision(), + request.canonicalGameInstanceId(), + firstProtection.request().launchAssociation().canonicalRealmId(), + firstProtection.request().launchAssociation().catalogRevision(), + request.expectedLifecycleEpoch(), + request.expectedRowVersion()); + if (updated != 1) { + throw new ActivationConflictException( + "Protected World lifecycle changed before its exact activation compare-and-set"); + } + WorldCanonicalInstanceLifecycleEvidence actual = + lifecycleRepository + .readForActivationInOwnerTransaction(request.preparing().request()) + .orElseThrow(() -> + new InvalidActivationEvidenceException( + "Protected World activation lost its owner readback")); + if (!Arrays.equals(predicted.canonicalBytes(), actual.canonicalBytes())) { + throw new InvalidActivationEvidenceException( + "Protected World activation result differs from its exact committed owner readback"); + } + completeActivationFence( + fence, + firstProtection, + committed, + WorldCanonicalInstanceActivation.Outcome.COMMITTED); + held.requireHeld(); + return null; + }); break; } catch (RuntimeException outcomeUncertain) { Optional terminal; @@ -427,10 +414,9 @@ public WorldOriginalStartSessionActivationTerminalEvidence activateProtected( } } return readTerminalEvidence(firstProtection) - .orElseThrow( - () -> - new InvalidActivationEvidenceException( - "Protected World activation transaction committed without exact terminal readback")); + .orElseThrow(() -> + new InvalidActivationEvidenceException( + "Protected World activation transaction committed without exact terminal readback")); } /** @@ -442,60 +428,57 @@ public WorldOriginalStartSessionActivationTerminalEvidence abortProtected( Objects.requireNonNull(protection, "protection"); requireTerminalCode(terminalCode); requireNoActiveTransaction("World protected canonical activation abort"); - writeTransaction.execute( - status -> { - requireWritableTransaction(); - lockActivationOperation(protection); - UUID activationId = protection.request().worldActivationRequest().activationRequestId(); - Record fence = activationFenceForUpdate(activationId); - if (fence == null) { - requireNoLegacyActivationResult(protection); - requireLocalProtectedActivationBinding(protection, false); - fence = insertActivationFence(protection); - } else { - requireSameProtectionIdentity(fence, protection); - } - if (!"PENDING".equals(required(fence, "operation_state", String.class))) return null; - WorldCanonicalInstanceActivation.Request request = - AccountStartSessionActivationProtectionEvidence.decode( - required(fence, "account_protection_evidence_bytes", byte[].class)) - .request() - .worldActivationRequest(); - WorldCanonicalInstanceLifecycleEvidence current = - lifecycleRepository - .readForActivationInOwnerTransaction(request.preparing().request()) - .orElseThrow( - () -> - new ActivationConflictException( - "Cannot fence activation without exact current World lifecycle evidence")); - requireLocalProtectedActivationBinding( - AccountStartSessionActivationProtectionEvidence.decode( - required(fence, "account_protection_evidence_bytes", byte[].class)), - false, - required(fence, "world_execution_fence", Long.class)); - Optional oldResult = - readResultInCurrentTransaction(request); - if (oldResult.isPresent()) { - throw new ActivationConflictException( - "Existing unprotected World activation result cannot be converted into a fenced abort"); - } - WorldCanonicalInstanceActivation.Result aborted = - new WorldCanonicalInstanceActivation.Result( - request, WorldCanonicalInstanceActivation.Outcome.ABORTED, terminalCode, current); - insertResult(request, aborted); - completeActivationFence( - fence, - AccountStartSessionActivationProtectionEvidence.decode( - required(fence, "account_protection_evidence_bytes", byte[].class)), - aborted, - WorldCanonicalInstanceActivation.Outcome.ABORTED); - return null; - }); + writeTransaction.execute(status -> { + requireWritableTransaction(); + lockActivationOperation(protection); + UUID activationId = protection.request().worldActivationRequest().activationRequestId(); + Record fence = activationFenceForUpdate(activationId); + if (fence == null) { + requireNoLegacyActivationResult(protection); + requireLocalProtectedActivationBinding(protection, false); + fence = insertActivationFence(protection); + } else { + requireSameProtectionIdentity(fence, protection); + } + if (!"PENDING".equals(required(fence, "operation_state", String.class))) return null; + WorldCanonicalInstanceActivation.Request request = + AccountStartSessionActivationProtectionEvidence.decode( + required(fence, "account_protection_evidence_bytes", byte[].class)) + .request() + .worldActivationRequest(); + WorldCanonicalInstanceLifecycleEvidence current = + lifecycleRepository + .readForActivationInOwnerTransaction(request.preparing().request()) + .orElseThrow(() -> + new ActivationConflictException( + "Cannot fence activation without exact current World lifecycle evidence")); + requireLocalProtectedActivationBinding( + AccountStartSessionActivationProtectionEvidence.decode( + required(fence, "account_protection_evidence_bytes", byte[].class)), + false, + required(fence, "world_execution_fence", Long.class)); + Optional oldResult = + readResultInCurrentTransaction(request); + if (oldResult.isPresent()) { + throw new ActivationConflictException( + "Existing unprotected World activation result cannot be converted into a fenced abort"); + } + WorldCanonicalInstanceActivation.Result aborted = + new WorldCanonicalInstanceActivation.Result( + request, WorldCanonicalInstanceActivation.Outcome.ABORTED, terminalCode, current); + insertResult(request, aborted); + completeActivationFence( + fence, + AccountStartSessionActivationProtectionEvidence.decode( + required(fence, "account_protection_evidence_bytes", byte[].class)), + aborted, + WorldCanonicalInstanceActivation.Outcome.ABORTED); + return null; + }); return readTerminalEvidence(protection) - .orElseThrow( - () -> - new InvalidActivationEvidenceException( - "Serialized World activation abort committed without exact terminal readback")); + .orElseThrow(() -> + new InvalidActivationEvidenceException( + "Serialized World activation abort committed without exact terminal readback")); } /** diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java index b4cf8a0a06..a13202cc8c 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java @@ -424,15 +424,14 @@ public void lockRunOwnedFixtureInOwnerTransaction( PreparedWorldInstanceRequest gameSessionRequest) { Objects.requireNonNull(fixtureEvidence, "fixtureEvidence").requireFixedGameSessionPeer(); requireWritableReadCommittedOwnerTransaction(); - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new IllegalStateException( - "Run-owned World fixture locking requires a physical writable READ COMMITTED owner transaction"); - } - }); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new IllegalStateException( + "Run-owned World fixture locking requires a physical writable READ COMMITTED owner transaction"); + } + }); Record state = Objects.requireNonNull( dsl.fetchOne( @@ -515,10 +514,9 @@ public WorldCanonicalInstanceAssociation allocateRunOwnedFixtureInOwnerTransacti sourceIntakeRepository .readInOwnerActivationTransaction( sourceReceipt.targetNamespace(), sourceReceipt.intakeRequestId()) - .orElseThrow( - () -> - new InvalidAssociationEvidenceException( - "Run-owned fixture lost its retained World source intake")); + .orElseThrow(() -> + new InvalidAssociationEvidenceException( + "Run-owned fixture lost its retained World source intake")); WorldAuthoredVersionIdentityReceipt storedVersion = versionIdentityRepository .readByCanonicalVersionInOwnerActivationTransaction( @@ -526,10 +524,9 @@ public WorldCanonicalInstanceAssociation allocateRunOwnedFixtureInOwnerTransacti versionIdentity.canonicalTenantId(), versionIdentity.worldSlug(), versionIdentity.canonicalVersionId()) - .orElseThrow( - () -> - new InvalidAssociationEvidenceException( - "Run-owned fixture lost its retained World Version identity")); + .orElseThrow(() -> + new InvalidAssociationEvidenceException( + "Run-owned fixture lost its retained World Version identity")); if (!storedSource.equals(sourceReceipt) || !storedVersion.equals(versionIdentity)) { throw new InvalidAssociationEvidenceException( "Run-owned fixture World source or Version receipt changed before allocation"); @@ -920,10 +917,9 @@ public WorldCanonicalInstanceAssociation readRunOwnedFixtureAssociation( } WorldCanonicalInstanceAssociation stored = readOwnerAssociation(gameSession.gameInstanceUuid()) - .orElseThrow( - () -> - new InvalidAssociationEvidenceException( - "Run-owned World fixture association is not retained")); + .orElseThrow(() -> + new InvalidAssociationEvidenceException( + "Run-owned World fixture association is not retained")); requireFixtureAssociationMatches(stored, evidence, originalGameSessionRequest); return stored; } @@ -960,10 +956,9 @@ public WorldCanonicalInstanceAssociation readRunOwnedFixtureAssociationInActivat } WorldCanonicalInstanceAssociation stored = readOwnerAssociation(gameSession.gameInstanceUuid(), true, true) - .orElseThrow( - () -> - new InvalidAssociationEvidenceException( - "Run-owned World fixture association is not retained")); + .orElseThrow(() -> + new InvalidAssociationEvidenceException( + "Run-owned World fixture association is not retained")); requireFixtureAssociationMatches(stored, evidence, originalGameSessionRequest); return stored; } @@ -1078,10 +1073,9 @@ private WorldCanonicalInstanceAssociation toAssociation( ? launchBindingRepository.readInOwnerReadOnlyRepeatableRead( namespace, tenantId, controlRequestId) : launchBindingRepository.read(namespace, tenantId, controlRequestId)) - .orElseThrow( - () -> - new InvalidAssociationEvidenceException( - "World canonical association lost its immutable launch binding")); + .orElseThrow(() -> + new InvalidAssociationEvidenceException( + "World canonical association lost its immutable launch binding")); if (!storedBinding.operationId().equals(bindingOperationId)) { throw new InvalidAssociationEvidenceException( "World canonical association substituted its complete launch binding"); @@ -1094,10 +1088,9 @@ private WorldCanonicalInstanceAssociation toAssociation( ? sourceIntakeRepository.readInOwnerReadOnlyRepeatableRead( namespace, intakeRequestId) : sourceIntakeRepository.read(namespace, intakeRequestId)) - .orElseThrow( - () -> - new InvalidAssociationEvidenceException( - "World canonical association lost its original source intake")); + .orElseThrow(() -> + new InvalidAssociationEvidenceException( + "World canonical association lost its original source intake")); WorldCompleteLaunchBindingReceipt completeBinding = launchBindingRepository.toReceipt(storedBinding, sourceReceipt); UUID canonicalVersionId = required(row, CANONICAL_VERSION_ID); @@ -1111,10 +1104,9 @@ private WorldCanonicalInstanceAssociation toAssociation( namespace, tenantId, worldSlug, canonicalVersionId) : versionIdentityRepository.readByCanonicalVersion( namespace, tenantId, worldSlug, canonicalVersionId)) - .orElseThrow( - () -> - new InvalidAssociationEvidenceException( - "World canonical association lost its UUID-to-private-Version receipt")); + .orElseThrow(() -> + new InvalidAssociationEvidenceException( + "World canonical association lost its UUID-to-private-Version receipt")); WorldCanonicalInstanceAssociation.CanonicalIdentity identity = new WorldCanonicalInstanceAssociation.CanonicalIdentity( required(row, CANONICAL_GAME_INSTANCE_ID), @@ -1202,10 +1194,9 @@ namespace, required(row, INTAKE_REQUEST_ID)) ? sourceIntakeRepository.readInOwnerReadOnlyRepeatableRead( namespace, required(row, INTAKE_REQUEST_ID)) : sourceIntakeRepository.read(namespace, required(row, INTAKE_REQUEST_ID))) - .orElseThrow( - () -> - new InvalidAssociationEvidenceException( - "Run-owned fixture association lost its exact World source intake")); + .orElseThrow(() -> + new InvalidAssociationEvidenceException( + "Run-owned fixture association lost its exact World source intake")); WorldAuthoredVersionIdentityReceipt versionIdentity = (inActivationTransaction ? versionIdentityRepository.readByCanonicalVersionInOwnerActivationTransaction( @@ -1215,10 +1206,9 @@ namespace, required(row, INTAKE_REQUEST_ID)) namespace, canonicalTenantId, worldSlug, canonicalVersionId) : versionIdentityRepository.readByCanonicalVersion( namespace, canonicalTenantId, worldSlug, canonicalVersionId)) - .orElseThrow( - () -> - new InvalidAssociationEvidenceException( - "Run-owned fixture association lost its exact World Version identity")); + .orElseThrow(() -> + new InvalidAssociationEvidenceException( + "Run-owned fixture association lost its exact World Version identity")); WorldCanonicalInstanceAssociation.WorldPrivateKeys worldPrivateKeys = new WorldCanonicalInstanceAssociation.WorldPrivateKeys( required(row, LOCAL_TENANT_KEY), diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java index 60045c83fc..6c810c8849 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java @@ -106,11 +106,10 @@ public Optional read( Objects.requireNonNull(request, "request"); requireNoActiveTransaction("World canonical lifecycle read"); return Optional.ofNullable( - transaction.execute( - status -> { - requireReadOnlyRepeatableReadOwnerTransaction(); - return readInCurrentOwnerTransaction(request, false); - })); + transaction.execute(status -> { + requireReadOnlyRepeatableReadOwnerTransaction(); + return readInCurrentOwnerTransaction(request, false); + })); } /** @@ -456,10 +455,9 @@ private Set requireFrozenGraphIdentity( } } if (expectedCounts.entrySet().stream() - .anyMatch( - entry -> - actualCounts.getOrDefault(entry.getKey(), 0).intValue() - != entry.getValue().intValue()) + .anyMatch(entry -> + actualCounts.getOrDefault(entry.getKey(), 0).intValue() + != entry.getValue().intValue()) || rows.size() != expectedCounts.values().stream().mapToInt(Integer::intValue).sum() || expectedRegionTemplates.size() != required(preparation, "region_count", Integer.class)) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java index 74822fb04a..0dfbf1dbad 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparation.java @@ -332,15 +332,14 @@ static void requireExactSelector( freeze.contentDigest(), freeze.digestSchemaVersion(), freeze.suppliedOwnedAffectedTuples().stream() - .map( - tuple -> - new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( - tuple.owner(), - tuple.aggregateType(), - tuple.aggregateId(), - tuple.scopeType(), - tuple.scopeId(), - tuple.expectedEpoch())) + .map(tuple -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) .toList()); var receipt = WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); var declaration = @@ -349,19 +348,15 @@ static void requireExactSelector( .plan() .graph() .freshGraphDeclaration() - .orElseThrow( - () -> - new IllegalArgumentException( - "Selected World graph has no original fresh declaration")); + .orElseThrow(() -> + new IllegalArgumentException( + "Selected World graph has no original fresh declaration")); if (!selector.request().equals(expected) || !declaration.startLocation().equals(receipt.startLocation()) || !receipt.bindingDigest().equals(topologyPlan.sourceBinding().plan().binding().digest()) || topologyPlan.rooms().stream() - .filter( - room -> - room.identity() - .templateId() - .equals(receipt.startLocation().roomTemplateId())) + .filter(room -> + room.identity().templateId().equals(receipt.startLocation().roomTemplateId())) .count() != 1) { throw new IllegalArgumentException( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyService.java index d5391f2610..bb2de677fa 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyService.java @@ -63,19 +63,17 @@ public WorldCanonicalInstancePreparation.Input assemble(Selector selector) { WorldCompleteLaunchBindingRepository.StoredBinding storedBinding = launchBindings .read(workloadNamespace, selector.canonicalTenantId(), selector.controlPlaneRequestId()) - .orElseThrow( - () -> - new AssemblyRejectedException( - "No committed World complete launch binding matches the stable selector")); + .orElseThrow(() -> + new AssemblyRejectedException( + "No committed World complete launch binding matches the stable selector")); requireStoredSelector(storedBinding, selector); WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceIntakes .read(workloadNamespace, storedBinding.intakeRequestId()) - .orElseThrow( - () -> - new AssemblyRejectedException( - "World launch binding has no exact committed source intake")); + .orElseThrow(() -> + new AssemblyRejectedException( + "World launch binding has no exact committed source intake")); WorldCompleteLaunchBindingReceipt launchBinding = launchBindings.toReceipt(storedBinding, sourceReceipt); @@ -96,10 +94,9 @@ public WorldCanonicalInstancePreparation.Input assemble(Selector selector) { selector.canonicalTenantId(), descriptor.worldSlug(), release.canonicalVersionId()) - .orElseThrow( - () -> - new AssemblyRejectedException( - "World has no committed source-qualified Version identity for the release UUID")); + .orElseThrow(() -> + new AssemblyRejectedException( + "World has no committed source-qualified Version identity for the release UUID")); if (!versionIdentity.sourceIntakeReceipt().equals(sourceReceipt) || !versionIdentity.canonicalVersionId().equals(release.canonicalVersionId()) || !versionIdentity.worldSlug().equals(descriptor.worldSlug())) { @@ -111,10 +108,9 @@ public WorldCanonicalInstancePreparation.Input assemble(Selector selector) { WorldCanonicalFrozenTopology frozen = frozenTopologies .readCommitted(captureRequest) - .orElseThrow( - () -> - new AssemblyRejectedException( - "Published release selector has no exact committed frozen World topology")); + .orElseThrow(() -> + new AssemblyRejectedException( + "Published release selector has no exact committed frozen World topology")); WorldCanonicalInstanceTopologyPlan topologyPlan = WorldCanonicalInstanceTopologyPlan.create(frozen); WorldCanonicalInstancePreparation.requireExactReleaseGraph(release, topologyPlan); @@ -181,15 +177,14 @@ private static CaptureRequest captureRequest(WorldPublishedStartLocationEvidence request.contentDigest(), request.digestSchemaVersion(), request.worldAffectedTuples().stream() - .map( - tuple -> - new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( - tuple.owner(), - tuple.aggregateType(), - tuple.aggregateId(), - tuple.scopeType(), - tuple.scopeId(), - tuple.expectedEpoch())) + .map(tuple -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) .toList()); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcService.java index c19c1d9639..6771545cdb 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationGrpcService.java @@ -117,10 +117,9 @@ public void prepareCanonicalWorldInstance( WorldCanonicalInstanceLifecycleEvidence lifecycle = lifecycleRepository .read(lifecycleRequest) - .orElseThrow( - () -> - new PreparationPreconditionException( - "Canonical World lifecycle readback is required after materialization")); + .orElseThrow(() -> + new PreparationPreconditionException( + "Canonical World lifecycle readback is required after materialization")); requireLifecycleMatchesPreparation(lifecycleRequest, input, prepared, lifecycle); PrepareCanonicalWorldInstanceResponse response = diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java index 2f6cc787a7..d721db3beb 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java @@ -121,33 +121,31 @@ public boolean hasRetainedCommittedCandidate( String inputDigest = digest(exactInput.getBytes(StandardCharsets.UTF_8)); var evidence = input.gameSessionReadEvidence(); return Boolean.TRUE.equals( - readTransaction.execute( - status -> { - applyDatabaseTimeouts(); - return dsl.fetchExists( - dsl.selectOne() - .from("world_canonical_instance_execution") - .where( - "target_namespace=? AND canonical_tenant_id=? AND control_plane_request_id=?" - + " AND canonical_game_instance_id=? AND operation_state='COMMITTED'" - + " AND original_post_authorization_tuple=?" - + " AND original_post_authorization_tuple_sha256=?" - + " AND game_session_owner_mutation_id=? AND game_session_owner_attempt_id=?" - + " AND game_session_owner_fence=? AND preparation_input_digest=?" - + " AND preparation_input_json=? AND original_attempt_evidence_bytes IS NOT NULL", - evidence.targetNamespace(), - evidence.canonicalTenantId(), - evidence.controlPlaneRequestId(), - input.canonicalGameInstanceId(), - operation.originalPostAuthorizationTuple(), - HexFormat.of() - .formatHex(sha256(operation.originalPostAuthorizationTuple())), - operation.gameSessionOwnerMutationId(), - operation.gameSessionOwnerAttemptId(), - operation.gameSessionOwnerFence(), - inputDigest, - exactInput)); - })); + readTransaction.execute(status -> { + applyDatabaseTimeouts(); + return dsl.fetchExists( + dsl.selectOne() + .from("world_canonical_instance_execution") + .where( + "target_namespace=? AND canonical_tenant_id=? AND control_plane_request_id=?" + + " AND canonical_game_instance_id=? AND operation_state='COMMITTED'" + + " AND original_post_authorization_tuple=?" + + " AND original_post_authorization_tuple_sha256=?" + + " AND game_session_owner_mutation_id=? AND game_session_owner_attempt_id=?" + + " AND game_session_owner_fence=? AND preparation_input_digest=?" + + " AND preparation_input_json=? AND original_attempt_evidence_bytes IS NOT NULL", + evidence.targetNamespace(), + evidence.canonicalTenantId(), + evidence.controlPlaneRequestId(), + input.canonicalGameInstanceId(), + operation.originalPostAuthorizationTuple(), + HexFormat.of().formatHex(sha256(operation.originalPostAuthorizationTuple())), + operation.gameSessionOwnerMutationId(), + operation.gameSessionOwnerAttemptId(), + operation.gameSessionOwnerFence(), + inputDigest, + exactInput)); + })); } /** @@ -242,56 +240,55 @@ public Result materialize( } committed = - transaction.execute( - status -> { - requireWritableReadCommittedTransaction(); - applyDatabaseTimeouts(); - authority.requireHeld(); - Record beginRow = - dsl.fetchOne( - "SELECT world_begin_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", - inputJson, - inputDigest, - executionIdentity.originalPostAuthorizationTuple(), - executionIdentity.accountWorldParticipationId(), - executionIdentity.accountWorldParticipationFence(), - executionIdentity.gameSessionOwnerAttemptId(), - executionIdentity.gameSessionOwnerFence(), - executionIdentity.canonicalGameInstanceId(), - intentFence, - executionIdentity.gameSessionOwnerMutationId(), - executionIdentity.originalAttemptReadRequestId(), - OffsetDateTime.ofInstant( - executionIdentity.originalGameSessionLeaseExpiresAt(), - java.time.ZoneOffset.UTC), - executionIdentity.originalAttemptEvidenceBytes(), - executionIdentity.originalAttemptEvidenceDigest()); - Long worldExecutionFence = beginRow == null ? null : beginRow.get(0, Long.class); - if (worldExecutionFence == null || worldExecutionFence <= 0L) { - return null; - } - Record row = - Objects.requireNonNull( - fetchCanonicalPreparation(inputJson, inputDigest), - "Canonical preparation owner function returned no row"); - MaterializedInstance materialized = - new MaterializedInstance( - required(row, "world_instance_id", Long.class), - required(row, "private_game_instance_key", Long.class)); - WorldCanonicalInstanceAssociation.Claim claim = - new WorldCanonicalInstanceAssociation.Claim( - input.gameSessionReadRequest(), - input.gameSessionReadEvidence(), - materialized.worldInstanceId(), - input.completeLaunchBinding(), - input.versionIdentity()); - associationRepository.retainClaimInOwnerTransaction(claim); - authority.requireHeld(); - dsl.fetch( - "SELECT world_commit_canonical_instance_execution(?)", - materialized.worldInstanceId()); - return materialized; - }); + transaction.execute(status -> { + requireWritableReadCommittedTransaction(); + applyDatabaseTimeouts(); + authority.requireHeld(); + Record beginRow = + dsl.fetchOne( + "SELECT world_begin_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", + inputJson, + inputDigest, + executionIdentity.originalPostAuthorizationTuple(), + executionIdentity.accountWorldParticipationId(), + executionIdentity.accountWorldParticipationFence(), + executionIdentity.gameSessionOwnerAttemptId(), + executionIdentity.gameSessionOwnerFence(), + executionIdentity.canonicalGameInstanceId(), + intentFence, + executionIdentity.gameSessionOwnerMutationId(), + executionIdentity.originalAttemptReadRequestId(), + OffsetDateTime.ofInstant( + executionIdentity.originalGameSessionLeaseExpiresAt(), + java.time.ZoneOffset.UTC), + executionIdentity.originalAttemptEvidenceBytes(), + executionIdentity.originalAttemptEvidenceDigest()); + Long worldExecutionFence = beginRow == null ? null : beginRow.get(0, Long.class); + if (worldExecutionFence == null || worldExecutionFence <= 0L) { + return null; + } + Record row = + Objects.requireNonNull( + fetchCanonicalPreparation(inputJson, inputDigest), + "Canonical preparation owner function returned no row"); + MaterializedInstance materialized = + new MaterializedInstance( + required(row, "world_instance_id", Long.class), + required(row, "private_game_instance_key", Long.class)); + WorldCanonicalInstanceAssociation.Claim claim = + new WorldCanonicalInstanceAssociation.Claim( + input.gameSessionReadRequest(), + input.gameSessionReadEvidence(), + materialized.worldInstanceId(), + input.completeLaunchBinding(), + input.versionIdentity()); + associationRepository.retainClaimInOwnerTransaction(claim); + authority.requireHeld(); + dsl.fetch( + "SELECT world_commit_canonical_instance_execution(?)", + materialized.worldInstanceId()); + return materialized; + }); } catch (RuntimeException outcomeUncertain) { return recoverAfterUncertainWrite(input, executionIdentity, outcomeUncertain); } @@ -300,10 +297,9 @@ public Result materialize( ExecutionOperation terminal = readExactExecution(executionIdentity) .operation() - .orElseThrow( - () -> - new InvalidPreparationEvidenceException( - "A serialized World execution disappeared before terminal readback")); + .orElseThrow(() -> + new InvalidPreparationEvidenceException( + "A serialized World execution disappeared before terminal readback")); if (terminal.state() == ExecutionState.COMMITTED) { return readCommittedResult(input, terminal); } @@ -313,10 +309,9 @@ public Result materialize( Result result = readOwnerPreparation(input) - .orElseThrow( - () -> - new InvalidPreparationEvidenceException( - "Committed canonical World preparation has no independent result readback")); + .orElseThrow(() -> + new InvalidPreparationEvidenceException( + "Committed canonical World preparation has no independent result readback")); if (result.association().worldInstanceId() != committed.worldInstanceId()) { throw new InvalidPreparationEvidenceException( "Canonical World preparation readback differs from its committed owner row"); @@ -336,30 +331,29 @@ private long persistExecutionIntent( WorldCanonicalInstanceExecutionIdentity identity, WorldCanonicalInstancePreparationService.HeldCommitAuthority authority) { Long fence = - intentTransaction.execute( - status -> { - requireWritableReadCommittedTransaction(); - applyDatabaseTimeouts(); - authority.requireHeld(); - Record intentRow = - dsl.fetchOne( - "SELECT world_persist_canonical_instance_execution_intent_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", - inputJson, - inputDigest, - identity.originalPostAuthorizationTuple(), - identity.accountWorldParticipationId(), - identity.accountWorldParticipationFence(), - identity.gameSessionOwnerAttemptId(), - identity.gameSessionOwnerFence(), - identity.canonicalGameInstanceId(), - identity.gameSessionOwnerMutationId(), - identity.originalAttemptReadRequestId(), - OffsetDateTime.ofInstant( - identity.originalGameSessionLeaseExpiresAt(), java.time.ZoneOffset.UTC), - identity.originalAttemptEvidenceBytes(), - identity.originalAttemptEvidenceDigest()); - return intentRow == null ? null : intentRow.get(0, Long.class); - }); + intentTransaction.execute(status -> { + requireWritableReadCommittedTransaction(); + applyDatabaseTimeouts(); + authority.requireHeld(); + Record intentRow = + dsl.fetchOne( + "SELECT world_persist_canonical_instance_execution_intent_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", + inputJson, + inputDigest, + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence(), + identity.canonicalGameInstanceId(), + identity.gameSessionOwnerMutationId(), + identity.originalAttemptReadRequestId(), + OffsetDateTime.ofInstant( + identity.originalGameSessionLeaseExpiresAt(), java.time.ZoneOffset.UTC), + identity.originalAttemptEvidenceBytes(), + identity.originalAttemptEvidenceDigest()); + return intentRow == null ? null : intentRow.get(0, Long.class); + }); if (fence == null) { throw new InvalidPreparationEvidenceException( "World execution intent transaction returned no fence result"); @@ -372,30 +366,29 @@ private Long claimExecutionIntent( WorldCanonicalInstanceExecutionIdentity identity, WorldCanonicalInstancePreparationService.HeldCommitAuthority authority) { Long fence = - intentTransaction.execute( - status -> { - requireWritableReadCommittedTransaction(); - applyDatabaseTimeouts(); - authority.requireHeld(); - Record claimRow = - dsl.fetchOne( - "SELECT world_claim_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", - identity.preparationInputJson(), - identity.preparationInputDigest(), - identity.originalPostAuthorizationTuple(), - identity.accountWorldParticipationId(), - identity.accountWorldParticipationFence(), - identity.gameSessionOwnerAttemptId(), - identity.gameSessionOwnerFence(), - identity.canonicalGameInstanceId(), - identity.gameSessionOwnerMutationId(), - identity.originalAttemptReadRequestId(), - OffsetDateTime.ofInstant( - identity.originalGameSessionLeaseExpiresAt(), java.time.ZoneOffset.UTC), - identity.originalAttemptEvidenceBytes(), - identity.originalAttemptEvidenceDigest()); - return claimRow == null ? null : claimRow.get(0, Long.class); - }); + intentTransaction.execute(status -> { + requireWritableReadCommittedTransaction(); + applyDatabaseTimeouts(); + authority.requireHeld(); + Record claimRow = + dsl.fetchOne( + "SELECT world_claim_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", + identity.preparationInputJson(), + identity.preparationInputDigest(), + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence(), + identity.canonicalGameInstanceId(), + identity.gameSessionOwnerMutationId(), + identity.originalAttemptReadRequestId(), + OffsetDateTime.ofInstant( + identity.originalGameSessionLeaseExpiresAt(), java.time.ZoneOffset.UTC), + identity.originalAttemptEvidenceBytes(), + identity.originalAttemptEvidenceDigest()); + return claimRow == null ? null : claimRow.get(0, Long.class); + }); authority.requireHeld(); return fence; } @@ -407,25 +400,24 @@ public ExecutionLookup readExactExecution(WorldCanonicalInstanceExecutionIdentit Objects.requireNonNull(identity, "identity"); requireNoActiveTransaction("World execution terminal read"); Record row = - readTransaction.execute( - status -> { - applyDatabaseTimeouts(); - return dsl.fetchOne( - "SELECT clock.database_now, e.canonical_game_instance_id, original_post_authorization_tuple, " - + "original_post_authorization_tuple_sha256, account_world_participation_id, " - + "account_world_participation_fence, game_session_owner_attempt_id, " - + "game_session_owner_fence, game_session_owner_mutation_id, " - + "original_attempt_read_request_id, original_game_session_lease_expires_at, " - + "original_attempt_evidence_bytes, original_attempt_evidence_sha256, " - + "preparation_input_digest, preparation_input_json, " - + "world_execution_fence, operation_state, world_instance_id " - + "FROM (SELECT clock_timestamp() AS database_now) clock " - + "LEFT JOIN world_canonical_instance_execution e ON e.target_namespace=? " - + "AND e.canonical_tenant_id=? AND e.control_plane_request_id=?", - identity.targetNamespace(), - identity.canonicalTenantId(), - identity.controlPlaneRequestId()); - }); + readTransaction.execute(status -> { + applyDatabaseTimeouts(); + return dsl.fetchOne( + "SELECT clock.database_now, e.canonical_game_instance_id, original_post_authorization_tuple, " + + "original_post_authorization_tuple_sha256, account_world_participation_id, " + + "account_world_participation_fence, game_session_owner_attempt_id, " + + "game_session_owner_fence, game_session_owner_mutation_id, " + + "original_attempt_read_request_id, original_game_session_lease_expires_at, " + + "original_attempt_evidence_bytes, original_attempt_evidence_sha256, " + + "preparation_input_digest, preparation_input_json, " + + "world_execution_fence, operation_state, world_instance_id " + + "FROM (SELECT clock_timestamp() AS database_now) clock " + + "LEFT JOIN world_canonical_instance_execution e ON e.target_namespace=? " + + "AND e.canonical_tenant_id=? AND e.control_plane_request_id=?", + identity.targetNamespace(), + identity.canonicalTenantId(), + identity.controlPlaneRequestId()); + }); if (row == null) { throw new InvalidPreparationEvidenceException( "World exact-operation read returned no database-clock result"); @@ -507,10 +499,9 @@ private Result recoverSerializedExecution( ExecutionOperation terminal = readExactExecution(identity) .operation() - .orElseThrow( - () -> - new InvalidPreparationEvidenceException( - "Serialized World execution disappeared before terminal readback")); + .orElseThrow(() -> + new InvalidPreparationEvidenceException( + "Serialized World execution disappeared before terminal readback")); if (terminal.state() == ExecutionState.ABORTED) { throw new ConflictingPreparationException( "Exact original World execution is durably ABORTED and cannot be restarted"); @@ -549,10 +540,9 @@ private Result recoverAfterUncertainWrite( private Result readCommittedResult(Input input, ExecutionOperation terminal) { Result result = readOwnerPreparation(input) - .orElseThrow( - () -> - new InvalidPreparationEvidenceException( - "Exact COMMITTED World execution has no immutable preparation readback")); + .orElseThrow(() -> + new InvalidPreparationEvidenceException( + "Exact COMMITTED World execution has no immutable preparation readback")); if (result.association().worldInstanceId() != terminal.worldInstanceId()) { throw new InvalidPreparationEvidenceException( "Exact COMMITTED World execution differs from its retained terminal result"); @@ -569,47 +559,46 @@ public ExecutionOperation recordDurableAbort(WorldCanonicalInstanceExecutionIden requireNoActiveTransaction("World execution abort"); Record row = Objects.requireNonNull( - abortTransaction.execute( - status -> { - requireWritableReadCommittedTransaction(); - applyDatabaseTimeouts(); - if (identity.hasOriginalAttemptEvidence()) { - return dsl.fetchOne( - "SELECT operation_state, world_execution_fence, world_instance_id " - + "FROM world_abort_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", - identity.targetNamespace(), - identity.canonicalTenantId(), - identity.controlPlaneRequestId(), - identity.canonicalGameInstanceId(), - identity.preparationInputJson(), - identity.preparationInputDigest(), - identity.originalPostAuthorizationTuple(), - identity.accountWorldParticipationId(), - identity.accountWorldParticipationFence(), - identity.gameSessionOwnerAttemptId(), - identity.gameSessionOwnerFence(), - identity.gameSessionOwnerMutationId(), - identity.originalAttemptReadRequestId(), - OffsetDateTime.ofInstant( - identity.originalGameSessionLeaseExpiresAt(), java.time.ZoneOffset.UTC), - identity.originalAttemptEvidenceBytes(), - identity.originalAttemptEvidenceDigest()); - } - return dsl.fetchOne( - "SELECT operation_state, world_execution_fence, world_instance_id " - + "FROM world_abort_canonical_instance_execution(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", - identity.targetNamespace(), - identity.canonicalTenantId(), - identity.controlPlaneRequestId(), - identity.canonicalGameInstanceId(), - identity.preparationInputJson(), - identity.preparationInputDigest(), - identity.originalPostAuthorizationTuple(), - identity.accountWorldParticipationId(), - identity.accountWorldParticipationFence(), - identity.gameSessionOwnerAttemptId(), - identity.gameSessionOwnerFence()); - }), + abortTransaction.execute(status -> { + requireWritableReadCommittedTransaction(); + applyDatabaseTimeouts(); + if (identity.hasOriginalAttemptEvidence()) { + return dsl.fetchOne( + "SELECT operation_state, world_execution_fence, world_instance_id " + + "FROM world_abort_canonical_instance_execution_with_original_attempt(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ), ?, ?)", + identity.targetNamespace(), + identity.canonicalTenantId(), + identity.controlPlaneRequestId(), + identity.canonicalGameInstanceId(), + identity.preparationInputJson(), + identity.preparationInputDigest(), + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence(), + identity.gameSessionOwnerMutationId(), + identity.originalAttemptReadRequestId(), + OffsetDateTime.ofInstant( + identity.originalGameSessionLeaseExpiresAt(), java.time.ZoneOffset.UTC), + identity.originalAttemptEvidenceBytes(), + identity.originalAttemptEvidenceDigest()); + } + return dsl.fetchOne( + "SELECT operation_state, world_execution_fence, world_instance_id " + + "FROM world_abort_canonical_instance_execution(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + identity.targetNamespace(), + identity.canonicalTenantId(), + identity.controlPlaneRequestId(), + identity.canonicalGameInstanceId(), + identity.preparationInputJson(), + identity.preparationInputDigest(), + identity.originalPostAuthorizationTuple(), + identity.accountWorldParticipationId(), + identity.accountWorldParticipationFence(), + identity.gameSessionOwnerAttemptId(), + identity.gameSessionOwnerFence()); + }), "World abort transaction did not complete"); String state = required(row, "operation_state", String.class); ExecutionState executionState = ExecutionState.valueOf(state); @@ -710,10 +699,9 @@ public Optional readOwnerPreparation(Input input) { WorldCanonicalInstanceAssociation association = associationRepository .readOwnerAssociation(input.canonicalGameInstanceId()) - .orElseThrow( - () -> - new InvalidPreparationEvidenceException( - "Canonical World preparation result lost its exact committed association")); + .orElseThrow(() -> + new InvalidPreparationEvidenceException( + "Canonical World preparation result lost its exact committed association")); if (!association.identity().equals(input.gameSessionReadEvidence().canonicalIdentity()) || !association.completeLaunchBinding().equals(input.completeLaunchBinding()) || !association.versionIdentity().equals(input.versionIdentity()) @@ -770,10 +758,9 @@ private void requireExactFrozenSource(Input input) { WorldCanonicalFrozenTopology frozen = frozenTopologyRepository .readCommitted(input.topologyPlan().sourceBinding()) - .orElseThrow( - () -> - new InvalidPreparationEvidenceException( - "Canonical preparation input has no exact committed frozen topology")); + .orElseThrow(() -> + new InvalidPreparationEvidenceException( + "Canonical preparation input has no exact committed frozen topology")); WorldCanonicalInstanceTopologyPlan reconstructed = WorldCanonicalInstanceTopologyPlan.create(frozen); if (!frozen.captureId().equals(input.captureId()) @@ -845,10 +832,9 @@ private void requireExactOriginalBindings(Input input) { var retainedSource = sourceIntakeRepository .read(source.targetNamespace(), source.intakeRequestId()) - .orElseThrow( - () -> - new InvalidPreparationEvidenceException( - "Canonical preparation has no exact committed World source intake")); + .orElseThrow(() -> + new InvalidPreparationEvidenceException( + "Canonical preparation has no exact committed World source intake")); if (!retainedSource.equals(source)) { throw new InvalidPreparationEvidenceException( "Canonical preparation source differs from its complete original immutable intake row"); @@ -860,10 +846,9 @@ private void requireExactOriginalBindings(Input input) { launch.targetNamespace(), launch.canonicalTenantId(), launch.controlPlaneRequestId()) - .orElseThrow( - () -> - new InvalidPreparationEvidenceException( - "Canonical preparation has no exact committed launch binding")); + .orElseThrow(() -> + new InvalidPreparationEvidenceException( + "Canonical preparation has no exact committed launch binding")); if (!retainedBinding.operationId().equals(launch.operationId()) || !retainedBinding.targetNamespace().equals(launch.targetNamespace()) || !retainedBinding.canonicalTenantId().equals(launch.canonicalTenantId()) @@ -893,10 +878,9 @@ private void requireExactOriginalBindings(Input input) { version.canonicalTenantId(), version.worldSlug(), version.canonicalVersionId()) - .orElseThrow( - () -> - new InvalidPreparationEvidenceException( - "Canonical preparation has no exact committed source-qualified Version identity")); + .orElseThrow(() -> + new InvalidPreparationEvidenceException( + "Canonical preparation has no exact committed source-qualified Version identity")); if (!retainedVersion.equals(version) || !retainedVersion.sourceIntakeReceipt().equals(source)) { throw new InvalidPreparationEvidenceException( "Canonical preparation Version/source evidence differs from its original immutable row"); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java index 8c8765f974..3f8b1992bf 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java @@ -223,31 +223,29 @@ public Optional recoverExactTerminal( WorldCanonicalInstanceExecutionIdentity originalIdentity) { return recoverExact(originalIdentity) .operation() - .filter( - operation -> + .filter(operation -> + operation.state() + == WorldCanonicalInstancePreparationRepository.ExecutionState.COMMITTED + || operation.state() + == WorldCanonicalInstancePreparationRepository.ExecutionState.ABORTED) + .map(operation -> + new WorldStartSessionExecutionTerminal( + originalIdentity.originalPostAuthorizationTuple(), + originalIdentity.accountWorldParticipationId(), + originalIdentity.accountWorldParticipationFence(), + originalIdentity.gameSessionOwnerAttemptId(), + originalIdentity.gameSessionOwnerFence(), + originalIdentity.targetNamespace(), + originalIdentity.canonicalTenantId(), + originalIdentity.controlPlaneRequestId(), + originalIdentity.canonicalGameInstanceId(), + originalIdentity.preparationInputDigest(), + originalIdentity.preparationInputJson(), + operation.worldExecutionFence(), operation.state() == WorldCanonicalInstancePreparationRepository.ExecutionState.COMMITTED - || operation.state() - == WorldCanonicalInstancePreparationRepository.ExecutionState.ABORTED) - .map( - operation -> - new WorldStartSessionExecutionTerminal( - originalIdentity.originalPostAuthorizationTuple(), - originalIdentity.accountWorldParticipationId(), - originalIdentity.accountWorldParticipationFence(), - originalIdentity.gameSessionOwnerAttemptId(), - originalIdentity.gameSessionOwnerFence(), - originalIdentity.targetNamespace(), - originalIdentity.canonicalTenantId(), - originalIdentity.controlPlaneRequestId(), - originalIdentity.canonicalGameInstanceId(), - originalIdentity.preparationInputDigest(), - originalIdentity.preparationInputJson(), - operation.worldExecutionFence(), - operation.state() - == WorldCanonicalInstancePreparationRepository.ExecutionState.COMMITTED - ? WorldStartSessionExecutionTerminal.Outcome.COMMITTED - : WorldStartSessionExecutionTerminal.Outcome.ABORTED)); + ? WorldStartSessionExecutionTerminal.Outcome.COMMITTED + : WorldStartSessionExecutionTerminal.Outcome.ABORTED)); } private static void denyRecoveryByDefault(WorldCanonicalInstanceExecutionIdentity identity) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingService.java index 579f2341d0..ad215f2d18 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingService.java @@ -304,10 +304,9 @@ public AuthoredWorldVersionStateEvidence readCurrentVersionState( WorldCompleteLaunchBindingRepository.StoredBinding stored = repository .read(workloadNamespace, expected.canonicalTenantId(), expected.controlPlaneRequestId()) - .orElseThrow( - () -> - new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( - "World current-version verification requires a committed launch binding")); + .orElseThrow(() -> + new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "World current-version verification requires a committed launch binding")); requireStoredRequest(stored, request); WorldCompleteLaunchBindingReceipt committed = loadExactSourceReceipt(stored); requireStoredRequest(committed, request); @@ -379,10 +378,9 @@ private WorldAuthoredSourceIntakeReceipt readExactSourceReceipt( descriptor.worldSlug(), descriptor.authoredWorldSourceOperationId(), descriptor.authoredWorldSourceEvidenceDigest()) - .orElseThrow( - () -> - new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( - "Complete launch binding has no exact committed World source intake")); + .orElseThrow(() -> + new WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException( + "Complete launch binding has no exact committed World source intake")); } private void requireFreshCommittedLaunchReadId( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java index 58524d02cc..7ae24abc01 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceRepository.java @@ -309,10 +309,9 @@ private ResolvedVersion resolveVersion(OwnerBinding binding, IntakeReadIntent re binding.targetNamespace(), binding.intakeRequestId()); }; WorldAuthoredSourceIntakeReceipt receipt = - intake.orElseThrow( - () -> - new MissingIntakeException( - "World publication fence requires an already committed authored-source intake")); + intake.orElseThrow(() -> + new MissingIntakeException( + "World publication fence requires an already committed authored-source intake")); requireExactIntake(binding, receipt); Record identity = diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplication.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplication.java index 81cc28eb69..38f5efb138 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplication.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplication.java @@ -17,25 +17,24 @@ public record WorldDraftGraphApplication( } plan.graph() .freshGraphDeclaration() - .ifPresent( - declaration -> { - Map actualCounts = - plan.graph().nodes().stream() - .collect( - Collectors.groupingBy( - node -> - node.mutation() - .getAggregateType() - .name() - .replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""), - Collectors.counting())); - for (var family : declaration.familyCounts()) { - String name = family.family().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); - if (actualCounts.getOrDefault(name, 0L) != family.count()) { - throw new IllegalArgumentException( - "Account-bound application differs from its complete family declaration"); - } - } - }); + .ifPresent(declaration -> { + Map actualCounts = + plan.graph().nodes().stream() + .collect( + Collectors.groupingBy( + node -> + node.mutation() + .getAggregateType() + .name() + .replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""), + Collectors.counting())); + for (var family : declaration.familyCounts()) { + String name = family.family().name().replace("WORLD_DESIGN_AGGREGATE_TYPE_", ""); + if (actualCounts.getOrDefault(name, 0L) != family.count()) { + throw new IllegalArgumentException( + "Account-bound application differs from its complete family declaration"); + } + } + }); } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java index 85d40971fd..2f8bcf330f 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationRepository.java @@ -227,9 +227,8 @@ WorldDraftGraphAppliedResult apply( var result = WorldDraftGraphAppliedResult.create(application, stored.graphBytes()); result .startLocationReceipt() - .ifPresent( - receipt -> - startLocations.store(receipt, application.operation().accountBindingBytes())); + .ifPresent(receipt -> + startLocations.store(receipt, application.operation().accountBindingBytes())); dsl.execute( "INSERT INTO world_draft_graph_application (operation_id,request_id,commit_id,authorization_fence_id," + "operation_bytes,account_binding_bytes,account_binding_digest,result_bytes,result_digest) VALUES (?,?,?,?,?,?,?,?,?)", @@ -490,12 +489,11 @@ private void requireTransaction() { if (!TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) throw new ConflictException("Writable World application transaction required"); - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) - throw new ConflictException("World application requires READ_COMMITTED"); - }); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) + throw new ConflictException("World application requires READ_COMMITTED"); + }); } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphAppliedResult.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphAppliedResult.java index 4355d6dcb1..d6fbaea620 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphAppliedResult.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphAppliedResult.java @@ -46,11 +46,10 @@ private WorldDraftGraphAppliedResult(WorldDraftGraphApplication application, byt result.put("operationBytesBase64", base64(application.operation().canonicalBytes())); result.put("graphBytesBase64", base64(this.graphBytes)); result.put("graphDigest", digest(this.graphBytes)); - startLocationReceipt.ifPresent( - receipt -> { - result.put("startLocationReceiptBase64", base64(receipt.canonicalBytes())); - result.put("startLocationReceiptDigest", receipt.receiptDigest()); - }); + startLocationReceipt.ifPresent(receipt -> { + result.put("startLocationReceiptBase64", base64(receipt.canonicalBytes())); + result.put("startLocationReceiptDigest", receipt.receiptDigest()); + }); result.put("appliedEpochs", appliedEpochs()); try { canonicalBytes = @@ -131,15 +130,14 @@ public DraftAuthorizationFenceBinding.OwnerReadback ownerReadback() { public List appliedEpochs() { return application.operation().binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .map(unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) .toList(); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceipt.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceipt.java index d7796b0f66..7f7a8c86d8 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceipt.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftStartLocationReceipt.java @@ -38,10 +38,9 @@ static WorldDraftStartLocationReceipt create( .plan() .graph() .freshGraphDeclaration() - .orElseThrow( - () -> - new IllegalArgumentException( - "World start-location receipt requires an original graph declaration")) + .orElseThrow(() -> + new IllegalArgumentException( + "World start-location receipt requires an original graph declaration")) .startLocation(); String graphDigest = WorldDraftGraphAppliedResult.digest(graphBytes); var evidence = diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeRepository.java index 6865e38baf..a7b1b837d1 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeRepository.java @@ -452,13 +452,12 @@ private void requireTransaction() { || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { throw new ConflictException("Writable World owner transaction required"); } - dsl.connection( - connection -> { - if (connection.getAutoCommit() - || connection.isReadOnly() - || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { - throw new ConflictException("World terminal outcome requires READ_COMMITTED"); - } - }); + dsl.connection(connection -> { + if (connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED) { + throw new ConflictException("World terminal outcome requires READ_COMMITTED"); + } + }); } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java index 91b83d63af..63e095b457 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitRepository.java @@ -622,16 +622,15 @@ private byte[] encodeResult(WorldDraftTopologyCommitPlan plan, byte[] graph) { result.put( "affectedEpochsAfter", plan.binding().affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - u -> { - Map after = new LinkedHashMap<>(); - after.put("aggregateType", u.aggregateType()); - after.put("aggregateId", u.aggregateId()); - after.put("scopeType", u.scopeType()); - after.put("scopeId", u.scopeId()); - after.put("epoch", "1"); - return after; - }) + .map(u -> { + Map after = new LinkedHashMap<>(); + after.put("aggregateType", u.aggregateType()); + after.put("aggregateId", u.aggregateId()); + after.put("scopeType", u.scopeType()); + after.put("scopeId", u.scopeId()); + after.put("epoch", "1"); + return after; + }) .toList()); return STABLE_JSON.writeValueAsBytes(result); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyInputGraph.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyInputGraph.java index 49238936d9..b667fd67db 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyInputGraph.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyInputGraph.java @@ -87,13 +87,12 @@ public Map content() { content.put( "familyCounts", familyCounts.stream() - .map( - family -> { - Map entry = new LinkedHashMap<>(); - entry.put("family", family.family().name()); - entry.put("count", family.count()); - return entry; - }) + .map(family -> { + Map entry = new LinkedHashMap<>(); + entry.put("family", family.family().name()); + entry.put("count", family.count()); + return entry; + }) .toList()); return content; } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplicationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplicationService.java index 496ee98394..7c17614218 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplicationService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplicationService.java @@ -74,19 +74,17 @@ public WorldDraftGraphAppliedResult apply( target.canonicalTenantId(), target.canonicalVersionId(), target.gameDesignVersionRowId()) - .orElseThrow( - () -> - new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( - "Exact World authored-Version identity receipt is missing")); + .orElseThrow(() -> + new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Exact World authored-Version identity receipt is missing")); WorldAuthoredSourceIntakeReceipt retainedIntake = identity.sourceIntakeReceipt(); WorldAuthoredSourceIntakeReceipt committedIntake = sourceIntakes .read(receiverNamespace, retainedIntake.intakeRequestId()) - .orElseThrow( - () -> - new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( - "Exact World source intake association is missing")); + .orElseThrow(() -> + new WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException( + "Exact World source intake association is missing")); if (!retainedIntake.equals(committedIntake)) { throw conflict("World Version identity differs from its independently read source intake"); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperation.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperation.java index 941f8a9725..07a4f2c848 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperation.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperation.java @@ -68,11 +68,10 @@ public static WorldPrivateFreshOperation create( throw new IllegalArgumentException( "Private FRESH generation and spawn intent are unsupported"); if (plan.regions().stream() - .anyMatch( - region -> - !region.content().getWeather().isEmpty() - || !region.content().getGeneratorType().isEmpty() - || !region.content().getGeneratorParams().isEmpty())) + .anyMatch(region -> + !region.content().getWeather().isEmpty() + || !region.content().getGeneratorType().isEmpty() + || !region.content().getGeneratorParams().isEmpty())) throw new IllegalArgumentException( "Private FRESH configured weather and region generation are unsupported"); if (plan.regions().isEmpty() || plan.zones().isEmpty() || plan.rooms().isEmpty()) diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperationRepository.java index b7308dcd71..2d2a97cf9c 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperationRepository.java @@ -96,31 +96,29 @@ private Terminal execute(WorldPrivateFreshOperation input, boolean abort) { ByteString original = Objects.requireNonNull(held.originalOperation()); requireExact(input, held, source, original); // Persist the immutable original before a separately committed materialization/abort outcome. - write.executeWithoutResult( - status -> { + write.executeWithoutResult(status -> { + requireExact(input, held, source, original); + timeouts(); + dsl.fetchValue( + "SELECT " + schema + ".world_private_fresh_intent(?,?,?)", + input.inputJson(), + input.inputDigest(), + original.toByteArray()); + requireExact(input, held, source, original); + }); + requireExact(input, held, source, original); + Terminal committed = + write.execute(status -> { requireExact(input, held, source, original); timeouts(); dsl.fetchValue( - "SELECT " + schema + ".world_private_fresh_intent(?,?,?)", - input.inputJson(), - input.inputDigest(), - original.toByteArray()); + "SELECT " + schema + ".world_private_fresh_finish(?,?)", + input.operationId(), + abort); requireExact(input, held, source, original); + return terminal(input.operationId()).orElseThrow(); }); requireExact(input, held, source, original); - Terminal committed = - write.execute( - status -> { - requireExact(input, held, source, original); - timeouts(); - dsl.fetchValue( - "SELECT " + schema + ".world_private_fresh_finish(?,?)", - input.operationId(), - abort); - requireExact(input, held, source, original); - return terminal(input.operationId()).orElseThrow(); - }); - requireExact(input, held, source, original); Terminal retained = read(input.operationId()).orElseThrow(); if (!retained.equals(committed)) throw new IllegalStateException("Private terminal changed before committed readback"); @@ -132,11 +130,10 @@ private Terminal execute(WorldPrivateFreshOperation input, boolean abort) { public Optional read(UUID operationId) { independent(); Objects.requireNonNull(operationId); - return read.execute( - status -> { - timeouts(); - return terminal(operationId); - }); + return read.execute(status -> { + timeouts(); + return terminal(operationId); + }); } private void timeouts() { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPrivatePreparationBuildAssembly.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPrivatePreparationBuildAssembly.java index c2756da20d..157b3d26af 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPrivatePreparationBuildAssembly.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPrivatePreparationBuildAssembly.java @@ -97,15 +97,14 @@ static WorldAuthoredGraphSnapshot.CaptureRequest capture( request.contentDigest(), request.digestSchemaVersion(), request.worldAffectedTuples().stream() - .map( - tuple -> - new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( - tuple.owner(), - tuple.aggregateType(), - tuple.aggregateId(), - tuple.scopeType(), - tuple.scopeId(), - tuple.expectedEpoch())) + .map(tuple -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) .toList()); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadService.java index 56158b34c0..0867464b34 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadService.java @@ -66,11 +66,10 @@ public GameDesignPublicationTerminalEvidence read( GameDesignPublicationTerminalEvidence committed = repository .readCommitted(terminalRequest) - .orElseThrow( - () -> - Status.FAILED_PRECONDITION - .withDescription("Exact committed World terminal is unavailable") - .asRuntimeException()); + .orElseThrow(() -> + Status.FAILED_PRECONDITION + .withDescription("Exact committed World terminal is unavailable") + .asRuntimeException()); if (!Arrays.equals( request.expectedGameDesignTerminalEvidence(), committed.canonicalBytes())) { throw Status.FAILED_PRECONDITION diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalRepository.java index 488febe63d..fb75ba7e05 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalRepository.java @@ -110,59 +110,56 @@ public GameDesignPublicationTerminalEvidence complete( requireNoAmbientTransaction("World publication terminal"); GameDesignPublicationTerminalEvidence committed = Objects.requireNonNull( - ownerTransaction.execute( - status -> { - requireWritableReadCommittedTransaction(); - authority.requireHeld(); - Record owner = lockOriginalOwner(request); - Optional prior = - readInOwnerTransaction(request); - if (prior.isPresent()) return prior.orElseThrow(); - if (!"FROZEN".equals(required(owner, "owner_freeze_phase", String.class))) { - throw new PublicationTerminalConflictException( - "World publication fence is no longer open for its first terminal result"); - } + ownerTransaction.execute(status -> { + requireWritableReadCommittedTransaction(); + authority.requireHeld(); + Record owner = lockOriginalOwner(request); + Optional prior = + readInOwnerTransaction(request); + if (prior.isPresent()) return prior.orElseThrow(); + if (!"FROZEN".equals(required(owner, "owner_freeze_phase", String.class))) { + throw new PublicationTerminalConflictException( + "World publication fence is no longer open for its first terminal result"); + } - insertTerminal(request); - String phase = request.ownerPhase(); - int updated = - dsl.execute( - "UPDATE world_design_publication_fence_owner SET owner_freeze_phase=? " - + "WHERE target_namespace=? AND canonical_tenant_id=? " - + "AND local_tenant_key=? AND version_id=? " - + "AND owner_freeze_phase='FROZEN' AND current_publication_fence=?", - phase, - request.worldEvidence().request().targetNamespace(), - request.worldEvidence().request().canonicalTenantId(), - required(owner, "local_tenant_key", Long.class), - required(owner, "version_id", Long.class), - request.worldEvidence().request().publicationFence()); - if (updated != 1) { - throw new PublicationTerminalConflictException( - "World publication terminal lost the exact locked FROZEN owner row"); - } - authority.requireHeld(); - GameDesignPublicationTerminalEvidence readback = - readInOwnerTransaction(request) - .orElseThrow( - () -> - new PublicationTerminalConflictException( - "World publication terminal has no exact immutable readback")); - if (!Arrays.equals(readback.canonicalBytes(), request.terminalBytes())) { - throw new PublicationTerminalConflictException( - "World publication terminal differs from exact inserted evidence"); - } - return readback; - }), + insertTerminal(request); + String phase = request.ownerPhase(); + int updated = + dsl.execute( + "UPDATE world_design_publication_fence_owner SET owner_freeze_phase=? " + + "WHERE target_namespace=? AND canonical_tenant_id=? " + + "AND local_tenant_key=? AND version_id=? " + + "AND owner_freeze_phase='FROZEN' AND current_publication_fence=?", + phase, + request.worldEvidence().request().targetNamespace(), + request.worldEvidence().request().canonicalTenantId(), + required(owner, "local_tenant_key", Long.class), + required(owner, "version_id", Long.class), + request.worldEvidence().request().publicationFence()); + if (updated != 1) { + throw new PublicationTerminalConflictException( + "World publication terminal lost the exact locked FROZEN owner row"); + } + authority.requireHeld(); + GameDesignPublicationTerminalEvidence readback = + readInOwnerTransaction(request) + .orElseThrow(() -> + new PublicationTerminalConflictException( + "World publication terminal has no exact immutable readback")); + if (!Arrays.equals(readback.canonicalBytes(), request.terminalBytes())) { + throw new PublicationTerminalConflictException( + "World publication terminal differs from exact inserted evidence"); + } + return readback; + }), "World publication terminal transaction did not commit"); // Confirm committed immutable readback after TransactionTemplate returns from commit. GameDesignPublicationTerminalEvidence readback = readCommitted(request) - .orElseThrow( - () -> - new PublicationTerminalConflictException( - "Committed World publication terminal has no independent readback")); + .orElseThrow(() -> + new PublicationTerminalConflictException( + "Committed World publication terminal has no independent readback")); if (!Arrays.equals(committed.canonicalBytes(), readback.canonicalBytes())) { throw new PublicationTerminalConflictException( "Committed World publication terminal differs from its owner transaction readback"); @@ -176,15 +173,14 @@ public Optional readCommitted( Objects.requireNonNull(request, "request"); requireNoAmbientTransaction("World publication terminal readback"); Record row = - independentReadTransaction.execute( - status -> { - requireReadOnlyRepeatableReadTransaction(); - Record terminal = readTerminalWithOwner(request, false); - if (terminal == null) { - requirePendingOwner(request); - } - return terminal; - }); + independentReadTransaction.execute(status -> { + requireReadOnlyRepeatableReadTransaction(); + Record terminal = readTerminalWithOwner(request, false); + if (terminal == null) { + requirePendingOwner(request); + } + return terminal; + }); if (row == null) return Optional.empty(); return Optional.of(exactReadback(request, row)); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java index 28adf84086..79d91dc025 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwner.java @@ -176,10 +176,9 @@ static RequirementProjection projectRequirements( FreshGraphDeclaration declaration = authoredGraph .freshGraphDeclaration() - .orElseThrow( - () -> - new IllegalArgumentException( - "Published World source lacks its original complete family declaration")); + .orElseThrow(() -> + new IllegalArgumentException( + "Published World source lacks its original complete family declaration")); if (!authoredGraph.tenantId().equals(frozenGraph.tenantId()) || !authoredGraph.versionId().equals(frozenGraph.versionId()) || authoredGraph.nodes().size() != frozenGraph.rows().size()) { @@ -365,33 +364,28 @@ private static void requireExactReleaseGraph( freeze.contentDigest(), freeze.digestSchemaVersion(), freeze.suppliedOwnedAffectedTuples().stream() - .map( - tuple -> - new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( - tuple.owner(), - tuple.aggregateType(), - tuple.aggregateId(), - tuple.scopeType(), - tuple.scopeId(), - tuple.expectedEpoch())) + .map(tuple -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) .toList()); var receipt = WorldDraftStartLocationEvidence.fromStored(selector.selectorReceiptBytes()); FreshGraphDeclaration declaration = plan.graph() .freshGraphDeclaration() - .orElseThrow( - () -> - new IllegalArgumentException( - "Selected World graph has no original fresh declaration")); + .orElseThrow(() -> + new IllegalArgumentException( + "Selected World graph has no original fresh declaration")); if (!selector.request().equals(expected) || !declaration.startLocation().equals(receipt.startLocation()) || !receipt.bindingDigest().equals(binding.digest()) || frozenTopology.graph().family(Family.ROOM).stream() - .filter( - room -> - room.template() - .templateId() - .equals(receipt.startLocation().roomTemplateId())) + .filter(room -> + room.template().templateId().equals(receipt.startLocation().roomTemplateId())) .count() != 1) { throw new IllegalArgumentException( @@ -415,15 +409,14 @@ private static CaptureRequest captureRequest(WorldPublishedStartLocationEvidence request.contentDigest(), request.digestSchemaVersion(), request.worldAffectedTuples().stream() - .map( - tuple -> - new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( - tuple.owner(), - tuple.aggregateType(), - tuple.aggregateId(), - tuple.scopeType(), - tuple.scopeId(), - tuple.expectedEpoch())) + .map(tuple -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) .toList()); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcService.java index c10d5c1f75..de9daad78c 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationReadGrpcService.java @@ -152,15 +152,14 @@ private static CaptureRequest toCaptureRequest( request.contentDigest(), request.digestSchemaVersion(), request.worldAffectedTuples().stream() - .map( - tuple -> - new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( - tuple.owner(), - tuple.aggregateType(), - tuple.aggregateId(), - tuple.scopeType(), - tuple.scopeId(), - tuple.expectedEpoch())) + .map(tuple -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) .toList()); } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationRepository.java index 02557eb327..8030dc25bb 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedStartLocationRepository.java @@ -74,10 +74,8 @@ private Optional readSource( var receipt = applied .startLocationReceipt() - .orElseThrow( - () -> - new ConflictException( - "World published selector lacks original selector receipt")); + .orElseThrow(() -> + new ConflictException("World published selector lacks original selector receipt")); if (!plan.binding().equals(application.plan().binding()) || !plan.ownerBinding().equals(application.plan().ownerBinding()) || !Arrays.equals(account.canonicalBytes(), application.operation().accountBindingBytes()) diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogRepository.java index ae5166b6de..ecb4422b2f 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogRepository.java @@ -50,29 +50,28 @@ public WorldRuntimeFamilyCatalogRepository( public Evidence read(Request request) { requireIndependent(request); byte[] committed = - capture.execute( - status -> { - WorldRuntimeFamilyCatalog catalog = currentCatalog(); - byte[] requestBytes = WorldRuntimeFamilyCatalogCodec.requestBytes(request); - var proposed = new Evidence(request, UUID.randomUUID(), catalog); - byte[] evidenceBytes = WorldRuntimeFamilyCatalogCodec.evidenceBytes(proposed); - dsl.execute( - "INSERT INTO " - + table("world_runtime_family_catalog_snapshot") - + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," - + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)" - + " ON CONFLICT (read_request_id) DO NOTHING", - request.readRequestId(), - request.targetNamespace(), - requestBytes, - WorldRuntimeFamilyCatalog.sha256(requestBytes), - proposed.snapshotId(), - catalog.catalogEpoch(), - catalog.digest(), - evidenceBytes, - proposed.digest()); - return retained(request, catalog); - }); + capture.execute(status -> { + WorldRuntimeFamilyCatalog catalog = currentCatalog(); + byte[] requestBytes = WorldRuntimeFamilyCatalogCodec.requestBytes(request); + var proposed = new Evidence(request, UUID.randomUUID(), catalog); + byte[] evidenceBytes = WorldRuntimeFamilyCatalogCodec.evidenceBytes(proposed); + dsl.execute( + "INSERT INTO " + + table("world_runtime_family_catalog_snapshot") + + " (read_request_id,target_namespace,request_bytes,request_digest,snapshot_id," + + "catalog_epoch,catalog_digest,evidence_bytes,evidence_digest) VALUES (?,?,?,?,?,?,?,?,?)" + + " ON CONFLICT (read_request_id) DO NOTHING", + request.readRequestId(), + request.targetNamespace(), + requestBytes, + WorldRuntimeFamilyCatalog.sha256(requestBytes), + proposed.snapshotId(), + catalog.catalogEpoch(), + catalog.digest(), + evidenceBytes, + proposed.digest()); + return retained(request, catalog); + }); Evidence result = readExact(request); if (!Arrays.equals(committed, WorldRuntimeFamilyCatalogCodec.evidenceBytes(result))) { throw new CatalogConflictException("Committed catalog readback changed"); @@ -85,9 +84,8 @@ public Evidence read(Request request) { */ public Evidence readExact(Request request) { requireIndependent(request); - return readback.execute( - status -> - WorldRuntimeFamilyCatalogCodec.evidenceFromStored(retained(request, currentCatalog()))); + return readback.execute(status -> + WorldRuntimeFamilyCatalogCodec.evidenceFromStored(retained(request, currentCatalog()))); } private WorldRuntimeFamilyCatalog currentCatalog() { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistry.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistry.java index 9ae41a57b6..b53b872883 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistry.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistry.java @@ -69,59 +69,57 @@ public Registration register() { held.requireCurrent(); var artifact = artifact(held); Registration committed = - write.execute( - status -> { - // One namespace serializes registration; source authority remains held through - // commit. - dsl.execute( - "SELECT pg_advisory_xact_lock(hashtextextended(?,0))", - "world-runtime-registry/" + namespace); - Record current = - dsl.fetchOne( - "SELECT * FROM " - + table("world_runtime_installation_current") - + " WHERE target_namespace=? FOR UPDATE", - namespace); - Record old = - dsl.fetchOne( - "SELECT * FROM " - + table("world_runtime_installation_registration") - + " WHERE artifact_id=?", - artifact.artifactId()); - Registration registered; - if (old != null) { - registered = registration(old); - exact(registered.artifact(), artifact); - if (current == null - || registered.revision() != current.get("revision", Long.class)) { - throw new RegistryUnavailableException( - "Historical installation cannot replace the current registration"); - } - } else { - Record inserted = - dsl.fetchSingle( - "INSERT INTO " - + table("world_runtime_installation_registration") - + " (artifact_id,installation_id,target_namespace,artifact_bytes,artifact_digest) VALUES (?,?,?,?,?) RETURNING *", - artifact.artifactId(), - artifact.installationId(), - namespace, - artifact.exactBytes(), - artifact.digest()); - registered = registration(inserted); - dsl.execute( + write.execute(status -> { + // One namespace serializes registration; source authority remains held through + // commit. + dsl.execute( + "SELECT pg_advisory_xact_lock(hashtextextended(?,0))", + "world-runtime-registry/" + namespace); + Record current = + dsl.fetchOne( + "SELECT * FROM " + + table("world_runtime_installation_current") + + " WHERE target_namespace=? FOR UPDATE", + namespace); + Record old = + dsl.fetchOne( + "SELECT * FROM " + + table("world_runtime_installation_registration") + + " WHERE artifact_id=?", + artifact.artifactId()); + Registration registered; + if (old != null) { + registered = registration(old); + exact(registered.artifact(), artifact); + if (current == null || registered.revision() != current.get("revision", Long.class)) { + throw new RegistryUnavailableException( + "Historical installation cannot replace the current registration"); + } + } else { + Record inserted = + dsl.fetchSingle( "INSERT INTO " - + table("world_runtime_installation_current") - + " (target_namespace,revision,artifact_digest) VALUES (?,?,?) ON CONFLICT (target_namespace)" - + " DO UPDATE SET revision=EXCLUDED.revision,artifact_digest=EXCLUDED.artifact_digest", + + table("world_runtime_installation_registration") + + " (artifact_id,installation_id,target_namespace,artifact_bytes,artifact_digest) VALUES (?,?,?,?,?) RETURNING *", + artifact.artifactId(), + artifact.installationId(), namespace, - registered.revision(), + artifact.exactBytes(), artifact.digest()); - } - held.requireCurrent(); - exact(artifact(held), artifact); - return registered; - }); + registered = registration(inserted); + dsl.execute( + "INSERT INTO " + + table("world_runtime_installation_current") + + " (target_namespace,revision,artifact_digest) VALUES (?,?,?) ON CONFLICT (target_namespace)" + + " DO UPDATE SET revision=EXCLUDED.revision,artifact_digest=EXCLUDED.artifact_digest", + namespace, + registered.revision(), + artifact.digest()); + } + held.requireCurrent(); + exact(artifact(held), artifact); + return registered; + }); held.requireCurrent(); Registration result = current(); if (committed.revision() != result.revision()) { @@ -154,17 +152,16 @@ public void preflightLaunchOwners(UUID gameInstanceId) { held.requireCurrent(); var artifact = artifact(held); artifact.requireResolved(); - read.executeWithoutResult( - status -> { - var registered = currentInTransaction(false); - exact(registered.artifact(), artifact); - if (dsl.fetchExists( - dsl.selectOne() - .from(table("world_runtime_required_owner_snapshot")) - .where("canonical_game_instance_id=?", gameInstanceId))) { - requireFrozen(gameInstanceId, registered); - } - }); + read.executeWithoutResult(status -> { + var registered = currentInTransaction(false); + exact(registered.artifact(), artifact); + if (dsl.fetchExists( + dsl.selectOne() + .from(table("world_runtime_required_owner_snapshot")) + .where("canonical_game_instance_id=?", gameInstanceId))) { + requireFrozen(gameInstanceId, registered); + } + }); held.requireCurrent(); exact(artifact(held), artifact); } @@ -186,26 +183,25 @@ public T withLaunchOwners(UUID gameInstanceId, Supplier launchOwner) { held.requireCurrent(); var artifact = artifact(held); artifact.requireResolved(); - write.executeWithoutResult( - status -> { - var registered = currentInTransaction(true); - exact(registered.artifact(), artifact); - dsl.execute( - "INSERT INTO " - + table("world_runtime_required_owner_snapshot") - + " (canonical_game_instance_id,target_namespace,registry_revision,artifact_digest,required_owners)" - + " VALUES (?,?,?,?," - + schema - + ".world_runtime_required_owners(?)) ON CONFLICT (canonical_game_instance_id) DO NOTHING", - gameInstanceId, - namespace, - registered.revision(), - artifact.digest(), - artifact.exactBytes()); - requireFrozen(gameInstanceId, registered); - held.requireCurrent(); - exact(artifact(held), artifact); - }); + write.executeWithoutResult(status -> { + var registered = currentInTransaction(true); + exact(registered.artifact(), artifact); + dsl.execute( + "INSERT INTO " + + table("world_runtime_required_owner_snapshot") + + " (canonical_game_instance_id,target_namespace,registry_revision,artifact_digest,required_owners)" + + " VALUES (?,?,?,?," + + schema + + ".world_runtime_required_owners(?)) ON CONFLICT (canonical_game_instance_id) DO NOTHING", + gameInstanceId, + namespace, + registered.revision(), + artifact.digest(), + artifact.exactBytes()); + requireFrozen(gameInstanceId, registered); + held.requireCurrent(); + exact(artifact(held), artifact); + }); read.executeWithoutResult( status -> requireFrozen(gameInstanceId, currentInTransaction(false))); held.requireCurrent(); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationCheckpointRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationCheckpointRepository.java index b5cdee2783..55397c0d09 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationCheckpointRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationCheckpointRepository.java @@ -65,10 +65,9 @@ CapturedCheckpoint captureWithSource( var inboundClosure = graph .inboundSourceClosure() - .orElseThrow( - () -> - new ConflictException( - "World selected digest requires the exact original inbound source closure")); + .orElseThrow(() -> + new ConflictException( + "World selected digest requires the exact original inbound source closure")); var digest = digestService.getSelectedDraftDesignDigest( Long.toString(owner.localTenantKey()), diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java index 2b5b65ccc9..000f10f038 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeService.java @@ -146,10 +146,8 @@ Acknowledgement begin(Request request) { request.canonicalTenantId(), request.canonicalVersionId(), selection) - .orElseThrow( - () -> - conflict( - "World selected-publication request has no exact retained APPLIED graph")); + .orElseThrow(() -> + conflict("World selected-publication request has no exact retained APPLIED graph")); WorldDraftTopologyCommitPlan selectedPlan = application.plan(); WorldDraftTerminalOperation operation = application.operation(); WorldDesignPublicationFenceEvidence.OwnerBinding owner = operation.ownerBinding(); @@ -232,10 +230,9 @@ FrozenAttempt freeze( AccountPublicationAuthorizationBinding retained = authorizationRepository .readCommitted(stored) - .orElseThrow( - () -> - conflict( - "World freeze attempt has no original Account publication qualification")); + .orElseThrow(() -> + conflict( + "World freeze attempt has no original Account publication qualification")); requireSameAccountBinding(accountBinding, retained); artifactInventoryRepository.readCommitted(stored, retained); return stored; @@ -251,55 +248,48 @@ FrozenAttempt freeze( capturedCheckpoint = new AtomicReference<>(); FrozenAttempt transactionResult = Objects.requireNonNull( - ownerTransaction.execute( - status -> { - if (!TransactionSynchronizationManager.isActualTransactionActive() - || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { - throw new IllegalStateException( - "World selected-publication freeze requires a writable owner transaction"); - } - FrozenAttempt attempt = - fence.claimFreeze( - evidence, - () -> { - var captured = - checkpointRepository.captureWithSource(evidence, selectedPlan); - capturedCheckpoint.set(captured); - attemptCreatedInTransaction.set(true); - return captured.checkpoint(); - }); - AccountPublicationAuthorizationBinding retained = - authorizationRepository.retainOrRequireExact( - attempt, accountBinding, attemptCreatedInTransaction.get()); - requireSameAccountBinding(accountBinding, retained); - artifactInventoryRepository.retainOrRequireExact( - attempt, - retained, - attemptCreatedInTransaction.get(), - capturedCheckpoint.get()); - requireCheckpointMatchesSelection( - attempt, selectedPlan, accountBinding.input().selection()); - return attempt; - }), + ownerTransaction.execute(status -> { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly()) { + throw new IllegalStateException( + "World selected-publication freeze requires a writable owner transaction"); + } + FrozenAttempt attempt = + fence.claimFreeze( + evidence, + () -> { + var captured = + checkpointRepository.captureWithSource(evidence, selectedPlan); + capturedCheckpoint.set(captured); + attemptCreatedInTransaction.set(true); + return captured.checkpoint(); + }); + AccountPublicationAuthorizationBinding retained = + authorizationRepository.retainOrRequireExact( + attempt, accountBinding, attemptCreatedInTransaction.get()); + requireSameAccountBinding(accountBinding, retained); + artifactInventoryRepository.retainOrRequireExact( + attempt, retained, attemptCreatedInTransaction.get(), capturedCheckpoint.get()); + requireCheckpointMatchesSelection( + attempt, selectedPlan, accountBinding.input().selection()); + return attempt; + }), "World selected-publication freeze transaction did not commit"); // Acknowledgement follows the owner transaction's commit and exact immutable readback. FrozenAttempt committed = fence .readAttempt(evidence) - .orElseThrow( - () -> - conflict("Committed World selected-publication freeze has no exact readback")); + .orElseThrow(() -> + conflict("Committed World selected-publication freeze has no exact readback")); if (!transactionResult.equals(committed)) { throw conflict("Committed World freeze differs from its owner-transaction result"); } AccountPublicationAuthorizationBinding retained = authorizationRepository .readCommitted(committed) - .orElseThrow( - () -> - conflict( - "Committed World freeze has no exact Account publication qualification")); + .orElseThrow(() -> + conflict("Committed World freeze has no exact Account publication qualification")); requireSameAccountBinding(accountBinding, retained); artifactInventoryRepository.readCommitted(committed, retained); requireCheckpointMatchesSelection(committed, selectedPlan, accountBinding.input().selection()); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java index 7893bfe0e1..366cbd36b7 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventory.java @@ -258,10 +258,9 @@ static WorldSelectedPublicationArtifactInventory capture( var inboundClosure = graph .inboundSourceClosure() - .orElseThrow( - () -> - new ConflictException( - "World selected inventory requires the exact original inbound source closure declaration")); + .orElseThrow(() -> + new ConflictException( + "World selected inventory requires the exact original inbound source closure declaration")); List counts = new ArrayList<>(); for (WorldCanonicalAuthoredGraph.Family family : SUPPORTED_FAMILY_ORDER) { counts.add(new FamilyCount(family.name(), graph.family(family).size())); @@ -323,10 +322,9 @@ static WorldSelectedPublicationArtifactInventory capture( new WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration( inboundClosure.schemaVersion(), inboundClosure.familyCounts().stream() - .map( - family -> - new WorldSelectedPublicationArtifactInventoryEvidence - .InboundSourceFamilyCount(family.family().name(), family.count())) + .map(family -> + new WorldSelectedPublicationArtifactInventoryEvidence + .InboundSourceFamilyCount(family.family().name(), family.count())) .toList())); var bindingBytes = accountBinding.canonicalBytes(); var envelope = @@ -808,11 +806,10 @@ private static int familyCount(List counts, String family) { .filter(count -> family.equals(count.family())) .mapToInt(FamilyCount::rowCount) .findFirst() - .orElseThrow( - () -> - unrepresentable( - UnrepresentableReason.UNKNOWN_GRAPH_FAMILY, - "World selected graph omitted a required closed source family")); + .orElseThrow(() -> + unrepresentable( + UnrepresentableReason.UNKNOWN_GRAPH_FAMILY, + "World selected graph omitted a required closed source family")); } private static boolean isSha256(String value) { @@ -865,15 +862,14 @@ private static boolean appliedEpochsMatch( List actual) { var expected = selectedCommit.affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new AppliedEpoch( - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch(), - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .map(unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) .toList(); return !expected.isEmpty() && expected.equals(actual); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationSelectorCapture.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationSelectorCapture.java index c2d6cee814..8ad96f7448 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationSelectorCapture.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationSelectorCapture.java @@ -61,15 +61,14 @@ WorldCanonicalFrozenTopology capture( var tuples = binding.affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) + .map(unit -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) .toList(); var captureRequest = new CaptureRequest( diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java index 86690ef819..5a74ec2c51 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/AccountTenantOperationEntitlementClientMtlsTest.java @@ -50,27 +50,23 @@ void protectedReceiverDispatchesExplicitSourcesWithAuthenticatedWorkloadAndNoFal var paid = request(SourceKind.PAID_HOSTING); var demo = request(SourceKind.NON_PAID_DEMO); when(owner.evaluatePaid(any())) - .thenAnswer( - invocation -> { - var actual = - (AccountTenantOperationEntitlementOwner.Request) invocation.getArgument(0); - assertThat(actual) - .isEqualTo( - new AccountTenantOperationEntitlementOwner.Request( - paid.tenantId(), paid.requestId(), paid.expectedWorldWorkload())); - return evidence(paid); - }); + .thenAnswer(invocation -> { + var actual = (AccountTenantOperationEntitlementOwner.Request) invocation.getArgument(0); + assertThat(actual) + .isEqualTo( + new AccountTenantOperationEntitlementOwner.Request( + paid.tenantId(), paid.requestId(), paid.expectedWorldWorkload())); + return evidence(paid); + }); when(owner.evaluateDemo(any())) - .thenAnswer( - invocation -> { - var actual = - (AccountTenantOperationEntitlementOwner.Request) invocation.getArgument(0); - assertThat(actual) - .isEqualTo( - new AccountTenantOperationEntitlementOwner.Request( - demo.tenantId(), demo.requestId(), demo.expectedWorldWorkload())); - return evidence(demo); - }); + .thenAnswer(invocation -> { + var actual = (AccountTenantOperationEntitlementOwner.Request) invocation.getArgument(0); + assertThat(actual) + .isEqualTo( + new AccountTenantOperationEntitlementOwner.Request( + demo.tenantId(), demo.requestId(), demo.expectedWorldWorkload())); + return evidence(demo); + }); var receiver = new AccountTenantOperationEntitlementGrpcService(owner, "firemud"); Server server = receiver @@ -101,20 +97,18 @@ void protectedReceiverDispatchesExplicitSourcesWithAuthenticatedWorkloadAndNoFal }) { doThrow(failure).when(owner).evaluatePaid(any()); assertThatThrownBy(() -> client.read(paid)) - .satisfies( - thrown -> { - assertThat(Status.fromThrowable(thrown).getCode()) - .isEqualTo(Status.Code.INTERNAL); - var details = io.grpc.protobuf.StatusProto.fromThrowable(thrown); - assertThat(details).isNotNull(); - assertThat(details.getDetailsCount()).isEqualTo(1); - var detail = - details - .getDetails(0) - .unpack(net.firedevops.firemud.shared.v1.ErrorDetail.class); - assertThat(detail.getCode()).isEqualTo("INTERNAL"); - assertThat(detail.getMessage()).doesNotContain("private"); - }); + .satisfies(thrown -> { + assertThat(Status.fromThrowable(thrown).getCode()).isEqualTo(Status.Code.INTERNAL); + var details = io.grpc.protobuf.StatusProto.fromThrowable(thrown); + assertThat(details).isNotNull(); + assertThat(details.getDetailsCount()).isEqualTo(1); + var detail = + details + .getDetails(0) + .unpack(net.firedevops.firemud.shared.v1.ErrorDetail.class); + assertThat(detail.getCode()).isEqualTo("INTERNAL"); + assertThat(detail.getMessage()).doesNotContain("private"); + }); } verify(owner, org.mockito.Mockito.times(1)).evaluateDemo(any()); TransactionSynchronizationManager.setActualTransactionActive(true); @@ -209,10 +203,9 @@ void clientRejectsPlaintextBeforeChannelCreation() { var properties = new net.firedevops.firemud.common.grpc.CommonGrpcClientProperties(); properties.setPlaintext(true); var channels = mock(GrpcChannelFactory.class); - assertThatThrownBy( - () -> - new AccountTenantOperationEntitlementClient( - new ServiceEndpointsProperties(), properties, channels, "firemud")) + assertThatThrownBy(() -> + new AccountTenantOperationEntitlementClient( + new ServiceEndpointsProperties(), properties, channels, "firemud")) .isInstanceOf(IllegalArgumentException.class); org.mockito.Mockito.verifyNoInteractions(channels); } diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/EntityPlayerCreatedActorPlacementReceiptClientMtlsTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/EntityPlayerCreatedActorPlacementReceiptClientMtlsTest.java index 344795f392..4536f72a8f 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/EntityPlayerCreatedActorPlacementReceiptClientMtlsTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/EntityPlayerCreatedActorPlacementReceiptClientMtlsTest.java @@ -74,10 +74,9 @@ void authenticatesExactEntityServerAndPreservesReceiptFields(@TempDir Path tempo .build()); assertThatThrownBy(() -> client.read(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); var exact = receipt(request()); for (var malformed : java.util.List.of( @@ -105,21 +104,18 @@ void authenticatesExactEntityServerAndPreservesReceiptFields(@TempDir Path tempo expected.set(malformed); assertThatThrownBy(() -> client.read(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); } int beforeInvalid = calls.get(); assertThatThrownBy(() -> client.read(request().toBuilder().setSchemaVersion(2).build())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - client.read( - request().toBuilder() - .setOrigin( - request().getOrigin().toBuilder().setTargetNamespace("other")) - .build())) + assertThatThrownBy(() -> + client.read( + request().toBuilder() + .setOrigin(request().getOrigin().toBuilder().setTargetNamespace("other")) + .build())) .isInstanceOf(IllegalArgumentException.class); assertThat(calls).hasValue(beforeInvalid); } @@ -149,10 +145,9 @@ void rejectsWrongEntityServerAndWrongWorldClientCertificate(@TempDir Path tempor client.init(); assertThatThrownBy(() -> client.read(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); } } finally { stopServer(wrongServer); diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/EntityPreseededActorAssignmentReceiptClientMtlsTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/EntityPreseededActorAssignmentReceiptClientMtlsTest.java index da81f0573c..c18a139996 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/EntityPreseededActorAssignmentReceiptClientMtlsTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/EntityPreseededActorAssignmentReceiptClientMtlsTest.java @@ -76,10 +76,9 @@ void authenticatesExactEntityServerAndPreservesReceiptFields(@TempDir Path tempo .build()); assertThatThrownBy(() -> client.read(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); } } finally { stopServer(server); @@ -107,10 +106,9 @@ void rejectsWrongEntityServerAndWrongWorldClientCertificate(@TempDir Path tempor client.init(); assertThatThrownBy(() -> client.read(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); } } finally { stopServer(wrongServer); diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionCanonicalInitialAdmissionOwnerClientMtlsTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionCanonicalInitialAdmissionOwnerClientMtlsTest.java index 11c3593e4b..803bdba20c 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionCanonicalInitialAdmissionOwnerClientMtlsTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionCanonicalInitialAdmissionOwnerClientMtlsTest.java @@ -83,10 +83,9 @@ void authenticatesExactGameSessionPeerAndPreservesTransportOrRejectsChangedRespo response.set(null); assertThatThrownBy(() -> client.read(expectedIdentity)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); } } finally { stopServer(server); @@ -115,10 +114,9 @@ void rejectsWrongGameSessionWorkloadServiceAndNamespace(@TempDir Path temporary) client.init(); assertThatThrownBy(() -> client.read(identity)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); } } finally { stopServer(server); @@ -146,10 +144,9 @@ void preservesSameNamespaceWorldWorkloadAuthenticationAtGameSession(@TempDir Pat client.init(); assertThatThrownBy(() -> client.read(identity)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } assertThat(calls).hasValue(1); } finally { diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/AccountAdmissionProtectionCurrentOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/AccountAdmissionProtectionCurrentOwnerCompositionCrossServiceTest.java index 70422fba25..c21bca9117 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/AccountAdmissionProtectionCurrentOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/AccountAdmissionProtectionCurrentOwnerCompositionCrossServiceTest.java @@ -205,17 +205,16 @@ public void attachAccountRedemptionProjection( var authority = StartSessionAuthorityEvidenceBundle.decode( tuple.authorityEvidenceBundleBytes()); - write.executeWithoutResult( - ignored -> - attempts.attachAccountRedemptionProjection( - claim.get(), - new GameSessionStartSessionOperatorAttemptRepository - .AccountRedemptionProjection( - tuple.authorizationReferenceFingerprint(), - tuple.authorityEvidenceBundleBytes(), - authority.issuanceOperationId(), - Long.parseLong(tuple.issuanceFence()), - tuple.canonicalBytes()))); + write.executeWithoutResult(ignored -> + attempts.attachAccountRedemptionProjection( + claim.get(), + new GameSessionStartSessionOperatorAttemptRepository + .AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + authority.issuanceOperationId(), + Long.parseLong(tuple.issuanceFence()), + tuple.canonicalBytes()))); } }); var tuple = original.originalTuple(); diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java index c304080b3d..bdc9242d77 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcServiceMtlsTest.java @@ -94,13 +94,12 @@ void regionCodecMismatchAndSizeHaveDeterministicStatuses(@TempDir Path temporary Status.Code.UNAVAILABLE)) { assertThatThrownBy(() -> stub.readInitialPlayerLocationRegion(request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code); - assertThat(Status.fromThrowable(failure).getDescription()) - .doesNotContain("private"); - assertThat(Status.fromThrowable(failure).getCause()).isNull(); - }); + .satisfies(failure -> { + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code); + assertThat(Status.fromThrowable(failure).getDescription()) + .doesNotContain("private"); + assertThat(Status.fromThrowable(failure).getCause()).isNull(); + }); } } finally { stopChannel(channel); @@ -269,42 +268,38 @@ void bothRpcMethodsRequireTheExactSameNamespaceGameSessionCertificate(@TempDir P assertThat(read).isEqualTo(placed); assertThatThrownBy(() -> stub.readInitialPlayerLocation(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.NOT_FOUND)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.NOT_FOUND)); assertThatThrownBy(() -> stub.readInitialPlayerLocationRegion(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.NOT_FOUND)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.NOT_FOUND)); assertThatThrownBy(() -> stub.placeInitialPlayer(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - var status = Status.fromThrowable(failure); - assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); - assertThat(status.getDescription()) - .isEqualTo("World initial-player placement is unavailable"); - assertThat(status.getCause()).isNull(); - Metadata responseTrailers = ((StatusRuntimeException) failure).getTrailers(); - assertThat(responseTrailers == null || !responseTrailers.containsKey(secretKey)) - .isTrue(); - }); + .satisfies(failure -> { + var status = Status.fromThrowable(failure); + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status.getDescription()) + .isEqualTo("World initial-player placement is unavailable"); + assertThat(status.getCause()).isNull(); + Metadata responseTrailers = ((StatusRuntimeException) failure).getTrailers(); + assertThat(responseTrailers == null || !responseTrailers.containsKey(secretKey)) + .isTrue(); + }); assertThatThrownBy(() -> stub.placeInitialPlayer(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - var status = Status.fromThrowable(failure); - assertThat(status.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); - assertThat(status.getDescription()) - .isEqualTo("Exact World initial-placement owner evidence is unavailable"); - assertThat(status.getCause()).isNull(); - Metadata responseTrailers = ((StatusRuntimeException) failure).getTrailers(); - assertThat(responseTrailers == null || !responseTrailers.containsKey(secretKey)) - .isTrue(); - }); + .satisfies(failure -> { + var status = Status.fromThrowable(failure); + assertThat(status.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(status.getDescription()) + .isEqualTo("Exact World initial-placement owner evidence is unavailable"); + assertThat(status.getCause()).isNull(); + Metadata responseTrailers = ((StatusRuntimeException) failure).getTrailers(); + assertThat(responseTrailers == null || !responseTrailers.containsKey(secretKey)) + .isTrue(); + }); verify(service, times(3)) .place(CanonicalInitialPlayerLocationGrpcCodec.fromRequest(request)); verify(service, times(2)) @@ -312,15 +307,12 @@ void bothRpcMethodsRequireTheExactSameNamespaceGameSessionCertificate(@TempDir P verify(service) .readRegion(CanonicalInitialPlayerLocationGrpcCodec.fromRegionRequest(request)); - assertThatThrownBy( - () -> - stub.placeInitialPlayer( - CanonicalInitialPlayerLocationRequest.getDefaultInstance())) + assertThatThrownBy(() -> + stub.placeInitialPlayer(CanonicalInitialPlayerLocationRequest.getDefaultInstance())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.INVALID_ARGUMENT)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT)); } finally { stopChannel(channel); } @@ -341,10 +333,9 @@ void bothRpcMethodsRequireTheExactSameNamespaceGameSessionCertificate(@TempDir P } }) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } } finally { stopChannel(rejectedPeerChannel); diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/PrivateWorldPreparationSourceCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/PrivateWorldPreparationSourceCompositionCrossServiceTest.java index 3c7a4970ce..dfce3b00f2 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/PrivateWorldPreparationSourceCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/PrivateWorldPreparationSourceCompositionCrossServiceTest.java @@ -141,19 +141,17 @@ void actualOwnerProtectionRoundTripRetainsPendingSourceAndBlocksSupersession() t assertThat(current.admissionAllowed()).isFalse(); assertThat(db.dsl.fetchCount(DSL.table("game_session_private_preparation_protection"))) .isEqualTo(1); - assertThatThrownBy( - () -> - db.in( - () -> - db.current.select( - new GameSessionCurrentPrivatePlaytestRepository.Request( - UUID.randomUUID(), - new GameSessionCurrentPrivatePlaytestRepository.Scope( - NS, db.tenant, "source-world", "private-playtest"), - db.second.request().requestId(), - db.second.playtestLifecycleId(), - 1L, - db.first.playtestLifecycleId())))) + assertThatThrownBy(() -> + db.in(() -> + db.current.select( + new GameSessionCurrentPrivatePlaytestRepository.Request( + UUID.randomUUID(), + new GameSessionCurrentPrivatePlaytestRepository.Scope( + NS, db.tenant, "source-world", "private-playtest"), + db.second.request().requestId(), + db.second.playtestLifecycleId(), + 1L, + db.first.playtestLifecycleId())))) .isInstanceOf(RuntimeException.class) .hasStackTraceContaining("unresolved World preparation"); assertThat(rpc.protectionClient.acquire(request, input.committedReadback()).evidence()) @@ -260,17 +258,16 @@ void laterCatalogRevisionComposesAcrossRealMtlsWithoutReplacingTheRealmOrOrigina Objects.requireNonNull(db.serializable.execute(status -> revisions.advance(advance))) .snapshot(); var selected = - db.in( - () -> - db.current.select( - new GameSessionCurrentPrivatePlaytestRepository.Request( - UUID.randomUUID(), - new GameSessionCurrentPrivatePlaytestRepository.Scope( - NS, db.tenant, "source-world", "private-playtest"), - db.second.request().requestId(), - db.second.playtestLifecycleId(), - 1L, - db.first.playtestLifecycleId()))) + db.in(() -> + db.current.select( + new GameSessionCurrentPrivatePlaytestRepository.Request( + UUID.randomUUID(), + new GameSessionCurrentPrivatePlaytestRepository.Scope( + NS, db.tenant, "source-world", "private-playtest"), + db.second.request().requestId(), + db.second.playtestLifecycleId(), + 1L, + db.first.playtestLifecycleId()))) .receipt(); db.allocateRuntime(revised, selected); try (var rpc = new Running(db, directory)) { @@ -312,23 +309,20 @@ void actualCurrentOwnerCasBetweenCommittedReadsRefusesOriginalInsteadOfReselecti db.allocate(); String beforePublic = db.publicRows(); try (var rpc = new Running(db, directory)) { - rpc.afterFirst.set( - () -> - db.in( - () -> - db.current.select( - new GameSessionCurrentPrivatePlaytestRepository.Request( - UUID.randomUUID(), - new GameSessionCurrentPrivatePlaytestRepository.Scope( - NS, db.tenant, "source-world", "private-playtest"), - db.second.request().requestId(), - db.second.playtestLifecycleId(), - 1L, - db.first.playtestLifecycleId())))); - assertThatThrownBy( - () -> - new WorldPrivatePreparationInputAssembly(rpc.client, Clock.systemUTC()) - .assemble(db.scope(), db.first.request().requestId())) + rpc.afterFirst.set(() -> + db.in(() -> + db.current.select( + new GameSessionCurrentPrivatePlaytestRepository.Request( + UUID.randomUUID(), + new GameSessionCurrentPrivatePlaytestRepository.Scope( + NS, db.tenant, "source-world", "private-playtest"), + db.second.request().requestId(), + db.second.playtestLifecycleId(), + 1L, + db.first.playtestLifecycleId())))); + assertThatThrownBy(() -> + new WorldPrivatePreparationInputAssembly(rpc.client, Clock.systemUTC()) + .assemble(db.scope(), db.first.request().requestId())) .isInstanceOfSatisfying( StatusRuntimeException.class, error -> @@ -379,22 +373,20 @@ void guardedSourceAndReceiptDriftCannotPoisonExistingTargetAndOwnerReadStillQual var target = db.allocate(); var before = db.retainedRows(); for (String column : List.of("receipt_digest", "private_source_policy_carrier_digest")) { - assertThatThrownBy( - () -> - db.dsl.execute( - "UPDATE game_session_canonical_realm_catalog SET " - + column - + " = ? WHERE realm_id = ?", - "sha256:" + "b".repeat(64), - target.realmId())) + assertThatThrownBy(() -> + db.dsl.execute( + "UPDATE game_session_canonical_realm_catalog SET " + + column + + " = ? WHERE realm_id = ?", + "sha256:" + "b".repeat(64), + target.realmId())) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(db.retainedRows()).isEqualTo(before); } assertThat( - db.in( - () -> - db.targets.readForWorldPreparation( - db.first.request().requestId(), db.first.playtestLifecycleId()))) + db.in(() -> + db.targets.readForWorldPreparation( + db.first.request().requestId(), db.first.playtestLifecycleId()))) .contains(target); try (var rpc = new Running(db, directory)) { assertThat( @@ -467,18 +459,16 @@ private static Database database() { "NEW_GAME_ROW")); var intake = Objects.requireNonNull( - write.execute( - status -> - new GameSessionAuthoredWorldSourceRepository(dsl) - .register(UUID.randomUUID(), source))); - write.executeWithoutResult( - status -> - new GameSessionFreshTenantAssociationRepository(dsl) - .associateFresh( - UUID.randomUUID(), - NS, - intake, - CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(source))); + write.execute(status -> + new GameSessionAuthoredWorldSourceRepository(dsl) + .register(UUID.randomUUID(), source))); + write.executeWithoutResult(status -> + new GameSessionFreshTenantAssociationRepository(dsl) + .associateFresh( + UUID.randomUUID(), + NS, + intake, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(source))); var catalogRequest = new CreateCanonicalRealmCatalogRequest( UUID.randomUUID(), @@ -497,9 +487,9 @@ private static Database database() { var policy = RealmEntryPolicy.parse( """ - {"schemaVersion":1,"worldSlug":"source-world","worldDisplayName":"Source World","realmSlug":"private-playtest", - "realmDisplayName":"Private Playtest","visible":true,"publicProduction":false,"stateScope":"ISOLATED","entryPolicy":"PRESEEDED_ONLY"} - """, + {"schemaVersion":1,"worldSlug":"source-world","worldDisplayName":"Source World","realmSlug":"private-playtest", + "realmDisplayName":"Private Playtest","visible":true,"publicProduction":false,"stateScope":"ISOLATED","entryPolicy":"PRESEEDED_ONLY"} + """, JsonMapper.builder().build()); var published = CanonicalHumanPublicationOwnerTestFixtures.publishedSet( @@ -544,17 +534,16 @@ private static Database database() { var current = new GameSessionCurrentPrivatePlaytestRepository(dsl); var selected = Objects.requireNonNull( - write.execute( - status -> - current.select( - new GameSessionCurrentPrivatePlaytestRepository.Request( - UUID.randomUUID(), - new GameSessionCurrentPrivatePlaytestRepository.Scope( - NS, tenant, "source-world", "private-playtest"), - first.request().requestId(), - first.playtestLifecycleId(), - null, - null)))) + write.execute(status -> + current.select( + new GameSessionCurrentPrivatePlaytestRepository.Request( + UUID.randomUUID(), + new GameSessionCurrentPrivatePlaytestRepository.Scope( + NS, tenant, "source-world", "private-playtest"), + first.request().requestId(), + first.playtestLifecycleId(), + null, + null)))) .receipt(); return new Database( dsl, @@ -614,13 +603,12 @@ Scope scope() { CanonicalPrivateFreshTargetSnapshot allocate() { var target = Objects.requireNonNull( - serializable.execute( - status -> - targets.allocate( - new GameSessionPrivateFreshTargetRepository.Request( - UUID.randomUUID(), - first.request().requestId(), - first.playtestLifecycleId())))) + serializable.execute(status -> + targets.allocate( + new GameSessionPrivateFreshTargetRepository.Request( + UUID.randomUUID(), + first.request().requestId(), + first.playtestLifecycleId())))) .snapshot(); allocateRuntime(target, selection); return target; @@ -629,20 +617,19 @@ CanonicalPrivateFreshTargetSnapshot allocate() { void allocateRuntime( CanonicalPrivateFreshTargetSnapshot target, GameSessionCurrentPrivatePlaytestRepository.SelectionReceipt selected) { - serializable.execute( - status -> - new GameSessionPrivateFreshRuntimeAllocationRepository(dsl) - .allocate( - new GameSessionPrivateFreshRuntimeAllocationRepository.Request( - UUID.randomUUID(), - target.preparationRequestId(), - target.playtestLifecycleId(), - target.realmId(), - target.catalogRevision(), - target.creationRequestId(), - target.receiptDigest(), - selected.request().requestId(), - selected.headRevision()))); + serializable.execute(status -> + new GameSessionPrivateFreshRuntimeAllocationRepository(dsl) + .allocate( + new GameSessionPrivateFreshRuntimeAllocationRepository.Request( + UUID.randomUUID(), + target.preparationRequestId(), + target.playtestLifecycleId(), + target.realmId(), + target.catalogRevision(), + target.creationRequestId(), + target.receiptDigest(), + selected.request().requestId(), + selected.headRevision()))); } String publicRows() { diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java index 1723ad85c1..f4016b1a80 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java @@ -665,20 +665,19 @@ public void attachAccountRedemptionProjection( AccountOriginalStartSessionAuthorizationProofFixture.OwnerClaim owner, StartSessionPostAuthorizationExecutionTuple tuple) { gs.write() - .executeWithoutResult( - status -> - attempts.attachAccountRedemptionProjection( - claim.get(), - new GameSessionStartSessionOperatorAttemptRepository - .AccountRedemptionProjection( - tuple.authorizationReferenceFingerprint(), - tuple.authorityEvidenceBundleBytes(), - net.firedevops.firemud.common.operator - .StartSessionAuthorityEvidenceBundle.decode( - tuple.authorityEvidenceBundleBytes()) - .issuanceOperationId(), - Long.parseLong(tuple.issuanceFence()), - tuple.canonicalBytes()))); + .executeWithoutResult(status -> + attempts.attachAccountRedemptionProjection( + claim.get(), + new GameSessionStartSessionOperatorAttemptRepository + .AccountRedemptionProjection( + tuple.authorizationReferenceFingerprint(), + tuple.authorityEvidenceBundleBytes(), + net.firedevops.firemud.common.operator + .StartSessionAuthorityEvidenceBundle.decode( + tuple.authorityEvidenceBundleBytes()) + .issuanceOperationId(), + Long.parseLong(tuple.issuanceFence()), + tuple.canonicalBytes()))); } }); var tuple = original.originalTuple(); @@ -1054,15 +1053,14 @@ public ServerCall.Listener interceptCall( "account_start_session_activation_protection_settlements")); await() .atMost(Duration.ofSeconds(120)) - .until( - () -> - gs.dsl() - .fetchSingle( - "SELECT lease_expires_at <= clock_timestamp() " - + "FROM game_session_start_session_operator_attempt " - + "WHERE owner_attempt_id=?", - claim.get().ownerAttemptId()) - .get(0, Boolean.class)); + .until(() -> + gs.dsl() + .fetchSingle( + "SELECT lease_expires_at <= clock_timestamp() " + + "FROM game_session_start_session_operator_attempt " + + "WHERE owner_attempt_id=?", + claim.get().ownerAttemptId()) + .get(0, Boolean.class)); } return evidence; }; @@ -1128,13 +1126,12 @@ public ServerCall.Listener interceptCall( // The actual owner lease expires naturally; no SQL lease/history edits are used. await() .atMost(Duration.ofSeconds(60)) - .until( - () -> - gs.dsl() - .fetchSingle( - "SELECT lease_expires_at <= clock_timestamp() FROM game_session_start_session_operator_attempt WHERE owner_attempt_id=?", - claim.get().ownerAttemptId()) - .get(0, Boolean.class)); + .until(() -> + gs.dsl() + .fetchSingle( + "SELECT lease_expires_at <= clock_timestamp() FROM game_session_start_session_operator_attempt WHERE owner_attempt_id=?", + claim.get().ownerAttemptId()) + .get(0, Boolean.class)); } if (refusal == Refusal.NONE || refusal == Refusal.CHANGED_ACTIVATION_ATTEMPT @@ -1146,13 +1143,12 @@ public ServerCall.Listener interceptCall( "SELECT setval((current_schema() || '.room_instance_id_seq')::regclass, GREATEST((SELECT last_value FROM room_instance_id_seq), 127), true)"); } if (refusal == Refusal.MISMATCHED_ATTEMPT || refusal == Refusal.EXPIRED_ATTEMPT) { - assertThatThrownBy( - () -> - ClientCalls.blockingUnaryCall( - channel, - method, - CallOptions.DEFAULT.withDeadlineAfter(10, TimeUnit.SECONDS), - Empty.getDefaultInstance())) + assertThatThrownBy(() -> + ClientCalls.blockingUnaryCall( + channel, + method, + CallOptions.DEFAULT.withDeadlineAfter(10, TimeUnit.SECONDS), + Empty.getDefaultInstance())) .isInstanceOf(StatusRuntimeException.class); assertThat(result.get()).isNull(); assertThat(ownerRefusal.get()).isNotNull(); @@ -1579,17 +1575,15 @@ public ServerCall.Listener interceptCall( + "WHERE activation_protection_id=? ORDER BY source_key LIMIT 1", acquired.accountProtectionId()) .get("source_key", String.class); - assertThatThrownBy( - () -> - new TransactionTemplate(accountManager(issuer.sourceDsl())) - .executeWithoutResult( - status -> - issuer - .sourceDsl() - .execute( - "SELECT account_control_ui_hold_required_sources(" - + "ARRAY[?]::text[])", - protectedSourceKey))) + assertThatThrownBy(() -> + new TransactionTemplate(accountManager(issuer.sourceDsl())) + .executeWithoutResult(status -> + issuer + .sourceDsl() + .execute( + "SELECT account_control_ui_hold_required_sources(" + + "ARRAY[?]::text[])", + protectedSourceKey))) .hasMessageContaining( "Original StartSession activation protection remains pending"); assertThat( @@ -1615,24 +1609,22 @@ public void close() {} }; if (activationFailure == ActivationFailure.TRANSIENT_ROLLBACK_ALWAYS_FINAL_READBACK_FAILURE) { - assertThatThrownBy( - () -> - world - .installationRegistry() - .withLaunchOwners( - activationRequest.canonicalGameInstanceId(), - () -> activationRepository.activateProtected(protection, held))) + assertThatThrownBy(() -> + world + .installationRegistry() + .withLaunchOwners( + activationRequest.canonicalGameInstanceId(), + () -> activationRepository.activateProtected(protection, held))) .isInstanceOfSatisfying( TransientDataAccessResourceException.class, failure -> assertSuppressedTerminalReadbackFailure(failure)); } else { - assertThatThrownBy( - () -> - world - .installationRegistry() - .withLaunchOwners( - activationRequest.canonicalGameInstanceId(), - () -> activationRepository.activateProtected(protection, held))) + assertThatThrownBy(() -> + world + .installationRegistry() + .withLaunchOwners( + activationRequest.canonicalGameInstanceId(), + () -> activationRepository.activateProtected(protection, held))) .isInstanceOfSatisfying( IllegalStateException.class, failure -> { @@ -2194,36 +2186,34 @@ private static void assertAbortedHoldStored( CountDownLatch acquisitionStarted = new CountDownLatch(1); Future acquiring = - workers.submit( - () -> { - acquisitionStarted.countDown(); - return acquisition.call(); - }); + workers.submit(() -> { + acquisitionStarted.countDown(); + return acquisition.call(); + }); assertThat(acquisitionStarted.await(5, TimeUnit.SECONDS)).isTrue(); int acquisitionPid = awaitAcquisitionBlockedBy(world.dsl(), gatePid, acquiring); CountDownLatch transitionStarted = new CountDownLatch(1); AtomicInteger transitionPid = new AtomicInteger(); Future transitioning = - workers.submit( - () -> { - try (Connection transition = source.getConnection()) { - transition.setAutoCommit(true); - DSLContext transitionSql = DSL.using(transition, SQLDialect.POSTGRES); - transitionPid.set( - transitionSql.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); - transitionStarted.countDown(); - transitionSql.execute( - "UPDATE world_instance SET status='TERMINATING', " - + "lifecycle_epoch=lifecycle_epoch+1,row_version=row_version+1 " - + "WHERE id=? AND status='ACTIVE' AND lifecycle_epoch=?", - association.worldInstanceId(), - request.activeLifecycleEpoch()); - return "COMMITTED"; - } catch (Throwable failure) { - return sqlState(failure); - } - }); + workers.submit(() -> { + try (Connection transition = source.getConnection()) { + transition.setAutoCommit(true); + DSLContext transitionSql = DSL.using(transition, SQLDialect.POSTGRES); + transitionPid.set( + transitionSql.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + transitionStarted.countDown(); + transitionSql.execute( + "UPDATE world_instance SET status='TERMINATING', " + + "lifecycle_epoch=lifecycle_epoch+1,row_version=row_version+1 " + + "WHERE id=? AND status='ACTIVE' AND lifecycle_epoch=?", + association.worldInstanceId(), + request.activeLifecycleEpoch()); + return "COMMITTED"; + } catch (Throwable failure) { + return sqlState(failure); + } + }); assertThat(transitionStarted.await(5, TimeUnit.SECONDS)).isTrue(); awaitTransitionQueuedBehindAcquisition( world.dsl(), gatePid, acquisitionPid, transitionPid.get(), acquiring, transitioning); @@ -2412,24 +2402,21 @@ private static String accountRowSnapshot(DSLContext accountSql, UUID accountUuid private static void assertAccountSourceWriteBlockedWhileAdmissionPending( DSLContext accountSql, UUID accountUuid, String passwordBeforeWrite) { - assertThatThrownBy( - () -> - new TransactionTemplate(accountManager(accountSql)) - .executeWithoutResult( - ignored -> - updateAccountPasswordThroughOwner( - accountSql, accountUuid, passwordBeforeWrite + "-blocked"))) - .satisfies( - failure -> { - SQLException sqlFailure = - Objects.requireNonNull( - findSqlException(failure), "Account source writer SQLException required"); - assertThat(sqlFailure.getSQLState()).isEqualTo("55P03"); - assertThat(sqlFailure.getMessage()) - .contains( - "Original StartSession admission protection remains pending for a required " - + "source"); - }); + assertThatThrownBy(() -> + new TransactionTemplate(accountManager(accountSql)) + .executeWithoutResult(ignored -> + updateAccountPasswordThroughOwner( + accountSql, accountUuid, passwordBeforeWrite + "-blocked"))) + .satisfies(failure -> { + SQLException sqlFailure = + Objects.requireNonNull( + findSqlException(failure), "Account source writer SQLException required"); + assertThat(sqlFailure.getSQLState()).isEqualTo("55P03"); + assertThat(sqlFailure.getMessage()) + .contains( + "Original StartSession admission protection remains pending for a required " + + "source"); + }); } private static void assertNoCanonicalAdmissionPointerArtifacts( @@ -2523,9 +2510,8 @@ private static void exerciseCoupledCanonicalInitialAdmission( var reservedIntent = Objects.requireNonNull( gs.write() - .execute( - ignored -> - intentRepository.reserveHumanStarting(holdRequest, lifecycleRequest)), + .execute(ignored -> + intentRepository.reserveHumanStarting(holdRequest, lifecycleRequest)), "Human STARTING intent reservation returned no readback"); assertThat(reservedIntent.state()) .isEqualTo(CanonicalInitialAdmissionIntentSnapshot.IntentState.PENDING_HOLD); @@ -2558,9 +2544,8 @@ private static void exerciseCoupledCanonicalInitialAdmission( var replayedIntent = Objects.requireNonNull( gs.write() - .execute( - ignored -> - intentRepository.reserveHumanStarting(holdRequest, lifecycleRequest)), + .execute(ignored -> + intentRepository.reserveHumanStarting(holdRequest, lifecycleRequest)), "Exact Human STARTING intent retry returned no readback"); assertThat(replayedIntent.holdIdentity().canonicalBytes()) .containsExactly(identity.canonicalBytes()); @@ -2593,17 +2578,15 @@ private static void exerciseCoupledCanonicalInitialAdmission( "coupled-conflicting-admission-" + UUID.randomUUID()); assertThatThrownBy(() -> worldHoldClient.acquire(conflictingRequest, lifecycleRequest)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.ALREADY_EXISTS)); + .satisfies(failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.ALREADY_EXISTS)); var mismatchedRequest = withChangedDigest(holdRequest); assertThatThrownBy(() -> worldHoldClient.acquire(mismatchedRequest, lifecycleRequest)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); var protectionRequest = AccountStartSessionAdmissionProtectionRequest.create( @@ -2710,12 +2693,10 @@ private static void exerciseCoupledCanonicalInitialAdmission( var accountSources = accountProtection.sourceEvidenceVector().stream() .filter(source -> source.kind().name().equals("ACCOUNT")) - .filter( - source -> - source - .scopeId() - .equals( - originalTuple.preAuthorizationTuple().actor().accountId().toString())) + .filter(source -> + source + .scopeId() + .equals(originalTuple.preAuthorizationTuple().actor().accountId().toString())) .toList(); assertThat(accountSources).hasSize(1); var accountSource = accountSources.get(0); @@ -2776,10 +2757,9 @@ private static void exerciseCoupledCanonicalInitialAdmission( var request = canonicalAdmissionRequest(identity); gs.write() - .executeWithoutResult( - ignored -> - admissionOwner.reserveProtectedStartingForRuntimeCompletion( - request, accountProtection)); + .executeWithoutResult(ignored -> + admissionOwner.reserveProtectedStartingForRuntimeCompletion( + request, accountProtection)); var pending = admissionOwner.read(NAMESPACE, request.initialAdmissionRequestId()).orElseThrow(); assertThat(pending.outcome()).isEqualTo(CanonicalInitialAdmissionOwnerProof.Outcome.PENDING); @@ -2803,13 +2783,11 @@ private static void exerciseCoupledCanonicalInitialAdmission( assertThat(aborted.provesCommit()).isFalse(); assertThat(aborted.holdId()).isEqualTo(identity.holdId()); assertThat(aborted.holdFence()).isEqualTo(identity.holdFence()); - assertThatThrownBy( - () -> - gs.write() - .executeWithoutResult( - ignored -> - admissionOwner.commitProtected( - request, accountProtection, pendingWorldProof))) + assertThatThrownBy(() -> + gs.write() + .executeWithoutResult(ignored -> + admissionOwner.commitProtected( + request, accountProtection, pendingWorldProof))) .isInstanceOf( CanonicalInitialAdmissionRepository.CanonicalInitialAdmissionConflictException .class) @@ -2856,12 +2834,11 @@ private static void exerciseCoupledCanonicalInitialAdmission( var releasedAccount = Objects.requireNonNull( new TransactionTemplate(accountManager(issuer.sourceDsl())) - .execute( - ignored -> - updateAccountPasswordThroughOwner( - issuer.sourceDsl(), - accountUuid, - accountPasswordBeforeSourceWrite + "-aborted")), + .execute(ignored -> + updateAccountPasswordThroughOwner( + issuer.sourceDsl(), + accountUuid, + accountPasswordBeforeSourceWrite + "-aborted")), "Settled Account owner update readback required"); assertThat(releasedAccount.getAccountUuid()).isEqualTo(accountUuid); assertThat( @@ -2891,18 +2868,16 @@ private static void exerciseCoupledCanonicalInitialAdmission( var completion = Objects.requireNonNull( gs.write() - .execute( - ignored -> - completionRepository.completeProtected( - request, accountProtection, worldProof)), + .execute(ignored -> + completionRepository.completeProtected( + request, accountProtection, worldProof)), "Protected Human runtime completion returned no receipt"); var completionReplay = Objects.requireNonNull( gs.write() - .execute( - ignored -> - completionRepository.completeProtected( - request, accountProtection, worldProof)), + .execute(ignored -> + completionRepository.completeProtected( + request, accountProtection, worldProof)), "Exact Human runtime completion retry returned no receipt"); assertThat(completionReplay).isEqualTo(completion); var running = @@ -3020,10 +2995,9 @@ private static void exerciseCoupledCanonicalInitialAdmission( var releasedAccount = Objects.requireNonNull( new TransactionTemplate(accountManager(issuer.sourceDsl())) - .execute( - ignored -> - updateAccountPasswordThroughOwner( - issuer.sourceDsl(), accountUuid, settledAccountPassword)), + .execute(ignored -> + updateAccountPasswordThroughOwner( + issuer.sourceDsl(), accountUuid, settledAccountPassword)), "Settled Account owner update readback required"); assertThat(releasedAccount.getAccountUuid()).isEqualTo(accountUuid); String accountPasswordAfterSettlement = @@ -3095,22 +3069,20 @@ private static void assertAccountAdmissionProtectionSettled( var accountSettlement = Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, gameSessionPeer) - .call( - () -> - accountSettlementOwner.settle( - accountProtection.accountProtectionId(), - accountProtection.accountProtectionFence())); + .call(() -> + accountSettlementOwner.settle( + accountProtection.accountProtectionId(), + accountProtection.accountProtectionFence())); assertThat(accountSettlement.protection().canonicalBytes()) .containsExactly(accountProtection.canonicalBytes()); assertThat(accountSettlement.terminal()).isEqualTo(expectedTerminal); var accountSettlementReplay = Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, gameSessionPeer) - .call( - () -> - accountSettlementOwner.settle( - accountProtection.accountProtectionId(), - accountProtection.accountProtectionFence())); + .call(() -> + accountSettlementOwner.settle( + accountProtection.accountProtectionId(), + accountProtection.accountProtectionFence())); assertThat(accountSettlementReplay.canonicalBytes()) .containsExactly(accountSettlement.canonicalBytes()); var storedSettlement = @@ -3416,17 +3388,14 @@ private static void composeActualEntityWorldRegionPrerequisite( ManagedChannel worldPeerChannel = entityChannel(entityPki, "world-management-client", entityServer.getPort()); try { - assertThatThrownBy( - () -> - CanonicalPreseededActorAssignmentServiceGrpc.newBlockingStub( - worldPeerChannel) - .withDeadlineAfter(10, TimeUnit.SECONDS) - .readPreseededActorRuntimeReference(runtimeReferenceSelector)) + assertThatThrownBy(() -> + CanonicalPreseededActorAssignmentServiceGrpc.newBlockingStub(worldPeerChannel) + .withDeadlineAfter(10, TimeUnit.SECONDS) + .readPreseededActorRuntimeReference(runtimeReferenceSelector)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(((StatusRuntimeException) failure).getStatus().getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(((StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } finally { shutdown(worldPeerChannel); } @@ -4316,32 +4285,29 @@ private static WorldCanonicalInstancePreparation.Input preparationInputs( Objects.requireNonNull( world .write() - .execute( - s -> { - attemptCreatedInTransaction.set(false); - var attempt = - fence.claimFreeze( - freeze, - () -> { - var captured = checkpointRepository.captureWithSource(freeze, plan); - capturedCheckpoint.set(captured); - attemptCreatedInTransaction.set(true); - return captured.checkpoint(); - }); - var retained = - authorizationRepository.retainOrRequireExact( - attempt, - publicationAccountBinding, - attemptCreatedInTransaction.get()); - assertThat(retained.canonicalBytes()) - .containsExactly(publicationAccountBinding.canonicalBytes()); - inventoryRepository.retainOrRequireExact( - attempt, - retained, - attemptCreatedInTransaction.get(), - capturedCheckpoint.get()); - return attempt; - })); + .execute(s -> { + attemptCreatedInTransaction.set(false); + var attempt = + fence.claimFreeze( + freeze, + () -> { + var captured = checkpointRepository.captureWithSource(freeze, plan); + capturedCheckpoint.set(captured); + attemptCreatedInTransaction.set(true); + return captured.checkpoint(); + }); + var retained = + authorizationRepository.retainOrRequireExact( + attempt, publicationAccountBinding, attemptCreatedInTransaction.get()); + assertThat(retained.canonicalBytes()) + .containsExactly(publicationAccountBinding.canonicalBytes()); + inventoryRepository.retainOrRequireExact( + attempt, + retained, + attemptCreatedInTransaction.get(), + capturedCheckpoint.get()); + return attempt; + })); assertThat(authorizationRepository.readCommitted(frozenAttempt).orElseThrow().canonicalBytes()) .containsExactly(publicationAccountBinding.canonicalBytes()); var freezeRequest = @@ -4373,15 +4339,14 @@ private static WorldCanonicalInstancePreparation.Input preparationInputs( .readRetained(freezeEvidence); var tuples = plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) + .map(unit -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) .toList(); var captureRequest = new WorldAuthoredGraphSnapshot.CaptureRequest( @@ -4422,15 +4387,13 @@ private static WorldCanonicalInstancePreparation.Input preparationInputs( var gsTenant = Objects.requireNonNull( gs.write() - .execute( - s -> - new GameSessionFreshTenantAssociationRepository(gs.dsl()) - .associateFresh( - UUID.randomUUID(), - NAMESPACE, - gsReceipt, - CanonicalHumanPublicationOwnerTestFixtures.creationEvidence( - source)))); + .execute(s -> + new GameSessionFreshTenantAssociationRepository(gs.dsl()) + .associateFresh( + UUID.randomUUID(), + NAMESPACE, + gsReceipt, + CanonicalHumanPublicationOwnerTestFixtures.creationEvidence(source)))); var catalogRequest = new CreateCanonicalRealmCatalogRequest( UUID.randomUUID(), @@ -4503,16 +4466,15 @@ private static WorldCanonicalInstancePreparation.Input preparationInputs( var starting = Objects.requireNonNull( gs.write() - .execute( - s -> - new GameSessionCanonicalStartingInstanceRepository(gs.dsl(), NAMESPACE) - .createStarting( - gsTenant, - complete, - tuple.preAuthorizationTuple().action().target().ownerAccountId(), - tuple.controlPlaneRequestId(), - tuple.mutationDigest(), - tuple))); + .execute(s -> + new GameSessionCanonicalStartingInstanceRepository(gs.dsl(), NAMESPACE) + .createStarting( + gsTenant, + complete, + tuple.preAuthorizationTuple().action().target().ownerAccountId(), + tuple.controlPlaneRequestId(), + tuple.mutationDigest(), + tuple))); var request = new CanonicalGameInstanceLaunchAssociationReadEvidence.Request( UUID.randomUUID(), @@ -4571,10 +4533,9 @@ private static WorldCanonicalInstancePreparation.Input preparationInputs( Objects.requireNonNull( world .write() - .execute( - s -> - new WorldCompleteLaunchBindingRepository(world.dsl()) - .acceptFresh(NAMESPACE, intake, complete))); + .execute(s -> + new WorldCompleteLaunchBindingRepository(world.dsl()) + .acceptFresh(NAMESPACE, intake, complete))); return new WorldCanonicalInstancePreparation.Input( readRequest, readEvidence, @@ -4599,21 +4560,20 @@ private static AuthoredDraftPublishSelectionBinding selection( DraftCommitBinding draft, byte[] appliedBytes, String publicationId) throws Exception { var epochs = draft.affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - Map.of( - "aggregateType", - unit.aggregateType(), - "aggregateId", - unit.aggregateId(), - "scopeType", - unit.scopeType(), - "scopeId", - unit.scopeId(), - "expectedEpoch", - unit.expectedEpoch(), - "resultingEpoch", - new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .map(unit -> + Map.of( + "aggregateType", + unit.aggregateType(), + "aggregateId", + unit.aggregateId(), + "scopeType", + unit.scopeType(), + "scopeId", + unit.scopeId(), + "expectedEpoch", + unit.expectedEpoch(), + "resultingEpoch", + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) .toList(); String vector = new String( @@ -5498,15 +5458,14 @@ private static WorldPublishedStartLocationEvidence publishedStartLocationEvidenc var freeze = source.frozenTopology().request().freeze(); var tuples = freeze.suppliedOwnedAffectedTuples().stream() - .map( - tuple -> - new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( - tuple.owner(), - tuple.aggregateType(), - tuple.aggregateId(), - tuple.scopeType(), - tuple.scopeId(), - tuple.expectedEpoch())) + .map(tuple -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) .toList(); var request = new WorldPublishedStartLocationEvidence.Request( @@ -5602,23 +5561,21 @@ private static RealmPolicyPublishedEvidence.PublishedSet publishedSet( var capture = new RealmPolicySnapshot(draft, "1", List.of(policySource)); var participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new GameDesignPublicationTerminalEvidence.Participant( + .map(owner -> + new GameDesignPublicationTerminalEvidence.Participant( + owner, + Long.toString(versionRowId), + null, + draft.commitId().toString(), + "WORLD_MANAGEMENT".equals(owner) + ? world.request().contentDigest() + : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( owner, - Long.toString(versionRowId), - null, - draft.commitId().toString(), - "WORLD_MANAGEMENT".equals(owner) - ? world.request().contentDigest() - : "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, - AuthoredWorldReleaseAttestationEvidence - .CLOSURE_SELECTOR_SCHEMA_VERSION), - "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, - null, - null)) + AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, + null, + null)) .toList(); var release = new GameDesignPublicationTerminalEvidence.ReleaseContent( @@ -5710,29 +5667,28 @@ private static AccountPublicationAuthorizationBinding publicationAccountBinding( new AccountPublicationAuthorizationBinding.PreallocationInput( original.actorAccountId(), selected), Arrays.stream(SourceKind.values()) - .flatMap( - kind -> { - if (kind == SourceKind.RECENT_REAUTH_POLICY) { - return java.util.stream.Stream.of( - recentReauthenticationPolicyEvidence("PLATFORM", 300L, 30L), - recentReauthenticationPolicyEvidence("DEPLOYMENT", 240L, 30L)); - } - return java.util.stream.Stream.of( - new SourceEvidence( - kind, - switch (kind) { - case ACCOUNT, GLOBAL_ROLES -> original.actorAccountId().toString(); - case TENANT -> source.canonicalTenantId().toString(); - case MEMBERSHIP -> - original.actorAccountId() + "/" + source.canonicalTenantId(); - default -> "TEST_ONLY-" + kind; - }, - "1", - "1", - null, - null, - ("TEST_ONLY-" + kind).getBytes(StandardCharsets.UTF_8))); - }) + .flatMap(kind -> { + if (kind == SourceKind.RECENT_REAUTH_POLICY) { + return java.util.stream.Stream.of( + recentReauthenticationPolicyEvidence("PLATFORM", 300L, 30L), + recentReauthenticationPolicyEvidence("DEPLOYMENT", 240L, 30L)); + } + return java.util.stream.Stream.of( + new SourceEvidence( + kind, + switch (kind) { + case ACCOUNT, GLOBAL_ROLES -> original.actorAccountId().toString(); + case TENANT -> source.canonicalTenantId().toString(); + case MEMBERSHIP -> + original.actorAccountId() + "/" + source.canonicalTenantId(); + default -> "TEST_ONLY-" + kind; + }, + "1", + "1", + null, + null, + ("TEST_ONLY-" + kind).getBytes(StandardCharsets.UTF_8))); + }) .toList()); } @@ -5823,19 +5779,18 @@ public void close() { var release = terminal.releaseContent(); var participants = release.participantDigests().stream() - .map( - participant -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - participant.participantKey(), - Long.toString(descriptor.versionId()), - false, - null, - publishedSet.sourceCommitId().toString(), - participant.contentDigest(), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - participant.participantKey(), 3), - participant.abilitySchemaDigest() != null, - participant.abilitySchemaDigest())) + .map(participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + Long.toString(descriptor.versionId()), + false, + null, + publishedSet.sourceCommitId().toString(), + participant.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participant.participantKey(), 3), + participant.abilitySchemaDigest() != null, + participant.abilitySchemaDigest())) .toList(); var evidence = AuthoredWorldReleaseAttestationEvidence.createClosureSelector( @@ -5936,19 +5891,18 @@ private static void pinLaunch( .setCanonicalVersionId(publishedSet.target().canonicalVersionId().toString()); release .participantDigests() - .forEach( - participant -> { - var item = - net.firedevops.firemud.gamedesign.v1.ParticipantDigest.newBuilder() - .setParticipantKey(participant.participantKey()) - .setScopeValue(participant.scopeValue()) - .setAppliedCommitId(participant.appliedCommitId()) - .setContentDigest(participant.contentDigest()) - .setDigestSchemaVersion(participant.digestSchemaVersion()); - if (participant.abilitySchemaDigest() != null) - item.setAbilitySchemaDigest(participant.abilitySchemaDigest()); - proto.addParticipantDigests(item); - }); + .forEach(participant -> { + var item = + net.firedevops.firemud.gamedesign.v1.ParticipantDigest.newBuilder() + .setParticipantKey(participant.participantKey()) + .setScopeValue(participant.scopeValue()) + .setAppliedCommitId(participant.appliedCommitId()) + .setContentDigest(participant.contentDigest()) + .setDigestSchemaVersion(participant.digestSchemaVersion()); + if (participant.abilitySchemaDigest() != null) + item.setAbilitySchemaDigest(participant.abilitySchemaDigest()); + proto.addParticipantDigests(item); + }); var initialRequest = new net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence .Request( diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java index 893cfbbd9d..36d0ba7239 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPlayerAdmissionEntitlementComposition.java @@ -219,18 +219,16 @@ static void exercise( fixture.assertAdmittingEvidence(joined); var journal = new InitialGameplayLoginCoordinationJournalRepository(gs); var beforeCustodyRefusal = journal.readCommitted(coordinates).orElseThrow(); - assertThatThrownBy( - () -> - entitlementClient.read( - lobby, coordinates, transport, UUID.randomUUID(), login, () -> false)) + assertThatThrownBy(() -> + entitlementClient.read( + lobby, coordinates, transport, UUID.randomUUID(), login, () -> false)) .isExactlyInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - var status = ((StatusRuntimeException) failure).getStatus(); - assertThat(status.getCode()).isEqualTo(Status.Code.CANCELLED); - assertThat(status.getDescription()) - .isEqualTo("Account player-admission entitlement read did not complete"); - }); + .satisfies(failure -> { + var status = ((StatusRuntimeException) failure).getStatus(); + assertThat(status.getCode()).isEqualTo(Status.Code.CANCELLED); + assertThat(status.getDescription()) + .isEqualTo("Account player-admission entitlement read did not complete"); + }); fixture.assertAdmittingEvidence(joined); assertThat(login.evidence()).isEqualTo(evidence); assertThat(journal.readCommitted(coordinates)).contains(beforeCustodyRefusal); @@ -241,10 +239,9 @@ static void exercise( var beforeClosedResultRefusal = journal.readCommitted(coordinates).orElseThrow(); // Cleanup has closed the private result. This proves local disposal refusal, // not an Account-side retired-token read over the wire. - assertThatThrownBy( - () -> - entitlementClient.read( - lobby, coordinates, transport, UUID.randomUUID(), login, () -> true)) + assertThatThrownBy(() -> + entitlementClient.read( + lobby, coordinates, transport, UUID.randomUUID(), login, () -> true)) .isExactlyInstanceOf(IllegalStateException.class) .hasMessage("Canonical LOGIN private result is closed"); fixture.assertAdmittingEvidence(joined); diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceCleanupTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceCleanupTest.java index 836920793e..332d191c30 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceCleanupTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceCleanupTest.java @@ -17,13 +17,12 @@ void successfulBodyStopsServerAndChecksLatePeerDiagnostic() throws Exception { var server = stoppedServer(); var peer = new AtomicReference(); Throwable result = - catchThrowable( - () -> { - try (var peerCheck = WorldPublishedAdmissionSourceComposition.checkPeerOnClose(peer); - var lifetime = WorldPublishedAdmissionSourceComposition.stopOnClose(server)) { - peer.set("wrong authenticated peer"); - } - }); + catchThrowable(() -> { + try (var peerCheck = WorldPublishedAdmissionSourceComposition.checkPeerOnClose(peer); + var lifetime = WorldPublishedAdmissionSourceComposition.stopOnClose(server)) { + peer.set("wrong authenticated peer"); + } + }); assertThat(result) .isInstanceOf(AssertionError.class) @@ -99,14 +98,13 @@ private static Server stoppedServer() throws InterruptedException { private static Throwable run(Server server, String peerFailure, AssertionError primary) { var peer = new AtomicReference<>(peerFailure); - return catchThrowable( - () -> { - try (var peerCheck = WorldPublishedAdmissionSourceComposition.checkPeerOnClose(peer); - var lifetime = WorldPublishedAdmissionSourceComposition.stopOnClose(server)) { - if (primary != null) { - throw primary; - } - } - }); + return catchThrowable(() -> { + try (var peerCheck = WorldPublishedAdmissionSourceComposition.checkPeerOnClose(peer); + var lifetime = WorldPublishedAdmissionSourceComposition.stopOnClose(server)) { + if (primary != null) { + throw primary; + } + } + }); } } diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java index ed12365736..db6a0c3921 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedAdmissionSourceComposition.java @@ -101,15 +101,14 @@ static void exercise( publication.policyCount(), publication.policySetDigest(), publication.policies().stream() - .map( - p -> - new PublishedRealmEntryPolicyEvidence( - p.policyId(), - p.source().commitId(), - p.source().revisionId(), - p.source().logicalRevisionId(), - p.source().policy(), - p.policyDigest())) + .map(p -> + new PublishedRealmEntryPolicyEvidence( + p.policyId(), + p.source().commitId(), + p.source().revisionId(), + p.source().logicalRevisionId(), + p.source().policy(), + p.policyDigest())) .toList()); // This is the sole stipulated source: the exact published set already used by the real // preparation/OPEN owners. No Game Design issuing-owner proof is claimed here. @@ -215,13 +214,12 @@ public void listPublishedRealmEntryPolicies( target.pointerVersion()); assertThatThrownBy(() -> accountClient.resolvePublishedRealmAdmissionTarget(wrong)) .isExactlyInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> { - var status = ((StatusRuntimeException) failure).getStatus(); - assertThat(status.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); - assertThat(status.getDescription()) - .isEqualTo("Canonical Game Session admission decision is unavailable"); - }); + .satisfies(failure -> { + var status = ((StatusRuntimeException) failure).getStatus(); + assertThat(status.getCode()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(status.getDescription()) + .isEqualTo("Canonical Game Session admission decision is unavailable"); + }); var afterRefusal = accountClient.resolvePublishedRealmAdmissionTarget(selector); assertThat(afterRefusal.selector()).isEqualTo(resolved.selector()); assertThat(afterRefusal.currentTarget()).isEqualTo(resolved.currentTarget()); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java index cf21bef94c..2125b61722 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java @@ -93,42 +93,39 @@ void holdAcquireWinsConcurrentTerminationAndExactRetrySurvivesServiceRecreation( try (ExecutorService executor = Executors.newFixedThreadPool(2)) { Future acquireFuture = - executor.submit( - () -> - transactionTemplate.execute( - status -> { - worldInstanceRepository - .findByTenantIdAndGameInstanceIdForUpdate(tenantId, gameInstanceId) - .orElseThrow(); - Record backendIdentity = - Objects.requireNonNull( - dsl.fetchOne("SELECT pg_backend_pid()"), - "PostgreSQL backend PID query returned no row"); - acquisitionBackendPid.set( - Objects.requireNonNull( - backendIdentity.get(0, Integer.class), - "PostgreSQL backend PID query returned a null PID")); - lifecycleLocked.countDown(); - await(allowAcquireCommit); - return holdService.acquire(request); - })); + executor.submit(() -> + transactionTemplate.execute(status -> { + worldInstanceRepository + .findByTenantIdAndGameInstanceIdForUpdate(tenantId, gameInstanceId) + .orElseThrow(); + Record backendIdentity = + Objects.requireNonNull( + dsl.fetchOne("SELECT pg_backend_pid()"), + "PostgreSQL backend PID query returned no row"); + acquisitionBackendPid.set( + Objects.requireNonNull( + backendIdentity.get(0, Integer.class), + "PostgreSQL backend PID query returned a null PID")); + lifecycleLocked.countDown(); + await(allowAcquireCommit); + return holdService.acquire(request); + })); assertThat(lifecycleLocked.await(5, TimeUnit.SECONDS)).isTrue(); int exactAcquisitionBackendPid = acquisitionBackendPid.get(); assertThat(exactAcquisitionBackendPid).isPositive(); CountDownLatch terminationStarted = new CountDownLatch(1); Future terminationFuture = - executor.submit( - () -> { - terminationStarted.countDown(); - try { - lifecycleCommandService.terminateWorldInstance( - tenantId, gameInstanceId, 4L, "terminate-race-1", "race"); - return "unexpected termination success"; - } catch (IllegalArgumentException exception) { - return exception.getMessage(); - } - }); + executor.submit(() -> { + terminationStarted.countDown(); + try { + lifecycleCommandService.terminateWorldInstance( + tenantId, gameInstanceId, 4L, "terminate-race-1", "race"); + return "unexpected termination success"; + } catch (IllegalArgumentException exception) { + return exception.getMessage(); + } + }); assertThat(terminationStarted.await(5, TimeUnit.SECONDS)).isTrue(); int terminationBackendPid = awaitBackendBlockedBy(exactAcquisitionBackendPid); assertThat(isBackendBlockedBy(terminationBackendPid, exactAcquisitionBackendPid)).isTrue(); @@ -175,10 +172,9 @@ void terminationWinsRaceAndLaterAcquireCannotCreateAnInitialHold() throws Except try (ExecutorService executor = Executors.newSingleThreadExecutor()) { Future termination = - executor.submit( - () -> - lifecycleCommandService.terminateWorldInstance( - tenantId, gameInstanceId, 4L, "terminate-race-2", "race")); + executor.submit(() -> + lifecycleCommandService.terminateWorldInstance( + tenantId, gameInstanceId, 4L, "terminate-race-2", "race")); assertThat(ownerCleanupCalled.await(5, TimeUnit.SECONDS)).isTrue(); assertThatThrownBy(() -> holdService.acquire(request(tenantId, gameInstanceId))) @@ -201,10 +197,9 @@ void reconciliationRequiredHoldContinuesToBlockTermination() { var acquired = holdService.acquire(request(tenantId, gameInstanceId)); holdService.requireReconciliation(acquired.holdId(), "GS_OWNER_READ_UNAVAILABLE"); - assertThatThrownBy( - () -> - lifecycleCommandService.terminateWorldInstance( - tenantId, gameInstanceId, 4L, "terminate-held-1", "stop")) + assertThatThrownBy(() -> + lifecycleCommandService.terminateWorldInstance( + tenantId, gameInstanceId, 4L, "terminate-held-1", "stop")) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("INITIAL_ADMISSION_BIND_HOLD_ACTIVE:"); } finally { diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java index b370c30aa9..2c35cfbf2a 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java @@ -411,15 +411,14 @@ public void terminateWorldInstance( gameSessionChannel.shutdownNow(); assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); gameSessionChannel = channelWithoutClientIdentity("localhost", worldServer.getPort()); - assertThatThrownBy( - () -> - authenticatedGameSessionStub() - .activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(1L) - .build())) + assertThatThrownBy(() -> + authenticatedGameSessionStub() + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build())) .isInstanceOf(StatusRuntimeException.class); assertThat(worldSaves).hasValue(writesAfterActivation); assertThat(descriptorReads).hasValue(4); @@ -460,15 +459,14 @@ public void terminateWorldInstance( assertThat(gameSessionChannel.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); gameSessionChannel = channel("localhost", worldServer.getPort(), pki.wrongCaGameSessionClient()); - assertThatThrownBy( - () -> - authenticatedGameSessionStub() - .activatePreparedWorldInstance( - ActivatePreparedWorldInstanceRequest.newBuilder() - .setTenantId("42") - .setGameInstanceId("101") - .setExpectedLifecycleEpoch(1L) - .build())) + assertThatThrownBy(() -> + authenticatedGameSessionStub() + .activatePreparedWorldInstance( + ActivatePreparedWorldInstanceRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setExpectedLifecycleEpoch(1L) + .build())) .isInstanceOf(StatusRuntimeException.class); assertThat(worldSaves).hasValue(writesAfterActivation); assertThat(descriptorReads).hasValue(4); @@ -751,9 +749,8 @@ void gameDesignTransportRejectsMissingAndWrongJwtBeforeHandlerRead() throws Exce gameSessionChannel = channel("localhost", gameDesignServer.getPort(), pki.worldManagement()); var missingJwtStub = GameDesignServiceGrpc.newBlockingStub(gameSessionChannel); - assertThatThrownBy( - () -> - missingJwtStub.getLaunchDescriptor(GetLaunchDescriptorRequest.getDefaultInstance())) + assertThatThrownBy(() -> + missingJwtStub.getLaunchDescriptor(GetLaunchDescriptorRequest.getDefaultInstance())) .isInstanceOfSatisfying( StatusRuntimeException.class, failure -> @@ -937,47 +934,43 @@ private WorldInstanceRepository mockWorldRepository( AtomicReference storedWorld, AtomicInteger worldSaves) { WorldInstanceRepository repository = mock(WorldInstanceRepository.class); when(repository.findByTenantIdAndGameInstanceId(anyLong(), anyLong())) - .thenAnswer( - invocation -> { - WorldInstance instance = storedWorld.get(); - return instance != null - && instance.getTenantId().equals(invocation.getArgument(0)) - && instance.getGameInstanceId().equals(invocation.getArgument(1)) - ? java.util.Optional.of(instance) - : java.util.Optional.empty(); - }); + .thenAnswer(invocation -> { + WorldInstance instance = storedWorld.get(); + return instance != null + && instance.getTenantId().equals(invocation.getArgument(0)) + && instance.getGameInstanceId().equals(invocation.getArgument(1)) + ? java.util.Optional.of(instance) + : java.util.Optional.empty(); + }); when(repository.findByTenantIdAndGameInstanceIdForUpdate(anyLong(), anyLong())) - .thenAnswer( - invocation -> { - WorldInstance instance = storedWorld.get(); - return instance != null - && instance.getTenantId().equals(invocation.getArgument(0)) - && instance.getGameInstanceId().equals(invocation.getArgument(1)) - ? java.util.Optional.of(instance) - : java.util.Optional.empty(); - }); + .thenAnswer(invocation -> { + WorldInstance instance = storedWorld.get(); + return instance != null + && instance.getTenantId().equals(invocation.getArgument(0)) + && instance.getGameInstanceId().equals(invocation.getArgument(1)) + ? java.util.Optional.of(instance) + : java.util.Optional.empty(); + }); when(repository.findRunOwnedFixtureByTenantIdAndControlPlaneRequestIdForUpdate( anyLong(), any(String.class))) - .thenAnswer( - invocation -> { - WorldInstance instance = storedWorld.get(); - return instance != null - && instance.getTenantId().equals(invocation.getArgument(0)) - && instance.getControlPlaneRequestId().equals(invocation.getArgument(1)) - ? java.util.Optional.of(instance) - : java.util.Optional.empty(); - }); + .thenAnswer(invocation -> { + WorldInstance instance = storedWorld.get(); + return instance != null + && instance.getTenantId().equals(invocation.getArgument(0)) + && instance.getControlPlaneRequestId().equals(invocation.getArgument(1)) + ? java.util.Optional.of(instance) + : java.util.Optional.empty(); + }); when(repository.save(any(WorldInstance.class))) - .thenAnswer( - invocation -> { - WorldInstance instance = invocation.getArgument(0); - if (instance.getId() == null) { - instance.setId(101L); - } - worldSaves.incrementAndGet(); - storedWorld.set(instance); - return instance; - }); + .thenAnswer(invocation -> { + WorldInstance instance = invocation.getArgument(0); + if (instance.getId() == null) { + instance.setId(101L); + } + worldSaves.incrementAndGet(); + storedWorld.set(instance); + return instance; + }); return repository; } @@ -1006,11 +999,10 @@ private WorldLifecycleCommandServiceImpl newCommandService( .thenAnswer(invocation -> invocation.getArgument(0)); EntityManagementClient entityManagementClient = mock(EntityManagementClient.class); when(entityManagementClient.cleanupRuntimeInstance(anyLong(), anyLong(), anyString())) - .thenAnswer( - invocation -> { - entityCleanupCalls.incrementAndGet(); - return CleanupRuntimeInstanceResponse.newBuilder().build(); - }); + .thenAnswer(invocation -> { + entityCleanupCalls.incrementAndGet(); + return CleanupRuntimeInstanceResponse.newBuilder().build(); + }); WorldProperties properties = new WorldProperties(); properties.setLocalShardId(7); WorldLifecycleCommandServiceImpl commandService = @@ -1340,8 +1332,8 @@ private static RunOwnedInitialAdmissionFixtureWireCodec.Capability capability( private static String capabilityJson( RunOwnedInitialAdmissionFixtureWireCodec.Capability capability) { return """ - {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":%d,"gameTemplateId":%d,"ownerAccountId":%d,"worldSlug":"%s","worldDisplayName":"%s","realmSlug":"%s","realmDisplayName":"%s","visible":%s,"publicProductionRealm":%s,"requiresCharacterSelection":%s,"stateScope":"%s","characterCreationPolicy":"%s","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","claimDigest":"%s"}\ - """ + {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":%d,"gameTemplateId":%d,"ownerAccountId":%d,"worldSlug":"%s","worldDisplayName":"%s","realmSlug":"%s","realmDisplayName":"%s","visible":%s,"publicProductionRealm":%s,"requiresCharacterSelection":%s,"stateScope":"%s","characterCreationPolicy":"%s","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","claimDigest":"%s"}\ + """ .formatted( capability.schema(), capability.runId(), @@ -1409,8 +1401,8 @@ private static String receiptJson( TestPki pki) throws Exception { return """ - {"schema":"firemud.run-owned-authored-world-source-receipt.v1","runId":"%s","composeProjectName":"%s","fixtureOperationId":"%s","ownerService":"game-design-service","gameSessionUriSan":"%s","gameSessionLeafSha256":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","sourceEvidence":{"schemaVersion":1,"targetNamespace":"dev","registrationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","tenantSlug":"%s","worldSlug":"%s","worldDisplayName":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"launchReadEvidence":{"schema":"firemud.run-owned-v1-launch-read-evidence.v1","gameTemplateId":17,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"},"creationEvidence":{"schemaVersion":%d,"targetNamespace":"%s","creationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"fixturePolicySeal":{"schema":"%s","ownerService":"%s","operationId":"%s","requestDigest":"%s","evidenceDigest":"%s"}}\ - """ + {"schema":"firemud.run-owned-authored-world-source-receipt.v1","runId":"%s","composeProjectName":"%s","fixtureOperationId":"%s","ownerService":"game-design-service","gameSessionUriSan":"%s","gameSessionLeafSha256":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","sourceEvidence":{"schemaVersion":1,"targetNamespace":"dev","registrationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","tenantSlug":"%s","worldSlug":"%s","worldDisplayName":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"launchReadEvidence":{"schema":"firemud.run-owned-v1-launch-read-evidence.v1","gameTemplateId":17,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"},"creationEvidence":{"schemaVersion":%d,"targetNamespace":"%s","creationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"fixturePolicySeal":{"schema":"%s","ownerService":"%s","operationId":"%s","requestDigest":"%s","evidenceDigest":"%s"}}\ + """ .formatted( RUN_ID, PROJECT, diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java index 0abe780565..4b9bbe727f 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidencePostgresIntegrationTest.java @@ -172,10 +172,9 @@ void prepareActivationReplayRestartChangedReceiptAndDuplicateOperationUseDurable when(changedProvider.requireAuthenticatedEvidence()).thenReturn(changedEvidence); when(changedEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) .thenReturn("b".repeat(64)); - assertThatThrownBy( - () -> - restartedLifecycleService(new WorldInstanceRepository(dsl), changedProvider) - .activatePreparedWorldInstance(tenantId, gameInstanceId, 1L)) + assertThatThrownBy(() -> + restartedLifecycleService(new WorldInstanceRepository(dsl), changedProvider) + .activatePreparedWorldInstance(tenantId, gameInstanceId, 1L)) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH:"); assertThat( @@ -197,29 +196,26 @@ void prepareActivationReplayRestartChangedReceiptAndDuplicateOperationUseDurable verify(gameDesignClient, never()).getVersionState(anyLong(), anyLong()); verify(fixtureProvider, org.mockito.Mockito.atLeast(3)).requireAuthenticatedEvidence(); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE world_instance SET run_owned_fixture_preparing_lifecycle_epoch = 0 " - + "WHERE tenant_id = ? AND game_instance_id = ?", - tenantId, - gameInstanceId)) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE world_instance SET run_owned_fixture_preparing_lifecycle_epoch = 0 " + + "WHERE tenant_id = ? AND game_instance_id = ?", + tenantId, + gameInstanceId)) .isInstanceOf(RuntimeException.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE world_instance SET run_owned_fixture_preparing_lifecycle_epoch = NULL " - + "WHERE tenant_id = ? AND game_instance_id = ?", - tenantId, - gameInstanceId)) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE world_instance SET run_owned_fixture_preparing_lifecycle_epoch = NULL " + + "WHERE tenant_id = ? AND game_instance_id = ?", + tenantId, + gameInstanceId)) .isInstanceOf(RuntimeException.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE world_instance SET run_owned_fixture_binding_sha256 = NULL " - + "WHERE tenant_id = ? AND game_instance_id = ?", - tenantId, - gameInstanceId)) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE world_instance SET run_owned_fixture_binding_sha256 = NULL " + + "WHERE tenant_id = ? AND game_instance_id = ?", + tenantId, + gameInstanceId)) .isInstanceOf(RuntimeException.class); WorldInstance fixtureBeforeMetadataMutation = @@ -324,23 +320,19 @@ void operationAdvisoryLockSerializesConcurrentRetriesOnPostgres() throws Excepti CountDownLatch secondHasLock = new CountDownLatch(1); try (ExecutorService executor = Executors.newFixedThreadPool(2)) { Future first = - executor.submit( - () -> - transaction.executeWithoutResult( - status -> { - repository.lockRunOwnedFixtureOperation(tenantId, operation); - firstHasLock.countDown(); - await(releaseFirst); - })); + executor.submit(() -> + transaction.executeWithoutResult(status -> { + repository.lockRunOwnedFixtureOperation(tenantId, operation); + firstHasLock.countDown(); + await(releaseFirst); + })); assertThat(firstHasLock.await(5, TimeUnit.SECONDS)).isTrue(); Future second = - executor.submit( - () -> - transaction.executeWithoutResult( - status -> { - repository.lockRunOwnedFixtureOperation(tenantId, operation); - secondHasLock.countDown(); - })); + executor.submit(() -> + transaction.executeWithoutResult(status -> { + repository.lockRunOwnedFixtureOperation(tenantId, operation); + secondHasLock.countDown(); + })); assertThat(secondHasLock.await(200, TimeUnit.MILLISECONDS)).isFalse(); releaseFirst.countDown(); first.get(10, TimeUnit.SECONDS); @@ -368,10 +360,8 @@ void fixtureFailureRequiresExactOwnerAndPersistsTheLockedPredecessorTransition() when(fixtureEvidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) .thenReturn("d".repeat(64)); - assertThatThrownBy( - () -> - lifecycleService.failPreparedWorldInstance( - tenantId, gameInstanceId, 1L, "failed")) + assertThatThrownBy(() -> + lifecycleService.failPreparedWorldInstance(tenantId, gameInstanceId, 1L, "failed")) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("RUN_OWNED_WORLD_LAUNCH_EVIDENCE_MISMATCH:"); WorldInstance unchanged = @@ -408,13 +398,12 @@ void fixtureTerminationHonorsPhysicalHoldAndRetainsEntityCleanupFailureForExactR configureEvidence(binding); AtomicBoolean failEntityCleanup = new AtomicBoolean(true); when(entityManagementClient.cleanupRuntimeInstance(anyLong(), anyLong(), anyString())) - .thenAnswer( - invocation -> { - if (failEntityCleanup.getAndSet(false)) { - throw new IllegalStateException("Entity cleanup unavailable"); - } - return CleanupRuntimeInstanceResponse.newBuilder().build(); - }); + .thenAnswer(invocation -> { + if (failEntityCleanup.getAndSet(false)) { + throw new IllegalStateException("Entity cleanup unavailable"); + } + return CleanupRuntimeInstanceResponse.newBuilder().build(); + }); try { lifecycleService.prepareWorldInstance(request); var active = lifecycleService.activatePreparedWorldInstance(tenantId, gameInstanceId, 1L); @@ -441,10 +430,9 @@ void fixtureTerminationHonorsPhysicalHoldAndRetainsEntityCleanupFailureForExactR operationId(), "a".repeat(64)); - assertThatThrownBy( - () -> - lifecycleService.terminateWorldInstance( - tenantId, gameInstanceId, 2L, "term-fixture", "stop")) + assertThatThrownBy(() -> + lifecycleService.terminateWorldInstance( + tenantId, gameInstanceId, 2L, "term-fixture", "stop")) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("INITIAL_ADMISSION_BIND_HOLD_ACTIVE:"); WorldInstance held = @@ -456,10 +444,9 @@ void fixtureTerminationHonorsPhysicalHoldAndRetainsEntityCleanupFailureForExactR .cleanupRuntimeInstance(tenantId, gameInstanceId, "term-fixture"); dsl.execute("DELETE FROM initial_admission_bind_hold WHERE hold_id = ?", holdId); - assertThatThrownBy( - () -> - lifecycleService.terminateWorldInstance( - tenantId, gameInstanceId, 2L, "term-fixture", "stop")) + assertThatThrownBy(() -> + lifecycleService.terminateWorldInstance( + tenantId, gameInstanceId, 2L, "term-fixture", "stop")) .isInstanceOf(IllegalStateException.class) .hasMessage("Entity cleanup unavailable"); WorldInstance terminating = @@ -490,10 +477,9 @@ void fixtureTerminationHonorsPhysicalHoldAndRetainsEntityCleanupFailureForExactR .orElseThrow() .getRowVersion()) .isEqualTo(3L); - assertThatThrownBy( - () -> - lifecycleService.terminateWorldInstance( - tenantId, gameInstanceId, 2L, "term-other", "stop")) + assertThatThrownBy(() -> + lifecycleService.terminateWorldInstance( + tenantId, gameInstanceId, 2L, "term-other", "stop")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("terminated under a different request id"); verify(entityManagementClient, org.mockito.Mockito.times(2)) @@ -516,17 +502,15 @@ void ordinaryFailureJoinsAndRollsBackWithItsCallerTransaction() { assertThat(prepared.status()).isEqualTo("PREPARING"); TransactionTemplate callerTransaction = new TransactionTemplate(transactionManager); - assertThatThrownBy( - () -> - callerTransaction.executeWithoutResult( - status -> { - var failed = - lifecycleService.failPreparedWorldInstance( - tenantId, gameInstanceId, 1L, "caller will roll back"); - assertThat(failed.status()).isEqualTo("FAILED_PRE_ACTIVATION"); - assertThat(failed.lifecycleEpoch()).isEqualTo(2L); - throw new IllegalStateException("rollback ordinary caller"); - })) + assertThatThrownBy(() -> + callerTransaction.executeWithoutResult(status -> { + var failed = + lifecycleService.failPreparedWorldInstance( + tenantId, gameInstanceId, 1L, "caller will roll back"); + assertThat(failed.status()).isEqualTo("FAILED_PRE_ACTIVATION"); + assertThat(failed.lifecycleEpoch()).isEqualTo(2L); + throw new IllegalStateException("rollback ordinary caller"); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("rollback ordinary caller"); @@ -550,19 +534,17 @@ void concurrentPrepareRetriesCreateOneFixtureBoundWorldInstance() throws Excepti CountDownLatch start = new CountDownLatch(1); try (ExecutorService executor = Executors.newFixedThreadPool(2)) { Future first = - executor.submit( - () -> { - ready.countDown(); - await(start); - return lifecycleService.prepareWorldInstance(request); - }); + executor.submit(() -> { + ready.countDown(); + await(start); + return lifecycleService.prepareWorldInstance(request); + }); Future second = - executor.submit( - () -> { - ready.countDown(); - await(start); - return lifecycleService.prepareWorldInstance(request); - }); + executor.submit(() -> { + ready.countDown(); + await(start); + return lifecycleService.prepareWorldInstance(request); + }); assertThat(ready.await(5, TimeUnit.SECONDS)).isTrue(); start.countDown(); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java index 0271fa56a4..7ba131a556 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeIntegrationTest.java @@ -201,20 +201,18 @@ void persistsCompleteFreshReceiptAndReusesExactTenantAssociationAcrossWorlds() { .isEqualTo(1L); assertThat(read(firstRequestId)).contains(first); - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO region (tenant_id, name) VALUES (?, ?)", - first.localTenantKey(), - "cannot-claim-canonical-selector")) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO region (tenant_id, name) VALUES (?, ?)", + first.localTenantKey(), + "cannot-claim-canonical-selector")) .isInstanceOf(DataIntegrityViolationException.class) .satisfies(this::assertReservedCanonicalSelectorRejected); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE region SET tenant_id = ? WHERE id = ?", - first.localTenantKey(), - legacyRegionId)) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE region SET tenant_id = ? WHERE id = ?", + first.localTenantKey(), + legacyRegionId)) .isInstanceOf(DataIntegrityViolationException.class) .satisfies(this::assertReservedCanonicalSelectorRejected); assertThat( @@ -350,42 +348,37 @@ void readBySourceRejectsMalformedBinding() { tenant, tenantSlug(tenant), "malformed-read-world", sourceRowId(tenant), "Malformed"); UUID nilUuid = new UUID(0L, 0L); - assertThatThrownBy( - () -> - repository.readBySource( - "FireMud", - tenant, - source.worldSlug(), - source.operationId(), - source.evidenceDigest())) + assertThatThrownBy(() -> + repository.readBySource( + "FireMud", + tenant, + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - repository.readBySource( - NAMESPACE, - nilUuid, - source.worldSlug(), - source.operationId(), - source.evidenceDigest())) + assertThatThrownBy(() -> + repository.readBySource( + NAMESPACE, + nilUuid, + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - repository.readBySource( - NAMESPACE, - tenant, - "Malformed-World", - source.operationId(), - source.evidenceDigest())) + assertThatThrownBy(() -> + repository.readBySource( + NAMESPACE, + tenant, + "Malformed-World", + source.operationId(), + source.evidenceDigest())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - repository.readBySource( - NAMESPACE, tenant, source.worldSlug(), nilUuid, source.evidenceDigest())) + assertThatThrownBy(() -> + repository.readBySource( + NAMESPACE, tenant, source.worldSlug(), nilUuid, source.evidenceDigest())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - repository.readBySource( - NAMESPACE, tenant, source.worldSlug(), source.operationId(), "sha256:BAD")) + assertThatThrownBy(() -> + repository.readBySource( + NAMESPACE, tenant, source.worldSlug(), source.operationId(), "sha256:BAD")) .isInstanceOf(IllegalArgumentException.class); } @@ -402,19 +395,18 @@ void readBySourceDoesNotExposeUncommittedOwnerEvidence() { "Uncommitted"); TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); - transactionTemplate.execute( - status -> { - repository.acceptFresh(NAMESPACE, requestId, source); - assertThat( - repository.readBySource( - NAMESPACE, - tenant, - source.worldSlug(), - source.operationId(), - source.evidenceDigest())) - .isEmpty(); - return null; - }); + transactionTemplate.execute(status -> { + repository.acceptFresh(NAMESPACE, requestId, source); + assertThat( + repository.readBySource( + NAMESPACE, + tenant, + source.worldSlug(), + source.operationId(), + source.evidenceDigest())) + .isEmpty(); + return null; + }); assertThat( repository.readBySource( @@ -440,16 +432,15 @@ void deniesRetainedEvidenceAndChangedRequestOrTenantScopeBeforeAddingClaims() { source(tenant, tenantSlug, "amber-coast", sourceRowId, "Amber Coast"); assertThatThrownBy(() -> accept(requestId, changedRequestSource)) .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); - assertThatThrownBy( - () -> - accept( - requestId, - source( - UUID.randomUUID(), - "unrelated-tenant-selector", - "violet-wilds", - 7_456_321_987L, - "Violet Wilds"))) + assertThatThrownBy(() -> + accept( + requestId, + source( + UUID.randomUUID(), + "unrelated-tenant-selector", + "violet-wilds", + 7_456_321_987L, + "Violet Wilds"))) .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); AuthoredWorldSourceEvidence changedWorldSource = @@ -497,13 +488,11 @@ void ownerTransactionRollbackLeavesNeitherAssociationNorReceipt() { "Rolled Back World"); TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); - assertThatThrownBy( - () -> - transactionTemplate.execute( - status -> { - repository.acceptFresh(NAMESPACE, requestId, source); - throw new ForcedOwnerRollbackException(); - })) + assertThatThrownBy(() -> + transactionTemplate.execute(status -> { + repository.acceptFresh(NAMESPACE, requestId, source); + throw new ForcedOwnerRollbackException(); + })) .isInstanceOf(ForcedOwnerRollbackException.class); assertThat(read(requestId)).isEmpty(); @@ -520,57 +509,51 @@ void rejectsImmutableHistoryMutationAndTruncation() { tenant, tenantSlug(tenant), "immutable-world", sourceRowId(tenant), "Immutable World"); WorldAuthoredSourceIntakeReceipt receipt = accept(requestId, source); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE world_authored_source_intake SET world_display_name = ? " - + "WHERE operation_id = ?", - "substituted", - receipt.operationId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE world_authored_source_intake SET world_display_name = ? " + + "WHERE operation_id = ?", + "substituted", + receipt.operationId())) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM world_authored_source_intake WHERE operation_id = ?", - receipt.operationId())) + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM world_authored_source_intake WHERE operation_id = ?", + receipt.operationId())) .isInstanceOf(DataAccessException.class); assertThatThrownBy(() -> dsl.execute("TRUNCATE world_authored_source_intake CASCADE")) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE world_authored_source_tenant_association SET tenant_slug = ? " - + "WHERE target_namespace = ? AND canonical_tenant_id = ?", - "changed-selector", - NAMESPACE, - tenant)) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE world_authored_source_tenant_association SET tenant_slug = ? " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + "changed-selector", + NAMESPACE, + tenant)) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM world_authored_source_tenant_association " - + "WHERE target_namespace = ? AND canonical_tenant_id = ?", - NAMESPACE, - tenant)) + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM world_authored_source_tenant_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + NAMESPACE, + tenant)) .isInstanceOf(DataAccessException.class); assertThatThrownBy( () -> dsl.execute("TRUNCATE world_authored_source_tenant_association CASCADE")) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE world_authored_source_tenant_key_reservation " - + "SET claim_kind = 'LEGACY_NUMERIC' WHERE tenant_key = ?", - receipt.localTenantKey())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE world_authored_source_tenant_key_reservation " + + "SET claim_kind = 'LEGACY_NUMERIC' WHERE tenant_key = ?", + receipt.localTenantKey())) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM world_authored_source_tenant_key_reservation " - + "WHERE tenant_key = ?", - receipt.localTenantKey())) + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM world_authored_source_tenant_key_reservation " + + "WHERE tenant_key = ?", + receipt.localTenantKey())) .isInstanceOf(DataAccessException.class); assertThatThrownBy( () -> dsl.execute("TRUNCATE world_authored_source_tenant_key_reservation CASCADE")) @@ -668,34 +651,30 @@ void sameLegacyTenantUpdatesDoNotLockTheSharedReservationRow() throws Exception try (ExecutorService executor = Executors.newFixedThreadPool(2)) { Future first = - executor.submit( - () -> - firstTransaction.execute( - status -> { - dsl.execute( - "UPDATE region SET name = ? WHERE id = ?", - "first-uncommitted-update", - firstRegionId); - firstUpdateFinished.countDown(); - await(allowFirstCommit, 20); - return null; - })); + executor.submit(() -> + firstTransaction.execute(status -> { + dsl.execute( + "UPDATE region SET name = ? WHERE id = ?", + "first-uncommitted-update", + firstRegionId); + firstUpdateFinished.countDown(); + await(allowFirstCommit, 20); + return null; + })); try { assertThat(firstUpdateFinished.await(5, TimeUnit.SECONDS)).isTrue(); assertThat(first.isDone()).isFalse(); Future second = - executor.submit( - () -> - secondTransaction.execute( - status -> { - dsl.execute( - "UPDATE region SET name = ? WHERE id = ?", - "second-committed-update", - secondRegionId); - return null; - })); + executor.submit(() -> + secondTransaction.execute(status -> { + dsl.execute( + "UPDATE region SET name = ? WHERE id = ?", + "second-committed-update", + secondRegionId); + return null; + })); second.get(5, TimeUnit.SECONDS); assertThat(first.isDone()).isFalse(); } finally { @@ -728,33 +707,30 @@ void freshIntakeLockTimeoutRollsBackAndExactRequestRetriesAfterWriterCommits() t try (ExecutorService executor = Executors.newFixedThreadPool(2)) { Future legacyWrite = - executor.submit( - () -> - legacyTransaction.execute( - status -> { - dsl.execute( - "INSERT INTO region (tenant_id, name) VALUES (?, ?)", - legacyTenantKey, - "lock-timeout-writer"); - legacyInserted.countDown(); - await(allowLegacyCommit, 20); - return null; - })); + executor.submit(() -> + legacyTransaction.execute(status -> { + dsl.execute( + "INSERT INTO region (tenant_id, name) VALUES (?, ?)", + legacyTenantKey, + "lock-timeout-writer"); + legacyInserted.countDown(); + await(allowLegacyCommit, 20); + return null; + })); try { assertThat(legacyInserted.await(5, TimeUnit.SECONDS)).isTrue(); long attemptStartedNanos = System.nanoTime(); Future failedIntake = - executor.submit( - () -> { - try { - intakeTransaction.execute( - status -> repository.acceptFresh(NAMESPACE, requestId, source)); - return null; - } catch (RuntimeException exception) { - return exception; - } - }); + executor.submit(() -> { + try { + intakeTransaction.execute( + status -> repository.acceptFresh(NAMESPACE, requestId, source)); + return null; + } catch (RuntimeException exception) { + return exception; + } + }); RuntimeException lockTimeout = failedIntake.get(5, TimeUnit.SECONDS); long attemptDurationNanos = System.nanoTime() - attemptStartedNanos; @@ -795,20 +771,19 @@ void preservesTighterCallerLockTimeoutAndResetsItAfterCommit() { TransactionTemplate intakeTransaction = new TransactionTemplate(transactionManager); WorldAuthoredSourceIntakeReceipt receipt = - intakeTransaction.execute( - status -> { - dsl.fetchOne("SELECT set_config('lock_timeout', '250ms', true)"); - WorldAuthoredSourceIntakeReceipt accepted = - repository.acceptFresh(NAMESPACE, requestId, source); - Integer activeTimeoutMillis = - Objects.requireNonNull( - dsl.fetchOne( - "SELECT setting::integer FROM pg_settings WHERE name = 'lock_timeout'"), - "PostgreSQL lock_timeout setting query returned no row") - .get(0, Integer.class); - assertThat(activeTimeoutMillis).isEqualTo(250); - return accepted; - }); + intakeTransaction.execute(status -> { + dsl.fetchOne("SELECT set_config('lock_timeout', '250ms', true)"); + WorldAuthoredSourceIntakeReceipt accepted = + repository.acceptFresh(NAMESPACE, requestId, source); + Integer activeTimeoutMillis = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT setting::integer FROM pg_settings WHERE name = 'lock_timeout'"), + "PostgreSQL lock_timeout setting query returned no row") + .get(0, Integer.class); + assertThat(activeTimeoutMillis).isEqualTo(250); + return accepted; + }); assertThat(receipt).isNotNull(); var lockTimeoutSettings = @@ -843,10 +818,8 @@ void rejectsReadOnlyAndNonReadCommittedOwnerTransactionsWithoutClaims() { TransactionTemplate repeatableRead = new TransactionTemplate(transactionManager); repeatableRead.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); - assertThatThrownBy( - () -> - repeatableRead.execute( - status -> repository.acceptFresh(NAMESPACE, requestId, source))) + assertThatThrownBy(() -> + repeatableRead.execute(status -> repository.acceptFresh(NAMESPACE, requestId, source))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("READ COMMITTED"); assertThat(countForCanonicalTenant(tenant)).isZero(); @@ -912,27 +885,24 @@ void concurrentLegacyNumericClaimSerializesBeforeFreshSelectorAllocation() throw try (ExecutorService executor = Executors.newFixedThreadPool(2)) { Future legacyWrite = - executor.submit( - () -> - legacyTransaction.execute( - status -> { - dsl.execute( - "INSERT INTO region (tenant_id, name) VALUES (?, ?)", - legacyTenantKey, - "concurrent-legacy-selector"); - legacyInserted.countDown(); - await(allowLegacyCommit, 20); - return null; - })); + executor.submit(() -> + legacyTransaction.execute(status -> { + dsl.execute( + "INSERT INTO region (tenant_id, name) VALUES (?, ?)", + legacyTenantKey, + "concurrent-legacy-selector"); + legacyInserted.countDown(); + await(allowLegacyCommit, 20); + return null; + })); assertThat(legacyInserted.await(5, TimeUnit.SECONDS)).isTrue(); Future intake = - executor.submit( - () -> { - intakeStarted.countDown(); - return intakeTransaction.execute( - status -> repository.acceptFresh(NAMESPACE, requestId, source)); - }); + executor.submit(() -> { + intakeStarted.countDown(); + return intakeTransaction.execute( + status -> repository.acceptFresh(NAMESPACE, requestId, source)); + }); assertThat(intakeStarted.await(5, TimeUnit.SECONDS)).isTrue(); awaitAllocatorLockWait(); allowLegacyCommit.countDown(); @@ -980,39 +950,35 @@ void concurrentLegacyClaimAfterAllocationCannotTakeTheReservedSelector() throws try (ExecutorService executor = Executors.newFixedThreadPool(2)) { Future intake = - executor.submit( - () -> - ownerTransaction.execute( - status -> { - WorldAuthoredSourceIntakeReceipt receipt = - repository.acceptFresh(NAMESPACE, requestId, source); - preparedReceipt.set(receipt); - intakePrepared.countDown(); - await(allowIntakeCommit, 20); - return receipt; - })); + executor.submit(() -> + ownerTransaction.execute(status -> { + WorldAuthoredSourceIntakeReceipt receipt = + repository.acceptFresh(NAMESPACE, requestId, source); + preparedReceipt.set(receipt); + intakePrepared.countDown(); + await(allowIntakeCommit, 20); + return receipt; + })); assertThat(intakePrepared.await(5, TimeUnit.SECONDS)).isTrue(); WorldAuthoredSourceIntakeReceipt receipt = preparedReceipt.get(); assertThat(receipt).isNotNull(); Future legacyWrite = - executor.submit( - () -> { - try { - legacyTransaction.execute( - status -> { - dsl.execute( - "INSERT INTO region (tenant_id, name) VALUES (?, ?)", - receipt.localTenantKey(), - "cannot-race-private-selector"); - return null; - }); - return true; - } catch (DataIntegrityViolationException expectedReservedKeyRejection) { - assertReservedCanonicalSelectorRejected(expectedReservedKeyRejection); - return false; - } + executor.submit(() -> { + try { + legacyTransaction.execute(status -> { + dsl.execute( + "INSERT INTO region (tenant_id, name) VALUES (?, ?)", + receipt.localTenantKey(), + "cannot-race-private-selector"); + return null; }); + return true; + } catch (DataIntegrityViolationException expectedReservedKeyRejection) { + assertReservedCanonicalSelectorRejected(expectedReservedKeyRejection); + return false; + } + }); awaitLegacyWriterLockWait(); allowIntakeCommit.countDown(); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java index 390b4eb634..09e43d235f 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredSourceIntakeMtlsIntegrationTest.java @@ -259,10 +259,9 @@ void reconcilesLostSuccessAcknowledgementWithExactRetryAndCommittedReadback() th intakeClient(pki.gameDesignClient(), "gd-retry")) { assertThatThrownBy(() -> client.intake(scenario.intakeRequest())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); WorldAuthoredSourceIntakeReceipt committedAfterLostAck = repository.read(NAMESPACE, scenario.intakeRequestId()).orElseThrow(); @@ -370,18 +369,17 @@ void registeredDraftMutationDeniesOtherAuthenticatedPeerBeforeOwnerReadOrMutatio private AuthoredWorldSourceClient sourceBoundary(Scenario scenario) { AuthoredWorldSourceClient syntheticSource = mock(AuthoredWorldSourceClient.class); when(syntheticSource.read(any(AuthoredWorldSourceGrpcCodec.ReadRequest.class))) - .thenAnswer( - invocation -> { - AuthoredWorldSourceGrpcCodec.ReadRequest request = invocation.getArgument(0); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); - assertThat(request.operationId()).isEqualTo(scenario.sourceOperationId()); - assertThat(request.canonicalTenantId()).isEqualTo(scenario.canonicalTenantId()); - assertThat(request.worldSlug()).isEqualTo(scenario.worldSlug()); - AuthoredWorldSourceEvidence answer = scenario.sourceEvidence(); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return answer; - }); + .thenAnswer(invocation -> { + AuthoredWorldSourceGrpcCodec.ReadRequest request = invocation.getArgument(0); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.operationId()).isEqualTo(scenario.sourceOperationId()); + assertThat(request.canonicalTenantId()).isEqualTo(scenario.canonicalTenantId()); + assertThat(request.worldSlug()).isEqualTo(scenario.worldSlug()); + AuthoredWorldSourceEvidence answer = scenario.sourceEvidence(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return answer; + }); return syntheticSource; } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java index 5c5d3d0d1e..539b13e3aa 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldAuthoredVersionIdentityIntegrationTest.java @@ -160,33 +160,31 @@ void persistsExactIdentityAndPrivateKeyWithoutContentOrLifecycleWrites() { long gameDesignVersionId = 103L; AuthoredWorldVersionStateClient client = mock(AuthoredWorldVersionStateClient.class); when(client.read(any())) - .thenAnswer( - invocation -> { - AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); - return versionEvidence( - request, - source, - canonicalVersionId, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, - 5L); - }); + .thenAnswer(invocation -> { + AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); + return versionEvidence( + request, + source, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 5L); + }); WorldAuthoredVersionIdentityRepository repository = new WorldAuthoredVersionIdentityRepository(dsl); WorldAuthoredVersionIdentityService service = service(client, repository, transactionManager); UUID readRequestId = UUID.randomUUID(); WorldAuthoredVersionIdentityReceipt receipt = - withGameDesign( - () -> - service.associate( - NAMESPACE, - source.canonicalTenantId(), - source.worldSlug(), - source.operationId(), - source.evidenceDigest(), - canonicalVersionId, - gameDesignVersionId, - readRequestId)); + withGameDesign(() -> + service.associate( + NAMESPACE, + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + canonicalVersionId, + gameDesignVersionId, + readRequestId)); WorldAuthoredVersionIdentityReceipt independentReadback = repository .readByCanonicalVersion( @@ -269,19 +267,17 @@ void persistsExactIdentityAndPrivateKeyWithoutContentOrLifecycleWrites() { assertThat(retainedWorld.get("version_id", Long.class)).isEqualTo(29L); assertThat(retainedWorld.get("status", String.class)).isEqualTo("ACTIVE"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE world_authored_version_identity SET world_slug = ? " - + "WHERE operation_id = ?", - "rewritten-world", - receipt.operationId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE world_authored_version_identity SET world_slug = ? " + + "WHERE operation_id = ?", + "rewritten-world", + receipt.operationId())) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM world_authored_version_identity WHERE operation_id = ?", - receipt.operationId())) + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM world_authored_version_identity WHERE operation_id = ?", + receipt.operationId())) .isInstanceOf(DataAccessException.class); assertThatThrownBy(() -> dsl.execute("TRUNCATE world_authored_version_identity")) .isInstanceOf(DataAccessException.class); @@ -298,46 +294,42 @@ void deniesWrongGameDesignIdentitySourceNamespaceAndMissingIntakeBeforeOwnerWrit AuthoredWorldVersionStateClient wrongUuidClient = mock(AuthoredWorldVersionStateClient.class); when(wrongUuidClient.read(any())) - .thenAnswer( - invocation -> - versionEvidence( - invocation.getArgument(0), - source, - OTHER_CANONICAL_VERSION, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, - 8L)); + .thenAnswer(invocation -> + versionEvidence( + invocation.getArgument(0), + source, + OTHER_CANONICAL_VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 8L)); WorldAuthoredVersionIdentityRepository repository = new WorldAuthoredVersionIdentityRepository(dsl); WorldAuthoredVersionIdentityService wrongUuidService = service(wrongUuidClient, repository, transactionManager); - assertThatThrownBy( - () -> - withGameDesign( - () -> - associate( - wrongUuidService, - source, - canonicalVersionId, - gameDesignVersionId, - UUID.randomUUID()))) + assertThatThrownBy(() -> + withGameDesign(() -> + associate( + wrongUuidService, + source, + canonicalVersionId, + gameDesignVersionId, + UUID.randomUUID()))) .isInstanceOf(InvalidIdentityEvidenceException.class); assertThat(identityCount(source)).isZero(); AuthoredWorldVersionStateClient wrongPeerClient = mock(AuthoredWorldVersionStateClient.class); WorldAuthoredVersionIdentityService wrongPeerService = service(wrongPeerClient, repository, transactionManager); - assertThatThrownBy( - () -> - withPeer( - NAMESPACE, - "game-session-service", - () -> - associate( - wrongPeerService, - source, - canonicalVersionId, - gameDesignVersionId, - UUID.randomUUID()))) + assertThatThrownBy(() -> + withPeer( + NAMESPACE, + "game-session-service", + () -> + associate( + wrongPeerService, + source, + canonicalVersionId, + gameDesignVersionId, + UUID.randomUUID()))) .isInstanceOf(SecurityException.class); verify(wrongPeerClient, never()).read(any()); assertThat(identityCount(source)).isZero(); @@ -346,26 +338,23 @@ void deniesWrongGameDesignIdentitySourceNamespaceAndMissingIntakeBeforeOwnerWrit AuthoredWorldVersionStateClient wrongSourceClient = mock(AuthoredWorldVersionStateClient.class); UUID substitutedReadId = UUID.randomUUID(); when(wrongSourceClient.read(any())) - .thenAnswer( - invocation -> - versionEvidence( - request(substitutedSource, substitutedReadId, gameDesignVersionId), - substitutedSource, - canonicalVersionId, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, - 9L)); + .thenAnswer(invocation -> + versionEvidence( + request(substitutedSource, substitutedReadId, gameDesignVersionId), + substitutedSource, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 9L)); WorldAuthoredVersionIdentityService wrongSourceService = service(wrongSourceClient, repository, transactionManager); - assertThatThrownBy( - () -> - withGameDesign( - () -> - associate( - wrongSourceService, - source, - canonicalVersionId, - gameDesignVersionId, - substitutedReadId))) + assertThatThrownBy(() -> + withGameDesign(() -> + associate( + wrongSourceService, + source, + canonicalVersionId, + gameDesignVersionId, + substitutedReadId))) .isInstanceOf(InvalidIdentityEvidenceException.class); assertThat(identityCount(source)).isZero(); assertThat(identityCount(substitutedSource)).isZero(); @@ -374,19 +363,17 @@ void deniesWrongGameDesignIdentitySourceNamespaceAndMissingIntakeBeforeOwnerWrit mock(AuthoredWorldVersionStateClient.class); WorldAuthoredVersionIdentityService wrongNamespaceService = service(wrongNamespaceClient, repository, transactionManager); - assertThatThrownBy( - () -> - withGameDesign( - () -> - wrongNamespaceService.associate( - "other-namespace", - source.canonicalTenantId(), - source.worldSlug(), - source.operationId(), - source.evidenceDigest(), - canonicalVersionId, - gameDesignVersionId, - UUID.randomUUID()))) + assertThatThrownBy(() -> + withGameDesign(() -> + wrongNamespaceService.associate( + "other-namespace", + source.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + canonicalVersionId, + gameDesignVersionId, + UUID.randomUUID()))) .isInstanceOf(SecurityException.class); verify(wrongNamespaceClient, never()).read(any()); assertThat(identityCount(source)).isZero(); @@ -395,26 +382,23 @@ void deniesWrongGameDesignIdentitySourceNamespaceAndMissingIntakeBeforeOwnerWrit AuthoredWorldVersionStateClient missingSourceClient = mock(AuthoredWorldVersionStateClient.class); when(missingSourceClient.read(any())) - .thenAnswer( - invocation -> - versionEvidence( - invocation.getArgument(0), - missingSource, - canonicalVersionId, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, - 10L)); + .thenAnswer(invocation -> + versionEvidence( + invocation.getArgument(0), + missingSource, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 10L)); WorldAuthoredVersionIdentityService missingSourceService = service(missingSourceClient, repository, transactionManager); - assertThatThrownBy( - () -> - withGameDesign( - () -> - associate( - missingSourceService, - missingSource, - canonicalVersionId, - gameDesignVersionId, - UUID.randomUUID()))) + assertThatThrownBy(() -> + withGameDesign(() -> + associate( + missingSourceService, + missingSource, + canonicalVersionId, + gameDesignVersionId, + UUID.randomUUID()))) .isInstanceOf(InvalidIdentityEvidenceException.class); assertThat(identityCount(missingSource)).isZero(); assertThat( @@ -441,35 +425,33 @@ void concurrentExactStableIdentityReturnsOneOriginalHistoricalReceipt() throws E AuthoredWorldVersionStateClient firstClient = mock(AuthoredWorldVersionStateClient.class); AuthoredWorldVersionStateClient secondClient = mock(AuthoredWorldVersionStateClient.class); when(firstClient.read(any())) - .thenAnswer( - invocation -> { - AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); - awaitReadBarrier(bothRead); - AuthoredWorldVersionStateEvidence evidence = - versionEvidence( - request, - source, - canonicalVersionId, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, - 12L); - firstEvidence.set(evidence); - return evidence; - }); + .thenAnswer(invocation -> { + AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); + awaitReadBarrier(bothRead); + AuthoredWorldVersionStateEvidence evidence = + versionEvidence( + request, + source, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 12L); + firstEvidence.set(evidence); + return evidence; + }); when(secondClient.read(any())) - .thenAnswer( - invocation -> { - AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); - awaitReadBarrier(bothRead); - AuthoredWorldVersionStateEvidence evidence = - versionEvidence( - request, - source, - canonicalVersionId, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE, - 13L); - secondEvidence.set(evidence); - return evidence; - }); + .thenAnswer(invocation -> { + AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); + awaitReadBarrier(bothRead); + AuthoredWorldVersionStateEvidence evidence = + versionEvidence( + request, + source, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE, + 13L); + secondEvidence.set(evidence); + return evidence; + }); WorldAuthoredVersionIdentityRepository repository = new WorldAuthoredVersionIdentityRepository(dsl); WorldAuthoredVersionIdentityService firstService = @@ -479,27 +461,19 @@ void concurrentExactStableIdentityReturnsOneOriginalHistoricalReceipt() throws E try (ExecutorService executor = Executors.newFixedThreadPool(2)) { Future first = - executor.submit( - () -> - withGameDesign( - () -> - associate( - firstService, - source, - canonicalVersionId, - gameDesignVersionId, - firstReadId))); + executor.submit(() -> + withGameDesign(() -> + associate( + firstService, source, canonicalVersionId, gameDesignVersionId, firstReadId))); Future second = - executor.submit( - () -> - withGameDesign( - () -> - associate( - secondService, - source, - canonicalVersionId, - gameDesignVersionId, - secondReadId))); + executor.submit(() -> + withGameDesign(() -> + associate( + secondService, + source, + canonicalVersionId, + gameDesignVersionId, + secondReadId))); WorldAuthoredVersionIdentityReceipt firstReceipt = first.get(25, TimeUnit.SECONDS); WorldAuthoredVersionIdentityReceipt secondReceipt = second.get(25, TimeUnit.SECONDS); @@ -531,50 +505,43 @@ void conflictingUuidOrGameDesignSelectorDoesNotRewriteTheOriginalReceipt() { long gameDesignVersionId = 401L; AuthoredWorldVersionStateClient client = mock(AuthoredWorldVersionStateClient.class); when(client.read(any())) - .thenAnswer( - invocation -> { - AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); - UUID returnedCanonicalId = - request.versionId() == gameDesignVersionId - ? canonicalVersionId - : OTHER_CANONICAL_VERSION; - return versionEvidence( - request, - source, - returnedCanonicalId, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, - 16L); - }); + .thenAnswer(invocation -> { + AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); + UUID returnedCanonicalId = + request.versionId() == gameDesignVersionId + ? canonicalVersionId + : OTHER_CANONICAL_VERSION; + return versionEvidence( + request, + source, + returnedCanonicalId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + 16L); + }); WorldAuthoredVersionIdentityRepository repository = new WorldAuthoredVersionIdentityRepository(dsl); WorldAuthoredVersionIdentityService service = service(client, repository, transactionManager); WorldAuthoredVersionIdentityReceipt original = - withGameDesign( - () -> + withGameDesign(() -> + associate(service, source, canonicalVersionId, gameDesignVersionId, UUID.randomUUID())); + + assertThatThrownBy(() -> + withGameDesign(() -> associate( - service, source, canonicalVersionId, gameDesignVersionId, UUID.randomUUID())); - - assertThatThrownBy( - () -> - withGameDesign( - () -> - associate( - service, - source, - canonicalVersionId, - gameDesignVersionId + 1, - UUID.randomUUID()))) + service, + source, + canonicalVersionId, + gameDesignVersionId + 1, + UUID.randomUUID()))) .isInstanceOf(RegistrationConflictException.class); - assertThatThrownBy( - () -> - withGameDesign( - () -> - associate( - service, - source, - OTHER_CANONICAL_VERSION, - gameDesignVersionId, - UUID.randomUUID()))) + assertThatThrownBy(() -> + withGameDesign(() -> + associate( + service, + source, + OTHER_CANONICAL_VERSION, + gameDesignVersionId, + UUID.randomUUID()))) .isInstanceOf(RegistrationConflictException.class); assertThat( @@ -593,14 +560,13 @@ void recoversLostCommitAcknowledgmentAndRetriesWithoutRereadingOrReminting() { long gameDesignVersionId = 503L; AuthoredWorldVersionStateClient client = mock(AuthoredWorldVersionStateClient.class); when(client.read(any())) - .thenAnswer( - invocation -> - versionEvidence( - invocation.getArgument(0), - source, - canonicalVersionId, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, - 21L)); + .thenAnswer(invocation -> + versionEvidence( + invocation.getArgument(0), + source, + canonicalVersionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 21L)); WorldAuthoredVersionIdentityRepository repository = new WorldAuthoredVersionIdentityRepository(dsl); WorldAuthoredVersionIdentityService service = @@ -609,15 +575,11 @@ void recoversLostCommitAcknowledgmentAndRetriesWithoutRereadingOrReminting() { UUID originalReadId = UUID.randomUUID(); WorldAuthoredVersionIdentityReceipt recovered = - withGameDesign( - () -> - associate( - service, source, canonicalVersionId, gameDesignVersionId, originalReadId)); + withGameDesign(() -> + associate(service, source, canonicalVersionId, gameDesignVersionId, originalReadId)); WorldAuthoredVersionIdentityReceipt retry = - withGameDesign( - () -> - associate( - service, source, canonicalVersionId, gameDesignVersionId, UUID.randomUUID())); + withGameDesign(() -> + associate(service, source, canonicalVersionId, gameDesignVersionId, UUID.randomUUID())); assertThat(recovered).isEqualTo(retry); assertThat(retry.versionStateEvidence().request().readRequestId()).isEqualTo(originalReadId); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java index 37023df234..2c8db69f9e 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldCompleteLaunchBindingIntegrationTest.java @@ -192,19 +192,17 @@ void persistsCompletePairReadsItBackAndLeavesUnmappedRetainedRowsUntouched() { .get("name", String.class)) .isEqualTo(retainedName); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE world_complete_launch_binding SET world_slug = ? " - + "WHERE binding_operation_id = ?", - "changed-world", - first.operationId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE world_complete_launch_binding SET world_slug = ? " + + "WHERE binding_operation_id = ?", + "changed-world", + first.operationId())) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM world_complete_launch_binding WHERE binding_operation_id = ?", - first.operationId())) + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM world_complete_launch_binding WHERE binding_operation_id = ?", + first.operationId())) .isInstanceOf(DataAccessException.class); assertThatThrownBy(() -> dsl.execute("TRUNCATE world_complete_launch_binding")) .isInstanceOf(DataAccessException.class); @@ -279,17 +277,15 @@ void simultaneousExactRetriesReturnTheSameDurableReceiptAndOwnerOperation() thro AuthoredWorldLaunchDescriptorClient secondClient = mock(AuthoredWorldLaunchDescriptorClient.class); when(firstClient.getComplete(any())) - .thenAnswer( - invocation -> { - awaitFetchBarrier(bothFetched); - return evidence; - }); + .thenAnswer(invocation -> { + awaitFetchBarrier(bothFetched); + return evidence; + }); when(secondClient.getComplete(any())) - .thenAnswer( - invocation -> { - awaitFetchBarrier(bothFetched); - return evidence; - }); + .thenAnswer(invocation -> { + awaitFetchBarrier(bothFetched); + return evidence; + }); WorldCompleteLaunchBindingService firstService = service(firstClient, transactionManager); WorldCompleteLaunchBindingService secondService = service(secondClient, transactionManager); GetRequest firstRequest = request(evidence); @@ -337,17 +333,15 @@ void concurrentExactAndChangedClaimsKeepOneImmutableBinding() throws Exception { AuthoredWorldLaunchDescriptorClient changedClient = mock(AuthoredWorldLaunchDescriptorClient.class); when(originalClient.getComplete(any())) - .thenAnswer( - invocation -> { - awaitFetchBarrier(bothFetched); - return original; - }); + .thenAnswer(invocation -> { + awaitFetchBarrier(bothFetched); + return original; + }); when(changedClient.getComplete(any())) - .thenAnswer( - invocation -> { - awaitFetchBarrier(bothFetched); - return changed; - }); + .thenAnswer(invocation -> { + awaitFetchBarrier(bothFetched); + return changed; + }); WorldCompleteLaunchBindingService originalService = service(originalClient, transactionManager); WorldCompleteLaunchBindingService changedService = service(changedClient, transactionManager); GetRequest originalRequest = request(original); @@ -425,25 +419,24 @@ void readsCurrentVersionForExactCommittedBindingAndPreservesOriginalReceipt() UUID firstReadId = UUID.randomUUID(); UUID retiredReadId = UUID.randomUUID(); when(versionStateClient.read(any())) - .thenAnswer( - invocation -> { - AuthoredWorldVersionStateEvidence.Request currentRequest = invocation.getArgument(0); - if (currentRequest.readRequestId().equals(firstReadId)) { - return currentVersionState( - currentRequest, - source, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, - evidence.descriptor().versionStateEpoch()); - } - if (currentRequest.readRequestId().equals(retiredReadId)) { - return currentVersionState( - currentRequest, - source, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE, - evidence.descriptor().versionStateEpoch() + 1); - } - throw new IllegalArgumentException("Unexpected synthetic current-read request"); - }); + .thenAnswer(invocation -> { + AuthoredWorldVersionStateEvidence.Request currentRequest = invocation.getArgument(0); + if (currentRequest.readRequestId().equals(firstReadId)) { + return currentVersionState( + currentRequest, + source, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + evidence.descriptor().versionStateEpoch()); + } + if (currentRequest.readRequestId().equals(retiredReadId)) { + return currentVersionState( + currentRequest, + source, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_ACTIVE, + evidence.descriptor().versionStateEpoch() + 1); + } + throw new IllegalArgumentException("Unexpected synthetic current-read request"); + }); WorldCompleteLaunchBindingService service = service(descriptorClient, versionStateClient, transactionManager); @@ -471,10 +464,8 @@ void readsCurrentVersionForExactCommittedBindingAndPreservesOriginalReceipt() evidence.descriptor().controlPlaneRequestId())) .isEqualTo(ownerRowsBeforeRead); - assertThatThrownBy( - () -> - withGameSession( - () -> service.readCurrentVersionState(bindingRequest, retiredReadId))) + assertThatThrownBy(() -> + withGameSession(() -> service.readCurrentVersionState(bindingRequest, retiredReadId))) .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) .hasMessageContaining("epoch differs"); assertThat( @@ -557,23 +548,22 @@ void deniesMixedCurrentVersionEvidenceWithoutChangingCommittedBinding() throws S changedSelectorEvidence.requireValid(); changedCanonicalVersionEvidence.requireValid(); when(versionStateClient.read(any())) - .thenAnswer( - invocation -> { - AuthoredWorldVersionStateEvidence.Request currentRequest = invocation.getArgument(0); - if (currentRequest.readRequestId().equals(mixedReadId)) { - return mixedEvidence; - } - if (currentRequest.readRequestId().equals(changedSelectorReadId)) { - return changedSelectorEvidence; - } - if (currentRequest.readRequestId().equals(changedCanonicalVersionReadId)) { - return changedCanonicalVersionEvidence; - } - if (currentRequest.readRequestId().equals(unavailableReadId)) { - throw new IllegalStateException("Synthetic current-version source is unavailable"); - } - throw new IllegalArgumentException("Unexpected synthetic current-read request"); - }); + .thenAnswer(invocation -> { + AuthoredWorldVersionStateEvidence.Request currentRequest = invocation.getArgument(0); + if (currentRequest.readRequestId().equals(mixedReadId)) { + return mixedEvidence; + } + if (currentRequest.readRequestId().equals(changedSelectorReadId)) { + return changedSelectorEvidence; + } + if (currentRequest.readRequestId().equals(changedCanonicalVersionReadId)) { + return changedCanonicalVersionEvidence; + } + if (currentRequest.readRequestId().equals(unavailableReadId)) { + throw new IllegalStateException("Synthetic current-version source is unavailable"); + } + throw new IllegalArgumentException("Unexpected synthetic current-read request"); + }); WorldCompleteLaunchBindingService service = service(descriptorClient, versionStateClient, transactionManager); WorldCompleteLaunchBindingReceipt committed = @@ -615,9 +605,8 @@ void deniesMixedCurrentVersionEvidenceWithoutChangingCommittedBinding() throws S assertThat(changedCanonicalVersionEvidence.canonicalVersionId()) .isNotEqualTo(bindingEvidence.releaseAttestation().canonicalVersionId()); - assertThatThrownBy( - () -> - withGameSession(() -> service.readCurrentVersionState(bindingRequest, mixedReadId))) + assertThatThrownBy(() -> + withGameSession(() -> service.readCurrentVersionState(bindingRequest, mixedReadId))) .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) .hasMessageContaining("exact committed World source"); assertThat( @@ -635,10 +624,9 @@ void deniesMixedCurrentVersionEvidenceWithoutChangingCommittedBinding() throws S otherControlPlaneRequestId)) .isEqualTo(otherSourceRowsBeforeRead); - assertThatThrownBy( - () -> - withGameSession( - () -> service.readCurrentVersionState(bindingRequest, changedSelectorReadId))) + assertThatThrownBy(() -> + withGameSession( + () -> service.readCurrentVersionState(bindingRequest, changedSelectorReadId))) .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) .hasMessageContaining("exact committed World source"); assertThat( @@ -649,12 +637,9 @@ void deniesMixedCurrentVersionEvidenceWithoutChangingCommittedBinding() throws S bindingEvidence.descriptor().controlPlaneRequestId())) .isEqualTo(committedRowsBeforeRead); - assertThatThrownBy( - () -> - withGameSession( - () -> - service.readCurrentVersionState( - bindingRequest, changedCanonicalVersionReadId))) + assertThatThrownBy(() -> + withGameSession(() -> + service.readCurrentVersionState(bindingRequest, changedCanonicalVersionReadId))) .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) .hasMessageContaining("canonical version UUID differs"); assertThat( @@ -681,10 +666,9 @@ void deniesMixedCurrentVersionEvidenceWithoutChangingCommittedBinding() throws S assertThat(committed.evidence()).isEqualTo(bindingEvidence); assertThat(committed.sourceIntakeReceipt()).isEqualTo(boundSourceReceipt); - assertThatThrownBy( - () -> - withGameSession( - () -> service.readCurrentVersionState(bindingRequest, unavailableReadId))) + assertThatThrownBy(() -> + withGameSession( + () -> service.readCurrentVersionState(bindingRequest, unavailableReadId))) .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) .hasMessageContaining("unavailable or invalid"); assertThat( @@ -695,12 +679,9 @@ void deniesMixedCurrentVersionEvidenceWithoutChangingCommittedBinding() throws S bindingEvidence.descriptor().controlPlaneRequestId())) .isEqualTo(committedRowsBeforeRead); - assertThatThrownBy( - () -> - withGameSession( - () -> - service.readCurrentVersionState( - missingBindingRequest, missingBindingReadId))) + assertThatThrownBy(() -> + withGameSession( + () -> service.readCurrentVersionState(missingBindingRequest, missingBindingReadId))) .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) .hasMessageContaining("requires a committed launch binding"); assertThat( @@ -1075,14 +1056,13 @@ private static void awaitFetchBarrier(CountDownLatch latch) { } private static Object attempt(WorldCompleteLaunchBindingService service, GetRequest request) { - return withGameSession( - () -> { - try { - return service.bind(request); - } catch (RegistrationConflictException exception) { - return exception; - } - }); + return withGameSession(() -> { + try { + return service.bind(request); + } catch (RegistrationConflictException exception) { + return exception; + } + }); } private static void migrateFixture(String schema, MigrationVersion target) { diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java index 5b681518cc..44c94f6ae7 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldDesignPublicationFenceIntegrationTest.java @@ -98,14 +98,12 @@ void rollbackAndCommittedExactReadbackRetainOneImmutableAttempt() { WorldDesignPublicationFenceEvidence request = evidence(receipt, "request-7", GAME_DESIGN_VERSION_A, 9L); - assertThatThrownBy( - () -> - ownerTransaction() - .execute( - status -> { - repository.lockOpen(request.ownerBinding()); - throw new ForcedRollbackException(); - })) + assertThatThrownBy(() -> + ownerTransaction() + .execute(status -> { + repository.lockOpen(request.ownerBinding()); + throw new ForcedRollbackException(); + })) .isInstanceOf(ForcedRollbackException.class); assertThat(ownerCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isZero(); @@ -139,14 +137,13 @@ void rollbackAndCommittedExactReadbackRetainOneImmutableAttempt() { AtomicBoolean retryRecapturedCheckpoint = new AtomicBoolean(); FrozenAttempt retry = ownerTransaction() - .execute( - status -> - repository.claimFreeze( - request, - () -> { - retryRecapturedCheckpoint.set(true); - return new Checkpoint("synthetic-new-commit", "d".repeat(64), 2); - })); + .execute(status -> + repository.claimFreeze( + request, + () -> { + retryRecapturedCheckpoint.set(true); + return new Checkpoint("synthetic-new-commit", "d".repeat(64), 2); + })); assertThat(retry).isEqualTo(frozen); assertThat(retryRecapturedCheckpoint).isFalse(); assertThat(attemptCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isEqualTo(1L); @@ -218,10 +215,9 @@ void schemaZeroAttemptAtResolvedLocalKeyCannotBePromotedByNumericCoincidence() { assertThatThrownBy(() -> repository.readAttempt(request)) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) .hasMessageContaining("schema-0"); - assertThatThrownBy( - () -> - ownerTransaction() - .execute(status -> repository.claimFreeze(request, () -> SYNTHETIC_CHECKPOINT))) + assertThatThrownBy(() -> + ownerTransaction() + .execute(status -> repository.claimFreeze(request, () -> SYNTHETIC_CHECKPOINT))) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) .hasMessageContaining("schema-0"); assertThat(ownerCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isZero(); @@ -238,17 +234,15 @@ void sameGameDesignSelectorUsesDistinctWorldLocalVersionRowsAcrossIntakes() { intake(canonicalTenantId, "brighter-coast", tenantSlug, 6_001L); ownerTransaction() - .execute( - status -> { - repository.lockOpen(ownerBinding(first, GAME_DESIGN_VERSION_A)); - return null; - }); + .execute(status -> { + repository.lockOpen(ownerBinding(first, GAME_DESIGN_VERSION_A)); + return null; + }); ownerTransaction() - .execute( - status -> { - repository.lockOpen(ownerBinding(second, GAME_DESIGN_VERSION_A)); - return null; - }); + .execute(status -> { + repository.lockOpen(ownerBinding(second, GAME_DESIGN_VERSION_A)); + return null; + }); assertThat(identity(first, GAME_DESIGN_VERSION_A).localVersionKey()) .isNotEqualTo(identity(second, GAME_DESIGN_VERSION_A).localVersionKey()); @@ -320,33 +314,29 @@ void concurrentExactFreezeRetryReturnsTheSameFenceAndCheckpoint() throws Excepti ExecutorService executor = Executors.newFixedThreadPool(2); try { Future first = - executor.submit( - () -> - ownerTransaction() - .execute( - status -> - repository.claimFreeze( - request, - () -> { - checkpointCaptured.countDown(); - await(releaseFirst); - return SYNTHETIC_CHECKPOINT; - }))); + executor.submit(() -> + ownerTransaction() + .execute(status -> + repository.claimFreeze( + request, + () -> { + checkpointCaptured.countDown(); + await(releaseFirst); + return SYNTHETIC_CHECKPOINT; + }))); await(checkpointCaptured); Future second = - executor.submit( - () -> { - secondStarted.countDown(); - return ownerTransaction() - .execute( - status -> - repository.claimFreeze( - request, - () -> { - secondCapturedCheckpoint.set(true); - return new Checkpoint("synthetic-second", "d".repeat(64), 3); - })); - }); + executor.submit(() -> { + secondStarted.countDown(); + return ownerTransaction() + .execute(status -> + repository.claimFreeze( + request, + () -> { + secondCapturedCheckpoint.set(true); + return new Checkpoint("synthetic-second", "d".repeat(64), 3); + })); + }); await(secondStarted); awaitOwnerRowLockWait(); releaseFirst.countDown(); @@ -374,31 +364,27 @@ void writerHoldingTheOpenLockCommitsBeforeFreezeCapturesItsCheckpoint() throws E ExecutorService executor = Executors.newFixedThreadPool(2); try { Future writer = - executor.submit( - () -> - ownerTransaction() - .execute( - status -> { - repository.lockOpen(request.ownerBinding()); - writerLocked.countDown(); - await(releaseWriter); - return null; - })); + executor.submit(() -> + ownerTransaction() + .execute(status -> { + repository.lockOpen(request.ownerBinding()); + writerLocked.countDown(); + await(releaseWriter); + return null; + })); await(writerLocked); Future freeze = - executor.submit( - () -> { - freezeStarted.countDown(); - return ownerTransaction() - .execute( - status -> - repository.claimFreeze( - request, - () -> { - checkpointCaptured.set(true); - return SYNTHETIC_CHECKPOINT; - })); - }); + executor.submit(() -> { + freezeStarted.countDown(); + return ownerTransaction() + .execute(status -> + repository.claimFreeze( + request, + () -> { + checkpointCaptured.set(true); + return SYNTHETIC_CHECKPOINT; + })); + }); await(freezeStarted); awaitOwnerRowLockWait(); assertThat(checkpointCaptured).isFalse(); @@ -427,38 +413,34 @@ void freezeHoldingTheLockMakesAWaitingOrdinaryWriterFailClosed() throws Exceptio ExecutorService executor = Executors.newFixedThreadPool(2); try { Future freeze = - executor.submit( - () -> - ownerTransaction() - .execute( - status -> { - FrozenAttempt result = - repository.claimFreeze( - request, - () -> { - freezeLocked.countDown(); - return SYNTHETIC_CHECKPOINT; - }); - await(releaseFreeze); - return result; - })); + executor.submit(() -> + ownerTransaction() + .execute(status -> { + FrozenAttempt result = + repository.claimFreeze( + request, + () -> { + freezeLocked.countDown(); + return SYNTHETIC_CHECKPOINT; + }); + await(releaseFreeze); + return result; + })); await(freezeLocked); Future writer = - executor.submit( - () -> { - writerStarted.countDown(); - try { - ownerTransaction() - .execute( - status -> { - repository.lockOpen(request.ownerBinding()); - return null; - }); - return false; - } catch (WorldDesignPublicationFenceRepository.ConflictException expected) { - return true; - } - }); + executor.submit(() -> { + writerStarted.countDown(); + try { + ownerTransaction() + .execute(status -> { + repository.lockOpen(request.ownerBinding()); + return null; + }); + return false; + } catch (WorldDesignPublicationFenceRepository.ConflictException expected) { + return true; + } + }); await(writerStarted); awaitOwnerRowLockWait(); releaseFreeze.countDown(); @@ -479,34 +461,30 @@ void privateKeyWriterGuardRequiresExistingOpenOwnerAndRejectsFrozenOwnerWithoutE WorldAuthoredSourceIntakeReceipt receipt = intake(UUID.randomUUID(), "private-key-guard"); WorldAuthoredVersionIdentityReceipt identity = identity(receipt, GAME_DESIGN_VERSION_A); - assertThatThrownBy( - () -> - ownerTransaction() - .execute( - status -> { - repository.lockExistingOpenByPrivateKeys( - receipt.localTenantKey(), identity.localVersionKey()); - return null; - })) + assertThatThrownBy(() -> + ownerTransaction() + .execute(status -> { + repository.lockExistingOpenByPrivateKeys( + receipt.localTenantKey(), identity.localVersionKey()); + return null; + })) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) .hasMessageContaining("existing publication owner row"); assertThat(ownerCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isZero(); assertThat(attemptCount(receipt.canonicalTenantId(), GAME_DESIGN_VERSION_A)).isZero(); ownerTransaction() - .execute( - status -> { - repository.lockOpen(ownerBinding(receipt, GAME_DESIGN_VERSION_A)); - return null; - }); + .execute(status -> { + repository.lockOpen(ownerBinding(receipt, GAME_DESIGN_VERSION_A)); + return null; + }); String openOwnerSnapshot = ownerSnapshot(receipt, identity); ownerTransaction() - .execute( - status -> { - repository.lockExistingOpenByPrivateKeys( - receipt.localTenantKey(), identity.localVersionKey()); - return null; - }); + .execute(status -> { + repository.lockExistingOpenByPrivateKeys( + receipt.localTenantKey(), identity.localVersionKey()); + return null; + }); assertThat(ownerSnapshot(receipt, identity)).isEqualTo(openOwnerSnapshot); WorldDesignPublicationFenceEvidence request = evidence(receipt, "private-key-guard-freeze", GAME_DESIGN_VERSION_A, 1L); @@ -515,15 +493,13 @@ void privateKeyWriterGuardRequiresExistingOpenOwnerAndRejectsFrozenOwnerWithoutE .execute(status -> repository.claimFreeze(request, () -> SYNTHETIC_CHECKPOINT)); String ownerBeforeDeniedWrite = ownerSnapshot(receipt, identity); - assertThatThrownBy( - () -> - ownerTransaction() - .execute( - status -> { - repository.lockExistingOpenByPrivateKeys( - receipt.localTenantKey(), identity.localVersionKey()); - return null; - })) + assertThatThrownBy(() -> + ownerTransaction() + .execute(status -> { + repository.lockExistingOpenByPrivateKeys( + receipt.localTenantKey(), identity.localVersionKey()); + return null; + })) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) .hasMessageContaining("not open"); @@ -553,26 +529,25 @@ void changedAssociationSourceRequestDigestEpochAndMissingCheckpointDoNotMutate() GAME_DESIGN_VERSION_A, () -> ownerTransaction() - .execute( - status -> - repository.claimFreeze( - new WorldDesignPublicationFenceEvidence( - NAMESPACE, - first.canonicalTenantId(), - identity(first, GAME_DESIGN_VERSION_A).canonicalVersionId(), - identity(first, GAME_DESIGN_VERSION_A).operationId(), - GAME_DESIGN_VERSION_A, - first.intakeRequestId(), - first.operationId(), - first.requestDigest(), - first.sourceOperationId(), - second.sourceEvidenceDigest(), - first.receiptDigest(), - "request-7", - FULL_REQUEST_DIGEST, - 9L, - request.publishWorkflowId()), - () -> SYNTHETIC_CHECKPOINT))); + .execute(status -> + repository.claimFreeze( + new WorldDesignPublicationFenceEvidence( + NAMESPACE, + first.canonicalTenantId(), + identity(first, GAME_DESIGN_VERSION_A).canonicalVersionId(), + identity(first, GAME_DESIGN_VERSION_A).operationId(), + GAME_DESIGN_VERSION_A, + first.intakeRequestId(), + first.operationId(), + first.requestDigest(), + first.sourceOperationId(), + second.sourceEvidenceDigest(), + first.receiptDigest(), + "request-7", + FULL_REQUEST_DIGEST, + 9L, + request.publishWorkflowId()), + () -> SYNTHETIC_CHECKPOINT))); UUID changedTenantId = UUID.randomUUID(); WorldDesignPublicationFenceEvidence changedAssociation = @@ -590,9 +565,8 @@ void changedAssociationSourceRequestDigestEpochAndMissingCheckpointDoNotMutate() GAME_DESIGN_VERSION_A, () -> ownerTransaction() - .execute( - status -> - repository.claimFreeze(changedAssociation, () -> SYNTHETIC_CHECKPOINT))); + .execute(status -> + repository.claimFreeze(changedAssociation, () -> SYNTHETIC_CHECKPOINT))); assertThat(ownerCount(changedTenantId, GAME_DESIGN_VERSION_A)).isZero(); WorldAuthoredVersionIdentityReceipt identity = identity(first, GAME_DESIGN_VERSION_A); @@ -618,10 +592,8 @@ void changedAssociationSourceRequestDigestEpochAndMissingCheckpointDoNotMutate() GAME_DESIGN_VERSION_A, () -> ownerTransaction() - .execute( - status -> - repository.claimFreeze( - changedCanonicalVersion, () -> SYNTHETIC_CHECKPOINT))); + .execute(status -> + repository.claimFreeze(changedCanonicalVersion, () -> SYNTHETIC_CHECKPOINT))); String changedSelectorWorkflow = PublicationDigestRequestBinding.full( @@ -649,10 +621,8 @@ void changedAssociationSourceRequestDigestEpochAndMissingCheckpointDoNotMutate() GAME_DESIGN_VERSION_A, () -> ownerTransaction() - .execute( - status -> - repository.claimFreeze( - changedGameDesignSelector, () -> SYNTHETIC_CHECKPOINT))); + .execute(status -> + repository.claimFreeze(changedGameDesignSelector, () -> SYNTHETIC_CHECKPOINT))); WorldDesignPublicationFenceEvidence changedRequest = evidence(first, "request-8", GAME_DESIGN_VERSION_A, 9L); @@ -693,26 +663,23 @@ void changedAssociationSourceRequestDigestEpochAndMissingCheckpointDoNotMutate() .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); assertThat(repository.readAttempt(request)).contains(frozen); - assertThatThrownBy( - () -> - evidence( - first, - "request-7", - GAME_DESIGN_VERSION_A, - 9L, - "F".repeat(64), - request.publishWorkflowId())) + assertThatThrownBy(() -> + evidence( + first, + "request-7", + GAME_DESIGN_VERSION_A, + 9L, + "F".repeat(64), + request.publishWorkflowId())) .isInstanceOf(IllegalArgumentException.class); WorldAuthoredSourceIntakeReceipt missingCheckpointReceipt = intake(UUID.randomUUID(), "uncheckpointed-world"); WorldDesignPublicationFenceEvidence missingCheckpointRequest = evidence(missingCheckpointReceipt, "request-missing-checkpoint", GAME_DESIGN_VERSION_B, 1L); - assertThatThrownBy( - () -> - ownerTransaction() - .execute( - status -> repository.claimFreeze(missingCheckpointRequest, () -> null))) + assertThatThrownBy(() -> + ownerTransaction() + .execute(status -> repository.claimFreeze(missingCheckpointRequest, () -> null))) .isInstanceOf(NullPointerException.class); assertThat(ownerCount(missingCheckpointReceipt.canonicalTenantId(), GAME_DESIGN_VERSION_B)) .isZero(); @@ -918,10 +885,8 @@ private WorldAuthoredVersionIdentityReceipt identity( VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, 1L); return ownerTransaction() - .execute( - status -> - new WorldAuthoredVersionIdentityRepository(dsl) - .acceptFresh(receipt, stateEvidence)); + .execute(status -> + new WorldAuthoredVersionIdentityRepository(dsl).acceptFresh(receipt, stateEvidence)); } private static UUID stableId( diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldManagementServiceApplicationIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldManagementServiceApplicationIntegrationTest.java index 474245bd44..ac3167d4c1 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldManagementServiceApplicationIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldManagementServiceApplicationIntegrationTest.java @@ -195,17 +195,15 @@ void worldEventDueQuerySkipsRowsClaimedByAnotherSweepUntilItsTransactionReleases CountDownLatch releaseFirst = new CountDownLatch(1); try (ExecutorService executor = Executors.newSingleThreadExecutor()) { Future> firstSweep = - executor.submit( - () -> - transactionTemplate.execute( - status -> { - List claimed = - worldEventRepository.findDueEventsForShard(repositoryCutoff, 0); - assertThat(claimed).extracting(WorldEvent::getId).contains(eventId); - firstClaimed.countDown(); - awaitLatch(releaseFirst); - return claimed; - })); + executor.submit(() -> + transactionTemplate.execute(status -> { + List claimed = + worldEventRepository.findDueEventsForShard(repositoryCutoff, 0); + assertThat(claimed).extracting(WorldEvent::getId).contains(eventId); + firstClaimed.countDown(); + awaitLatch(releaseFirst); + return claimed; + })); assertThat(firstClaimed.await(5, TimeUnit.SECONDS)).isTrue(); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPreparationStartLocationSubtransactionPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPreparationStartLocationSubtransactionPostgresIntegrationTest.java index b5b76184c2..73afb183bb 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPreparationStartLocationSubtransactionPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldPreparationStartLocationSubtransactionPostgresIntegrationTest.java @@ -117,26 +117,24 @@ void installedSchema4GuardAcceptsStampedSavepointPreparationAndRejectsLateOrHist savepoint.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED); savepoint.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); XidObservation observation = - outer.execute( - status -> { - savepoint.executeWithoutResult( - nested -> - insertPreparation(probeSchema, fixture, 2, fixture.freshInstanceId())); - var row = - dsl.fetchSingle( - "SELECT preparation_inserted_full_xid::text, xmin::text, " - + "pg_current_xact_id()::text, " - + "(txid_current() % 4294967296)::text " - + "FROM " - + DSL.name(probeSchema, "world_canonical_instance_preparation") - + " WHERE canonical_game_instance_id = ?", - fixture.freshInstanceId()); - return new XidObservation( - row.get(0, String.class), - row.get(1, String.class), - row.get(2, String.class), - row.get(3, String.class)); - }); + outer.execute(status -> { + savepoint.executeWithoutResult( + nested -> insertPreparation(probeSchema, fixture, 2, fixture.freshInstanceId())); + var row = + dsl.fetchSingle( + "SELECT preparation_inserted_full_xid::text, xmin::text, " + + "pg_current_xact_id()::text, " + + "(txid_current() % 4294967296)::text " + + "FROM " + + DSL.name(probeSchema, "world_canonical_instance_preparation") + + " WHERE canonical_game_instance_id = ?", + fixture.freshInstanceId()); + return new XidObservation( + row.get(0, String.class), + row.get(1, String.class), + row.get(2, String.class), + row.get(3, String.class)); + }); assertThat(observation).isNotNull(); assertThat(observation.serverStamp()) @@ -458,10 +456,9 @@ private Fixture fixture() throws Exception { retainedRequest.put("versionStateEpoch", 7L); Map freezeRequest = new LinkedHashMap<>(); - selectedRequest.forEach( - (key, value) -> { - if (!key.equals("worldAffectedTuples")) freezeRequest.put(key, value); - }); + selectedRequest.forEach((key, value) -> { + if (!key.equals("worldAffectedTuples")) freezeRequest.put(key, value); + }); freezeRequest.remove("versionStateEpoch"); freezeRequest.put("versionStateEpoch", 7L); freezeRequest.put("suppliedOwnedAffectedTuples", List.of()); @@ -543,13 +540,12 @@ private String scalarText(String sql, Object... bindings) { private static void assertSqlState( org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String state) { assertThatThrownBy(action) - .satisfies( - failure -> { - Throwable cause = failure; - while (cause.getCause() != null) cause = cause.getCause(); - assertThat(cause).isInstanceOf(PSQLException.class); - assertThat(((PSQLException) cause).getSQLState()).isEqualTo(state); - }); + .satisfies(failure -> { + Throwable cause = failure; + while (cause.getCause() != null) cause = cause.getCause(); + assertThat(cause).isInstanceOf(PSQLException.class); + assertThat(((PSQLException) cause).getSQLState()).isEqualTo(state); + }); } private record XidObservation( diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldSameTransactionGuardSubtransactionPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldSameTransactionGuardSubtransactionPostgresIntegrationTest.java index 9f69264606..8d9d970a3b 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldSameTransactionGuardSubtransactionPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldSameTransactionGuardSubtransactionPostgresIntegrationTest.java @@ -99,68 +99,65 @@ void childSubtransactionAttemptAcceptsTopLevelAccountBindingAndInventory() { UUID publicationFence = ownerTransaction() - .execute( - status -> { - var frozen = - childTransaction.execute( - nestedStatus -> - fenceRepository.claimFreeze( - request, - () -> - new WorldDesignPublicationFenceEvidence.Checkpoint( - "savepoint-commit", "c".repeat(64), 3))); - assertThat(frozen).isNotNull(); - var insertedAttempt = - dsl.fetchSingle( - "SELECT attempt_created_full_xid::text AS created_full_xid, " - + "attempt_inserted_full_xid::text AS inserted_full_xid, " - + "xmin::text AS tuple_xid, " - + "(attempt_created_full_xid = pg_current_xact_id()) AS top_created_stamp, " - + "(attempt_inserted_full_xid = pg_current_xact_id()) AS top_inserted_stamp, " - + "(xmin::text = (txid_current() % 4294967296)::text) AS top_xmin " - + "FROM world_design_publication_fence_attempt WHERE publication_fence = ?", - frozen.publicationFence()); - assertThat(insertedAttempt.get("top_created_stamp", Boolean.class)).isTrue(); - assertThat(insertedAttempt.get("top_inserted_stamp", Boolean.class)).isTrue(); - assertThat(insertedAttempt.get("top_xmin", Boolean.class)) - .as("the tuple was inserted by the committed child transaction") - .isFalse(); + .execute(status -> { + var frozen = + childTransaction.execute(nestedStatus -> + fenceRepository.claimFreeze( + request, + () -> + new WorldDesignPublicationFenceEvidence.Checkpoint( + "savepoint-commit", "c".repeat(64), 3))); + assertThat(frozen).isNotNull(); + var insertedAttempt = + dsl.fetchSingle( + "SELECT attempt_created_full_xid::text AS created_full_xid, " + + "attempt_inserted_full_xid::text AS inserted_full_xid, " + + "xmin::text AS tuple_xid, " + + "(attempt_created_full_xid = pg_current_xact_id()) AS top_created_stamp, " + + "(attempt_inserted_full_xid = pg_current_xact_id()) AS top_inserted_stamp, " + + "(xmin::text = (txid_current() % 4294967296)::text) AS top_xmin " + + "FROM world_design_publication_fence_attempt WHERE publication_fence = ?", + frozen.publicationFence()); + assertThat(insertedAttempt.get("top_created_stamp", Boolean.class)).isTrue(); + assertThat(insertedAttempt.get("top_inserted_stamp", Boolean.class)).isTrue(); + assertThat(insertedAttempt.get("top_xmin", Boolean.class)) + .as("the tuple was inserted by the committed child transaction") + .isFalse(); - UUID accountOperationId = UUID.randomUUID(); - UUID accountFenceId = UUID.randomUUID(); - byte[] accountBytes = - "controlled account binding".getBytes(StandardCharsets.UTF_8); - dsl.execute( - "INSERT INTO world_design_publication_account_binding " - + "(publication_fence, account_operation_id, account_fence_id, " - + "account_binding_bytes, account_binding_digest) VALUES (?, ?, ?, ?, ?)", - frozen.publicationFence(), - accountOperationId, - accountFenceId, - accountBytes, - "sha256:" + sha256(accountBytes)); + UUID accountOperationId = UUID.randomUUID(); + UUID accountFenceId = UUID.randomUUID(); + byte[] accountBytes = "controlled account binding".getBytes(StandardCharsets.UTF_8); + dsl.execute( + "INSERT INTO world_design_publication_account_binding " + + "(publication_fence, account_operation_id, account_fence_id, " + + "account_binding_bytes, account_binding_digest) VALUES (?, ?, ?, ?, ?)", + frozen.publicationFence(), + accountOperationId, + accountFenceId, + accountBytes, + "sha256:" + sha256(accountBytes)); - byte[] inventoryBytes = - "controlled selected inventory".getBytes(StandardCharsets.UTF_8); - dsl.execute( - "INSERT INTO world_selected_publication_artifact_inventory " - + "(publication_fence, target_namespace, canonical_tenant_id, canonical_version_id, " - + "local_tenant_key, local_version_key, applied_commit_id, account_operation_id, " - + "account_fence_id, inventory_schema_version, inventory_bytes, inventory_digest) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?)", - frozen.publicationFence(), - request.targetNamespace(), - request.canonicalTenantId(), - request.canonicalVersionId(), - receipt.localTenantKey(), - identity.localVersionKey(), - frozen.checkpoint().appliedCommitId(), - accountOperationId, - accountFenceId, - inventoryBytes, - "sha256:" + sha256(inventoryBytes)); - return frozen.publicationFence(); - }); + byte[] inventoryBytes = + "controlled selected inventory".getBytes(StandardCharsets.UTF_8); + dsl.execute( + "INSERT INTO world_selected_publication_artifact_inventory " + + "(publication_fence, target_namespace, canonical_tenant_id, canonical_version_id, " + + "local_tenant_key, local_version_key, applied_commit_id, account_operation_id, " + + "account_fence_id, inventory_schema_version, inventory_bytes, inventory_digest) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?)", + frozen.publicationFence(), + request.targetNamespace(), + request.canonicalTenantId(), + request.canonicalVersionId(), + receipt.localTenantKey(), + identity.localVersionKey(), + frozen.checkpoint().appliedCommitId(), + accountOperationId, + accountFenceId, + inventoryBytes, + "sha256:" + sha256(inventoryBytes)); + return frozen.publicationFence(); + }); assertThat( dsl.fetchSingle( @@ -174,11 +171,10 @@ void childSubtransactionAttemptAcceptsTopLevelAccountBindingAndInventory() { publicationFence) .get(0, Long.class)) .isEqualTo(1L); - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM world_design_publication_fence_attempt WHERE publication_fence = ?", - publicationFence)) + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM world_design_publication_fence_attempt WHERE publication_fence = ?", + publicationFence)) .hasMessageContaining("World publication-fence attempt history is immutable"); assertThat( dsl.fetchSingle( @@ -198,66 +194,65 @@ void callerSuppliedFutureStampIsOverwrittenAndCommittedAttemptCannotBeAttachedLa .executeWithoutResult(status -> fenceRepository.lockOpen(request.ownerBinding())); ownerTransaction() - .executeWithoutResult( - status -> { - dsl.execute( - "INSERT INTO world_design_publication_fence_attempt " - + "(publication_fence, target_namespace, canonical_tenant_id, local_tenant_key, " - + "version_id, intake_operation_id, intake_request_id, source_operation_id, " - + "source_evidence_digest, intake_receipt_digest, publication_request_id, " - + "request_digest, version_state_epoch, publish_workflow_id, applied_commit_id, " - + "content_digest, digest_schema_version, owner_binding_schema_version, " - + "canonical_version_id, version_identity_operation_id, game_design_version_id, " - + "intake_request_digest, attempt_created_full_xid, attempt_inserted_full_xid) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 3, 1, ?, ?, ?, ?, ?::xid8, ?::xid8)", - publicationFence, - request.targetNamespace(), - request.canonicalTenantId(), - receipt.localTenantKey(), - identity.localVersionKey(), - receipt.operationId(), - receipt.intakeRequestId(), - receipt.sourceOperationId(), - receipt.sourceEvidenceDigest(), - receipt.receiptDigest(), - request.publicationRequestId(), - request.requestDigest(), - request.versionStateEpoch(), - request.publishWorkflowId(), - "caller-stamp-probe", - "d".repeat(64), - request.canonicalVersionId(), - request.versionIdentityOperationId(), - request.gameDesignVersionId(), - receipt.requestDigest(), - FUTURE_FULL_XID, - FUTURE_FULL_XID); - assertThat( - dsl.execute( - "UPDATE world_design_publication_fence_owner " - + "SET owner_freeze_phase = 'FROZEN', current_publication_fence = ? " - + "WHERE target_namespace = ? AND canonical_tenant_id = ? " - + "AND local_tenant_key = ? AND version_id = ?", - publicationFence, - request.targetNamespace(), - request.canonicalTenantId(), - receipt.localTenantKey(), - identity.localVersionKey())) - .isEqualTo(1); - var stored = - dsl.fetchSingle( - "SELECT attempt_created_full_xid::text AS created_full_xid, " - + "attempt_inserted_full_xid::text AS inserted_full_xid, " - + "pg_current_xact_id()::text AS current_full_xid " - + "FROM world_design_publication_fence_attempt WHERE publication_fence = ?", - publicationFence); - assertThat(stored.get("created_full_xid", String.class)) - .isEqualTo(stored.get("current_full_xid", String.class)) - .isNotEqualTo(FUTURE_FULL_XID); - assertThat(stored.get("inserted_full_xid", String.class)) - .isEqualTo(stored.get("current_full_xid", String.class)) - .isNotEqualTo(FUTURE_FULL_XID); - }); + .executeWithoutResult(status -> { + dsl.execute( + "INSERT INTO world_design_publication_fence_attempt " + + "(publication_fence, target_namespace, canonical_tenant_id, local_tenant_key, " + + "version_id, intake_operation_id, intake_request_id, source_operation_id, " + + "source_evidence_digest, intake_receipt_digest, publication_request_id, " + + "request_digest, version_state_epoch, publish_workflow_id, applied_commit_id, " + + "content_digest, digest_schema_version, owner_binding_schema_version, " + + "canonical_version_id, version_identity_operation_id, game_design_version_id, " + + "intake_request_digest, attempt_created_full_xid, attempt_inserted_full_xid) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 3, 1, ?, ?, ?, ?, ?::xid8, ?::xid8)", + publicationFence, + request.targetNamespace(), + request.canonicalTenantId(), + receipt.localTenantKey(), + identity.localVersionKey(), + receipt.operationId(), + receipt.intakeRequestId(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.receiptDigest(), + request.publicationRequestId(), + request.requestDigest(), + request.versionStateEpoch(), + request.publishWorkflowId(), + "caller-stamp-probe", + "d".repeat(64), + request.canonicalVersionId(), + request.versionIdentityOperationId(), + request.gameDesignVersionId(), + receipt.requestDigest(), + FUTURE_FULL_XID, + FUTURE_FULL_XID); + assertThat( + dsl.execute( + "UPDATE world_design_publication_fence_owner " + + "SET owner_freeze_phase = 'FROZEN', current_publication_fence = ? " + + "WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "AND local_tenant_key = ? AND version_id = ?", + publicationFence, + request.targetNamespace(), + request.canonicalTenantId(), + receipt.localTenantKey(), + identity.localVersionKey())) + .isEqualTo(1); + var stored = + dsl.fetchSingle( + "SELECT attempt_created_full_xid::text AS created_full_xid, " + + "attempt_inserted_full_xid::text AS inserted_full_xid, " + + "pg_current_xact_id()::text AS current_full_xid " + + "FROM world_design_publication_fence_attempt WHERE publication_fence = ?", + publicationFence); + assertThat(stored.get("created_full_xid", String.class)) + .isEqualTo(stored.get("current_full_xid", String.class)) + .isNotEqualTo(FUTURE_FULL_XID); + assertThat(stored.get("inserted_full_xid", String.class)) + .isEqualTo(stored.get("current_full_xid", String.class)) + .isNotEqualTo(FUTURE_FULL_XID); + }); var ownerBeforeLateAttachment = dsl.fetchSingle( @@ -272,17 +267,16 @@ void callerSuppliedFutureStampIsOverwrittenAndCommittedAttemptCannotBeAttachedLa assertSqlState( () -> ownerTransaction() - .executeWithoutResult( - status -> - dsl.execute( - "INSERT INTO world_design_publication_account_binding " - + "(publication_fence, account_operation_id, account_fence_id, " - + "account_binding_bytes, account_binding_digest) VALUES (?, ?, ?, ?, ?)", - publicationFence, - UUID.randomUUID(), - UUID.randomUUID(), - accountBytes, - "sha256:" + sha256(accountBytes))), + .executeWithoutResult(status -> + dsl.execute( + "INSERT INTO world_design_publication_account_binding " + + "(publication_fence, account_operation_id, account_fence_id, " + + "account_binding_bytes, account_binding_digest) VALUES (?, ?, ?, ?, ?)", + publicationFence, + UUID.randomUUID(), + UUID.randomUUID(), + accountBytes, + "sha256:" + sha256(accountBytes))), "P0002", "query returned no rows"); assertThat( @@ -421,15 +415,14 @@ private TransactionTemplate ownerTransaction() { private static void assertSqlState( org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String state, String message) { assertThatThrownBy(action) - .satisfies( - failure -> { - Throwable cause = failure; - while (cause.getCause() != null) cause = cause.getCause(); - assertThat(cause).isInstanceOf(PSQLException.class); - PSQLException postgresFailure = (PSQLException) cause; - assertThat(postgresFailure.getSQLState()).isEqualTo(state); - assertThat(postgresFailure.getMessage()).contains(message); - }); + .satisfies(failure -> { + Throwable cause = failure; + while (cause.getCause() != null) cause = cause.getCause(); + assertThat(cause).isInstanceOf(PSQLException.class); + PSQLException postgresFailure = (PSQLException) cause; + assertThat(postgresFailure.getSQLState()).isEqualTo(state); + assertThat(postgresFailure.getMessage()).contains(message); + }); } private static String sha256(byte[] value) { diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/LegacyDemoSeedingPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/LegacyDemoSeedingPostgresIntegrationTest.java index ce5daec19e..e697d564b6 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/LegacyDemoSeedingPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/LegacyDemoSeedingPostgresIntegrationTest.java @@ -192,29 +192,25 @@ void legacyClaimSerializesWithTheExistingCanonicalTenantAllocator() throws Excep try { Future legacyClaim = - executor.submit( - () -> - transactionTemplate() - .executeWithoutResult( - status -> { - setSearchPath(); - sourceIntakeRepository.claimLegacyDemoTenant(); - claimCommittedToTransaction.countDown(); - await(allowClaimCommit); - })); + executor.submit(() -> + transactionTemplate() + .executeWithoutResult(status -> { + setSearchPath(); + sourceIntakeRepository.claimLegacyDemoTenant(); + claimCommittedToTransaction.countDown(); + await(allowClaimCommit); + })); assertThat(claimCommittedToTransaction.await(5, TimeUnit.SECONDS)).isTrue(); Future canonicalAllocation = - executor.submit( - () -> - transactionTemplate() - .execute( - status -> { - setSearchPath(); - allocatorBackendPid.set(backendPid()); - allocationStarted.countDown(); - return sourceIntakeRepository.acceptFresh(NAMESPACE, requestId, source); - })); + executor.submit(() -> + transactionTemplate() + .execute(status -> { + setSearchPath(); + allocatorBackendPid.set(backendPid()); + allocationStarted.countDown(); + return sourceIntakeRepository.acceptFresh(NAMESPACE, requestId, source); + })); try { assertThat(allocationStarted.await(5, TimeUnit.SECONDS)).isTrue(); @@ -237,20 +233,18 @@ void legacyClaimSerializesWithTheExistingCanonicalTenantAllocator() throws Excep private void runSeeder() { transactionTemplate() - .executeWithoutResult( - status -> { - setSearchPath(); - seeder.run(new DefaultApplicationArguments(new String[0])); - }); + .executeWithoutResult(status -> { + setSearchPath(); + seeder.run(new DefaultApplicationArguments(new String[0])); + }); } private WorldAuthoredSourceIntakeReceipt acceptFresh(AuthoredWorldSourceEvidence source) { return transactionTemplate() - .execute( - status -> { - setSearchPath(); - return sourceIntakeRepository.acceptFresh(NAMESPACE, UUID.randomUUID(), source); - }); + .execute(status -> { + setSearchPath(); + return sourceIntakeRepository.acceptFresh(NAMESPACE, UUID.randomUUID(), source); + }); } private TransactionTemplate transactionTemplate() { diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java index 163e03ce44..3cc65ebfee 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java @@ -474,10 +474,9 @@ void fixtureAssociationRejectsEveryWorldCopyMismatchThroughTheOwnerTransaction() var source = Objects.requireNonNull( ownerTransaction() - .execute( - status -> - sourceRepository.acceptFresh( - "dev", UUID.randomUUID(), evidence.sourceReceipt().sourceEvidence()))); + .execute(status -> + sourceRepository.acceptFresh( + "dev", UUID.randomUUID(), evidence.sourceReceipt().sourceEvidence()))); var state = AuthoredWorldVersionStateEvidence.create( new AuthoredWorldVersionStateEvidence.Request( @@ -598,15 +597,13 @@ CREATE FUNCTION __test_function__() RETURNS TRIGGER assertSqlState( () -> ownerTransaction(evidence) - .executeWithoutResult( - status -> { - dsl.fetchOne( - "SELECT set_config('world.fixture_copy_mismatch_field', ?, TRUE)", - field); - fenceRepository.lockOpen(binding(source, version)); - associationRepository.allocateRunOwnedFixtureInOwnerTransaction( - evidence, request, source, version); - }), + .executeWithoutResult(status -> { + dsl.fetchOne( + "SELECT set_config('world.fixture_copy_mismatch_field', ?, TRUE)", field); + fenceRepository.lockOpen(binding(source, version)); + associationRepository.allocateRunOwnedFixtureInOwnerTransaction( + evidence, request, source, version); + }), "23514", "Run-owned fixture association differs from its exact World, source, Version, or GS owner readback"); assertThat(allRows(dsl)) @@ -628,23 +625,19 @@ void racingActualPackageOwnersConvergeOneOriginalAllocation() throws Exception { CountDownLatch release = new CountDownLatch(1); try (ExecutorService executor = Executors.newFixedThreadPool(2)) { Future first = - executor.submit( - () -> - withControlledPeer( - () -> { - ready.countDown(); - await(release); - return prepareWithInstallation(firstOwner, evidence); - })); + executor.submit(() -> + withControlledPeer(() -> { + ready.countDown(); + await(release); + return prepareWithInstallation(firstOwner, evidence); + })); Future second = - executor.submit( - () -> - withControlledPeer( - () -> { - ready.countDown(); - await(release); - return prepareWithInstallation(secondOwner, evidence); - })); + executor.submit(() -> + withControlledPeer(() -> { + ready.countDown(); + await(release); + return prepareWithInstallation(secondOwner, evidence); + })); assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); release.countDown(); assertThat(first.get(30, TimeUnit.SECONDS)).isEqualTo(second.get(30, TimeUnit.SECONDS)); @@ -671,10 +664,9 @@ void actualOwnerRollbackLeavesNoAllocationTopologyResultOrManifest() { var versionOwner = new WorldAuthoredVersionIdentityRepository(dsl); var intake = ownerTransaction() - .execute( - status -> - sourceOwner.acceptFresh( - "dev", UUID.randomUUID(), evidence.sourceReceipt().sourceEvidence())); + .execute(status -> + sourceOwner.acceptFresh( + "dev", UUID.randomUUID(), evidence.sourceReceipt().sourceEvidence())); var state = AuthoredWorldVersionStateEvidence.create( new AuthoredWorldVersionStateEvidence.Request( @@ -694,29 +686,27 @@ void actualOwnerRollbackLeavesNoAllocationTopologyResultOrManifest() { controlledInstallation.withLaunchOwners( evidence.gameSessionAssociation().gameInstanceUuid(), () -> null); var original = allRows(dsl); - assertThatThrownBy( - () -> - ownerTransaction(evidence) - .executeWithoutResult( - status -> { - new WorldDesignPublicationFenceRepository(dsl, sourceOwner) - .lockOpen(binding(intake, version)); - var allocated = - associationRepository() - .allocateRunOwnedFixtureInOwnerTransaction( - evidence, - RunOwnedWorldFixtureEvidenceTestFixtures.request(evidence), - intake, - version); - RunOwnedWorldFixedPresetResources.materialize( - dsl, + assertThatThrownBy(() -> + ownerTransaction(evidence) + .executeWithoutResult(status -> { + new WorldDesignPublicationFenceRepository(dsl, sourceOwner) + .lockOpen(binding(intake, version)); + var allocated = + associationRepository() + .allocateRunOwnedFixtureInOwnerTransaction( evidence, - RunOwnedWorldFixedPresetResources.plan(allocated, intake, version), - allocated.worldInstanceId(), - allocated.worldPrivateKeys().gameInstanceId()); - throw new IllegalStateException( - "controlled failure after actual topology writes"); - })) + RunOwnedWorldFixtureEvidenceTestFixtures.request(evidence), + intake, + version); + RunOwnedWorldFixedPresetResources.materialize( + dsl, + evidence, + RunOwnedWorldFixedPresetResources.plan(allocated, intake, version), + allocated.worldInstanceId(), + allocated.worldPrivateKeys().gameInstanceId()); + throw new IllegalStateException( + "controlled failure after actual topology writes"); + })) .isInstanceOf(IllegalStateException.class) .hasMessage("controlled failure after actual topology writes"); assertThat(allRows(dsl)).isEqualTo(original); @@ -730,10 +720,9 @@ void actualFixtureMaterializationRetainsUnderOwnerSavepoint() { var versionOwner = new WorldAuthoredVersionIdentityRepository(dsl); var intake = ownerTransaction() - .execute( - status -> - sourceOwner.acceptFresh( - "dev", UUID.randomUUID(), evidence.sourceReceipt().sourceEvidence())); + .execute(status -> + sourceOwner.acceptFresh( + "dev", UUID.randomUUID(), evidence.sourceReceipt().sourceEvidence())); var state = AuthoredWorldVersionStateEvidence.create( new AuthoredWorldVersionStateEvidence.Request( @@ -757,12 +746,11 @@ void actualFixtureMaterializationRetainsUnderOwnerSavepoint() { var fixtureRequest = RunOwnedWorldFixtureEvidenceTestFixtures.request(evidence); var allocatedFixture = ownerTransaction(evidence) - .execute( - status -> { - fixtureFence.lockOpen(binding(intake, version)); - return fixtureAssociations.allocateRunOwnedFixtureInOwnerTransaction( - evidence, fixtureRequest, intake, version); - }); + .execute(status -> { + fixtureFence.lockOpen(binding(intake, version)); + return fixtureAssociations.allocateRunOwnedFixtureInOwnerTransaction( + evidence, fixtureRequest, intake, version); + }); var fixtureAssociation = fixtureAssociations.readRunOwnedFixtureAssociation(evidence, fixtureRequest); var fixturePlan = RunOwnedWorldFixedPresetResources.plan(fixtureAssociation, intake, version); @@ -772,33 +760,31 @@ void actualFixtureMaterializationRetainsUnderOwnerSavepoint() { var materialized = ownerTransaction(evidence) - .execute( - status -> { - var result = - savepoint.execute( - nestedStatus -> - RunOwnedWorldFixedPresetResources.materialize( - dsl, - evidence, - fixturePlan, - allocatedFixture.worldInstanceId(), - allocatedFixture.worldPrivateKeys().gameInstanceId())); - var preparationStamp = - dsl.fetchSingle( - "SELECT p.preparation_inserted_full_xid::text, p.xmin::text, " - + "pg_current_xact_id()::text, " - + "(txid_current() % 4294967296)::text " - + "FROM world_canonical_instance_preparation p " - + "WHERE p.world_instance_id = ?", - allocatedFixture.worldInstanceId()); - assertThat(preparationStamp.get(0, String.class)) - .as("the BEFORE INSERT server stamp records the top-level full XID") - .isEqualTo(preparationStamp.get(2, String.class)); - assertThat(preparationStamp.get(1, String.class)) - .as("the row inserted beneath the owner savepoint keeps its child xmin") - .isNotEqualTo(preparationStamp.get(3, String.class)); - return result; - }); + .execute(status -> { + var result = + savepoint.execute(nestedStatus -> + RunOwnedWorldFixedPresetResources.materialize( + dsl, + evidence, + fixturePlan, + allocatedFixture.worldInstanceId(), + allocatedFixture.worldPrivateKeys().gameInstanceId())); + var preparationStamp = + dsl.fetchSingle( + "SELECT p.preparation_inserted_full_xid::text, p.xmin::text, " + + "pg_current_xact_id()::text, " + + "(txid_current() % 4294967296)::text " + + "FROM world_canonical_instance_preparation p " + + "WHERE p.world_instance_id = ?", + allocatedFixture.worldInstanceId()); + assertThat(preparationStamp.get(0, String.class)) + .as("the BEFORE INSERT server stamp records the top-level full XID") + .isEqualTo(preparationStamp.get(2, String.class)); + assertThat(preparationStamp.get(1, String.class)) + .as("the row inserted beneath the owner savepoint keeps its child xmin") + .isNotEqualTo(preparationStamp.get(3, String.class)); + return result; + }); assertThat(materialized).isNotNull(); assertThat(materialized.regionCount()).isEqualTo(1); assertThat(materialized.zoneCount()).isEqualTo(1); @@ -845,10 +831,8 @@ void fixturePreparingCannotActivateAcquireHoldsPlaceActorsOrReuseConsumedManifes positiveLong(), id), "23514"); - assertThatThrownBy( - () -> - associationRepository() - .activateRunOwnedFixtureInOwnerTransaction(association, 1L, 0L)) + assertThatThrownBy(() -> + associationRepository().activateRunOwnedFixtureInOwnerTransaction(association, 1L, 0L)) .isInstanceOf(IllegalStateException.class) .hasMessageStartingWith("RUN_OWNED_WORLD_ACTIVATION_UNAVAILABLE:"); assertThat( @@ -860,22 +844,20 @@ void fixturePreparingCannotActivateAcquireHoldsPlaceActorsOrReuseConsumedManifes .isNull(); assertThat( ownerTransaction() - .execute( - status -> - dsl.fetchSingle( - "SELECT world_consume_canonical_prepare_execution_manifest('world_instance','INSERT',NULL,to_jsonb(w)) FROM world_instance w WHERE id = ?", - id) - .get(0, Boolean.class))) + .execute(status -> + dsl.fetchSingle( + "SELECT world_consume_canonical_prepare_execution_manifest('world_instance','INSERT',NULL,to_jsonb(w)) FROM world_instance w WHERE id = ?", + id) + .get(0, Boolean.class))) .isFalse(); assertThat( ownerTransaction() - .execute( - status -> - dsl.fetchSingle( - "SELECT world_consume_region_execution_manifest('region','INSERT',NULL,to_jsonb(r)) FROM region r WHERE tenant_id = ? AND version_id = ?", - association.worldPrivateKeys().tenantId(), - association.worldPrivateKeys().versionId()) - .get(0, Boolean.class))) + .execute(status -> + dsl.fetchSingle( + "SELECT world_consume_region_execution_manifest('region','INSERT',NULL,to_jsonb(r)) FROM region r WHERE tenant_id = ? AND version_id = ?", + association.worldPrivateKeys().tenantId(), + association.worldPrivateKeys().versionId()) + .get(0, Boolean.class))) .isFalse(); for (String table : List.of( @@ -922,10 +904,9 @@ void fixturePreparingCannotActivateAcquireHoldsPlaceActorsOrReuseConsumedManifes assertSqlState( () -> ownerTransaction() - .executeWithoutResult( - status -> - dsl.fetch( - "SELECT world_finalize_canonical_initial_admission_hold(NULL::uuid,NULL::uuid,'COMMITTED',NULL::text,NULL::text,NULL::text,NULL::bigint,NULL::timestamptz,false,NULL::bytea,NULL::text)")), + .executeWithoutResult(status -> + dsl.fetch( + "SELECT world_finalize_canonical_initial_admission_hold(NULL::uuid,NULL::uuid,'COMMITTED',NULL::text,NULL::text,NULL::text,NULL::bigint,NULL::timestamptz,false,NULL::bytea,NULL::text)")), "23514", "terminal proof is incomplete"); // Invalid controlled bytes with a correct byte digest only pass the preliminary digest @@ -939,12 +920,11 @@ void fixturePreparingCannotActivateAcquireHoldsPlaceActorsOrReuseConsumedManifes assertSqlState( () -> ownerTransaction() - .executeWithoutResult( - status -> - dsl.fetch( - "SELECT world_finalize_canonical_initial_admission_hold(NULL::uuid,NULL::uuid,'COMMITTED',NULL::text,NULL::text,NULL::text,NULL::bigint,TIMESTAMPTZ '2026-10-14T00:00:00Z',false,?::bytea,?::text)", - invalidControlledProbe, - invalidControlledProbeDigest)), + .executeWithoutResult(status -> + dsl.fetch( + "SELECT world_finalize_canonical_initial_admission_hold(NULL::uuid,NULL::uuid,'COMMITTED',NULL::text,NULL::text,NULL::text,NULL::bigint,TIMESTAMPTZ '2026-10-14T00:00:00Z',false,?::bytea,?::text)", + invalidControlledProbe, + invalidControlledProbeDigest)), "55000", "hold identity is missing or untyped"); assertThat(allRows(dsl)).isEqualTo(original); @@ -1003,10 +983,9 @@ void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUp UUID intakeRequest = UUID.randomUUID(); var intake = Objects.requireNonNull( - write.execute( - status -> - sourceOwner.acceptFresh( - "dev", intakeRequest, evidence.sourceReceipt().sourceEvidence()))); + write.execute(status -> + sourceOwner.acceptFresh( + "dev", intakeRequest, evidence.sourceReceipt().sourceEvidence()))); var state = AuthoredWorldVersionStateEvidence.create( new AuthoredWorldVersionStateEvidence.Request( @@ -1133,25 +1112,23 @@ public void bindEnd(ExecuteContext context) { descriptor.versionStateEpoch(), null); WorldCanonicalInstanceAssociation allocatedFixture = - write.execute( - status -> { - fixtureFence.lockOpen(binding(intake, version)); - return fixtureAssociations.allocateRunOwnedFixtureInOwnerTransaction( - evidence, fixtureRequest, intake, version); - }); + write.execute(status -> { + fixtureFence.lockOpen(binding(intake, version)); + return fixtureAssociations.allocateRunOwnedFixtureInOwnerTransaction( + evidence, fixtureRequest, intake, version); + }); assertThat(allocatedFixture).isNotNull(); assertThat(historicalRequests).hasValue(1); var fixtureAssociation = fixtureAssociations.readRunOwnedFixtureAssociation(evidence, fixtureRequest); var fixturePlan = RunOwnedWorldFixedPresetResources.plan(fixtureAssociation, intake, version); - write.executeWithoutResult( - status -> - RunOwnedWorldFixedPresetResources.materialize( - connection, - evidence, - fixturePlan, - fixtureAssociation.worldInstanceId(), - fixtureAssociation.worldPrivateKeys().gameInstanceId())); + write.executeWithoutResult(status -> + RunOwnedWorldFixedPresetResources.materialize( + connection, + evidence, + fixturePlan, + fixtureAssociation.worldInstanceId(), + fixtureAssociation.worldPrivateKeys().gameInstanceId())); var preparedFixture = connection.fetchSingle( "SELECT status, lifecycle_epoch, row_version FROM world_instance WHERE id = ?", @@ -1362,11 +1339,10 @@ public void bindEnd(ExecuteContext context) { preservedForgedPublicationFence)) .as( "the pre-1042.9 caller-forged stamp is retained while the new server stamp stays NULL") - .satisfies( - row -> { - assertThat(row.get(0, String.class)).isEqualTo("9223372036854775807"); - assertThat(row.get(1, String.class)).isNull(); - }); + .satisfies(row -> { + assertThat(row.get(0, String.class)).isEqualTo("9223372036854775807"); + assertThat(row.get(1, String.class)).isNull(); + }); assertThat( connection .fetchSingle( @@ -1435,18 +1411,17 @@ public void bindEnd(ExecuteContext context) { + "AND c.relname = 'world_canonical_instance_preparation' " + "AND t.tgname = 'trg_world_preparation_full_xid_stamp'", schema)) - .satisfies( - row -> { - assertThat(row.get(0, String.class)).isEqualTo("7"); - assertThat(row.get(1, String.class)).isEqualTo("O"); - assertThat(row.get(2, String.class)) - .isEqualTo( - connection - .fetchSingle( - "SELECT oid::text FROM pg_proc WHERE oid = to_regprocedure(?)", - schema + ".world_stamp_preparation_insert_full_xid()") - .get(0, String.class)); - }); + .satisfies(row -> { + assertThat(row.get(0, String.class)).isEqualTo("7"); + assertThat(row.get(1, String.class)).isEqualTo("O"); + assertThat(row.get(2, String.class)) + .isEqualTo( + connection + .fetchSingle( + "SELECT oid::text FROM pg_proc WHERE oid = to_regprocedure(?)", + schema + ".world_stamp_preparation_insert_full_xid()") + .get(0, String.class)); + }); assertThat( connection .fetchSingle( @@ -1969,14 +1944,13 @@ void realWorldOwnersMaterializeSixFixtureMappingsAndReplayExactCommittedBytes() null); WorldCanonicalInstanceAssociation allocated = ownerTransaction(evidence) - .execute( - status -> { - fenceRepository.lockOpen(binding); - var association = - associationRepository.allocateRunOwnedFixtureInOwnerTransaction( - evidence, request, source, version); - return association; - }); + .execute(status -> { + fenceRepository.lockOpen(binding); + var association = + associationRepository.allocateRunOwnedFixtureInOwnerTransaction( + evidence, request, source, version); + return association; + }); assertThat(allocated).isNotNull(); assertNoPendingManifests(allocated.worldInstanceId()); var association = associationRepository.readRunOwnedFixtureAssociation(evidence, request); @@ -2021,12 +1995,11 @@ void realWorldOwnersMaterializeSixFixtureMappingsAndReplayExactCommittedBytes() assertSqlState( () -> ownerTransaction() - .executeWithoutResult( - status -> - dsl.execute( - "INSERT INTO world_canonical_instance_association " - + "SELECT (jsonb_populate_record(NULL::world_canonical_instance_association, ?::jsonb)).*", - unmanifestedAssociation)), + .executeWithoutResult(status -> + dsl.execute( + "INSERT INTO world_canonical_instance_association " + + "SELECT (jsonb_populate_record(NULL::world_canonical_instance_association, ?::jsonb)).*", + unmanifestedAssociation)), "23514", "exact one-use transaction execution manifest"); Map changedUnmanifestedAssociation = new LinkedHashMap<>(allocationAssociation); @@ -2034,12 +2007,11 @@ void realWorldOwnersMaterializeSixFixtureMappingsAndReplayExactCommittedBytes() assertSqlState( () -> ownerTransaction() - .executeWithoutResult( - status -> - dsl.execute( - "INSERT INTO world_canonical_instance_association " - + "SELECT (jsonb_populate_record(NULL::world_canonical_instance_association, ?::jsonb)).*", - json(changedUnmanifestedAssociation))), + .executeWithoutResult(status -> + dsl.execute( + "INSERT INTO world_canonical_instance_association " + + "SELECT (jsonb_populate_record(NULL::world_canonical_instance_association, ?::jsonb)).*", + json(changedUnmanifestedAssociation))), "23514", "exact one-use transaction execution manifest"); assertThat(resourceCount()).isEqualTo(before); @@ -2067,12 +2039,11 @@ void realWorldOwnersMaterializeSixFixtureMappingsAndReplayExactCommittedBytes() assertSqlState( () -> ownerTransaction() - .executeWithoutResult( - status -> - dsl.fetchSingle( - "SELECT world_allocate_run_owned_fixture_instance(?::jsonb, ?::jsonb)", - json(incompleteAllocationWorld), - json(allocationAssociation))), + .executeWithoutResult(status -> + dsl.fetchSingle( + "SELECT world_allocate_run_owned_fixture_instance(?::jsonb, ?::jsonb)", + json(incompleteAllocationWorld), + json(allocationAssociation))), "P0001", "Fixture allocation requires complete exact owner row values"); assertThat(resourceCount()).isEqualTo(before); @@ -2083,12 +2054,11 @@ void realWorldOwnersMaterializeSixFixtureMappingsAndReplayExactCommittedBytes() assertSqlState( () -> ownerTransaction() - .executeWithoutResult( - status -> - dsl.fetchSingle( - "SELECT world_allocate_run_owned_fixture_instance(?::jsonb, ?::jsonb)", - json(changedAllocationWorld), - json(allocationAssociation))), + .executeWithoutResult(status -> + dsl.fetchSingle( + "SELECT world_allocate_run_owned_fixture_instance(?::jsonb, ?::jsonb)", + json(changedAllocationWorld), + json(allocationAssociation))), "23514", "no exact transaction execution manifest"); assertThat(resourceCount()).isEqualTo(before); @@ -2101,12 +2071,11 @@ void realWorldOwnersMaterializeSixFixtureMappingsAndReplayExactCommittedBytes() assertSqlState( () -> ownerTransaction() - .executeWithoutResult( - status -> - dsl.fetchSingle( - "SELECT world_allocate_run_owned_fixture_instance(?::jsonb, ?::jsonb)", - json(allocationWorld), - json(changedAllocationAssociation))), + .executeWithoutResult(status -> + dsl.fetchSingle( + "SELECT world_allocate_run_owned_fixture_instance(?::jsonb, ?::jsonb)", + json(allocationWorld), + json(changedAllocationAssociation))), "23514"); assertThat(resourceCount()).isEqualTo(before); assertThat(dsl.fetchValue("SELECT count(*) FROM world_instance WHERE id = ?", rejectedWorldId)) @@ -2134,29 +2103,27 @@ void realWorldOwnersMaterializeSixFixtureMappingsAndReplayExactCommittedBytes() assertSqlState( () -> ownerTransaction() - .executeWithoutResult( - status -> - dsl.execute( - "INSERT INTO region (tenant_id, version_id, name, shard_id, generation_seed, spacing_multiplier, version) " - + "VALUES (?, ?, 'unowned resource', 0, 0, 1.0, 0)", - source.localTenantKey(), - version.localVersionKey())), + .executeWithoutResult(status -> + dsl.execute( + "INSERT INTO region (tenant_id, version_id, name, shard_id, generation_seed, spacing_multiplier, version) " + + "VALUES (?, ?, 'unowned resource', 0, 0, 1.0, 0)", + source.localTenantKey(), + version.localVersionKey())), "23514", "no exact transaction execution manifest"); assertThat(resourceCount()).isEqualTo(before); var result = ownerTransaction(evidence) - .execute( - status -> { - fenceRepository.lockOpen(binding); - var replayAllocation = - associationRepository.allocateRunOwnedFixtureInOwnerTransaction( - evidence, request, source, version); - assertThat(replayAllocation.worldInstanceId()).isEqualTo(worldId); - return RunOwnedWorldFixedPresetResources.materialize( - dsl, evidence, plan, worldId, privateKey); - }); + .execute(status -> { + fenceRepository.lockOpen(binding); + var replayAllocation = + associationRepository.allocateRunOwnedFixtureInOwnerTransaction( + evidence, request, source, version); + assertThat(replayAllocation.worldInstanceId()).isEqualTo(worldId); + return RunOwnedWorldFixedPresetResources.materialize( + dsl, evidence, plan, worldId, privateKey); + }); assertThat(result).isNotNull(); assertThat(result.regionCount()).isEqualTo(1); assertThat(result.zoneCount()).isEqualTo(1); @@ -2310,16 +2277,15 @@ void realWorldOwnersMaterializeSixFixtureMappingsAndReplayExactCommittedBytes() worldId); var replayResult = ownerTransaction(evidence) - .execute( - status -> { - fenceRepository.lockOpen(binding); - var replayAllocation = - associationRepository.allocateRunOwnedFixtureInOwnerTransaction( - evidence, request, source, version); - assertThat(replayAllocation.worldInstanceId()).isEqualTo(worldId); - return RunOwnedWorldFixedPresetResources.materialize( - dsl, evidence, plan, worldId, privateKey); - }); + .execute(status -> { + fenceRepository.lockOpen(binding); + var replayAllocation = + associationRepository.allocateRunOwnedFixtureInOwnerTransaction( + evidence, request, source, version); + assertThat(replayAllocation.worldInstanceId()).isEqualTo(worldId); + return RunOwnedWorldFixedPresetResources.materialize( + dsl, evidence, plan, worldId, privateKey); + }); assertThat(replayResult).isEqualTo(result); assertThat(resourceCount()).isEqualTo(materializedCount); assertThat( @@ -2345,26 +2311,24 @@ private WorldLifecycleCommandServiceImpl nativeService( // Only upstream replies are controlled. The fixture bridge uses real World SQL owners. var source = mock(AuthoredWorldSourceClient.class); when(source.read(any())) - .thenAnswer( - invocation -> { - upstreamReads.incrementAndGet(); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return evidence.sourceReceipt().sourceEvidence(); - }); + .thenAnswer(invocation -> { + upstreamReads.incrementAndGet(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return evidence.sourceReceipt().sourceEvidence(); + }); var versions = mock(AuthoredWorldVersionStateClient.class); when(versions.read(any())) - .thenAnswer( - invocation -> { - upstreamReads.incrementAndGet(); - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); - return AuthoredWorldVersionStateEvidence.create( - request, - evidence.sourceReceipt().sourceEvidence(), - evidence.gameSessionAssociation().canonicalVersionId(), - VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, - evidence.launchDescriptor().versionStateEpoch()); - }); + .thenAnswer(invocation -> { + upstreamReads.incrementAndGet(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + AuthoredWorldVersionStateEvidence.Request request = invocation.getArgument(0); + return AuthoredWorldVersionStateEvidence.create( + request, + evidence.sourceReceipt().sourceEvidence(), + evidence.gameSessionAssociation().canonicalVersionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + evidence.launchDescriptor().versionStateEpoch()); + }); // Package preparation consumes the closed-parser carrier directly; this enabled provider // supplies configuration only and does not pretend to read files or authenticate producers. var provider = @@ -3227,11 +3191,10 @@ record -> record.get("family", String.class))) read.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); read.setReadOnly(true); assertThat( - read.execute( - status -> - RunOwnedWorldFixedPresetResources.readCommitted( - dsl, plan, worldId, association.worldPrivateKeys().gameInstanceId()) - .graphSha256())) + read.execute(status -> + RunOwnedWorldFixedPresetResources.readCommitted( + dsl, plan, worldId, association.worldPrivateKeys().gameInstanceId()) + .graphSha256())) .isEqualTo(plan.expectedGraphSha256()); } @@ -3502,18 +3465,16 @@ private void assertFixedPresetReadbackMode( transaction.setReadOnly(readOnly); if (supported) { RunOwnedWorldFixedPresetResources.MaterializedFixedPreset actual = - transaction.execute( - status -> - readPresetInCurrentTransaction( - plan, worldId, privateGameInstanceKey, readOnly, expectedIsolation)); + transaction.execute(status -> + readPresetInCurrentTransaction( + plan, worldId, privateGameInstanceKey, readOnly, expectedIsolation)); assertThat(actual).as(mode).isEqualTo(expected); } else { assertSqlState( () -> - transaction.execute( - status -> - readPresetInCurrentTransaction( - plan, worldId, privateGameInstanceKey, readOnly, expectedIsolation)), + transaction.execute(status -> + readPresetInCurrentTransaction( + plan, worldId, privateGameInstanceKey, readOnly, expectedIsolation)), "23514", "Run-owned fixed-preset readback requires an owner read transaction"); } @@ -3762,14 +3723,13 @@ private static void frame(MessageDigest digest, String value) { private void materialize(String planJson, long worldInstanceId, long privateGameInstanceKey) { TransactionTemplate transaction = new TransactionTemplate(transactionManager); transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - transaction.executeWithoutResult( - status -> - dsl.fetch( - "SELECT * FROM world_materialize_run_owned_fixed_preset(?, ?, ?, ?)", - planJson, - CONTENT_DIGEST, - worldInstanceId, - privateGameInstanceKey)); + transaction.executeWithoutResult(status -> + dsl.fetch( + "SELECT * FROM world_materialize_run_owned_fixed_preset(?, ?, ?, ?)", + planJson, + CONTENT_DIGEST, + worldInstanceId, + privateGameInstanceKey)); } private long insertLegacyWorldRow(long tenantKey, long privateKey, long versionKey) { @@ -3915,19 +3875,18 @@ private static void assertSqlState( private static void assertSqlState( org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String state, String message) { assertThatThrownBy(action) - .satisfies( - failure -> { - Throwable cause = failure; - while (cause.getCause() != null) { - cause = cause.getCause(); - } - assertThat(cause).isInstanceOf(PSQLException.class); - PSQLException postgresFailure = (PSQLException) cause; - assertThat(postgresFailure.getSQLState()).isEqualTo(state); - if (message != null) { - assertThat(postgresFailure.getMessage()).contains(message); - } - }); + .satisfies(failure -> { + Throwable cause = failure; + while (cause.getCause() != null) { + cause = cause.getCause(); + } + assertThat(cause).isInstanceOf(PSQLException.class); + PSQLException postgresFailure = (PSQLException) cause; + assertThat(postgresFailure.getSQLState()).isEqualTo(state); + if (message != null) { + assertThat(postgresFailure.getMessage()).contains(message); + } + }); } private RunOwnedCanonicalWorldLaunchEvidence controlledEvidence() { diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java index cb10dfd07d..edbab8a697 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java @@ -346,9 +346,8 @@ void gameDesignTransportRejectsMissingAndWrongJwtBeforeHandlerRead() throws Exce gameSessionChannel = channel("localhost", gameDesignServer.getPort(), pki.worldManagement()); var missingJwtStub = GameDesignServiceGrpc.newBlockingStub(gameSessionChannel); - assertThatThrownBy( - () -> - missingJwtStub.getLaunchDescriptor(GetLaunchDescriptorRequest.getDefaultInstance())) + assertThatThrownBy(() -> + missingJwtStub.getLaunchDescriptor(GetLaunchDescriptorRequest.getDefaultInstance())) .isInstanceOfSatisfying( StatusRuntimeException.class, failure -> @@ -849,8 +848,8 @@ private static AuthoredWorldLaunchDescriptorEvidence descriptorEvidence( private static String capabilityJson(TestPki pki, String operationId, String claimDigest) throws Exception { return """ - {"schema":"firemud.run-owned-initial-admission-fixture.v1","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":42,"gameTemplateId":17,"ownerAccountId":9,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","claimDigest":"%s"}\ - """ + {"schema":"firemud.run-owned-initial-admission-fixture.v1","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":42,"gameTemplateId":17,"ownerAccountId":9,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","claimDigest":"%s"}\ + """ .formatted( RUN_ID, PROJECT, @@ -875,8 +874,8 @@ private static String receiptJson( TestPki pki) throws Exception { return """ - {"schema":"firemud.run-owned-authored-world-source-receipt.v1","runId":"%s","composeProjectName":"%s","fixtureOperationId":"%s","ownerService":"game-design-service","gameSessionUriSan":"%s","gameSessionLeafSha256":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","sourceEvidence":{"schemaVersion":1,"targetNamespace":"dev","registrationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","tenantSlug":"%s","worldSlug":"%s","worldDisplayName":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"launchReadEvidence":{"schema":"firemud.run-owned-v1-launch-read-evidence.v1","gameTemplateId":17,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"},"creationEvidence":{"schemaVersion":%d,"targetNamespace":"%s","creationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"fixturePolicySeal":{"schema":"%s","ownerService":"%s","operationId":"%s","requestDigest":"%s","evidenceDigest":"%s"}}\ - """ + {"schema":"firemud.run-owned-authored-world-source-receipt.v1","runId":"%s","composeProjectName":"%s","fixtureOperationId":"%s","ownerService":"game-design-service","gameSessionUriSan":"%s","gameSessionLeafSha256":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","sourceEvidence":{"schemaVersion":1,"targetNamespace":"dev","registrationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","tenantSlug":"%s","worldSlug":"%s","worldDisplayName":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"launchReadEvidence":{"schema":"firemud.run-owned-v1-launch-read-evidence.v1","gameTemplateId":17,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"},"creationEvidence":{"schemaVersion":%d,"targetNamespace":"%s","creationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"fixturePolicySeal":{"schema":"%s","ownerService":"%s","operationId":"%s","requestDigest":"%s","evidenceDigest":"%s"}}\ + """ .formatted( RUN_ID, PROJECT, diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAppliedGraphHistoryPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAppliedGraphHistoryPostgresIntegrationTest.java index cba901c88f..15ec28e329 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAppliedGraphHistoryPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldAppliedGraphHistoryPostgresIntegrationTest.java @@ -103,28 +103,27 @@ void originalV1012AppliedBytesAndAbsentSelectorSurviveReceiptAndCurrentMigration // The complete Account binding is test evidence; no protected Account producer is claimed. WorldDraftGraphAppliedResult original = Objects.requireNonNull( - write.execute( - ignored -> { - assertThat( - Objects.requireNonNull(dsl.fetchOne("SHOW session_replication_role")) - .get(0, String.class)) - .isEqualTo("origin"); - var graph = topology.store(plan); - var result = WorldDraftGraphAppliedResult.create(application, graph.graphBytes()); - var operation = application.operation(); - dsl.execute( - "INSERT INTO world_draft_graph_application (operation_id,request_id,commit_id,authorization_fence_id,operation_bytes,account_binding_bytes,account_binding_digest,result_bytes,result_digest) VALUES (?,?,?,?,?,?,?,?,?)", - operation.operationId(), - operation.requestId(), - operation.commitId(), - operation.authorizationFenceId(), - operation.canonicalBytes(), - operation.accountBindingBytes(), - operation.accountBindingDigest(), - result.canonicalBytes(), - result.digest()); - return result; - })); + write.execute(ignored -> { + assertThat( + Objects.requireNonNull(dsl.fetchOne("SHOW session_replication_role")) + .get(0, String.class)) + .isEqualTo("origin"); + var graph = topology.store(plan); + var result = WorldDraftGraphAppliedResult.create(application, graph.graphBytes()); + var operation = application.operation(); + dsl.execute( + "INSERT INTO world_draft_graph_application (operation_id,request_id,commit_id,authorization_fence_id,operation_bytes,account_binding_bytes,account_binding_digest,result_bytes,result_digest) VALUES (?,?,?,?,?,?,?,?,?)", + operation.operationId(), + operation.requestId(), + operation.commitId(), + operation.authorizationFenceId(), + operation.canonicalBytes(), + operation.accountBindingBytes(), + operation.accountBindingDigest(), + result.canonicalBytes(), + result.digest()); + return result; + })); assertThat(original.resultIdentity()).contains("/v1:"); assertThat(original.startLocationReceipt()).isEmpty(); assertThat( @@ -158,18 +157,16 @@ void originalV1012AppliedBytesAndAbsentSelectorSurviveReceiptAndCurrentMigration () -> WorldDraftStartLocationReceipt.create(application, original.graphBytes())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("requires an original graph declaration"); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE world_draft_graph_application SET result_bytes = ? WHERE operation_id = ?", - new byte[] {99}, - application.operation().operationId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE world_draft_graph_application SET result_bytes = ? WHERE operation_id = ?", + new byte[] {99}, + application.operation().operationId())) .isInstanceOf(DataAccessException.class); - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM world_draft_graph_terminal_identity WHERE operation_id = ?", - application.operation().operationId())) + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM world_draft_graph_terminal_identity WHERE operation_id = ?", + application.operation().operationId())) .isInstanceOf(DataAccessException.class); assertThat(rows(dsl, queries)).isEqualTo(rows); } @@ -251,43 +248,42 @@ private static Fixture fixture( Objects.requireNonNull( write.execute(ignored -> intakeRepository.acceptFresh(NAMESPACE, request, source))); return Objects.requireNonNull( - write.execute( - ignored -> { - var stateRequest = - new AuthoredWorldVersionStateEvidence.Request( - 1, - NAMESPACE, - UUID.randomUUID(), - tenant, - slug, - operation, - source.evidenceDigest(), - GAME_DESIGN_VERSION); - var version = - new WorldAuthoredVersionIdentityRepository(dsl) - .acceptFresh( - intake, - AuthoredWorldVersionStateEvidence.create( - stateRequest, - source, - UUID.randomUUID(), - VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, - 1)); - var owner = - new OwnerBinding( - NAMESPACE, - tenant, - version.canonicalVersionId(), - version.operationId(), - GAME_DESIGN_VERSION, - request, - intake.operationId(), - intake.requestDigest(), - operation, - source.evidenceDigest(), - intake.receiptDigest()); - return new Fixture(intake, owner); - })); + write.execute(ignored -> { + var stateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + tenant, + slug, + operation, + source.evidenceDigest(), + GAME_DESIGN_VERSION); + var version = + new WorldAuthoredVersionIdentityRepository(dsl) + .acceptFresh( + intake, + AuthoredWorldVersionStateEvidence.create( + stateRequest, + source, + UUID.randomUUID(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1)); + var owner = + new OwnerBinding( + NAMESPACE, + tenant, + version.canonicalVersionId(), + version.operationId(), + GAME_DESIGN_VERSION, + request, + intake.operationId(), + intake.requestDigest(), + operation, + source.evidenceDigest(), + intake.receiptDigest()); + return new Fixture(intake, owner); + })); } private record Fixture(WorldAuthoredSourceIntakeReceipt intake, OwnerBinding owner) {} diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTerminalSchemaPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTerminalSchemaPostgresIntegrationTest.java index db72d9c0be..4fb36e4e01 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTerminalSchemaPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionTerminalSchemaPostgresIntegrationTest.java @@ -128,14 +128,12 @@ void forwardRepairPreservesTerminalTriggerAndWorksWithoutWorldInCallerSearchPath // not prove production admission or a successful terminal settlement. assertThatThrownBy(() -> invokeProductionFunctionAgainstTempProbe(source, schema)) .isInstanceOf(SQLException.class) - .satisfies( - failure -> { - SQLException sql = (SQLException) failure; - assertThat(sql.getSQLState()).isEqualTo("23514"); - assertThat(sql.getMessage()) - .contains( - "World EXECUTING state cannot commit without exact terminal settlement"); - }); + .satisfies(failure -> { + SQLException sql = (SQLException) failure; + assertThat(sql.getSQLState()).isEqualTo("23514"); + assertThat(sql.getMessage()) + .contains("World EXECUTING state cannot commit without exact terminal settlement"); + }); assertThat(executionRows(dsl, qualifiedExecutionTable)).isEmpty(); } finally { dsl.execute("DROP SCHEMA IF EXISTS \"" + schema + "\" CASCADE"); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java index 55781f985a..2f9b9e7f9b 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPostgresIntegrationTest.java @@ -93,28 +93,27 @@ void currentDefaultOwnerGuardRefusesFreshExecutionWithoutExactAccountObservation // must reject the incomplete fresh PENDING row before any canonical instance or association // can be written. This direct SQL probe does not establish who could authenticate such a // witness through Account's separate mTLS and currentness path. - assertThatThrownBy( - () -> - dsl.execute( - "INSERT INTO world_canonical_instance_execution (" - + "target_namespace,canonical_tenant_id,control_plane_request_id," - + "canonical_game_instance_id,canonical_world_slug,game_template_id," - + "original_post_authorization_tuple,original_post_authorization_tuple_sha256," - + "account_world_participation_id,account_world_participation_fence," - + "game_session_owner_attempt_id,game_session_owner_fence," - + "preparation_input_digest,preparation_input_json,world_execution_fence,operation_state) " - + "VALUES (?, ?, ?, ?, 'controlled-proof', 1, ?, ?, ?, 1, ?, 1, ?, ?, " - + "nextval('world_canonical_instance_execution_fence_seq'), 'PENDING')", - "world-runtime", - tenant, - requestId, - gameInstance, - tuple, - sha256(tuple), - participation, - attempt, - inputDigest, - inputJson)) + assertThatThrownBy(() -> + dsl.execute( + "INSERT INTO world_canonical_instance_execution (" + + "target_namespace,canonical_tenant_id,control_plane_request_id," + + "canonical_game_instance_id,canonical_world_slug,game_template_id," + + "original_post_authorization_tuple,original_post_authorization_tuple_sha256," + + "account_world_participation_id,account_world_participation_fence," + + "game_session_owner_attempt_id,game_session_owner_fence," + + "preparation_input_digest,preparation_input_json,world_execution_fence,operation_state) " + + "VALUES (?, ?, ?, ?, 'controlled-proof', 1, ?, ?, ?, 1, ?, 1, ?, ?, " + + "nextval('world_canonical_instance_execution_fence_seq'), 'PENDING')", + "world-runtime", + tenant, + requestId, + gameInstance, + tuple, + sha256(tuple), + participation, + attempt, + inputDigest, + inputJson)) .isInstanceOf(DataAccessException.class) .hasMessageContaining( "A fresh World execution intent requires its exact Account owner observation") diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomePostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomePostgresIntegrationTest.java index 6d0af94ec0..2cad58900d 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomePostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomePostgresIntegrationTest.java @@ -338,14 +338,12 @@ void absentReadbackIsUnknownChangedBindingsConflictAndRolledBackAbortLeavesNoRow WorldDraftTerminalOutcomeService service = terminalService(); assertThat(service.readDefinitiveAbort(operation)).isEmpty(); - assertThatThrownBy( - () -> - ownerTransaction() - .execute( - status -> { - terminalRepository().recordDefinitiveAbort(operation); - throw new IllegalStateException("rollback fixture"); - })) + assertThatThrownBy(() -> + ownerTransaction() + .execute(status -> { + terminalRepository().recordDefinitiveAbort(operation); + throw new IllegalStateException("rollback fixture"); + })) .hasMessageContaining("rollback fixture"); assertThat(service.readDefinitiveAbort(operation)).isEmpty(); @@ -463,10 +461,9 @@ void authenticatedMtlsReadReturnsUnknownThenExactAbortAcrossFreezeAndRejectsSubs WorldDraftTerminalReadEvidence.Request.create(NAMESPACE, changedAccount); assertThatThrownBy(() -> client.read(changedBindingRequest)) .isInstanceOf(RuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); freeze(f); var postFreeze = client.read(request); @@ -486,19 +483,17 @@ private Race race(ThrowingRunnable commit, ThrowingRunnable abort) throws Except ExecutorService executor = Executors.newFixedThreadPool(2); try { Future commitFuture = - executor.submit( - () -> { - ready.countDown(); - await(start); - return succeeded(commit); - }); + executor.submit(() -> { + ready.countDown(); + await(start); + return succeeded(commit); + }); Future abortFuture = - executor.submit( - () -> { - ready.countDown(); - await(start); - return succeeded(abort); - }); + executor.submit(() -> { + ready.countDown(); + await(start); + return succeeded(abort); + }); await(ready); start.countDown(); return new Race( @@ -534,18 +529,16 @@ private void assertGuardedUuidTopologyFunctionDenied(WorldDraftGraphApplication } String ownerJson = mapper.writeValueAsString(application.plan().ownerBinding()); String executionJson = mapper.writeValueAsString(executionRevisions); - assertThatThrownBy( - () -> - ownerTransaction() - .execute( - status -> - dsl.resultQuery( - "SELECT world_store_guarded_uuid_topology(" - + "?::jsonb, ?::jsonb, ?::jsonb)", - ownerJson, - application.operation().binding().canonicalJson(), - executionJson) - .fetch())) + assertThatThrownBy(() -> + ownerTransaction() + .execute(status -> + dsl.resultQuery( + "SELECT world_store_guarded_uuid_topology(" + + "?::jsonb, ?::jsonb, ?::jsonb)", + ownerJson, + application.operation().binding().canonicalJson(), + executionJson) + .fetch())) .isInstanceOf(RuntimeException.class) .hasMessageContaining("definitive no-commit"); } @@ -568,30 +561,29 @@ private void insertRetainedUnverifiedHistory( "controlled retained World result history fixture" .getBytes(java.nio.charset.StandardCharsets.UTF_8); ownerTransaction() - .execute( - status -> - dsl.execute( - "INSERT INTO " - + table - + " (request_id,commit_id,version_identity_operation_id,target_namespace," - + "canonical_tenant_id,canonical_version_id,local_tenant_key,local_version_key," - + "owner_binding_json,binding_json,binding_digest,graph_bytes,graph_sha256," - + "result_bytes,storage_status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", - application.operation().requestId(), - application.operation().commitId(), - application.operation().ownerBinding().versionIdentityOperationId(), - application.operation().ownerBinding().targetNamespace(), - application.operation().canonicalTenantId(), - application.operation().canonicalVersionId(), - fixture.intake().localTenantKey(), - fixture.version().localVersionKey(), - mapper.writeValueAsString(application.operation().ownerBinding()), - application.operation().binding().canonicalJson(), - application.operation().binding().digest(), - retainedGraphBytes, - digest(retainedGraphBytes).substring("sha256:".length()), - retainedResultBytes, - "STORED_PERMISSION_UNVERIFIED")); + .execute(status -> + dsl.execute( + "INSERT INTO " + + table + + " (request_id,commit_id,version_identity_operation_id,target_namespace," + + "canonical_tenant_id,canonical_version_id,local_tenant_key,local_version_key," + + "owner_binding_json,binding_json,binding_digest,graph_bytes,graph_sha256," + + "result_bytes,storage_status) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + application.operation().requestId(), + application.operation().commitId(), + application.operation().ownerBinding().versionIdentityOperationId(), + application.operation().ownerBinding().targetNamespace(), + application.operation().canonicalTenantId(), + application.operation().canonicalVersionId(), + fixture.intake().localTenantKey(), + fixture.version().localVersionKey(), + mapper.writeValueAsString(application.operation().ownerBinding()), + application.operation().binding().canonicalJson(), + application.operation().binding().digest(), + retainedGraphBytes, + digest(retainedGraphBytes).substring("sha256:".length()), + retainedResultBytes, + "STORED_PERMISSION_UNVERIFIED")); } private Fixture fixture() { @@ -640,44 +632,43 @@ private Fixture fixture() { intakeRepository.read(NAMESPACE, intakeRequest).orElseThrow(); Fixture created = ownerTransaction() - .execute( - status -> { - UUID versionId = UUID.randomUUID(); - AuthoredWorldVersionStateEvidence.Request stateRequest = - new AuthoredWorldVersionStateEvidence.Request( - 1, - NAMESPACE, - UUID.randomUUID(), - tenant, - worldSlug, - sourceOperation, - sourceDigest, - GAME_DESIGN_VERSION); - WorldAuthoredVersionIdentityReceipt version = - new WorldAuthoredVersionIdentityRepository(dsl) - .acceptFresh( - intake, - AuthoredWorldVersionStateEvidence.create( - stateRequest, - source, - versionId, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, - 1)); - OwnerBinding owner = - new OwnerBinding( - NAMESPACE, - tenant, - versionId, - version.operationId(), - GAME_DESIGN_VERSION, - intakeRequest, - intake.operationId(), - intake.requestDigest(), - sourceOperation, - sourceDigest, - intake.receiptDigest()); - return new Fixture(intake, version, owner); - }); + .execute(status -> { + UUID versionId = UUID.randomUUID(); + AuthoredWorldVersionStateEvidence.Request stateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + tenant, + worldSlug, + sourceOperation, + sourceDigest, + GAME_DESIGN_VERSION); + WorldAuthoredVersionIdentityReceipt version = + new WorldAuthoredVersionIdentityRepository(dsl) + .acceptFresh( + intake, + AuthoredWorldVersionStateEvidence.create( + stateRequest, + source, + versionId, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1)); + OwnerBinding owner = + new OwnerBinding( + NAMESPACE, + tenant, + versionId, + version.operationId(), + GAME_DESIGN_VERSION, + intakeRequest, + intake.operationId(), + intake.requestDigest(), + sourceOperation, + sourceDigest, + intake.receiptDigest()); + return new Fixture(intake, version, owner); + }); return created; } @@ -1006,10 +997,9 @@ private void freeze(Fixture f) { 1, "publish:" + owner.canonicalTenantId() + ":publish-request:" + request); ownerTransaction() - .execute( - status -> - fence.claimFreeze( - evidence, () -> new Checkpoint("synthetic-checkpoint", "b".repeat(64), 3))); + .execute(status -> + fence.claimFreeze( + evidence, () -> new Checkpoint("synthetic-checkpoint", "b".repeat(64), 3))); } private long count(String table, UUID requestId) { diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldExecutionIntentHistoryPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldExecutionIntentHistoryPostgresIntegrationTest.java index 92d0ce739d..3a9d0802f0 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldExecutionIntentHistoryPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldExecutionIntentHistoryPostgresIntegrationTest.java @@ -101,28 +101,25 @@ void originalPendingAndAbortedIntentsRetainBytesWithoutAcquiringAnAccountWitness abort(sql, transaction, abortedAfterIntent); abort(sql, transaction, bornAborted); assertThat(snapshots(sql, seeds)).isEqualTo(after1036); - assertThatThrownBy( - () -> - transaction.execute( - status -> - sql.fetchSingle( - "SELECT world_claim_canonical_instance_execution(?,?,?,?,?,?,?,?)", - pending.inputJson(), - digest(pending.inputJson()), - pending.tupleJson().getBytes(StandardCharsets.UTF_8), - pending.participation(), - 7L, - pending.attempt(), - 9007199254740993L, - pending.instance()))) + assertThatThrownBy(() -> + transaction.execute(status -> + sql.fetchSingle( + "SELECT world_claim_canonical_instance_execution(?,?,?,?,?,?,?,?)", + pending.inputJson(), + digest(pending.inputJson()), + pending.tupleJson().getBytes(StandardCharsets.UTF_8), + pending.participation(), + 7L, + pending.attempt(), + 9007199254740993L, + pending.instance()))) .isInstanceOf(DataAccessException.class) .hasMessageContaining("exact complete owner observation and serialization fence"); - assertThatThrownBy( - () -> - sql.execute( - "UPDATE world_canonical_instance_execution SET game_session_owner_mutation_id = ? WHERE canonical_game_instance_id = ?", - UUID.randomUUID(), - pending.instance())) + assertThatThrownBy(() -> + sql.execute( + "UPDATE world_canonical_instance_execution SET game_session_owner_mutation_id = ? WHERE canonical_game_instance_id = ?", + UUID.randomUUID(), + pending.instance())) .isInstanceOf(DataAccessException.class) .hasMessageContaining("World execution identity and Account owner witness are immutable"); Seed freshWithoutWitness = seed(); @@ -202,39 +199,37 @@ private static Seed seed() { private static long persist(DSLContext sql, TransactionTemplate transaction, Seed seed) { return Objects.requireNonNull( - transaction.execute( - status -> - sql.fetchSingle( - "SELECT world_persist_canonical_instance_execution_intent(?,?,?,?,?,?,?,?)", - seed.inputJson(), - digest(seed.inputJson()), - seed.tupleJson().getBytes(StandardCharsets.UTF_8), - seed.participation(), - 7L, - seed.attempt(), - 9007199254740993L, - seed.instance()) - .get(0, Long.class))); + transaction.execute(status -> + sql.fetchSingle( + "SELECT world_persist_canonical_instance_execution_intent(?,?,?,?,?,?,?,?)", + seed.inputJson(), + digest(seed.inputJson()), + seed.tupleJson().getBytes(StandardCharsets.UTF_8), + seed.participation(), + 7L, + seed.attempt(), + 9007199254740993L, + seed.instance()) + .get(0, Long.class))); } private static void abort(DSLContext sql, TransactionTemplate transaction, Seed seed) { var result = Objects.requireNonNull( - transaction.execute( - status -> - sql.fetchSingle( - "SELECT * FROM world_abort_canonical_instance_execution(?,?,?,?,?,?,?,?,?,?,?)", - NAMESPACE, - seed.tenant(), - seed.request(), - seed.instance(), - seed.inputJson(), - digest(seed.inputJson()), - seed.tupleJson().getBytes(StandardCharsets.UTF_8), - seed.participation(), - 7L, - seed.attempt(), - 9007199254740993L))); + transaction.execute(status -> + sql.fetchSingle( + "SELECT * FROM world_abort_canonical_instance_execution(?,?,?,?,?,?,?,?,?,?,?)", + NAMESPACE, + seed.tenant(), + seed.request(), + seed.instance(), + seed.inputJson(), + digest(seed.inputJson()), + seed.tupleJson().getBytes(StandardCharsets.UTF_8), + seed.participation(), + 7L, + seed.attempt(), + 9007199254740993L))); assertThat(result.get("operation_state", String.class)).isEqualTo("ABORTED"); assertThat(result.get("world_execution_fence", Long.class)).isPositive(); assertThat(result.get("world_instance_id", Long.class)).isNull(); @@ -255,17 +250,16 @@ private static Map snapshots(DSLContext sql, List seeds) { } private static void assertOriginalRows(DSLContext sql, Map before) { - before.forEach( - (id, snapshot) -> { - var row = - sql.fetchSingle( - "SELECT (to_jsonb(e) - ?::text[]) = ?::jsonb AS original, xmin::text AS xmin FROM world_canonical_instance_execution e WHERE canonical_game_instance_id = ?", - WITNESS_COLUMNS.toArray(String[]::new), - snapshot.json(), - id); - assertThat(row.get("original", Boolean.class)).isTrue(); - assertThat(row.get("xmin", String.class)).isEqualTo(snapshot.xmin()); - }); + before.forEach((id, snapshot) -> { + var row = + sql.fetchSingle( + "SELECT (to_jsonb(e) - ?::text[]) = ?::jsonb AS original, xmin::text AS xmin FROM world_canonical_instance_execution e WHERE canonical_game_instance_id = ?", + WITNESS_COLUMNS.toArray(String[]::new), + snapshot.json(), + id); + assertThat(row.get("original", Boolean.class)).isTrue(); + assertThat(row.get("xmin", String.class)).isEqualTo(snapshot.xmin()); + }); } private static void assertNoWitness(DSLContext sql) { diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java index 314ae18205..df0084622c 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java @@ -340,13 +340,12 @@ private static void assertDigestPredicates(FunctionMetadata graph, FunctionMetad private static void assertCanonicalInitialAdmissionHoldLifecycleGuard( DSLContext dsl, String schema) { assertThat(triggerMetadata(dsl, schema, "world_instance")) - .anySatisfy( - trigger -> { - assertThat(trigger) - .contains("aaa_world_canonical_initial_admission_hold_lifecycle") - .contains("world_guard_canonical_initial_admission_hold_lifecycle"); - assertThat(trigger.split(":", 8)[4]).isIn("O", "A"); - }); + .anySatisfy(trigger -> { + assertThat(trigger) + .contains("aaa_world_canonical_initial_admission_hold_lifecycle") + .contains("world_guard_canonical_initial_admission_hold_lifecycle"); + assertThat(trigger.split(":", 8)[4]).isIn("O", "A"); + }); } private static void cloneProbeTables(DSLContext dsl, String sourceSchema, String probeSchema) { @@ -442,129 +441,128 @@ private static void persistFixture( byte[] resultBytes = resultBytes(fixture, receiptBytes, receiptDigest); String correctResultDigest = digest(resultBytes); - dsl.transaction( - configuration -> { - DSLContext tx = DSL.using(configuration); - String commitTable = DSL.name(schema, "world_topology_draft_commit").toString(); - String ownerTable = DSL.name(schema, "world_design_publication_fence_owner").toString(); - String roomTable = DSL.name(schema, "room").toString(); - String identityTable = DSL.name(schema, "world_authored_topology_identity").toString(); - String receiptTable = DSL.name(schema, "world_draft_start_location_receipt").toString(); - String applicationTable = DSL.name(schema, "world_draft_graph_application").toString(); - - tx.execute( - "INSERT INTO " - + commitTable - + " (request_id, commit_id, target_namespace, canonical_tenant_id, " - + "canonical_version_id, local_tenant_key, local_version_key, binding_json, " - + "binding_digest, graph_bytes, graph_sha256, application_transaction_id) " - + "VALUES (?, ?, 'dev', ?, ?, ?, ?, ?::jsonb, ?, ?, ?, txid_current())", - fixture.requestId(), - fixture.commitId(), - fixture.tenantId(), - fixture.versionId(), - fixture.localTenantKey(), - fixture.localVersionKey(), - fixture.bindingJson(), - fixture.bindingDigest(), - fixture.graphBytes(), - fixture.graphSha256()); - tx.execute( - "INSERT INTO " - + ownerTable - + " (target_namespace, canonical_tenant_id, local_tenant_key, version_id, " - + "owner_freeze_phase, current_publication_fence) " - + "VALUES ('dev', ?, ?, ?, 'OPEN', NULL)", - fixture.tenantId(), - fixture.localTenantKey(), - fixture.localVersionKey()); - tx.execute( - "INSERT INTO " + roomTable + " (id, tenant_id, version_id) VALUES (?, ?, ?)", - fixture.roomRowId(), - fixture.localTenantKey(), - fixture.localVersionKey()); - tx.execute( - "INSERT INTO " - + identityTable - + " (target_namespace, canonical_tenant_id, canonical_version_id, family, " - + "template_id, private_row_key, tenant_id, version_id, " - + "version_identity_operation_id, request_id, commit_id, revision_id, revision_order) " - + "VALUES ('dev', ?, ?, 'ROOM', ?, ?, ?, ?, ?, ?, ?, ?, '0')", - fixture.tenantId(), - fixture.versionId(), - fixture.roomTemplateId(), - fixture.roomRowId(), - fixture.localTenantKey(), - fixture.localVersionKey(), - fixture.versionIdentityOperationId(), - fixture.requestId(), - fixture.commitId(), - fixture.revisionId()); - - String receiptAccountDigest = - corruption == Corruption.RECEIPT_ACCOUNT_DIGEST - ? wrongDigest(fixture.accountBindingDigest()) - : fixture.accountBindingDigest(); - boolean bypassReceiptGuard = corruption == Corruption.APPLICATION_RECEIPT_FIELD_MISMATCH; - if (bypassReceiptGuard) { - tx.execute( - "ALTER TABLE " - + receiptTable - + " DISABLE TRIGGER trg_world_start_location_receipt_guard"); - } - tx.execute( - "INSERT INTO " - + receiptTable - + " (operation_id, request_id, commit_id, authorization_fence_id, " - + "target_namespace, account_binding_bytes, account_binding_digest, binding_digest, " - + "canonical_tenant_id, canonical_version_id, room_template_id, graph_digest, " - + "receipt_digest, receipt_bytes) " - + "VALUES (?, ?, ?, ?, 'dev', ?, ?, ?, ?, ?, ?, ?, ?, ?)", - fixture.operationId(), - fixture.requestId(), - fixture.commitId(), - fixture.authorizationFenceId(), - fixture.accountBindingBytes(), - receiptAccountDigest, - fixture.bindingDigest(), - fixture.tenantId(), - fixture.versionId(), - fixture.roomTemplateId(), - fixture.graphDigest(), - receiptDigest, - receiptBytes); - if (bypassReceiptGuard) { - tx.execute( - "ALTER TABLE " - + receiptTable - + " ENABLE TRIGGER trg_world_start_location_receipt_guard"); - } - - String applicationAccountDigest = - corruption == Corruption.APPLICATION_ACCOUNT_DIGEST - ? wrongDigest(fixture.accountBindingDigest()) - : fixture.accountBindingDigest(); - String resultDigest = - corruption == Corruption.RESULT_DIGEST - ? wrongDigest(correctResultDigest) - : correctResultDigest; - tx.execute( - "INSERT INTO " - + applicationTable - + " (operation_id, request_id, commit_id, authorization_fence_id, " - + "operation_bytes, account_binding_bytes, account_binding_digest, result_bytes, " - + "result_digest, application_transaction_id) " - + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, txid_current())", - fixture.operationId(), - fixture.requestId(), - fixture.commitId(), - fixture.authorizationFenceId(), - fixture.operationBytes(), - fixture.accountBindingBytes(), - applicationAccountDigest, - resultBytes, - resultDigest); - }); + dsl.transaction(configuration -> { + DSLContext tx = DSL.using(configuration); + String commitTable = DSL.name(schema, "world_topology_draft_commit").toString(); + String ownerTable = DSL.name(schema, "world_design_publication_fence_owner").toString(); + String roomTable = DSL.name(schema, "room").toString(); + String identityTable = DSL.name(schema, "world_authored_topology_identity").toString(); + String receiptTable = DSL.name(schema, "world_draft_start_location_receipt").toString(); + String applicationTable = DSL.name(schema, "world_draft_graph_application").toString(); + + tx.execute( + "INSERT INTO " + + commitTable + + " (request_id, commit_id, target_namespace, canonical_tenant_id, " + + "canonical_version_id, local_tenant_key, local_version_key, binding_json, " + + "binding_digest, graph_bytes, graph_sha256, application_transaction_id) " + + "VALUES (?, ?, 'dev', ?, ?, ?, ?, ?::jsonb, ?, ?, ?, txid_current())", + fixture.requestId(), + fixture.commitId(), + fixture.tenantId(), + fixture.versionId(), + fixture.localTenantKey(), + fixture.localVersionKey(), + fixture.bindingJson(), + fixture.bindingDigest(), + fixture.graphBytes(), + fixture.graphSha256()); + tx.execute( + "INSERT INTO " + + ownerTable + + " (target_namespace, canonical_tenant_id, local_tenant_key, version_id, " + + "owner_freeze_phase, current_publication_fence) " + + "VALUES ('dev', ?, ?, ?, 'OPEN', NULL)", + fixture.tenantId(), + fixture.localTenantKey(), + fixture.localVersionKey()); + tx.execute( + "INSERT INTO " + roomTable + " (id, tenant_id, version_id) VALUES (?, ?, ?)", + fixture.roomRowId(), + fixture.localTenantKey(), + fixture.localVersionKey()); + tx.execute( + "INSERT INTO " + + identityTable + + " (target_namespace, canonical_tenant_id, canonical_version_id, family, " + + "template_id, private_row_key, tenant_id, version_id, " + + "version_identity_operation_id, request_id, commit_id, revision_id, revision_order) " + + "VALUES ('dev', ?, ?, 'ROOM', ?, ?, ?, ?, ?, ?, ?, ?, '0')", + fixture.tenantId(), + fixture.versionId(), + fixture.roomTemplateId(), + fixture.roomRowId(), + fixture.localTenantKey(), + fixture.localVersionKey(), + fixture.versionIdentityOperationId(), + fixture.requestId(), + fixture.commitId(), + fixture.revisionId()); + + String receiptAccountDigest = + corruption == Corruption.RECEIPT_ACCOUNT_DIGEST + ? wrongDigest(fixture.accountBindingDigest()) + : fixture.accountBindingDigest(); + boolean bypassReceiptGuard = corruption == Corruption.APPLICATION_RECEIPT_FIELD_MISMATCH; + if (bypassReceiptGuard) { + tx.execute( + "ALTER TABLE " + + receiptTable + + " DISABLE TRIGGER trg_world_start_location_receipt_guard"); + } + tx.execute( + "INSERT INTO " + + receiptTable + + " (operation_id, request_id, commit_id, authorization_fence_id, " + + "target_namespace, account_binding_bytes, account_binding_digest, binding_digest, " + + "canonical_tenant_id, canonical_version_id, room_template_id, graph_digest, " + + "receipt_digest, receipt_bytes) " + + "VALUES (?, ?, ?, ?, 'dev', ?, ?, ?, ?, ?, ?, ?, ?, ?)", + fixture.operationId(), + fixture.requestId(), + fixture.commitId(), + fixture.authorizationFenceId(), + fixture.accountBindingBytes(), + receiptAccountDigest, + fixture.bindingDigest(), + fixture.tenantId(), + fixture.versionId(), + fixture.roomTemplateId(), + fixture.graphDigest(), + receiptDigest, + receiptBytes); + if (bypassReceiptGuard) { + tx.execute( + "ALTER TABLE " + + receiptTable + + " ENABLE TRIGGER trg_world_start_location_receipt_guard"); + } + + String applicationAccountDigest = + corruption == Corruption.APPLICATION_ACCOUNT_DIGEST + ? wrongDigest(fixture.accountBindingDigest()) + : fixture.accountBindingDigest(); + String resultDigest = + corruption == Corruption.RESULT_DIGEST + ? wrongDigest(correctResultDigest) + : correctResultDigest; + tx.execute( + "INSERT INTO " + + applicationTable + + " (operation_id, request_id, commit_id, authorization_fence_id, " + + "operation_bytes, account_binding_bytes, account_binding_digest, result_bytes, " + + "result_digest, application_transaction_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, txid_current())", + fixture.operationId(), + fixture.requestId(), + fixture.commitId(), + fixture.authorizationFenceId(), + fixture.operationBytes(), + fixture.accountBindingBytes(), + applicationAccountDigest, + resultBytes, + resultDigest); + }); } private static Fixture fixture() throws Exception { @@ -676,13 +674,12 @@ private static byte[] resultBytes( private static String bindingJson(UUID tenantId, UUID versionId, UUID roomTemplateId) { String familyCounts = FAMILY_NAMES.stream() - .map( - family -> - "{\"family\":\"WORLD_DESIGN_AGGREGATE_TYPE_" - + family - + "\",\"count\":" - + (family.equals("ROOM") ? 1 : 0) - + "}") + .map(family -> + "{\"family\":\"WORLD_DESIGN_AGGREGATE_TYPE_" + + family + + "\",\"count\":" + + (family.equals("ROOM") ? 1 : 0) + + "}") .reduce((left, right) -> left + "," + right) .orElseThrow(); return "{\"revisions\":[{\"owner\":\"WORLD_MANAGEMENT\",\"payload\":{" @@ -787,13 +784,12 @@ private static String wrongDigest(String digest) { private static void assertSqlState( org.assertj.core.api.ThrowableAssert.ThrowingCallable action, String state) { assertThatThrownBy(action) - .satisfies( - failure -> { - Throwable cause = failure; - while (cause.getCause() != null) cause = cause.getCause(); - assertThat(cause).isInstanceOf(PSQLException.class); - assertThat(((PSQLException) cause).getSQLState()).isEqualTo(state); - }); + .satisfies(failure -> { + Throwable cause = failure; + while (cause.getCause() != null) cause = cause.getCause(); + assertThat(cause).isInstanceOf(PSQLException.class); + assertThat(((PSQLException) cause).getSQLState()).isEqualTo(state); + }); } private static DriverManagerDataSource source(String schema) { diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java index f259c0601c..b6322be610 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGuardedAuthoredGraphCapturePostgresIntegrationTest.java @@ -318,11 +318,10 @@ void exactParentWithRetainedOwnerAndLegacyWorldRowsUpgradesToHistoricalGuardedFr first.rollback(); } } - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM world_authored_source_intake WHERE operation_id = ?", - source.operationId())) + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM world_authored_source_intake WHERE operation_id = ?", + source.operationId())) .hasMessageContaining("immutable"); assertThat( retainedRows( @@ -359,10 +358,9 @@ void schemaTwoRepositorySnapshotRetainsEveryOriginalByteAndXminThroughSchemaThre UUID intakeRequest = UUID.randomUUID(); WorldAuthoredSourceIntakeReceipt intake = Objects.requireNonNull( - write.execute( - status -> - new WorldAuthoredSourceIntakeRepository(dsl) - .acceptFresh(NAMESPACE, intakeRequest, upstream))); + write.execute(status -> + new WorldAuthoredSourceIntakeRepository(dsl) + .acceptFresh(NAMESPACE, intakeRequest, upstream))); UUID canonicalVersion = UUID.randomUUID(); long gameDesignVersion = 43L; var versionState = @@ -382,10 +380,9 @@ void schemaTwoRepositorySnapshotRetainsEveryOriginalByteAndXminThroughSchemaThre 1L); WorldAuthoredVersionIdentityReceipt version = Objects.requireNonNull( - write.execute( - status -> - new WorldAuthoredVersionIdentityRepository(dsl) - .acceptFresh(intake, versionState))); + write.execute(status -> + new WorldAuthoredVersionIdentityRepository(dsl) + .acceptFresh(intake, versionState))); String publicationRequest = "retained-schema2-repository"; String requestDigest = "b".repeat(64); @@ -422,13 +419,12 @@ void schemaTwoRepositorySnapshotRetainsEveryOriginalByteAndXminThroughSchemaThre // authority is inferred from it. var frozen = Objects.requireNonNull( - write.execute( - status -> - fenceRepository.claimFreeze( - publication, - () -> - new WorldDesignPublicationFenceEvidence.Checkpoint( - legacyCheckpoint, contentDigest, 2)))); + write.execute(status -> + fenceRepository.claimFreeze( + publication, + () -> + new WorldDesignPublicationFenceEvidence.Checkpoint( + legacyCheckpoint, contentDigest, 2)))); var request = new WorldAuthoredGraphSnapshot.CaptureRequest( NAMESPACE, @@ -466,42 +462,41 @@ void schemaTwoRepositorySnapshotRetainsEveryOriginalByteAndXminThroughSchemaThre String captureRequestDigest = retainedCaptureRequestDigest(request, intake, version); WorldAuthoredGraphSnapshot stored = Objects.requireNonNull( - write.execute( - status -> { - var provenance = snapshotRepository.lockAndResolve(request); - return snapshotRepository.insertAndReadback( - new WorldAuthoredGraphSnapshot( - UUID.randomUUID(), - provenance.targetNamespace(), - provenance.canonicalTenantId(), - provenance.canonicalVersionId(), - provenance.versionIdentityOperationId(), - provenance.worldSlug(), - provenance.gameDesignVersionId(), - provenance.localVersionKey(), - provenance.localTenantKey(), - (short) 1, - provenance.intakeOperationId(), - provenance.intakeRequestId(), - provenance.intakeRequestDigest(), - provenance.sourceOperationId(), - provenance.sourceEvidenceDigest(), - provenance.intakeReceiptDigest(), - frozen.publicationFence(), - publicationRequest, - requestDigest, - 1L, - workflow, - legacyCheckpoint, - contentDigest, - 2, - captureRequestDigest, - "[]", - "[]", - graphBytes, - WorldAuthoredGraphSnapshotCapture.sha256(graphBytes), - WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED)); - })); + write.execute(status -> { + var provenance = snapshotRepository.lockAndResolve(request); + return snapshotRepository.insertAndReadback( + new WorldAuthoredGraphSnapshot( + UUID.randomUUID(), + provenance.targetNamespace(), + provenance.canonicalTenantId(), + provenance.canonicalVersionId(), + provenance.versionIdentityOperationId(), + provenance.worldSlug(), + provenance.gameDesignVersionId(), + provenance.localVersionKey(), + provenance.localTenantKey(), + (short) 1, + provenance.intakeOperationId(), + provenance.intakeRequestId(), + provenance.intakeRequestDigest(), + provenance.sourceOperationId(), + provenance.sourceEvidenceDigest(), + provenance.intakeReceiptDigest(), + frozen.publicationFence(), + publicationRequest, + requestDigest, + 1L, + workflow, + legacyCheckpoint, + contentDigest, + 2, + captureRequestDigest, + "[]", + "[]", + graphBytes, + WorldAuthoredGraphSnapshotCapture.sha256(graphBytes), + WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED)); + })); List columns = dsl.fetch( "SELECT column_name FROM information_schema.columns " @@ -615,10 +610,9 @@ void currentTopologyWriterCommitsBeforeFreezeCheckpointAndFrozenRetryRetainsRows var upstream = controlledSource(); var intake = Objects.requireNonNull( - write.execute( - status -> - new WorldAuthoredSourceIntakeRepository(dsl) - .acceptFresh(NAMESPACE, UUID.randomUUID(), upstream))); + write.execute(status -> + new WorldAuthoredSourceIntakeRepository(dsl) + .acceptFresh(NAMESPACE, UUID.randomUUID(), upstream))); var state = AuthoredWorldVersionStateEvidence.create( new AuthoredWorldVersionStateEvidence.Request( @@ -636,9 +630,8 @@ void currentTopologyWriterCommitsBeforeFreezeCheckpointAndFrozenRetryRetainsRows 1L); var version = Objects.requireNonNull( - write.execute( - status -> - new WorldAuthoredVersionIdentityRepository(dsl).acceptFresh(intake, state))); + write.execute(status -> + new WorldAuthoredVersionIdentityRepository(dsl).acceptFresh(intake, state))); var fence = new WorldDesignPublicationFenceRepository( dsl, new WorldAuthoredSourceIntakeRepository(dsl)); @@ -700,76 +693,71 @@ void currentTopologyWriterCommitsBeforeFreezeCheckpointAndFrozenRetryRetainsRows WorldDesignPublicationFenceEvidence.FrozenAttempt frozen; try { Future writer = - executor.submit( - () -> - write.execute( - status -> { - writerBackendPid.set( - dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); - var stored = topology.store(plan); - storedReference.set(stored); - writerStored.countDown(); - await(releaseWriter); - return stored; - })); + executor.submit(() -> + write.execute(status -> { + writerBackendPid.set( + dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + var stored = topology.store(plan); + storedReference.set(stored); + writerStored.countDown(); + await(releaseWriter); + return stored; + })); await(writerStored); Future freeze = - executor.submit( - () -> - write.execute( - status -> { - freezeBackendPid.set( - dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); - freezeStarted.countDown(); - return fence.claimFreeze( - publication, - () -> { - checkpointCaptured.set(true); - var committed = - Objects.requireNonNull(storedReference.get(), "writer result"); - var committedRow = - dsl.fetchOne( - "SELECT graph_bytes, graph_sha256, result_bytes " - + "FROM world_topology_draft_commit WHERE request_id=?", - plan.binding().requestId()); - assertThat(committedRow) - .as("writer topology must be committed before checkpoint read") - .isNotNull(); - assertThat(committedRow.get("graph_bytes", byte[].class)) - .containsExactly(committed.graphBytes()); - assertThat(committedRow.get("result_bytes", byte[].class)) - .containsExactly(committed.resultBytes()); - assertThat(committedRow.get("graph_sha256", String.class)) - .isEqualTo( - WorldAuthoredGraphSnapshotCapture.sha256( - committed.graphBytes())); - for (var familyAndCount : expectedFamilyCounts.entrySet()) { - String family = familyAndCount.getKey(); - assertThat( - dsl.fetchSingle( - "SELECT count(*) FROM " - + family - + " WHERE tenant_id=? AND version_id=?", - intake.localTenantKey(), - version.localVersionKey()) - .get(0, Long.class)) - .as("committed authored family %s", family) - .isEqualTo(familyAndCount.getValue()); - } - var observed = - digest.getDraftDesignDigest( - Long.toString(intake.localTenantKey()), - Long.toString(version.localVersionKey())); - var checkpoint = - new WorldDesignPublicationFenceEvidence.Checkpoint( - observed.appliedCommitId(), - observed.contentDigest(), - observed.digestSchemaVersion()); - checkpointReference.set(checkpoint); - return checkpoint; - }); - })); + executor.submit(() -> + write.execute(status -> { + freezeBackendPid.set( + dsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + freezeStarted.countDown(); + return fence.claimFreeze( + publication, + () -> { + checkpointCaptured.set(true); + var committed = + Objects.requireNonNull(storedReference.get(), "writer result"); + var committedRow = + dsl.fetchOne( + "SELECT graph_bytes, graph_sha256, result_bytes " + + "FROM world_topology_draft_commit WHERE request_id=?", + plan.binding().requestId()); + assertThat(committedRow) + .as("writer topology must be committed before checkpoint read") + .isNotNull(); + assertThat(committedRow.get("graph_bytes", byte[].class)) + .containsExactly(committed.graphBytes()); + assertThat(committedRow.get("result_bytes", byte[].class)) + .containsExactly(committed.resultBytes()); + assertThat(committedRow.get("graph_sha256", String.class)) + .isEqualTo( + WorldAuthoredGraphSnapshotCapture.sha256(committed.graphBytes())); + for (var familyAndCount : expectedFamilyCounts.entrySet()) { + String family = familyAndCount.getKey(); + assertThat( + dsl.fetchSingle( + "SELECT count(*) FROM " + + family + + " WHERE tenant_id=? AND version_id=?", + intake.localTenantKey(), + version.localVersionKey()) + .get(0, Long.class)) + .as("committed authored family %s", family) + .isEqualTo(familyAndCount.getValue()); + } + var observed = + digest.getDraftDesignDigest( + Long.toString(intake.localTenantKey()), + Long.toString(version.localVersionKey())); + var checkpoint = + new WorldDesignPublicationFenceEvidence.Checkpoint( + observed.appliedCommitId(), + observed.contentDigest(), + observed.digestSchemaVersion()); + checkpointReference.set(checkpoint); + return checkpoint; + }); + })); await(freezeStarted); awaitOwnerRowLockWait( dsl, @@ -877,10 +865,9 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin var upstream = controlledSource(); var intake = Objects.requireNonNull( - write.execute( - status -> - new WorldAuthoredSourceIntakeRepository(dsl) - .acceptFresh(NAMESPACE, UUID.randomUUID(), upstream))); + write.execute(status -> + new WorldAuthoredSourceIntakeRepository(dsl) + .acceptFresh(NAMESPACE, UUID.randomUUID(), upstream))); var state = AuthoredWorldVersionStateEvidence.create( new AuthoredWorldVersionStateEvidence.Request( @@ -898,9 +885,8 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin 1L); var version = Objects.requireNonNull( - write.execute( - status -> - new WorldAuthoredVersionIdentityRepository(dsl).acceptFresh(intake, state))); + write.execute(status -> + new WorldAuthoredVersionIdentityRepository(dsl).acceptFresh(intake, state))); var fence = new WorldDesignPublicationFenceRepository( dsl, new WorldAuthoredSourceIntakeRepository(dsl)); @@ -932,11 +918,9 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin // graph/codec proof only: it does not supply the missing V19 complete-commit history. var authored = Objects.requireNonNull( - write.execute( - status -> - new WorldAuthoredGraphReader(dsl) - .readAndValidateGraph( - intake.localTenantKey(), version.localVersionKey()))); + write.execute(status -> + new WorldAuthoredGraphReader(dsl) + .readAndValidateGraph(intake.localTenantKey(), version.localVersionKey()))); var spawnRow = dsl.fetchSingle( "SELECT entity_template_id, entity_canonical_tenant_id, entity_canonical_version_id, " @@ -1027,11 +1011,9 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin List rowsBefore = dsl.fetch("SELECT to_jsonb(t)::text FROM world_topology_draft_commit t") .getValues(0, String.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE region SET name = 'naked' WHERE tenant_id = ?", - intake.localTenantKey())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE region SET name = 'naked' WHERE tenant_id = ?", intake.localTenantKey())) .isInstanceOf(org.jooq.exception.DataAccessException.class); assertThat(topology.readCommitted(plan).orElseThrow().resultBytes()) .isEqualTo(stored.resultBytes()); @@ -1076,26 +1058,24 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin // APPLIED. var frozen = Objects.requireNonNull( - write.execute( - status -> - fence.claimFreeze( - publication, - () -> - new WorldDesignPublicationFenceEvidence.Checkpoint( - actual.appliedCommitId(), - actual.contentDigest(), - actual.digestSchemaVersion())))); + write.execute(status -> + fence.claimFreeze( + publication, + () -> + new WorldDesignPublicationFenceEvidence.Checkpoint( + actual.appliedCommitId(), + actual.contentDigest(), + actual.digestSchemaVersion())))); var tuples = plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - u -> - new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( - u.owner().name(), - u.aggregateType(), - u.aggregateId(), - u.scopeType(), - u.scopeId(), - u.expectedEpoch())) + .map(u -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + u.owner().name(), + u.aggregateType(), + u.aggregateId(), + u.scopeType(), + u.scopeId(), + u.expectedEpoch())) .toList(); var capture = new WorldAuthoredGraphSnapshot.CaptureRequest( @@ -1147,30 +1127,28 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin capture.contentDigest(), 2, capture.suppliedOwnedAffectedTuples()); - assertThatThrownBy( - () -> - insertCanonicalFrozenCandidate( - dsl, - plan, - capture, - stored, - mapper.writeValueAsString(schemaTwoCapture), - identityJson, - intakeJson)) + assertThatThrownBy(() -> + insertCanonicalFrozenCandidate( + dsl, + plan, + capture, + stored, + mapper.writeValueAsString(schemaTwoCapture), + identityJson, + intakeJson)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("New canonical graph capture requires digest schema 3") .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("23514")); - assertThatThrownBy( - () -> - insertCanonicalFrozenCandidate( - dsl, - plan, - capture, - stored, - "{\"digestSchemaVersion\":3}", - identityJson, - intakeJson)) + assertThatThrownBy(() -> + insertCanonicalFrozenCandidate( + dsl, + plan, + capture, + stored, + "{\"digestSchemaVersion\":3}", + identityJson, + intakeJson)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("Canonical frozen capture differs") .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("23514")); @@ -1190,16 +1168,15 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin capture.contentDigest(), capture.digestSchemaVersion(), capture.suppliedOwnedAffectedTuples()); - assertThatThrownBy( - () -> - insertCanonicalFrozenCandidate( - dsl, - plan, - capture, - stored, - mapper.writeValueAsString(changedCheckpointCapture), - identityJson, - intakeJson)) + assertThatThrownBy(() -> + insertCanonicalFrozenCandidate( + dsl, + plan, + capture, + stored, + mapper.writeValueAsString(changedCheckpointCapture), + identityJson, + intakeJson)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("Canonical frozen capture differs") .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("23514")); @@ -1211,20 +1188,18 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin // Row-level V1006 UPDATE/DELETE guards cannot fire on an empty frozen table. Verify their // installed shared-function bindings, and exercise UPDATE/DELETE on retained source rows. - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE world_authored_source_intake SET tenant_slug=tenant_slug " - + "WHERE operation_id=?", - intake.operationId())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE world_authored_source_intake SET tenant_slug=tenant_slug " + + "WHERE operation_id=?", + intake.operationId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("immutable") .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("55000")); - assertThatThrownBy( - () -> - dsl.execute( - "DELETE FROM world_authored_source_intake WHERE operation_id=?", - intake.operationId())) + assertThatThrownBy(() -> + dsl.execute( + "DELETE FROM world_authored_source_intake WHERE operation_id=?", + intake.operationId())) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("immutable") .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("55000")); @@ -1279,11 +1254,10 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin + "WHERE tenant_id=? ORDER BY id", intake.localTenantKey()) .getValues(0, String.class); - assertThatThrownBy( - () -> - dsl.execute( - "UPDATE region SET name='naked at current frontier' WHERE tenant_id=?", - intake.localTenantKey())) + assertThatThrownBy(() -> + dsl.execute( + "UPDATE region SET name='naked at current frontier' WHERE tenant_id=?", + intake.localTenantKey())) .isInstanceOf(org.jooq.exception.DataAccessException.class) .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("23514")); assertThat( @@ -1297,16 +1271,15 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin assertThatThrownBy(() -> write.execute(status -> graphCapture.capture(capture))) .isInstanceOf(WorldAuthoredGraphSnapshotRepository.MissingOwnerHistoryException.class) .hasMessageContaining("retained V19 revision history"); - assertThatThrownBy( - () -> - insertCanonicalFrozenCandidate( - dsl, - plan, - schemaTwoCapture, - stored, - mapper.writeValueAsString(schemaTwoCapture), - identityJson, - intakeJson)) + assertThatThrownBy(() -> + insertCanonicalFrozenCandidate( + dsl, + plan, + schemaTwoCapture, + stored, + mapper.writeValueAsString(schemaTwoCapture), + identityJson, + intakeJson)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("New canonical graph capture requires selected closure schema 4") .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("23514")); @@ -1317,16 +1290,15 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin var currentMatchingCheckpointFreezeRequest = (tools.jackson.databind.node.ObjectNode) mapper.valueToTree(capture); currentMatchingCheckpointFreezeRequest.put("digestSchemaVersion", 4); - assertThatThrownBy( - () -> - insertCanonicalFrozenCandidate( - dsl, - plan, - capture, - stored, - mapper.writeValueAsString(currentMatchingCheckpointFreezeRequest), - identityJson, - intakeJson)) + assertThatThrownBy(() -> + insertCanonicalFrozenCandidate( + dsl, + plan, + capture, + stored, + mapper.writeValueAsString(currentMatchingCheckpointFreezeRequest), + identityJson, + intakeJson)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("differs from exact FROZEN source and checkpoint") .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("23514")); @@ -1350,16 +1322,15 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin (tools.jackson.databind.node.ObjectNode) mapper.valueToTree(currentWrongCheckpointCapture); currentWrongCheckpointFreezeRequest.put("digestSchemaVersion", 4); - assertThatThrownBy( - () -> - insertCanonicalFrozenCandidate( - dsl, - plan, - currentWrongCheckpointCapture, - stored, - mapper.writeValueAsString(currentWrongCheckpointFreezeRequest), - identityJson, - intakeJson)) + assertThatThrownBy(() -> + insertCanonicalFrozenCandidate( + dsl, + plan, + currentWrongCheckpointCapture, + stored, + mapper.writeValueAsString(currentWrongCheckpointFreezeRequest), + identityJson, + intakeJson)) .isInstanceOf(org.jooq.exception.DataAccessException.class) .hasMessageContaining("differs from exact FROZEN source and checkpoint") .satisfies(exception -> assertThat(sqlState(exception)).isEqualTo("23514")); @@ -1378,182 +1349,168 @@ void historicalGuardedStoreReplaysAndRejectsNakedWritesAndMissingCommitCheckpoin @Test void currentTopologyLateFailureRollsBackEveryOwnerRowBeforeExactRetry() throws Exception { - withCurrentStorageOwner( - fixture -> { - var dsl = fixture.dsl(); - var topology = fixture.topology(); - var plan = fixture.plan(); - Map> before = - retainedTableSnapshot(dsl, fixture.schema(), currentStorageTables()); - assertThatThrownBy( - () -> - fixture - .write() - .execute( - status -> { - topology.store(plan); - throw new IllegalStateException("late controlled storage failure"); - })) - .isInstanceOf(IllegalStateException.class) - .hasMessage("late controlled storage failure"); - assertThat(retainedTableSnapshot(dsl, fixture.schema(), currentStorageTables())) - .isEqualTo(before); - assertThat(topology.readCommitted(plan)).isEmpty(); + withCurrentStorageOwner(fixture -> { + var dsl = fixture.dsl(); + var topology = fixture.topology(); + var plan = fixture.plan(); + Map> before = + retainedTableSnapshot(dsl, fixture.schema(), currentStorageTables()); + assertThatThrownBy(() -> + fixture + .write() + .execute(status -> { + topology.store(plan); + throw new IllegalStateException("late controlled storage failure"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("late controlled storage failure"); + assertThat(retainedTableSnapshot(dsl, fixture.schema(), currentStorageTables())) + .isEqualTo(before); + assertThat(topology.readCommitted(plan)).isEmpty(); - var stored = - Objects.requireNonNull(fixture.write().execute(status -> topology.store(plan))); - assertThat(stored.status()).isEqualTo("STORED_PERMISSION_UNVERIFIED"); - assertCompleteCurrentStorage(fixture); - Map> committed = - retainedTableSnapshot(dsl, fixture.schema(), currentStorageTables()); - var retried = - Objects.requireNonNull(fixture.write().execute(status -> topology.store(plan))); - var readback = topology.readCommitted(plan).orElseThrow(); - assertThat(retried.graphBytes()).containsExactly(stored.graphBytes()); - assertThat(retried.resultBytes()).containsExactly(stored.resultBytes()); - assertThat(readback.graphBytes()).containsExactly(stored.graphBytes()); - assertThat(readback.resultBytes()).containsExactly(stored.resultBytes()); - assertThat(retainedTableSnapshot(dsl, fixture.schema(), currentStorageTables())) - .isEqualTo(committed); - }); + var stored = Objects.requireNonNull(fixture.write().execute(status -> topology.store(plan))); + assertThat(stored.status()).isEqualTo("STORED_PERMISSION_UNVERIFIED"); + assertCompleteCurrentStorage(fixture); + Map> committed = + retainedTableSnapshot(dsl, fixture.schema(), currentStorageTables()); + var retried = Objects.requireNonNull(fixture.write().execute(status -> topology.store(plan))); + var readback = topology.readCommitted(plan).orElseThrow(); + assertThat(retried.graphBytes()).containsExactly(stored.graphBytes()); + assertThat(retried.resultBytes()).containsExactly(stored.resultBytes()); + assertThat(readback.graphBytes()).containsExactly(stored.graphBytes()); + assertThat(readback.resultBytes()).containsExactly(stored.resultBytes()); + assertThat(retainedTableSnapshot(dsl, fixture.schema(), currentStorageTables())) + .isEqualTo(committed); + }); } @Test void currentTopologyConcurrentExactFirstClaimsReturnOneOriginalStoredResult() throws Exception { - withCurrentStorageOwner( - fixture -> { - CountDownLatch begin = new CountDownLatch(1); - ExecutorService executor = Executors.newFixedThreadPool(2); - try { - Future one = - executor.submit( - () -> { - await(begin); - return fixture - .write() - .execute(status -> fixture.topology().store(fixture.plan())); - }); - Future two = - executor.submit( - () -> { - await(begin); - return fixture - .write() - .execute(status -> fixture.topology().store(fixture.plan())); - }); - begin.countDown(); - var first = Objects.requireNonNull(one.get(20, TimeUnit.SECONDS)); - var second = Objects.requireNonNull(two.get(20, TimeUnit.SECONDS)); - assertThat(first.status()).isEqualTo("STORED_PERMISSION_UNVERIFIED"); - assertThat(second.graphBytes()).containsExactly(first.graphBytes()); - assertThat(second.resultBytes()).containsExactly(first.resultBytes()); - assertCompleteCurrentStorage(fixture); - var original = fixture.topology().readCommitted(fixture.plan()).orElseThrow(); - assertThat(original.graphBytes()).containsExactly(first.graphBytes()); - assertThat(original.resultBytes()).containsExactly(first.resultBytes()); - } finally { - begin.countDown(); - executor.shutdownNow(); - } - }); + withCurrentStorageOwner(fixture -> { + CountDownLatch begin = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future one = + executor.submit(() -> { + await(begin); + return fixture.write().execute(status -> fixture.topology().store(fixture.plan())); + }); + Future two = + executor.submit(() -> { + await(begin); + return fixture.write().execute(status -> fixture.topology().store(fixture.plan())); + }); + begin.countDown(); + var first = Objects.requireNonNull(one.get(20, TimeUnit.SECONDS)); + var second = Objects.requireNonNull(two.get(20, TimeUnit.SECONDS)); + assertThat(first.status()).isEqualTo("STORED_PERMISSION_UNVERIFIED"); + assertThat(second.graphBytes()).containsExactly(first.graphBytes()); + assertThat(second.resultBytes()).containsExactly(first.resultBytes()); + assertCompleteCurrentStorage(fixture); + var original = fixture.topology().readCommitted(fixture.plan()).orElseThrow(); + assertThat(original.graphBytes()).containsExactly(first.graphBytes()); + assertThat(original.resultBytes()).containsExactly(first.resultBytes()); + } finally { + begin.countDown(); + executor.shutdownNow(); + } + }); } @Test void currentTopologyReplayRejectsChangedOriginalBindingAndSourceWithoutMutatingRows() throws Exception { - withCurrentStorageOwner( - fixture -> { - var topology = fixture.topology(); - var original = fixture.plan(); - fixture.write().execute(status -> topology.store(original)); - var binding = original.binding(); - List changed = new ArrayList<>(); - changed.add( - WorldDraftTopologyCommitPlan.create( - DraftCommitBinding.create( - binding.target(), - binding.requestId(), - binding.commitId(), - binding.baseCommitId() + "-changed", - binding.revisions(), - binding.affectedUnits()), - original.ownerBinding())); + withCurrentStorageOwner(fixture -> { + var topology = fixture.topology(); + var original = fixture.plan(); + fixture.write().execute(status -> topology.store(original)); + var binding = original.binding(); + List changed = new ArrayList<>(); + changed.add( + WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId() + "-changed", + binding.revisions(), + binding.affectedUnits()), + original.ownerBinding())); + + var payloads = new ArrayList<>(binding.revisions()); + var first = payloads.getFirst(); + var region = WorldDesignMutationRevision.newBuilder(); + JsonFormat.parser().merge(first.payload(), region); + region.setRegion(region.getRegion().toBuilder().setName("changed original region")); + payloads.set( + 0, + new RevisionPayload( + first.revisionOrder(), + first.revisionId(), + first.owner(), + JsonFormat.printer().omittingInsignificantWhitespace().print(region))); + changed.add( + WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + payloads, + binding.affectedUnits()), + original.ownerBinding())); - var payloads = new ArrayList<>(binding.revisions()); - var first = payloads.getFirst(); - var region = WorldDesignMutationRevision.newBuilder(); - JsonFormat.parser().merge(first.payload(), region); - region.setRegion(region.getRegion().toBuilder().setName("changed original region")); - payloads.set( - 0, - new RevisionPayload( - first.revisionOrder(), - first.revisionId(), - first.owner(), - JsonFormat.printer().omittingInsignificantWhitespace().print(region))); - changed.add( - WorldDraftTopologyCommitPlan.create( - DraftCommitBinding.create( - binding.target(), - binding.requestId(), - binding.commitId(), - binding.baseCommitId(), - payloads, - binding.affectedUnits()), - original.ownerBinding())); + var mixedRevisions = new ArrayList<>(binding.revisions()); + mixedRevisions.add( + new RevisionPayload( + Integer.toString(mixedRevisions.size()), + UUID.randomUUID(), + Owner.GAME_LOGIC, + "opaque other-owner revision, never applied by World")); + var mixedUnits = new ArrayList<>(binding.affectedUnits()); + mixedUnits.add( + new AffectedUnit(Owner.GAME_LOGIC, "COMMAND", "other", "AGGREGATE", "other", "0")); + changed.add( + WorldDraftTopologyCommitPlan.create( + DraftCommitBinding.create( + binding.target(), + binding.requestId(), + binding.commitId(), + binding.baseCommitId(), + mixedRevisions, + mixedUnits), + original.ownerBinding())); - var mixedRevisions = new ArrayList<>(binding.revisions()); - mixedRevisions.add( - new RevisionPayload( - Integer.toString(mixedRevisions.size()), + var owner = original.ownerBinding(); + changed.add( + WorldDraftTopologyCommitPlan.create( + binding, + new OwnerBinding( + owner.targetNamespace(), + owner.canonicalTenantId(), + owner.canonicalVersionId(), + owner.versionIdentityOperationId(), + owner.gameDesignVersionId(), + owner.intakeRequestId(), + owner.intakeOperationId(), + owner.intakeRequestDigest(), UUID.randomUUID(), - Owner.GAME_LOGIC, - "opaque other-owner revision, never applied by World")); - var mixedUnits = new ArrayList<>(binding.affectedUnits()); - mixedUnits.add( - new AffectedUnit(Owner.GAME_LOGIC, "COMMAND", "other", "AGGREGATE", "other", "0")); - changed.add( - WorldDraftTopologyCommitPlan.create( - DraftCommitBinding.create( - binding.target(), - binding.requestId(), - binding.commitId(), - binding.baseCommitId(), - mixedRevisions, - mixedUnits), - original.ownerBinding())); - - var owner = original.ownerBinding(); - changed.add( - WorldDraftTopologyCommitPlan.create( - binding, - new OwnerBinding( - owner.targetNamespace(), - owner.canonicalTenantId(), - owner.canonicalVersionId(), - owner.versionIdentityOperationId(), - owner.gameDesignVersionId(), - owner.intakeRequestId(), - owner.intakeOperationId(), - owner.intakeRequestDigest(), - UUID.randomUUID(), - owner.sourceEvidenceDigest(), - owner.intakeReceiptDigest()))); - Map> before = - retainedTableSnapshot(fixture.dsl(), fixture.schema(), currentStorageTables()); - for (var candidate : changed) { - assertThatThrownBy(() -> fixture.write().execute(status -> topology.store(candidate))) - .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) - .hasMessageContaining("changed full input or source"); - assertThatThrownBy(() -> topology.readCommitted(candidate)) - .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) - .hasMessageContaining("changed full input or source"); - assertThat( - retainedTableSnapshot(fixture.dsl(), fixture.schema(), currentStorageTables())) - .isEqualTo(before); - } - assertCompleteCurrentStorage(fixture); - }); + owner.sourceEvidenceDigest(), + owner.intakeReceiptDigest()))); + Map> before = + retainedTableSnapshot(fixture.dsl(), fixture.schema(), currentStorageTables()); + for (var candidate : changed) { + assertThatThrownBy(() -> fixture.write().execute(status -> topology.store(candidate))) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("changed full input or source"); + assertThatThrownBy(() -> topology.readCommitted(candidate)) + .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) + .hasMessageContaining("changed full input or source"); + assertThat(retainedTableSnapshot(fixture.dsl(), fixture.schema(), currentStorageTables())) + .isEqualTo(before); + } + assertCompleteCurrentStorage(fixture); + }); } private static List currentStorageTables() { @@ -1625,10 +1582,9 @@ private static void withCurrentStorageOwner(CurrentStorageProof proof) throws Ex var upstream = controlledSource(); var intake = Objects.requireNonNull( - write.execute( - status -> - new WorldAuthoredSourceIntakeRepository(dsl) - .acceptFresh(NAMESPACE, UUID.randomUUID(), upstream))); + write.execute(status -> + new WorldAuthoredSourceIntakeRepository(dsl) + .acceptFresh(NAMESPACE, UUID.randomUUID(), upstream))); var state = AuthoredWorldVersionStateEvidence.create( new AuthoredWorldVersionStateEvidence.Request( @@ -1646,9 +1602,8 @@ private static void withCurrentStorageOwner(CurrentStorageProof proof) throws Ex 1L); var version = Objects.requireNonNull( - write.execute( - status -> - new WorldAuthoredVersionIdentityRepository(dsl).acceptFresh(intake, state))); + write.execute(status -> + new WorldAuthoredVersionIdentityRepository(dsl).acceptFresh(intake, state))); var fence = new WorldDesignPublicationFenceRepository( dsl, new WorldAuthoredSourceIntakeRepository(dsl)); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldInitialAdmissionHoldHistoryPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldInitialAdmissionHoldHistoryPostgresIntegrationTest.java index 7c544f0827..9b1a252fe1 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldInitialAdmissionHoldHistoryPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldInitialAdmissionHoldHistoryPostgresIntegrationTest.java @@ -92,23 +92,21 @@ void originalNumericHoldsSurviveCanonicalBindingAndCurrentMigrationsWithoutPromo // Actual current repository reads of retained rows, not a canonical finalizer or owner call. var repository = new InitialAdmissionBindHoldRepository(sql); - beforeHold.forEach( - (id, before) -> { - var retained = repository.findByHoldId(id.toString()).orElseThrow(); - assertThat(retained.status()).isEqualTo(before.get("status")); - assertThat(retained.rowVersion()).isEqualTo(before.get("row_version")); - assertThat(retained.ownerProofId()).isEqualTo(before.get("owner_proof_id")); - assertThat(retained.ownerProofDigest()).isEqualTo(before.get("owner_proof_digest")); - assertThat(retained.ownerPointerAuditId()) - .isEqualTo(before.get("owner_pointer_audit_id")); - assertThat(retained.ownerPointerVersion()).isEqualTo(before.get("owner_pointer_version")); - assertThat( - repository.findByTenantIdAndRequestId( - retained.tenantId(), retained.initialAdmissionRequestId())) - .contains(retained); - assertThat(repository.hasNonterminalForRealm(retained.tenantId(), retained.realmUuid())) - .isEqualTo(List.of("PENDING", "RECONCILIATION_REQUIRED").contains(retained.status())); - }); + beforeHold.forEach((id, before) -> { + var retained = repository.findByHoldId(id.toString()).orElseThrow(); + assertThat(retained.status()).isEqualTo(before.get("status")); + assertThat(retained.rowVersion()).isEqualTo(before.get("row_version")); + assertThat(retained.ownerProofId()).isEqualTo(before.get("owner_proof_id")); + assertThat(retained.ownerProofDigest()).isEqualTo(before.get("owner_proof_digest")); + assertThat(retained.ownerPointerAuditId()).isEqualTo(before.get("owner_pointer_audit_id")); + assertThat(retained.ownerPointerVersion()).isEqualTo(before.get("owner_pointer_version")); + assertThat( + repository.findByTenantIdAndRequestId( + retained.tenantId(), retained.initialAdmissionRequestId())) + .contains(retained); + assertThat(repository.hasNonterminalForRealm(retained.tenantId(), retained.realmUuid())) + .isEqualTo(List.of("PENDING", "RECONCILIATION_REQUIRED").contains(retained.status())); + }); assertThat(repository.findNonterminal(256)).hasSize(2); assertPromotionDenied(sql, beforeHold.keySet().iterator().next()); assertRetained(sql, after1020World, after1020Hold); @@ -185,11 +183,10 @@ private void assertUnmapped(DSLContext sql, boolean current) { } private void assertPromotionDenied(DSLContext sql, UUID holdId) { - assertThatThrownBy( - () -> - sql.execute( - "UPDATE initial_admission_bind_hold SET canonical_target_namespace = 'forged-space' WHERE hold_id = ?", - holdId)) + assertThatThrownBy(() -> + sql.execute( + "UPDATE initial_admission_bind_hold SET canonical_target_namespace = 'forged-space' WHERE hold_id = ?", + holdId)) .isInstanceOf(DataAccessException.class) .hasMessageContaining("Initial-admission hold acquisition identity is immutable"); } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldOperationalRegionAssignmentPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldOperationalRegionAssignmentPostgresIntegrationTest.java index 95d0890bdc..128ac3b2b6 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldOperationalRegionAssignmentPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldOperationalRegionAssignmentPostgresIntegrationTest.java @@ -114,20 +114,18 @@ void operationalIdentityUpgradePreservesOriginalRowsAndClosedPreparationFunction "world_canonical_instance_execution")) { assertThat(sql.fetchCount(DSL.table(DSL.name(table)))).as(table).isZero(); } - assertThatThrownBy( - () -> - sql.execute( - "UPDATE region_instance SET operational_region_id = ? WHERE id = ?", - UUID.randomUUID(), - regionId)) + assertThatThrownBy(() -> + sql.execute( + "UPDATE region_instance SET operational_region_id = ? WHERE id = ?", + UUID.randomUUID(), + regionId)) .isInstanceOf(DataAccessException.class) .hasMessageContaining("operational assignment tuple is immutable"); - assertThatThrownBy( - () -> - sql.execute( - "UPDATE world_instance SET canonical_realm_id = ?, catalog_revision = 1 WHERE id = ?", - UUID.randomUUID(), - worldId)) + assertThatThrownBy(() -> + sql.execute( + "UPDATE world_instance SET canonical_realm_id = ?, catalog_revision = 1 WHERE id = ?", + UUID.randomUUID(), + worldId)) .isInstanceOf(DataAccessException.class); assertThat(row(sql, "world_instance", worldId)).isEqualTo(currentWorld); assertThat(row(sql, "region_instance", regionId)).isEqualTo(currentRegion); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperationPostgresIntegrationTest.java index 630e7cd28b..2a6248cef3 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperationPostgresIntegrationTest.java @@ -90,22 +90,20 @@ void actualMaterializationExactReplayIndependentTerminalRetainClosedPreparingSta f.dsl .fetchSingle("SELECT original_operation_bytes FROM world_private_fresh_operation") .get(0, byte[].class); - assertThatThrownBy( - () -> - f.dsl.fetchValue( - "SELECT world_private_fresh_intent(?,?,?)", - changedJson, - hash(changedJson.getBytes(java.nio.charset.StandardCharsets.UTF_8)), - originalOperation)) + assertThatThrownBy(() -> + f.dsl.fetchValue( + "SELECT world_private_fresh_intent(?,?,?)", + changedJson, + hash(changedJson.getBytes(java.nio.charset.StandardCharsets.UTF_8)), + originalOperation)) .hasMessageContaining("different exact original inputs"); - assertThatThrownBy( - () -> - f.dsl.fetchValue( - "SELECT world_private_fresh_intent(?,?,?)", - prepared.inputJson(), - prepared.inputDigest(), - "substituted original operation" - .getBytes(java.nio.charset.StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + f.dsl.fetchValue( + "SELECT world_private_fresh_intent(?,?,?)", + prepared.inputJson(), + prepared.inputDigest(), + "substituted original operation" + .getBytes(java.nio.charset.StandardCharsets.UTF_8))) .hasMessageContaining("different exact original inputs"); assertThat(f.rows()).isEqualTo(originalRows); assertThat(f.owner().read(prepared.operationId())).contains(terminal); @@ -149,10 +147,9 @@ void actualMaterializationExactReplayIndependentTerminalRetainClosedPreparingSta .isEqualTo(5); assertThatThrownBy(() -> owner.abort(prepared)) .hasMessageContaining("different terminal outcome"); - assertThatThrownBy( - () -> - f.dsl.execute( - "UPDATE world_instance SET status='ACTIVE',lifecycle_epoch=2,row_version=1")) + assertThatThrownBy(() -> + f.dsl.execute( + "UPDATE world_instance SET status='ACTIVE',lifecycle_epoch=2,row_version=1")) .isInstanceOf(RuntimeException.class); assertThatThrownBy(() -> f.dsl.execute("UPDATE room_instance SET name='foreign'")) .hasMessageContaining("no exact transaction execution manifest"); @@ -338,19 +335,17 @@ void expiredSourceAndPublicShapeCannotEnterPrivateOwner() { input.put("zoneCount", 1); input.put("roomCount", 1); input.put("exitCount", 0); - assertThatThrownBy( - () -> - f.dsl.fetchValue( - "SELECT world_private_fresh_assert_inputs(?::JSONB)", - JSON.writeValueAsString(input))) + assertThatThrownBy(() -> + f.dsl.fetchValue( + "SELECT world_private_fresh_assert_inputs(?::JSONB)", + JSON.writeValueAsString(input))) .hasMessageContaining("nonpublic generation-one FRESH target required"); input.put("forkExpiresAt", Instant.now().plusSeconds(600).toString()); input.put("publicProduction", true); - assertThatThrownBy( - () -> - f.dsl.fetchValue( - "SELECT world_private_fresh_assert_inputs(?::JSONB)", - JSON.writeValueAsString(input))) + assertThatThrownBy(() -> + f.dsl.fetchValue( + "SELECT world_private_fresh_assert_inputs(?::JSONB)", + JSON.writeValueAsString(input))) .hasMessageContaining("nonpublic generation-one FRESH target required"); assertThat(f.count("world_instance")).isZero(); } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java index 6bef591ca7..c4de7cf121 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -53,11 +53,10 @@ void configuredFlywayHistoryNameBindsTheActualInstallationAndReadback() throws E try (Fixture f = fixture(null, history)) { var original = f.owner().read(request()); assertThat(original.catalog().families()) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo(history); - assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.CONTROL_ONLY); - }); + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo(history); + assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.CONTROL_ONLY); + }); assertThat(f.owner().readExact(original.request())).isEqualTo(original); assertThat( f.dsl @@ -92,38 +91,32 @@ void actualCompleteCurrentCensusIncludesEmptyRuntimeAndNonPayloadFamilies() thro .isEqualTo( catalog.schemaFacts().stream().filter(fact -> fact.kind() == FactKind.TABLE).count()); assertThat(catalog.families()) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo("region_instance.weather"); - assertThat(family.freshDisposition()) - .isEqualTo(FreshDisposition.UNSUPPORTED_WEATHER); - }) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo("instance"); - assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.LEGACY_EXCLUDED); - }) - .anySatisfy( - family -> { - assertThat(family.familyId()).isEqualTo("character_location"); - assertThat(family.freshDisposition()) - .isEqualTo(FreshDisposition.NOT_INITIALIZED_ACTOR_LOCATION); - }) - .anySatisfy( - family -> { - assertThat(family.familyId()) - .isEqualTo("world_canonical_initial_player_location_operation"); - assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.PROVENANCE_ONLY); - }); + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo("region_instance.weather"); + assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.UNSUPPORTED_WEATHER); + }) + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo("instance"); + assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.LEGACY_EXCLUDED); + }) + .anySatisfy(family -> { + assertThat(family.familyId()).isEqualTo("character_location"); + assertThat(family.freshDisposition()) + .isEqualTo(FreshDisposition.NOT_INITIALIZED_ACTOR_LOCATION); + }) + .anySatisfy(family -> { + assertThat(family.familyId()) + .isEqualTo("world_canonical_initial_player_location_operation"); + assertThat(family.freshDisposition()).isEqualTo(FreshDisposition.PROVENANCE_ONLY); + }); assertThat(f.count("region_instance")).isZero(); assertThat(f.count("character_location")).isZero(); assertThat(f.count("world_event")).isZero(); assertThat(catalog.families()) - .noneMatch( - family -> - family.familyId().equals("npc_location") - || family.familyId().equals("population_schedule_instance") - || family.familyId().equals("generation_run")); + .noneMatch(family -> + family.familyId().equals("npc_location") + || family.familyId().equals("population_schedule_instance") + || family.familyId().equals("generation_run")); assertThat(catalog.schemaFacts()) .anyMatch(fact -> fact.kind() == FactKind.MIGRATION) .anyMatch(fact -> fact.kind() == FactKind.ROUTINE) @@ -283,18 +276,16 @@ void schemaColumnRenameConstraintAndRoutineChangesCannotResampleUnderSameEpoch() private static void assertCatalogDrift(Runnable read) { assertThatThrownBy(read::run) - .satisfies( - failure -> { - if (failure instanceof org.jooq.exception.DataAccessException sql) { - assertThat(sql.sqlState()).isEqualTo("23514"); - assertThat(sql).hasMessageContaining("Unclassified or changed World schema family"); - } else { - assertThat(failure) - .isInstanceOf( - WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class) - .hasMessageContaining("drift invalidates its epoch"); - } - }); + .satisfies(failure -> { + if (failure instanceof org.jooq.exception.DataAccessException sql) { + assertThat(sql.sqlState()).isEqualTo("23514"); + assertThat(sql).hasMessageContaining("Unclassified or changed World schema family"); + } else { + assertThat(failure) + .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class) + .hasMessageContaining("drift invalidates its epoch"); + } + }); } @Test @@ -318,13 +309,11 @@ void installedViewAndMaterializedViewOptionsInvalidateTheSealWithoutResampling() var original = f.owner().read(read); assertThat(original.catalog().catalogEpoch()).isEqualTo(5); assertThat(original.catalog().schemaFacts()) - .anyMatch( - fact -> - fact.kind() == FactKind.VIEW && fact.identity().equals("catalog_option_probe")) - .anyMatch( - fact -> - fact.kind() == FactKind.VIEW - && fact.identity().equals("catalog_materialized_probe")); + .anyMatch(fact -> + fact.kind() == FactKind.VIEW && fact.identity().equals("catalog_option_probe")) + .anyMatch(fact -> + fact.kind() == FactKind.VIEW + && fact.identity().equals("catalog_materialized_probe")); var snapshots = f.retainedRows("world_runtime_family_catalog_snapshot"); var epochs = f.retainedRows("world_runtime_family_catalog_epoch"); f.dsl.execute(change); @@ -520,18 +509,15 @@ void forwardFrameGuardUpgradeRetainsOldEpochSnapshotAndHistoryWithoutResampling( assertThat(current.catalog().catalogEpoch()).isEqualTo(3); assertThat(current.catalog().digest()).isNotEqualTo(original.catalog().digest()); assertThat(current.catalog().schemaFacts()) - .anyMatch( - fact -> - fact.kind() == FactKind.MIGRATION - && fact.identity().equals("catalog-installation:1046")) - .anyMatch( - fact -> - fact.kind() == FactKind.MIGRATION - && fact.identity().equals("catalog-installation:1047")) - .anyMatch( - fact -> - fact.kind() == FactKind.MIGRATION - && fact.identity().equals("catalog-installation:1048")); + .anyMatch(fact -> + fact.kind() == FactKind.MIGRATION + && fact.identity().equals("catalog-installation:1046")) + .anyMatch(fact -> + fact.kind() == FactKind.MIGRATION + && fact.identity().equals("catalog-installation:1047")) + .anyMatch(fact -> + fact.kind() == FactKind.MIGRATION + && fact.identity().equals("catalog-installation:1048")); assertThat(f.count("world_runtime_family_catalog_snapshot")).isEqualTo(2); migration(f.source, f.schema, "1048").validate(); } @@ -586,16 +572,14 @@ void epochMetadataAndSnapshotsAreRetainedAndWrongSealsCannotBeInserted() throws assertThatThrownBy( () -> f.dsl.execute("UPDATE world_runtime_family_catalog_epoch SET catalog_epoch=2")) .hasMessageContaining("immutable"); - assertThatThrownBy( - () -> - f.dsl.execute( - "UPDATE world_runtime_family_classification SET fresh_disposition='LEGACY_EXCLUDED' WHERE family_id='instance'")) + assertThatThrownBy(() -> + f.dsl.execute( + "UPDATE world_runtime_family_classification SET fresh_disposition='LEGACY_EXCLUDED' WHERE family_id='instance'")) .hasMessageContaining("immutable"); - assertThatThrownBy( - () -> - f.dsl.execute( - "INSERT INTO world_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 4,catalog_bytes,catalog_digest FROM world_runtime_family_catalog_epoch WHERE catalog_epoch=3")) + assertThatThrownBy(() -> + f.dsl.execute( + "INSERT INTO world_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" + + " SELECT 4,catalog_bytes,catalog_digest FROM world_runtime_family_catalog_epoch WHERE catalog_epoch=3")) .hasMessageContaining("exact classified installed schema"); } } @@ -612,10 +596,9 @@ void actualProducerReturnsCompleteCorrelatedEvidenceWithoutMaterializingRuntime( .orElseThrow(); Context.current() .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .run( - () -> - service.readWorldRuntimeFamilyCatalog( - WorldRuntimeFamilyCatalogCodec.toRequest(read), collector)); + .run(() -> + service.readWorldRuntimeFamilyCatalog( + WorldRuntimeFamilyCatalogCodec.toRequest(read), collector)); assertThat(collector.error).isNull(); assertThat(collector.completed).isTrue(); var evidence = WorldRuntimeFamilyCatalogCodec.fromResponse(read, collector.value); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistryPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistryPostgresIntegrationTest.java index 72419af2de..ed38bd7c82 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistryPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistryPostgresIntegrationTest.java @@ -225,28 +225,26 @@ void heldSourceChangingInsideRegistrationRollsBackRowsAndCurrentPointer() { void directSqlCannotFreezeACallerSelectedSubsetOrForeignRevision() { try (Fixture f = fixture(null)) { var registration = f.registry(new ControlledInstallationSource(artifact())).register(); - assertThatThrownBy( - () -> - f.dsl.execute( - "INSERT INTO world_runtime_required_owner_snapshot" - + "(canonical_game_instance_id,target_namespace,registry_revision,artifact_digest,required_owners)" - + " SELECT ?,target_namespace,revision,artifact_digest," - + " jsonb_build_array(world_runtime_required_owners(artifact_bytes)->0)" - + " FROM world_runtime_installation_registration WHERE revision=?", - UUID.randomUUID(), - registration.revision())) + assertThatThrownBy(() -> + f.dsl.execute( + "INSERT INTO world_runtime_required_owner_snapshot" + + "(canonical_game_instance_id,target_namespace,registry_revision,artifact_digest,required_owners)" + + " SELECT ?,target_namespace,revision,artifact_digest," + + " jsonb_build_array(world_runtime_required_owners(artifact_bytes)->0)" + + " FROM world_runtime_installation_registration WHERE revision=?", + UUID.randomUUID(), + registration.revision())) .hasMessageContaining("complete current installation"); - assertThatThrownBy( - () -> - f.dsl.execute( - "INSERT INTO world_runtime_required_owner_snapshot" - + "(canonical_game_instance_id,target_namespace,registry_revision,artifact_digest,required_owners)" - + " VALUES (?,?,?,?,world_runtime_required_owners(?))", - UUID.randomUUID(), - NAMESPACE, - registration.revision() + 1, - registration.artifact().digest(), - registration.artifact().exactBytes())) + assertThatThrownBy(() -> + f.dsl.execute( + "INSERT INTO world_runtime_required_owner_snapshot" + + "(canonical_game_instance_id,target_namespace,registry_revision,artifact_digest,required_owners)" + + " VALUES (?,?,?,?,world_runtime_required_owners(?))", + UUID.randomUUID(), + NAMESPACE, + registration.revision() + 1, + registration.artifact().digest(), + registration.artifact().exactBytes())) .hasMessageContaining("Frozen owners must match the complete current installation") .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")); assertThat(f.count("world_runtime_required_owner_snapshot")).isZero(); @@ -297,15 +295,14 @@ void currentPointerOnlyAdvancesAndHistoricalRegistrationCannotBeReinstalled() { var second = registry.register(); var pointer = f.retainedRows("world_runtime_installation_current"); for (long revision : List.of(first.revision(), second.revision())) { - assertThatThrownBy( - () -> - f.dsl.execute( - "UPDATE world_runtime_installation_current SET revision=?,artifact_digest=? WHERE target_namespace=?", - revision, - revision == first.revision() - ? first.artifact().digest() - : second.artifact().digest(), - NAMESPACE)) + assertThatThrownBy(() -> + f.dsl.execute( + "UPDATE world_runtime_installation_current SET revision=?,artifact_digest=? WHERE target_namespace=?", + revision, + revision == first.revision() + ? first.artifact().digest() + : second.artifact().digest(), + NAMESPACE)) .hasMessageContaining("monotonically"); } for (String statement : @@ -357,12 +354,9 @@ void installedLaunchPredicateRequiresTheExactCurrentFreezeOnControlledReceiverOn var registry = f.registry(source); registry.register(); UUID instanceId = UUID.randomUUID(); - assertThatThrownBy( - () -> - f.dsl.execute( - "INSERT INTO " + receiver + " VALUES (?,?,'PREPARING')", - instanceId, - NAMESPACE)) + assertThatThrownBy(() -> + f.dsl.execute( + "INSERT INTO " + receiver + " VALUES (?,?,'PREPARING')", instanceId, NAMESPACE)) .hasMessageContaining("complete current frozen runtime owners"); registry.withLaunchOwners( instanceId, @@ -371,13 +365,10 @@ void installedLaunchPredicateRequiresTheExactCurrentFreezeOnControlledReceiverOn "INSERT INTO " + receiver + " VALUES (?,?,'PREPARING')", instanceId, NAMESPACE)); source.replace(artifact()); registry.register(); - assertThatThrownBy( - () -> - f.dsl.execute( - "UPDATE " - + receiver - + " SET status='ACTIVE' WHERE canonical_game_instance_id=?", - instanceId)) + assertThatThrownBy(() -> + f.dsl.execute( + "UPDATE " + receiver + " SET status='ACTIVE' WHERE canonical_game_instance_id=?", + instanceId)) .hasMessageContaining("complete current frozen runtime owners"); assertThat(f.dsl.fetchSingle("SELECT status FROM " + receiver).get(0, String.class)) .isEqualTo("PREPARING"); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java index e41f3a32f2..582542f2d5 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java @@ -310,10 +310,9 @@ public static AppliedGraph applyGraph( org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); var intake = Objects.requireNonNull( - write.execute( - status -> - intakeRepository.acceptFresh( - namespace, originalIntakeRequestId, controlledWorldSource))); + write.execute(status -> + intakeRepository.acceptFresh( + namespace, originalIntakeRequestId, controlledWorldSource))); var versionStateRequest = new AuthoredWorldVersionStateEvidence.Request( 1, @@ -460,15 +459,14 @@ private static WorldAuthoredGraphSnapshot.CaptureRequest captureRequest( WorldDesignPublicationFenceEvidence.FrozenAttempt attempt) { List tuples = plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) + .map(unit -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) .toList(); return new WorldAuthoredGraphSnapshot.CaptureRequest( freeze.targetNamespace(), @@ -501,15 +499,14 @@ private static WorldPublishedStartLocationEvidence publishedStartLocationEvidenc var freeze = source.frozenTopology().request().freeze(); var tuples = freeze.suppliedOwnedAffectedTuples().stream() - .map( - tuple -> - new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( - tuple.owner(), - tuple.aggregateType(), - tuple.aggregateId(), - tuple.scopeType(), - tuple.scopeId(), - tuple.expectedEpoch())) + .map(tuple -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) .toList(); var request = new WorldPublishedStartLocationEvidence.Request( diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixtureTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixtureTest.java index f6082e5461..aa261a43b2 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixtureTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixtureTest.java @@ -59,10 +59,9 @@ void rejectsVersionWithDifferentSourceIntakeOperationBeforeSqlOrAccountEvidenceR when(version.sourceIntakeReceipt()).thenReturn(versionIntake); when(versionIntake.operationId()).thenReturn(versionIntakeOperationId); - assertThatThrownBy( - () -> - WorldSelectedFullPublicationEvidenceFixture.readCommittedFreeze( - worldDsl, "test", selection, graph, accountBinding, freezeEvidence)) + assertThatThrownBy(() -> + WorldSelectedFullPublicationEvidenceFixture.readCommittedFreeze( + worldDsl, "test", selection, graph, accountBinding, freezeEvidence)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("World retained source/Version rows differ"); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationPostgresIntegrationTest.java index 1176493411..126fdde98d 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationPostgresIntegrationTest.java @@ -263,11 +263,10 @@ void currentDefaultAppliedFreezeInventoryTerminalAndIndependentOwnerReadback() t assertThat(appliedResult.appliedEpochs()) .hasSize(12) - .allSatisfy( - epoch -> { - assertThat(epoch.expectedEpoch()).isEqualTo("0"); - assertThat(epoch.resultingEpoch()).isEqualTo("1"); - }); + .allSatisfy(epoch -> { + assertThat(epoch.expectedEpoch()).isEqualTo("0"); + assertThat(epoch.resultingEpoch()).isEqualTo("1"); + }); assertThat(appliedPlan.graph().freshGraphDeclaration().orElseThrow().familyCounts()) .extracting(WorldDraftTopologyInputGraph.FamilyCount::count) .containsExactly(1, 1, 2, 1, 0, 1); @@ -407,30 +406,26 @@ void currentDefaultAppliedFreezeInventoryTerminalAndIndependentOwnerReadback() t new AtomicReference( GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN); when(terminalClient.read(any())) - .thenAnswer( - invocation -> { - var request = - (GameDesignPublicationTerminalReadEvidence.ReadRequest) - invocation.getArgument(0); - var status = terminalStatus.get(); - return new GameDesignPublicationTerminalReadEvidence.ReadResult( - request, - status, - status == GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN - ? Optional.empty() - : Optional.of(terminal)); - }); + .thenAnswer(invocation -> { + var request = + (GameDesignPublicationTerminalReadEvidence.ReadRequest) invocation.getArgument(0); + var status = terminalStatus.get(); + return new GameDesignPublicationTerminalReadEvidence.ReadResult( + request, + status, + status == GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN + ? Optional.empty() + : Optional.of(terminal)); + }); var terminalRepository = new WorldPublicationTerminalRepository(dsl, transactionManager); WorldPublicationTerminalService terminalService = WorldPublicationTerminalService.authenticated( terminalRepository, terminalClient, NAMESPACE); Map> beforeUnknownTerminal = snapshotMutationRows(dsl); - assertThatThrownBy( - () -> - authenticatedGameDesign.call( - () -> - terminalService.complete( - publicationOperation.canonicalBytes(), terminal.canonicalBytes()))) + assertThatThrownBy(() -> + authenticatedGameDesign.call(() -> + terminalService.complete( + publicationOperation.canonicalBytes(), terminal.canonicalBytes()))) .isInstanceOf(SecurityException.class) .hasMessageContaining("outcome is unknown"); assertThat(snapshotMutationRows(dsl)).isEqualTo(beforeUnknownTerminal); @@ -439,10 +434,9 @@ void currentDefaultAppliedFreezeInventoryTerminalAndIndependentOwnerReadback() t assertThat(publicationTerminalCount(dsl, acknowledgement.publicationFence())).isZero(); terminalStatus.set(GameDesignPublicationTerminalReadEvidence.Status.PUBLISHED); GameDesignPublicationTerminalEvidence completed = - authenticatedGameDesign.call( - () -> - terminalService.complete( - publicationOperation.canonicalBytes(), terminal.canonicalBytes())); + authenticatedGameDesign.call(() -> + terminalService.complete( + publicationOperation.canonicalBytes(), terminal.canonicalBytes())); assertThat(completed.canonicalBytes()).containsExactly(terminal.canonicalBytes()); assertThat(publicationOwnerPhase(dsl, acknowledgement.publicationFence())) .isEqualTo("PUBLISHED"); @@ -492,12 +486,11 @@ void currentDefaultAppliedFreezeInventoryTerminalAndIndependentOwnerReadback() t GameDesignPublicationTerminalReadEvidence.ReadRequest.class); verify(terminalClient, org.mockito.Mockito.times(2)).read(terminalReadRequests.capture()); assertThat(terminalReadRequests.getAllValues()) - .allSatisfy( - request -> { - assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); - assertThat(request.operationBytes()) - .containsExactly(publicationOperation.canonicalBytes()); - }); + .allSatisfy(request -> { + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.operationBytes()) + .containsExactly(publicationOperation.canonicalBytes()); + }); assertThat(terminalReadRequests.getAllValues().get(0).readRequestId()) .isNotEqualTo(terminalReadRequests.getAllValues().get(1).readRequestId()); @@ -545,18 +538,13 @@ void currentDefaultAppliedFreezeInventoryTerminalAndIndependentOwnerReadback() t transactionManager, unsupportedRuleOwner); Map> beforeUnsupportedRuleFreeze = snapshotMutationRows(dsl); - assertThatThrownBy( - () -> - authenticatedGameDesign.call( - () -> - unsupportedRuleFreeze - .freezeService() - .begin(unsupportedRuleFreezeRequest))) - .satisfies( - failure -> - assertThat(allThrowableText(failure)) - .contains( - "GENERATION_RULE name/scope/value inputs without a closed requiredness registry")); + assertThatThrownBy(() -> + authenticatedGameDesign.call( + () -> unsupportedRuleFreeze.freezeService().begin(unsupportedRuleFreezeRequest))) + .satisfies(failure -> + assertThat(allThrowableText(failure)) + .contains( + "GENERATION_RULE name/scope/value inputs without a closed requiredness registry")); assertThat(snapshotMutationRows(dsl)).isEqualTo(beforeUnsupportedRuleFreeze); assertThat(publicationOwnerPhase(dsl, unsupportedRuleOwner)).isEqualTo("OPEN"); assertThat( @@ -636,12 +624,11 @@ static PrivateFreshPublished privateFreshPublished( var terminal = publishedTerminal(operation, world); var client = mock(GameDesignPublicationTerminalClient.class); when(client.read(any())) - .thenAnswer( - invocation -> - new GameDesignPublicationTerminalReadEvidence.ReadResult( - invocation.getArgument(0), - GameDesignPublicationTerminalReadEvidence.Status.PUBLISHED, - Optional.of(terminal))); + .thenAnswer(invocation -> + new GameDesignPublicationTerminalReadEvidence.ReadResult( + invocation.getArgument(0), + GameDesignPublicationTerminalReadEvidence.Status.PUBLISHED, + Optional.of(terminal))); var terminalService = WorldPublicationTerminalService.authenticated( new WorldPublicationTerminalRepository(dsl, transactions), client, NAMESPACE); @@ -665,36 +652,33 @@ private static FreezeFixture freezeFixture( OwnerFixture owner) { var selectionClient = mock(AuthoredDraftPublishSelectionReadClient.class); when(selectionClient.read(any())) - .thenAnswer( - invocation -> { - var request = - (AuthoredDraftPublishSelectionReadEvidence.Request) invocation.getArgument(0); - var evidence = mock(AuthoredDraftPublishSelectionReadEvidence.class); - when(evidence.request()).thenReturn(request); - return evidence; - }); + .thenAnswer(invocation -> { + var request = + (AuthoredDraftPublishSelectionReadEvidence.Request) invocation.getArgument(0); + var evidence = mock(AuthoredDraftPublishSelectionReadEvidence.class); + when(evidence.request()).thenReturn(request); + return evidence; + }); var versionStateClient = mock(AuthoredWorldVersionStateClient.class); when(versionStateClient.read(any())) - .thenAnswer( - invocation -> { - var request = (AuthoredWorldVersionStateEvidence.Request) invocation.getArgument(0); - return AuthoredWorldVersionStateEvidence.create( - request, - owner.source(), - owner.version().canonicalVersionId(), - VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, - 1L); - }); + .thenAnswer(invocation -> { + var request = (AuthoredWorldVersionStateEvidence.Request) invocation.getArgument(0); + return AuthoredWorldVersionStateEvidence.create( + request, + owner.source(), + owner.version().canonicalVersionId(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1L); + }); var accountClient = mock(AccountPublicationAuthorizationReadClient.class); when(accountClient.read(any())) - .thenAnswer( - invocation -> { - var request = - (AccountPublicationAuthorizationReadEvidence.Request) invocation.getArgument(0); - var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); - when(evidence.request()).thenReturn(request); - return evidence; - }); + .thenAnswer(invocation -> { + var request = + (AccountPublicationAuthorizationReadEvidence.Request) invocation.getArgument(0); + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(request); + return evidence; + }); var authorizationRepository = new WorldSelectedDraftPublicationAuthorizationRepository(dsl); var inventoryRepository = new WorldSelectedPublicationArtifactInventoryRepository(dsl); var authoredSnapshotRepository = new WorldAuthoredGraphSnapshotRepository(dsl); @@ -761,15 +745,14 @@ private static WorldAuthoredGraphSnapshot.CaptureRequest selectorRequest( .derivedWorkflowIdentity(); var tuples = plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) + .map(unit -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) .toList(); return new WorldAuthoredGraphSnapshot.CaptureRequest( request.targetNamespace(), @@ -792,15 +775,14 @@ private static WorldPublishedStartLocationEvidence publishedStartLocationEvidenc var freeze = source.frozenTopology().request().freeze(); var tuples = freeze.suppliedOwnedAffectedTuples().stream() - .map( - tuple -> - new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( - tuple.owner(), - tuple.aggregateType(), - tuple.aggregateId(), - tuple.scopeType(), - tuple.scopeId(), - tuple.expectedEpoch())) + .map(tuple -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) .toList(); var request = new WorldPublishedStartLocationEvidence.Request( @@ -833,23 +815,21 @@ private static GameDesignPublicationTerminalEvidence publishedTerminal( String commitId = worldEvidence.request().appliedCommitId(); List participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - participant -> - new Participant( + .map(participant -> + new Participant( + participant, + scope, + null, + commitId, + "WORLD_MANAGEMENT".equals(participant) + ? worldEvidence.request().contentDigest() + : "a".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( participant, - scope, - null, - commitId, - "WORLD_MANAGEMENT".equals(participant) - ? worldEvidence.request().contentDigest() - : "a".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - participant, - AuthoredWorldReleaseAttestationEvidence - .CLOSURE_SELECTOR_SCHEMA_VERSION), - "GAME_LOGIC".equals(participant) ? "sha256:" + "b".repeat(64) : null, - null, - null)) + AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(participant) ? "sha256:" + "b".repeat(64) : null, + null, + null)) .toList(); var release = new ReleaseContent( diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldV1PreparationHistoryPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldV1PreparationHistoryPostgresIntegrationTest.java index e8b3971537..4ed70030cc 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldV1PreparationHistoryPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldV1PreparationHistoryPostgresIntegrationTest.java @@ -186,12 +186,9 @@ public void release(java.sql.Connection connection) { ? Context.current().withCancellation() : Context.current().withDeadlineAfter(3, TimeUnit.SECONDS, timer)) { var pending = - callers.submit( - () -> - context.call( - () -> - boundedReader.readCommitted( - request, Deadline.after(30, TimeUnit.SECONDS)))); + callers.submit(() -> + context.call(() -> + boundedReader.readCommitted(request, Deadline.after(30, TimeUnit.SECONDS)))); try { var lockBudget = Deadline.after(2, TimeUnit.SECONDS); while (!"Lock" @@ -332,15 +329,13 @@ sql, captures, new WorldDraftGraphApplicationRepository(sql, fence, mapper)) "worldStartLocationEvidenceBase64", java.util.Base64.getEncoder().encodeToString(originalSelector.canonicalBytes())); String promoted = mapper.writeValueAsString(changed); - assertThatThrownBy( - () -> - write.executeWithoutResult( - ignored -> - sql.fetchSingle( - "SELECT * FROM world_prepare_canonical_instance(?,?)", - promoted, - DraftAuthorizationFenceBinding.digest( - promoted.getBytes(StandardCharsets.UTF_8))))) + assertThatThrownBy(() -> + write.executeWithoutResult(ignored -> + sql.fetchSingle( + "SELECT * FROM world_prepare_canonical_instance(?,?)", + promoted, + DraftAuthorizationFenceBinding.digest( + promoted.getBytes(StandardCharsets.UTF_8))))) .isInstanceOf(DataAccessException.class) .hasMessageContaining( "V2 preparation requires original complete World selector evidence"); @@ -369,11 +364,9 @@ sql, captures, new WorldDraftGraphApplicationRepository(sql, fence, mapper)) sql.fetchSingle("SELECT input_json FROM world_canonical_instance_preparation") .get(0, String.class)) .isEqualTo(exactInput); - assertThatThrownBy( - () -> - sql.execute( - "UPDATE world_canonical_instance_preparation SET input_json = ?", - exactInput + " ")) + assertThatThrownBy(() -> + sql.execute( + "UPDATE world_canonical_instance_preparation SET input_json = ?", exactInput + " ")) .isInstanceOf(DataAccessException.class); assertThat(rows(sql, queries)).isEqualTo(before); assertThat(sql.fetchCount(DSL.table(DSL.name("world_canonical_instance_execution")))).isZero(); @@ -410,10 +403,9 @@ sql, captures, new WorldDraftGraphApplicationRepository(sql, fence, mapper)) assertThat(sql.fetchCount(DSL.table("world_canonical_instance_activation_fence"))).isZero(); assertThat(sql.fetchCount(DSL.table("world_canonical_activation_execution_manifest"))) .isZero(); - assertThatThrownBy( - () -> - sql.execute( - "UPDATE world_canonical_instance_activation_operation SET result_bytes=result_bytes")) + assertThatThrownBy(() -> + sql.execute( + "UPDATE world_canonical_instance_activation_operation SET result_bytes=result_bytes")) .isInstanceOf(DataAccessException.class); assertThat(rows(sql, queries)).isEqualTo(before); } @@ -511,38 +503,37 @@ private static Map activationGuard(DSLContext sql) { net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation.Outcome.COMMITTED, null, active); - write.executeWithoutResult( - ignored -> { - sql.execute( - "INSERT INTO world_canonical_instance_activation_operation " - + "(activation_request_id,request_digest,request_bytes,preparing_evidence_bytes," - + "canonical_game_instance_id,world_instance_id,expected_lifecycle_epoch,expected_row_version," - + "outcome,terminal_code,result_lifecycle_epoch,result_row_version,result_bytes,result_digest) " - + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", - activation.activationRequestId(), - activation.requestDigest(), - activation.canonicalRequestBytes(), - activation.preparingEvidenceBytes(), - activation.canonicalGameInstanceId(), - retained.get("id", Long.class), - activation.expectedLifecycleEpoch(), - activation.expectedRowVersion(), - "COMMITTED", - null, - active.lifecycleEpoch(), - active.rowVersion(), - result.canonicalBytes(), - DraftAuthorizationFenceBinding.digest(result.canonicalBytes())); - assertThat( - sql.execute( - "UPDATE world_instance SET status='ACTIVE',lifecycle_epoch=lifecycle_epoch+1," - + "row_version=row_version+1,updated_at=CURRENT_TIMESTAMP " - + "WHERE id=? AND status='PREPARING' AND lifecycle_epoch=? AND row_version=?", - retained.get("id", Long.class), - activation.expectedLifecycleEpoch(), - activation.expectedRowVersion())) - .isEqualTo(1); - }); + write.executeWithoutResult(ignored -> { + sql.execute( + "INSERT INTO world_canonical_instance_activation_operation " + + "(activation_request_id,request_digest,request_bytes,preparing_evidence_bytes," + + "canonical_game_instance_id,world_instance_id,expected_lifecycle_epoch,expected_row_version," + + "outcome,terminal_code,result_lifecycle_epoch,result_row_version,result_bytes,result_digest) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + activation.activationRequestId(), + activation.requestDigest(), + activation.canonicalRequestBytes(), + activation.preparingEvidenceBytes(), + activation.canonicalGameInstanceId(), + retained.get("id", Long.class), + activation.expectedLifecycleEpoch(), + activation.expectedRowVersion(), + "COMMITTED", + null, + active.lifecycleEpoch(), + active.rowVersion(), + result.canonicalBytes(), + DraftAuthorizationFenceBinding.digest(result.canonicalBytes())); + assertThat( + sql.execute( + "UPDATE world_instance SET status='ACTIVE',lifecycle_epoch=lifecycle_epoch+1," + + "row_version=row_version+1,updated_at=CURRENT_TIMESTAMP " + + "WHERE id=? AND status='PREPARING' AND lifecycle_epoch=? AND row_version=?", + retained.get("id", Long.class), + activation.expectedLifecycleEpoch(), + activation.expectedRowVersion())) + .isEqualTo(1); + }); assertThat(sql.fetchCount(DSL.table("world_canonical_activation_execution_manifest"))).isZero(); assertThat(sql.fetchSingle("SELECT status FROM world_instance").get(0, String.class)) .isEqualTo("ACTIVE"); @@ -618,10 +609,9 @@ void unqualifiedFrozenHistoryCannotGainAccountOrderOrCompleteInventory() throws application(fixture.plan()).operation().accountBindingBytes(), fixture.selection(), fixture.attempt().request().publicationRequestId()); - assertThatThrownBy( - () -> - new WorldSelectedPublicationArtifactInventoryRepository(sql) - .readCommitted(fixture.attempt(), account)) + assertThatThrownBy(() -> + new WorldSelectedPublicationArtifactInventoryRepository(sql) + .readCommitted(fixture.attempt(), account)) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) .hasMessage("Exact frozen World publication has no complete artifact inventory"); assertThat(sql.fetchCount(DSL.table("world_selected_publication_artifact_inventory"))) @@ -636,19 +626,17 @@ void unqualifiedFrozenHistoryCannotGainAccountOrderOrCompleteInventory() throws fixture.attempt().request().publicationRequestId()); // A plausible distinct Account order supplied now is not the missing original order. // Keep all installed triggers enabled and attempt the forbidden late attachment directly. - assertThatThrownBy( - () -> - write.executeWithoutResult( - ignored -> - sql.execute( - "INSERT INTO world_design_publication_account_binding " - + "(publication_fence,account_operation_id,account_fence_id,account_binding_bytes,account_binding_digest) " - + "VALUES (?,?,?,?,?)", - fixture.attempt().publicationFence(), - account.operationId(), - account.fenceId(), - account.canonicalBytes(), - DraftAuthorizationFenceBinding.digest(account.canonicalBytes())))) + assertThatThrownBy(() -> + write.executeWithoutResult(ignored -> + sql.execute( + "INSERT INTO world_design_publication_account_binding " + + "(publication_fence,account_operation_id,account_fence_id,account_binding_bytes,account_binding_digest) " + + "VALUES (?,?,?,?,?)", + fixture.attempt().publicationFence(), + account.operationId(), + account.fenceId(), + account.canonicalBytes(), + DraftAuthorizationFenceBinding.digest(account.canonicalBytes())))) .isInstanceOf(DataAccessException.class); assertUnqualifiedFreeze(sql, fixture); assertThat(rows(sql, queries)).isEqualTo(before); @@ -667,12 +655,11 @@ private static void assertUnqualifiedFreeze(DSLContext sql, FrozenHistoryFixture assertThat( sql.fetchSingle( "SELECT owner_freeze_phase,current_publication_fence FROM world_design_publication_fence_owner")) - .satisfies( - row -> { - assertThat(row.get("owner_freeze_phase", String.class)).isEqualTo("FROZEN"); - assertThat(row.get("current_publication_fence", UUID.class)) - .isEqualTo(fixture.attempt().publicationFence()); - }); + .satisfies(row -> { + assertThat(row.get("owner_freeze_phase", String.class)).isEqualTo("FROZEN"); + assertThat(row.get("current_publication_fence", UUID.class)) + .isEqualTo(fixture.attempt().publicationFence()); + }); } private static FrozenHistoryFixture frozenHistory(DSLContext sql, TransactionTemplate write) @@ -686,29 +673,26 @@ private static FrozenHistoryFixture frozenHistory(DSLContext sql, TransactionTem var fence = new WorldDesignPublicationFenceRepository(sql, intake); var topology = new WorldDraftTopologyCommitRepository(sql, fence, mapper); var app = application(plan); - write.executeWithoutResult( - ignored -> { - assertThat(sql.fetchValue("SHOW session_replication_role", String.class)) - .isEqualTo("origin"); - var stored = topology.store(plan); - var applied = WorldDraftGraphAppliedResult.create(app, stored.graphBytes()); - new WorldDraftStartLocationReceiptRepository(sql) - .store( - applied.startLocationReceipt().orElseThrow(), - app.operation().accountBindingBytes()); - var operation = app.operation(); - sql.execute( - "INSERT INTO world_draft_graph_application (operation_id,request_id,commit_id,authorization_fence_id,operation_bytes,account_binding_bytes,account_binding_digest,result_bytes,result_digest) VALUES (?,?,?,?,?,?,?,?,?)", - operation.operationId(), - operation.requestId(), - operation.commitId(), - operation.authorizationFenceId(), - operation.canonicalBytes(), - operation.accountBindingBytes(), - operation.accountBindingDigest(), - applied.canonicalBytes(), - applied.digest()); - }); + write.executeWithoutResult(ignored -> { + assertThat(sql.fetchValue("SHOW session_replication_role", String.class)).isEqualTo("origin"); + var stored = topology.store(plan); + var applied = WorldDraftGraphAppliedResult.create(app, stored.graphBytes()); + new WorldDraftStartLocationReceiptRepository(sql) + .store( + applied.startLocationReceipt().orElseThrow(), app.operation().accountBindingBytes()); + var operation = app.operation(); + sql.execute( + "INSERT INTO world_draft_graph_application (operation_id,request_id,commit_id,authorization_fence_id,operation_bytes,account_binding_bytes,account_binding_digest,result_bytes,result_digest) VALUES (?,?,?,?,?,?,?,?,?)", + operation.operationId(), + operation.requestId(), + operation.commitId(), + operation.authorizationFenceId(), + operation.canonicalBytes(), + operation.accountBindingBytes(), + operation.accountBindingDigest(), + applied.canonicalBytes(), + applied.digest()); + }); var digestService = new net.firedevops.firemud.worldmanagement.service.impl.WorldDraftDesignDigestServiceImpl( new net.firedevops.firemud.worldmanagement.repository.RegionRepository(sql), @@ -744,29 +728,27 @@ private static FrozenHistoryFixture frozenHistory(DSLContext sql, TransactionTem .derivedWorkflowIdentity()); var attempt = Objects.requireNonNull( - write.execute( - ignored -> - fence.claimFreeze( - freeze, - () -> { - var digest = - digestService.getDraftDesignDigest( - Long.toString(f.intake().localTenantKey()), - Long.toString(f.version().localVersionKey())); - return new WorldDesignPublicationFenceEvidence.Checkpoint( - plan.binding().commitId().toString(), digest.contentDigest(), 3); - }))); + write.execute(ignored -> + fence.claimFreeze( + freeze, + () -> { + var digest = + digestService.getDraftDesignDigest( + Long.toString(f.intake().localTenantKey()), + Long.toString(f.version().localVersionKey())); + return new WorldDesignPublicationFenceEvidence.Checkpoint( + plan.binding().commitId().toString(), digest.contentDigest(), 3); + }))); var tuples = plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) + .map(unit -> + new WorldAuthoredGraphSnapshot.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) .toList(); var captureRequest = new WorldAuthoredGraphSnapshot.CaptureRequest( @@ -788,10 +770,8 @@ private static FrozenHistoryFixture frozenHistory(DSLContext sql, TransactionTem sql, new WorldAuthoredGraphSnapshotRepository(sql), topology, digestService); var frozen = Objects.requireNonNull( - write.execute( - ignored -> - captures.capture( - new WorldCanonicalFrozenTopology.Request(plan, captureRequest)))); + write.execute(ignored -> + captures.capture(new WorldCanonicalFrozenTopology.Request(plan, captureRequest)))); return new FrozenHistoryFixture(f, plan, selection, attempt, captures, frozen); } @@ -817,84 +797,82 @@ private static Map prepare( UUID instance = UUID.fromString(parsed.get("identity").get("canonicalGameInstanceId").textValue()); return Objects.requireNonNull( - write.execute( - ignored -> { - var row = - sql.fetchSingle( - "SELECT * FROM world_prepare_canonical_instance(?,?)", input, digest); - long allocatedWorldInstanceId = - Objects.requireNonNull(row.get("world_instance_id", Long.class)); - // The historical owner caller retains its exact schema-1 association before the - // deferred - // preparation FK is checked at this same physical transaction's commit. - String associationSelect = - "SELECT 1::SMALLINT AS schema_version,wi.canonical_game_instance_id," - + "wi.canonical_target_namespace,wi.canonical_tenant_id,wi.canonical_world_slug," - + "wi.playable_state_namespace_id,wi.playable_state_scope,wi.public_production," - + "wi.playtest_lifecycle_id,wi.playtest_state_generation," - + "wi.control_plane_request_id,wi.id AS world_instance_id," - + "b.binding_operation_id AS canonical_launch_binding_operation_id," - + "v.operation_id AS version_identity_operation_id,b.canonical_version_id," - + "wi.tenant_id AS local_tenant_key,wi.game_instance_id AS private_game_instance_key," - + "wi.game_template_id,wi.launch_descriptor_id,wi.version_id AS local_version_key," - + "wi.script_patch_version,wi.runtime_flags_json,wi.generation_config_revision," - + "wi.release_bundle_id,wi.published_release_bundle_ref,wi.version_state_epoch," - + "wi.remap_set_id,b.intake_operation_id,b.intake_request_id,b.source_operation_id," - + "b.source_evidence_digest,s.request_digest AS intake_request_digest," - + "b.intake_receipt_digest,b.descriptor_request_digest,b.descriptor_result_digest," - + "b.release_attestation_digest FROM world_instance wi " - + "JOIN world_complete_launch_binding b " - + "ON b.binding_operation_id=wi.canonical_launch_binding_operation_id " - + "JOIN world_authored_version_identity v ON v.operation_id=? " - + "JOIN world_authored_source_intake s ON s.operation_id=b.intake_operation_id " - + "WHERE wi.id=?"; - var expectedAssociation = - Objects.requireNonNull( - sql.fetchOne(associationSelect, versionIdentity, allocatedWorldInstanceId), - "V34 historical fixture could not resolve its exact association fields"); - org.jooq.Record retainedAssociation = - sql.fetchOne( - "SELECT * FROM world_canonical_instance_association " - + "WHERE canonical_game_instance_id = ?", - instance); - if (retainedAssociation == null) { - int inserted = - sql.execute( - "INSERT INTO world_canonical_instance_association (" - + "schema_version,canonical_game_instance_id,canonical_target_namespace," - + "canonical_tenant_id,canonical_world_slug,playable_state_namespace_id," - + "playable_state_scope,public_production,playtest_lifecycle_id," - + "playtest_state_generation,control_plane_request_id,world_instance_id," - + "canonical_launch_binding_operation_id,version_identity_operation_id," - + "canonical_version_id,local_tenant_key,private_game_instance_key," - + "game_template_id,launch_descriptor_id,local_version_key,script_patch_version," - + "runtime_flags_json,generation_config_revision,release_bundle_id," - + "published_release_bundle_ref,version_state_epoch,remap_set_id," - + "intake_operation_id,intake_request_id,source_operation_id,source_evidence_digest," - + "intake_request_digest,intake_receipt_digest,descriptor_request_digest," - + "descriptor_result_digest,release_attestation_digest) " - + associationSelect, - versionIdentity, - allocatedWorldInstanceId); - if (inserted != 1) { - throw new IllegalStateException( - "V34 historical fixture failed to retain its schema-1 association"); - } - retainedAssociation = - Objects.requireNonNull( - sql.fetchOne( - "SELECT * FROM world_canonical_instance_association " - + "WHERE canonical_game_instance_id = ?", - instance), - "V34 historical fixture association was not retained"); - } - if (!java.util.Arrays.equals( - expectedAssociation.intoArray(), retainedAssociation.intoArray())) { - throw new IllegalStateException( - "V34 historical fixture retry differs from its full retained schema-1 association"); - } - return row.intoMap(); - })); + write.execute(ignored -> { + var row = + sql.fetchSingle("SELECT * FROM world_prepare_canonical_instance(?,?)", input, digest); + long allocatedWorldInstanceId = + Objects.requireNonNull(row.get("world_instance_id", Long.class)); + // The historical owner caller retains its exact schema-1 association before the + // deferred + // preparation FK is checked at this same physical transaction's commit. + String associationSelect = + "SELECT 1::SMALLINT AS schema_version,wi.canonical_game_instance_id," + + "wi.canonical_target_namespace,wi.canonical_tenant_id,wi.canonical_world_slug," + + "wi.playable_state_namespace_id,wi.playable_state_scope,wi.public_production," + + "wi.playtest_lifecycle_id,wi.playtest_state_generation," + + "wi.control_plane_request_id,wi.id AS world_instance_id," + + "b.binding_operation_id AS canonical_launch_binding_operation_id," + + "v.operation_id AS version_identity_operation_id,b.canonical_version_id," + + "wi.tenant_id AS local_tenant_key,wi.game_instance_id AS private_game_instance_key," + + "wi.game_template_id,wi.launch_descriptor_id,wi.version_id AS local_version_key," + + "wi.script_patch_version,wi.runtime_flags_json,wi.generation_config_revision," + + "wi.release_bundle_id,wi.published_release_bundle_ref,wi.version_state_epoch," + + "wi.remap_set_id,b.intake_operation_id,b.intake_request_id,b.source_operation_id," + + "b.source_evidence_digest,s.request_digest AS intake_request_digest," + + "b.intake_receipt_digest,b.descriptor_request_digest,b.descriptor_result_digest," + + "b.release_attestation_digest FROM world_instance wi " + + "JOIN world_complete_launch_binding b " + + "ON b.binding_operation_id=wi.canonical_launch_binding_operation_id " + + "JOIN world_authored_version_identity v ON v.operation_id=? " + + "JOIN world_authored_source_intake s ON s.operation_id=b.intake_operation_id " + + "WHERE wi.id=?"; + var expectedAssociation = + Objects.requireNonNull( + sql.fetchOne(associationSelect, versionIdentity, allocatedWorldInstanceId), + "V34 historical fixture could not resolve its exact association fields"); + org.jooq.Record retainedAssociation = + sql.fetchOne( + "SELECT * FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id = ?", + instance); + if (retainedAssociation == null) { + int inserted = + sql.execute( + "INSERT INTO world_canonical_instance_association (" + + "schema_version,canonical_game_instance_id,canonical_target_namespace," + + "canonical_tenant_id,canonical_world_slug,playable_state_namespace_id," + + "playable_state_scope,public_production,playtest_lifecycle_id," + + "playtest_state_generation,control_plane_request_id,world_instance_id," + + "canonical_launch_binding_operation_id,version_identity_operation_id," + + "canonical_version_id,local_tenant_key,private_game_instance_key," + + "game_template_id,launch_descriptor_id,local_version_key,script_patch_version," + + "runtime_flags_json,generation_config_revision,release_bundle_id," + + "published_release_bundle_ref,version_state_epoch,remap_set_id," + + "intake_operation_id,intake_request_id,source_operation_id,source_evidence_digest," + + "intake_request_digest,intake_receipt_digest,descriptor_request_digest," + + "descriptor_result_digest,release_attestation_digest) " + + associationSelect, + versionIdentity, + allocatedWorldInstanceId); + if (inserted != 1) { + throw new IllegalStateException( + "V34 historical fixture failed to retain its schema-1 association"); + } + retainedAssociation = + Objects.requireNonNull( + sql.fetchOne( + "SELECT * FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id = ?", + instance), + "V34 historical fixture association was not retained"); + } + if (!java.util.Arrays.equals( + expectedAssociation.intoArray(), retainedAssociation.intoArray())) { + throw new IllegalStateException( + "V34 historical fixture retry differs from its full retained schema-1 association"); + } + return row.intoMap(); + })); } private static void assertSelector(DSLContext sql, WorldPublishedStartLocationEvidence selector) { @@ -979,20 +957,19 @@ private static ReleaseContent isolatedReleaseContent( var world = Objects.requireNonNull(release.worldStartLocationEvidence()); var participants = release.participantDigests().stream() - .map( - participant -> - new Participant( - participant.participantKey(), - participant.scopeValue(), - participant.baseVersionIdPresent() ? participant.baseVersionId() : null, - participant.appliedCommitId(), - participant.contentDigest(), - participant.digestSchemaVersion(), - participant.abilitySchemaDigestPresent() - ? participant.abilitySchemaDigest() - : null, - null, - null)) + .map(participant -> + new Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent() ? participant.baseVersionId() : null, + participant.appliedCommitId(), + participant.contentDigest(), + participant.digestSchemaVersion(), + participant.abilitySchemaDigestPresent() + ? participant.abilitySchemaDigest() + : null, + null, + null)) .toList(); return new ReleaseContent( release.canonicalTenantId(), @@ -1049,30 +1026,29 @@ private static void retainHistoricalPublicationTerminal( isolatedReleaseContent(input.completeLaunchBinding().evidence()), input.completeLaunchBinding().evidence().releaseAttestation().versionStateEpoch()); var request = WorldPublicationTerminal.Request.fromStored(terminal.canonicalBytes()); - write.executeWithoutResult( - ignored -> { - insertPublicationTerminal(sql, request); - var attempt = - sql.fetchSingle( - "SELECT local_tenant_key,version_id FROM world_design_publication_fence_attempt " - + "WHERE publication_fence=? AND target_namespace=? " - + "AND canonical_tenant_id=? AND canonical_version_id=?", - world.request().publicationFence(), + write.executeWithoutResult(ignored -> { + insertPublicationTerminal(sql, request); + var attempt = + sql.fetchSingle( + "SELECT local_tenant_key,version_id FROM world_design_publication_fence_attempt " + + "WHERE publication_fence=? AND target_namespace=? " + + "AND canonical_tenant_id=? AND canonical_version_id=?", + world.request().publicationFence(), + world.request().targetNamespace(), + world.request().canonicalTenantId(), + world.request().canonicalVersionId()); + assertThat( + sql.execute( + "UPDATE world_design_publication_fence_owner SET owner_freeze_phase='PUBLISHED' " + + "WHERE target_namespace=? AND canonical_tenant_id=? AND local_tenant_key=? " + + "AND version_id=? AND owner_freeze_phase='FROZEN' AND current_publication_fence=?", world.request().targetNamespace(), world.request().canonicalTenantId(), - world.request().canonicalVersionId()); - assertThat( - sql.execute( - "UPDATE world_design_publication_fence_owner SET owner_freeze_phase='PUBLISHED' " - + "WHERE target_namespace=? AND canonical_tenant_id=? AND local_tenant_key=? " - + "AND version_id=? AND owner_freeze_phase='FROZEN' AND current_publication_fence=?", - world.request().targetNamespace(), - world.request().canonicalTenantId(), - attempt.get("local_tenant_key", Long.class), - attempt.get("version_id", Long.class), - world.request().publicationFence())) - .isEqualTo(1); - }); + attempt.get("local_tenant_key", Long.class), + attempt.get("version_id", Long.class), + world.request().publicationFence())) + .isEqualTo(1); + }); } private static byte[] sha256(byte[] bytes) { @@ -1139,15 +1115,14 @@ private static WorldPublishedStartLocationEvidence publishedEvidence( freeze.contentDigest(), freeze.digestSchemaVersion(), freeze.suppliedOwnedAffectedTuples().stream() - .map( - tuple -> - new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( - tuple.owner(), - tuple.aggregateType(), - tuple.aggregateId(), - tuple.scopeType(), - tuple.scopeId(), - tuple.expectedEpoch())) + .map(tuple -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) .toList()), source.selectorReceipt().canonicalBytes(), source.appliedResult().application().operation().accountBindingBytes(), @@ -1194,22 +1169,21 @@ private static WorldCanonicalInstancePreparation.Input preparationInput( var freeze = frozen.request().freeze(); var participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new AuthoredWorldReleaseAttestationEvidence.Participant( + .map(owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(GAME_DESIGN_VERSION), + false, + null, + freeze.appliedCommitId(), + "WORLD_MANAGEMENT".equals(owner) ? freeze.contentDigest() : "a".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( owner, - Long.toString(GAME_DESIGN_VERSION), - false, - null, - freeze.appliedCommitId(), - "WORLD_MANAGEMENT".equals(owner) ? freeze.contentDigest() : "a".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, - selector == null - ? AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION - : AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - "GAME_LOGIC".equals(owner), - "GAME_LOGIC".equals(owner) ? "sha256:" + "b".repeat(64) : null)) + selector == null + ? AuthoredWorldReleaseAttestationEvidence.SCHEMA_VERSION + : AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "b".repeat(64) : null)) .toList(); // Complete legacy release/GS values are constructed test evidence, never live producers. var release = @@ -1257,13 +1231,12 @@ private static WorldCanonicalInstancePreparation.Input preparationInput( selector); var launch = Objects.requireNonNull( - write.execute( - ignored -> - new WorldCompleteLaunchBindingRepository(sql) - .acceptFresh( - NAMESPACE, - f.intake(), - new CompleteLaunchBindingEvidence(descriptor, release)))); + write.execute(ignored -> + new WorldCompleteLaunchBindingRepository(sql) + .acceptFresh( + NAMESPACE, + f.intake(), + new CompleteLaunchBindingEvidence(descriptor, release)))); UUID read = UUID.randomUUID(); UUID instance = UUID.randomUUID(); var request = @@ -1421,43 +1394,42 @@ private static Fixture fixture( Objects.requireNonNull( write.execute(ignored -> intakeRepository.acceptFresh(NAMESPACE, request, source))); return Objects.requireNonNull( - write.execute( - ignored -> { - var stateRequest = - new AuthoredWorldVersionStateEvidence.Request( - 1, - NAMESPACE, - UUID.randomUUID(), - tenant, - slug, - operation, - source.evidenceDigest(), - GAME_DESIGN_VERSION); - var version = - new WorldAuthoredVersionIdentityRepository(dsl) - .acceptFresh( - intake, - AuthoredWorldVersionStateEvidence.create( - stateRequest, - source, - UUID.randomUUID(), - VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, - 1)); - var owner = - new OwnerBinding( - NAMESPACE, - tenant, - version.canonicalVersionId(), - version.operationId(), - GAME_DESIGN_VERSION, - request, - intake.operationId(), - intake.requestDigest(), - operation, - source.evidenceDigest(), - intake.receiptDigest()); - return new Fixture(intake, owner, version); - })); + write.execute(ignored -> { + var stateRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + UUID.randomUUID(), + tenant, + slug, + operation, + source.evidenceDigest(), + GAME_DESIGN_VERSION); + var version = + new WorldAuthoredVersionIdentityRepository(dsl) + .acceptFresh( + intake, + AuthoredWorldVersionStateEvidence.create( + stateRequest, + source, + UUID.randomUUID(), + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + 1)); + var owner = + new OwnerBinding( + NAMESPACE, + tenant, + version.canonicalVersionId(), + version.operationId(), + GAME_DESIGN_VERSION, + request, + intake.operationId(), + intake.requestDigest(), + operation, + source.evidenceDigest(), + intake.receiptDigest()); + return new Fixture(intake, owner, version); + })); } private record Fixture( diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java index 406e32c29b..8a9d91d8ae 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldGameDesignPublicationTerminalVerifierTest.java @@ -70,17 +70,15 @@ void authenticatesSameNamespaceGameDesignCallerBeforeDecodingOrCallingClient() { assertThatThrownBy(() -> verifier.authenticateAndVerifyAndHold(new byte[] {1}, new byte[] {2})) .isInstanceOf(SecurityException.class) .hasMessageContaining("same-namespace Game Design"); - assertThatThrownBy( - () -> - withPeer( - peer("other", "game-design-service"), - () -> verifier.authenticateAndVerifyAndHold(new byte[] {1}, new byte[] {2}))) + assertThatThrownBy(() -> + withPeer( + peer("other", "game-design-service"), + () -> verifier.authenticateAndVerifyAndHold(new byte[] {1}, new byte[] {2}))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withPeer( - peer(NAMESPACE, "game-session-service"), - () -> verifier.authenticateAndVerifyAndHold(new byte[] {1}, new byte[] {2}))) + assertThatThrownBy(() -> + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> verifier.authenticateAndVerifyAndHold(new byte[] {1}, new byte[] {2}))) .isInstanceOf(SecurityException.class); verifyNoInteractions(client); @@ -92,11 +90,10 @@ void requiresNoAmbientTransactionAndRejectsMalformedOperationBeforeRemoteRead() var verifier = new WorldGameDesignPublicationTerminalVerifier(NAMESPACE, client); TransactionSynchronizationManager.setActualTransactionActive(true); try { - assertThatThrownBy( - () -> - withPeer( - peer(NAMESPACE, "game-design-service"), - () -> verifier.authenticateAndVerifyAndHold(new byte[] {1}, new byte[] {2}))) + assertThatThrownBy(() -> + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> verifier.authenticateAndVerifyAndHold(new byte[] {1}, new byte[] {2}))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("outside owner transactions"); } finally { @@ -104,11 +101,10 @@ void requiresNoAmbientTransactionAndRejectsMalformedOperationBeforeRemoteRead() } verifyNoInteractions(client); - assertThatThrownBy( - () -> - withPeer( - peer(NAMESPACE, "game-design-service"), - () -> verifier.authenticateAndVerifyAndHold(new byte[] {1}, new byte[] {2}))) + assertThatThrownBy(() -> + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> verifier.authenticateAndVerifyAndHold(new byte[] {1}, new byte[] {2}))) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(client); } @@ -121,12 +117,11 @@ void authenticatedExactCanonicalReadReturnsClosableAuthorityThroughTheRealClient var operation = operation(); var terminal = terminal(operation, Outcome.NO_PUBLICATION); try (var upstream = new StubbedGameDesignClient(directory)) { - upstream.respondWith( - wireRequest -> { - var readRequest = GameDesignPublicationTerminalReadGrpcCodec.fromRequest(wireRequest); - return GameDesignPublicationTerminalReadGrpcCodec.toResponse( - readRequest, terminalResult(readRequest, terminal)); - }); + upstream.respondWith(wireRequest -> { + var readRequest = GameDesignPublicationTerminalReadGrpcCodec.fromRequest(wireRequest); + return GameDesignPublicationTerminalReadGrpcCodec.toResponse( + readRequest, terminalResult(readRequest, terminal)); + }); var verifier = new WorldGameDesignPublicationTerminalVerifier(NAMESPACE, upstream.client); var verified = withPeer( @@ -156,41 +151,34 @@ void rejectsChangedReadEchoAndSubstitutedCanonicalTerminal(@TempDir Path directo var substitutedTerminal = terminal(operation, Outcome.PUBLISHED); try (var upstream = new StubbedGameDesignClient(directory)) { var verifier = new WorldGameDesignPublicationTerminalVerifier(NAMESPACE, upstream.client); - upstream.respondWith( - wireRequest -> { - var readRequest = GameDesignPublicationTerminalReadGrpcCodec.fromRequest(wireRequest); - var changed = - new GameDesignPublicationTerminalReadEvidence.ReadRequest( - 1, - readRequest.targetNamespace(), - UUID.randomUUID(), - readRequest.operationBytes()); - return GameDesignPublicationTerminalReadGrpcCodec.toResponse( - changed, terminalResult(changed, expectedTerminal)); - }); - assertThatThrownBy( - () -> - withPeer( - peer(NAMESPACE, "game-design-service"), - () -> - verifier.authenticateAndVerifyAndHold( - operation.canonicalBytes(), expectedTerminal.canonicalBytes()))) + upstream.respondWith(wireRequest -> { + var readRequest = GameDesignPublicationTerminalReadGrpcCodec.fromRequest(wireRequest); + var changed = + new GameDesignPublicationTerminalReadEvidence.ReadRequest( + 1, readRequest.targetNamespace(), UUID.randomUUID(), readRequest.operationBytes()); + return GameDesignPublicationTerminalReadGrpcCodec.toResponse( + changed, terminalResult(changed, expectedTerminal)); + }); + assertThatThrownBy(() -> + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> + verifier.authenticateAndVerifyAndHold( + operation.canonicalBytes(), expectedTerminal.canonicalBytes()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("invalid publication terminal read evidence"); - upstream.respondWith( - wireRequest -> { - var readRequest = GameDesignPublicationTerminalReadGrpcCodec.fromRequest(wireRequest); - return GameDesignPublicationTerminalReadGrpcCodec.toResponse( - readRequest, terminalResult(readRequest, substitutedTerminal)); - }); - assertThatThrownBy( - () -> - withPeer( - peer(NAMESPACE, "game-design-service"), - () -> - verifier.authenticateAndVerifyAndHold( - operation.canonicalBytes(), expectedTerminal.canonicalBytes()))) + upstream.respondWith(wireRequest -> { + var readRequest = GameDesignPublicationTerminalReadGrpcCodec.fromRequest(wireRequest); + return GameDesignPublicationTerminalReadGrpcCodec.toResponse( + readRequest, terminalResult(readRequest, substitutedTerminal)); + }); + assertThatThrownBy(() -> + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> + verifier.authenticateAndVerifyAndHold( + operation.canonicalBytes(), expectedTerminal.canonicalBytes()))) .isInstanceOf(SecurityException.class) .hasMessageContaining("differs from the submitted exact operation or result"); } @@ -202,20 +190,18 @@ void unknownOwnerOutcomeNeverCreatesPositiveTerminalAuthority() throws Exception var expected = terminal(operation, Outcome.NO_PUBLICATION); var client = mock(GameDesignPublicationTerminalClient.class); when(client.read(any())) - .thenAnswer( - call -> - new GameDesignPublicationTerminalReadEvidence.ReadResult( - call.getArgument(0), - GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN, - Optional.empty())); + .thenAnswer(call -> + new GameDesignPublicationTerminalReadEvidence.ReadResult( + call.getArgument(0), + GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN, + Optional.empty())); var verifier = new WorldGameDesignPublicationTerminalVerifier(NAMESPACE, client); - assertThatThrownBy( - () -> - withPeer( - peer(NAMESPACE, "game-design-service"), - () -> - verifier.authenticateAndVerifyAndHold( - operation.canonicalBytes(), expected.canonicalBytes()))) + assertThatThrownBy(() -> + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> + verifier.authenticateAndVerifyAndHold( + operation.canonicalBytes(), expected.canonicalBytes()))) .isInstanceOf(SecurityException.class) .hasMessageContaining("unknown"); } @@ -290,15 +276,14 @@ public static GameDesignPublicationOperationBinding operation() throws Exception publicationSources); var tuples = draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) + .map(unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) .toList(); String workflow = PublicationDigestRequestBinding.full( @@ -348,19 +333,18 @@ public static GameDesignPublicationTerminalEvidence terminal( var world = operation.world().request(); var participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new GameDesignPublicationTerminalEvidence.Participant( - owner, - Long.toString(selection.target().gameDesignVersionRowId()), - null, - world.appliedCommitId(), - "WORLD_MANAGEMENT".equals(owner) ? world.contentDigest() : "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), - "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, - null, - null)) + .map(owner -> + new GameDesignPublicationTerminalEvidence.Participant( + owner, + Long.toString(selection.target().gameDesignVersionRowId()), + null, + world.appliedCommitId(), + "WORLD_MANAGEMENT".equals(owner) ? world.contentDigest() : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner) ? "sha256:" + "d".repeat(64) : null, + null, + null)) .toList(); var release = new GameDesignPublicationTerminalEvidence.ReleaseContent( diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeServiceTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeServiceTest.java index 7ff400fb35..6f25fe33bc 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeServiceTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedDraftPublicationFreezeServiceTest.java @@ -64,28 +64,19 @@ void callerAuthenticationPrecedesAnyRepositoryOrRemoteRead() { var collaborators = new Collaborators(); var service = service(fixture, collaborators); - assertThatThrownBy( - () -> - withoutPeer( - () -> - service.freeze( - fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + assertThatThrownBy(() -> + withoutPeer( + () -> service.freeze(fixture.evidence(), fixture.plan(), fixture.accountBinding()))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withPeer( - peer("other", "game-design-service"), - () -> - service.freeze( - fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + assertThatThrownBy(() -> + withPeer( + peer("other", "game-design-service"), + () -> service.freeze(fixture.evidence(), fixture.plan(), fixture.accountBinding()))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withPeer( - peer(NAMESPACE, "game-session-service"), - () -> - service.freeze( - fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + assertThatThrownBy(() -> + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> service.freeze(fixture.evidence(), fixture.plan(), fixture.accountBinding()))) .isInstanceOf(SecurityException.class); collaborators.verifyNoReadsOrWrites(); @@ -146,10 +137,8 @@ void changedAccountOperationOrFenceDeniesAnOtherwiseExactRetry() { fixture.selection(), fixture.accountBinding().operationId(), uuid("14141414-1414-4414-8414-141414141414")); - assertThatThrownBy( - () -> - withGameDesign( - () -> service.freeze(fixture.evidence(), fixture.plan(), changedFence))) + assertThatThrownBy(() -> + withGameDesign(() -> service.freeze(fixture.evidence(), fixture.plan(), changedFence))) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) .hasMessageContaining("Account"); verifyNoInteractions( @@ -168,12 +157,9 @@ void unqualifiedHistoricalAttemptIsDeniedWithoutCurrentStateOrHeldResampling() { when(collaborators.authorizationRepository.readCommitted(prior)).thenReturn(Optional.empty()); var service = service(fixture, collaborators); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.freeze( - fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + assertThatThrownBy(() -> + withGameDesign( + () -> service.freeze(fixture.evidence(), fixture.plan(), fixture.accountBinding()))) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) .hasMessageContaining("no original Account"); verifyNoInteractions( @@ -194,10 +180,8 @@ void completeAccountSelectionRelationIsRejectedBeforeStorageOrTransport() { accountBinding(changedSelection, uuid("15151515-1515-4515-8515-151515151515")); var service = service(fixture, collaborators); - assertThatThrownBy( - () -> - withGameDesign( - () -> service.freeze(fixture.evidence(), fixture.plan(), changedOrder))) + assertThatThrownBy(() -> + withGameDesign(() -> service.freeze(fixture.evidence(), fixture.plan(), changedOrder))) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) .hasMessageContaining("not exact"); collaborators.verifyNoReadsOrWrites(); @@ -214,19 +198,15 @@ void selectedReadMustEchoExactImmutableSelectionBeforeStateOrAccountReads() { var changedSelection = selection(fixture.binding(), "other-selection", VERSION_EPOCH, "other immutable selection"); when(collaborators.selectionClient.read(any())) - .thenAnswer( - invocation -> - selectionRead( - AuthoredDraftPublishSelectionReadEvidence.Request.create( - NAMESPACE, changedSelection))); + .thenAnswer(invocation -> + selectionRead( + AuthoredDraftPublishSelectionReadEvidence.Request.create( + NAMESPACE, changedSelection))); var service = service(fixture, collaborators); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.freeze( - fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + assertThatThrownBy(() -> + withGameDesign( + () -> service.freeze(fixture.evidence(), fixture.plan(), fixture.accountBinding()))) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) .hasMessageContaining("selected Draft read"); verify(collaborators.versionStateClient, never()).read(any()); @@ -245,42 +225,37 @@ void firstFreezeReadsSelectionCurrentDraftAndAccountHeldBeforeOwnerTransaction() when(collaborators.fence.readAttempt(fixture.evidence())) .thenReturn(Optional.empty(), Optional.of(committed)); when(collaborators.selectionClient.read(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - return selectionRead(invocation.getArgument(0)); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return selectionRead(invocation.getArgument(0)); + }); when(collaborators.versionStateClient.read(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - return AuthoredWorldVersionStateEvidence.create( - invocation.getArgument(0), - fixture.source(), - VERSION, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, - VERSION_EPOCH); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return AuthoredWorldVersionStateEvidence.create( + invocation.getArgument(0), + fixture.source(), + VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + VERSION_EPOCH); + }); when(collaborators.accountClient.read(any())) - .thenAnswer( - invocation -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); - return accountRead(invocation.getArgument(0)); - }); + .thenAnswer(invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return accountRead(invocation.getArgument(0)); + }); when(collaborators.checkpointRepository.captureWithSource(fixture.evidence(), fixture.plan())) .thenReturn( new WorldSelectedDraftPublicationCheckpointRepository.CapturedCheckpoint( fixture.checkpoint(), null, null, null, null)); when(collaborators.fence.claimFreeze(eq(fixture.evidence()), any())) - .thenAnswer( - invocation -> { - Checkpoint checkpoint = ((Supplier) invocation.getArgument(1)).get(); - return new FrozenAttempt( - fixture.evidence(), committed.publicationFence(), checkpoint); - }); + .thenAnswer(invocation -> { + Checkpoint checkpoint = ((Supplier) invocation.getArgument(1)).get(); + return new FrozenAttempt(fixture.evidence(), committed.publicationFence(), checkpoint); + }); when(collaborators.authorizationRepository.retainOrRequireExact( committed, fixture.accountBinding(), true)) .thenReturn(fixture.accountBinding()); @@ -335,22 +310,18 @@ void currentStateMustStillBeExactDraftEpochBeforeAccountReadOrFreeze() { when(collaborators.selectionClient.read(any())) .thenAnswer(invocation -> selectionRead(invocation.getArgument(0))); when(collaborators.versionStateClient.read(any())) - .thenAnswer( - invocation -> - AuthoredWorldVersionStateEvidence.create( - invocation.getArgument(0), - fixture.source(), - VERSION, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, - VERSION_EPOCH)); + .thenAnswer(invocation -> + AuthoredWorldVersionStateEvidence.create( + invocation.getArgument(0), + fixture.source(), + VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + VERSION_EPOCH)); var service = service(fixture, collaborators); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.freeze( - fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + assertThatThrownBy(() -> + withGameDesign( + () -> service.freeze(fixture.evidence(), fixture.plan(), fixture.accountBinding()))) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) .hasMessageContaining("DRAFT epoch"); verify(collaborators.accountClient, never()).read(any()); @@ -368,22 +339,18 @@ void staleCurrentEpochIsRejectedBeforeAccountReadOrFreeze() { when(collaborators.selectionClient.read(any())) .thenAnswer(invocation -> selectionRead(invocation.getArgument(0))); when(collaborators.versionStateClient.read(any())) - .thenAnswer( - invocation -> - AuthoredWorldVersionStateEvidence.create( - invocation.getArgument(0), - fixture.source(), - VERSION, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, - VERSION_EPOCH + 1L)); + .thenAnswer(invocation -> + AuthoredWorldVersionStateEvidence.create( + invocation.getArgument(0), + fixture.source(), + VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + VERSION_EPOCH + 1L)); var service = service(fixture, collaborators); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.freeze( - fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + assertThatThrownBy(() -> + withGameDesign( + () -> service.freeze(fixture.evidence(), fixture.plan(), fixture.accountBinding()))) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) .hasMessageContaining("DRAFT epoch"); verify(collaborators.accountClient, never()).read(any()); @@ -401,35 +368,31 @@ void changedCurrentSourceSelectorIsRejectedBeforeAccountReadOrFreeze() { when(collaborators.selectionClient.read(any())) .thenAnswer(invocation -> selectionRead(invocation.getArgument(0))); when(collaborators.versionStateClient.read(any())) - .thenAnswer( - invocation -> { - AuthoredWorldVersionStateEvidence.Request expected = invocation.getArgument(0); - AuthoredWorldSourceEvidence changedSource = changedSource(fixture.source()); - var changedRequest = - new AuthoredWorldVersionStateEvidence.Request( - 1, - NAMESPACE, - expected.readRequestId(), - expected.canonicalTenantId(), - changedSource.worldSlug(), - changedSource.operationId(), - changedSource.evidenceDigest(), - expected.versionId()); - return AuthoredWorldVersionStateEvidence.create( - changedRequest, - changedSource, - VERSION, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, - VERSION_EPOCH); - }); + .thenAnswer(invocation -> { + AuthoredWorldVersionStateEvidence.Request expected = invocation.getArgument(0); + AuthoredWorldSourceEvidence changedSource = changedSource(fixture.source()); + var changedRequest = + new AuthoredWorldVersionStateEvidence.Request( + 1, + NAMESPACE, + expected.readRequestId(), + expected.canonicalTenantId(), + changedSource.worldSlug(), + changedSource.operationId(), + changedSource.evidenceDigest(), + expected.versionId()); + return AuthoredWorldVersionStateEvidence.create( + changedRequest, + changedSource, + VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + VERSION_EPOCH); + }); var service = service(fixture, collaborators); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.freeze( - fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + assertThatThrownBy(() -> + withGameDesign( + () -> service.freeze(fixture.evidence(), fixture.plan(), fixture.accountBinding()))) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) .hasMessageContaining("DRAFT epoch"); verify(collaborators.accountClient, never()).read(any()); @@ -447,29 +410,23 @@ void accountReadMustEchoExactHeldOrderBeforeOwnerFreeze() { when(collaborators.selectionClient.read(any())) .thenAnswer(invocation -> selectionRead(invocation.getArgument(0))); when(collaborators.versionStateClient.read(any())) - .thenAnswer( - invocation -> - AuthoredWorldVersionStateEvidence.create( - invocation.getArgument(0), - fixture.source(), - VERSION, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, - VERSION_EPOCH)); + .thenAnswer(invocation -> + AuthoredWorldVersionStateEvidence.create( + invocation.getArgument(0), + fixture.source(), + VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + VERSION_EPOCH)); var changed = accountBinding(fixture.selection(), uuid("16161616-1616-4616-8616-161616161616")); when(collaborators.accountClient.read(any())) - .thenAnswer( - invocation -> - accountRead( - AccountPublicationAuthorizationReadEvidence.Request.create( - NAMESPACE, changed))); + .thenAnswer(invocation -> + accountRead( + AccountPublicationAuthorizationReadEvidence.Request.create(NAMESPACE, changed))); var service = service(fixture, collaborators); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.freeze( - fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + assertThatThrownBy(() -> + withGameDesign( + () -> service.freeze(fixture.evidence(), fixture.plan(), fixture.accountBinding()))) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) .hasMessageContaining("HELD read"); verify(collaborators.fence, never()).claimFreeze(any(), any()); @@ -486,24 +443,20 @@ void unavailableAccountReadDoesNotCreateOrAcknowledgeFreeze() { when(collaborators.selectionClient.read(any())) .thenAnswer(invocation -> selectionRead(invocation.getArgument(0))); when(collaborators.versionStateClient.read(any())) - .thenAnswer( - invocation -> - AuthoredWorldVersionStateEvidence.create( - invocation.getArgument(0), - fixture.source(), - VERSION, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, - VERSION_EPOCH)); + .thenAnswer(invocation -> + AuthoredWorldVersionStateEvidence.create( + invocation.getArgument(0), + fixture.source(), + VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + VERSION_EPOCH)); when(collaborators.accountClient.read(any())) .thenThrow(new IllegalStateException("Account authorization read unavailable")); var service = service(fixture, collaborators); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.freeze( - fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + assertThatThrownBy(() -> + withGameDesign( + () -> service.freeze(fixture.evidence(), fixture.plan(), fixture.accountBinding()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("unavailable"); verify(collaborators.fence, never()).claimFreeze(any(), any()); @@ -521,14 +474,13 @@ void transactionFailureAfterClaimRollsBackAndReturnsNoAcknowledgement() { when(collaborators.selectionClient.read(any())) .thenAnswer(invocation -> selectionRead(invocation.getArgument(0))); when(collaborators.versionStateClient.read(any())) - .thenAnswer( - invocation -> - AuthoredWorldVersionStateEvidence.create( - invocation.getArgument(0), - fixture.source(), - VERSION, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, - VERSION_EPOCH)); + .thenAnswer(invocation -> + AuthoredWorldVersionStateEvidence.create( + invocation.getArgument(0), + fixture.source(), + VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + VERSION_EPOCH)); when(collaborators.accountClient.read(any())) .thenAnswer(invocation -> accountRead(invocation.getArgument(0))); when(collaborators.checkpointRepository.captureWithSource(fixture.evidence(), fixture.plan())) @@ -536,11 +488,10 @@ void transactionFailureAfterClaimRollsBackAndReturnsNoAcknowledgement() { new WorldSelectedDraftPublicationCheckpointRepository.CapturedCheckpoint( fixture.checkpoint(), null, null, null, null)); when(collaborators.fence.claimFreeze(eq(fixture.evidence()), any())) - .thenAnswer( - invocation -> { - ((Supplier) invocation.getArgument(1)).get(); - return claimed; - }); + .thenAnswer(invocation -> { + ((Supplier) invocation.getArgument(1)).get(); + return claimed; + }); when(collaborators.authorizationRepository.retainOrRequireExact( claimed, fixture.accountBinding(), true)) .thenThrow( @@ -548,12 +499,9 @@ void transactionFailureAfterClaimRollsBackAndReturnsNoAcknowledgement() { "qualification readback failed")); var service = service(fixture, collaborators); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.freeze( - fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + assertThatThrownBy(() -> + withGameDesign( + () -> service.freeze(fixture.evidence(), fixture.plan(), fixture.accountBinding()))) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) .hasMessageContaining("qualification readback"); assertThat(collaborators.transactionManager.commits).isZero(); @@ -572,14 +520,13 @@ void raceLoserCannotAttachAccountOrderToAnExistingUnqualifiedFreeze() { when(collaborators.selectionClient.read(any())) .thenAnswer(invocation -> selectionRead(invocation.getArgument(0))); when(collaborators.versionStateClient.read(any())) - .thenAnswer( - invocation -> - AuthoredWorldVersionStateEvidence.create( - invocation.getArgument(0), - fixture.source(), - VERSION, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, - VERSION_EPOCH)); + .thenAnswer(invocation -> + AuthoredWorldVersionStateEvidence.create( + invocation.getArgument(0), + fixture.source(), + VERSION, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_DRAFT, + VERSION_EPOCH)); when(collaborators.accountClient.read(any())) .thenAnswer(invocation -> accountRead(invocation.getArgument(0))); when(collaborators.fence.claimFreeze(eq(fixture.evidence()), any())).thenReturn(unqualified); @@ -590,12 +537,9 @@ void raceLoserCannotAttachAccountOrderToAnExistingUnqualifiedFreeze() { "unqualified race winner cannot be attached to this Account order")); var service = service(fixture, collaborators); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.freeze( - fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + assertThatThrownBy(() -> + withGameDesign( + () -> service.freeze(fixture.evidence(), fixture.plan(), fixture.accountBinding()))) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) .hasMessageContaining("cannot be attached"); verify(collaborators.checkpointRepository, never()).captureWithSource(any(), any()); @@ -611,12 +555,9 @@ void ambientTransactionIsRejectedBeforeAnyRead() { var service = service(fixture, collaborators); TransactionSynchronizationManager.setActualTransactionActive(true); try { - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.freeze( - fixture.evidence(), fixture.plan(), fixture.accountBinding()))) + assertThatThrownBy(() -> + withGameDesign(() -> + service.freeze(fixture.evidence(), fixture.plan(), fixture.accountBinding()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("ambient transaction"); } finally { diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java index 1d74b3318e..e7eb95e765 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadGrpcServiceTest.java @@ -126,10 +126,9 @@ void attributesWorldStatusAndStorageFailuresToWorldWithoutLeakingDetails() { var fixture = WorldSelectedOwnerInventoryTestFixtures.fixture(Owner.ENTITY_MANAGEMENT); var account = mock(SelectedOwnerIntakeWorldClosureAuthorizationReadClient.class); when(account.readHeld(any())) - .thenAnswer( - invocation -> - new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence( - invocation.getArgument(0))); + .thenAnswer(invocation -> + new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence( + invocation.getArgument(0))); var inventory = mock(WorldSelectedPublicationArtifactInventoryReadService.class); var trailers = new Metadata(); trailers.put( @@ -163,10 +162,9 @@ void attributesWorldStatusAndStorageFailuresToWorldWithoutLeakingDetails() { var fixture = WorldSelectedOwnerInventoryTestFixtures.fixture(Owner.ENTITY_MANAGEMENT); var account = mock(SelectedOwnerIntakeWorldClosureAuthorizationReadClient.class); when(account.readHeld(any())) - .thenAnswer( - invocation -> - new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence( - invocation.getArgument(0))); + .thenAnswer(invocation -> + new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence( + invocation.getArgument(0))); var inventory = mock(WorldSelectedPublicationArtifactInventoryReadService.class); when(inventory.readRetained(any())) .thenThrow(new DataAccessResourceFailureException("secret World storage detail")); diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java index 947877a200..49826c4f80 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedOwnerInventoryReadServiceTest.java @@ -110,31 +110,29 @@ void accountConfirmationPrecedesTheExactRetainedReadForBothOwners() { var callOrder = new ArrayList(); when(account.readHeld(any())) - .thenAnswer( - invocation -> { - var request = - (SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request) - invocation.getArgument(0); - callOrder.add("account"); - assertThat(request.binding().canonicalBytes()) - .containsExactly(fixture.binding().canonicalBytes()); - assertThat(request.intendedReader()) - .isEqualTo("spiffe://firemud/ns/firemud/sa/world-management-service"); - assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); - assertThat(request.readRequestId()).isNotEqualTo(fixture.request().readRequestId()); - assertThat(request.closureReadPurpose()) - .isEqualTo( - owner == Owner.ENTITY_MANAGEMENT - ? "ENTITY_INTAKE_WORLD_CLOSURE_READ" - : "AUTOMATION_INTAKE_WORLD_CLOSURE_READ"); - return new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence(request); - }); + .thenAnswer(invocation -> { + var request = + (SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request) + invocation.getArgument(0); + callOrder.add("account"); + assertThat(request.binding().canonicalBytes()) + .containsExactly(fixture.binding().canonicalBytes()); + assertThat(request.intendedReader()) + .isEqualTo("spiffe://firemud/ns/firemud/sa/world-management-service"); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.readRequestId()).isNotEqualTo(fixture.request().readRequestId()); + assertThat(request.closureReadPurpose()) + .isEqualTo( + owner == Owner.ENTITY_MANAGEMENT + ? "ENTITY_INTAKE_WORLD_CLOSURE_READ" + : "AUTOMATION_INTAKE_WORLD_CLOSURE_READ"); + return new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence(request); + }); when(inventoryRead.readRetained(fixture.freezeEvidence())) - .thenAnswer( - invocation -> { - callOrder.add("retained-world"); - return retainedInventory; - }); + .thenAnswer(invocation -> { + callOrder.add("retained-world"); + return retainedInventory; + }); var service = new WorldSelectedOwnerInventoryReadService(NAMESPACE, inventoryRead, account); var result = @@ -158,28 +156,26 @@ void absentOrChangedAccountEchoNeverReadsWorldStorage() { var inventoryRead = mock(WorldSelectedPublicationArtifactInventoryReadService.class); var account = mock(SelectedOwnerIntakeWorldClosureAuthorizationReadClient.class); when(account.readHeld(any())) - .thenAnswer( - invocation -> { - var expected = - (SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request) - invocation.getArgument(0); - if (absent) return null; - var changed = - SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create( - NAMESPACE, fixture.binding()); - while (changed.readRequestId().equals(expected.readRequestId())) { - changed = - SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create( - NAMESPACE, fixture.binding()); - } - return new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence(changed); - }); + .thenAnswer(invocation -> { + var expected = + (SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request) + invocation.getArgument(0); + if (absent) return null; + var changed = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create( + NAMESPACE, fixture.binding()); + while (changed.readRequestId().equals(expected.readRequestId())) { + changed = + SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence.Request.create( + NAMESPACE, fixture.binding()); + } + return new SelectedOwnerIntakeWorldClosureAuthorizationReadEvidence(changed); + }); var service = new WorldSelectedOwnerInventoryReadService(NAMESPACE, inventoryRead, account); - assertThatThrownBy( - () -> - withPeer( - peer(NAMESPACE, serviceName(owner)), () -> service.read(fixture.request()))) + assertThatThrownBy(() -> + withPeer( + peer(NAMESPACE, serviceName(owner)), () -> service.read(fixture.request()))) .isInstanceOfSatisfying( WorldSelectedOwnerInventoryReadService.ReadFailure.class, failure -> { diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java index 0d77a6b099..5621e5b315 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationArtifactInventoryTest.java @@ -40,10 +40,9 @@ void projectsOriginalTypedItemAndNpcSourcesWithCanonicalUuidRepresentation() { assertThat(projected.entityVersionId()).isEqualTo(VERSION); assertThat(projected.entityTemplateId()).isEqualTo(row.entityReference().templateId()); assertThat(projected.spawnCount()).isEqualTo(2); - assertThatCode( - () -> - WorldSelectedPublicationArtifactInventory.requireSupportedRequiredness( - TENANT, VERSION, List.of(), 0, List.of(projected))) + assertThatCode(() -> + WorldSelectedPublicationArtifactInventory.requireSupportedRequiredness( + TENANT, VERSION, List.of(), 0, List.of(projected))) .doesNotThrowAnyException(); } } @@ -161,10 +160,9 @@ void acceptsExplicitEmptyRegionInputsAndClosedCanonicalSpawnBinding() { 2, 30); - assertThatCode( - () -> - WorldSelectedPublicationArtifactInventory.requireSupportedRequiredness( - TENANT, VERSION, List.of(region), 0, List.of(spawn))) + assertThatCode(() -> + WorldSelectedPublicationArtifactInventory.requireSupportedRequiredness( + TENANT, VERSION, List.of(region), 0, List.of(spawn))) .doesNotThrowAnyException(); } @@ -261,19 +259,17 @@ void canonicalLongFieldsRoundTripAsExactDecimalStrings() { canonicalJson.replace( "\"versionStateEpoch\":\"9223372036854775807\"", "\"versionStateEpoch\":\"09223372036854775807\""); - assertThatThrownBy( - () -> - WorldSelectedPublicationArtifactInventory.decodeCanonicalEnvelope( - zeroPaddedEpoch.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + WorldSelectedPublicationArtifactInventory.decodeCanonicalEnvelope( + zeroPaddedEpoch.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); String floatingEpoch = canonicalJson.replace( "\"versionStateEpoch\":\"9223372036854775807\"", "\"versionStateEpoch\":9223372036854775807.0"); - assertThatThrownBy( - () -> - WorldSelectedPublicationArtifactInventory.decodeCanonicalEnvelope( - floatingEpoch.getBytes(StandardCharsets.UTF_8))) + assertThatThrownBy(() -> + WorldSelectedPublicationArtifactInventory.decodeCanonicalEnvelope( + floatingEpoch.getBytes(StandardCharsets.UTF_8))) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); } @@ -388,12 +384,11 @@ void closureProfileRetainsExplicitSourceAndRequiresSelectedDigestSchema4() { envelope.checkpoint().appliedCommitId(), envelope.checkpoint().contentDigest(), 3), envelope.sourceModel(), envelope.artifactDecisions()); - assertThatThrownBy( - () -> - new WorldSelectedPublicationArtifactInventory( - wrongCheckpoint, - WorldSelectedPublicationArtifactInventory.encode(wrongCheckpoint)) - .publicEvidence()) + assertThatThrownBy(() -> + new WorldSelectedPublicationArtifactInventory( + wrongCheckpoint, + WorldSelectedPublicationArtifactInventory.encode(wrongCheckpoint)) + .publicEvidence()) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("participant digest schema"); } diff --git a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationSelectorCaptureTest.java b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationSelectorCaptureTest.java index 92906dc4c5..5f2e7022e4 100644 --- a/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationSelectorCaptureTest.java +++ b/services/world-management-service/src/test/java/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedPublicationSelectorCaptureTest.java @@ -53,15 +53,14 @@ void capturesExactFenceCheckpointAndTuplesFromRetainedApplicationAndAcknowledgem assertThat(frozen.digestSchemaVersion()).isEqualTo(acknowledgement.digestSchemaVersion()); var expectedTuples = fixture.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) + .map(unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) .toList(); assertThat(frozen.suppliedOwnedAffectedTuples()).containsExactlyElementsOf(expectedTuples); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/WorldManagementTemporalHostingTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/WorldManagementTemporalHostingTest.java index da2b184a0e..6f6f8c1024 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/WorldManagementTemporalHostingTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/WorldManagementTemporalHostingTest.java @@ -34,23 +34,22 @@ class WorldManagementTemporalHostingTest { @Test void worldManagementModuleUsesSharedTemporalHostingPattern() { - contextRunner.run( - context -> { - TemporalTaskQueueResolver taskQueues = context.getBean(TemporalTaskQueueResolver.class); - WorkerFactory workerFactory = context.getBean(WorkerFactory.class); - Worker worker = context.getBean(Worker.class); - String taskQueue = taskQueues.forWorkflowFamily("world-lifecycle"); + contextRunner.run(context -> { + TemporalTaskQueueResolver taskQueues = context.getBean(TemporalTaskQueueResolver.class); + WorkerFactory workerFactory = context.getBean(WorkerFactory.class); + Worker worker = context.getBean(Worker.class); + String taskQueue = taskQueues.forWorkflowFamily("world-lifecycle"); - assertThat(taskQueue).isEqualTo("firemud:world-management-service:world-lifecycle"); - assertThat( - FiremudWorkflowIds.workflowId( - "world-lifecycle", "tenant-1", "world-instance", "create-request-1")) - .isEqualTo("world-lifecycle:tenant-1:world-instance:create-request-1"); + assertThat(taskQueue).isEqualTo("firemud:world-management-service:world-lifecycle"); + assertThat( + FiremudWorkflowIds.workflowId( + "world-lifecycle", "tenant-1", "world-instance", "create-request-1")) + .isEqualTo("world-lifecycle:tenant-1:world-instance:create-request-1"); - verify(workerFactory).newWorker(taskQueue); - verify(worker).registerWorkflowImplementationTypes(HostProbeWorkflowImpl.class); - verify(workerFactory).start(); - }); + verify(workerFactory).newWorker(taskQueue); + verify(worker).registerWorkflowImplementationTypes(HostProbeWorkflowImpl.class); + verify(workerFactory).start(); + }); } @Configuration(proxyBeanMethods = false) diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionCanonicalInitialAdmissionOwnerClientTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionCanonicalInitialAdmissionOwnerClientTest.java index 61694a4376..6276d57232 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionCanonicalInitialAdmissionOwnerClientTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionCanonicalInitialAdmissionOwnerClientTest.java @@ -71,10 +71,9 @@ void requiresReadableFileBackedWorkloadMtls(@TempDir Path temporary) throws Exce CommonGrpcClientProperties plaintext = tlsProperties(temporary); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new GrpcGameSessionCanonicalInitialAdmissionOwnerClient( - endpoints, plaintext, new PassingChannelFactory(), NAMESPACE)) + assertThatThrownBy(() -> + new GrpcGameSessionCanonicalInitialAdmissionOwnerClient( + endpoints, plaintext, new PassingChannelFactory(), NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("require workload mTLS"); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProviderTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProviderTest.java index 7b303283bf..0f1f3e83eb 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProviderTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceProviderTest.java @@ -78,29 +78,23 @@ void retainedCarrierRequiresOriginalFixedPeerAndLeafForEveryOwnerOperation() { RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); assertThatThrownBy(() -> withControlledPeer(null, null, evidence::requireFixedGameSessionPeer)) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withControlledPeer( - peer("dev", "game-session-service"), - null, - evidence::requireFixedGameSessionPeer)) + assertThatThrownBy(() -> + withControlledPeer( + peer("dev", "game-session-service"), null, evidence::requireFixedGameSessionPeer)) .isInstanceOf(SecurityException.class); for (GrpcPeerIdentity wrongPeer : new GrpcPeerIdentity[] { peer("dev", "world-management-service"), peer("other", "game-session-service") }) { - assertThatThrownBy( - () -> - withControlledPeer( - wrongPeer, "a".repeat(64), evidence::requireFixedGameSessionPeer)) + assertThatThrownBy(() -> + withControlledPeer(wrongPeer, "a".repeat(64), evidence::requireFixedGameSessionPeer)) .isInstanceOf(SecurityException.class); } - assertThatThrownBy( - () -> - withControlledPeer( - peer("dev", "game-session-service"), - "d".repeat(64), - evidence::requireFixedGameSessionPeer)) + assertThatThrownBy(() -> + withControlledPeer( + peer("dev", "game-session-service"), + "d".repeat(64), + evidence::requireFixedGameSessionPeer)) .isInstanceOf(SecurityException.class); withControlledPeer( peer("dev", "game-session-service"), @@ -188,11 +182,10 @@ void fixtureOwnerWireResultRejectsNonStartingAllocationsBeforeWorldConsumption() .CanonicalGameInstanceLaunchAssociationReadGrpcCodec.toFixtureResponse(original); for (var status : java.util.List.of("RUNNING", "STOPPED")) { var changed = response.toBuilder().setCurrentGameInstanceStatus(status).build(); - assertThatThrownBy( - () -> - net.firedevops.firemud.common.gamesession - .CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse( - original.request(), changed)) + assertThatThrownBy(() -> + net.firedevops.firemud.common.gamesession + .CanonicalGameInstanceLaunchAssociationReadGrpcCodec.fromFixtureResponse( + original.request(), changed)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Fixture launch association read requires the current STARTING snapshot"); } @@ -811,8 +804,8 @@ private static GameDesignClient mockDescriptorReader( private static String capabilityJson( RunOwnedInitialAdmissionFixtureWireCodec.Capability capability) { return """ - {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":%d,"gameTemplateId":%d,"ownerAccountId":%d,"worldSlug":"%s","worldDisplayName":"%s","realmSlug":"%s","realmDisplayName":"%s","visible":%s,"publicProductionRealm":%s,"requiresCharacterSelection":%s,"stateScope":"%s","characterCreationPolicy":"%s","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","claimDigest":"%s"}%n\ - """ + {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":%d,"gameTemplateId":%d,"ownerAccountId":%d,"worldSlug":"%s","worldDisplayName":"%s","realmSlug":"%s","realmDisplayName":"%s","visible":%s,"publicProductionRealm":%s,"requiresCharacterSelection":%s,"stateScope":"%s","characterCreationPolicy":"%s","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","claimDigest":"%s"}%n\ + """ .formatted( capability.schema(), capability.runId(), @@ -845,8 +838,8 @@ private static String receiptJson( var launch = receipt.launchReadEvidence(); var seal = receipt.fixturePolicySeal(); return """ - {"schema":"%s","runId":"%s","composeProjectName":"%s","fixtureOperationId":"%s","ownerService":"%s","gameSessionUriSan":"%s","gameSessionLeafSha256":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","sourceEvidence":{"schemaVersion":%d,"targetNamespace":"%s","registrationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","tenantSlug":"%s","worldSlug":"%s","worldDisplayName":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"launchReadEvidence":{"schema":"%s","gameTemplateId":%d,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"},"creationEvidence":{"schemaVersion":%d,"targetNamespace":"%s","creationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"fixturePolicySeal":{"schema":"%s","ownerService":"%s","operationId":"%s","requestDigest":"%s","evidenceDigest":"%s"}}%n\ - """ + {"schema":"%s","runId":"%s","composeProjectName":"%s","fixtureOperationId":"%s","ownerService":"%s","gameSessionUriSan":"%s","gameSessionLeafSha256":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","sourceEvidence":{"schemaVersion":%d,"targetNamespace":"%s","registrationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","tenantSlug":"%s","worldSlug":"%s","worldDisplayName":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"launchReadEvidence":{"schema":"%s","gameTemplateId":%d,"publishedReleaseBundleBase64":"%s","versionAssetArtifactStateBase64":"%s","versionStateBase64":"%s","launchDescriptorBase64":"%s"},"creationEvidence":{"schemaVersion":%d,"targetNamespace":"%s","creationRequestId":"%s","operationId":"%s","requestDigest":"%s","canonicalTenantId":"%s","sourceGameRowId":%d,"sourceGameTenantKey":"%s","provenanceKind":"%s","evidenceDigest":"%s"},"fixturePolicySeal":{"schema":"%s","ownerService":"%s","operationId":"%s","requestDigest":"%s","evidenceDigest":"%s"}}%n\ + """ .formatted( receipt.schema(), receipt.runId(), diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesTest.java index 36d6780a62..60ec29b859 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesTest.java @@ -79,13 +79,12 @@ private static void assertOverrideRejected( WorldAuthoredSourceIntakeReceipt sourceReceipt = sourceReceipt(evidence); WorldAuthoredVersionIdentityReceipt versionReceipt = versionReceipt(evidence, sourceReceipt); - assertThatThrownBy( - () -> - withFixturePeer( - evidence, - () -> - RunOwnedWorldFixedPresetResources.plan( - evidence, sourceReceipt, versionReceipt))) + assertThatThrownBy(() -> + withFixturePeer( + evidence, + () -> + RunOwnedWorldFixedPresetResources.plan( + evidence, sourceReceipt, versionReceipt))) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith("RUN_OWNED_WORLD_FIXED_PRESET_OVERRIDES_UNSUPPORTED:"); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/GenerationRuleServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/GenerationRuleServiceImplTest.java index 43a419f655..e698fda85a 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/GenerationRuleServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/GenerationRuleServiceImplTest.java @@ -84,9 +84,8 @@ void existingRuleMustMatchLockedScopeAndPreservesOptimisticVersion() { order .verify(repository) .save( - argThat( - entity -> - entity.getVersion() == 3 && Long.valueOf(7L).equals(entity.getVersionId()))); + argThat(entity -> + entity.getVersion() == 3 && Long.valueOf(7L).equals(entity.getVersionId()))); } @Test diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconcilerTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconcilerTest.java index 9472f91fb1..7d4c50c3f7 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconcilerTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconcilerTest.java @@ -89,10 +89,9 @@ void overdueObservationCountsBoundedOwnerPendingCodeWithoutIdentityLabels() { assertThat(counter(meterRegistry, "GS_OWNER_PENDING")).isEqualTo(1.0); assertThat(meterRegistry.getMeters()) - .allSatisfy( - meter -> - assertThat(meter.getId().getTags()) - .containsExactly(Tag.of("error_code", "GS_OWNER_PENDING"))); + .allSatisfy(meter -> + assertThat(meter.getId().getTags()) + .containsExactly(Tag.of("error_code", "GS_OWNER_PENDING"))); verify(service).reconcileOwnerProof(hold.holdId(), ownerProof); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java index f23515e255..1bf0596d86 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java @@ -92,12 +92,11 @@ void acquireAllocatesOpaqueHoldAndExactRetryReusesItsIdentity() { .thenAnswer(invocation -> Optional.ofNullable(persisted.get())); when(holdRepository.hasNonterminalForRealm(TENANT_ID, REALM_UUID)).thenReturn(false); when(holdRepository.insertIfNoUniqueConflict(any())) - .thenAnswer( - invocation -> { - InitialAdmissionBindHold hold = invocation.getArgument(0); - persisted.set(hold); - return Optional.of(hold); - }); + .thenAnswer(invocation -> { + InitialAdmissionBindHold hold = invocation.getArgument(0); + persisted.set(hold); + return Optional.of(hold); + }); var first = service.acquire(request()); var retry = service.acquire(request()); @@ -251,16 +250,15 @@ void exactCommittedPointerAndAuditReadbackTerminalizesAndReplays() { Mockito.eq("audit-100"), Mockito.eq(1L), any())) - .thenAnswer( - invocation -> { - InitialAdmissionBindHold committed = - withTerminalProof( - pending, - ownerProof(Outcome.COMMITTED, true, REQUEST_DIGEST), - invocation.getArgument(3)); - persisted.set(committed); - return Optional.of(committed); - }); + .thenAnswer(invocation -> { + InitialAdmissionBindHold committed = + withTerminalProof( + pending, + ownerProof(Outcome.COMMITTED, true, REQUEST_DIGEST), + invocation.getArgument(3)); + persisted.set(committed); + return Optional.of(committed); + }); var first = service.reconcileOwnerProof(HOLD_ID, ownerProof(Outcome.COMMITTED, true, REQUEST_DIGEST)); @@ -306,9 +304,8 @@ void exactAbortedTombstoneDoesNotRequirePriorPointerAbsence() { Mockito.isNull(), Mockito.isNull(), any())) - .thenAnswer( - invocation -> - Optional.of(withTerminalProof(pending, proof, invocation.getArgument(3)))); + .thenAnswer(invocation -> + Optional.of(withTerminalProof(pending, proof, invocation.getArgument(3)))); var result = service.reconcileOwnerProof(HOLD_ID, proof); @@ -342,9 +339,8 @@ void repeatedIdenticalOwnerErrorsStillTouchAndRotateBlockedHold() { InitialAdmissionBindHold blocked = withStatus(pendingHold(), "RECONCILIATION_REQUIRED", 1L); when(holdRepository.findByHoldId(HOLD_ID)).thenReturn(Optional.of(blocked)); when(holdRepository.markReconciliationRequired(any(), Mockito.eq("GS_OWNER_PENDING"), any())) - .thenAnswer( - invocation -> - Optional.of(withStatus(invocation.getArgument(0), "RECONCILIATION_REQUIRED", 2L))); + .thenAnswer(invocation -> + Optional.of(withStatus(invocation.getArgument(0), "RECONCILIATION_REQUIRED", 2L))); var result = service.reconcileOwnerProof(HOLD_ID, ownerProof(Outcome.PENDING, false, null)); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java index 147772b341..79b9103265 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java @@ -87,12 +87,11 @@ void setUp() { when(entityManagementClient.validateEntityTemplateReference(1L, 7L, "NPC", 55L)) .thenReturn(true); when(regionRepository.save(any(Region.class))) - .thenAnswer( - invocation -> { - Region region = invocation.getArgument(0); - region.setId(44L); - return region; - }); + .thenAnswer(invocation -> { + Region region = invocation.getArgument(0); + region.setId(44L); + return region; + }); when(aggregateEpochRepository.save(any(WorldDesignAggregateEpoch.class))) .thenAnswer(invocation -> invocation.getArgument(0)); when(scopeEpochRepository.findByTenantIdAndVersionIdAndScopeTypeAndScopeId( @@ -381,12 +380,11 @@ void replaceScopeClearsExistingSpawnBindingsWithinZoneSubtree() { 1L, 7L, 12L, "NPC", 55L)) .thenReturn(Optional.empty()); when(worldEntitySpawnBindingRepository.save(any(WorldEntitySpawnBinding.class))) - .thenAnswer( - invocation -> { - WorldEntitySpawnBinding binding = invocation.getArgument(0); - binding.setId(102L); - return binding; - }); + .thenAnswer(invocation -> { + WorldEntitySpawnBinding binding = invocation.getArgument(0); + binding.setId(102L); + return binding; + }); when(aggregateEpochRepository.findByTenantIdAndVersionIdAndAggregateTypeAndAggregateId( 1L, 7L, "WORLD_ENTITY_SPAWN_BINDING", 102L)) .thenReturn(Optional.empty()); @@ -397,18 +395,16 @@ void replaceScopeClearsExistingSpawnBindingsWithinZoneSubtree() { assertEquals("APPLIED", result.result()); verify(worldEntitySpawnBindingRepository) .deleteAll( - org.mockito.ArgumentMatchers.argThat( - bindings -> { - java.util.Iterator iterator = - bindings.iterator(); - if (!iterator.hasNext()) { - return false; - } - WorldEntitySpawnBinding binding = iterator.next(); - return !iterator.hasNext() - && binding.getId().equals(100L) - && binding.getRoom().getId().equals(13L); - })); + org.mockito.ArgumentMatchers.argThat(bindings -> { + java.util.Iterator iterator = bindings.iterator(); + if (!iterator.hasNext()) { + return false; + } + WorldEntitySpawnBinding binding = iterator.next(); + return !iterator.hasNext() + && binding.getId().equals(100L) + && binding.getRoom().getId().equals(13L); + })); } @Test @@ -453,12 +449,11 @@ void replaceScopeClearsExistingSpawnBindingsWithinRegionSubtree() { 1L, 7L, 12L, "NPC", 55L)) .thenReturn(Optional.empty()); when(worldEntitySpawnBindingRepository.save(any(WorldEntitySpawnBinding.class))) - .thenAnswer( - invocation -> { - WorldEntitySpawnBinding binding = invocation.getArgument(0); - binding.setId(102L); - return binding; - }); + .thenAnswer(invocation -> { + WorldEntitySpawnBinding binding = invocation.getArgument(0); + binding.setId(102L); + return binding; + }); when(aggregateEpochRepository.findByTenantIdAndVersionIdAndAggregateTypeAndAggregateId( 1L, 7L, "WORLD_ENTITY_SPAWN_BINDING", 102L)) .thenReturn(Optional.empty()); @@ -470,18 +465,16 @@ void replaceScopeClearsExistingSpawnBindingsWithinRegionSubtree() { assertEquals("APPLIED", result.result()); verify(worldEntitySpawnBindingRepository) .deleteAll( - org.mockito.ArgumentMatchers.argThat( - bindings -> { - java.util.Iterator iterator = - bindings.iterator(); - if (!iterator.hasNext()) { - return false; - } - WorldEntitySpawnBinding binding = iterator.next(); - return !iterator.hasNext() - && binding.getId().equals(100L) - && binding.getRoom().getId().equals(13L); - })); + org.mockito.ArgumentMatchers.argThat(bindings -> { + java.util.Iterator iterator = bindings.iterator(); + if (!iterator.hasNext()) { + return false; + } + WorldEntitySpawnBinding binding = iterator.next(); + return !iterator.hasNext() + && binding.getId().equals(100L) + && binding.getRoom().getId().equals(13L); + })); } @Test @@ -512,12 +505,11 @@ void scopedRoomMutationRejectsRoomOutsideDeclaredZoneSubtree() { Zone zone = zone(13L, 99L); when(zoneRepository.findByTenantIdAndVersionIdAndId(1L, 7L, 13L)).thenReturn(Optional.of(zone)); when(roomRepository.save(any(Room.class))) - .thenAnswer( - invocation -> { - Room room = invocation.getArgument(0); - room.setId(88L); - return room; - }); + .thenAnswer(invocation -> { + Room room = invocation.getArgument(0); + room.setId(88L); + return room; + }); when(ledgerRepository .findByTenantIdAndVersionIdAndCommitIdAndRevisionIdAndOperationTypeAndAggregateTypeAndRequestedAggregateId( 1L, 7L, "commit-room", "revision-room", "UPSERT", "ROOM", "")) @@ -555,12 +547,11 @@ void scopedRoomMutationAllowsRoomInsideDeclaredRegionSubtree() { Zone zone = zone(13L, 99L); when(zoneRepository.findByTenantIdAndVersionIdAndId(1L, 7L, 13L)).thenReturn(Optional.of(zone)); when(roomRepository.save(any(Room.class))) - .thenAnswer( - invocation -> { - Room room = invocation.getArgument(0); - room.setId(88L); - return room; - }); + .thenAnswer(invocation -> { + Room room = invocation.getArgument(0); + room.setId(88L); + return room; + }); when(ledgerRepository .findByTenantIdAndVersionIdAndCommitIdAndRevisionIdAndOperationTypeAndAggregateTypeAndRequestedAggregateId( 1L, 7L, "commit-room", "revision-room", "UPSERT", "ROOM", "")) @@ -586,12 +577,11 @@ void scopedRoomExitRejectsExitCrossingOutsideDeclaredZoneSubtree() { when(roomRepository.findByTenantIdAndVersionIdAndId(1L, 7L, 22L)) .thenReturn(Optional.of(toRoom)); when(roomExitRepository.save(any(RoomExit.class))) - .thenAnswer( - invocation -> { - RoomExit exit = invocation.getArgument(0); - exit.setId(31L); - return exit; - }); + .thenAnswer(invocation -> { + RoomExit exit = invocation.getArgument(0); + exit.setId(31L); + return exit; + }); when(ledgerRepository .findByTenantIdAndVersionIdAndCommitIdAndRevisionIdAndOperationTypeAndAggregateTypeAndRequestedAggregateId( 1L, 7L, "commit-exit", "revision-exit", "UPSERT", "ROOM_EXIT", "")) @@ -651,12 +641,11 @@ void replaceScopeClearsExistingGenerationRulesWithinDeclaredZoneScope() { 1L, 7L, "ZONE_SUBTREE", "12", "population")) .thenReturn(Optional.empty()); when(generationRuleRepository.save(any(GenerationRule.class))) - .thenAnswer( - invocation -> { - GenerationRule rule = invocation.getArgument(0); - rule.setId(71L); - return rule; - }); + .thenAnswer(invocation -> { + GenerationRule rule = invocation.getArgument(0); + rule.setId(71L); + return rule; + }); when(aggregateEpochRepository.findByTenantIdAndVersionIdAndAggregateTypeAndAggregateId( 1L, 7L, "GENERATION_RULE", 71L)) .thenReturn(Optional.empty()); @@ -668,13 +657,12 @@ void replaceScopeClearsExistingGenerationRulesWithinDeclaredZoneScope() { assertEquals("APPLIED", result.result()); verify(generationRuleRepository) .deleteAll( - org.mockito.ArgumentMatchers.argThat( - rules -> { - java.util.Iterator iterator = rules.iterator(); - return iterator.hasNext() - && iterator.next().getId().equals(70L) - && !iterator.hasNext(); - })); + org.mockito.ArgumentMatchers.argThat(rules -> { + java.util.Iterator iterator = rules.iterator(); + return iterator.hasNext() + && iterator.next().getId().equals(70L) + && !iterator.hasNext(); + })); } @Test @@ -800,12 +788,11 @@ void replaceScopeAppliesGeneratedSubtreeInOneScopedMutation() { 1L, 7L, "ZONE_SUBTREE", "12", "population")) .thenReturn(Optional.empty()); when(roomRepository.save(any(Room.class))) - .thenAnswer( - invocation -> { - Room room = invocation.getArgument(0); - room.setId("room-a".equals(room.getName()) ? 90L : 91L); - return room; - }); + .thenAnswer(invocation -> { + Room room = invocation.getArgument(0); + room.setId("room-a".equals(room.getName()) ? 90L : 91L); + return room; + }); when(entityManagementClient.validateEntityTemplateReference(1L, 7L, "NPC", 55L)) .thenReturn(true); when(worldEntitySpawnBindingRepository diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java index 62b1a3b948..beb160c6e1 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java @@ -196,12 +196,11 @@ void prepareWorldInstanceMaterializesSeededRoomIdentityAndActivatesOwnerLifecycl when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) .thenAnswer(invocation -> Optional.ofNullable(storedInstance.get())); when(worldInstanceRepository.save(any(WorldInstance.class))) - .thenAnswer( - invocation -> { - WorldInstance worldInstance = invocation.getArgument(0); - storedInstance.set(worldInstance); - return worldInstance; - }); + .thenAnswer(invocation -> { + WorldInstance worldInstance = invocation.getArgument(0); + storedInstance.set(worldInstance); + return worldInstance; + }); var prepared = service.prepareWorldInstance( @@ -384,11 +383,10 @@ void fixtureFailureRequiresExactOwnerAndUsesLockedLegacyRow() { RunOwnedWorldLaunchEvidence evidence = mock(RunOwnedWorldLaunchEvidence.class); when(provider.isEnabled()).thenReturn(true); when(provider.requireAuthenticatedEvidence()) - .thenAnswer( - invocation -> { - assertFalse(localTransactionActive.get()); - return evidence; - }); + .thenAnswer(invocation -> { + assertFalse(localTransactionActive.get()); + return evidence; + }); when(evidence.bindingDigest(any(PreparedWorldInstanceRequest.class), anyLong())) .thenReturn("c".repeat(64)); WorldInstance instance = boundFixtureInstance("PREPARING", 1L); @@ -565,11 +563,10 @@ void terminationDoesNotCrossAnUnresolvedInitialAdmissionBindHold() { WorldInstance instance = activeWorldInstance(); stubPersistedWorldInstance(instance); when(worldInstanceRepository.hasNonterminalInitialAdmissionBindHold(42L, 101L)) - .thenAnswer( - invocation -> { - assertTrue(localTransactionActive.get()); - return true; - }); + .thenAnswer(invocation -> { + assertTrue(localTransactionActive.get()); + return true; + }); IllegalArgumentException error = assertThrows( @@ -595,11 +592,10 @@ void fixtureTerminationKeepsActiveRowAndSkipsEntityWhenOwnerHoldIsUnresolved() { WorldInstance instance = boundFixtureInstance("ACTIVE", 2L); stubPersistedWorldInstance(instance); when(worldInstanceRepository.hasNonterminalInitialAdmissionBindHold(42L, 101L)) - .thenAnswer( - invocation -> { - assertTrue(localTransactionActive.get()); - return true; - }); + .thenAnswer(invocation -> { + assertTrue(localTransactionActive.get()); + return true; + }); IllegalArgumentException error = assertThrows( @@ -726,11 +722,10 @@ void entityCleanupRunsBeforeTheLocalWorldTransaction() { .when(worldEventRepository) .deleteByTenantIdAndGameInstanceId(42L, 101L); when(entityManagementClient.cleanupRuntimeInstance(42L, 101L, "term-1")) - .thenAnswer( - invocation -> { - assertFalse(localTransactionActive.get()); - return CleanupRuntimeInstanceResponse.newBuilder().build(); - }); + .thenAnswer(invocation -> { + assertFalse(localTransactionActive.get()); + return CleanupRuntimeInstanceResponse.newBuilder().build(); + }); var snapshot = service.terminateWorldInstance(42L, 101L, 2L, "term-1", "stop"); @@ -750,13 +745,12 @@ void terminationFinalizationRejectsChangedRequestBeforeLocalCleanup() { WorldInstance instance = activeWorldInstance(); AtomicReference persisted = stubPersistedWorldInstance(instance); when(entityManagementClient.cleanupRuntimeInstance(42L, 101L, "term-1")) - .thenAnswer( - invocation -> { - WorldInstance changed = copyWorldInstance(persisted.get()); - changed.setTerminationRequestId("term-2"); - persisted.set(changed); - return CleanupRuntimeInstanceResponse.newBuilder().build(); - }); + .thenAnswer(invocation -> { + WorldInstance changed = copyWorldInstance(persisted.get()); + changed.setTerminationRequestId("term-2"); + persisted.set(changed); + return CleanupRuntimeInstanceResponse.newBuilder().build(); + }); IllegalArgumentException error = assertThrows( @@ -776,13 +770,12 @@ void terminationFinalizationRejectsChangedStateBeforeLocalCleanup() { WorldInstance instance = activeWorldInstance(); AtomicReference persisted = stubPersistedWorldInstance(instance); when(entityManagementClient.cleanupRuntimeInstance(42L, 101L, "term-1")) - .thenAnswer( - invocation -> { - WorldInstance changed = copyWorldInstance(persisted.get()); - changed.setStatus("ACTIVE"); - persisted.set(changed); - return CleanupRuntimeInstanceResponse.newBuilder().build(); - }); + .thenAnswer(invocation -> { + WorldInstance changed = copyWorldInstance(persisted.get()); + changed.setStatus("ACTIVE"); + persisted.set(changed); + return CleanupRuntimeInstanceResponse.newBuilder().build(); + }); IllegalArgumentException error = assertThrows( @@ -802,15 +795,14 @@ void terminationFinalizationAcceptsSameRequestConcurrentCompletionWithoutDoubleE WorldInstance instance = activeWorldInstance(); AtomicReference persisted = stubPersistedWorldInstance(instance); when(entityManagementClient.cleanupRuntimeInstance(42L, 101L, "term-1")) - .thenAnswer( - invocation -> { - WorldInstance completed = copyWorldInstance(persisted.get()); - completed.setStatus("TERMINATED"); - completed.setLifecycleEpoch(4L); - completed.setTerminatedAt(Instant.parse("2026-09-01T00:00:00Z")); - persisted.set(completed); - return CleanupRuntimeInstanceResponse.newBuilder().build(); - }); + .thenAnswer(invocation -> { + WorldInstance completed = copyWorldInstance(persisted.get()); + completed.setStatus("TERMINATED"); + completed.setLifecycleEpoch(4L); + completed.setTerminatedAt(Instant.parse("2026-09-01T00:00:00Z")); + persisted.set(completed); + return CleanupRuntimeInstanceResponse.newBuilder().build(); + }); var snapshot = service.terminateWorldInstance(42L, 101L, 2L, "term-1", "stop"); @@ -835,14 +827,13 @@ void terminationFinalizationPropagatesOptimisticWriteFailure() { when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) .thenReturn(Optional.of(instance), Optional.of(terminating)); when(worldInstanceRepository.save(any(WorldInstance.class))) - .thenAnswer( - invocation -> { - WorldInstance submitted = invocation.getArgument(0); - if ("TERMINATED".equals(submitted.getStatus())) { - throw new IllegalStateException("stale write for world_instance"); - } - return submitted; - }); + .thenAnswer(invocation -> { + WorldInstance submitted = invocation.getArgument(0); + if ("TERMINATED".equals(submitted.getStatus())) { + throw new IllegalStateException("stale write for world_instance"); + } + return submitted; + }); IllegalStateException error = assertThrows( @@ -1079,13 +1070,12 @@ void fixturePrepareBindsOriginalPreparingEpochAndExactRetryDoesNotRepeatMaterial when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) .thenAnswer(invocation -> Optional.ofNullable(persisted.get())); when(worldInstanceRepository.save(any(WorldInstance.class))) - .thenAnswer( - invocation -> { - WorldInstance submitted = invocation.getArgument(0); - submitted.setId(101L); - persisted.set(copyWorldInstance(submitted)); - return submitted; - }); + .thenAnswer(invocation -> { + WorldInstance submitted = invocation.getArgument(0); + submitted.setId(101L); + persisted.set(copyWorldInstance(submitted)); + return submitted; + }); WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider); PreparedWorldInstanceRequest request = ordinaryPreparedRequest(); @@ -1197,13 +1187,12 @@ void fixtureActivationVerifiesBindingThenAllowsOnlyOriginalEpochActiveReplayWith when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) .thenAnswer(invocation -> Optional.of(copyWorldInstance(persisted.get()))); when(worldInstanceRepository.save(any(WorldInstance.class))) - .thenAnswer( - invocation -> { - WorldInstance submitted = invocation.getArgument(0); - submitted.setRowVersion(submitted.getRowVersion() + 1L); - persisted.set(copyWorldInstance(submitted)); - return copyWorldInstance(submitted); - }); + .thenAnswer(invocation -> { + WorldInstance submitted = invocation.getArgument(0); + submitted.setRowVersion(submitted.getRowVersion() + 1L); + persisted.set(copyWorldInstance(submitted)); + return copyWorldInstance(submitted); + }); WorldLifecycleCommandServiceImpl fixtureService = fixtureService(provider); var active = fixtureService.activatePreparedWorldInstance(42L, 101L, 1L); @@ -1382,40 +1371,37 @@ private AtomicReference stubPersistedWorldInstance(WorldInstance new AtomicReference<>(copyWorldInstance(initiallyLoaded)); AtomicBoolean firstFind = new AtomicBoolean(true); when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) - .thenAnswer( - invocation -> { - if (localTransactionActive.get()) { - worldInstanceReadInLocalTransaction.set(true); - } - if (firstFind.compareAndSet(true, false)) { - return Optional.of(initiallyLoaded); - } - return Optional.of(copyWorldInstance(persisted.get())); - }); + .thenAnswer(invocation -> { + if (localTransactionActive.get()) { + worldInstanceReadInLocalTransaction.set(true); + } + if (firstFind.compareAndSet(true, false)) { + return Optional.of(initiallyLoaded); + } + return Optional.of(copyWorldInstance(persisted.get())); + }); AtomicBoolean firstLockedFind = new AtomicBoolean(true); when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) - .thenAnswer( - invocation -> { - if (localTransactionActive.get()) { - worldInstanceReadInLocalTransaction.set(true); - } - return firstLockedFind.compareAndSet(true, false) - ? Optional.of(initiallyLoaded) - : Optional.of(copyWorldInstance(persisted.get())); - }); + .thenAnswer(invocation -> { + if (localTransactionActive.get()) { + worldInstanceReadInLocalTransaction.set(true); + } + return firstLockedFind.compareAndSet(true, false) + ? Optional.of(initiallyLoaded) + : Optional.of(copyWorldInstance(persisted.get())); + }); when(worldInstanceRepository.save(any(WorldInstance.class))) - .thenAnswer( - invocation -> { - WorldInstance submitted = invocation.getArgument(0); - if ("TERMINATED".equals(submitted.getStatus())) { - assertTrue(localTransactionActive.get()); - } - WorldInstance saved = copyWorldInstance(submitted); - long rowVersion = submitted.getRowVersion() == null ? 0L : submitted.getRowVersion(); - saved.setRowVersion(rowVersion + 1L); - persisted.set(saved); - return copyWorldInstance(saved); - }); + .thenAnswer(invocation -> { + WorldInstance submitted = invocation.getArgument(0); + if ("TERMINATED".equals(submitted.getStatus())) { + assertTrue(localTransactionActive.get()); + } + WorldInstance saved = copyWorldInstance(submitted); + long rowVersion = submitted.getRowVersion() == null ? 0L : submitted.getRowVersion(); + saved.setRowVersion(rowVersion + 1L); + persisted.set(saved); + return copyWorldInstance(saved); + }); return persisted; } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java index 61d587427a..62ea0c0d43 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java @@ -562,14 +562,11 @@ void getDraftDesignDigestRejectsChangedBindingBeforeOwnerRead() { SessionContext.setContext( null, List.of(), Map.of(), true, "game-design-service", "test-instance"); AtomicReference ref = new AtomicReference<>(); - runAsGameDesign( - () -> - ref.set( - invokeDigest( - service, - fullDigestRequest("1", "7").toBuilder() - .setRequestDigest("0".repeat(64)) - .build()))); + runAsGameDesign(() -> + ref.set( + invokeDigest( + service, + fullDigestRequest("1", "7").toBuilder().setRequestDigest("0".repeat(64)).build()))); assertEquals("INVALID_ARGUMENT", ref.get().getError().getCode()); Mockito.verifyNoInteractions(digestService); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodecTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodecTest.java index 3ff3b0b00a..cda3f16598 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodecTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationGrpcCodecTest.java @@ -57,10 +57,9 @@ void decodesTheCompleteEntityTargetAndExactOwnerSelectors() { @Test void rejectsMissingUnknownAndMalformedSelectorsBeforeOwnerReads() { - assertThatThrownBy( - () -> - CanonicalInitialPlayerLocationGrpcCodec.fromRequest( - CanonicalInitialPlayerLocationRequest.getDefaultInstance())) + assertThatThrownBy(() -> + CanonicalInitialPlayerLocationGrpcCodec.fromRequest( + CanonicalInitialPlayerLocationRequest.getDefaultInstance())) .isInstanceOf(IllegalArgumentException.class); var unknownRequest = @@ -232,12 +231,10 @@ void rendersOnlyRetainedAppliedOrConflictOutcomes() { assertThat(conflictResponse.hasStartLocation()).isFalse(); assertThat(conflictResponse.getPrivateRuntimeRoomKey()).isEmpty(); - assertThatThrownBy( - () -> - CanonicalInitialPlayerLocationGrpcCodec.toResponse( - selection, - new Result( - Outcome.UNREGISTERED, null, null, null, null, null, null, null, false))) + assertThatThrownBy(() -> + CanonicalInitialPlayerLocationGrpcCodec.toResponse( + selection, + new Result(Outcome.UNREGISTERED, null, null, null, null, null, null, null, false))) .isInstanceOf(IllegalStateException.class); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationServiceTest.java index 4c41c5fc2d..05d9be72e8 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/CanonicalInitialPlayerLocationServiceTest.java @@ -75,39 +75,37 @@ void createdHistoricalReferenceIsReadBeforeLocalSqlAndPreservesStableSelectors() var preseeded = mock(CanonicalInitialPlayerLocationService.EntityReceiptReader.class); var created = mock(CanonicalInitialPlayerLocationService.EntityCreatedReceiptReader.class); when(created.read(any())) - .thenAnswer( - call -> { - verifyNoInteractions(location); - var selector = - (net.firedevops.firemud.entitymanagement.v1 - .PlayerCreatedActorRuntimeReferenceRequest) - call.getArgument(0); - assertThat(selector.getAccountUuid()) - .isEqualTo(selection.canonicalAccountId().toString()); - assertThat(selector.getOrigin()).isEqualTo(selection.playerCreatedOrigin()); - // Explicit controlled authenticated-response input; no genuine Entity producer claim. - var verified = - mock( - net.firedevops.firemud.worldmanagement.client - .EntityPlayerCreatedActorPlacementReceiptClient.VerifiedReceipt.class); - when(verified.response()) - .thenReturn( - net.firedevops.firemud.entitymanagement.v1 - .PlayerCreatedActorRuntimeReferenceResponse.newBuilder() - .setSchemaVersion(1) - .setSelector(selector) - .setRuntimeEntityId(23L) - .setProjectionGeneration(1L) - .setProjectionFence(1L) - .setOriginalCatalogRevision(1L) - .setOriginalPointerVersion(1L) - .setOriginalActiveLifecycleEpoch(1L) - .setOriginalDescriptorDigest("sha256:" + "a".repeat(64)) - .setOriginalAuthoredBindingDigest("sha256:" + "b".repeat(64)) - .setOriginalPolicyContentDigest("sha256:" + "c".repeat(64)) - .build()); - return verified; - }); + .thenAnswer(call -> { + verifyNoInteractions(location); + var selector = + (net.firedevops.firemud.entitymanagement.v1.PlayerCreatedActorRuntimeReferenceRequest) + call.getArgument(0); + assertThat(selector.getAccountUuid()) + .isEqualTo(selection.canonicalAccountId().toString()); + assertThat(selector.getOrigin()).isEqualTo(selection.playerCreatedOrigin()); + // Explicit controlled authenticated-response input; no genuine Entity producer claim. + var verified = + mock( + net.firedevops.firemud.worldmanagement.client + .EntityPlayerCreatedActorPlacementReceiptClient.VerifiedReceipt.class); + when(verified.response()) + .thenReturn( + net.firedevops.firemud.entitymanagement.v1 + .PlayerCreatedActorRuntimeReferenceResponse.newBuilder() + .setSchemaVersion(1) + .setSelector(selector) + .setRuntimeEntityId(23L) + .setProjectionGeneration(1L) + .setProjectionFence(1L) + .setOriginalCatalogRevision(1L) + .setOriginalPointerVersion(1L) + .setOriginalActiveLifecycleEpoch(1L) + .setOriginalDescriptorDigest("sha256:" + "a".repeat(64)) + .setOriginalAuthoredBindingDigest("sha256:" + "b".repeat(64)) + .setOriginalPolicyContentDigest("sha256:" + "c".repeat(64)) + .build()); + return verified; + }); when(location.readByOperationId(eq(selection.placementOperationId()), any())) .thenReturn(Optional.empty()); var service = @@ -139,10 +137,8 @@ void createdRemoteFailureStopsBeforeLocalSql() { }); assertThatThrownBy(() -> service.place(selection)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.UNAVAILABLE)); verifyNoInteractions(association, location, holds, gameSession, preseeded); } @@ -185,10 +181,9 @@ void unavailableEntityReceiptStopsBeforeHoldOrPlacementWrite() { assertThatThrownBy(() -> service.place(selection)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - org.assertj.core.api.Assertions.assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAVAILABLE)); + .satisfies(failure -> + org.assertj.core.api.Assertions.assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAVAILABLE)); verifyNoInteractions(holds, gameSession); verify(location, never()).store(any()); @@ -363,10 +358,9 @@ void regionReadWithRetainedConflictFailsBeforeReadingRegion() { assertThatThrownBy(() -> service.readRegion(selection)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - org.assertj.core.api.Assertions.assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + org.assertj.core.api.Assertions.assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); assertThat(entityReads.get()).isZero(); verify(location, never()).readInitialPlayerLocationRegion(any(RequestSelector.class)); @@ -408,10 +402,9 @@ void mismatchedEntityReceiptStopsRegionReadBeforePlacementMutation() { assertThatThrownBy(() -> service.readRegion(selection)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - org.assertj.core.api.Assertions.assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + org.assertj.core.api.Assertions.assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); assertThat(entityReads.get()).isEqualTo(1); verify(location, never()).readInitialPlayerLocationRegion(any(RequestSelector.class)); @@ -431,10 +424,9 @@ void mismatchedEntityReceiptStopsBeforeHoldOrPlacementWrite() { assertThatThrownBy(() -> service.place(selection)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - org.assertj.core.api.Assertions.assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + org.assertj.core.api.Assertions.assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); verifyNoInteractions(holds, gameSession); verify(location, never()).store(any()); @@ -452,10 +444,9 @@ void missingCommittedWorldHoldStopsBeforeGameSessionOrPlacementWrite() { assertThatThrownBy(() -> service.place(selection)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - org.assertj.core.api.Assertions.assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + org.assertj.core.api.Assertions.assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); verifyNoInteractions(gameSession); verify(location, never()).store(any()); @@ -467,29 +458,27 @@ void mismatchedWorldHoldFenceStopsBeforeGameSessionOrPlacementWrite() { var location = emptyLocation(selection); var holds = mock(WorldCanonicalInitialAdmissionHoldRepository.class); when(holds.readState(any(), any())) - .thenAnswer( - invocation -> { - HoldIdentity requested = invocation.getArgument(0); - var mismatchedIdentity = - new HoldIdentity( - requested.request(), - requested.holdId(), - uuid("12121212-1212-4212-8212-121212121212")); - var state = mock(WorldCanonicalInitialAdmissionHoldState.class); - when(state.holdIdentity()).thenReturn(mismatchedIdentity); - when(state.holdStatus()).thenReturn(HoldStatus.COMMITTED); - return Optional.of(state); - }); + .thenAnswer(invocation -> { + HoldIdentity requested = invocation.getArgument(0); + var mismatchedIdentity = + new HoldIdentity( + requested.request(), + requested.holdId(), + uuid("12121212-1212-4212-8212-121212121212")); + var state = mock(WorldCanonicalInitialAdmissionHoldState.class); + when(state.holdIdentity()).thenReturn(mismatchedIdentity); + when(state.holdStatus()).thenReturn(HoldStatus.COMMITTED); + return Optional.of(state); + }); var gameSession = mock(GameSessionCanonicalInitialAdmissionOwnerClient.class); var service = service(selection, location, holds, gameSession, ignored -> entityReceipt(selection)); assertThatThrownBy(() -> service.place(selection)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - org.assertj.core.api.Assertions.assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + org.assertj.core.api.Assertions.assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); verifyNoInteractions(gameSession); verify(location, never()).store(any()); @@ -501,27 +490,25 @@ void staleWorldActiveEpochStopsBeforeGameSessionOrPlacementWrite() { var location = emptyLocation(selection); var holds = mock(WorldCanonicalInitialAdmissionHoldRepository.class); when(holds.readState(any(), any())) - .thenAnswer( - invocation -> { - var state = mock(WorldCanonicalInitialAdmissionHoldState.class); - when(state.holdIdentity()).thenReturn(invocation.getArgument(0)); - when(state.holdStatus()).thenReturn(HoldStatus.COMMITTED); - var lifecycle = mock(WorldCanonicalInstanceLifecycleEvidence.class); - when(lifecycle.lifecycleStatus()).thenReturn("ACTIVE"); - when(lifecycle.lifecycleEpoch()).thenReturn(selection.activeLifecycleEpoch() - 1); - when(state.lifecycleEvidence()).thenReturn(lifecycle); - return Optional.of(state); - }); + .thenAnswer(invocation -> { + var state = mock(WorldCanonicalInitialAdmissionHoldState.class); + when(state.holdIdentity()).thenReturn(invocation.getArgument(0)); + when(state.holdStatus()).thenReturn(HoldStatus.COMMITTED); + var lifecycle = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(lifecycle.lifecycleStatus()).thenReturn("ACTIVE"); + when(lifecycle.lifecycleEpoch()).thenReturn(selection.activeLifecycleEpoch() - 1); + when(state.lifecycleEvidence()).thenReturn(lifecycle); + return Optional.of(state); + }); var gameSession = mock(GameSessionCanonicalInitialAdmissionOwnerClient.class); var service = service(selection, location, holds, gameSession, ignored -> entityReceipt(selection)); assertThatThrownBy(() -> service.place(selection)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - org.assertj.core.api.Assertions.assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + org.assertj.core.api.Assertions.assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); verifyNoInteractions(gameSession); verify(location, never()).store(any()); @@ -534,28 +521,27 @@ void nonCommittedGameSessionTerminalStopsBeforePlacementWrite() { var holds = mock(WorldCanonicalInitialAdmissionHoldRepository.class); var readIdentity = new AtomicReference(); when(holds.readState(any(), any())) - .thenAnswer( - invocation -> { - readIdentity.set(invocation.getArgument(0)); - var lifecycleRequest = mock(Request.class); - when(lifecycleRequest.canonicalGameInstanceId()).thenReturn(GAME_INSTANCE); - when(lifecycleRequest.canonicalTenantId()).thenReturn(TENANT); - when(lifecycleRequest.canonicalVersionId()).thenReturn(VERSION); - when(lifecycleRequest.playableStateNamespaceId()).thenReturn(PLAYABLE_NAMESPACE); - var start = mock(RoomTemplateRef.class); - when(start.tenantId()).thenReturn(TENANT); - when(start.versionId()).thenReturn(VERSION); - var lifecycle = mock(WorldCanonicalInstanceLifecycleEvidence.class); - when(lifecycle.lifecycleStatus()).thenReturn("ACTIVE"); - when(lifecycle.lifecycleEpoch()).thenReturn(selection.activeLifecycleEpoch()); - when(lifecycle.request()).thenReturn(lifecycleRequest); - when(lifecycle.startLocation()).thenReturn(start); - var state = mock(WorldCanonicalInitialAdmissionHoldState.class); - when(state.holdIdentity()).thenReturn(invocation.getArgument(0)); - when(state.holdStatus()).thenReturn(HoldStatus.COMMITTED); - when(state.lifecycleEvidence()).thenReturn(lifecycle); - return Optional.of(state); - }); + .thenAnswer(invocation -> { + readIdentity.set(invocation.getArgument(0)); + var lifecycleRequest = mock(Request.class); + when(lifecycleRequest.canonicalGameInstanceId()).thenReturn(GAME_INSTANCE); + when(lifecycleRequest.canonicalTenantId()).thenReturn(TENANT); + when(lifecycleRequest.canonicalVersionId()).thenReturn(VERSION); + when(lifecycleRequest.playableStateNamespaceId()).thenReturn(PLAYABLE_NAMESPACE); + var start = mock(RoomTemplateRef.class); + when(start.tenantId()).thenReturn(TENANT); + when(start.versionId()).thenReturn(VERSION); + var lifecycle = mock(WorldCanonicalInstanceLifecycleEvidence.class); + when(lifecycle.lifecycleStatus()).thenReturn("ACTIVE"); + when(lifecycle.lifecycleEpoch()).thenReturn(selection.activeLifecycleEpoch()); + when(lifecycle.request()).thenReturn(lifecycleRequest); + when(lifecycle.startLocation()).thenReturn(start); + var state = mock(WorldCanonicalInitialAdmissionHoldState.class); + when(state.holdIdentity()).thenReturn(invocation.getArgument(0)); + when(state.holdStatus()).thenReturn(HoldStatus.COMMITTED); + when(state.lifecycleEvidence()).thenReturn(lifecycle); + return Optional.of(state); + }); var terminal = mock(GameSessionCanonicalInitialAdmissionOwnerProof.class); when(terminal.holdIdentity()).thenAnswer(invocation -> readIdentity.get()); when(terminal.outcome()) @@ -585,10 +571,9 @@ void nonCommittedGameSessionTerminalStopsBeforePlacementWrite() { assertThatThrownBy(() -> service.place(selection)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - org.assertj.core.api.Assertions.assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + org.assertj.core.api.Assertions.assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); verify(gameSession).read(any()); verify(location, never()).store(any()); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphCodecTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphCodecTest.java index 882993f57e..21ea539728 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphCodecTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphCodecTest.java @@ -73,9 +73,8 @@ void retainedSchemaOneNumericSnapshotsReencodeWithExactlyTheirOriginalBytes() { @ParameterizedTest @MethodSource("invalidReferences") void schemaTwoRejectsPartialMixedUnknownAndNoncanonicalReferences(String reference) { - assertThatThrownBy( - () -> - WorldAuthoredGraph.decode(snapshot(2, "\"entityReference\":" + reference), MAPPER)) + assertThatThrownBy(() -> + WorldAuthoredGraph.decode(snapshot(2, "\"entityReference\":" + reference), MAPPER)) .isInstanceOf(WorldAuthoredGraphSnapshotRepository.SnapshotConflictException.class); } @@ -104,15 +103,13 @@ void snapshotVersionsDoNotAcceptEachOthersSpawnRepresentationOrDigestSchemaVersi assertThatThrownBy( () -> WorldAuthoredGraph.decode(snapshot(2, "\"entityTemplateId\":1"), MAPPER)) .isInstanceOf(WorldAuthoredGraphSnapshotRepository.SnapshotConflictException.class); - assertThatThrownBy( - () -> - WorldAuthoredGraph.decode( - snapshot(1, "\"entityReference\":" + CANONICAL_REFERENCE), MAPPER)) + assertThatThrownBy(() -> + WorldAuthoredGraph.decode( + snapshot(1, "\"entityReference\":" + CANONICAL_REFERENCE), MAPPER)) .isInstanceOf(WorldAuthoredGraphSnapshotRepository.SnapshotConflictException.class); - assertThatThrownBy( - () -> - WorldAuthoredGraph.decode( - snapshot(3, "\"entityReference\":" + CANONICAL_REFERENCE), MAPPER)) + assertThatThrownBy(() -> + WorldAuthoredGraph.decode( + snapshot(3, "\"entityReference\":" + CANONICAL_REFERENCE), MAPPER)) .isInstanceOf(WorldAuthoredGraphSnapshotRepository.SnapshotConflictException.class); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java index aaa7fd0c6a..033c783cbe 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphSnapshotTest.java @@ -77,9 +77,8 @@ void changedOrAmbiguousTupleDeclarationsAreRejected() { assertThatThrownBy( () -> new OwnedAffectedTuple("GAME_DESIGN", "ROOM", "1", "ZONE_SUBTREE", "2", "3")) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - new OwnedAffectedTuple("WORLD_MANAGEMENT", "ROOM", "1", "ZONE_SUBTREE", "2", "03")) + assertThatThrownBy(() -> + new OwnedAffectedTuple("WORLD_MANAGEMENT", "ROOM", "1", "ZONE_SUBTREE", "2", "03")) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> new OwnedAffectedTuple("WORLD_MANAGEMENT", "ROOM", "1", "ZONE_SUBTREE", "", "3")) @@ -88,75 +87,73 @@ void changedOrAmbiguousTupleDeclarationsAreRejected() { @Test void sourceAndReceiptDigestsRetainTheirRequiredPrefix() { - assertThatThrownBy( - () -> - new WorldAuthoredGraphSnapshot( - UUID.randomUUID(), - "firemud", - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - "world-one", - 1L, - 2L, - 3L, - (short) 1, - UUID.randomUUID(), - UUID.randomUUID(), - "sha256:" + DIGEST, - UUID.randomUUID(), - DIGEST, - "sha256:" + DIGEST, - UUID.randomUUID(), - "publish-request-1", - DIGEST, - 1L, - "publish:tenant:publish-request:publish-request-1", - "commit-1", - DIGEST, - 2, - DIGEST, - "[]", - "[]", - "{}".getBytes(java.nio.charset.StandardCharsets.UTF_8), - DIGEST, - WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED)) + assertThatThrownBy(() -> + new WorldAuthoredGraphSnapshot( + UUID.randomUUID(), + "firemud", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "world-one", + 1L, + 2L, + 3L, + (short) 1, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + DIGEST, + UUID.randomUUID(), + DIGEST, + "sha256:" + DIGEST, + UUID.randomUUID(), + "publish-request-1", + DIGEST, + 1L, + "publish:tenant:publish-request:publish-request-1", + "commit-1", + DIGEST, + 2, + DIGEST, + "[]", + "[]", + "{}".getBytes(java.nio.charset.StandardCharsets.UTF_8), + DIGEST, + WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("sourceEvidenceDigest"); - assertThatThrownBy( - () -> - new WorldAuthoredGraphSnapshot( - UUID.randomUUID(), - "firemud", - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - "world-one", - 1L, - 2L, - 3L, - (short) 1, - UUID.randomUUID(), - UUID.randomUUID(), - "sha256:" + DIGEST, - UUID.randomUUID(), - "sha256:" + DIGEST, - DIGEST, - UUID.randomUUID(), - "publish-request-1", - DIGEST, - 1L, - "publish:tenant:publish-request:publish-request-1", - "commit-1", - DIGEST, - 2, - DIGEST, - "[]", - "[]", - "{}".getBytes(java.nio.charset.StandardCharsets.UTF_8), - DIGEST, - WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED)) + assertThatThrownBy(() -> + new WorldAuthoredGraphSnapshot( + UUID.randomUUID(), + "firemud", + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "world-one", + 1L, + 2L, + 3L, + (short) 1, + UUID.randomUUID(), + UUID.randomUUID(), + "sha256:" + DIGEST, + UUID.randomUUID(), + "sha256:" + DIGEST, + DIGEST, + UUID.randomUUID(), + "publish-request-1", + DIGEST, + 1L, + "publish:tenant:publish-request:publish-request-1", + "commit-1", + DIGEST, + 2, + DIGEST, + "[]", + "[]", + "{}".getBytes(java.nio.charset.StandardCharsets.UTF_8), + DIGEST, + WorldAuthoredGraphSnapshot.OwnerCommitProofStatus.CAPTURED_UNVERIFIED)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("intakeReceiptDigest"); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphTest.java index f038538704..c3ca756f6f 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredGraphTest.java @@ -175,10 +175,9 @@ void rejectsMalformedRootFamiliesAndUnknownOrNoncanonicalSnapshots() { emptyGraph.replace(",\"zones\":[]", ",\"regions\":[],\"zones\":[]")); for (String invalidSnapshot : invalidSnapshots) { - assertThatThrownBy( - () -> - WorldAuthoredGraph.decode( - invalidSnapshot.getBytes(StandardCharsets.UTF_8), objectMapper)) + assertThatThrownBy(() -> + WorldAuthoredGraph.decode( + invalidSnapshot.getBytes(StandardCharsets.UTF_8), objectMapper)) .isInstanceOf(SnapshotConflictException.class); } assertThatThrownBy( @@ -208,10 +207,9 @@ void rejectsMalformedRowsDuplicateFieldsAndChangedJsonTypes() { graph.replace("\"shardId\":4,\"name\":\"edge\"", "\"name\":\"edge\",\"shardId\":4")); for (String invalidSnapshot : invalidSnapshots) { - assertThatThrownBy( - () -> - WorldAuthoredGraph.decode( - invalidSnapshot.getBytes(StandardCharsets.UTF_8), objectMapper)) + assertThatThrownBy(() -> + WorldAuthoredGraph.decode( + invalidSnapshot.getBytes(StandardCharsets.UTF_8), objectMapper)) .isInstanceOf(SnapshotConflictException.class); } } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigestTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigestTest.java index 3231c170f7..7899f12f24 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigestTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeDigestTest.java @@ -70,28 +70,23 @@ void rejectsNilMalformedMismatchedAndRetainedInputs() { assertThatThrownBy( () -> WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, new UUID(0L, 0L), fresh)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldAuthoredSourceIntakeDigest.requestDigest( - "other-namespace", INTAKE_REQUEST, fresh)) + assertThatThrownBy(() -> + WorldAuthoredSourceIntakeDigest.requestDigest("other-namespace", INTAKE_REQUEST, fresh)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, retained)) + assertThatThrownBy(() -> + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, retained)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldAuthoredSourceIntakeDigest.receiptDigest( - NAMESPACE, WORLD_OPERATION, "sha256:bad", fresh, 9001L)) + assertThatThrownBy(() -> + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, WORLD_OPERATION, "sha256:bad", fresh, 9001L)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - WorldAuthoredSourceIntakeDigest.receiptDigest( - NAMESPACE, - WORLD_OPERATION, - WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, fresh), - fresh, - 0L)) + assertThatThrownBy(() -> + WorldAuthoredSourceIntakeDigest.receiptDigest( + NAMESPACE, + WORLD_OPERATION, + WorldAuthoredSourceIntakeDigest.requestDigest(NAMESPACE, INTAKE_REQUEST, fresh), + fresh, + 0L)) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcServiceTest.java index 304ebe79ab..ff9e0ecc78 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeGrpcServiceTest.java @@ -207,10 +207,9 @@ void readByIdRejectsWrongPeerEndUserContextAndUnknownFieldsBeforeOwnerAccess() { RecordingObserver wrongNamespace = new RecordingObserver<>(); - withGameDesign( - () -> - grpcService.readAuthoredWorldSourceIntakeById( - request.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); + withGameDesign(() -> + grpcService.readAuthoredWorldSourceIntakeById( + request.toBuilder().setTargetNamespace("other").build(), wrongNamespace)); assertThat(Status.fromThrowable(wrongNamespace.error).getCode()) .isEqualTo(Status.Code.PERMISSION_DENIED); @@ -323,10 +322,9 @@ void rejectsUnknownWireFieldsBeforeCallingOwnerService() { new RecordingObserver<>(); ReadAuthoredWorldSourceIntakeRequest crossNamespaceReadRequest = readRequest().toBuilder().setTargetNamespace("other").build(); - withGameDesign( - () -> - grpcService.readAuthoredWorldSourceIntake( - crossNamespaceReadRequest, wrongReadTargetNamespace)); + withGameDesign(() -> + grpcService.readAuthoredWorldSourceIntake( + crossNamespaceReadRequest, wrongReadTargetNamespace)); assertThat(Status.fromThrowable(wrongReadTargetNamespace.error).getCode()) .isEqualTo(Status.Code.PERMISSION_DENIED); assertThat(wrongReadTargetNamespace.values).isEmpty(); @@ -341,14 +339,12 @@ void intakeAndExactReadRejectCallerContextBeforeDecodeAndOwnerAccess() { SessionContext.setContext("account", List.of(), java.util.Map.of()); try { - withGameDesign( - () -> - grpcService.intakeAuthoredWorldSource( - intakeRequest().toBuilder().setSchemaVersion(2).build(), intakeObserver)); - withGameDesign( - () -> - grpcService.readAuthoredWorldSourceIntake( - readRequest().toBuilder().setRequestId("not-a-uuid").build(), readObserver)); + withGameDesign(() -> + grpcService.intakeAuthoredWorldSource( + intakeRequest().toBuilder().setSchemaVersion(2).build(), intakeObserver)); + withGameDesign(() -> + grpcService.readAuthoredWorldSourceIntake( + readRequest().toBuilder().setRequestId("not-a-uuid").build(), readObserver)); } finally { SessionContext.clear(); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeMtlsTest.java index 0e5cb1d834..e428d870c6 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeMtlsTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeMtlsTest.java @@ -218,10 +218,9 @@ void wrongWorkloadsAndWrongNamespaceAreDeniedBeforeDecodeOrOwnerAccess() throws WorldAuthoredSourceIntakeServiceGrpc.newBlockingStub(malformedCallerChannel) .withDeadlineAfter(3, TimeUnit.SECONDS); Throwable failure = - catchFailure( - () -> - stub.intakeAuthoredWorldSource( - IntakeAuthoredWorldSourceRequest.getDefaultInstance())); + catchFailure(() -> + stub.intakeAuthoredWorldSource( + IntakeAuthoredWorldSourceRequest.getDefaultInstance())); assertThat(failure).isInstanceOf(StatusRuntimeException.class); assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(Status.Code.PERMISSION_DENIED); } finally { @@ -248,13 +247,12 @@ void jwtOnlyAndPlaintextCallersFailAtThePhysicalTransportBoundary() throws Excep jwtOnlyHeaders.put(AUTHORIZATION, "Bearer header.payload.signature"); ManagedChannel noCertificateChannel = rawMtlsChannel(null); try { - assertTransportFailure( - () -> - WorldAuthoredSourceIntakeServiceGrpc.newBlockingStub(noCertificateChannel) - .withInterceptors(MetadataUtils.newAttachHeadersInterceptor(jwtOnlyHeaders)) - .withDeadlineAfter(3, TimeUnit.SECONDS) - .intakeAuthoredWorldSource( - WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(INTAKE_REQUEST))); + assertTransportFailure(() -> + WorldAuthoredSourceIntakeServiceGrpc.newBlockingStub(noCertificateChannel) + .withInterceptors(MetadataUtils.newAttachHeadersInterceptor(jwtOnlyHeaders)) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .intakeAuthoredWorldSource( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(INTAKE_REQUEST))); } finally { stopChannel(noCertificateChannel); } @@ -264,25 +262,23 @@ void jwtOnlyAndPlaintextCallersFailAtThePhysicalTransportBoundary() throws Excep .usePlaintext() .build(); try { - assertTransportFailure( - () -> - WorldAuthoredSourceIntakeServiceGrpc.newBlockingStub(plaintextChannel) - .withDeadlineAfter(3, TimeUnit.SECONDS) - .intakeAuthoredWorldSource( - WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(INTAKE_REQUEST))); + assertTransportFailure(() -> + WorldAuthoredSourceIntakeServiceGrpc.newBlockingStub(plaintextChannel) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .intakeAuthoredWorldSource( + WorldAuthoredSourceIntakeGrpcCodec.toIntakeRequest(INTAKE_REQUEST))); } finally { stopChannel(plaintextChannel); } CommonGrpcClientProperties plaintext = tlsProperties(pki.gameDesignClient(), "constructor"); plaintext.setPlaintext(true); - assertThatThrownBy( - () -> - new WorldAuthoredSourceIntakeClient( - endpoints(), - plaintext, - new net.firedevops.firemud.common.grpc.GrpcChannelFactory(), - NAMESPACE)) + assertThatThrownBy(() -> + new WorldAuthoredSourceIntakeClient( + endpoints(), + plaintext, + new net.firedevops.firemud.common.grpc.GrpcChannelFactory(), + NAMESPACE)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("mTLS"); verifyNoInteractions(intakeService); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java index 5fb37a3bb6..d06bc6b90e 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredSourceIntakeServiceTest.java @@ -71,22 +71,20 @@ void fixtureIntakeRevalidatesPeerAndCallerBeforeAnyOwnerReadOrTransaction() { {"dev", "game-session-service", "d".repeat(64)}, {"dev", "game-session-service", null} }) { - assertThatThrownBy( - () -> - withFixturePeer( - candidate[0], - candidate[1], - candidate[2], - () -> fixtureService.intakeRunOwnedFixture(evidence))) + assertThatThrownBy(() -> + withFixturePeer( + candidate[0], + candidate[1], + candidate[2], + () -> fixtureService.intakeRunOwnedFixture(evidence))) .isInstanceOf(SecurityException.class); } - assertThatThrownBy( - () -> - withFixturePeer( - "dev", - "game-session-service", - "a".repeat(64), - () -> withCallerContext(() -> fixtureService.intakeRunOwnedFixture(evidence)))) + assertThatThrownBy(() -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> withCallerContext(() -> fixtureService.intakeRunOwnedFixture(evidence)))) .isInstanceOf(SecurityException.class); verifyNoInteractions(client, repository); assertThat(transactionManager.startedWith).isNull(); @@ -100,37 +98,33 @@ void fixtureIntakeReadsControlledSourceBeforeSqlAndIndependentlyReadsExactReceip AtomicInteger reads = new AtomicInteger(); AtomicReference committed = new AtomicReference<>(); when(repository.read(eq("dev"), any(UUID.class))) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - if (reads.incrementAndGet() == 1) { - committed.set(receipt(source, 9001L, call.getArgument(1))); - return Optional.empty(); - } - return Optional.of(committed.get()); - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + if (reads.incrementAndGet() == 1) { + committed.set(receipt(source, 9001L, call.getArgument(1))); + return Optional.empty(); + } + return Optional.of(committed.get()); + }); when(client.read(any(ReadRequest.class))) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(transactionManager.startedWith).isNull(); - ReadRequest request = call.getArgument(0); - assertThat(request.targetNamespace()).isEqualTo("dev"); - assertThat(request.operationId()).isEqualTo(source.operationId()); - assertThat(request.canonicalTenantId()).isEqualTo(source.canonicalTenantId()); - assertThat(request.worldSlug()).isEqualTo(source.worldSlug()); - assertThat(request.requestId()).isNotEqualTo(committed.get().intakeRequestId()); - return source; - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(transactionManager.startedWith).isNull(); + ReadRequest request = call.getArgument(0); + assertThat(request.targetNamespace()).isEqualTo("dev"); + assertThat(request.operationId()).isEqualTo(source.operationId()); + assertThat(request.canonicalTenantId()).isEqualTo(source.canonicalTenantId()); + assertThat(request.worldSlug()).isEqualTo(source.worldSlug()); + assertThat(request.requestId()).isNotEqualTo(committed.get().intakeRequestId()); + return source; + }); when(repository.acceptFresh(eq("dev"), any(UUID.class), eq(source))) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) - .isFalse(); - assertThat(call.getArgument(1)).isEqualTo(committed.get().intakeRequestId()); - return committed.get(); - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(call.getArgument(1)).isEqualTo(committed.get().intakeRequestId()); + return committed.get(); + }); WorldAuthoredSourceIntakeService fixtureService = fixtureService(); WorldAuthoredSourceIntakeReceipt result = withFixturePeer( @@ -169,13 +163,12 @@ void fixtureIntakeDeniesChangedRemoteSourceBeforeSql() { when(repository.read(eq("dev"), any(UUID.class))).thenReturn(Optional.empty()); when(client.read(any(ReadRequest.class))) .thenReturn(source("other", TENANT, SOURCE_OPERATION, WORLD)); - assertThatThrownBy( - () -> - withFixturePeer( - "dev", - "game-session-service", - "a".repeat(64), - () -> fixtureService().intakeRunOwnedFixture(evidence))) + assertThatThrownBy(() -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService().intakeRunOwnedFixture(evidence))) .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class); verify(repository, never()).acceptFresh(any(), any(), any()); assertThat(transactionManager.startedWith).isNull(); @@ -189,13 +182,12 @@ void fixtureIntakeDeniesNullOwnerReceiptBeforeIndependentReadback() { when(repository.read(eq("dev"), any(UUID.class))).thenReturn(Optional.empty()); when(client.read(any(ReadRequest.class))).thenReturn(source); - assertThatThrownBy( - () -> - withFixturePeer( - "dev", - "game-session-service", - "a".repeat(64), - () -> fixtureService().intakeRunOwnedFixture(evidence))) + assertThatThrownBy(() -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService().intakeRunOwnedFixture(evidence))) .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class) .hasMessageContaining("owner transaction returned no receipt"); @@ -215,13 +207,12 @@ void fixtureIntakeDeniesMissingIndependentReceiptAfterOwnerTransaction() { when(client.read(any(ReadRequest.class))).thenReturn(source); when(repository.acceptFresh(eq("dev"), any(UUID.class), eq(source))) .thenAnswer(call -> receipt(source, 9001L, call.getArgument(1))); - assertThatThrownBy( - () -> - withFixturePeer( - "dev", - "game-session-service", - "a".repeat(64), - () -> fixtureService().intakeRunOwnedFixture(evidence))) + assertThatThrownBy(() -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService().intakeRunOwnedFixture(evidence))) .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class) .hasMessageContaining("missing after its owner commit"); verify(repository).acceptFresh(eq("dev"), any(UUID.class), eq(source)); @@ -235,21 +226,19 @@ void fixtureIntakeDeniesChangedIndependentReceiptAfterOwnerTransaction() { var source = evidence.sourceReceipt().sourceEvidence(); AtomicInteger reads = new AtomicInteger(); when(repository.read(eq("dev"), any(UUID.class))) - .thenAnswer( - call -> - reads.incrementAndGet() == 1 - ? Optional.empty() - : Optional.of(receipt(source, 9002L, call.getArgument(1)))); + .thenAnswer(call -> + reads.incrementAndGet() == 1 + ? Optional.empty() + : Optional.of(receipt(source, 9002L, call.getArgument(1)))); when(client.read(any(ReadRequest.class))).thenReturn(source); when(repository.acceptFresh(eq("dev"), any(UUID.class), eq(source))) .thenAnswer(call -> receipt(source, 9001L, call.getArgument(1))); - assertThatThrownBy( - () -> - withFixturePeer( - "dev", - "game-session-service", - "a".repeat(64), - () -> fixtureService().intakeRunOwnedFixture(evidence))) + assertThatThrownBy(() -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService().intakeRunOwnedFixture(evidence))) .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class) .hasMessageContaining("changed during independent commit readback"); assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); @@ -260,13 +249,12 @@ void fixtureIntakeDeniesAmbientTransactionBeforeOwnerAccess() { RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); TransactionSynchronizationManager.setActualTransactionActive(true); - assertThatThrownBy( - () -> - withFixturePeer( - "dev", - "game-session-service", - "a".repeat(64), - () -> fixtureService().intakeRunOwnedFixture(evidence))) + assertThatThrownBy(() -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService().intakeRunOwnedFixture(evidence))) .isInstanceOf(IllegalStateException.class); verifyNoInteractions(client, repository); assertThat(transactionManager.startedWith).isNull(); @@ -295,28 +283,19 @@ private static T withFixturePeer( @Test void requiresExactAuthenticatedGameDesignPeerBeforeOwnerAccess() { - assertThatThrownBy( - () -> - withoutPeer( - () -> - service.intake( - INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + assertThatThrownBy(() -> + withoutPeer( + () -> service.intake(INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withPeer( - peer("firemud", "game-session-service"), - () -> - service.intake( - INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + assertThatThrownBy(() -> + withPeer( + peer("firemud", "game-session-service"), + () -> service.intake(INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withPeer( - peer("other", "game-design-service"), - () -> - service.intake( - INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + assertThatThrownBy(() -> + withPeer( + peer("other", "game-design-service"), + () -> service.intake(INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) .isInstanceOf(SecurityException.class); verifyNoInteractions(client, repository); @@ -324,55 +303,38 @@ INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) @Test void validatesAllRequestSelectorsAndDigestBeforeOwnerAccess() { - withGameDesign( - () -> { - assertThatThrownBy( - () -> service.intake(null, TENANT, WORLD, SOURCE_OPERATION, digest('a'))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - service.intake( - new UUID(0L, 0L), TENANT, WORLD, SOURCE_OPERATION, digest('a'))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> service.intake(INTAKE_REQUEST, null, WORLD, SOURCE_OPERATION, digest('a'))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - service.intake( - INTAKE_REQUEST, new UUID(0L, 0L), WORLD, SOURCE_OPERATION, digest('a'))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - service.intake( - INTAKE_REQUEST, TENANT, "Bad-Slug", SOURCE_OPERATION, digest('a'))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - service.intake(INTAKE_REQUEST, TENANT, WORLD, new UUID(0L, 0L), digest('a'))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - service.intake(INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, "sha256:bad")) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - service.intake( - 2, - NAMESPACE, - INTAKE_REQUEST, - TENANT, - WORLD, - SOURCE_OPERATION, - digest('a'))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - service.intake( - 1, "other", INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a'))) - .isInstanceOf(SecurityException.class); - return null; - }); + withGameDesign(() -> { + assertThatThrownBy(() -> service.intake(null, TENANT, WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> service.intake(new UUID(0L, 0L), TENANT, WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> service.intake(INTAKE_REQUEST, null, WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> + service.intake( + INTAKE_REQUEST, new UUID(0L, 0L), WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> + service.intake(INTAKE_REQUEST, TENANT, "Bad-Slug", SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> service.intake(INTAKE_REQUEST, TENANT, WORLD, new UUID(0L, 0L), digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> service.intake(INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, "sha256:bad")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> + service.intake( + 2, NAMESPACE, INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> + service.intake( + 1, "other", INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a'))) + .isInstanceOf(SecurityException.class); + return null; + }); verifyNoInteractions(client, repository); } @@ -382,12 +344,9 @@ void deniesWritableAmbientTransactionBeforeReadingOrWriting() { TransactionSynchronizationManager.setActualTransactionActive(true); TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.intake( - INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + assertThatThrownBy(() -> + withGameDesign( + () -> service.intake(INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) .isInstanceOf(IllegalStateException.class); verifyNoInteractions(client, repository); } @@ -397,12 +356,9 @@ void deniesReadOnlyAmbientTransactionBeforeReadingOrWriting() { TransactionSynchronizationManager.setActualTransactionActive(true); TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.intake( - INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + assertThatThrownBy(() -> + withGameDesign( + () -> service.intake(INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) .isInstanceOf(IllegalStateException.class); verifyNoInteractions(client, repository); } @@ -414,10 +370,9 @@ void exactStoredRetryReturnsOriginalReceiptWithoutCallingGameDesign() { when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.of(receipt)); WorldAuthoredSourceIntakeReceipt result = - withGameDesign( - () -> - service.intake( - INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())); + withGameDesign(() -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())); assertThat(result).isSameAs(receipt); verify(client, never()).read(any(ReadRequest.class)); @@ -432,17 +387,16 @@ void exactCommittedReadReturnsWorldReceiptWithoutSourceReadOrAllocation() { when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.of(receipt)); Optional result = - withGameDesign( - () -> - service.readCommittedReceipt( - 1, - NAMESPACE, - READ_REQUEST, - INTAKE_REQUEST, - TENANT, - WORLD, - SOURCE_OPERATION, - source.evidenceDigest())); + withGameDesign(() -> + service.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest())); assertThat(result).containsSame(receipt); verify(repository).read(NAMESPACE, INTAKE_REQUEST); @@ -458,10 +412,8 @@ void committedReadByIdReturnsFullExactReceiptWithoutSourceReadOrMutation() { when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.of(receipt)); Optional result = - withGameDesign( - () -> - service.readCommittedReceiptById( - 1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT)); + withGameDesign(() -> + service.readCommittedReceiptById(1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT)); assertThat(result).containsSame(receipt); verify(repository).read(NAMESPACE, INTAKE_REQUEST); @@ -472,50 +424,37 @@ void committedReadByIdReturnsFullExactReceiptWithoutSourceReadOrMutation() { @Test void committedReadByIdRejectsWrongPeerCallerContextAndInvalidScopeBeforeOwnerAccess() { - assertThatThrownBy( - () -> - withoutPeer( - () -> - service.readCommittedReceiptById( - 1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT))) + assertThatThrownBy(() -> + withoutPeer(() -> + service.readCommittedReceiptById( + 1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withPeer( - peer(NAMESPACE, "game-session-service"), - () -> - service.readCommittedReceiptById( - 1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT))) + assertThatThrownBy(() -> + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> + service.readCommittedReceiptById( + 1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withGameDesign( - () -> - withCallerContext( - () -> - service.readCommittedReceiptById( - 1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT)))) + assertThatThrownBy(() -> + withGameDesign(() -> + withCallerContext(() -> + service.readCommittedReceiptById( + 1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT)))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.readCommittedReceiptById( - 1, "other", READ_REQUEST, INTAKE_REQUEST, TENANT))) + assertThatThrownBy(() -> + withGameDesign(() -> + service.readCommittedReceiptById(1, "other", READ_REQUEST, INTAKE_REQUEST, TENANT))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.readCommittedReceiptById( - 2, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT))) + assertThatThrownBy(() -> + withGameDesign(() -> + service.readCommittedReceiptById( + 2, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.readCommittedReceiptById( - 1, NAMESPACE, INTAKE_REQUEST, INTAKE_REQUEST, TENANT))) + assertThatThrownBy(() -> + withGameDesign(() -> + service.readCommittedReceiptById( + 1, NAMESPACE, INTAKE_REQUEST, INTAKE_REQUEST, TENANT))) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(client, repository); @@ -526,25 +465,21 @@ void committedReadByIdRejectsWrongPeerCallerContextAndInvalidScopeBeforeOwnerAcc void committedReadByIdReturnsAbsentAndRejectsSubstitutedTenantWithoutMutation() { when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty()); Optional missing = - withGameDesign( - () -> - service.readCommittedReceiptById( - 1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT)); + withGameDesign(() -> + service.readCommittedReceiptById(1, NAMESPACE, READ_REQUEST, INTAKE_REQUEST, TENANT)); assertThat(missing).isEmpty(); AuthoredWorldSourceEvidence source = source(NAMESPACE, TENANT, SOURCE_OPERATION, WORLD); when(repository.read(NAMESPACE, INTAKE_REQUEST)) .thenReturn(Optional.of(receipt(source, 9001L))); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.readCommittedReceiptById( - 1, - NAMESPACE, - READ_REQUEST, - INTAKE_REQUEST, - UUID.fromString("77777777-7777-4777-8777-777777777777")))) + assertThatThrownBy(() -> + withGameDesign(() -> + service.readCommittedReceiptById( + 1, + NAMESPACE, + READ_REQUEST, + INTAKE_REQUEST, + UUID.fromString("77777777-7777-4777-8777-777777777777")))) .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); verify(repository, org.mockito.Mockito.times(2)).read(NAMESPACE, INTAKE_REQUEST); @@ -559,62 +494,55 @@ void exactCommittedReadRejectsWrongPeerNamespaceAndChangedReceiptBindingBeforeOw WorldAuthoredSourceIntakeReceipt receipt = receipt(source, 9001L); when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.of(receipt)); - assertThatThrownBy( - () -> - withoutPeer( - () -> - service.readCommittedReceipt( - 1, - NAMESPACE, - READ_REQUEST, - INTAKE_REQUEST, - TENANT, - WORLD, - SOURCE_OPERATION, - source.evidenceDigest()))) + assertThatThrownBy(() -> + withoutPeer(() -> + service.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withPeer( - peer(NAMESPACE, "game-session-service"), - () -> - service.readCommittedReceipt( - 1, - NAMESPACE, - READ_REQUEST, - INTAKE_REQUEST, - TENANT, - WORLD, - SOURCE_OPERATION, - source.evidenceDigest()))) + assertThatThrownBy(() -> + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> + service.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.readCommittedReceipt( - 1, - "other", - READ_REQUEST, - INTAKE_REQUEST, - TENANT, - WORLD, - SOURCE_OPERATION, - source.evidenceDigest()))) + assertThatThrownBy(() -> + withGameDesign(() -> + service.readCommittedReceipt( + 1, + "other", + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.readCommittedReceipt( - 1, - NAMESPACE, - INTAKE_REQUEST, - INTAKE_REQUEST, - TENANT, - WORLD, - SOURCE_OPERATION, - source.evidenceDigest()))) + assertThatThrownBy(() -> + withGameDesign(() -> + service.readCommittedReceipt( + 1, + NAMESPACE, + INTAKE_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) .isInstanceOf(IllegalArgumentException.class); verifyNoInteractions(client, repository); @@ -626,17 +554,16 @@ void exactCommittedReadReturnsAbsentWithoutMutationWhenNoReceiptExists() { when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty()); Optional result = - withGameDesign( - () -> - service.readCommittedReceipt( - 1, - NAMESPACE, - READ_REQUEST, - INTAKE_REQUEST, - TENANT, - WORLD, - SOURCE_OPERATION, - digest('a'))); + withGameDesign(() -> + service.readCommittedReceipt( + 1, + NAMESPACE, + READ_REQUEST, + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + digest('a'))); assertThat(result).isEmpty(); verify(repository).read(NAMESPACE, INTAKE_REQUEST); @@ -651,45 +578,36 @@ void changedRequestScopeOrExpectedDigestConflictsBeforeRemoteReadOrMutation() { when(repository.read(NAMESPACE, INTAKE_REQUEST)) .thenReturn(Optional.of(receipt(source, 9001L))); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.intake( - INTAKE_REQUEST, - UUID.fromString("66666666-6666-4666-8666-666666666666"), - WORLD, - SOURCE_OPERATION, - source.evidenceDigest()))) + assertThatThrownBy(() -> + withGameDesign(() -> + service.intake( + INTAKE_REQUEST, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + WORLD, + SOURCE_OPERATION, + source.evidenceDigest()))) .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.intake( - INTAKE_REQUEST, - TENANT, - "amber-coast", - SOURCE_OPERATION, - source.evidenceDigest()))) + assertThatThrownBy(() -> + withGameDesign(() -> + service.intake( + INTAKE_REQUEST, + TENANT, + "amber-coast", + SOURCE_OPERATION, + source.evidenceDigest()))) .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.intake( - INTAKE_REQUEST, - TENANT, - WORLD, - UUID.fromString("77777777-7777-4777-8777-777777777777"), - source.evidenceDigest()))) + assertThatThrownBy(() -> + withGameDesign(() -> + service.intake( + INTAKE_REQUEST, + TENANT, + WORLD, + UUID.fromString("77777777-7777-4777-8777-777777777777"), + source.evidenceDigest()))) .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.intake( - INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('b')))) + assertThatThrownBy(() -> + withGameDesign( + () -> service.intake(INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('b')))) .isInstanceOf(WorldAuthoredSourceIntakeRepository.RegistrationConflictException.class); verify(client, never()).read(any(ReadRequest.class)); @@ -702,12 +620,9 @@ void sourceUnavailableCannotEnterTheOwnerWriteTransaction() { when(client.read(any(ReadRequest.class))) .thenThrow(new IllegalStateException("source unavailable")); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.intake( - INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) + assertThatThrownBy(() -> + withGameDesign( + () -> service.intake(INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('a')))) .isInstanceOf(IllegalStateException.class) .hasMessage("source unavailable"); @@ -732,16 +647,14 @@ void changedAuthenticatedSourceCannotEnterTheOwnerWriteTransaction() { for (AuthoredWorldSourceEvidence substituted : substitutedSources) { when(client.read(any(ReadRequest.class))).thenReturn(substituted); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.intake( - INTAKE_REQUEST, - TENANT, - WORLD, - SOURCE_OPERATION, - substituted.evidenceDigest()))) + assertThatThrownBy(() -> + withGameDesign(() -> + service.intake( + INTAKE_REQUEST, + TENANT, + WORLD, + SOURCE_OPERATION, + substituted.evidenceDigest()))) .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class); } @@ -755,12 +668,9 @@ void callerDigestMustMatchFreshAuthenticatedEvidenceBeforeOpeningTransaction() { when(repository.read(NAMESPACE, INTAKE_REQUEST)).thenReturn(Optional.empty()); when(client.read(any(ReadRequest.class))).thenReturn(source); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.intake( - INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('b')))) + assertThatThrownBy(() -> + withGameDesign( + () -> service.intake(INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, digest('b')))) .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class); verify(repository, never()).acceptFresh(any(), any(), any()); @@ -773,31 +683,26 @@ void readsFreshSourceBeforeWritableReadCommittedTransactionAndVerifiesFullCommit WorldAuthoredSourceIntakeReceipt receipt = receipt(source, 9001L); AtomicInteger readCount = new AtomicInteger(); when(repository.read(NAMESPACE, INTAKE_REQUEST)) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return readCount.incrementAndGet() == 1 ? Optional.empty() : Optional.of(receipt); - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return readCount.incrementAndGet() == 1 ? Optional.empty() : Optional.of(receipt); + }); when(client.read(any(ReadRequest.class))) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return source; - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return source; + }); when(repository.acceptFresh(NAMESPACE, INTAKE_REQUEST, source)) - .thenAnswer( - ignored -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) - .isFalse(); - return receipt; - }); + .thenAnswer(ignored -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + return receipt; + }); WorldAuthoredSourceIntakeReceipt result = - withGameDesign( - () -> - service.intake( - INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())); + withGameDesign(() -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())); assertThat(result).isEqualTo(receipt); assertThat(readCount.get()).isEqualTo(2); @@ -826,16 +731,10 @@ void deniesMissingPostCommitReadback() { when(repository.acceptFresh(NAMESPACE, INTAKE_REQUEST, source)) .thenReturn(receipt(source, 9001L)); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.intake( - INTAKE_REQUEST, - TENANT, - WORLD, - SOURCE_OPERATION, - source.evidenceDigest()))) + assertThatThrownBy(() -> + withGameDesign(() -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest()))) .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class) .hasMessageContaining("missing after commit readback"); @@ -853,16 +752,10 @@ void deniesChangedPostCommitLocalSelectorReadback() { when(client.read(any(ReadRequest.class))).thenReturn(source); when(repository.acceptFresh(NAMESPACE, INTAKE_REQUEST, source)).thenReturn(accepted); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.intake( - INTAKE_REQUEST, - TENANT, - WORLD, - SOURCE_OPERATION, - source.evidenceDigest()))) + assertThatThrownBy(() -> + withGameDesign(() -> + service.intake( + INTAKE_REQUEST, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest()))) .isInstanceOf(WorldAuthoredSourceIntakeRepository.InvalidIntakeEvidenceException.class) .hasMessageContaining("changed during commit readback"); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityCanonicalTargetReadTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityCanonicalTargetReadTest.java index 6c7e5a0d73..02bf71d40c 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityCanonicalTargetReadTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityCanonicalTargetReadTest.java @@ -34,13 +34,12 @@ void canonicalTargetReadRejectsAmbientTransactionBeforeSql() { TransactionSynchronizationManager.setActualTransactionActive(true); var repository = new WorldAuthoredVersionIdentityRepository(dsl); - assertThatThrownBy( - () -> - repository.readByCanonicalTarget( - "firemud", - UUID.fromString("22222222-2222-4222-8222-222222222222"), - UUID.fromString("33333333-3333-4333-8333-333333333333"), - 42L)) + assertThatThrownBy(() -> + repository.readByCanonicalTarget( + "firemud", + UUID.fromString("22222222-2222-4222-8222-222222222222"), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + 42L)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("independent committed owner read"); @@ -60,13 +59,12 @@ void canonicalTargetReadRejectsMultipleWorldAssociationsAsAmbiguous() { when(rows.size()).thenReturn(2); var repository = new WorldAuthoredVersionIdentityRepository(dsl); - assertThatThrownBy( - () -> - repository.readByCanonicalTarget( - "firemud", - UUID.fromString("22222222-2222-4222-8222-222222222222"), - UUID.fromString("33333333-3333-4333-8333-333333333333"), - 42L)) + assertThatThrownBy(() -> + repository.readByCanonicalTarget( + "firemud", + UUID.fromString("22222222-2222-4222-8222-222222222222"), + UUID.fromString("33333333-3333-4333-8333-333333333333"), + 42L)) .isInstanceOf(WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class) .hasMessageContaining("ambiguous World associations"); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java index 2253dd2001..57908f3402 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldAuthoredVersionIdentityServiceTest.java @@ -85,9 +85,8 @@ void fixtureVersionRevalidatesPeerAndCallerBeforeAnyOwnerOrRemoteRead() { RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); var sourceReceipt = sourceReceipt(evidence.sourceReceipt().sourceEvidence()); WorldAuthoredVersionIdentityService fixtureService = fixtureService(); - assertThatThrownBy( - () -> - withoutPeer(() -> fixtureService.associateRunOwnedFixture(evidence, sourceReceipt))) + assertThatThrownBy(() -> + withoutPeer(() -> fixtureService.associateRunOwnedFixture(evidence, sourceReceipt))) .isInstanceOf(SecurityException.class); for (String[] candidate : new String[][] { @@ -96,29 +95,27 @@ void fixtureVersionRevalidatesPeerAndCallerBeforeAnyOwnerOrRemoteRead() { {"dev", "game-session-service", "d".repeat(64)}, {"dev", "game-session-service", null} }) { - assertThatThrownBy( - () -> - withFixturePeer( - candidate[0], - candidate[1], - candidate[2], - () -> fixtureService.associateRunOwnedFixture(evidence, sourceReceipt))) + assertThatThrownBy(() -> + withFixturePeer( + candidate[0], + candidate[1], + candidate[2], + () -> fixtureService.associateRunOwnedFixture(evidence, sourceReceipt))) .isInstanceOf(SecurityException.class); } - assertThatThrownBy( - () -> - withFixturePeer( - "dev", - "game-session-service", - "a".repeat(64), - () -> { - SessionContext.setContext(TENANT.toString(), List.of(), java.util.Map.of()); - try { - return fixtureService.associateRunOwnedFixture(evidence, sourceReceipt); - } finally { - SessionContext.clear(); - } - })) + assertThatThrownBy(() -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> { + SessionContext.setContext(TENANT.toString(), List.of(), java.util.Map.of()); + try { + return fixtureService.associateRunOwnedFixture(evidence, sourceReceipt); + } finally { + SessionContext.clear(); + } + })) .isInstanceOf(SecurityException.class); verifyNoInteractions(sourceIntakeRepository, repository, versionStateClient); assertThat(transactionManager.startedWith).isNull(); @@ -140,56 +137,47 @@ void fixtureVersionConsumesCommittedSourceThenControlledCurrentStateBeforeSqlAnd source.worldSlug(), source.operationId(), source.evidenceDigest())) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return Optional.of(intake); - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return Optional.of(intake); + }); when(repository.readByCanonicalVersion( "dev", source.canonicalTenantId(), source.worldSlug(), canonicalVersion)) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - return ownerReads.incrementAndGet() == 1 - ? Optional.empty() - : Optional.of(committed.get()); - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + return ownerReads.incrementAndGet() == 1 + ? Optional.empty() + : Optional.of(committed.get()); + }); when(repository.readByGameDesignVersion( "dev", source.canonicalTenantId(), source.worldSlug(), gameDesignVersion)) .thenReturn(Optional.empty()); when(versionStateClient.read(any())) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); - assertThat(transactionManager.startedWith).isNull(); - AuthoredWorldVersionStateEvidence.Request request = call.getArgument(0); - assertThat(request.targetNamespace()).isEqualTo("dev"); - assertThat(request.canonicalTenantId()).isEqualTo(source.canonicalTenantId()); - assertThat(request.versionId()).isEqualTo(gameDesignVersion); - assertThat(request.readRequestId()) - .isNotEqualTo(intake.intakeRequestId()) - .isNotEqualTo(source.operationId()); - return AuthoredWorldVersionStateEvidence.create( - request, - source, - canonicalVersion, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, - evidence - .sourceReceipt() - .launchReadEvidence() - .versionState() - .getVersionStateEpoch()); - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(transactionManager.startedWith).isNull(); + AuthoredWorldVersionStateEvidence.Request request = call.getArgument(0); + assertThat(request.targetNamespace()).isEqualTo("dev"); + assertThat(request.canonicalTenantId()).isEqualTo(source.canonicalTenantId()); + assertThat(request.versionId()).isEqualTo(gameDesignVersion); + assertThat(request.readRequestId()) + .isNotEqualTo(intake.intakeRequestId()) + .isNotEqualTo(source.operationId()); + return AuthoredWorldVersionStateEvidence.create( + request, + source, + canonicalVersion, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + evidence.sourceReceipt().launchReadEvidence().versionState().getVersionStateEpoch()); + }); when(repository.acceptFresh(any(), any())) - .thenAnswer( - call -> { - assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); - assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) - .isFalse(); - assertThat(call.getArgument(0)).isEqualTo(intake); - committed.set(identityReceipt(intake, call.getArgument(1), 101L)); - return committed.get(); - }); + .thenAnswer(call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse(); + assertThat(call.getArgument(0)).isEqualTo(intake); + committed.set(identityReceipt(intake, call.getArgument(1), 101L)); + return committed.get(); + }); WorldAuthoredVersionIdentityService fixtureService = fixtureService(); var result = withFixturePeer( @@ -279,13 +267,12 @@ void fixtureVersionRejectsDifferentCommittedSourceBeforeVersionAccessOrSql() { source.operationId(), source.evidenceDigest())) .thenReturn(Optional.of(different)); - assertThatThrownBy( - () -> - withFixturePeer( - "dev", - "game-session-service", - "a".repeat(64), - () -> fixtureService().associateRunOwnedFixture(evidence, intake))) + assertThatThrownBy(() -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService().associateRunOwnedFixture(evidence, intake))) .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class); verifyNoInteractions(repository, versionStateClient); assertThat(transactionManager.startedWith).isNull(); @@ -339,13 +326,12 @@ void fixtureVersionRejectsRemoteStateEpochCanonicalVersionAndRequestSubstitution }) .when(versionStateClient) .read(any()); - assertThatThrownBy( - () -> - withFixturePeer( - "dev", - "game-session-service", - "a".repeat(64), - () -> fixtureService().associateRunOwnedFixture(evidence, intake))) + assertThatThrownBy(() -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService().associateRunOwnedFixture(evidence, intake))) .isInstanceOf( WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class); } @@ -378,36 +364,34 @@ void fixtureVersionRejectsChangedRetainedSnapshotOnExactRetryWithoutRemoteOrSql( "dev", source.canonicalTenantId(), source.worldSlug(), gameDesignVersion)) .thenReturn(Optional.empty()); when(versionStateClient.read(any())) - .thenAnswer( - call -> { - AuthoredWorldVersionStateEvidence.Request request = call.getArgument(0); - assertThat(request.targetNamespace()).isEqualTo("dev"); - assertThat(request.canonicalTenantId()).isEqualTo(source.canonicalTenantId()); - assertThat(request.worldSlug()).isEqualTo(source.worldSlug()); - assertThat(request.sourceOperationId()).isEqualTo(source.operationId()); - assertThat(request.expectedSourceEvidenceDigest()).isEqualTo(source.evidenceDigest()); - assertThat(request.versionId()).isEqualTo(gameDesignVersion); - var current = - AuthoredWorldVersionStateEvidence.create( - request, - source, - canonicalVersion, - VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, - evidence - .sourceReceipt() - .launchReadEvidence() - .versionState() - .getVersionStateEpoch()); - originalState.set(current); - return current; - }); + .thenAnswer(call -> { + AuthoredWorldVersionStateEvidence.Request request = call.getArgument(0); + assertThat(request.targetNamespace()).isEqualTo("dev"); + assertThat(request.canonicalTenantId()).isEqualTo(source.canonicalTenantId()); + assertThat(request.worldSlug()).isEqualTo(source.worldSlug()); + assertThat(request.sourceOperationId()).isEqualTo(source.operationId()); + assertThat(request.expectedSourceEvidenceDigest()).isEqualTo(source.evidenceDigest()); + assertThat(request.versionId()).isEqualTo(gameDesignVersion); + var current = + AuthoredWorldVersionStateEvidence.create( + request, + source, + canonicalVersion, + VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, + evidence + .sourceReceipt() + .launchReadEvidence() + .versionState() + .getVersionStateEpoch()); + originalState.set(current); + return current; + }); when(repository.acceptFresh(any(), any())) - .thenAnswer( - call -> { - var accepted = identityReceipt(intake, call.getArgument(1), 101L); - retained.set(accepted); - return accepted; - }); + .thenAnswer(call -> { + var accepted = identityReceipt(intake, call.getArgument(1), 101L); + retained.set(accepted); + return accepted; + }); WorldAuthoredVersionIdentityService fixtureService = fixtureService(); var accepted = @@ -452,13 +436,12 @@ void fixtureVersionRejectsChangedRetainedSnapshotOnExactRetryWithoutRemoteOrSql( ? 1L : 0L)); retained.set(identityReceipt(intake, changed, 101L)); - assertThatThrownBy( - () -> - withFixturePeer( - "dev", - "game-session-service", - "a".repeat(64), - () -> fixtureService().associateRunOwnedFixture(evidence, intake))) + assertThatThrownBy(() -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService().associateRunOwnedFixture(evidence, intake))) .isInstanceOf( WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class); } @@ -488,19 +471,18 @@ void fixtureVersionDeniesMissingOrSubstitutedIndependentVersionReceipt() { AtomicReference current = new AtomicReference<>(); when(repository.readByCanonicalVersion( "dev", source.canonicalTenantId(), source.worldSlug(), canonicalVersion)) - .thenAnswer( - call -> { - if (ownerReads.incrementAndGet() == 1 || selected == 0) return Optional.empty(); - var original = current.get(); - var changed = - AuthoredWorldVersionStateEvidence.create( - original.request(), - source, - canonicalVersion, - original.versionState(), - original.versionStateEpoch() + 1L); - return Optional.of(identityReceipt(intake, changed, 101L)); - }); + .thenAnswer(call -> { + if (ownerReads.incrementAndGet() == 1 || selected == 0) return Optional.empty(); + var original = current.get(); + var changed = + AuthoredWorldVersionStateEvidence.create( + original.request(), + source, + canonicalVersion, + original.versionState(), + original.versionStateEpoch() + 1L); + return Optional.of(identityReceipt(intake, changed, 101L)); + }); when(repository.readByGameDesignVersion( "dev", source.canonicalTenantId(), source.worldSlug(), gameDesignVersion)) .thenReturn(Optional.empty()); @@ -525,13 +507,12 @@ void fixtureVersionDeniesMissingOrSubstitutedIndependentVersionReceipt() { doAnswer(call -> identityReceipt(intake, call.getArgument(1), 101L)) .when(repository) .acceptFresh(any(), any()); - assertThatThrownBy( - () -> - withFixturePeer( - "dev", - "game-session-service", - "a".repeat(64), - () -> fixtureService().associateRunOwnedFixture(evidence, intake))) + assertThatThrownBy(() -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> fixtureService().associateRunOwnedFixture(evidence, intake))) .isInstanceOf( WorldAuthoredVersionIdentityRepository.InvalidIdentityEvidenceException.class); assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); @@ -544,17 +525,15 @@ void fixtureVersionDeniesAmbientTransactionBeforeOwnerAccess() { RunOwnedCanonicalWorldLaunchEvidence evidence = RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.create(); TransactionSynchronizationManager.setActualTransactionActive(true); - assertThatThrownBy( - () -> - withFixturePeer( - "dev", - "game-session-service", - "a".repeat(64), - () -> - fixtureService() - .associateRunOwnedFixture( - evidence, - sourceReceipt(evidence.sourceReceipt().sourceEvidence())))) + assertThatThrownBy(() -> + withFixturePeer( + "dev", + "game-session-service", + "a".repeat(64), + () -> + fixtureService() + .associateRunOwnedFixture( + evidence, sourceReceipt(evidence.sourceReceipt().sourceEvidence())))) .isInstanceOf(IllegalStateException.class); verifyNoInteractions(repository, sourceIntakeRepository, versionStateClient); assertThat(transactionManager.startedWith).isNull(); @@ -586,31 +565,27 @@ private static T withFixturePeer( void requiresExactSameNamespaceGameDesignPeerBeforeAnyOwnerOrRemoteAccess() { assertThatThrownBy(() -> withoutPeer(() -> associate(VERSION, GAME_DESIGN_VERSION_ID))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withPeer( - peer("other", "game-design-service"), - () -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + assertThatThrownBy(() -> + withPeer( + peer("other", "game-design-service"), + () -> associate(VERSION, GAME_DESIGN_VERSION_ID))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withPeer( - peer(NAMESPACE, "game-session-service"), - () -> associate(VERSION, GAME_DESIGN_VERSION_ID))) + assertThatThrownBy(() -> + withPeer( + peer(NAMESPACE, "game-session-service"), + () -> associate(VERSION, GAME_DESIGN_VERSION_ID))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withGameDesign( - () -> - service.associate( - "other", - TENANT, - WORLD, - SOURCE_OPERATION, - source().evidenceDigest(), - VERSION, - GAME_DESIGN_VERSION_ID, - READ_REQUEST))) + assertThatThrownBy(() -> + withGameDesign(() -> + service.associate( + "other", + TENANT, + WORLD, + SOURCE_OPERATION, + source().evidenceDigest(), + VERSION, + GAME_DESIGN_VERSION_ID, + READ_REQUEST))) .isInstanceOf(SecurityException.class); verifyNoInteractions(sourceIntakeRepository, repository, versionStateClient); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReaderTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReaderTest.java index 98ccea06cd..12e411bc20 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReaderTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalAuthoredGraphReaderTest.java @@ -119,16 +119,13 @@ void graphThreeRejectsMissingChangedUnsupportedExtraAndUnselectedClosure() throw ((tools.jackson.databind.node.ObjectNode) wrongSchema).put("schemaVersion", "2"); for (var malformed : List.of(missing, changed, unsupported, extra, wrongSchema)) { assertThat(malformed).isNotEqualTo(original); - assertThatThrownBy( - () -> - new WorldCanonicalAuthoredGraphReader() - .read(selected, json.writeValueAsBytes(malformed))) + assertThatThrownBy(() -> + new WorldCanonicalAuthoredGraphReader() + .read(selected, json.writeValueAsBytes(malformed))) .isExactlyInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); } - assertThatThrownBy( - () -> - new WorldCanonicalAuthoredGraphReader() - .read(plan(), json.writeValueAsBytes(original))) + assertThatThrownBy(() -> + new WorldCanonicalAuthoredGraphReader().read(plan(), json.writeValueAsBytes(original))) .isExactlyInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); assertThat( new WorldCanonicalAuthoredGraphReader() @@ -250,15 +247,15 @@ static WorldDraftTopologyCommitPlan plan() throws Exception { // Synthetic bytes are deliberate decoder fixtures; real V30 storage is covered by PostgreSQL. private String graphJson() { return """ - {"schemaVersion":"2","canonicalTenantId":"%s","canonicalVersionId":"%s","rows":[ - {"mapping":{"id":1,"target_namespace":"firemud","canonical_tenant_id":"%s", - "canonical_version_id":"%s","family":"REGION","template_id":"%s","private_row_key":11, - "tenant_id":9007199254740993,"version_id":31,"version_identity_operation_id":"%s", - "request_id":"%s","commit_id":"%s","revision_id":"%s","revision_order":"0"}, - "content":{"id":11,"tenant_id":9007199254740993,"version_id":31,"version":0,"name":"region", - "shard_id":0,"weather":"rain","generation_seed":0,"generator_type":"","generator_params":"", - "spacing_multiplier":1.0}}]} - """ + {"schemaVersion":"2","canonicalTenantId":"%s","canonicalVersionId":"%s","rows":[ + {"mapping":{"id":1,"target_namespace":"firemud","canonical_tenant_id":"%s", + "canonical_version_id":"%s","family":"REGION","template_id":"%s","private_row_key":11, + "tenant_id":9007199254740993,"version_id":31,"version_identity_operation_id":"%s", + "request_id":"%s","commit_id":"%s","revision_id":"%s","revision_order":"0"}, + "content":{"id":11,"tenant_id":9007199254740993,"version_id":31,"version":0,"name":"region", + "shard_id":0,"weather":"rain","generation_seed":0,"generator_type":"","generator_params":"", + "spacing_multiplier":1.0}}]} + """ .replace("\n", "") .formatted( TENANT, diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyDeadlineReadTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyDeadlineReadTest.java index 4e9283e079..a9ce2e678e 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyDeadlineReadTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyDeadlineReadTest.java @@ -69,10 +69,8 @@ class WorldCanonicalFrozenTopologyDeadlineReadTest { @Test void expiredCancelledAndAmbientCallsNeverAcquire() throws Exception { var fixture = new Fixture(0, 1); - assertThatThrownBy( - () -> - fixture.repository.readCommitted( - fixture.request, Deadline.after(-1, TimeUnit.SECONDS))) + assertThatThrownBy(() -> + fixture.repository.readCommitted(fixture.request, Deadline.after(-1, TimeUnit.SECONDS))) .isInstanceOfSatisfying( StatusRuntimeException.class, error -> @@ -84,10 +82,9 @@ void expiredCancelledAndAmbientCallsNeverAcquire() throws Exception { } TransactionSynchronizationManager.initSynchronization(); try { - assertThatThrownBy( - () -> - fixture.repository.readCommitted( - fixture.request, Deadline.after(5, TimeUnit.SECONDS))) + assertThatThrownBy(() -> + fixture.repository.readCommitted( + fixture.request, Deadline.after(5, TimeUnit.SECONDS))) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class); } finally { TransactionSynchronizationManager.clearSynchronization(); @@ -194,10 +191,9 @@ void abandonedAcquisitionsRemainCappedWithoutAQueue() throws Exception { } await(fixture.acquireEntered); for (var read : reads) assertStatus(read, Status.Code.DEADLINE_EXCEEDED); - assertThatThrownBy( - () -> - fixture.repository.readCommitted( - fixture.request, Deadline.after(5, TimeUnit.SECONDS))) + assertThatThrownBy(() -> + fixture.repository.readCommitted( + fixture.request, Deadline.after(5, TimeUnit.SECONDS))) .isInstanceOfSatisfying( StatusRuntimeException.class, error -> @@ -308,10 +304,9 @@ void failedConnectionReturnRetainsItsSlotWithoutRetry() throws Exception { boolean resourceStopped = false; try { try { - assertThatThrownBy( - () -> - fixture.repository.readCommitted( - fixture.request, Deadline.after(5, TimeUnit.SECONDS))) + assertThatThrownBy(() -> + fixture.repository.readCommitted( + fixture.request, Deadline.after(5, TimeUnit.SECONDS))) .isInstanceOf(DataAccessException.class) .hasMessage("Controlled connection return failed"); } finally { @@ -319,20 +314,18 @@ void failedConnectionReturnRetainsItsSlotWithoutRetry() throws Exception { resourceStopped = true; } assertThat(appender.list) - .anySatisfy( - event -> { - assertThat(event.getLevel()).isEqualTo(Level.WARN); - assertThat(event.getFormattedMessage()) - .contains("retaining deadline-read slot", "Remaining capacity: 0 of 4"); - assertThat(event.getThrowableProxy().getMessage()) - .isEqualTo("Controlled connection return failed"); - }); + .anySatisfy(event -> { + assertThat(event.getLevel()).isEqualTo(Level.WARN); + assertThat(event.getFormattedMessage()) + .contains("retaining deadline-read slot", "Remaining capacity: 0 of 4"); + assertThat(event.getThrowableProxy().getMessage()) + .isEqualTo("Controlled connection return failed"); + }); assertThat(fixture.releaseAttempts.get()).isEqualTo(1); assertThat(capacity.availablePermits()).isZero(); - assertThatThrownBy( - () -> - fixture.repository.readCommitted( - fixture.request, Deadline.after(5, TimeUnit.SECONDS))) + assertThatThrownBy(() -> + fixture.repository.readCommitted( + fixture.request, Deadline.after(5, TimeUnit.SECONDS))) .isInstanceOfSatisfying( StatusRuntimeException.class, error -> @@ -448,15 +441,14 @@ private Fixture(int blockedQuery, int expectedAcquisitions) throws Exception { "e".repeat(64), 3, binding.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) + .map(unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) .toList()); includeBinding = blockedQuery == 2; backing = @@ -605,14 +597,13 @@ private CompletableFuture> async( var value = new CompletableFuture>(); Thread.ofVirtual() .start( - context.wrap( - () -> { - try { - value.complete(repository.readCommitted(request, deadline)); - } catch (RuntimeException | Error failure) { - value.completeExceptionally(failure); - } - })); + context.wrap(() -> { + try { + value.complete(repository.readCommitted(request, deadline)); + } catch (RuntimeException | Error failure) { + value.completeExceptionally(failure); + } + })); return value; } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyTest.java index 2c308c3abf..a26a7f5558 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalFrozenTopologyTest.java @@ -37,15 +37,14 @@ private CaptureRequest freeze( var owner = plan.ownerBinding(); var affected = plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) + .map(unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) .toList(); return new CaptureRequest( owner.targetNamespace(), diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldOwnerTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldOwnerTest.java index d86c782842..55b9ffab51 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldOwnerTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldOwnerTest.java @@ -119,10 +119,9 @@ void unavailableOrMismatchedOwnerReadCannotReachWorldSettlement() { assertThatThrownBy(() -> owner.settleFromAuthenticatedOwnerRead(identity)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.DEADLINE_EXCEEDED)); verifyNoInteractions(repository); HoldIdentity otherIdentity = identity(request("e")); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepositoryTest.java index eb7292ee63..0d1d689932 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepositoryTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationRepositoryTest.java @@ -64,15 +64,14 @@ void activationRejectsAmbientTransactionBeforeOpeningItsOwnerCas() { var repository = new WorldCanonicalInstanceActivationRepository(dsl, manager, lifecycle); TransactionSynchronizationManager.setActualTransactionActive(true); - assertThatThrownBy( - () -> - repository.activate( - request(), - new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { - public void requireHeld() {} - - public void close() {} - })) + assertThatThrownBy(() -> + repository.activate( + request(), + new WorldCanonicalInstanceActivationService.HeldActivationAuthority() { + public void requireHeld() {} + + public void close() {} + })) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("must not join an ambient transaction"); @@ -114,13 +113,12 @@ void multipleProtectedFenceRowsBecomeAnActivationConflictInsteadOfJooqCardinalit String query = "SELECT * FROM world_canonical_instance_activation_fence " + "WHERE activation_request_id=? OR canonical_game_instance_id=?"; - assertThatThrownBy( - () -> - context(provider(fixture, 2, 0, new AtomicInteger(), new AtomicInteger())) - .fetchOne( - query, - input.worldActivationRequest().activationRequestId(), - input.worldActivationRequest().canonicalGameInstanceId())) + assertThatThrownBy(() -> + context(provider(fixture, 2, 0, new AtomicInteger(), new AtomicInteger())) + .fetchOne( + query, + input.worldActivationRequest().activationRequestId(), + input.worldActivationRequest().canonicalGameInstanceId())) .isInstanceOf(TooManyRowsException.class); AtomicInteger protectedQueries = new AtomicInteger(); @@ -143,13 +141,12 @@ void multipleLegacyRowsRemainAnActivationConflictInsteadOfJooqCardinalityFailure "SELECT 1 FROM world_canonical_instance_activation_operation " + "WHERE activation_request_id=? " + "OR (canonical_game_instance_id=? AND outcome='COMMITTED')"; - assertThatThrownBy( - () -> - context(provider(fixture, 0, 2, new AtomicInteger(), new AtomicInteger())) - .fetchOne( - query, - input.worldActivationRequest().activationRequestId(), - input.worldActivationRequest().canonicalGameInstanceId())) + assertThatThrownBy(() -> + context(provider(fixture, 0, 2, new AtomicInteger(), new AtomicInteger())) + .fetchOne( + query, + input.worldActivationRequest().activationRequestId(), + input.worldActivationRequest().canonicalGameInstanceId())) .isInstanceOf(TooManyRowsException.class); AtomicInteger protectedQueries = new AtomicInteger(); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java index 86d4755582..0cfb05f5f1 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java @@ -113,16 +113,15 @@ void protectedOperationHoldsItsDistinctAuthorityAroundTheOwnerCas() { var installation = mock(WorldRuntimeInstallationRegistry.class); var installationHeld = new AtomicBoolean(); when(installation.withLaunchOwners(eq(gameInstanceId), any())) - .thenAnswer( - call -> { - Supplier owner = call.getArgument(1); - installationHeld.set(true); - try { - return owner.get(); - } finally { - installationHeld.set(false); - } - }); + .thenAnswer(call -> { + Supplier owner = call.getArgument(1); + installationHeld.set(true); + try { + return owner.get(); + } finally { + installationHeld.set(false); + } + }); var heldChecks = new AtomicInteger(); var closed = new java.util.concurrent.atomic.AtomicBoolean(); var held = @@ -139,12 +138,11 @@ public void close() { }; when(repository.readTerminalEvidence(protection)).thenReturn(Optional.empty()); when(repository.activateProtected(eq(protection), any())) - .thenAnswer( - call -> { - assertThat(installationHeld).isTrue(); - assertThat(closed).isFalse(); - return terminal; - }); + .thenAnswer(call -> { + assertThat(installationHeld).isTrue(); + assertThat(closed).isFalse(); + return terminal; + }); var service = new WorldCanonicalInstanceActivationService(repository, installation); assertThat(service.activateProtected(protection, held)).isSameAs(terminal); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionIdentityTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionIdentityTest.java index 2e5abe26a8..ed607d1a36 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionIdentityTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceExecutionIdentityTest.java @@ -32,19 +32,18 @@ void observationWithNullMutationIdIsRejectedAsIncomplete() { var observationBytes = OriginalStartSessionCurrentAttemptEvidenceGrpcCodec.toResponse(observation).toByteArray(); - assertThatThrownBy( - () -> - new WorldCanonicalInstanceExecutionIdentity( - tupleBytes, - PARTICIPATION_ID, - ACCOUNT_FENCE, - null, - ATTEMPT_ID, - OWNER_FENCE, - observation, - GAME_INSTANCE_ID, - "{}", - observationBytes)) + assertThatThrownBy(() -> + new WorldCanonicalInstanceExecutionIdentity( + tupleBytes, + PARTICIPATION_ID, + ACCOUNT_FENCE, + null, + ATTEMPT_ID, + OWNER_FENCE, + observation, + GAME_INSTANCE_ID, + "{}", + observationBytes)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Account original-attempt observation is incomplete"); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java index 6f920c1eb3..bd1485ce66 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepositoryTest.java @@ -93,14 +93,13 @@ void preservesSpringResourceFailuresAcrossBothRepositoryReadBoundaries() throws Record.class, boolean.class); readMaterialized.setAccessible(true); - assertThatThrownBy( - () -> - readMaterialized.invoke( - repository, - request, - mock(WorldCanonicalInstanceAssociation.class), - preparation, - false)) + assertThatThrownBy(() -> + readMaterialized.invoke( + repository, + request, + mock(WorldCanonicalInstanceAssociation.class), + preparation, + false)) .isInstanceOf(InvocationTargetException.class) .satisfies(failure -> assertThat(failure.getCause()).isSameAs(materializedFailure)); } @@ -134,14 +133,13 @@ void preservesNontransientSpringAndJooqStorageFailuresAtMaterializedReadBoundary var preparation = mock(Record.class); when(preparation.get("capture_id", UUID.class)).thenThrow(storageFailure); - assertThatThrownBy( - () -> - readMaterialized.invoke( - repository, - request, - mock(WorldCanonicalInstanceAssociation.class), - preparation, - false)) + assertThatThrownBy(() -> + readMaterialized.invoke( + repository, + request, + mock(WorldCanonicalInstanceAssociation.class), + preparation, + false)) .isInstanceOf(InvocationTargetException.class) .satisfies(failure -> assertThat(failure.getCause()).isSameAs(storageFailure)); } @@ -195,25 +193,22 @@ void rejectsUnsupportedOrMixedCurrentSelectorAttestationProfiles() throws Except var closureSelector = release(AuthoredWorldReleaseAttestationEvidence.CLOSURE_SELECTOR_SCHEMA_VERSION); - assertThatThrownBy( - () -> - closureSelector( - closureSelector, - participantDigestsWithSchema(closureSelector, "ENTITY_MANAGEMENT", 1))) + assertThatThrownBy(() -> + closureSelector( + closureSelector, + participantDigestsWithSchema(closureSelector, "ENTITY_MANAGEMENT", 1))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Participant digest schema is unsupported"); - assertThatThrownBy( - () -> - closureSelector( - closureSelector, - participantDigestsWithSchema(closureSelector, "AUTOMATION_SCRIPTING", 4))) + assertThatThrownBy(() -> + closureSelector( + closureSelector, + participantDigestsWithSchema(closureSelector, "AUTOMATION_SCRIPTING", 4))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Participant digest schema is unsupported"); - assertThatThrownBy( - () -> - closureSelector( - closureSelector, - participantDigestsWithSchema(closureSelector, "WORLD_MANAGEMENT", 3))) + assertThatThrownBy(() -> + closureSelector( + closureSelector, + participantDigestsWithSchema(closureSelector, "WORLD_MANAGEMENT", 3))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Participant digest schema is unsupported"); } @@ -281,25 +276,24 @@ private static AuthoredWorldReleaseAttestationEvidence release(int schemaVersion : selector.request().canonicalVersionId(); var participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> { - boolean gameLogic = "GAME_LOGIC".equals(owner); - String contentDigest = - "WORLD_MANAGEMENT".equals(owner) && selector != null - ? selector.request().contentDigest() - : "a".repeat(64); - return new AuthoredWorldReleaseAttestationEvidence.Participant( - owner, - "7", - false, - null, - commitId, - contentDigest, - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner, schemaVersion), - gameLogic, - gameLogic ? "sha256:" + "c".repeat(64) : null); - }) + .map(owner -> { + boolean gameLogic = "GAME_LOGIC".equals(owner); + String contentDigest = + "WORLD_MANAGEMENT".equals(owner) && selector != null + ? selector.request().contentDigest() + : "a".repeat(64); + return new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + "7", + false, + null, + commitId, + contentDigest, + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, schemaVersion), + gameLogic, + gameLogic ? "sha256:" + "c".repeat(64) : null); + }) .toList(); String descriptorDigest = "sha256:" + "b".repeat(64); @@ -432,20 +426,19 @@ private static WorldPublishedStartLocationEvidence selectedWorldEvidence(int sch participantDigestsWithSchema( AuthoredWorldReleaseAttestationEvidence release, String owner, int schemaVersion) { return release.participantDigests().stream() - .map( - participant -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - participant.participantKey(), - participant.scopeValue(), - participant.baseVersionIdPresent(), - participant.baseVersionId(), - participant.appliedCommitId(), - participant.contentDigest(), - owner.equals(participant.participantKey()) - ? schemaVersion - : participant.digestSchemaVersion(), - participant.abilitySchemaDigestPresent(), - participant.abilitySchemaDigest())) + .map(participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant.participantKey(), + participant.scopeValue(), + participant.baseVersionIdPresent(), + participant.baseVersionId(), + participant.appliedCommitId(), + participant.contentDigest(), + owner.equals(participant.participantKey()) + ? schemaVersion + : participant.digestSchemaVersion(), + participant.abilitySchemaDigestPresent(), + participant.abilitySchemaDigest())) .toList(); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest.java index 9479cb89bd..377acac882 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceOriginalOperationRecoveryVerifierTest.java @@ -98,25 +98,23 @@ void rejectsNonSharedRetainedScopeAgainstSharedGameSessionAssociation() throws E var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); when(account.read(any(AccountStartSessionWorldParticipationHistoricalReadRequest.class))) - .thenAnswer( - invocation -> - accountEvidence( - invocation.getArgument(0), - ORIGINAL_TUPLE, - ATTEMPT_ID, - GAME_SESSION_FENCE, - changedInput)); + .thenAnswer(invocation -> + accountEvidence( + invocation.getArgument(0), + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + changedInput)); var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); when(gameSession.read(any(HistoricalOriginalStartSessionOwnerEvidence.Request.class))) - .thenAnswer( - invocation -> - gameSessionEvidence( - invocation.getArgument(0), - fixture, - ORIGINAL_TUPLE, - ATTEMPT_ID, - GAME_SESSION_FENCE, - fixture.launchAssociation())); + .thenAnswer(invocation -> + gameSessionEvidence( + invocation.getArgument(0), + fixture, + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + fixture.launchAssociation())); assertThatThrownBy( () -> verifier(account, gameSession).verifyOriginalOperation(fixture.identity())) @@ -177,24 +175,22 @@ private void acceptsExactHistoricalOwnerEvidenceAndUsesFreshReadCorrelations(Fix var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); when(account.read(any(AccountStartSessionWorldParticipationHistoricalReadRequest.class))) - .thenAnswer( - invocation -> - accountEvidence( - invocation.getArgument(0), - ORIGINAL_TUPLE, - ATTEMPT_ID, - GAME_SESSION_FENCE, - fixture.preparationInputJson())); + .thenAnswer(invocation -> + accountEvidence( + invocation.getArgument(0), + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + fixture.preparationInputJson())); when(gameSession.read(any(HistoricalOriginalStartSessionOwnerEvidence.Request.class))) - .thenAnswer( - invocation -> - gameSessionEvidence( - invocation.getArgument(0), - fixture, - ORIGINAL_TUPLE, - ATTEMPT_ID, - GAME_SESSION_FENCE, - fixture.launchAssociation())); + .thenAnswer(invocation -> + gameSessionEvidence( + invocation.getArgument(0), + fixture, + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + fixture.launchAssociation())); verifier(account, gameSession).verifyOriginalOperation(fixture.identity()); @@ -254,14 +250,13 @@ void rejectsAccountTupleAttemptOrFenceSubstitutionBeforeGameSessionRead() { UUID attempt = substitution == 1 ? uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa") : ATTEMPT_ID; long fence = substitution == 2 ? GAME_SESSION_FENCE + 1L : GAME_SESSION_FENCE; when(account.read(any(AccountStartSessionWorldParticipationHistoricalReadRequest.class))) - .thenAnswer( - invocation -> - accountEvidence( - invocation.getArgument(0), - tuple, - attempt, - fence, - fixture.preparationInputJson())); + .thenAnswer(invocation -> + accountEvidence( + invocation.getArgument(0), + tuple, + attempt, + fence, + fixture.preparationInputJson())); assertDenied(verifier(account, gameSession), fixture.identity()); verifyNoInteractions(gameSession); @@ -275,23 +270,22 @@ void rejectsAccountResolvedParticipationIdOrFenceBeforeGameSessionRead() { var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); when(account.read(any(AccountStartSessionWorldParticipationHistoricalReadRequest.class))) - .thenAnswer( - invocation -> { - var evidence = - accountEvidence( - invocation.getArgument(0), - ORIGINAL_TUPLE, - ATTEMPT_ID, - GAME_SESSION_FENCE, - fixture.preparationInputJson()); - if (substituteId) { - when(evidence.accountWorldParticipationId()) - .thenReturn(uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")); - } else { - when(evidence.accountWorldParticipationFence()).thenReturn(ACCOUNT_FENCE + 1L); - } - return evidence; - }); + .thenAnswer(invocation -> { + var evidence = + accountEvidence( + invocation.getArgument(0), + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + fixture.preparationInputJson()); + if (substituteId) { + when(evidence.accountWorldParticipationId()) + .thenReturn(uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa")); + } else { + when(evidence.accountWorldParticipationFence()).thenReturn(ACCOUNT_FENCE + 1L); + } + return evidence; + }); assertDenied(verifier(account, gameSession), fixture.identity()); verifyNoInteractions(gameSession); @@ -308,15 +302,14 @@ void rejectsGameSessionTupleAttemptOrFenceSubstitution() { UUID attempt = substitution == 1 ? uuid("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa") : ATTEMPT_ID; long fence = substitution == 2 ? GAME_SESSION_FENCE + 1L : GAME_SESSION_FENCE; when(gameSession.read(any(HistoricalOriginalStartSessionOwnerEvidence.Request.class))) - .thenAnswer( - invocation -> - gameSessionEvidence( - invocation.getArgument(0), - fixture, - tuple, - attempt, - fence, - fixture.launchAssociation())); + .thenAnswer(invocation -> + gameSessionEvidence( + invocation.getArgument(0), + fixture, + tuple, + attempt, + fence, + fixture.launchAssociation())); assertDenied(verifier(account, gameSession), fixture.identity()); } @@ -329,14 +322,13 @@ void rejectsAccountCaptureFenceOrLinearizationSubstitutionBeforeGameSessionRead( var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); when(account.read(any(AccountStartSessionWorldParticipationHistoricalReadRequest.class))) - .thenAnswer( - invocation -> - accountEvidence( - invocation.getArgument(0), - substituted, - ATTEMPT_ID, - GAME_SESSION_FENCE, - fixture.preparationInputJson())); + .thenAnswer(invocation -> + accountEvidence( + invocation.getArgument(0), + substituted, + ATTEMPT_ID, + GAME_SESSION_FENCE, + fixture.preparationInputJson())); assertDenied(verifier(account, gameSession), fixture.identity()); verifyNoInteractions(gameSession); @@ -350,15 +342,14 @@ void rejectsGameSessionCaptureFenceOrLinearizationSubstitution() { var account = exactAccountClient(fixture); var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); when(gameSession.read(any(HistoricalOriginalStartSessionOwnerEvidence.Request.class))) - .thenAnswer( - invocation -> - gameSessionEvidence( - invocation.getArgument(0), - fixture, - substituted, - ATTEMPT_ID, - GAME_SESSION_FENCE, - fixture.launchAssociation())); + .thenAnswer(invocation -> + gameSessionEvidence( + invocation.getArgument(0), + fixture, + substituted, + ATTEMPT_ID, + GAME_SESSION_FENCE, + fixture.launchAssociation())); assertDenied(verifier(account, gameSession), fixture.identity()); } @@ -403,30 +394,28 @@ void rejectsDescriptorOrSourceAssociationSubstitution() { var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); LaunchAssociation substitutedDescriptor = fixture(true).launchAssociation(); when(gameSession.read(any(HistoricalOriginalStartSessionOwnerEvidence.Request.class))) - .thenAnswer( - invocation -> - gameSessionEvidence( - invocation.getArgument(0), - exact, - ORIGINAL_TUPLE, - ATTEMPT_ID, - GAME_SESSION_FENCE, - substitutedDescriptor)); + .thenAnswer(invocation -> + gameSessionEvidence( + invocation.getArgument(0), + exact, + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + substitutedDescriptor)); assertDenied(verifier(account, gameSession), exact.identity()); Fixture substitutedSource = fixtureWithSubstitutedSource(); var sourceAccount = exactAccountClient(substitutedSource); var sourceGameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); when(sourceGameSession.read(any(HistoricalOriginalStartSessionOwnerEvidence.Request.class))) - .thenAnswer( - invocation -> - gameSessionEvidence( - invocation.getArgument(0), - substitutedSource, - ORIGINAL_TUPLE, - ATTEMPT_ID, - GAME_SESSION_FENCE, - exact.launchAssociation())); + .thenAnswer(invocation -> + gameSessionEvidence( + invocation.getArgument(0), + substitutedSource, + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + exact.launchAssociation())); assertDenied(verifier(sourceAccount, sourceGameSession), substitutedSource.identity()); } @@ -436,14 +425,13 @@ void rejectsPreparationInputSubstitutionAndMissingOwnerEvidence() { var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); when(account.read(any(AccountStartSessionWorldParticipationHistoricalReadRequest.class))) - .thenAnswer( - invocation -> - accountEvidence( - invocation.getArgument(0), - ORIGINAL_TUPLE, - ATTEMPT_ID, - GAME_SESSION_FENCE, - fixture.preparationInputJson() + " ")); + .thenAnswer(invocation -> + accountEvidence( + invocation.getArgument(0), + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + fixture.preparationInputJson() + " ")); assertDenied(verifier(account, gameSession), fixture.identity()); verifyNoInteractions(gameSession); @@ -485,25 +473,23 @@ void rejectsSchemaTwoSelectorSubstitutionAgainstTheRetainedRelease() { var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); when(account.read(any(AccountStartSessionWorldParticipationHistoricalReadRequest.class))) - .thenAnswer( - invocation -> - accountEvidence( - invocation.getArgument(0), - ORIGINAL_TUPLE, - ATTEMPT_ID, - GAME_SESSION_FENCE, - substitutedInput)); + .thenAnswer(invocation -> + accountEvidence( + invocation.getArgument(0), + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + substitutedInput)); var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); when(gameSession.read(any(HistoricalOriginalStartSessionOwnerEvidence.Request.class))) - .thenAnswer( - invocation -> - gameSessionEvidence( - invocation.getArgument(0), - fixture, - ORIGINAL_TUPLE, - ATTEMPT_ID, - GAME_SESSION_FENCE, - fixture.launchAssociation())); + .thenAnswer(invocation -> + gameSessionEvidence( + invocation.getArgument(0), + fixture, + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + fixture.launchAssociation())); assertDenied(verifier(account, gameSession), fixture.identity()); } @@ -530,25 +516,23 @@ void rejectsSchemaFourSelectorSubstitutionAgainstTheRetainedRelease() { var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); when(account.read(any(AccountStartSessionWorldParticipationHistoricalReadRequest.class))) - .thenAnswer( - invocation -> - accountEvidence( - invocation.getArgument(0), - ORIGINAL_TUPLE, - ATTEMPT_ID, - GAME_SESSION_FENCE, - substitutedInput)); + .thenAnswer(invocation -> + accountEvidence( + invocation.getArgument(0), + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + substitutedInput)); var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); when(gameSession.read(any(HistoricalOriginalStartSessionOwnerEvidence.Request.class))) - .thenAnswer( - invocation -> - gameSessionEvidence( - invocation.getArgument(0), - fixture, - ORIGINAL_TUPLE, - ATTEMPT_ID, - GAME_SESSION_FENCE, - fixture.launchAssociation())); + .thenAnswer(invocation -> + gameSessionEvidence( + invocation.getArgument(0), + fixture, + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + fixture.launchAssociation())); assertDenied(verifier(account, gameSession), fixture.identity()); } @@ -586,15 +570,14 @@ void schemaOneAndThreeCannotPairTheirLegacyProjectionWithASelectedReleaseSelecto var account = exactAccountClient(fixture); var gameSession = mock(HistoricalOriginalStartSessionOwnerEvidenceReadClient.class); when(gameSession.read(any(HistoricalOriginalStartSessionOwnerEvidence.Request.class))) - .thenAnswer( - invocation -> - gameSessionEvidence( - invocation.getArgument(0), - fixture, - ORIGINAL_TUPLE, - ATTEMPT_ID, - GAME_SESSION_FENCE, - fixture.launchAssociation())); + .thenAnswer(invocation -> + gameSessionEvidence( + invocation.getArgument(0), + fixture, + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + fixture.launchAssociation())); assertThatThrownBy( () -> verifier(account, gameSession).verifyOriginalOperation(fixture.identity())) @@ -1119,14 +1102,13 @@ private static AccountStartSessionWorldParticipationHistoricalReadClient exactAc Fixture fixture) { var account = mock(AccountStartSessionWorldParticipationHistoricalReadClient.class); when(account.read(any(AccountStartSessionWorldParticipationHistoricalReadRequest.class))) - .thenAnswer( - invocation -> - accountEvidence( - invocation.getArgument(0), - ORIGINAL_TUPLE, - ATTEMPT_ID, - GAME_SESSION_FENCE, - fixture.preparationInputJson())); + .thenAnswer(invocation -> + accountEvidence( + invocation.getArgument(0), + ORIGINAL_TUPLE, + ATTEMPT_ID, + GAME_SESSION_FENCE, + fixture.preparationInputJson())); return account; } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyServiceTest.java index db66d48804..da561f6447 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationAssemblyServiceTest.java @@ -97,16 +97,15 @@ void selectorIsMinimalAndReadsUseOnlyTheConfiguredNamespace() { verify(launchBindings).read(NAMESPACE, TENANT_ID, CONTROL_REQUEST_ID); verifyNoInteractions( sourceIntakes, versionIdentities, frozenTopologies, gameSession, gameDesign); - assertThatThrownBy( - () -> - new WorldCanonicalInstancePreparationAssemblyService( - "not a namespace", - launchBindings, - sourceIntakes, - versionIdentities, - frozenTopologies, - gameSession, - gameDesign)) + assertThatThrownBy(() -> + new WorldCanonicalInstancePreparationAssemblyService( + "not a namespace", + launchBindings, + sourceIntakes, + versionIdentities, + frozenTopologies, + gameSession, + gameDesign)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("canonical DNS label"); } @@ -246,10 +245,9 @@ void acceptsOnlyTheExactGameSessionSelectorAndCompleteStoredPair() { var changedInstanceRequest = gameSessionRequest(stored, UUID.randomUUID()); var changedInstanceResult = gameSessionResult(changedInstanceRequest, stored); - assertThatThrownBy( - () -> - WorldCanonicalInstancePreparationAssemblyService.requireGameSessionBinding( - request, changedInstanceResult, stored)) + assertThatThrownBy(() -> + WorldCanonicalInstancePreparationAssemblyService.requireGameSessionBinding( + request, changedInstanceResult, stored)) .isInstanceOf( WorldCanonicalInstancePreparationAssemblyService.AssemblyRejectedException.class) .hasMessageContaining("Game Session association differs"); @@ -257,10 +255,9 @@ void acceptsOnlyTheExactGameSessionSelectorAndCompleteStoredPair() { var changedPair = binding('b'); var changedPairRequest = gameSessionRequest(changedPair, INSTANCE_ID); var changedPairResult = gameSessionResult(changedPairRequest, changedPair); - assertThatThrownBy( - () -> - WorldCanonicalInstancePreparationAssemblyService.requireGameSessionBinding( - request, changedPairResult, stored)) + assertThatThrownBy(() -> + WorldCanonicalInstancePreparationAssemblyService.requireGameSessionBinding( + request, changedPairResult, stored)) .isInstanceOf( WorldCanonicalInstancePreparationAssemblyService.AssemblyRejectedException.class) .hasMessageContaining("Game Session association differs"); @@ -276,20 +273,18 @@ void rejectsNonSharedOrNonProductionGameSessionReadProjection() { when(invalid.publicProduction()).thenReturn(true); when(invalid.launchBindingEvidence()).thenReturn(stored); - assertThatThrownBy( - () -> - WorldCanonicalInstancePreparationAssemblyService.requireGameSessionBinding( - request, invalid, stored)) + assertThatThrownBy(() -> + WorldCanonicalInstancePreparationAssemblyService.requireGameSessionBinding( + request, invalid, stored)) .isInstanceOf( WorldCanonicalInstancePreparationAssemblyService.AssemblyRejectedException.class) .hasMessageContaining("Game Session association differs"); when(invalid.playableStateScope()).thenReturn(RealmEntryPolicy.StateScope.SHARED); when(invalid.publicProduction()).thenReturn(false); - assertThatThrownBy( - () -> - WorldCanonicalInstancePreparationAssemblyService.requireGameSessionBinding( - request, invalid, stored)) + assertThatThrownBy(() -> + WorldCanonicalInstancePreparationAssemblyService.requireGameSessionBinding( + request, invalid, stored)) .isInstanceOf( WorldCanonicalInstancePreparationAssemblyService.AssemblyRejectedException.class) .hasMessageContaining("Game Session association differs"); @@ -300,10 +295,9 @@ void independentlyAuthenticatedGameDesignPairMustMatchEveryStoredEvidenceField() var stored = binding('a'); WorldCanonicalInstancePreparationAssemblyService.requireSameCompletePair(stored, binding('a')); - assertThatThrownBy( - () -> - WorldCanonicalInstancePreparationAssemblyService.requireSameCompletePair( - stored, binding('b'))) + assertThatThrownBy(() -> + WorldCanonicalInstancePreparationAssemblyService.requireSameCompletePair( + stored, binding('b'))) .isInstanceOf( WorldCanonicalInstancePreparationAssemblyService.AssemblyRejectedException.class) .hasMessageContaining("Authenticated Game Design complete launch pair differs"); @@ -383,19 +377,17 @@ private static CompleteLaunchBindingEvidence binding(char digestCharacter) { String commitId = BINDING_COMMIT_ID; var participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - owner, - Long.toString(descriptor.versionId()), - false, - null, - commitId, - String.valueOf(digestCharacter).repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), - "GAME_LOGIC".equals(owner), - "GAME_LOGIC".equals(owner) ? "sha256:" + "1".repeat(64) : null)) + .map(owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(descriptor.versionId()), + false, + null, + commitId, + String.valueOf(digestCharacter).repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema(owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "1".repeat(64) : null)) .toList(); var release = AuthoredWorldReleaseAttestationEvidence.create( diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java index 65a562297e..a46458918c 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java @@ -42,10 +42,9 @@ void defaultConstructorsDenyRecoveryWithoutTouchingRepository() { var commitVerifier = mock(WorldCanonicalInstancePreparationService.CommitAuthorityVerifier.class); - assertThatThrownBy( - () -> - new WorldCanonicalInstancePreparationService(repository, commitVerifier) - .recoverExact(identity)) + assertThatThrownBy(() -> + new WorldCanonicalInstancePreparationService(repository, commitVerifier) + .recoverExact(identity)) .isInstanceOf(WorldCanonicalInstancePreparationService.PreparationDeniedException.class) .hasMessageContaining("no authenticated original-operation verifier"); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationTest.java index 583e656c52..192614d3f4 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationTest.java @@ -69,10 +69,8 @@ void exactReleaseGraphJoinRejectsChangedCommitDigestSchemaVersionAndWorkflow() t freeze.appliedCommitId(), freeze.contentDigest(), "another-workflow"))) { - assertThatThrownBy( - () -> - WorldCanonicalInstancePreparation.requireExactReleaseGraph( - changed, fixture.plan())) + assertThatThrownBy(() -> + WorldCanonicalInstancePreparation.requireExactReleaseGraph(changed, fixture.plan())) .isInstanceOf(IllegalArgumentException.class); } var changedSchema = @@ -91,10 +89,9 @@ void exactReleaseGraphJoinRejectsChangedCommitDigestSchemaVersionAndWorkflow() t 2, freeze.suppliedOwnedAffectedTuples()); when(fixture.plan().sourceBinding()).thenReturn(new Request(source.plan(), changedSchema)); - assertThatThrownBy( - () -> - WorldCanonicalInstancePreparation.requireExactReleaseGraph( - fixture.release(), fixture.plan())) + assertThatThrownBy(() -> + WorldCanonicalInstancePreparation.requireExactReleaseGraph( + fixture.release(), fixture.plan())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("World participant differs"); } @@ -154,19 +151,17 @@ private static AuthoredWorldReleaseAttestationEvidence releaseFor( Request source, UUID version, String commit, String worldDigest, String workflow) { var participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - owner -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - owner, - Long.toString(source.plan().ownerBinding().gameDesignVersionId()), - false, - null, - commit, - "WORLD_MANAGEMENT".equals(owner) ? worldDigest : "a".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - owner), - "GAME_LOGIC".equals(owner), - "GAME_LOGIC".equals(owner) ? "sha256:" + "b".repeat(64) : null)) + .map(owner -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + owner, + Long.toString(source.plan().ownerBinding().gameDesignVersionId()), + false, + null, + commit, + "WORLD_MANAGEMENT".equals(owner) ? worldDigest : "a".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema(owner), + "GAME_LOGIC".equals(owner), + "GAME_LOGIC".equals(owner) ? "sha256:" + "b".repeat(64) : null)) .toList(); return AuthoredWorldReleaseAttestationEvidence.create( source.freeze().targetNamespace(), @@ -592,15 +587,14 @@ private static CaptureRequest freezeRequest(OwnerBinding owner, DraftCommitBindi "5".repeat(64), 3, binding.affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) + .map(unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) .toList()); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceStartLocationReadbackTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceStartLocationReadbackTest.java index 150992da11..93333500ce 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceStartLocationReadbackTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceStartLocationReadbackTest.java @@ -40,12 +40,11 @@ void exactOriginalSelectorReadbackBindsItsReceiptIdentityAndComparesAllRetainedB AtomicReference query = new AtomicReference<>(); AtomicReference bindings = new AtomicReference<>(); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - query.set(invocation.getArgument(0)); - bindings.set((Object[]) invocation.getRawArguments()[1]); - return row(originalRow(fixture)); - }); + .thenAnswer(invocation -> { + query.set(invocation.getArgument(0)); + bindings.set((Object[]) invocation.getRawArguments()[1]); + return row(originalRow(fixture)); + }); WorldCanonicalInstanceStartLocationReadback.requireExactOriginalSelector( dsl, fixture.selector(), fixture.receipt(), fixture.graphBytes()); @@ -78,10 +77,9 @@ void exactOriginalSelectorReadbackBindsItsReceiptIdentityAndComparesAllRetainedB var changedDsl = mock(DSLContext.class); when(changedDsl.fetchOne(anyString(), any(Object[].class))).thenReturn(row(changedRow)); - assertThatThrownBy( - () -> - WorldCanonicalInstanceStartLocationReadback.requireExactOriginalSelector( - changedDsl, fixture.selector(), fixture.receipt(), fixture.graphBytes())) + assertThatThrownBy(() -> + WorldCanonicalInstanceStartLocationReadback.requireExactOriginalSelector( + changedDsl, fixture.selector(), fixture.receipt(), fixture.graphBytes())) .as("changed original %s", changed.getKey()) .isInstanceOf( WorldCanonicalInstanceStartLocationReadback.InvalidStartLocationReadbackException @@ -99,12 +97,11 @@ void mappedRoomReadbackAcceptsTheExactScopedRoomAndRejectsIndependentFieldChange AtomicReference query = new AtomicReference<>(); AtomicReference bindings = new AtomicReference<>(); when(dsl.fetchOne(anyString(), any(Object[].class))) - .thenAnswer( - invocation -> { - query.set(invocation.getArgument(0)); - bindings.set((Object[]) invocation.getRawArguments()[1]); - return row(selected); - }); + .thenAnswer(invocation -> { + query.set(invocation.getArgument(0)); + bindings.set((Object[]) invocation.getRawArguments()[1]); + return row(selected); + }); assertThat( WorldCanonicalInstanceStartLocationReadback.requireMappedRoom( @@ -154,13 +151,12 @@ void mappedRoomReadbackAcceptsTheExactScopedRoomAndRejectsIndependentFieldChange var changedDsl = mock(DSLContext.class); when(changedDsl.fetchOne(anyString(), any(Object[].class))).thenReturn(row(changedRow)); - assertThatThrownBy( - () -> - WorldCanonicalInstanceStartLocationReadback.requireMappedRoom( - changedDsl, - association, - fixture.receipt().startLocation(), - fixture.selector().canonicalBytes())) + assertThatThrownBy(() -> + WorldCanonicalInstanceStartLocationReadback.requireMappedRoom( + changedDsl, + association, + fixture.receipt().startLocation(), + fixture.selector().canonicalBytes())) .as("changed mapped ROOM field %s", changed.getKey()) .isInstanceOf( WorldCanonicalInstanceStartLocationReadback.InvalidStartLocationReadbackException @@ -175,19 +171,17 @@ void bothReadbackQueriesPassThroughRawStorageFailure() throws Exception { var dsl = mock(DSLContext.class); when(dsl.fetchOne(anyString(), any(Object[].class))).thenThrow(storageFailure); - assertThatThrownBy( - () -> - WorldCanonicalInstanceStartLocationReadback.requireMappedRoom( - dsl, - association(fixture), - fixture.receipt().startLocation(), - fixture.selector().canonicalBytes())) + assertThatThrownBy(() -> + WorldCanonicalInstanceStartLocationReadback.requireMappedRoom( + dsl, + association(fixture), + fixture.receipt().startLocation(), + fixture.selector().canonicalBytes())) .isSameAs(storageFailure); - assertThatThrownBy( - () -> - WorldCanonicalInstanceStartLocationReadback.requireExactOriginalSelector( - dsl, fixture.selector(), fixture.receipt(), fixture.graphBytes())) + assertThatThrownBy(() -> + WorldCanonicalInstanceStartLocationReadback.requireExactOriginalSelector( + dsl, fixture.selector(), fixture.receipt(), fixture.graphBytes())) .isSameAs(storageFailure); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceTopologyPlanTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceTopologyPlanTest.java index 8b1e9ab387..f2c0e11570 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceTopologyPlanTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceTopologyPlanTest.java @@ -160,12 +160,10 @@ void keepsSourceBindingPayloadBytesAndOrderingAcrossDeterministicRetries() throw for (Entry entry : first.entries()) { String exactPayload = fixture.plan().binding().revisions().stream() - .filter( - revision -> - revision - .revisionId() - .equals( - uuidFrom(entry.source().authoredRevision().getLogicalRevisionId()))) + .filter(revision -> + revision + .revisionId() + .equals(uuidFrom(entry.source().authoredRevision().getLogicalRevisionId()))) .findFirst() .orElseThrow() .payload(); @@ -195,10 +193,8 @@ void rejectsMissingDuplicateAndTypeConfusedFrozenRows() throws Exception { List missingRegion = new ArrayList<>(fixture.rows()); missingRegion.removeIf(row -> row.template().equals(new Template(Family.REGION, REGION_B))); - assertThatThrownBy( - () -> - WorldCanonicalInstanceTopologyPlan.create( - withRows(fixture, missingRegion).source())) + assertThatThrownBy(() -> + WorldCanonicalInstanceTopologyPlan.create(withRows(fixture, missingRegion).source())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("omits or adds"); @@ -220,9 +216,8 @@ void rejectsMissingDuplicateAndTypeConfusedFrozenRows() throws Exception { zone.privateRowKey(), zone.authored(), zone.content())); - assertThatThrownBy( - () -> - WorldCanonicalInstanceTopologyPlan.create(withRows(fixture, typeConfused).source())) + assertThatThrownBy(() -> + WorldCanonicalInstanceTopologyPlan.create(withRows(fixture, typeConfused).source())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("confuses authored family"); @@ -241,10 +236,9 @@ void rejectsMissingDuplicateAndTypeConfusedFrozenRows() throws Exception { exit.privateRowKey(), exit.authored(), badExitContent)); - assertThatThrownBy( - () -> - WorldCanonicalInstanceTopologyPlan.create( - withRows(fixture, missingRoomReference).source())) + assertThatThrownBy(() -> + WorldCanonicalInstanceTopologyPlan.create( + withRows(fixture, missingRoomReference).source())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Frozen content differs"); } @@ -363,15 +357,14 @@ private static CaptureRequest freeze(WorldDraftTopologyCommitPlan plan) { var owner = plan.ownerBinding(); List affected = plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) + .map(unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) .toList(); String publicationRequestId = "publication-request"; return new CaptureRequest( diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalStartSessionTerminalReadTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalStartSessionTerminalReadTest.java index 43481856ab..05d3120cd8 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalStartSessionTerminalReadTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalStartSessionTerminalReadTest.java @@ -189,10 +189,8 @@ void defaultDenialVerifierDenialAndAmbientTransactionPrecedeStorage() { WorldCanonicalInstanceExecutionIdentity identity = mock(WorldCanonicalInstanceExecutionIdentity.class); - assertThatThrownBy( - () -> - new WorldCanonicalInstancePreparationService(repository) - .recoverExactTerminal(identity)) + assertThatThrownBy(() -> + new WorldCanonicalInstancePreparationService(repository).recoverExactTerminal(identity)) .isInstanceOf(PreparationDeniedException.class) .hasMessageContaining("no authenticated original-operation verifier"); verifyNoInteractions(repository); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java index 31b4fa6f61..3eb4a8a3e2 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCompleteLaunchBindingServiceTest.java @@ -150,17 +150,15 @@ void committedLaunchRequiresSameNamespaceGameSessionWithoutEndUserContextBeforeA assertThatThrownBy( () -> withoutPeer(() -> committedService.bindCommittedLaunch(fixture.request()))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withPeer( - peer(NAMESPACE, "game-design-service"), - () -> committedService.bindCommittedLaunch(fixture.request()))) + assertThatThrownBy(() -> + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> committedService.bindCommittedLaunch(fixture.request()))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withPeer( - peer("other", "game-session-service"), - () -> committedService.bindCommittedLaunch(fixture.request()))) + assertThatThrownBy(() -> + withPeer( + peer("other", "game-session-service"), + () -> committedService.bindCommittedLaunch(fixture.request()))) .isInstanceOf(SecurityException.class); SessionContext.setContext( @@ -182,9 +180,8 @@ void committedLaunchRequiresSameNamespaceGameSessionWithoutEndUserContextBeforeA fixture.request().expectedDescriptorResultDigest(), fixture.request().expectedReleaseAttestationEvidenceDigest()); SessionContext.clear(); - assertThatThrownBy( - () -> - withGameSession(() -> committedService.bindCommittedLaunch(wrongNamespaceRequest))) + assertThatThrownBy(() -> + withGameSession(() -> committedService.bindCommittedLaunch(wrongNamespaceRequest))) .isInstanceOf(SecurityException.class); verifyNoInteractions(client, gameSessionClient, repository, sourceRepository); assertThat(transactionManager.startedWith).isNull(); @@ -207,10 +204,8 @@ void committedLaunchRefusesAmbientTransactionBeforeRemoteOrOwnerAccess() { TransactionSynchronizationManager.setActualTransactionActive(true); TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); - assertThatThrownBy( - () -> - withGameSession( - () -> committedLaunchService().bindCommittedLaunch(fixture.request()))) + assertThatThrownBy(() -> + withGameSession(() -> committedLaunchService().bindCommittedLaunch(fixture.request()))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("outside ambient transactions"); verifyNoInteractions(client, gameSessionClient, repository, sourceRepository); @@ -264,10 +259,8 @@ void committedLaunchRejectsGameSessionPairThatDiffersFromGameDesignBeforeSourceO when(client.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(fixture.evidence()); when(gameSessionClient.read(fixture.request())).thenReturn(mismatchedAssociation); - assertThatThrownBy( - () -> - withGameSession( - () -> committedLaunchService().bindCommittedLaunch(fixture.request()))) + assertThatThrownBy(() -> + withGameSession(() -> committedLaunchService().bindCommittedLaunch(fixture.request()))) .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class); verify(sourceRepository, never()).readBySource(any(), any(), any(), any(), any()); verifyNoInteractions(repository); @@ -299,10 +292,8 @@ void committedLaunchRejectsGameSessionReadbackForAChangedSelectorBeforeSourceOrW when(client.getComplete(any(GetLaunchDescriptorRequest.class))).thenReturn(fixture.evidence()); when(gameSessionClient.read(fixture.request())).thenReturn(changedAssociation); - assertThatThrownBy( - () -> - withGameSession( - () -> committedLaunchService().bindCommittedLaunch(fixture.request()))) + assertThatThrownBy(() -> + withGameSession(() -> committedLaunchService().bindCommittedLaunch(fixture.request()))) .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class) .hasMessageContaining("exact World selector"); verify(sourceRepository, never()).readBySource(any(), any(), any(), any(), any()); @@ -342,10 +333,8 @@ void committedLaunchRetryRejectsAChangedRetainedReleasePairWithoutReplacement() when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)) .thenReturn(Optional.of(changedStored)); - assertThatThrownBy( - () -> - withGameSession( - () -> committedLaunchService().bindCommittedLaunch(fixture.request()))) + assertThatThrownBy(() -> + withGameSession(() -> committedLaunchService().bindCommittedLaunch(fixture.request()))) .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class); verify(repository, never()).acceptFresh(any(), any(), any()); verify(repository, never()).toReceipt(any(), any()); @@ -364,10 +353,8 @@ void committedLaunchRequiresExactSourceIntakeBeforeWorldBindingOwnerAccess() { fixture.sourceReceipt().sourceEvidenceDigest())) .thenReturn(Optional.empty()); - assertThatThrownBy( - () -> - withGameSession( - () -> committedLaunchService().bindCommittedLaunch(fixture.request()))) + assertThatThrownBy(() -> + withGameSession(() -> committedLaunchService().bindCommittedLaunch(fixture.request()))) .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) .hasMessageContaining("no exact committed World source intake"); verifyNoInteractions(repository); @@ -474,10 +461,8 @@ void committedLaunchRejectsChangedPairDuringLostCommitAcknowledgmentRecovery() { .thenReturn(fixture.receipt()); transactionManager.loseCommitAcknowledgment = true; - assertThatThrownBy( - () -> - withGameSession( - () -> committedLaunchService().bindCommittedLaunch(fixture.request()))) + assertThatThrownBy(() -> + withGameSession(() -> committedLaunchService().bindCommittedLaunch(fixture.request()))) .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class); verify(repository).acceptFresh(NAMESPACE, fixture.sourceReceipt(), fixture.evidence()); verify(repository, never()).toReceipt(any(), any()); @@ -499,17 +484,15 @@ void requiresExactSameNamespaceGameSessionPeerBeforeOwnerOrGameDesignAccess() { assertThatThrownBy( () -> withoutPeer(() -> service.readCurrentVersionState(request, CURRENT_READ_ID))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withPeer( - peer(NAMESPACE, "game-design-service"), - () -> service.readCurrentVersionState(request, CURRENT_READ_ID))) + assertThatThrownBy(() -> + withPeer( + peer(NAMESPACE, "game-design-service"), + () -> service.readCurrentVersionState(request, CURRENT_READ_ID))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withPeer( - peer("other", "game-session-service"), - () -> service.readCurrentVersionState(request, CURRENT_READ_ID))) + assertThatThrownBy(() -> + withPeer( + peer("other", "game-session-service"), + () -> service.readCurrentVersionState(request, CURRENT_READ_ID))) .isInstanceOf(SecurityException.class); AuthoredWorldLaunchDescriptorEvidence.Request original = request.expectedRequest(); AuthoredWorldLaunchDescriptorEvidence.Request wrongNamespace = @@ -529,20 +512,15 @@ void requiresExactSameNamespaceGameSessionPeerBeforeOwnerOrGameDesignAccess() { original.targetVersionId(), original.requestedRuntimeFlagsJsonPresent(), original.requestedRuntimeFlagsJson()); - assertThatThrownBy( - () -> - withGameSession( - () -> - service.bind( - new GetRequest(UUID.randomUUID(), wrongNamespace, digest('a'))))) + assertThatThrownBy(() -> + withGameSession( + () -> service.bind(new GetRequest(UUID.randomUUID(), wrongNamespace, digest('a'))))) .isInstanceOf(SecurityException.class); - assertThatThrownBy( - () -> - withGameSession( - () -> - service.readCurrentVersionState( - new GetRequest(UUID.randomUUID(), wrongNamespace, digest('a')), - CURRENT_READ_ID))) + assertThatThrownBy(() -> + withGameSession(() -> + service.readCurrentVersionState( + new GetRequest(UUID.randomUUID(), wrongNamespace, digest('a')), + CURRENT_READ_ID))) .isInstanceOf(SecurityException.class); verifyNoInteractions(client, versionStateClient, repository, sourceRepository); } @@ -624,10 +602,9 @@ void missingOrSwappedCompletePairCannotReachWorldPersistence() { CompleteLaunchBindingEvidence expectedEvidence = evidence(source); CompleteLaunchBindingEvidence otherEvidence = evidence(source, "another-world-launch-request", 42L); - assertThatThrownBy( - () -> - new CompleteLaunchBindingEvidence( - expectedEvidence.descriptor(), otherEvidence.releaseAttestation())) + assertThatThrownBy(() -> + new CompleteLaunchBindingEvidence( + expectedEvidence.descriptor(), otherEvidence.releaseAttestation())) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> new CompleteLaunchBindingEvidence(null, null)) .isInstanceOf(NullPointerException.class); @@ -656,10 +633,9 @@ void refusesAmbientTransactionBeforeReadingOrCallingGameDesign() { assertThatThrownBy(() -> withGameSession(() -> service.bind(request(evidence)))) .isInstanceOf(IllegalStateException.class); - assertThatThrownBy( - () -> - withGameSession( - () -> service.readCurrentVersionState(request(evidence), CURRENT_READ_ID))) + assertThatThrownBy(() -> + withGameSession( + () -> service.readCurrentVersionState(request(evidence), CURRENT_READ_ID))) .isInstanceOf(IllegalStateException.class); verifyNoInteractions(client, versionStateClient, repository, sourceRepository); } @@ -675,21 +651,19 @@ void recoversACommitAcknowledgmentLossByReadingTheSameOwnerOperation() { AtomicReference committed = new AtomicReference<>(); when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)) - .thenAnswer( - invocation -> { - WorldCompleteLaunchBindingRepository.StoredBinding value = committed.get(); - return value == null ? Optional.empty() : Optional.of(value); - }); + .thenAnswer(invocation -> { + WorldCompleteLaunchBindingRepository.StoredBinding value = committed.get(); + return value == null ? Optional.empty() : Optional.of(value); + }); when(client.getComplete(any())).thenReturn(evidence); when(sourceRepository.readBySource( NAMESPACE, TENANT, WORLD, SOURCE_OPERATION, source.evidenceDigest())) .thenReturn(Optional.of(sourceReceipt)); when(repository.acceptFresh(NAMESPACE, sourceReceipt, evidence)) - .thenAnswer( - invocation -> { - committed.set(stored); - return receipt; - }); + .thenAnswer(invocation -> { + committed.set(stored); + return receipt; + }); when(repository.toReceipt(stored, sourceReceipt)).thenReturn(receipt); transactionManager.loseCommitAcknowledgment = true; @@ -791,10 +765,9 @@ void repeatedCurrentReadsObserveVersionAdvanceAndRejectTheStaleDescriptorPair() AuthoredWorldVersionStateEvidence firstRead = withGameSession(() -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID)); assertThat(firstRead).isEqualTo(first); - assertThatThrownBy( - () -> - withGameSession( - () -> service.readCurrentVersionState(request(binding), ADVANCED_READ_ID))) + assertThatThrownBy(() -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), ADVANCED_READ_ID))) .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) .hasMessageContaining("epoch differs"); @@ -826,10 +799,9 @@ void rejectsCurrentEvidenceForAnotherAuthoredSource() { binding.descriptor().versionStateEpoch()); when(versionStateClient.read(any())).thenReturn(swappedSource); - assertThatThrownBy( - () -> - withGameSession( - () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + assertThatThrownBy(() -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) .hasMessageContaining("exact committed World source"); verify(repository, never()).acceptFresh(any(), any(), any()); @@ -849,10 +821,9 @@ void rejectsAChangedVersionSelectorInCurrentOwnerEvidence() { binding.descriptor().versionStateEpoch()); when(versionStateClient.read(any())).thenReturn(swappedSelector); - assertThatThrownBy( - () -> - withGameSession( - () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + assertThatThrownBy(() -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) .hasMessageContaining("exact committed World source"); verify(repository, never()).acceptFresh(any(), any(), any()); @@ -887,10 +858,9 @@ void rejectsCurrentEvidenceWithCanonicalVersionUuidDifferentFromReleaseAttestati assertThat(substituted.canonicalVersionId()).isNotEqualTo(committedCanonicalVersionId); when(versionStateClient.read(any())).thenReturn(substituted); - assertThatThrownBy( - () -> - withGameSession( - () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + assertThatThrownBy(() -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) .hasMessageContaining("canonical version UUID differs"); verify(repository, never()).acceptFresh(any(), any(), any()); @@ -904,10 +874,8 @@ void changedBindingRequestIsRejectedBeforeReadingCurrentOwnerEvidence() { GetRequest substituted = new GetRequest(UUID.randomUUID(), binding.descriptor().request(), digest('b')); - assertThatThrownBy( - () -> - withGameSession( - () -> service.readCurrentVersionState(substituted, CURRENT_READ_ID))) + assertThatThrownBy(() -> + withGameSession(() -> service.readCurrentVersionState(substituted, CURRENT_READ_ID))) .isInstanceOf(WorldCompleteLaunchBindingRepository.RegistrationConflictException.class); verifyNoInteractions(versionStateClient); verify(repository, never()).acceptFresh(any(), any(), any()); @@ -918,10 +886,9 @@ void requiresAnAlreadyCommittedPairWithoutRegisteringOne() { CompleteLaunchBindingEvidence binding = evidence(source()); when(repository.read(NAMESPACE, TENANT, CONTROL_PLANE_REQUEST)).thenReturn(Optional.empty()); - assertThatThrownBy( - () -> - withGameSession( - () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + assertThatThrownBy(() -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) .hasMessageContaining("requires a committed launch binding"); verifyNoInteractions(client, versionStateClient, sourceRepository); @@ -942,10 +909,9 @@ void deniesDraftRetiredAndUnavailableCurrentVersionEvidenceWithoutChangingThePai binding.descriptor().versionStateEpoch()); when(versionStateClient.read(any())).thenReturn(draft); - assertThatThrownBy( - () -> - withGameSession( - () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) + assertThatThrownBy(() -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), CURRENT_READ_ID))) .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) .hasMessageContaining("not PUBLISHED or ACTIVE"); @@ -957,19 +923,16 @@ void deniesDraftRetiredAndUnavailableCurrentVersionEvidenceWithoutChangingThePai VersionLifecycleState.VERSION_LIFECYCLE_STATE_RETIRED, binding.descriptor().versionStateEpoch()); when(versionStateClient.read(any())).thenReturn(retired); - assertThatThrownBy( - () -> - withGameSession( - () -> service.readCurrentVersionState(request(binding), OTHER_READ_ID))) + assertThatThrownBy(() -> + withGameSession(() -> service.readCurrentVersionState(request(binding), OTHER_READ_ID))) .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) .hasMessageContaining("not PUBLISHED or ACTIVE"); when(versionStateClient.read(any())) .thenThrow(new IllegalStateException("Game Design is unavailable")); - assertThatThrownBy( - () -> - withGameSession( - () -> service.readCurrentVersionState(request(binding), ADVANCED_READ_ID))) + assertThatThrownBy(() -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), ADVANCED_READ_ID))) .isInstanceOf(WorldCompleteLaunchBindingRepository.InvalidBindingEvidenceException.class) .hasMessageContaining("unavailable or invalid"); assertThat(original.evidence()).isEqualTo(binding); @@ -982,26 +945,19 @@ void rejectsReadCorrelationIdsReusedFromSourceOrRegistration() { CompleteLaunchBindingEvidence binding = evidence(source); stubCommittedBinding(source, binding); - assertThatThrownBy( - () -> - withGameSession( - () -> service.readCurrentVersionState(request(binding), SOURCE_OPERATION))) + assertThatThrownBy(() -> + withGameSession( + () -> service.readCurrentVersionState(request(binding), SOURCE_OPERATION))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("separate from source and registration IDs"); - assertThatThrownBy( - () -> - withGameSession( - () -> - service.readCurrentVersionState( - request(binding), source.registrationRequestId()))) + assertThatThrownBy(() -> + withGameSession(() -> + service.readCurrentVersionState(request(binding), source.registrationRequestId()))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("separate from source and registration IDs"); - assertThatThrownBy( - () -> - withGameSession( - () -> - service.readCurrentVersionState( - request(binding), request(binding).requestId()))) + assertThatThrownBy(() -> + withGameSession(() -> + service.readCurrentVersionState(request(binding), request(binding).requestId()))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("separate from source and registration IDs"); verifyNoInteractions(versionStateClient); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java index efc37b84fc..585690386e 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDesignPublicationFenceEvidenceTest.java @@ -74,100 +74,95 @@ void rejectsMalformedScopeAndAuthoredSourceIdentifiers() { assertThatIllegalArgumentException() .isThrownBy(() -> evidence("request-7", validDigest(), validWorkflow(), 42, 0L)); assertThatIllegalArgumentException() - .isThrownBy( - () -> - new WorldDesignPublicationFenceEvidence( - "FireMUD", - TENANT_ID, - CANONICAL_VERSION_ID, - VERSION_IDENTITY_OPERATION_ID, - 42, - INTAKE_REQUEST_ID, - INTAKE_OPERATION_ID, - INTAKE_REQUEST_DIGEST, - SOURCE_OPERATION_ID, - SOURCE_EVIDENCE_DIGEST, - INTAKE_RECEIPT_DIGEST, - "request-7", - validDigest(), - 9, - validWorkflow())); + .isThrownBy(() -> + new WorldDesignPublicationFenceEvidence( + "FireMUD", + TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, + 42, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST, + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + INTAKE_RECEIPT_DIGEST, + "request-7", + validDigest(), + 9, + validWorkflow())); assertThatIllegalArgumentException() - .isThrownBy( - () -> - new WorldDesignPublicationFenceEvidence( - "firemud", - TENANT_ID, - CANONICAL_VERSION_ID, - VERSION_IDENTITY_OPERATION_ID, - GAME_DESIGN_VERSION_ID, - INTAKE_REQUEST_ID, - INTAKE_OPERATION_ID, - INTAKE_REQUEST_DIGEST, - SOURCE_OPERATION_ID, - SOURCE_EVIDENCE_DIGEST, - INTAKE_RECEIPT_DIGEST.substring("sha256:".length()), - "request-7", - validDigest(), - 9, - validWorkflow())); + .isThrownBy(() -> + new WorldDesignPublicationFenceEvidence( + "firemud", + TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, + GAME_DESIGN_VERSION_ID, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST, + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + INTAKE_RECEIPT_DIGEST.substring("sha256:".length()), + "request-7", + validDigest(), + 9, + validWorkflow())); assertThatIllegalArgumentException() - .isThrownBy( - () -> - new WorldDesignPublicationFenceEvidence( - "firemud", - NIL_TENANT_ID, - CANONICAL_VERSION_ID, - VERSION_IDENTITY_OPERATION_ID, - GAME_DESIGN_VERSION_ID, - INTAKE_REQUEST_ID, - INTAKE_OPERATION_ID, - INTAKE_REQUEST_DIGEST, - SOURCE_OPERATION_ID, - SOURCE_EVIDENCE_DIGEST, - INTAKE_RECEIPT_DIGEST, - "request-7", - validDigest(), - 9, - validWorkflow(NIL_TENANT_ID))); + .isThrownBy(() -> + new WorldDesignPublicationFenceEvidence( + "firemud", + NIL_TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, + GAME_DESIGN_VERSION_ID, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST, + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + INTAKE_RECEIPT_DIGEST, + "request-7", + validDigest(), + 9, + validWorkflow(NIL_TENANT_ID))); assertThatIllegalArgumentException() - .isThrownBy( - () -> - new WorldDesignPublicationFenceEvidence( - "firemud", - TENANT_ID, - CANONICAL_VERSION_ID, - VERSION_IDENTITY_OPERATION_ID, - 42, - INTAKE_REQUEST_ID, - INTAKE_OPERATION_ID, - INTAKE_REQUEST_DIGEST, - SOURCE_OPERATION_ID, - "a".repeat(64), - INTAKE_RECEIPT_DIGEST, - "request-7", - validDigest(), - 9, - validWorkflow())); + .isThrownBy(() -> + new WorldDesignPublicationFenceEvidence( + "firemud", + TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, + 42, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST, + SOURCE_OPERATION_ID, + "a".repeat(64), + INTAKE_RECEIPT_DIGEST, + "request-7", + validDigest(), + 9, + validWorkflow())); assertThatIllegalArgumentException() - .isThrownBy( - () -> - new WorldDesignPublicationFenceEvidence( - "firemud", - TENANT_ID, - CANONICAL_VERSION_ID, - VERSION_IDENTITY_OPERATION_ID, - GAME_DESIGN_VERSION_ID, - INTAKE_REQUEST_ID, - INTAKE_OPERATION_ID, - INTAKE_REQUEST_DIGEST.substring("sha256:".length()), - SOURCE_OPERATION_ID, - SOURCE_EVIDENCE_DIGEST, - INTAKE_RECEIPT_DIGEST, - "request-7", - validDigest(), - 9, - validWorkflow())); + .isThrownBy(() -> + new WorldDesignPublicationFenceEvidence( + "firemud", + TENANT_ID, + CANONICAL_VERSION_ID, + VERSION_IDENTITY_OPERATION_ID, + GAME_DESIGN_VERSION_ID, + INTAKE_REQUEST_ID, + INTAKE_OPERATION_ID, + INTAKE_REQUEST_DIGEST.substring("sha256:".length()), + SOURCE_OPERATION_ID, + SOURCE_EVIDENCE_DIGEST, + INTAKE_RECEIPT_DIGEST, + "request-7", + validDigest(), + 9, + validWorkflow())); } @Test @@ -185,15 +180,11 @@ void checkpointRequiresACompleteCanonicalDigestTuple() { .isThrownBy( () -> new WorldDesignPublicationFenceEvidence.Checkpoint(" \t", CONTENT_DIGEST, 2)); assertThatIllegalArgumentException() - .isThrownBy( - () -> - new WorldDesignPublicationFenceEvidence.Checkpoint( - "version:42", "B".repeat(64), 2)); + .isThrownBy(() -> + new WorldDesignPublicationFenceEvidence.Checkpoint("version:42", "B".repeat(64), 2)); assertThatIllegalArgumentException() - .isThrownBy( - () -> - new WorldDesignPublicationFenceEvidence.Checkpoint( - "version:42", CONTENT_DIGEST, 0)); + .isThrownBy(() -> + new WorldDesignPublicationFenceEvidence.Checkpoint("version:42", CONTENT_DIGEST, 0)); } private static WorldDesignPublicationFenceEvidence evidence( diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftCommitOrderVerifierTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftCommitOrderVerifierTest.java index 123167bf71..8c9ad815eb 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftCommitOrderVerifierTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftCommitOrderVerifierTest.java @@ -37,12 +37,11 @@ void derivesExactOriginalBindingAndReturnsProofOnlyAfterClientHeldResponse() thr var operation = operation("test"); var client = mock(DraftCommitOrderReadClient.class); when(client.read(any())) - .thenAnswer( - invocation -> { - var request = (DraftCommitOrderReadEvidence.Request) invocation.getArgument(0); - return DraftCommitOrderReadGrpcCodec.fromResponse( - request, DraftCommitOrderReadGrpcCodec.toHeldResponse(request)); - }); + .thenAnswer(invocation -> { + var request = (DraftCommitOrderReadEvidence.Request) invocation.getArgument(0); + return DraftCommitOrderReadGrpcCodec.fromResponse( + request, DraftCommitOrderReadGrpcCodec.toHeldResponse(request)); + }); var verifier = new WorldDraftCommitOrderVerifier(client, "test"); CommitOrderProof proof = verifier.verifyHeldOriginalCommitOrder(operation); @@ -78,19 +77,17 @@ void rejectsChangedReadRequestUnavailableClientAndWrongNamespaceWithoutProof() t var offline = mock(DraftCommitOrderReadClient.class); when(offline.read(any())).thenThrow(new IllegalStateException("Account unavailable")); - assertThatThrownBy( - () -> - new WorldDraftCommitOrderVerifier(offline, "test") - .verifyHeldOriginalCommitOrder(operation)) + assertThatThrownBy(() -> + new WorldDraftCommitOrderVerifier(offline, "test") + .verifyHeldOriginalCommitOrder(operation)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("unavailable"); var namespaceClient = mock(DraftCommitOrderReadClient.class); var otherNamespaceOperation = operation("other"); - assertThatThrownBy( - () -> - new WorldDraftCommitOrderVerifier(namespaceClient, "test") - .verifyHeldOriginalCommitOrder(otherNamespaceOperation)) + assertThatThrownBy(() -> + new WorldDraftCommitOrderVerifier(namespaceClient, "test") + .verifyHeldOriginalCommitOrder(otherNamespaceOperation)) .isInstanceOf(WorldDesignPublicationFenceRepository.ConflictException.class) .hasMessageContaining("namespace"); verify(namespaceClient, never()).read(any()); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationServiceTest.java index cd8bb0bf94..985228a0ac 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftGraphApplicationServiceTest.java @@ -69,10 +69,8 @@ void changedOriginalProofDeniesBeforeWriterTransaction() { when(operation.accountBindingBytes()).thenReturn(new byte[] {3}); when(repository.readCommitted(application)).thenReturn(Optional.empty()); when(verifier.verifyHeldOriginalCommitOrder(operation)).thenReturn(proof); - assertThatThrownBy( - () -> - new WorldDraftGraphApplicationService(repository, manager, verifier) - .apply(application)) + assertThatThrownBy(() -> + new WorldDraftGraphApplicationService(repository, manager, verifier).apply(application)) .hasMessageContaining("proof differs from original complete operation"); verifyNoInteractions(manager); } @@ -89,10 +87,8 @@ void stipulatedAuthorityPrecedesDedicatedTransactionAndLateFailureRollsBack() { var status = mock(TransactionStatus.class); when(manager.getTransaction(any())).thenReturn(status); when(repository.apply(application, proof)).thenThrow(new IllegalStateException("late failure")); - assertThatThrownBy( - () -> - new WorldDraftGraphApplicationService(repository, manager, verifier) - .apply(application)) + assertThatThrownBy(() -> + new WorldDraftGraphApplicationService(repository, manager, verifier).apply(application)) .hasMessage("late failure"); var order = inOrder(repository, verifier, manager); order.verify(repository).readCommitted(application); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeTest.java index 2f80d78869..a412343e35 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTerminalOutcomeTest.java @@ -41,40 +41,32 @@ void changedOperationFenceTargetOrGameDesignBytesCannotReuseTheAccountBinding() DraftCommitBinding binding = binding(ids); byte[] accountBytes = accountBinding(binding, ids).canonicalBytes(); - assertThatThrownBy( - () -> - operation( - binding, - accountBytes, - new Ids( - UUID.randomUUID(), ids.request(), ids.commit(), ids.fence(), ids.actor()))) + assertThatThrownBy(() -> + operation( + binding, + accountBytes, + new Ids(UUID.randomUUID(), ids.request(), ids.commit(), ids.fence(), ids.actor()))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("V57 Account binding"); - assertThatThrownBy( - () -> - operation( - binding, - accountBytes, - new Ids( - ids.operation(), - ids.request(), - ids.commit(), - UUID.randomUUID(), - ids.actor()))) + assertThatThrownBy(() -> + operation( + binding, + accountBytes, + new Ids( + ids.operation(), ids.request(), ids.commit(), UUID.randomUUID(), ids.actor()))) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("V57 Account binding"); - assertThatThrownBy( - () -> - new WorldDraftTerminalOperation( - ids.operation(), - ids.request(), - ids.commit(), - ids.fence(), - UUID.randomUUID(), - binding.target().canonicalVersionId(), - binding, - ownerBinding(binding), - accountBytes)) + assertThatThrownBy(() -> + new WorldDraftTerminalOperation( + ids.operation(), + ids.request(), + ids.commit(), + ids.fence(), + UUID.randomUUID(), + binding.target().canonicalVersionId(), + binding, + ownerBinding(binding), + accountBytes)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("complete Draft binding"); } @@ -100,27 +92,24 @@ void abortEvidenceRequiresEveryExactWorldEpochAndRejectsSubstitutionOrMalformedF assertThat(replay.canonicalBytes()).containsExactly(outcome.canonicalBytes()); assertThat(replay.digest()).isEqualTo(outcome.digest()); assertThat(replay.observedEpochs()).isEqualTo(observed); - assertThatThrownBy( - () -> - WorldDraftTerminalOutcome.create( - operation, observed.subList(0, 1), outcome.recordedAt())) + assertThatThrownBy(() -> + WorldDraftTerminalOutcome.create( + operation, observed.subList(0, 1), outcome.recordedAt())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("complete affected set"); - assertThatThrownBy( - () -> - WorldDraftTerminalOutcome.fromStored( - operation, - outcome.canonicalBytes(), - digest("substituted".getBytes(StandardCharsets.UTF_8)), - outcome.recordedAt())) + assertThatThrownBy(() -> + WorldDraftTerminalOutcome.fromStored( + operation, + outcome.canonicalBytes(), + digest("substituted".getBytes(StandardCharsets.UTF_8)), + outcome.recordedAt())) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("not exact canonical evidence"); byte[] trailing = java.util.Arrays.copyOf(outcome.canonicalBytes(), outcome.canonicalBytes().length + 1); - assertThatThrownBy( - () -> - WorldDraftTerminalOutcome.fromStored( - operation, trailing, outcome.digest(), outcome.recordedAt())) + assertThatThrownBy(() -> + WorldDraftTerminalOutcome.fromStored( + operation, trailing, outcome.digest(), outcome.recordedAt())) .isInstanceOf(IllegalArgumentException.class); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidenceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidenceTest.java index cb20d8e0c8..fa4656c1eb 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidenceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitEvidenceTest.java @@ -31,13 +31,12 @@ void graphAndResultBytesAreDefensiveAndRemainExplicitlyUnverifiedPermission() { @Test void incompleteEvidenceCannotBeReturnedAsSuccessfulComponentStorage() { - assertThatThrownBy( - () -> - new WorldDraftTopologyCommitEvidence( - mock(DraftCommitBinding.class), - mock(WorldDesignPublicationFenceEvidence.OwnerBinding.class), - new byte[0], - new byte[] {1})) + assertThatThrownBy(() -> + new WorldDraftTopologyCommitEvidence( + mock(DraftCommitBinding.class), + mock(WorldDesignPublicationFenceEvidence.OwnerBinding.class), + new byte[0], + new byte[] {1})) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlanTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlanTest.java index 258eb81309..11e0b0adf3 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlanTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldDraftTopologyCommitPlanTest.java @@ -78,11 +78,8 @@ void preservesCompleteMixedOwnerBindingAllFamiliesAndEveryPayloadField() { .isEqualTo("other-owner-byte-string"); assertThatThrownBy(() -> plan.graph().nodes().clear()) .isInstanceOf(UnsupportedOperationException.class); - assertThatThrownBy( - () -> - plan.graph() - .family(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM) - .clear()) + assertThatThrownBy(() -> + plan.graph().family(WorldDesignAggregateType.WORLD_DESIGN_AGGREGATE_TYPE_ROOM).clear()) .isInstanceOf(UnsupportedOperationException.class); } @@ -691,15 +688,14 @@ TENANT, id(99), 901, "source-key", 801, "source-key", "NEW_GAME_ROW"), new DraftCommitBinding.RevisionPayload( prior.revisionOrder(), revisions.get(1).revisionId(), prior.owner(), prior.payload())); assertThatIllegalArgumentException() - .isThrownBy( - () -> - DraftCommitBinding.create( - good.target(), - good.requestId(), - good.commitId(), - good.baseCommitId(), - revisions, - good.affectedUnits())); + .isThrownBy(() -> + DraftCommitBinding.create( + good.target(), + good.requestId(), + good.commitId(), + good.baseCommitId(), + revisions, + good.affectedUnits())); } static WorldDraftTopologyCommitPlan selectedPlanWithAllFamilies() { diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplicationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplicationServiceTest.java index 92f676d42b..9aee9c13b4 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplicationServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplicationServiceTest.java @@ -225,54 +225,51 @@ void sourceRowKeyProvenanceAndTargetScopeSubstitutionsAreDenied() { .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class) .hasMessageContaining("retained World source"); - assertThatThrownBy( - () -> - service.apply( - NAMESPACE, - accountBinding( - binding( - id(22), - VERSION, - GAME_DESIGN_VERSION_ROW, - GAME_TENANT_KEY, - SOURCE_GAME_ROW, - GAME_TENANT_KEY, - "NEW_GAME_ROW")) - .canonicalBytes())) + assertThatThrownBy(() -> + service.apply( + NAMESPACE, + accountBinding( + binding( + id(22), + VERSION, + GAME_DESIGN_VERSION_ROW, + GAME_TENANT_KEY, + SOURCE_GAME_ROW, + GAME_TENANT_KEY, + "NEW_GAME_ROW")) + .canonicalBytes())) .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class) .hasMessageContaining("retained World source"); - assertThatThrownBy( - () -> - service.apply( - NAMESPACE, - accountBinding( - binding( - TENANT, - id(23), - GAME_DESIGN_VERSION_ROW, - GAME_TENANT_KEY, - SOURCE_GAME_ROW, - GAME_TENANT_KEY, - "NEW_GAME_ROW")) - .canonicalBytes())) + assertThatThrownBy(() -> + service.apply( + NAMESPACE, + accountBinding( + binding( + TENANT, + id(23), + GAME_DESIGN_VERSION_ROW, + GAME_TENANT_KEY, + SOURCE_GAME_ROW, + GAME_TENANT_KEY, + "NEW_GAME_ROW")) + .canonicalBytes())) .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class) .hasMessageContaining("retained World source"); - assertThatThrownBy( - () -> - service.apply( - NAMESPACE, - accountBinding( - binding( - TENANT, - VERSION, - GAME_DESIGN_VERSION_ROW + 1, - GAME_TENANT_KEY, - SOURCE_GAME_ROW, - GAME_TENANT_KEY, - "NEW_GAME_ROW")) - .canonicalBytes())) + assertThatThrownBy(() -> + service.apply( + NAMESPACE, + accountBinding( + binding( + TENANT, + VERSION, + GAME_DESIGN_VERSION_ROW + 1, + GAME_TENANT_KEY, + SOURCE_GAME_ROW, + GAME_TENANT_KEY, + "NEW_GAME_ROW")) + .canonicalBytes())) .isInstanceOf(WorldAuthoredVersionIdentityRepository.RegistrationConflictException.class) .hasMessageContaining("retained World source"); verify(graphApplications, never()).apply(any(WorldDraftGraphApplication.class)); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcServiceTest.java index f5f8550190..4bdaa48cae 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalDraftGraphApplyGrpcServiceTest.java @@ -181,11 +181,10 @@ void mapsUpstreamTransportStatusToRetryableOrSafePreconditionStatus() { .isEqualTo("World original apply owner did not accept the request") .doesNotContain("account-permission-sensitive"); assertThat(List.of(unavailable, deadline, denied)) - .allSatisfy( - response -> { - assertThat(response.value).isNull(); - assertThat(response.completed).isFalse(); - }); + .allSatisfy(response -> { + assertThat(response.value).isNull(); + assertThat(response.completed).isFalse(); + }); } @Test diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionActivationTerminalReadGrpcMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionActivationTerminalReadGrpcMtlsTest.java index 53a6e4ebba..43a8557a8a 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionActivationTerminalReadGrpcMtlsTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionActivationTerminalReadGrpcMtlsTest.java @@ -112,10 +112,9 @@ void trustedWrongServiceAndWrongNamespaceCertificatesAreDeniedBeforeOwner() thro assertThatThrownBy(() -> client.read(input)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } } } @@ -146,20 +145,16 @@ void missingClientCertificateIsRejectedByTlsBeforeHandlerOrOwner() throws Except var request = WorldOriginalStartSessionActivationTerminalReadGrpcCodec.toRequest(input, "test"); - assertThatThrownBy( - () -> - WorldOriginalStartSessionActivationTerminalReadServiceGrpc.newBlockingStub( - unauthenticatedClient.channel()) - .withDeadlineAfter(3, TimeUnit.SECONDS) - .readOriginalStartSessionActivationTerminalEvidence(request)) + assertThatThrownBy(() -> + WorldOriginalStartSessionActivationTerminalReadServiceGrpc.newBlockingStub( + unauthenticatedClient.channel()) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .readOriginalStartSessionActivationTerminalEvidence(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) - .as( - "missing client certificate must fail during TLS negotiation: %s", - failure) - .isTrue()); + .satisfies(failure -> + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as("missing client certificate must fail during TLS negotiation: %s", failure) + .isTrue()); } assertThat(handlerCalls).hasValue(0); @@ -189,10 +184,9 @@ void authenticatedEndUserContextIsDeniedBeforeOwner() throws Exception { assertThatThrownBy(() -> client.read(input)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } assertThat(handlerCalls).hasValue(1); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcMtlsTest.java index d58e63e4f6..59b9d08cbe 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcMtlsTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationGrpcMtlsTest.java @@ -110,10 +110,9 @@ void trustedWrongServiceAndWrongNamespaceCertificatesAreDeniedBeforeOwner() thro assertThatThrownBy(() -> client.activate(fixture.input())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } } } @@ -140,20 +139,16 @@ void missingClientCertificateIsRejectedByTlsBeforeHandlerOrOwner() throws Except var request = WorldOriginalStartSessionProtectedActivationGrpcCodec.toRequest(fixture.input(), "test"); - assertThatThrownBy( - () -> - WorldOriginalStartSessionProtectedActivationServiceGrpc.newBlockingStub( - unauthenticatedClient.channel()) - .withDeadlineAfter(3, TimeUnit.SECONDS) - .activateOriginalStartSessionProtected(request)) + assertThatThrownBy(() -> + WorldOriginalStartSessionProtectedActivationServiceGrpc.newBlockingStub( + unauthenticatedClient.channel()) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .activateOriginalStartSessionProtected(request)) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) - .as( - "missing client certificate must fail during TLS negotiation: %s", - failure) - .isTrue()); + .satisfies(failure -> + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as("missing client certificate must fail during TLS negotiation: %s", failure) + .isTrue()); } assertThat(handlerCalls).hasValue(0); @@ -179,10 +174,9 @@ void authenticatedEndUserContextIsDeniedBeforeOwner() throws Exception { assertThatThrownBy(() -> client.activate(fixture.input())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } assertThat(handlerCalls).hasValue(1); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationServiceTest.java index ffad688ece..f8d8e1f366 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationServiceTest.java @@ -116,17 +116,16 @@ void absentOperationAcquiresAndComparesCompleteCallerBindingBeforeProtectedCas() when(repository.readProtectedActivationByAcquisitionInput(input)).thenReturn(Optional.empty()); when(account.acquire(input)).thenReturn(protection); when(activation.activateProtected(eq(protection), any())) - .thenAnswer( - call -> { - WorldCanonicalInstanceActivationService.HeldActivationAuthority held = - call.getArgument(1); - held.requireHeld(); - held.close(); - assertThatThrownBy(held::requireHeld) - .isInstanceOf( - WorldCanonicalInstanceActivationService.ActivationDeniedException.class); - return terminal; - }); + .thenAnswer(call -> { + WorldCanonicalInstanceActivationService.HeldActivationAuthority held = + call.getArgument(1); + held.requireHeld(); + held.close(); + assertThatThrownBy(held::requireHeld) + .isInstanceOf( + WorldCanonicalInstanceActivationService.ActivationDeniedException.class); + return terminal; + }); assertThat(service.activate(input)).isSameAs(terminal); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperationRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperationRepositoryTest.java index 786854a681..f8acfa01a3 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperationRepositoryTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperationRepositoryTest.java @@ -114,16 +114,15 @@ void terminalAndSourceBindingsRejectIncompleteIdentityAndNeverAdmit() { ByteString.copyFromUtf8("controlled abort")); assertThat(applied.admissionAllowed()).isFalse(); assertThat(aborted.admissionAllowed()).isFalse(); - assertThatThrownBy( - () -> - new Terminal( - UUID.randomUUID(), - UUID.randomUUID(), - DIGEST, - "APPLIED", - null, - null, - ByteString.copyFromUtf8("bad"))) + assertThatThrownBy(() -> + new Terminal( + UUID.randomUUID(), + UUID.randomUUID(), + DIGEST, + "APPLIED", + null, + null, + ByteString.copyFromUtf8("bad"))) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy( () -> new SourceProtectionBinding(UUID.randomUUID(), new UUID(0, 0), 1, DIGEST)) diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPrivatePreparationInputAssemblyTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPrivatePreparationInputAssemblyTest.java index 38d1464ca5..e556d32e73 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPrivatePreparationInputAssemblyTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPrivatePreparationInputAssemblyTest.java @@ -51,14 +51,13 @@ void changedTargetReceiptBetweenActualReadsRejectsAssembly() throws Exception { index == 1 ? facts : WorldPrivatePreparationSourceClientMtlsTest.changedReceipt(facts)))) { - assertThatThrownBy( - () -> - new WorldPrivatePreparationInputAssembly( - f.client, - Clock.fixed( - WorldPrivatePreparationSourceClientMtlsTest.NOW.plusSeconds(2), - ZoneOffset.UTC)) - .assemble(facts.scope(), facts.preparation().requestId())) + assertThatThrownBy(() -> + new WorldPrivatePreparationInputAssembly( + f.client, + Clock.fixed( + WorldPrivatePreparationSourceClientMtlsTest.NOW.plusSeconds(2), + ZoneOffset.UTC)) + .assemble(facts.scope(), facts.preparation().requestId())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("changed between committed reads"); assertThat(f.requests).hasSize(2); @@ -74,11 +73,10 @@ void wrongExpectedOriginalAndExpiredSourceNeverProduceInputs() throws Exception "gs", WorldPrivatePreparationSourceClientMtlsTest.CLOCK, (request, index) -> PrivateWorldPreparationReadGrpcCodec.toResponse(request, facts))) { - assertThatThrownBy( - () -> - new WorldPrivatePreparationInputAssembly( - f.client, WorldPrivatePreparationSourceClientMtlsTest.CLOCK) - .assemble(facts.scope(), UUID.randomUUID())) + assertThatThrownBy(() -> + new WorldPrivatePreparationInputAssembly( + f.client, WorldPrivatePreparationSourceClientMtlsTest.CLOCK) + .assemble(facts.scope(), UUID.randomUUID())) .isInstanceOf(RuntimeException.class); } Clock expired = Clock.fixed(facts.preparation().forkExpiresAt(), ZoneOffset.UTC); @@ -88,10 +86,9 @@ void wrongExpectedOriginalAndExpiredSourceNeverProduceInputs() throws Exception "gs", expired, (request, index) -> PrivateWorldPreparationReadGrpcCodec.toResponse(request, facts))) { - assertThatThrownBy( - () -> - new WorldPrivatePreparationInputAssembly(f.client, expired) - .assemble(facts.scope(), facts.preparation().requestId())) + assertThatThrownBy(() -> + new WorldPrivatePreparationInputAssembly(f.client, expired) + .assemble(facts.scope(), facts.preparation().requestId())) .isInstanceOf(IllegalArgumentException.class); } } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPrivatePreparationProtectionClientMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPrivatePreparationProtectionClientMtlsTest.java index 80d5a24e24..e612622c20 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPrivatePreparationProtectionClientMtlsTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPrivatePreparationProtectionClientMtlsTest.java @@ -111,10 +111,9 @@ void ambientSqlAndCancellationDoNotAcquireProtection() throws Exception { } try (var cancelled = Context.current().withCancellation()) { cancelled.cancel(null); - cancelled.run( - () -> - assertThatThrownBy(() -> h.client.acquire(UUID.randomUUID(), source())) - .isInstanceOf(StatusRuntimeException.class)); + cancelled.run(() -> + assertThatThrownBy(() -> h.client.acquire(UUID.randomUUID(), source())) + .isInstanceOf(StatusRuntimeException.class)); } assertThat(h.calls.get()).isZero(); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPrivatePreparationSourceClientMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPrivatePreparationSourceClientMtlsTest.java index e8faafa744..33578c3176 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPrivatePreparationSourceClientMtlsTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPrivatePreparationSourceClientMtlsTest.java @@ -101,20 +101,18 @@ void selectedBuildUsesExactPeerAndCannotInventMissingWorldGraph() throws Excepti WorldPrivatePreparationBuildAssembly.capture(world.request())), org.mockito.ArgumentMatchers.any(Deadline.class))) .thenReturn(java.util.Optional.empty()); - assertThatThrownBy( - () -> - new WorldPrivatePreparationBuildAssembly(h.client, topology, CLOCK) - .assemble(scope, facts.preparation().requestId())) + assertThatThrownBy(() -> + new WorldPrivatePreparationBuildAssembly(h.client, topology, CLOCK) + .assemble(scope, facts.preparation().requestId())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("frozen graph is absent"); org.mockito.Mockito.verify(topology) .readCommitted( org.mockito.ArgumentMatchers.eq( WorldPrivatePreparationBuildAssembly.capture(world.request())), - org.mockito.ArgumentMatchers.argThat( - deadline -> - deadline.timeRemaining(TimeUnit.NANOSECONDS) > 0 - && deadline.timeRemaining(TimeUnit.SECONDS) <= 5)); + org.mockito.ArgumentMatchers.argThat(deadline -> + deadline.timeRemaining(TimeUnit.NANOSECONDS) > 0 + && deadline.timeRemaining(TimeUnit.SECONDS) <= 5)); assertThat(h.requests).hasSize(2); } } @@ -194,11 +192,10 @@ void wrongScopeAmbientSqlCancellationAndExpiredBudgetDoNotCallPeer() throws Exce "gs", CLOCK, (request, index) -> PrivateWorldPreparationReadGrpcCodec.toResponse(request, facts))) { - assertThatThrownBy( - () -> - f.client.read( - new Scope("other", facts.scope().tenantId(), "world", "private"), - facts.preparation().requestId())) + assertThatThrownBy(() -> + f.client.read( + new Scope("other", facts.scope().tenantId(), "world", "private"), + facts.preparation().requestId())) .isInstanceOf(IllegalArgumentException.class); try { TransactionSynchronizationManager.setActualTransactionActive(true); @@ -209,18 +206,15 @@ void wrongScopeAmbientSqlCancellationAndExpiredBudgetDoNotCallPeer() throws Exce } try (var cancelled = Context.current().withCancellation()) { cancelled.cancel(null); - cancelled.run( - () -> - assertThatThrownBy( - () -> f.client.read(facts.scope(), facts.preparation().requestId())) - .isInstanceOf(StatusRuntimeException.class)); + cancelled.run(() -> + assertThatThrownBy(() -> f.client.read(facts.scope(), facts.preparation().requestId())) + .isInstanceOf(StatusRuntimeException.class)); } - assertThatThrownBy( - () -> - f.client.read( - facts.scope(), - facts.preparation().requestId(), - Deadline.after(-1, TimeUnit.SECONDS))) + assertThatThrownBy(() -> + f.client.read( + facts.scope(), + facts.preparation().requestId(), + Deadline.after(-1, TimeUnit.SECONDS))) .isInstanceOf(StatusRuntimeException.class); assertThat(f.requests).isEmpty(); } @@ -347,9 +341,9 @@ static Snapshot snapshot(Scope scope, UUID version) { var policy = RealmEntryPolicy.parse( """ - {"schemaVersion":1,"worldSlug":"world","worldDisplayName":"World","realmSlug":"private", - "realmDisplayName":"Private","visible":true,"publicProduction":false,"stateScope":"ISOLATED","entryPolicy":"PRESEEDED_ONLY"} - """, + {"schemaVersion":1,"worldSlug":"world","worldDisplayName":"World","realmSlug":"private", + "realmDisplayName":"Private","visible":true,"publicProduction":false,"stateScope":"ISOLATED","entryPolicy":"PRESEEDED_ONLY"} + """, JsonMapper.builder().build()); var source = new Source( diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcMtlsTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcMtlsTest.java index c83080ebb5..5b351e5ce2 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcMtlsTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalCompletionGrpcMtlsTest.java @@ -115,17 +115,14 @@ void wrongWorkloadAndNamespaceCertificatesAreDeniedBeforeOwner() throws Exceptio for (var identity : java.util.List.of(pki.accountClient(), pki.otherNamespaceGameDesignClient())) { try (var channel = managedChannel(pki, server.port(), identity)) { - assertThatThrownBy( - () -> - WorldPublicationTerminalCompletionServiceGrpc.newBlockingStub( - channel.channel()) - .withDeadlineAfter(5, TimeUnit.SECONDS) - .completeVersionPublication(input.wire())) + assertThatThrownBy(() -> + WorldPublicationTerminalCompletionServiceGrpc.newBlockingStub(channel.channel()) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .completeVersionPublication(input.wire())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } } } @@ -145,16 +142,14 @@ void requestNamespaceMustMatchTheAuthenticatedWorldOwner() throws Exception { try (var server = startServer(pki, pki.otherNamespaceWorldServer(), service, handlerCalls, false, null); var channel = managedChannel(pki, server.port(), pki.otherNamespaceGameDesignClient())) { - assertThatThrownBy( - () -> - WorldPublicationTerminalCompletionServiceGrpc.newBlockingStub(channel.channel()) - .withDeadlineAfter(5, TimeUnit.SECONDS) - .completeVersionPublication(input.wire())) + assertThatThrownBy(() -> + WorldPublicationTerminalCompletionServiceGrpc.newBlockingStub(channel.channel()) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .completeVersionPublication(input.wire())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } assertThat(handlerCalls).hasValue(1); @@ -175,10 +170,9 @@ void clientPinsExactWorldPeerBeforeSendingRequest() throws Exception { client.init(); assertThatThrownBy(() -> client.complete(input.request())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.UNAUTHENTICATED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); } assertThat(handlerCalls).hasValue(0); @@ -195,16 +189,14 @@ void authenticatedEndUserContextIsDeniedBeforeOwner() throws Exception { try (var server = startServer(pki, service, handlerCalls, true, null); var channel = managedChannel(pki, server.port(), pki.gameDesignClient())) { - assertThatThrownBy( - () -> - WorldPublicationTerminalCompletionServiceGrpc.newBlockingStub(channel.channel()) - .withDeadlineAfter(5, TimeUnit.SECONDS) - .completeVersionPublication(input.wire())) + assertThatThrownBy(() -> + WorldPublicationTerminalCompletionServiceGrpc.newBlockingStub(channel.channel()) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .completeVersionPublication(input.wire())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } assertThat(handlerCalls).hasValue(1); @@ -222,16 +214,14 @@ void defaultMissingVerifierFailsClosedWithoutOwnerStorage() throws Exception { try (var server = startServer(pki, service, handlerCalls, false, null); var channel = managedChannel(pki, server.port(), pki.gameDesignClient())) { - assertThatThrownBy( - () -> - WorldPublicationTerminalCompletionServiceGrpc.newBlockingStub(channel.channel()) - .withDeadlineAfter(5, TimeUnit.SECONDS) - .completeVersionPublication(input.wire())) + assertThatThrownBy(() -> + WorldPublicationTerminalCompletionServiceGrpc.newBlockingStub(channel.channel()) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .completeVersionPublication(input.wire())) .isInstanceOf(StatusRuntimeException.class) - .satisfies( - failure -> - assertThat(Status.fromThrowable(failure).getCode()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); } assertThat(handlerCalls).hasValue(1); @@ -248,12 +238,11 @@ void missingClientCertificateIsRejectedDuringTlsBeforeHandlerOrOwner() throws Ex try (var server = startServer(pki, service, handlerCalls, false, null); var unauthenticatedClient = clientWithoutIdentity(pki, server.port())) { - assertThatThrownBy( - () -> - WorldPublicationTerminalCompletionServiceGrpc.newBlockingStub( - unauthenticatedClient.channel()) - .withDeadlineAfter(5, TimeUnit.SECONDS) - .completeVersionPublication(input.wire())) + assertThatThrownBy(() -> + WorldPublicationTerminalCompletionServiceGrpc.newBlockingStub( + unauthenticatedClient.channel()) + .withDeadlineAfter(5, TimeUnit.SECONDS) + .completeVersionPublication(input.wire())) .isInstanceOf(StatusRuntimeException.class) .satisfies( failure -> assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)).isTrue()); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadServiceTest.java index 57484db97d..9231659826 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublicationTerminalReadServiceTest.java @@ -97,14 +97,13 @@ void classifiesTransactionCreationAndTimeoutFailuresAsUnavailable() throws Excep try { assertThatThrownBy(() -> service.read(request)) .isInstanceOf(io.grpc.StatusRuntimeException.class) - .satisfies( - failure -> { - var status = Status.fromThrowable(failure); - assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); - assertThat(status.getDescription()) - .isEqualTo("World publication terminal owner read is unavailable") - .doesNotContain("sensitive"); - }); + .satisfies(failure -> { + var status = Status.fromThrowable(failure); + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status.getDescription()) + .isEqualTo("World publication terminal owner read is unavailable") + .doesNotContain("sensitive"); + }); } finally { context.detach(previous); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java index 62667189de..0444ba5fd2 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldPublishedSpawnRequirementsReadOwnerTest.java @@ -95,25 +95,22 @@ void rejectsWrongPeerAndEndUserBeforeRequestDecodingOrOwnerAccess() { try (var ignored = attach(identity)) { assertThatThrownBy(() -> owner().read(malformed)) .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) - .satisfies( - failure -> - assertThat( - ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) - failure) - .code()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } } SessionContext.setContext(TENANT.toString(), List.of(), java.util.Map.of()); try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { assertThatThrownBy(() -> owner().read(malformed)) .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) - .satisfies( - failure -> - assertThat( - ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) - .code()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } verifyNoInteractions(gameDesign, published, transactions); } @@ -122,20 +119,18 @@ void rejectsWrongPeerAndEndUserBeforeRequestDecodingOrOwnerAccess() { void ambientTransactionIsRejectedBeforeDecodingOrGameDesignRead() { TransactionSynchronizationManager.setActualTransactionActive(true); try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { - assertThatThrownBy( - () -> - owner() - .read( - ReadWorldPublishedSpawnRequirementsRequest.newBuilder() - .setSchemaVersion(-1) - .build())) + assertThatThrownBy(() -> + owner() + .read( + ReadWorldPublishedSpawnRequirementsRequest.newBuilder() + .setSchemaVersion(-1) + .build())) .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) - .satisfies( - failure -> - assertThat( - ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) - .code()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); } verifyNoInteractions(gameDesign, published, transactions); } @@ -145,12 +140,11 @@ void requestNamespaceMustMatchConfiguredOwnerBeforeGameDesignRead() { try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { assertThatThrownBy(() -> owner().read(wireRequest("other"))) .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) - .satisfies( - failure -> - assertThat( - ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) - .code()) - .isEqualTo(Status.Code.PERMISSION_DENIED)); + .satisfies(failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); } verifyNoInteractions(gameDesign, published, transactions); } @@ -164,12 +158,11 @@ void unavailableGameDesignReadNeverOpensWorldSnapshot() { try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { assertThatThrownBy(() -> owner.read(wire)) .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) - .satisfies( - failure -> - assertThat( - ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) - .code()) - .isEqualTo(Status.Code.UNAVAILABLE)); + .satisfies(failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.UNAVAILABLE)); } verify(gameDesign).getComplete(any(GetLaunchDescriptorRequest.class)); verifyNoInteractions(published, transactions); @@ -193,27 +186,25 @@ void gameDesignStatusCodesAreMappedAndSanitizedBeforeWorldRead(Status.Code forei try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { assertThatThrownBy(() -> owner.read(wire)) .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) - .satisfies( - failure -> { - var rejected = - (WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure; - Status.Code expected = - switch (foreignCode) { - case UNAVAILABLE, - DEADLINE_EXCEEDED, - CANCELLED, - RESOURCE_EXHAUSTED, - INTERNAL, - UNKNOWN -> - foreignCode; - default -> Status.Code.FAILED_PRECONDITION; - }; - assertThat(rejected.code()).isEqualTo(expected); - assertThat(rejected.getMessage()) - .isEqualTo("Authenticated Game Design release read could not complete") - .doesNotContain("foreign", "private", "secret"); - assertThat(rejected.getCause()).isNull(); - }); + .satisfies(failure -> { + var rejected = (WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure; + Status.Code expected = + switch (foreignCode) { + case UNAVAILABLE, + DEADLINE_EXCEEDED, + CANCELLED, + RESOURCE_EXHAUSTED, + INTERNAL, + UNKNOWN -> + foreignCode; + default -> Status.Code.FAILED_PRECONDITION; + }; + assertThat(rejected.code()).isEqualTo(expected); + assertThat(rejected.getMessage()) + .isEqualTo("Authenticated Game Design release read could not complete") + .doesNotContain("foreign", "private", "secret"); + assertThat(rejected.getCause()).isNull(); + }); } verify(gameDesign).getComplete(any(GetLaunchDescriptorRequest.class)); @@ -235,18 +226,16 @@ void invalidOrUnexpectedGameDesignRuntimeFailureIsSanitizedInternal( try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { assertThatThrownBy(() -> owner().read(wireRequest(NAMESPACE))) .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) - .satisfies( - failure -> { - var rejected = - (WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure; - assertThat(rejected.code()).isEqualTo(Status.Code.INTERNAL); - assertThat(rejected.getMessage()) - .isEqualTo( - failureKind == InvalidCarrierFailure.UNEXPECTED - ? "Authenticated Game Design release read failed" - : "Authenticated Game Design release evidence is invalid"); - assertThat(rejected.getCause()).isNull(); - }); + .satisfies(failure -> { + var rejected = (WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure; + assertThat(rejected.code()).isEqualTo(Status.Code.INTERNAL); + assertThat(rejected.getMessage()) + .isEqualTo( + failureKind == InvalidCarrierFailure.UNEXPECTED + ? "Authenticated Game Design release read failed" + : "Authenticated Game Design release evidence is invalid"); + assertThat(rejected.getCause()).isNull(); + }); } verify(gameDesign).getComplete(any(GetLaunchDescriptorRequest.class)); @@ -277,23 +266,21 @@ void readsRequirementsFromTheExactReleaseAndOwnedFrozenSource() throws Exception .containsExactly(1, 1, 2, 1, 1, 1); assertThat(evidence.spawnRequirements()) .singleElement() - .satisfies( - spawn -> { - assertThat(spawn.roomTemplate()) - .isEqualTo( - fixture.plan().graph().freshGraphDeclaration().orElseThrow().startLocation()); - assertThat(spawn.entityTemplate().kind()) - .isEqualTo(EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC); - assertThat(spawn.spawnCount()).isEqualTo(3); - assertThat(spawn.respawnDelaySeconds()).isEqualTo(90); - }); + .satisfies(spawn -> { + assertThat(spawn.roomTemplate()) + .isEqualTo( + fixture.plan().graph().freshGraphDeclaration().orElseThrow().startLocation()); + assertThat(spawn.entityTemplate().kind()) + .isEqualTo(EntityTemplateReferenceType.ENTITY_TEMPLATE_REFERENCE_TYPE_NPC); + assertThat(spawn.spawnCount()).isEqualTo(3); + assertThat(spawn.respawnDelaySeconds()).isEqualTo(90); + }); assertThat(evidence.generationRequirements()) .singleElement() - .satisfies( - generation -> { - assertThat(generation.name()).isEqualTo("density"); - assertThat(generation.value()).isEqualTo("sparse"); - }); + .satisfies(generation -> { + assertThat(generation.name()).isEqualTo("density"); + assertThat(generation.value()).isEqualTo("sparse"); + }); verify(gameDesign).getComplete(eq(fixture.request().getLaunchBindingRequest())); verify(published).readInOwnedSnapshot(eq(fixture.readCaptureRequest())); @@ -312,16 +299,14 @@ void releaseAndFrozenSourceMismatchesFailAfterTheOwnedRead(ReleaseSourceMismatch try (var ignored = attach(peer("entity-management-service", fixture.namespace()))) { assertThatThrownBy(() -> owner(fixture.namespace()).read(fixture.request())) .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) - .satisfies( - failure -> { - var rejected = - (WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure; - assertThat(rejected.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); - assertThat(rejected.getMessage()) - .isEqualTo("Frozen World source differs from authenticated release evidence") - .doesNotContain("private", "SQL", "receipt"); - assertThat(rejected.getCause()).isNull(); - }); + .satisfies(failure -> { + var rejected = (WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure; + assertThat(rejected.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(rejected.getMessage()) + .isEqualTo("Frozen World source differs from authenticated release evidence") + .doesNotContain("private", "SQL", "receipt"); + assertThat(rejected.getCause()).isNull(); + }); } verify(gameDesign).getComplete(eq(fixture.request().getLaunchBindingRequest())); @@ -362,12 +347,11 @@ void changedReleaseAttestationDigestFailsBeforeWorldRead() { try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { assertThatThrownBy(() -> owner().read(wire)) .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) - .satisfies( - failure -> - assertThat( - ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) - .code()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); } verifyNoInteractions(published, transactions); } @@ -389,12 +373,11 @@ void unselectedLegacyReleaseCannotBeUsedAsPublishedSpawnSelector() { try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { assertThatThrownBy(() -> owner().read(wire)) .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) - .satisfies( - failure -> - assertThat( - ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) - .code()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); } verifyNoInteractions(published, transactions); } @@ -423,24 +406,22 @@ void snapshotFailuresMapOnlyRecoverableDataAccessFailuresToUnavailable( try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { assertThatThrownBy(() -> owner().read(wire)) .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) - .satisfies( - failure -> { - var rejected = - (WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure; - var expectedCode = - switch (failureKind) { - case TRANSIENT, RECOVERABLE -> Status.Code.UNAVAILABLE; - case BAD_SQL, INTEGRITY, UNRELATED_RUNTIME -> Status.Code.INTERNAL; - }; - assertThat(rejected.code()).isEqualTo(expectedCode); - assertThat(rejected.getMessage()) - .isEqualTo( - expectedCode == Status.Code.UNAVAILABLE - ? "World published source is temporarily unavailable" - : "World published source read failed") - .doesNotContain("private", "SQL", "integrity"); - assertThat(rejected.getCause()).isNull(); - }); + .satisfies(failure -> { + var rejected = (WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure; + var expectedCode = + switch (failureKind) { + case TRANSIENT, RECOVERABLE -> Status.Code.UNAVAILABLE; + case BAD_SQL, INTEGRITY, UNRELATED_RUNTIME -> Status.Code.INTERNAL; + }; + assertThat(rejected.code()).isEqualTo(expectedCode); + assertThat(rejected.getMessage()) + .isEqualTo( + expectedCode == Status.Code.UNAVAILABLE + ? "World published source is temporarily unavailable" + : "World published source read failed") + .doesNotContain("private", "SQL", "integrity"); + assertThat(rejected.getCause()).isNull(); + }); } verify(gameDesign).getComplete(any(GetLaunchDescriptorRequest.class)); @@ -492,12 +473,11 @@ void malformedFrozenSourceFailsClosedAfterTheOwnedRead() { try (var ignored = attach(peer("entity-management-service", NAMESPACE))) { assertThatThrownBy(() -> owner().read(wire)) .isInstanceOf(WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException.class) - .satisfies( - failure -> - assertThat( - ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) - .code()) - .isEqualTo(Status.Code.FAILED_PRECONDITION)); + .satisfies(failure -> + assertThat( + ((WorldPublishedSpawnRequirementsReadOwner.ReadRejectedException) failure) + .code()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); } verify(published).readInOwnedSnapshot(any()); } @@ -825,15 +805,14 @@ private static CaptureRequest captureRequest( contentDigest, digestSchemaVersion, plan.binding().affectedUnits(Owner.WORLD_MANAGEMENT).stream() - .map( - unit -> - new OwnedAffectedTuple( - unit.owner().name(), - unit.aggregateType(), - unit.aggregateId(), - unit.scopeType(), - unit.scopeId(), - unit.expectedEpoch())) + .map(unit -> + new OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) .toList()); } @@ -931,15 +910,14 @@ private static WorldPublishedStartLocationEvidence.Request selectorRequest( captureRequest.contentDigest(), captureRequest.digestSchemaVersion(), captureRequest.suppliedOwnedAffectedTuples().stream() - .map( - tuple -> - new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( - tuple.owner(), - tuple.aggregateType(), - tuple.aggregateId(), - tuple.scopeType(), - tuple.scopeId(), - tuple.expectedEpoch())) + .map(tuple -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + tuple.owner(), + tuple.aggregateType(), + tuple.aggregateId(), + tuple.scopeType(), + tuple.scopeId(), + tuple.expectedEpoch())) .toList()); } @@ -1000,21 +978,20 @@ private static CompleteLaunchBindingEvidence launchBinding( String commitId = selectorEvidence.request().appliedCommitId(); List participants = AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() - .map( - participant -> - new AuthoredWorldReleaseAttestationEvidence.Participant( - participant, - Integer.toString(descriptorVersionId), - false, - null, - commitId, - "WORLD_MANAGEMENT".equals(participant) - ? selectorEvidence.request().contentDigest() - : "c".repeat(64), - AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( - participant, attestationSchemaVersion), - "GAME_LOGIC".equals(participant), - "GAME_LOGIC".equals(participant) ? "sha256:" + "d".repeat(64) : null)) + .map(participant -> + new AuthoredWorldReleaseAttestationEvidence.Participant( + participant, + Integer.toString(descriptorVersionId), + false, + null, + commitId, + "WORLD_MANAGEMENT".equals(participant) + ? selectorEvidence.request().contentDigest() + : "c".repeat(64), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + participant, attestationSchemaVersion), + "GAME_LOGIC".equals(participant), + "GAME_LOGIC".equals(participant) ? "sha256:" + "d".repeat(64) : null)) .toList(); var release = attestationSchemaVersion == AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationArtifactTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationArtifactTest.java index abfe1e11cb..17d83bf435 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationArtifactTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationArtifactTest.java @@ -204,35 +204,30 @@ void enforcesFormatsEnumsAndExplicitOwnerEvidence() { @Test void rejectsUnsortedMembersAndDuplicateCrossReferences() { - refuses( - root -> { - owner(root).put("containerKind", "INIT"); - owner(root).put("containerName", "z-last"); - }); + refuses(root -> { + owner(root).put("containerKind", "INIT"); + owner(root).put("containerName", "z-last"); + }); refuses(root -> members(root).set(1, owner(root).deepCopy())); - refuses( - root -> { - ArrayNode sources = (ArrayNode) owner(root).get("catalogSources"); - sources.add(source(root).deepCopy()); - }); - refuses( - root -> { - ArrayNode families = (ArrayNode) owner(root).get("families"); - families.add(family(root).deepCopy()); - }); - refuses( - root -> { - ObjectNode second = (ObjectNode) members(root).get(1); - second.put("ownerId", "world-management-service"); - second.put("ownership", "RUNTIME_OWNER"); - second.set("catalogSources", owner(root).get("catalogSources").deepCopy()); - second.set("families", owner(root).get("families").deepCopy()); - }); - refuses( - root -> { - ArrayNode bindings = (ArrayNode) root.get("inputBindings").get("secretContracts"); - bindings.add(bindings.get(0).deepCopy()); - }); + refuses(root -> { + ArrayNode sources = (ArrayNode) owner(root).get("catalogSources"); + sources.add(source(root).deepCopy()); + }); + refuses(root -> { + ArrayNode families = (ArrayNode) owner(root).get("families"); + families.add(family(root).deepCopy()); + }); + refuses(root -> { + ObjectNode second = (ObjectNode) members(root).get(1); + second.put("ownerId", "world-management-service"); + second.put("ownership", "RUNTIME_OWNER"); + second.set("catalogSources", owner(root).get("catalogSources").deepCopy()); + second.set("families", owner(root).get("families").deepCopy()); + }); + refuses(root -> { + ArrayNode bindings = (ArrayNode) root.get("inputBindings").get("secretContracts"); + bindings.add(bindings.get(0).deepCopy()); + }); } @Test @@ -245,13 +240,12 @@ void unresolvedAndMissingOwnerSetsRemainParseableButBlockQualification() { var noOwner = WorldRuntimeInstallationArtifact.parse( - changed( - root -> { - owner(root).put("ownership", "NO_INSTANCE_STATE"); - owner(root).put("ownerId", ""); - owner(root).putArray("catalogSources"); - owner(root).putArray("families"); - })); + changed(root -> { + owner(root).put("ownership", "NO_INSTANCE_STATE"); + owner(root).put("ownerId", ""); + owner(root).putArray("catalogSources"); + owner(root).putArray("families"); + })); assertThatIllegalArgumentException().isThrownBy(noOwner::requireResolved); var empty = WorldRuntimeInstallationArtifact.parse(changed(root -> root.putArray("members"))); assertThatIllegalArgumentException().isThrownBy(empty::requireResolved); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistryTest.java index e016b0c983..3a48707c3e 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistryTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistryTest.java @@ -16,10 +16,8 @@ void unavailableDefaultSourceRefusesPreflightWithoutAnyDatabaseAccess() { var transactions = mock(PlatformTransactionManager.class); var registry = new WorldRuntimeInstallationRegistry(dsl, transactions, "world", "firemud"); - assertThatThrownBy( - () -> - registry.preflightLaunchOwners( - UUID.fromString("88888888-8888-4888-8888-888888888888"))) + assertThatThrownBy(() -> + registry.preflightLaunchOwners(UUID.fromString("88888888-8888-4888-8888-888888888888"))) .isInstanceOf(WorldRuntimeInstallationRegistry.RegistryUnavailableException.class) .hasMessage("Protected current-installation source is unavailable"); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionExecutionTerminalReadGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionExecutionTerminalReadGrpcServiceTest.java index ae843b5133..187fad94f4 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionExecutionTerminalReadGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldStartSessionExecutionTerminalReadGrpcServiceTest.java @@ -376,11 +376,10 @@ void returnsOnlyExactCommittedOrAbortedTerminalAfterSyntheticOriginalVerificatio var lookup = new ExecutionLookup(Optional.of(new ExecutionOperation(state, 73L, instanceId)), false); when(repository.readExactExecution(any(WorldCanonicalInstanceExecutionIdentity.class))) - .thenAnswer( - invocation -> { - order.add("owner-read"); - return lookup; - }); + .thenAnswer(invocation -> { + order.add("owner-read"); + return lookup; + }); // This explicitly synthetic verifier accepts the expired historical tuple so the test // proves recovery reads history without applying fresh-admission expiry. var grpc =